repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
gozer/voice-web
ios/voicebank-ios-wrapper/Recorder.swift
1
5071
// 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 https://mozilla.org/MPL/2.0/. import Foundation import AVFoundation import WebKit class Recorder: NSObject, AVAudioRecorderDelegate { var recordingSession: AVAudioSession! var audioRecorder: AVAudioRecorder! var audioFilename: URL? = nil var webView: WKWebView? = nil var audioPlayer:AVAudioPlayer! var metertimer : Timer? = nil var hasMicPermission: Bool = false override init() { super.init() let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = paths[0] self.audioFilename = documentsDirectory.appendingPathComponent("recording.m4a") self.recordingSession = AVAudioSession.sharedInstance() do { try self.recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker]) try self.recordingSession.setActive(true) } catch { // failed to record! } } func startRecording() { // first we declare the closure to start recording let record = { () -> Void in self.audioRecorder.record() self.audioRecorder.isMeteringEnabled = true; self.metertimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.updateAudioMeter), userInfo: nil, repeats: true); } // then we check if we have mic permission if (!self.hasMicPermission){ // if not, we ask it requestPermission(completion:{(allowed: Bool) -> Void in if (!allowed) { // if permission wasn't given, we let the webapp now self.hasMicPermission = false self.webView?.evaluateJavaScript("nativemsgs('nomicpermission')") } else { // if permission was given, we start recording if (self.createRecorder()) { self.hasMicPermission = true record() self.webView?.evaluateJavaScript("nativemsgs('capturestarted')") } else { self.webView?.evaluateJavaScript("nativemsgs('errorrecording')") } } }) } else { // if we have permission, then we start capturing record() self.webView?.evaluateJavaScript("nativemsgs('capturestarted')") } } func requestPermission(completion: @escaping (Bool) -> Void) { // first we show the permissions popup recordingSession.requestRecordPermission() { [unowned self] allowed in DispatchQueue.main.async { completion(allowed) } } } func stopRecording() { self.audioRecorder.stop() self.metertimer?.invalidate() } func stopPlayingCapture() { self.audioPlayer.stop() } func createRecorder() -> Bool { let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC), AVSampleRateKey: 48000, AVNumberOfChannelsKey: 1, AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ] do { self.audioRecorder = try AVAudioRecorder(url: self.audioFilename!, settings: settings) } catch { return false } self.audioRecorder.delegate = self return true } func playCapture() { do { try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.speaker) try audioPlayer = AVAudioPlayer(contentsOf: self.audioFilename!) audioPlayer.prepareToPlay() audioPlayer.play() } catch { self.webView?.evaluateJavaScript("nativemsgs('errorplaying')") } } func updateAudioMeter() { self.audioRecorder.updateMeters() let dBLevel = self.audioRecorder.averagePower(forChannel: 0) let peaklevel = self.audioRecorder.peakPower(forChannel: 0) NSLog("peaklevel \(peaklevel) dblevel \(dBLevel) ") webView?.evaluateJavaScript("levels('\(dBLevel)', '\(peaklevel)')") } func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) { if (flag){ do { let data: NSData = try NSData(contentsOfFile: self.audioFilename!.path) // Convert swift dictionary into encoded json let encodedData = data.base64EncodedString(options: .endLineWithLineFeed) // This WKWebView API to calls 'reloadData' function defined in js webView?.evaluateJavaScript("uploadData('\(encodedData)')") } catch { // failed to record! } } } }
mpl-2.0
29348ad42921b18f158737b580c45dbf
36.286765
158
0.59081
5.435155
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/SwiftFilePath/SwiftFilePath/Path.swift
2
3100
// // Path.swift // SwiftFilePath // // Created by nori0620 on 2015/01/08. // Copyright (c) 2015年 Norihiro Sakamoto. All rights reserved. // public class Path { // MARK: - Class methods public class func isDir(path:NSString) -> Bool { var isDirectory: ObjCBool = false let isFileExists = NSFileManager.defaultManager().fileExistsAtPath(path as String, isDirectory:&isDirectory) return isDirectory ? true : false } // MARK: - Instance properties and initializer lazy var fileManager = NSFileManager.defaultManager() public let path_string:String public init(_ p: String) { self.path_string = p } // MARK: - Instance val public var attributes:NSDictionary?{ get { return self.loadAttributes() } } public var asString: String { return path_string } public var exists: Bool { return fileManager.fileExistsAtPath(path_string) } public var isDir: Bool { return Path.isDir(path_string); } public var basename:NSString { return path_string.lastPathComponent } public var parent: Path{ return Path( path_string.stringByDeletingLastPathComponent ) } // MARK: - Instance methods public func toString() -> String { return path_string } public func remove() -> Result<Path,NSError> { assert(self.exists,"To remove file, file MUST be exists") var error: NSError? let result = fileManager.removeItemAtPath(path_string, error:&error) return result ? Result(success: self) : Result(failure: error!); } public func copyTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To copy file, file MUST be exists") var error: NSError? let result = fileManager.copyItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } public func moveTo(toPath:Path) -> Result<Path,NSError> { assert(self.exists,"To move file, file MUST be exists") var error: NSError? let result = fileManager.moveItemAtPath(path_string, toPath: toPath.toString(), error: &error) return result ? Result(success: self) : Result(failure: error!) } private func loadAttributes() -> NSDictionary? { assert(self.exists,"File must be exists to load file.< \(path_string) >") var loadError: NSError? let result = self.fileManager.attributesOfItemAtPath(path_string, error: &loadError) if let error = loadError { println("Error< \(error.localizedDescription) >") } return result } } // MARK: - extension Path: Printable { public var description: String { return "\(NSStringFromClass(self.dynamicType))<path:\(path_string)>" } }
mit
f144032bd11c44ddd073acc365da5a03
25.93913
116
0.593932
4.665663
false
false
false
false
rnystrom/GitHawk
Classes/Repository/RepositoryIssueSummaryModel.swift
1
1870
// // RepositoryIssueSummaryModel.swift // Freetime // // Created by Ryan Nystrom on 9/3/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit import StyledTextKit final class RepositoryIssueSummaryModel: ListSwiftDiffable { let id: String let title: StyledTextRenderer let number: Int let created: Date let author: String let status: IssueStatus let pullRequest: Bool let labels: [RepositoryLabel] let ciStatus: RepositoryIssueCIStatus? // quicker comparison for diffing rather than scanning the labels array let labelSummary: String init( id: String, title: StyledTextRenderer, number: Int, created: Date, author: String, status: IssueStatus, pullRequest: Bool, labels: [RepositoryLabel], ciStatus: RepositoryIssueCIStatus? ) { self.id = id self.title = title self.number = number self.created = created self.author = author self.status = status self.pullRequest = pullRequest self.labels = labels self.labelSummary = labels.reduce("", { $0 + $1.name }) self.ciStatus = ciStatus } // MARK: ListSwiftDiffable var identifier: String { return id } func isEqual(to value: ListSwiftDiffable) -> Bool { guard let object = value as? RepositoryIssueSummaryModel else { return false } return id == object.id && number == object.number && pullRequest == object.pullRequest && status == object.status && author == object.author && created == object.created && title.string == object.title.string && labelSummary == object.labelSummary && ciStatus == object.ciStatus } }
mit
ee5bbfd15c9fb79ac766359d3ce39f7d
25.7
86
0.614232
4.755725
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/View/ChatPreviewDocVC.swift
1
10267
// // ChatPreviewDocVC.swift // qonsultant // // Created by Ahmad Athaullah on 7/27/16. // Copyright © 2016 qiscus. All rights reserved. // import UIKit import WebKit import SwiftyJSON import RealmSwift open class ChatPreviewDocVC: UIViewController, UIWebViewDelegate, WKNavigationDelegate { var webView = WKWebView() var url: String = "" var fileName: String = "" var progressView = UIProgressView(progressViewStyle: UIProgressViewStyle.bar) var roomName:String = "" var accountLinking = false var accountData:JSON? var accountLinkURL:String = "" var accountRedirectURL:String = "" var file:QFile? = nil deinit{ self.webView.removeObserver(self, forKeyPath: "estimatedProgress") } // MARK: - UI Lifecycle override open func viewDidLoad() { super.viewDidLoad() self.webView.navigationDelegate = self self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: NSKeyValueObservingOptions.new, context: nil) if !self.accountLinking { let shareButton = UIBarButtonItem(title: "Share", style: .plain, target: self, action: #selector(ChatPreviewDocVC.share)) self.navigationItem.rightBarButtonItem = shareButton } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if !accountLinking { self.navigationItem.setTitleWithSubtitle(title: self.roomName, subtitle: self.fileName) }else{ if let data = accountData { self.title = data["params"]["view_title"].stringValue self.accountLinkURL = data["url"].stringValue self.accountRedirectURL = data["redirect_url"].stringValue } } self.webView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(webView) self.view.addSubview(progressView) let constraints = [ NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0), NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0), NSLayoutConstraint(item: self.progressView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0) ] view.addConstraints(constraints) view.layoutIfNeeded() //self.webView.backgroundColor = UIColor.red if !self.accountLinking{ if let openFile = self.file { if QFileManager.isFileExist(inLocalPath: openFile.localPath) { let url = URL(fileURLWithPath: openFile.localPath) self.webView.loadFileURL(url, allowingReadAccessTo: url) }else{ if let openURL = URL(string: openFile.url.replacingOccurrences(of: " ", with: "%20")){ self.webView.load(URLRequest(url: openURL)) } } }else if let openURL = URL(string: self.url.replacingOccurrences(of: " ", with: "%20")){ self.webView.load(URLRequest(url: openURL)) } }else{ if let openURL = URL(string: self.accountLinkURL.replacingOccurrences(of: " ", with: "%20")) { self.webView.load(URLRequest(url: openURL)) } } } override open func viewWillDisappear(_ animated: Bool) { self.progressView.removeFromSuperview() super.viewWillDisappear(animated) } override open func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - WebView Delegate override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let objectSender = object as? WKWebView { if (keyPath! == "estimatedProgress") && (objectSender == self.webView) { progressView.isHidden = self.webView.estimatedProgress == 1 progressView.setProgress(Float(self.webView.estimatedProgress), animated: true) }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } open func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.progressView.progress = 0.0 } if !self.accountLinking { if let file = self.file { if !QFileManager.isFileExist(inLocalPath: file.localPath){ let remoteURL = file.url.replacingOccurrences(of: " ", with: "%20") if let url = URL(string: remoteURL) { do { let data = try Data(contentsOf: url as URL) let directoryPath = QFileManager.directoryPath(forDirectory: .comment) let path = "\(directoryPath)/\(file.filename.replacingOccurrences(of: " ", with: "_"))" try? data.write(to: URL(fileURLWithPath: path), options: [.atomic]) let realm = try! Realm(configuration: Qiscus.dbConfiguration) realm.refresh() try! realm.write { file.localPath = path } } catch { } } } } } } open func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int(0.2 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)) { () -> Void in self.progressView.progress = 0.0 //self.setupTableMessage(error.localizedDescription) } } open func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { decisionHandler(WKNavigationActionPolicy.allow) if self.accountLinking { if let urlToLoad = webView.url { let urlString = urlToLoad.absoluteString if urlString == self.accountRedirectURL.replacingOccurrences(of: " ", with: "%20") { let _ = self.navigationController?.popViewController(animated: true) } } } } open func webViewDidFinishLoad(_ webView: UIWebView) { self.progressView.isHidden = true } // MARK: - Navigation open func goBack(_ sender: AnyObject) { let _ = self.navigationController?.popViewController(animated: true) } // MARK: - Custom Component open func backButton(_ target: UIViewController, action: Selector) -> UIBarButtonItem{ let backIcon = UIImageView() backIcon.contentMode = .scaleAspectFit let backLabel = UILabel() backLabel.text = "" backLabel.textColor = QiscusChatVC.currentNavbarTint backLabel.font = UIFont.systemFont(ofSize: 12) let image = Qiscus.image(named: "ic_back")?.withRenderingMode(.alwaysTemplate) backIcon.image = image backIcon.tintColor = QiscusChatVC.currentNavbarTint if UIApplication.shared.userInterfaceLayoutDirection == .leftToRight { backIcon.frame = CGRect(x: 0,y: 0,width: 10,height: 15) backLabel.frame = CGRect(x: 15,y: 0,width: 45,height: 15) }else{ backIcon.frame = CGRect(x: 50,y: 0,width: 10,height: 15) backLabel.frame = CGRect(x: 0,y: 0,width: 45,height: 15) } let backButton = UIButton(frame:CGRect(x: 0,y: 0,width: 60,height: 20)) backButton.addSubview(backIcon) backButton.addSubview(backLabel) backButton.addTarget(target, action: action, for: UIControlEvents.touchUpInside) return UIBarButtonItem(customView: backButton) } @objc func share(){ if let file = self.file { if QFileManager.isFileExist(inLocalPath: file.localPath){ let url = URL(fileURLWithPath: file.localPath) let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) }else{ if let url = URL(string: file.url) { let activityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view self.present(activityViewController, animated: true, completion: nil) } } } } }
mit
0de818e4234268eef4d2adedb50ad910
44.626667
166
0.600623
5.104923
false
false
false
false
SuPair/firefox-ios
Sync/Synchronizers/Bookmarks/ThreeWayTreeMerger.swift
5
68073
/* 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 Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger private func negate<T>(_ f: @escaping (T) throws -> Bool) -> (T) throws -> Bool { return { try !f($0) } } extension Collection { func exclude(_ predicate: @escaping (Self.Iterator.Element) throws -> Bool) throws -> [Self.Iterator.Element] { return try self.filter(negate(predicate)) } } /** * This class takes as input three 'trees'. * * The mirror is always complete, never contains deletions, never has * orphans, and has a single root. * * Each of local and remote can contain a number of subtrees (each of which must * be a folder or root), a number of deleted GUIDs, and a number of orphans (records * with no known parent). * * As output it produces a merged tree. The tree contains the new structure, * including every record that we're keeping, and also makes note of any deletions. * * The merged tree can be walked to yield a set of operations against the original * three trees. Those operations will make the upstream source and local storage * match the merge output. * * It's very likely that there's almost no overlap between local and remote, and * thus no real conflicts to resolve -- a three-way merge isn't always a bad thing * -- but we won't know until we compare records. * * * Even though this is called 'three way merge', it also handles the case * of a two-way merge (one without a shared parent; for the roots, this will only * be on a first sync): content-based and structural merging is needed at all * layers of the hierarchy, so we simply generalize that to also apply to roots. * * In a sense, a two-way merge is solved by constructing a shared parent consisting of * roots, which are implicitly shared. * * (Special care must be taken to not deduce that one side has deleted a root, of course, * as would be the case of a Sync server that doesn't contain * a Mobile Bookmarks folder -- the set of roots can only grow, not shrink.) * * * To begin with we structurally reconcile. If necessary we will lazily fetch the * attributes of records in order to do a content-based reconciliation. Once we've * matched up any records that match (including remapping local GUIDs), we're able to * process _content_ changes, which is much simpler. * * We have to handle an arbitrary combination of the following structural operations: * * * Creating a folder. * Created folders might now hold existing items, new items, or nothing at all. * * Creating a bookmark. * It might be in a new folder or an existing folder. * * Moving one or more leaf records to an existing or new folder. * * Reordering the children of a folder. * * Deleting an entire subtree. * * Deleting an entire subtree apart from some moved nodes. * * Deleting a leaf node. * * Transplanting a subtree: moving a folder but not changing its children. * * And, of course, the non-structural operations such as renaming or changing URLs. * * We ignore all changes to roots themselves; the only acceptable operation on a root * is to change its children. The Places root is entirely immutable. * * Steps: * * Construct a collection of subtrees for local and buffer, and a complete tree for the mirror. * The more thorough this step, the more confidence we have in consistency. * * Fetch all local and remote deletions. These won't be included in structure (for obvious * reasons); we hold on to them explicitly so we can spot the difference between a move * and a deletion. * * Walk each subtree, top-down. At each point if there are two back-pointers to * the mirror node for a GUID, we have a potential conflict, and we have all three * parts that we need to resolve it via a content-based or structure-based 3WM. * * Observations: * * If every GUID on each side is present in the mirror, we have no new records. * * If a non-root GUID is present on both sides but not in the mirror, then either * we're re-syncing from scratch, or (unlikely) we have a random collision. * * Otherwise, we have a GUID that we don't recognize. We will structure+content reconcile * this later -- we first make sure we have handled any tree moves, so that the addition * of a bookmark to a moved folder on A, and the addition of the same bookmark to the non- * moved version of the folder, will collide successfully. * * When we look at a child list: * * It's the same. Great! Keep walking down. * * There are added GUIDs. * * An added GUID might be a move from elsewhere. Coordinate with the removal step. * * An added GUID might be a brand new record. If there are local additions too, * check to see if they value-reconcile, and keep the remote GUID. * * There are removed GUIDs. * * A removed GUID might have been deleted. Deletions win. * * A missing GUID might be a move -- removed from here and added to another folder. * Process this as a move. * * The order has changed. * * When we get to a subtree that contains no changes, we can never hit conflicts, and * application becomes easier. * * When we run out of subtrees on both sides, we're done. * * Note that these trees don't include values. This is because we usually don't need them: * if there are no conflicts, or no shared parents, we can do everything we need to do * at this stage simply with structure and GUIDs, and then flush rows straight from the * buffer into the mirror with a single SQL INSERT. We do need to fetch values later * in some cases: to amend child lists or otherwise construct outbound records. We do * need to fetch values immediately in other cases: in order to reconcile conflicts. * Those should ordinarily be uncommon, and because we know most of the conflicting * GUIDs up-front, we can prime a cache of records. */ class ThreeWayTreeMerger { let local: BookmarkTree let mirror: BookmarkTree let remote: BookmarkTree var merged: MergedTree // Don't merge twice. var mergeAttempted: Bool = false let itemSources: ItemSources // Sets computed by looking at the three trees. These are used for diagnostics, // to simplify operations, to pre-fetch items for value comparison, and for testing. let mirrorAllGUIDs: Set<GUID> // Excluding deletions. let localAllGUIDs: Set<GUID> // Excluding deletions. let remoteAllGUIDs: Set<GUID> // Excluding deletions. let localAdditions: Set<GUID> // New records added locally, not present in the mirror. let remoteAdditions: Set<GUID> // New records from the server, not present in the mirror. let allDeletions: Set<GUID> // Records deleted locally or remotely. var allChangedGUIDs: Set<GUID> // Everything added or changed locally or remotely. let conflictingGUIDs: Set<GUID> // Anything added or changed both locally and remotely. let nonRemoteKnownGUIDs: Set<GUID> // Everything existing, added, or deleted locally or in the mirror. // For now, track just one list. We might need to split this later. var done: Set<GUID> = Set() // Local records that we identified as being the same as remote records. var duped: Set<GUID> = Set() init(local: BookmarkTree, mirror: BookmarkTree, remote: BookmarkTree, itemSources: ItemSources) { precondition(mirror.root != nil) assert((mirror.root!.children?.count ?? 0) == BookmarkRoots.RootChildren.count) precondition(mirror.orphans.isEmpty) precondition(mirror.deleted.isEmpty) precondition(mirror.subtrees.count == 1) // These are runtime-tested in merge(). assert to make sure that tests // don't do anything stupid, and we don't slip past those constraints. //assert(local.isFullyRootedIn(mirror)) //assert(remote.isFullyRootedIn(mirror)) self.local = local self.mirror = mirror self.remote = remote self.itemSources = itemSources self.merged = MergedTree(mirrorRoot: self.mirror.root!) // We won't get here unless every local and remote orphan is correctly rooted // when overlaid on the mirror, so we don't need to exclude orphans here. self.mirrorAllGUIDs = self.mirror.modified self.localAllGUIDs = self.local.modified self.remoteAllGUIDs = self.remote.modified self.localAdditions = localAllGUIDs.subtracting(mirrorAllGUIDs) self.remoteAdditions = remoteAllGUIDs.subtracting(mirrorAllGUIDs) self.allDeletions = self.local.deleted.union(self.remote.deleted) self.allChangedGUIDs = localAllGUIDs.union(self.remoteAllGUIDs) self.conflictingGUIDs = localAllGUIDs.intersection(remoteAllGUIDs) self.nonRemoteKnownGUIDs = self.mirrorAllGUIDs.union(self.localAllGUIDs).union(self.local.deleted) } fileprivate func nullOrMatch(_ a: String?, _ b: String?) -> Bool { guard let a = a, let b = b else { return true } return a == b } /** * When we have a folder match and new records on each side -- records * not mentioned in the buffer -- it's possible that the new records * are the same but have different GUIDs. * This function will look at value matches to identify a local * equivalent in this folder, returning nil if none are found. * * Note that we don't match records that have already been matched, and * we don't match any for which a GUID is known in the mirror or remote. */ fileprivate func findNewLocalNodeMatchingContentOfRemoteNote(_ remote: BookmarkTreeNode, inFolder parent: GUID, withLocalChildren children: [BookmarkTreeNode], havingSeen seen: Set<GUID>) -> BookmarkTreeNode? { // TODO: don't compute this list once per incoming child! Profile me. let candidates = children.filter { child in let childGUID = child.recordGUID return !seen.contains(childGUID) && // Not already used in this folder. !self.remoteAdditions.contains(childGUID) && // Not locally and remotely added with same GUID. !self.remote.deleted.contains(childGUID) && // Not remotely deleted. !self.done.contains(childGUID) // Not already processed elsewhere in the tree. } guard let remoteValue = self.itemSources.buffer.getBufferItemWithGUID(remote.recordGUID).value.successValue else { log.error("Couldn't find remote value for \(remote.recordGUID).") return nil } let guids = candidates.map { $0.recordGUID } guard let items = self.itemSources.local.getLocalItemsWithGUIDs(guids).value.successValue else { log.error("Couldn't find local values for \(candidates.count) candidates.") return nil } // Return the first candidate that's a value match. guard let localItem = (guids.compactMap { items[$0] }.find { $0.sameAs(remoteValue) }) else { log.debug("Didn't find a local value match for new remote record \(remote.recordGUID).") return nil } log.debug("Found a local match \(localItem.guid) for new remote record \(remote.recordGUID) in parent \(parent).") // Find the original contributing child node by GUID. return children.find { $0.recordGUID == localItem.guid } } fileprivate func takeMirrorChildrenInMergedNode(_ result: MergedTreeNode) throws { guard let mirrorChildren = result.mirror?.children else { preconditionFailure("Expected children.") } let out: [MergedTreeNode] = try mirrorChildren.compactMap { child in // TODO: handle deletions. That might change the below from 'Unchanged' // to 'New'. let childGUID = child.recordGUID if self.done.contains(childGUID) { log.warning("Not taking mirror child \(childGUID): already done. This is unexpected.") return nil } let localCounterpart = self.local.find(childGUID) let remoteCounterpart = self.remote.find(childGUID) return try self.mergeNode(childGUID, localNode: localCounterpart, mirrorNode: child, remoteNode: remoteCounterpart) } result.mergedChildren = out result.structureState = MergeState.unchanged } fileprivate func oneWayMergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromRemote remote: BookmarkTreeNode) throws { guard case .folder = remote else { preconditionFailure("Expected folder from which to merge children.") } result.structureState = MergeState.remote // If the list changes, this will switch to .new. try self.mergeChildListsIntoMergedNode(result, fromLocal: nil, remote: remote, mirror: self.mirror.find(remote.recordGUID)) } fileprivate func oneWayMergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromLocal local: BookmarkTreeNode) throws { guard case .folder = local else { preconditionFailure("Expected folder from which to merge children.") } result.structureState = MergeState.local // If the list changes, this will switch to .new. try self.mergeChildListsIntoMergedNode(result, fromLocal: local, remote: nil, mirror: self.mirror.find(local.recordGUID)) } fileprivate func mergeChildListsIntoMergedNode(_ result: MergedTreeNode, fromLocal local: BookmarkTreeNode?, remote: BookmarkTreeNode?, mirror: BookmarkTreeNode?) throws { precondition(local != nil || remote != nil, "Expected either local or remote folder for merge.") // The most trivial implementation: take everything in the first list, then append // everything new in the second list. // Anything present in both is resolved. // We can't get away from handling deletions and moves, etc. -- one might have // created a folder on two devices and moved existing items on one, some of which // might have been deleted on the other. // This kind of shit is why bookmark sync is hard. // See each of the test cases in TestBookmarkTreeMerging, which have helpful diagrams. var out: [MergedTreeNode] = [] var seen: Set<GUID> = Set() var changed = false func processRemoteOrphansForNode(_ node: BookmarkTreeNode) throws -> [MergedTreeNode]? { // Now we recursively merge down into our list of orphans. If those contain deleted // subtrees, excess leaves will be flattened up; we'll get a single list of nodes // here, and we'll take them as additional children. let guid = node.recordGUID func isLocallyDeleted(_ child: BookmarkTreeNode) throws -> Bool { return try checkForLocalDeletionOfRemoteNode(child, mirrorNode: self.mirror.find(child.recordGUID)) } guard let orphans = try node.children?.exclude(isLocallyDeleted), !orphans.isEmpty else { log.debug("No remote orphans from local deletion of \(guid).") return nil } let mergedOrphans = try orphans.map { (orphan: BookmarkTreeNode) throws -> MergedTreeNode in let guidO = orphan.recordGUID let locO = self.local.find(guidO) let remO = orphan let mirO = self.mirror.find(guidO) log.debug("Merging up remote orphan \(guidO).") return try self.mergeNode(guidO, localNode: locO, mirrorNode: mirO, remoteNode: remO) } log.debug("Collected \(mergedOrphans.count) remote orphans for deleted folder \(guid).") if mergedOrphans.isEmpty { return nil } changed = true return mergedOrphans } func processLocalOrphansForNode(_ node: BookmarkTreeNode) throws -> [MergedTreeNode]? { // Now we recursively merge down into our list of orphans. If those contain deleted // subtrees, excess leaves will be flattened up; we'll get a single list of nodes // here, and we'll take them as additional children. let guid = node.recordGUID if case .folder = node {} else { log.debug("\(guid) isn't a folder, so it won't have orphans.") return nil } func isRemotelyDeleted(_ child: BookmarkTreeNode) throws -> Bool { return try checkForRemoteDeletionOfLocalNode(child, mirrorNode: self.mirror.find(child.recordGUID)) } guard let orphans = try node.children?.exclude(isRemotelyDeleted), !orphans.isEmpty else { log.debug("No local orphans from remote deletion of folder \(guid).") return nil } let mergedOrphans = try orphans.map { (orphan: BookmarkTreeNode) throws -> MergedTreeNode in let guidO = orphan.recordGUID let locO = orphan let remO = self.remote.find(guidO) let mirO = self.mirror.find(guidO) log.debug("Merging up local orphan \(guidO).") return try self.mergeNode(guidO, localNode: locO, mirrorNode: mirO, remoteNode: remO) } log.debug("Collected \(mergedOrphans.count) local orphans for deleted folder \(guid).") if mergedOrphans.isEmpty { return nil } changed = true return mergedOrphans } func checkForLocalDeletionOfRemoteNode(_ node: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> Bool { let guid = node.recordGUID guard self.local.deleted.contains(guid) else { return false } // It was locally deleted. This would be good enough for us, // but we need to ensure that any remote children are recursively // deleted or handled as orphans. log.warning("Quietly accepting local deletion of record \(guid).") changed = true self.merged.deleteRemotely.insert(guid) self.merged.acceptLocalDeletion.insert(guid) if mirrorNode != nil { self.merged.deleteFromMirror.insert(guid) } if let orphans = try processRemoteOrphansForNode(node) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } return true } func checkForRemoteDeletionOfLocalNode(_ node: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> Bool { let guid = node.recordGUID guard self.remote.deleted.contains(guid) else { return false } // It was remotely deleted. This would be good enough for us, // but we need to ensure that any local children are recursively // deleted or handled as orphans. log.warning("Quietly accepting remote deletion of record \(guid).") self.merged.deleteLocally.insert(guid) self.merged.acceptRemoteDeletion.insert(guid) if mirrorNode != nil { self.merged.deleteFromMirror.insert(guid) } if let orphans = try processLocalOrphansForNode(node) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } return true } // Do a recursive merge of each child. if let remote = remote, let children = remote.children { try children.forEach { rem in let guid = rem.recordGUID seen.insert(guid) if self.done.contains(guid) { log.debug("Processing children of \(result.guid). Child \(guid) already seen elsewhere!") return } if try checkForLocalDeletionOfRemoteNode(rem, mirrorNode: self.mirror.find(guid)) { log.debug("Child \(guid) is locally deleted.") return } let mir = self.mirror.find(guid) if let localByGUID = self.local.find(guid) { // Let's check the parent of the local match. If it differs, then the matching // record is elsewhere in the local tree, and we need to decide which place to // keep it. // We do so by finding the modification time of the parent on each side, // unless one of the records is explicitly non-modified. if let localParentGUID = self.local.parents[guid] { // Oh hey look! Ad hoc three-way merge! let mirrorParentGUID = self.mirror.parents[guid] if localParentGUID != result.guid { log.debug("Local child \(guid) is in folder \(localParentGUID), but remotely is in \(result.guid).") if mirrorParentGUID != localParentGUID { log.debug("… and locally it has changed since our last sync, moving from \(mirrorParentGUID ?? "nil") to \(localParentGUID).") // Find out which parent is most recent. if let localRecords = self.itemSources.local.getLocalItemsWithGUIDs([localParentGUID, guid]).value.successValue, let remoteRecords = self.itemSources.buffer.getBufferItemsWithGUIDs([result.guid, guid]).value.successValue { let latestLocalTimestamp = max(localRecords[guid]?.localModified ?? 0, localRecords[localParentGUID]?.localModified ?? 0) let latestRemoteTimestamp = max(remoteRecords[guid]?.serverModified ?? 0, remoteRecords[result.guid]?.serverModified ?? 0) log.debug("Latest remote timestamp: \(latestRemoteTimestamp). Latest local timestamp: \(latestLocalTimestamp).") if latestLocalTimestamp > latestRemoteTimestamp { log.debug("Keeping record in its local position. We'll merge these later.") return } log.debug("Taking remote, because it's later. Merging now.") } } else { log.debug("\(guid) didn't move from \(mirrorParentGUID ?? "nil") since our last sync. Taking remote parent.") } } else { log.debug("\(guid) is locally in \(localParentGUID) and remotely in \(result.guid). Easy.") } } out.append(try self.mergeNode(guid, localNode: localByGUID, mirrorNode: mir, remoteNode: rem)) return } // We don't ever have to handle moves in this case: we only search this directory. let localByContent: BookmarkTreeNode? if let localChildren = local?.children { localByContent = self.findNewLocalNodeMatchingContentOfRemoteNote(rem, inFolder: result.guid, withLocalChildren: localChildren, havingSeen: seen) } else { localByContent = nil } out.append(try self.mergeNode(guid, localNode: localByContent, mirrorNode: mir, remoteNode: rem)) } } if let local = local, let children = local.children { try children.forEach { loc in let guid = loc.recordGUID if seen.contains(guid) { log.debug("Already saw local child \(guid).") return } if self.done.contains(guid) { log.debug("Already saw local child \(guid) elsewhere.") return } if try checkForRemoteDeletionOfLocalNode(loc, mirrorNode: self.mirror.find(guid)) { return } let mir = self.mirror.find(guid) let rem = self.remote.find(guid) changed = true out.append(try self.mergeNode(guid, localNode: loc, mirrorNode: mir, remoteNode: rem)) } } // Walk the mirror node's children. Any that are deleted on only one side might contribute // orphans, so descend into those nodes' children on the other side. if let expectedParent = mirror?.recordGUID, let mirrorChildren = mirror?.children { try mirrorChildren.forEach { child in let potentiallyDeleted = child.recordGUID if seen.contains(potentiallyDeleted) || self.done.contains(potentiallyDeleted) { return } let locallyDeleted = self.local.deleted.contains(potentiallyDeleted) let remotelyDeleted = self.remote.deleted.contains(potentiallyDeleted) if !locallyDeleted && !remotelyDeleted { log.debug("Mirror child \(potentiallyDeleted) no longer here, but not deleted on either side: must be elsewhere.") return } if locallyDeleted && remotelyDeleted { log.debug("Mirror child \(potentiallyDeleted) was deleted both locally and remoted. We cool.") self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.acceptLocalDeletion.insert(potentiallyDeleted) self.merged.acceptRemoteDeletion.insert(potentiallyDeleted) return } if locallyDeleted { // See if the remote side still thinks this is the parent. let parent = self.remote.parents[potentiallyDeleted] if parent == nil || parent == expectedParent { log.debug("Remote still thinks \(potentiallyDeleted) is here. Processing for orphans.") if let parentOfOrphans = self.remote.find(potentiallyDeleted), let orphans = try processRemoteOrphansForNode(parentOfOrphans) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } } // Accept the local deletion, and make a note to apply it elsewhere. self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.deleteRemotely.insert(potentiallyDeleted) self.merged.acceptLocalDeletion.insert(potentiallyDeleted) return } // Remotely deleted. let parent = self.local.parents[potentiallyDeleted] if parent == nil || parent == expectedParent { log.debug("Local still thinks \(potentiallyDeleted) is here. Processing for orphans.") if let parentOfOrphans = self.local.find(potentiallyDeleted), let orphans = try processLocalOrphansForNode(parentOfOrphans) { out.append(contentsOf: try self.relocateOrphansTo(result, orphans: orphans)) } } // Accept the remote deletion, and make a note to apply it elsewhere. self.merged.deleteFromMirror.insert(potentiallyDeleted) self.merged.deleteLocally.insert(potentiallyDeleted) self.merged.acceptRemoteDeletion.insert(potentiallyDeleted) } } log.debug("Setting \(result.guid)'s children to \(out.map { $0.guid }).") result.mergedChildren = out // If the child list didn't change, then we don't need .new. if changed { let newStructure = out.map { $0.asMergedTreeNode() } result.structureState = MergeState.new(value: BookmarkTreeNode.folder(guid: result.guid, children: newStructure)) return } log.debug("Child list didn't change for \(result.guid). Keeping structure state \(result.structureState).") } fileprivate func resolveThreeWayValueConflict(_ guid: GUID) throws -> MergeState<BookmarkMirrorItem> { // TODO return try self.resolveTwoWayValueConflict(guid, localGUID: guid) } fileprivate func resolveTwoWayValueConflict(_ guid: GUID, localGUID: GUID) throws -> MergeState<BookmarkMirrorItem> { // We don't check for all roots, because we might have to // copy them to the mirror or buffer, so we need to pick // a direction. The Places root is never uploaded. if BookmarkRoots.RootGUID == guid { log.debug("Two-way value merge on the root: always unaltered.") return MergeState.unchanged } let localRecord = self.itemSources.local.getLocalItemWithGUID(localGUID).value.successValue let remoteRecord = self.itemSources.buffer.getBufferItemWithGUID(guid).value.successValue if let local = localRecord { if let remote = remoteRecord { // Two-way. // If they're the same, take the remote record. It saves us having to rewrite // local values to keep a remote GUID. if local.sameAs(remote) { log.debug("Local record \(local.guid) same as remote \(remote.guid). Taking remote.") return MergeState.remote } log.debug("Comparing local (\(local.localModified ??? "0")) to remote (\(remote.serverModified)) clock for two-way value merge of \(guid).") if let localModified = local.localModified, localModified > remote.serverModified { // If we're taking the local record because it was modified, check to see // whether the remote record has a creation date that we want to keep. let dateAddedRemote = remote.dateAdded ?? remote.serverModified if (local.dateAdded ?? UInt64.max) > dateAddedRemote { return MergeState.new(value: local.copyWithDateAdded(dateAddedRemote)) } return MergeState.local } return MergeState.remote } // No remote! log.debug("Expected two-way merge for \(guid), but no remote item found.") return MergeState.local } if let _ = remoteRecord { // No local! log.debug("Expected two-way merge for \(guid), but no local item found.") return MergeState.remote } // Can't two-way merge with nothing! log.error("Expected two-way merge for \(guid), but no local or remote item found!") throw BookmarksMergeError() } // This will never be called with two primary .unknown values. fileprivate func threeWayMerge(_ guid: GUID, localNode: BookmarkTreeNode, remoteNode: BookmarkTreeNode, mirrorNode: BookmarkTreeNode?) throws -> MergedTreeNode { if mirrorNode == nil { log.debug("Two-way merge for \(guid).") } else { log.debug("Three-way merge for \(guid).") } if remoteNode.isUnknown { if localNode.isUnknown { preconditionFailure("Two unknown nodes!") } log.debug("Taking local node in two/three-way merge: remote bafflingly unchanged.") // TODO: value-unchanged return MergedTreeNode.forLocal(localNode) } if localNode.isUnknown { log.debug("Taking remote node in two/three-way merge: local bafflingly unchanged.") // TODO: value-unchanged return MergedTreeNode.forRemote(remoteNode) } let result = MergedTreeNode(guid: guid, mirror: mirrorNode) result.local = localNode result.remote = remoteNode // Value merge. This applies regardless. if localNode.isUnknown { result.valueState = MergeState.remote } else if remoteNode.isUnknown { result.valueState = MergeState.local } else { if mirrorNode == nil { result.valueState = try self.resolveTwoWayValueConflict(guid, localGUID: localNode.recordGUID) } else { result.valueState = try self.resolveThreeWayValueConflict(guid) } } switch localNode { case let .folder(_, localChildren): if case let .folder(_, remoteChildren) = remoteNode { // Structural merge. if localChildren.sameElements(remoteChildren) { // Great! log.debug("Local and remote records have same children in two-way merge.") result.structureState = MergeState.new(value: localNode) // TODO: what if it's the same as the mirror? try self.mergeChildListsIntoMergedNode(result, fromLocal: localNode, remote: remoteNode, mirror: mirrorNode) return result } // Merge the two folder lists. // We know that each side is internally consistent: that is, each // node in this list is present in the tree once only. But when we // combine the two lists, we might be inadvertently duplicating a // record that has already been, or will soon be, found in the other // tree. We need to be careful to make sure that we don't feature // a node in the tree more than once. // Remember to check deletions. log.debug("Local and remote records have different children. Merging.") // Assume it'll be the same as the remote one; mergeChildListsIntoMergedNode // sets this to New if the structure changes. result.structureState = MergeState.remote try self.mergeChildListsIntoMergedNode(result, fromLocal: localNode, remote: remoteNode, mirror: mirrorNode) return result } case .nonFolder: if case .nonFolder = remoteNode { log.debug("Two non-folders with GUID \(guid) collide. Taking remote.") return result } default: break } // Otherwise, this must be a GUID collision between different types. // TODO: Assign a new GUID to the local record // but do not upload a deletion; these shouldn't merge. log.debug("Remote and local records with same GUID \(guid) but different types. Consistency error.") throw BookmarksMergeConsistencyError() } fileprivate func twoWayMerge(_ guid: GUID, localNode: BookmarkTreeNode, remoteNode: BookmarkTreeNode) throws -> MergedTreeNode { return try self.threeWayMerge(guid, localNode: localNode, remoteNode: remoteNode, mirrorNode: nil) } fileprivate func unchangedIf(_ out: MergedTreeNode, original: BookmarkMirrorItem?, new: BookmarkMirrorItem?) -> MergedTreeNode { guard let original = original, let new = new else { return out } if new.sameAs(original) { out.valueState = MergeState.unchanged } return out } fileprivate func takeLocalIfChanged(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let guid = local.recordGUID let localValues = self.itemSources.local.getLocalItemWithGUID(guid).value.successValue let mirrorValues = self.itemSources.mirror.getMirrorItemWithGUID(guid).value.successValue // We don't expect these to ever fail to exist. assert(localValues != nil) let merged = MergedTreeNode.forLocal(local, mirror: mirror) return unchangedIf(merged, original: mirrorValues, new: localValues) } fileprivate func takeRemoteIfChanged(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let guid = remote.recordGUID let remoteValues = self.itemSources.buffer.getBufferItemWithGUID(guid).value.successValue let mirrorValues = self.itemSources.mirror.getMirrorItemWithGUID(guid).value.successValue assert(remoteValues != nil) let merged = MergedTreeNode.forRemote(remote, mirror: mirror) return unchangedIf(merged, original: mirrorValues, new: remoteValues) } fileprivate var folderNameCache: [GUID: String?] = [:] func getNameForFolder(_ folder: MergedTreeNode) throws -> String? { if let name = self.folderNameCache[folder.guid] { return name } let name = try self.fetchNameForFolder(folder) self.folderNameCache[folder.guid] = name return name } func fetchNameForFolder(_ folder: MergedTreeNode) throws -> String? { switch folder.valueState { case let .new(v): return v.title case .unchanged: if let mirror = folder.mirror?.recordGUID, let title = self.itemSources.mirror.getMirrorItemWithGUID(mirror).value.successValue?.title { return title } case .remote: if let remote = folder.remote?.recordGUID, let title = self.itemSources.buffer.getBufferItemWithGUID(remote).value.successValue?.title { return title } case .local: if let local = folder.local?.recordGUID, let title = self.itemSources.local.getLocalItemWithGUID(local).value.successValue?.title { return title } case .unknown: break } throw BookmarksMergeConsistencyError() } func relocateOrphansTo(_ mergedNode: MergedTreeNode, orphans: [MergedTreeNode]?) throws -> [MergedTreeNode] { guard let orphans = orphans else { return [] } let parentName = try self.getNameForFolder(mergedNode) return try orphans.map { try self.relocateMergedTreeNode($0, parentID: mergedNode.guid, parentName: parentName) } } func relocateMergedTreeNode(_ node: MergedTreeNode, parentID: GUID, parentName: String?) throws -> MergedTreeNode { func copyWithMirrorItem(_ item: BookmarkMirrorItem?) throws -> MergedTreeNode { guard let item = item else { throw BookmarksMergeConsistencyError() } if item.parentID == parentID && item.parentName == parentName { log.debug("Don't need to relocate \(node.guid)'s for value table.") return node } log.debug("Relocating \(node.guid) to parent \(parentID).") let n = MergedTreeNode(guid: node.guid, mirror: node.mirror) n.local = node.local n.remote = node.remote n.mergedChildren = node.mergedChildren n.structureState = node.structureState n.valueState = .new(value: item.copyWithParentID(parentID, parentName: parentName)) return n } switch node.valueState { case .unknown: return node case .unchanged: return try copyWithMirrorItem(self.itemSources.mirror.getMirrorItemWithGUID(node.guid).value.successValue) case .local: return try copyWithMirrorItem(self.itemSources.local.getLocalItemWithGUID(node.guid).value.successValue) case .remote: return try copyWithMirrorItem(self.itemSources.buffer.getBufferItemWithGUID(node.guid).value.successValue) case let .new(value): return try copyWithMirrorItem(value) } } // A helper that'll rewrite the resulting node's value to have the right parent. func mergeNode(_ guid: GUID, intoFolder parentID: GUID, withParentName parentName: String?, localNode: BookmarkTreeNode?, mirrorNode: BookmarkTreeNode?, remoteNode: BookmarkTreeNode?) throws -> MergedTreeNode { let m = try self.mergeNode(guid, localNode: localNode, mirrorNode: mirrorNode, remoteNode: remoteNode) // We could check the parent pointers in the tree, but looking at the values themselves // will catch any mismatches between the value and structure tables. return try self.relocateMergedTreeNode(m, parentID: parentID, parentName: parentName) } // We'll end up looking at deletions and such as we go. // TODO: accumulate deletions into the three buckets as we go. // // TODO: if a local or remote node is kept but put in a different folder, we actually // need to generate a .new node, so we can take the parentid and parentNode that we // must preserve. func mergeNode(_ guid: GUID, localNode: BookmarkTreeNode?, mirrorNode: BookmarkTreeNode?, remoteNode: BookmarkTreeNode?) throws -> MergedTreeNode { if let localGUID = localNode?.recordGUID { log.verbose("Merging nodes with GUID \(guid). Local match is \(localGUID).") } else { log.verbose("Merging nodes with GUID \(guid). No local match.") } // TODO: if the local node has a different GUID, it's because we did a value-based // merge. Make sure the local row with the differing local GUID doesn't // stick around. // We'll never get here with no nodes at all… right? precondition((localNode != nil) || (mirrorNode != nil) || (remoteNode != nil)) // Note that not all of the input nodes must share a GUID: we might have decided, based on // value comparison in an earlier recursive call, that a local node will be replaced by a // remote node, and we'll need to mark the local GUID as a deletion, using its values and // structure during our reconciling. // But we will never have the mirror and remote differ. precondition(nullOrMatch(remoteNode?.recordGUID, mirrorNode?.recordGUID)) precondition(nullOrMatch(remoteNode?.recordGUID, guid)) precondition(nullOrMatch(mirrorNode?.recordGUID, guid)) // Immediately mark this GUID -- and the local GUID, if it differs -- as done. // This avoids repeated code in each conditional branch, and avoids the possibility of // certain moves causing us to hit the same node again. self.done.insert(guid) if let otherGUID = localNode?.recordGUID, otherGUID != guid { log.debug("Marking superseded local record \(otherGUID) as merged.") self.done.insert(otherGUID) self.duped.insert(otherGUID) } func takeRemoteAndMergeChildren(_ remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) throws -> MergedTreeNode { let merged = self.takeRemoteIfChanged(remote, mirror: mirror) if case .folder = remote { log.debug("… and it's a folder. Taking remote children.") try self.oneWayMergeChildListsIntoMergedNode(merged, fromRemote: remote) } return merged } func takeLocalAndMergeChildren(_ local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) throws -> MergedTreeNode { let merged = self.takeLocalIfChanged(local, mirror: mirror) if case .folder = local { log.debug("… and it's a folder. Taking local children.") try self.oneWayMergeChildListsIntoMergedNode(merged, fromLocal: local) } return merged } func takeMirrorNode(_ mirror: BookmarkTreeNode) throws -> MergedTreeNode { let merged = MergedTreeNode.forUnchanged(mirror) if case .folder = mirror { try self.takeMirrorChildrenInMergedNode(merged) } return merged } // If we ended up here with two unknowns, just proceed down the mirror. // We know we have a mirror, else we'd have a non-unknown edge. if (localNode?.isUnknown ?? true) && (remoteNode?.isUnknown ?? true) { precondition(mirrorNode != nil) log.verbose("Record \(guid) didn't change from mirror.") self.done.insert(guid) return try takeMirrorNode(mirrorNode!) } guard let mirrorNode = mirrorNode else { // No mirror node: at most a two-way merge. if let loc = localNode, !loc.isUnknown { if let rem = remoteNode { // Two-way merge; probably a disconnect-reconnect scenario. return try self.twoWayMerge(guid, localNode: loc, remoteNode: rem) } // No remote. Node only exists locally. // However! The children might be mentioned in the mirror or // remote tree. log.verbose("Node \(guid) only exists locally.") return try takeLocalAndMergeChildren(loc) } // No local. guard let rem = remoteNode, !rem.isUnknown else { // No remote! // This should not occur: we have preconditions above. preconditionFailure("Unexpectedly got past our preconditions!") } // Node only exists remotely. Take it. log.verbose("Node \(guid) only exists remotely.") return try takeRemoteAndMergeChildren(rem) } // We have a mirror node. if let loc = localNode, !loc.isUnknown { if let rem = remoteNode, !rem.isUnknown { log.debug("Both local and remote changes to mirror item \(guid). Resolving conflict.") return try self.threeWayMerge(guid, localNode: loc, remoteNode: rem, mirrorNode: mirrorNode) } log.verbose("Local-only change to mirror item \(guid).") return try takeLocalAndMergeChildren(loc, mirror: mirrorNode) } if let rem = remoteNode, !rem.isUnknown { log.verbose("Remote-only change to mirror item \(guid).") return try takeRemoteAndMergeChildren(rem, mirror: mirrorNode) } log.verbose("Record \(guid) didn't change from mirror.") return try takeMirrorNode(mirrorNode) } func merge() -> Deferred<Maybe<BookmarksMergeResult>> { return self.produceMergedTree() >>== self.produceMergeResultFromMergedTree } func produceMergedTree() -> Deferred<Maybe<MergedTree>> { // Don't ever do this work twice. if self.mergeAttempted { return deferMaybe(self.merged) } // Both local and remote should reach a single root when overlayed. If not, it means that // the tree is inconsistent -- there isn't a full tree present either on the server (or // local) or in the mirror, or the changes aren't congruent in some way. If we reach this // state, we cannot proceed. // // This is assert()ed in the initializer, too, so that we crash hard and early in developer // builds and tests. if !self.local.isFullyRootedIn(self.mirror) { log.warning("Local bookmarks not fully rooted when overlayed on mirror. This is most unusual.") return deferMaybe(BookmarksMergeErrorTreeIsUnrooted(roots: self.local.subtreeGUIDs)) } if !self.remote.isFullyRootedIn(mirror) { log.warning("Remote bookmarks not fully rooted when overlayed on mirror. Partial read or write in buffer?") // This might be a temporary state: another client might not have uploaded all of its // records yet. Another batch might arrive in a second, or it might arrive a month // later if the user just closed the lid of their laptop and went on vacation! // // This can also be a semi-stable state; e.g., Bug 1235269. It's theoretically // possible for us to try to recover by requesting reupload from other devices // by changing syncID, or through some new command. // // Regardless, we can't proceed until this situation changes. return deferMaybe(BookmarksMergeErrorTreeIsUnrooted(roots: self.remote.subtreeGUIDs)) } log.debug("Processing \(self.localAllGUIDs.count) local changes and \(self.remoteAllGUIDs.count) remote changes.") log.debug("\(self.local.subtrees.count) local subtrees and \(self.remote.subtrees.count) remote subtrees.") log.debug("Local is adding \(self.localAdditions.count) records, and remote is adding \(self.remoteAdditions.count).") log.debug("Local and remote have \(self.allDeletions.count) deletions.") if !conflictingGUIDs.isEmpty { log.warning("Expecting conflicts between local and remote: \(self.conflictingGUIDs.joined(separator: ", ")).") } // Pre-fetch items so we don't need to do async work later. return self.prefetchItems() >>> self.walkProducingMergedTree } fileprivate func prefetchItems() -> Success { return self.itemSources.prefetchWithGUIDs(self.allChangedGUIDs) } // This should only be called once. // Callers should ensure validity of inputs. fileprivate func walkProducingMergedTree() -> Deferred<Maybe<MergedTree>> { let root = self.merged.root assert((root.mirror?.children?.count ?? 0) == BookmarkRoots.RootChildren.count) // Get to walkin'. root.structureState = MergeState.unchanged // We never change the root. root.valueState = MergeState.unchanged root.local = self.local.find(BookmarkRoots.RootGUID) do { try root.mergedChildren = root.mirror!.children!.map { let guid = $0.recordGUID let loc = self.local.find(guid) let mir = self.mirror.find(guid) let rem = self.remote.find(guid) return try self.mergeNode(guid, localNode: loc, mirrorNode: mir, remoteNode: rem) } } catch let error as MaybeErrorType { return deferMaybe(error) } catch let error { return deferMaybe(BookmarksMergeError(error: error)) } // If the buffer contains deletions for records that aren't in the mirror or in local, // then we'll never normally encounter them, and thus we'll never accept the deletion. // Check for that here. let additionalRemoteDeletions = self.remote.deleted.subtracting(self.done) log.debug("Additional remote deletions: \(additionalRemoteDeletions.count).") self.merged.acceptRemoteDeletion.formUnion(additionalRemoteDeletions) self.mergeAttempted = true // Validate. Note that we might end up with *more* records than this -- records // that didn't change naturally aren't present in the change list on either side. let expected = self.allChangedGUIDs.subtracting(self.allDeletions).subtracting(self.duped) assert(self.merged.allGUIDs.isSuperset(of: expected)) assert(self.merged.allGUIDs.intersection(self.allDeletions).isEmpty) return deferMaybe(self.merged) } /** * Input to this function will be a merged tree: a collection of known deletions, * and a tree of nodes that reflect an action and pointers to the edges and the * mirror, something like this: * * ------------------------------------------------------------------------------- * Deleted locally: folderBBBBBB * Deleted remotely: folderDDDDDD * Deleted from mirror: folderBBBBBB, folderDDDDDD * Accepted local deletions: folderDDDDDD * Accepted remote deletions: folderBBBBBB * Root: * [V: □ M □ root________ Unchanged ] * [S: Unchanged ] * .. * [V: □ M □ menu________ Unchanged ] * [S: Unchanged ] * .. * [V: □ M L folderCCCCCC Unchanged ] * [S: New ] * .. * [V: R □ □ bookmarkFFFF Remote ] * [V: □ M □ toolbar_____ Unchanged ] * [S: Unchanged ] * .. * [V: R M □ folderAAAAAA Unchanged ] * [S: New ] * .. * [V: □ □ L r_FpO9_RAXp3 Local ] * [V: □ M □ unfiled_____ Unchanged ] * [S: Unchanged ] * .. * [V: □ M □ mobile______ Unchanged ] * [S: Unchanged ] * .. * ------------------------------------------------------------------------------- * * We walk this tree from the root, breadth-first in order to process folders before * their children. We look at the valueState and structureState (for folders) to decide * whether to spit out actions into the completion ops. * * Changes recorded in the completion ops are along the lines of "copy the record with * this GUID from local into the mirror", "upload this record from local", "delete this * record". Dependencies are encoded by the sequence of completion ops: for example, we * don't want to drop local changes and update the mirror until the server reflects our * local state, and we achieve that by only running the local completion op if the * upload succeeds. * * There's a lot of boilerplate in this function. That's partly because the lines of * switch statements are easier to read through and match up to expected behavior, but * also because it's simpler than threading all of the edge cases around. */ func produceMergeResultFromMergedTree(_ mergedTree: MergedTree) -> Deferred<Maybe<BookmarksMergeResult>> { let upstreamOp = UpstreamCompletionOp() let bufferOp = BufferCompletionOp() let localOp = LocalOverrideCompletionOp() func accumulateNonRootFolder(_ node: MergedTreeNode) { assert(node.isFolder) guard let children = node.mergedChildren else { preconditionFailure("Shouldn't have a non-Unknown folder without known children.") } let childGUIDs = children.map { $0.guid } // Recurse first — because why not? // We don't expect deep enough bookmark trees that we'll overflow the stack, so // we don't bother making a queue. children.forEach(accumulateNode) // Verify that computed child lists match the right source node. switch node.structureState { case .remote: assert(node.remote?.children?.map { $0.recordGUID } ?? [] == childGUIDs) case .local: assert(node.local?.children?.map { $0.recordGUID } ?? [] == childGUIDs) case let .new(treeNode): assert(treeNode.children?.map { $0.recordGUID } ?? [] == childGUIDs) default: break } switch node.valueState { case .unknown: return // Never occurs: guarded by precondition. case .unchanged: // We can't have Unchanged value without a mirror node… assert(node.hasMirror) switch node.structureState { case .unknown: return // Never occurs: guarded by precondition. case .unchanged: // Nothing changed! return case .remote: // Nothing special to do: no need to amend server. break case .local: upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs case .new: // No change in value, but a new structure. // Construct a new upstream record from the old mirror value, // and update the mirror structure. upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs } // We always need to do this for Remote, Local, New. localOp.mirrorStructures[node.guid] = childGUIDs case .local: localOp.mirrorValuesToCopyFromLocal.insert(node.guid) // Generate a new upstream record. upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs // Update the structure in the mirror if necessary. if case .unchanged = node.structureState { return } localOp.mirrorStructures[node.guid] = childGUIDs case .remote: localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) // Update the structure in the mirror if necessary. switch node.structureState { case .unchanged: return case .remote: localOp.mirrorStructures[node.guid] = childGUIDs default: // We need to upload a new record. upstreamOp.amendChildrenFromBuffer[node.guid] = childGUIDs localOp.mirrorStructures[node.guid] = childGUIDs } case let .new(value): // We can only do this if we stuffed the BookmarkMirrorItem with the right children. // Verify that with a precondition. precondition(value.children ?? [] == childGUIDs) localOp.mirrorStructures[node.guid] = childGUIDs if node.hasMirror { localOp.mirrorItemsToUpdate[node.guid] = value } else { localOp.mirrorItemsToInsert[node.guid] = value } let record = Record<BookmarkBasePayload>(id: node.guid, payload: value.asPayload()) upstreamOp.records.append(record) } } func accumulateRoot(_ node: MergedTreeNode) { log.debug("Accumulating \(node.guid).") assert(node.isFolder) assert(BookmarkRoots.Real.contains(node.guid)) guard let children = node.mergedChildren else { preconditionFailure("Shouldn't have a non-Unknown folder without known children.") } // Recurse first — because why not? children.forEach(accumulateNode) let mirrorVersionIsVirtual = self.mirror.virtual.contains(node.guid) // Note that a root can be Unchanged, but be missing from the mirror. That's OK: roots // don't really have values. Take whichever we find. if node.mirror == nil || mirrorVersionIsVirtual { if node.hasLocal { localOp.mirrorValuesToCopyFromLocal.insert(node.guid) } else if node.hasRemote { localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) } else { log.warning("No values to copy into mirror for \(node.guid). Need to synthesize root. Empty merge?") } } log.debug("Need to accumulate a root.") if case .unchanged = node.structureState { if !mirrorVersionIsVirtual { log.debug("Root \(node.guid) is unchanged and already in the mirror.") return } } let childGUIDs = children.map { $0.guid } localOp.mirrorStructures[node.guid] = childGUIDs switch node.structureState { case .remote: log.debug("Root \(node.guid) taking remote structure.") return case .local: log.debug("Root \(node.guid) taking local structure.") upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs case .new: log.debug("Root \(node.guid) taking new structure.") if node.hasMirror && !mirrorVersionIsVirtual { log.debug("… uploading with mirror value.") upstreamOp.amendChildrenFromMirror[node.guid] = childGUIDs } else if node.hasLocal { log.debug("… uploading with local value.") upstreamOp.amendChildrenFromLocal[node.guid] = childGUIDs } else if node.hasRemote { log.debug("… uploading with remote value.") upstreamOp.amendChildrenFromBuffer[node.guid] = childGUIDs } else { log.warning("No values to copy to remote for \(node.guid). Need to synthesize root. Empty merge?") } default: // Filler. return } } func accumulateNode(_ node: MergedTreeNode) { precondition(!node.valueState.isUnknown) precondition(!node.isFolder || !node.structureState.isUnknown) // These two clauses are common to all: if we walk through a node, // it means it's been processed, and no longer needs to be kept // on the edges. if node.hasLocal { let localGUID = node.local!.recordGUID log.debug("Marking \(localGUID) to drop from local.") localOp.processedLocalChanges.insert(localGUID) } if node.hasRemote { log.debug("Marking \(node.guid) to drop from buffer.") bufferOp.processedBufferChanges.insert(node.guid) } if node.isFolder { if BookmarkRoots.Real.contains(node.guid) { accumulateRoot(node) return } // We have to consider structure, and we have to recurse. accumulateNonRootFolder(node) return } // Value didn't change, and no structure to handle. Done. if node.valueState.isUnchanged { precondition(node.hasMirror, "Can't have an unchanged non-root without there being a mirror record.") } // Not new. Emit copy directives. switch node.valueState { case .remote: localOp.mirrorValuesToCopyFromBuffer.insert(node.guid) case .local: let localGUID = node.local!.recordGUID // If we're taking the local value, we expect to keep the local GUID. // TODO: this restriction isn't strictly required, but we know that our // content-based merges will only ever take the remote value. precondition(localGUID == node.guid, "Can't take local value without keeping local GUID.") guard let value = self.itemSources.local.getLocalItemWithGUID(localGUID).value.successValue else { assertionFailure("Couldn't fetch local value for new item \(localGUID). This should never happen.") return } let record = Record<BookmarkBasePayload>(id: localGUID, payload: value.asPayload()) upstreamOp.records.append(record) localOp.mirrorValuesToCopyFromLocal.insert(localGUID) // New. Emit explicit insertions into all three places, // and eliminate any existing records for this GUID. // Note that we don't check structure: this isn't a folder. case let .new(value): // // TODO: ensure that `value` has the right parent GUID!!! // Reparenting means that the moved node has _new_ values // pointing to the _new_ parent. // // It also must have the correct child list. That isn't a // problem in this value-only branch. // // Upstream. let record = Record<BookmarkBasePayload>(id: node.guid, payload: value.asPayload()) upstreamOp.records.append(record) // Mirror. No structure needed. if node.hasMirror { localOp.mirrorItemsToUpdate[node.guid] = value } else { localOp.mirrorItemsToInsert[node.guid] = value } default: return // Deliberately incomplete switch. } } // Upload deleted records for anything we need to delete. // Each one also ends up being dropped from the buffer. if !mergedTree.deleteRemotely.isEmpty { upstreamOp.records.append(contentsOf: mergedTree.deleteRemotely.map { Record<BookmarkBasePayload>(id: $0, payload: BookmarkBasePayload.deletedPayload($0)) }) bufferOp.processedBufferChanges.formUnion(mergedTree.deleteRemotely) } // Drop deleted items from the mirror. localOp.mirrorItemsToDelete.formUnion(mergedTree.deleteFromMirror) // Anything we deleted on either end and accepted, add to the processed lists to be // automatically dropped. localOp.processedLocalChanges.formUnion(mergedTree.acceptLocalDeletion) bufferOp.processedBufferChanges.formUnion(mergedTree.acceptRemoteDeletion) // We draw a terminological distinction between accepting a local deletion (which // drops it from the local table) and deleting an item that's locally modified // (which drops it from the local table, and perhaps also from the mirror). // Either way, we put it in the list to drop. // The former is `localOp.processedLocalChanges`, accumulated as we walk local. // The latter is `mergedTree.deleteLocally`, accumulated as we process incoming deletions. localOp.processedLocalChanges.formUnion(mergedTree.deleteLocally) // Now walk the final tree to get the substantive changes. accumulateNode(mergedTree.root) // Postconditions. // None of the work items appear in more than one place. assert(Set(upstreamOp.amendChildrenFromBuffer.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromLocal.keys))) assert(Set(upstreamOp.amendChildrenFromBuffer.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromMirror.keys))) assert(Set(upstreamOp.amendChildrenFromLocal.keys).isDisjoint(with: Set(upstreamOp.amendChildrenFromMirror.keys))) assert(localOp.mirrorItemsToDelete.isDisjoint(with: Set(localOp.mirrorItemsToInsert.keys))) assert(localOp.mirrorItemsToDelete.isDisjoint(with: Set(localOp.mirrorItemsToUpdate.keys))) assert(Set(localOp.mirrorItemsToInsert.keys).isDisjoint(with: Set(localOp.mirrorItemsToUpdate.keys))) assert(localOp.mirrorValuesToCopyFromBuffer.isDisjoint(with: Set(localOp.mirrorValuesToCopyFromLocal))) // Pass through the item sources so we're able to apply the parts of the result that // are in reference to storage. let result = BookmarksMergeResult(uploadCompletion: upstreamOp, overrideCompletion: localOp, bufferCompletion: bufferOp, itemSources: self.itemSources) return deferMaybe(result) } }
mpl-2.0
599add27da064050d15053e1eadb9211
46.798313
214
0.614979
5.114829
false
false
false
false
aroyarexs/PASTA
Tests/PASTATangibleTests.swift
1
15482
// // Created by Aaron Krämer on 21.08.17. // Copyright (c) 2017 Aaron Krämer. All rights reserved. // import Quick import Nimble import Metron @testable import PASTA class PASTATangibleTests: QuickSpec { override func spec() { var m1: PASTAMarker! var m2: PASTAMarker! var m3: PASTAMarker! var tangible: PASTATangible! beforeEach { m1 = PASTAMarker(center: CGPoint(x: 0, y: 10), radius: 5) m2 = PASTAMarker(center: CGPoint.zero, radius: 5) m3 = PASTAMarker(center: CGPoint(x: 10, y: 0), radius: 5) tangible = PASTATangible(markers: [m1, m2, m3]) } describe("a Tangible") { it("is active") { expect(tangible.isActive).to(beFalse()) } it("has center") { expect(tangible.center).to(equal(CGPoint(x: 5, y: 5))) } it("has markers") { expect(tangible.markers.count).to(equal(3)) } it("has radius") { expect(tangible.radius).to(beCloseTo(14.1421/2.0)) } it("has orientation") { let angle = CGVector(angle: Angle(.pi/2 * -1), magnitude: 1) .angle(between: tangible.initialOrientationVector) expect(angle.degrees).to(equal(0)) expect(tangible.orientationVector).toNot(beNil()) } it("is similar to itself") { expect(tangible ~ tangible).to(beTrue()) } it("has interior angle") { let m1UuidString = m1.markerSnapshot.uuidString let m2UuidString = m2.markerSnapshot.uuidString let m3UuidString = m3.markerSnapshot.uuidString expect(tangible.pattern.angle(atMarkerWith: m1UuidString).degrees).to(beCloseTo(45)) expect(tangible.pattern.angle(atMarkerWith: m2UuidString).degrees).to(beCloseTo(90)) expect(tangible.pattern.angle(atMarkerWith: m3UuidString).degrees).to(beCloseTo(45)) } it("markers their tangible property is set") { expect(m1.tangible).toNot(beNil()) expect(m2.tangible).toNot(beNil()) expect(m3.tangible).toNot(beNil()) } context("rotated") { it("has orientation") { let vectorBeforeRotation = tangible.orientationVector let angle = Angle(56, unit: .degrees) m1.center = LineSegment(a: tangible.center, b: m1.center).rotatedAroundA(angle).b m2.center = LineSegment(a: tangible.center, b: m2.center).rotatedAroundA(angle).b m3.center = LineSegment(a: tangible.center, b: m3.center).rotatedAroundA(angle).b let up = CGVector(angle: Angle(.pi/2 * -1), magnitude: 1) let angle1 = up.angle(between: tangible.initialOrientationVector) expect(angle1.degrees).to(beCloseTo(56)) expect(tangible.orientationVector).toNot(beNil()) guard let v = tangible.orientationVector, let v2 = vectorBeforeRotation else { fail() return } var angle2 = v.angle(between: v2) angle2 = angle2 < Angle(0) ? angle2.inversed : angle2 expect(angle2.degrees).to(beCloseTo(56)) } } context("one is moving") { var beforeRadius: CGFloat! beforeEach { beforeRadius = tangible.radius m1.center = m1.center.applying(.init(translationX: 0, y: -5)) m1.tangible?.markerMoved(m1) } it("center changes") { expect(tangible.center.y) < tangible.previousCenter.y } it("radius changes") { expect(tangible.radius) < beforeRadius } } context("one active marker") { beforeEach { m2.isActive = true } it("has two inactive") { expect(tangible.inactiveMarkers.count) == 2 } it("will replace an inactive marker") { let marker = PASTAMarker(center: CGPoint(x: 2, y: 9), radius: 5) marker.isActive = true let success = tangible.replaceInactiveMarker(with: marker) expect(success) == true expect(tangible.markers.contains(marker)) == true expect(tangible.inactiveMarkers.count) == 1 } it("won't replace inactive marker") { let marker = PASTAMarker(center: CGPoint(x: 4, y: 2.5), radius: 5) marker.isActive = true let success = tangible.replaceInactiveMarker(with: marker) expect(success) == false expect(tangible.markers.contains(marker)) == false expect(tangible.inactiveMarkers.count) == 2 } context("all marker active") { var activePattern: PASTAPattern! beforeEach { m1.isActive = true m3.isActive = true activePattern = tangible.pattern } it("has no inactive marker") { expect(tangible.inactiveMarkers.isEmpty) == true } context("m3 is inactive") { var inactivePattern: PASTAPattern! beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesEnded(touches, with: nil) inactivePattern = tangible.pattern } it("has an inactive marker") { expect(tangible.inactiveMarkers.count) == 1 } it("current and previous pattern are similar") { expect(activePattern.isSimilar(to: tangible.pattern)) == true } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } context("m3 active again") { var secondActivePattern: PASTAPattern! beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesBegan(touches, with: nil) secondActivePattern = tangible.pattern } it("has no inactive markers") { expect(tangible.inactiveMarkers.isEmpty) == true } it("pattern similar to previous") { expect(tangible.pattern.isSimilar(to: inactivePattern)) == true } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } context("m3 inactive again") { beforeEach { var touches = Set<MockTouch>() touches.insert(MockTouch(location: m3.center, radius: m3.radius)) m3.touchesEnded(touches, with: nil) } it("has an inactive marker") { expect(tangible.inactiveMarkers.count) == 1 } it("m3 marker did not moved") { expect(m3.center) == m3.previousCenter } it("pattern similar to previous") { expect(tangible.pattern.isSimilar(to: secondActivePattern)) == true } } } } } } context("received a marker-moved event") { var translation: CGPoint! var prevTangibleRadius: CGFloat! beforeEach { prevTangibleRadius = tangible.radius var touches = Set<MockTouch>() let angle = Angle(45, unit: .degrees) let newMarkerPosition = LineSegment(a: m2.center, b: m1.center).rotatedAroundA(angle).b translation = (newMarkerPosition - m1.center).point touches.insert(MockTouch(location: newMarkerPosition, radius: 11)) m1.touchesBegan(touches, with: nil) } it("has one active marker") { expect(tangible.inactiveMarkers.count).to(equal(2)) } it("is active") { expect(tangible.isActive).to(beTrue()) } it("active marker moved") { expect(m1.center.x).to(beCloseTo(m1.previousCenter.x + translation.x)) expect(m1.center.y).to(beCloseTo(m1.previousCenter.y + translation.y)) } it("inactive markers moved") { expect(m2.center.x).to(beCloseTo(m2.previousCenter.x + translation.x)) expect(m2.center.y).to(beCloseTo(m2.previousCenter.y + translation.y)) expect(m3.center.x).to(beCloseTo(m3.previousCenter.x + translation.x)) expect(m3.center.y).to(beCloseTo(m3.previousCenter.y + translation.y)) } it("center moved") { expect(tangible.center.x).to(beCloseTo(tangible.previousCenter.x + translation.x)) expect(tangible.center.y).to(beCloseTo(tangible.previousCenter.y + translation.y)) } it("frame updates") { expect(tangible.frame.origin).to(equal(tangible.center.applying( .init(translationX: -tangible.radius, y: -tangible.radius)))) expect(tangible.frame.width).to(equal(tangible.radius*2)) } it("radius did not changed") { expect(tangible.radius).to(beCloseTo(prevTangibleRadius)) } context("received marker-moved event from different marker") { var prevTangibleRadius2: CGFloat! beforeEach { prevTangibleRadius2 = tangible.radius var touches2 = Set<MockTouch>() let angle = Angle(45, unit: .degrees) let newMarkerPosition2 = LineSegment(a: m1.center, b: m2.center).rotatedAroundA(angle).b touches2.insert(MockTouch(location: newMarkerPosition2, radius: 11)) m2.touchesBegan(touches2, with: nil) } it("has two active markers") { expect(tangible.inactiveMarkers.count).to(equal(1)) } it("radius did not changed") { expect(tangible.radius).to(beCloseTo(prevTangibleRadius2)) } it("is active") { expect(tangible.isActive).to(beTrue()) } it("center moved") { let prevCenter = Triangle(a: m1.center, b: m2.previousCenter, c: tangible.inactiveMarkers.first!.previousCenter).cicrumcenter expect(prevCenter.x).toNot(beCloseTo(tangible.center.x, within: 0.1)) expect(prevCenter.y).toNot(beCloseTo(tangible.center.y, within: 0.1)) expect(tangible.previousCenter.x).to(beCloseTo(prevCenter.x)) expect(tangible.previousCenter.y).to(beCloseTo(prevCenter.y)) } xit("inactive marker moved") { // FIXME: update let v1 = CGVector(from: m1.center, to: m3.previousCenter) var angle = CGVector(from: m1.center, to: m3.center).angle(between: v1) angle = angle.degrees < 0 ? angle.inversed : angle expect(angle.degrees).to(beCloseTo(45)) let rotationAngle = Angle(45, unit: .degrees) let newPos = LineSegment(a: m1.center, b: m3.previousCenter).rotatedAroundA(rotationAngle).b expect(m3.center.x).to(beCloseTo(newPos.x)) expect(m3.center.y).to(beCloseTo(newPos.y)) } it("other active marker did not moved") { expect(m1.center.x).to(beCloseTo(m1.previousCenter.x + translation.x)) expect(m1.center.y).to(beCloseTo(m1.previousCenter.y + translation.y)) } it("active marker moved") { let cv = CGVector(from: m1.center, to: m2.center) let ov = CGVector(from: m1.center, to: m2.previousCenter) var angle = cv.angle(between: ov) angle = angle < Angle(0) ? angle.inversed : angle expect(angle.degrees).to(beCloseTo(45)) let rotationAngle = Angle(45, unit: .degrees) let newPos = LineSegment(a: m1.center, b: m2.previousCenter).rotatedAroundA(rotationAngle).b expect(m2.center.x).to(beCloseTo(newPos.x)) expect(m2.center.y).to(beCloseTo(newPos.x)) } } } } describe("a Tangible init with coder") { expect(PASTATangible(coder: NSCoder())).to(beNil()) } describe("a mocked Tangible") { var t: MockTangibleMarkerMovedCalled? beforeEach { t = MockTangibleMarkerMovedCalled(markers: [m1, m2, m3]) } it("is not nil") { expect(t).toNot(beNil()) } it("calls marker moved") { var touches = Set<MockTouch>() touches.insert(MockTouch(location: CGPoint(x: 5, y: -5), radius: 11)) m1.touchesMoved(touches, with: nil) guard let tangible = t else { return } expect(tangible.called).to(beTrue()) } } } } class MockTangibleMarkerMovedCalled: PASTATangible { var called = false override func markerMoved(_ marker: PASTAMarker) { called = true } }
mit
9ea1a56a9e50dbbbdeb9c7774fc0e90d
47.679245
116
0.477067
5.156562
false
false
false
false
brentdax/swift
test/Sema/substring_to_string_conversion_swift4.swift
15
3765
// RUN: %target-swift-frontend -typecheck -verify -swift-version 4 %s let s = "Hello" let ss = s[s.startIndex..<s.endIndex] // CTP_Initialization do { let s1: String = { return ss }() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{35-35=)}} _ = s1 } // CTP_ReturnStmt do { func returnsAString() -> String { return ss // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{12-12=String(}} {{14-14=)}} } } // CTP_ThrowStmt // Doesn't really make sense for this fix-it - see case in diagnoseContextualConversionError: // The conversion destination of throw is always ErrorType (at the moment) // if this ever expands, this should be a specific form like () is for // return. // CTP_EnumCaseRawValue // Substrings can't be raw values because they aren't literals. // CTP_DefaultParameter do { func foo(x: String = ss) {} // expected-error {{default argument value of type 'Substring' cannot be converted to type 'String'}} {{24-24=String(}} {{26-26=)}} } // CTP_CalleeResult do { func getSubstring() -> Substring { return ss } let gottenString : String = getSubstring() // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{31-31=String(}} {{45-45=)}} _ = gottenString } // CTP_CallArgument do { func takesAString(_ s: String) {} takesAString(ss) // expected-error {{cannot convert value of type 'Substring' to expected argument type 'String'}} {{16-16=String(}} {{18-18=)}} } // CTP_ClosureResult do { [ss].map { (x: Substring) -> String in x } // expected-error {{cannot convert value of type 'Substring' to closure result type 'String'}} {{42-42=String(}} {{43-43=)}} } // CTP_ArrayElement do { let a: [String] = [ ss ] // expected-error {{cannot convert value of type 'Substring' to expected element type 'String'}} {{23-23=String(}} {{25-25=)}} _ = a } // CTP_DictionaryKey do { let d: [ String : String ] = [ ss : s ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary key type 'String'}} {{34-34=String(}} {{36-36=)}} _ = d } // CTP_DictionaryValue do { let d: [ String : String ] = [ s : ss ] // expected-error {{cannot convert value of type 'Substring' to expected dictionary value type 'String'}} {{38-38=String(}} {{40-40=)}} _ = d } // CTP_CoerceOperand do { let s1: String = ss as String // expected-error {{cannot convert value of type 'Substring' to type 'String' in coercion}} {{20-20=String(}} {{22-22=)}} _ = s1 } // CTP_AssignSource do { let s1: String = ss // expected-error {{cannot convert value of type 'Substring' to specified type 'String'}} {{20-20=String(}} {{22-22=)}} _ = s1 } // Substring-to-String via subscripting in a context expecting String func takesString(_ s: String) {} func apply(_ fn: (String) -> (), _ s: String) { fn(s[s.startIndex..<s.endIndex]) // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{6-6=String(}} {{34-34=)}} let _: String = s[s.startIndex..<s.endIndex] // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{19-19=String(}} {{47-47=)}} _ = s[s.startIndex..<s.endIndex] as String // expected-error{{subscripts returning String were obsoleted in Swift 4; explicitly construct a String from subscripted result}} {{7-7=String(}} {{35-35=)}} } // rdar://33474838 protocol Derivable { func derive() -> Substring } func foo<T: Derivable>(t: T) -> String { return t.derive() // expected-error {{cannot convert return expression of type 'Substring' to return type 'String'}} {{10-10=String(}} {{20-20=)}} }
apache-2.0
a0cf93f6b79ef594b1ffec3f2198056b
38.21875
206
0.669854
3.56872
false
false
false
false
kmikiy/SpotMenu
MusicPlayer/Manager/MusicPlayerManager.swift
1
5358
// // MusicPlayerManager.swift // MusicPlayer // // Created by Michael Row on 2017/9/3. // import Foundation public class MusicPlayerManager { public weak var delegate: MusicPlayerManagerDelegate? public fileprivate(set) var musicPlayers = [MusicPlayer]() public weak var currentPlayer: MusicPlayer? public init() {} } // MARK: - Public Manager Methods public extension MusicPlayerManager { /// The player names that added to the manager. public var allPlayerNames: [MusicPlayerName] { var playerNames = [MusicPlayerName]() for player in musicPlayers { playerNames.append(player.name) } return playerNames } /// Return the player with selected name if exists. public func existMusicPlayer(with name: MusicPlayerName) -> MusicPlayer? { for player in musicPlayers { if player.name == name { return player } } return nil } /// Add a music player to the manager. /// /// - Parameter name: The name of the music player you wanna add. public func add(musicPlayer name: MusicPlayerName) { for player in musicPlayers { guard player.name != name else { return } } guard let player = MusicPlayerFactory.musicPlayer(name: name) else { return } player.delegate = self player.startPlayerTracking() musicPlayers.append(player) selectMusicPlayer(with: player) } /// Add music players to the manager. /// /// - Parameter names: The names of the music player you wanna add. public func add(musicPlayers names: [MusicPlayerName]) { for name in names { add(musicPlayer: name) } } /// Remove a music player from the manager. /// /// - Parameter name: The name of the music player you wanna remove. public func remove(musicPlayer name: MusicPlayerName) { for index in 0 ..< musicPlayers.count { let player = musicPlayers[index] guard player.name == name else { continue } player.stopPlayerTracking() musicPlayers.remove(at: index) // if the removal is the current player, we should select a new one. if currentPlayer?.name == player.name { currentPlayer = nil selectMusicPlayerFromList() } return } } /// Remove music players from the manager. /// /// - Parameter names: The names of the music player you wanna remove. public func remove(musicPlayers names: [MusicPlayerName]) { for name in names { remove(musicPlayer: name) } } /// Remove all music players from the manager. public func removeAllMusicPlayers() { for player in musicPlayers { player.stopPlayerTracking() } musicPlayers.removeAll() currentPlayer = nil } } // MARK: - MusicPlayerDelegate extension MusicPlayerManager: MusicPlayerDelegate { public func player(_ player: MusicPlayer, didChangeTrack track: MusicTrack, atPosition position: TimeInterval) { selectMusicPlayer(with: player) guard currentPlayer?.name == player.name else { return } delegate?.manager(self, trackingPlayer: player, didChangeTrack: track, atPosition: position) } public func player(_ player: MusicPlayer, playbackStateChanged playbackState: MusicPlaybackState, atPosition postion: TimeInterval) { selectMusicPlayer(with: player) guard currentPlayer?.name == player.name else { return } delegate?.manager(self, trackingPlayer: player, playbackStateChanged: playbackState, atPosition: postion) if !playbackState.isActiveState { selectMusicPlayerFromList() } } public func playerDidQuit(_ player: MusicPlayer) { guard currentPlayer != nil, currentPlayer!.name == player.name else { return } currentPlayer = nil delegate?.manager(self, trackingPlayerDidQuit: player) selectMusicPlayerFromList() } fileprivate func selectMusicPlayerFromList() { for player in musicPlayers { selectMusicPlayer(with: player) if let playerState = currentPlayer?.playbackState, playerState.isActiveState { return } } } fileprivate func selectMusicPlayer(with player: MusicPlayer) { guard shouldChangePlayer(with: player) else { return } currentPlayer = player delegate?.manager(self, trackingPlayerDidChange: player) } fileprivate func shouldChangePlayer(with player: MusicPlayer) -> Bool { // check wheter the new player and current one are the same player. guard currentPlayer !== player else { return false } // check the new player's playback state guard player.playbackState.isActiveState else { return false } // check current player's playback state guard let playbackState = currentPlayer?.playbackState else { return true } if playbackState.isActiveState { return false } else { return true } } }
mit
55102fa199c5abcc3ec1a4809b409ce0
31.277108
137
0.621874
5.358
false
false
false
false
xmartlabs/Bender
Sources/Graph/Graph.swift
1
745
// // Graph.swift // Bender // // Created by Mathias Claassen on 5/17/17. // // /// Protocol implemented by any Graph public protocol GraphProtocol { associatedtype T: Node var nodes: [T] { get set } } public extension GraphProtocol { /// Removes nodes that have no adjacencies mutating func removeLonely() { nodes = nodes.filter { !$0.isLonely } } /// Sort nodes by dependencies mutating func sortNodes() { let inputs: [T] = nodes.filter { $0.incomingNodes().isEmpty } let sorted = DependencyListBuilder().list(from: inputs) assert(nodes.count == sorted.count, "Seems you might have a cyclic dependency in your graph. That is not supported!") nodes = sorted } }
mit
18b6f849f4eee96211e692c47a23daa9
22.28125
125
0.641611
3.921053
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/PartyService/View/ScoreTableViewCell.swift
1
1971
// // ScoreTableViewCell.swift // WePeiYang // // Created by JinHongxu on 16/8/15. // Copyright © 2016年 Qin Yubo. All rights reserved. // import Foundation import UIKit //import SnapKit class ScoreTableViewCell: UITableViewCell { 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 } convenience init(title: String, score: String, completeTime: String) { self.init() let titleLabel = UILabel(text: title) let timeLabel = UILabel(text: completeTime) let scoreLabel = UILabel(text: score) titleLabel.font = UIFont.boldSystemFontOfSize(12.0) titleLabel.textColor = UIColor.lightGrayColor() scoreLabel.font = UIFont.boldSystemFontOfSize(12.0) scoreLabel.textColor = UIColor.redColor() timeLabel.font = UIFont.boldSystemFontOfSize(10.0) timeLabel.textColor = UIColor.lightGrayColor() contentView.addSubview(titleLabel) contentView.addSubview(timeLabel) contentView.addSubview(scoreLabel) timeLabel.snp_makeConstraints { make in make.right.equalTo(contentView).offset(-8) make.centerY.equalTo(contentView) } scoreLabel.snp_makeConstraints { make in make.right.equalTo(timeLabel.snp_left).offset(-8) make.centerY.equalTo(contentView) } titleLabel.snp_makeConstraints { make in make.left.equalTo(contentView).offset(8) make.centerY.equalTo(contentView) make.right.lessThanOrEqualTo(scoreLabel.snp_left).offset(-8) } } }
mit
7b5d6044ab44f58d4220f99f0a5df5cd
26.732394
74
0.60315
5.111688
false
false
false
false
migueloruiz/la-gas-app-swift
lasgasmx/UINavigationItem+Helper.swift
1
1845
// // UINavigationItem+Helper.swift // lasgasmx // // Created by Desarrollo on 4/6/17. // Copyright © 2017 migueloruiz. All rights reserved. // import UIKit extension UINavigationItem { func set(title:String, subtitle:String) { let titleLabel = UILabel() titleLabel.backgroundColor = .clear titleLabel.textColor = .white titleLabel.font = UIFont.boldSystemFont(ofSize: 14) titleLabel.text = title titleLabel.textAlignment = .center titleLabel.sizeToFit() let subtitleLabel = UILabel() subtitleLabel.backgroundColor = .clear subtitleLabel.textColor = .white subtitleLabel.font = UIFont.systemFont(ofSize: 12) subtitleLabel.text = subtitle subtitleLabel.textAlignment = .center subtitleLabel.sizeToFit() let titleView = UIView(frame: CGRect(x: 0, y: 0, width: max(titleLabel.frame.size.width, subtitleLabel.frame.size.width), height: 30)) titleView.addSubview(titleLabel) titleView.addSubview(subtitleLabel) titleLabel.anchor(top: titleView.topAnchor, left: titleView.leftAnchor, bottom: subtitleLabel.topAnchor, right: titleView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0 ) subtitleLabel.anchor(top: titleLabel.bottomAnchor, left: titleView.leftAnchor, bottom: titleView.bottomAnchor, right: titleView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0 ) self.titleView = titleView } } extension UINavigationBar { func hiddeShadow() { self.setBackgroundImage(UIImage(), for: .default) self.shadowImage = UIImage() } }
mit
1f8677c2b49c6d9fee6bf73a9a895021
33.792453
256
0.670282
4.802083
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/Printers/controller/PrintersTabBarViewController.swift
1
1919
// // PrintersTabBarViewController.swift // byuSuite // // Created by Alex Boswell on 8/24/18. // Copyright © 2018 Brigham Young University. All rights reserved. // import UIKit class PrintersTabBarViewController: ByuTabBarViewController { var printerBuildings: [PrintersBuilding]? var printers: [Printer]? override func viewDidLoad() { super.viewDidLoad() loadData() } private func loadData() { if let vcs = self.viewControllers, let buildingsVC = vcs[0] as? PrintersBuildingsViewController, let mapVC = vcs[1] as? PrintersMapViewController { buildingsVC.spinner?.startAnimating() PrintersClient.getAllBuildingsWithCurrentFilter { (printerBuildings, error) in buildingsVC.spinner?.stopAnimating() if let printerBuildings = printerBuildings { self.printerBuildings = printerBuildings buildingsVC.updatePrinterBuildings(printerBuildings) } else { super.displayAlert(error: error) } } mapVC.spinner?.startAnimating() PrintersClient.getAllPrintersWithCurrentFilter(buildingCode: nil) { (printers, error) in mapVC.spinner?.stopAnimating() if let printers = printers { self.printers = printers mapVC.updatePrinters(printers) } else { super.displayAlert(error: error) } } } else { super.displayAlert() } } @IBAction func unwindFromFilterVC(_ sender: UIStoryboardSegue) { if let filterVC = sender.source as? PrintersFilterViewController { if filterVC.filtersChanged { loadData() } } } }
apache-2.0
8080a831fe5304e4203c400a263f9956
31.508475
100
0.570386
5.372549
false
false
false
false
TellMeAMovieTeam/TellMeAMovie_iOSApp
TellMeAMovie/Pods/TMDBSwift/Sources/Models/MovieReleaseDatesMDB.swift
1
1021
// // MovieReleaseDatesMDB.swift // MDBSwiftWrapper // // Created by George Kye on 2016-03-08. // Copyright © 2016 George KyeKye. All rights reserved. // import Foundation open class MovieReleaseDatesMDB: ArrayObject{ open var iso_3166_1: String? open var release_dates = [Release_Dates]() required public init(results: JSON){ iso_3166_1 = results["iso_3166_1"].string release_dates = Release_Dates.initialize(json: results["release_dates"]) } } //move inside class? public struct Release_Dates: ArrayObject{ public var certification: String? public var iso_639_1: String? public var note: String? public var release_date: String? //change to formatted NSDate later?? public var type: Int? public init(results release_date: JSON){ certification = release_date["certification"].string iso_639_1 = release_date["iso_639_1"].string note = release_date["note"].string self.release_date = release_date["release_date"].string type = release_date["type"].int } }
apache-2.0
dd0ce381bbb688725cedc17f6c40f44a
26.567568
76
0.703922
3.722628
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Task/CSDoLaterOnce.swift
1
500
// // Created by Rene Dohan on 1/1/21. // import Foundation public class CSDoLaterOnce { let delay: TimeInterval, function: Func var willInvoke = false public init(delay: TimeInterval = 0, _ function: @escaping Func) { self.delay = delay; self.function = function } public func start() { if willInvoke { return } willInvoke = true later(seconds: delay) { [unowned self] in function() willInvoke = false } } }
mit
101cef8ea6853529461c7e7455985d78
20.782609
70
0.592
4.132231
false
false
false
false
zakkhoyt/ColorPicKit
ColorPicKitExample/HSBWheelBrightnessViewController.swift
1
1873
// // HSBWheelBrightnessViewController.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/8/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit class HSBWheelBrightnessViewController: BaseViewController { @IBOutlet weak var hsbWheel: HSBWheel! @IBOutlet weak var brightnessSlider: GradientSlider! // MARK: colorWheel actions @IBAction func colorWheelValueChanged(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } @IBAction func colorWheelTouchDown(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } @IBAction func colorWheelTouchUpInside(_ sender: HSBWheel) { updateBackgroundColor() updateBrightnessSlider() } // MARK: brightnessSlider actions @IBAction func brightnessSliderTouchDown(_ sender: GradientSlider) { updateBackgroundColor() } @IBAction func brightnessSliderTouchUpInside(_ sender: GradientSlider) { updateBackgroundColor() } @IBAction func brightnessSliderValueChanged(_ sender: GradientSlider) { updateBackgroundColor() } private func updateBrightnessSlider() { let hsba = hsbWheel.color.hsba() let color = UIColor(hue: hsba.hue, saturation: 1.0, brightness: 1.0, alpha: 1.0) brightnessSlider.color2 = color } private func updateBackgroundColor() { let brightness = brightnessSlider.value hsbWheel.brightness = brightness colorView.backgroundColor = hsbWheel.color } override func reset() { hsbWheel.position = CGPoint(x: hsbWheel.bounds.midX, y: hsbWheel.bounds.midY) brightnessSlider.value = resetValue updateBackgroundColor() updateBrightnessSlider() } }
mit
2b4b236438b013432717b151eebd31d4
26.940299
88
0.663462
5.672727
false
false
false
false
editfmah/AeonAPI
Sources/Mutex.swift
1
572
// // Mutex.swift // scale // // Created by Adrian Herridge on 06/02/2017. // // import Foundation import Dispatch import SWSQLite class Mutex { private var thread: Thread? = nil; private var lock: DispatchQueue init() { lock = DispatchQueue(label: uuid()) } func mutex(_ closure: ()->()) { if thread != Thread.current { lock.sync { thread = Thread.current closure() thread = nil } } else { closure() } } }
mit
6d89d3514de1d14756d552870e532619
15.823529
45
0.480769
4.366412
false
false
false
false
skonb/YapDatabaseExtensions
framework/Pods/PromiseKit/Sources/Promise.swift
4
15079
import Foundation.NSError public let PMKOperationQueue = NSOperationQueue() public enum CatchPolicy { case AllErrors case AllErrorsExceptCancellation } /** A promise represents the future value of a task. To obtain the value of a promise we call `then`. Promises are chainable: `then` returns a promise, you can call `then` on that promise, which returns a promise, you can call `then` on that promise, et cetera. 0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2 Promises start in a pending state and *resolve* with a value to become *fulfilled* or with an `NSError` to become rejected. @see [PromiseKit `then` Guide](http://promisekit.org/then/) @see [PromiseKit Chaining Guide](http://promisekit.org/chaining/) */ public class Promise<T> { let state: State /** Create a new pending promise. Use this method when wrapping asynchronous systems that do *not* use promises so that they can be involved in promise chains. Don’t use this method if you already have promises! Instead, just return your promise! The closure you pass is executed immediately on the calling thread. func fetchKitten() -> Promise<UIImage> { return Promise { fulfill, reject in KittenFetcher.fetchWithCompletionBlock({ img, err in if err == nil { fulfill(img) } else { reject(err) } }) } } @param resolvers The provided closure is called immediately. Inside, execute your asynchronous system, calling fulfill if it suceeds and reject for any errors. @return A new promise. @warning *Note* If you are wrapping a delegate-based system, we recommend to use instead: defer @see http://promisekit.org/sealing-your-own-promises/ @see http://promisekit.org/wrapping-delegation/ */ public convenience init(@noescape resolvers: (fulfill: (T) -> Void, reject: (NSError) -> Void) -> Void) { self.init(sealant: { sealant in resolvers(fulfill: sealant.resolve, reject: sealant.resolve) }) } /** Create a new pending promise. This initializer is convenient when wrapping asynchronous systems that use common patterns. For example: func fetchKitten() -> Promise<UIImage> { return Promise { sealant in KittenFetcher.fetchWithCompletionBlock(sealant.resolve) } } @see Sealant @see init(resolvers:) */ public init(@noescape sealant: (Sealant<T>) -> Void) { var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) sealant(Sealant(body: resolve)) } /** Create a new fulfilled promise. */ public init(_ value: T) { state = SealedState(resolution: .Fulfilled(value)) } /** Create a new rejected promise. */ public init(_ error: NSError) { unconsume(error) state = SealedState(resolution: .Rejected(error)) } /** I’d prefer this to be the designated initializer, but then there would be no public designated unsealed initializer! Making this convenience would be inefficient. Not very inefficient, but still it seems distasteful to me. */ init(passthru: ((Resolution) -> Void) -> Void) { var resolve: ((Resolution) -> Void)! state = UnsealedState(resolver: &resolve) passthru(resolve) } /** defer is convenient for wrapping delegates or larger asynchronous systems. class Foo: BarDelegate { let (promise, fulfill, reject) = Promise<Int>.defer() func barDidFinishWithResult(result: Int) { fulfill(result) } func barDidError(error: NSError) { reject(error) } } @return A tuple consisting of: 1) A promise 2) A function that fulfills that promise 3) A function that rejects that promise */ public class func defer() -> (promise: Promise, fulfill: (T) -> Void, reject: (NSError) -> Void) { var sealant: Sealant<T>! let promise = Promise { sealant = $0 } return (promise, sealant.resolve, sealant.resolve) } func pipe(body: (Resolution) -> Void) { state.get { seal in switch seal { case .Pending(let handlers): handlers.append(body) case .Resolved(let resolution): body(resolution) } } } private convenience init<U>(when: Promise<U>, body: (Resolution, (Resolution) -> Void) -> Void) { self.init(passthru: { resolve in when.pipe{ body($0, resolve) } }) } /** The provided block is executed when this Promise is resolved. If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter. @param on The queue on which body should be executed. @param body The closure that is executed when this Promise is fulfilled. [NSURLConnection GET:url].then(^(NSData *data){ // do something with data }); @return A new promise that is resolved with the value returned from the provided closure. For example: [NSURLConnection GET:url].then(^(NSData *data){ return data.length; }).then(^(NSNumber *number){ //… }); @see thenInBackground */ public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> U) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { resolve(.Fulfilled(body(value as! T))) } } } } public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> Promise<U>) -> Promise<U> { return Promise<U>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { body(value as! T).pipe(resolve) } } } } public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) -> AnyPromise) -> Promise<AnyObject?> { return Promise<AnyObject?>(when: self) { resolution, resolve in switch resolution { case .Rejected: resolve(resolution) case .Fulfilled(let value): contain_zalgo(q) { let anypromise = body(value as! T) anypromise.pipe { obj in if let error = obj as? NSError { resolve(.Rejected(error)) } else { // possibly the value of this promise is a PMKManifold, if so // calling the objc `value` method will return the first item. let obj: AnyObject? = anypromise.valueForKey("value") resolve(.Fulfilled(obj)) } } } } } } /** The provided closure is executed on the default background queue when this Promise is fulfilled. This method is provided as a convenience for `then`. @see then */ public func thenInBackground<U>(body: (T) -> U) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } public func thenInBackground<U>(body: (T) -> Promise<U>) -> Promise<U> { return then(on: dispatch_get_global_queue(0, 0), body) } /** The provided closure is executed when this Promise is rejected. Rejecting a promise cascades: rejecting all subsequent promises (unless recover is invoked) thus you will typically place your catch at the end of a chain. Often utility promises will not have a catch, instead delegating the error handling to the caller. The provided closure always runs on the main queue. @param policy The default policy does not execute your handler for cancellation errors. See registerCancellationError for more documentation. @param body The handler to execute when this Promise is rejected. @see registerCancellationError */ public func catch(policy: CatchPolicy = .AllErrorsExceptCancellation, _ body: (NSError) -> Void) { pipe { resolution in switch resolution { case .Fulfilled: break case .Rejected(let error): if policy == .AllErrors || !error.cancelled { dispatch_async(dispatch_get_main_queue()) { consume(error) body(error) } } } } } /** The provided closure is executed when this Promise is rejected giving you an opportunity to recover from the error and continue the promise chain. */ public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (NSError) -> Promise<T>) -> Promise<T> { return Promise(when: self) { resolution, resolve in switch resolution { case .Rejected(let error): contain_zalgo(q) { consume(error) body(error).pipe(resolve) } case .Fulfilled: resolve(resolution) } } } /** The provided closure is executed when this Promise is resolved. @param on The queue on which body should be executed. @param body The closure that is executed when this Promise is resolved. UIApplication.sharedApplication().networkActivityIndicatorVisible = true somePromise().then { //… }.finally { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } */ public func finally(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise<T> { return Promise(when: self) { resolution, resolve in contain_zalgo(q) { body() resolve(resolution) } } } /** @return The value with which this promise was fulfilled or nil if this promise is not fulfilled. */ public var value: T? { switch state.get() { case .None: return nil case .Some(.Fulfilled(let value)): return (value as! T) case .Some(.Rejected): return nil } } } /** Zalgo is dangerous. Pass as the `on` parameter for a `then`. Causes the handler to be executed as soon as it is resolved. That means it will be executed on the queue it is resolved. This means you cannot predict the queue. In the case that the promise is already resolved the handler will be executed immediately. zalgo is provided for libraries providing promises that have good tests that prove unleashing zalgo is safe. You can also use it in your application code in situations where performance is critical, but be careful: read the essay at the provided link to understand the risks. @see http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony */ public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil) /** Waldo is dangerous. Waldo is zalgo, unless the current queue is the main thread, in which case we dispatch to the default background queue. If your block is likely to take more than a few milliseconds to execute, then you should use waldo: 60fps means the main thread cannot hang longer than 17 milliseconds. Don’t contribute to UI lag. Conversely if your then block is trivial, use zalgo: GCD is not free and for whatever reason you may already be on the main thread so just do what you are doing quickly and pass on execution. It is considered good practice for asynchronous APIs to complete onto the main thread. Apple do not always honor this, nor do other developers. However, they *should*. In that respect waldo is a good choice if your then is going to take a while and doesn’t interact with the UI. Please note (again) that generally you should not use zalgo or waldo. The performance gains are neglible and we provide these functions only out of a misguided sense that library code should be as optimized as possible. If you use zalgo or waldo without tests proving their correctness you may unwillingly introduce horrendous, near-impossible-to-trace bugs. @see zalgo */ public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil) func contain_zalgo(q: dispatch_queue_t, block: () -> Void) { if q === zalgo { block() } else if q === waldo { if NSThread.isMainThread() { dispatch_async(dispatch_get_global_queue(0, 0), block) } else { block() } } else { dispatch_async(q, block) } } extension Promise { /** Creates a rejected Promise with `PMKErrorDomain` and a specified localizedDescription and error code. */ public convenience init(error: String, code: Int = PMKUnexpectedError) { let error = NSError(domain: "PMKErrorDomain", code: code, userInfo: [NSLocalizedDescriptionKey: error]) self.init(error) } /** Promise<Any> is more flexible, and often needed. However Swift won't cast <T> to <Any> directly. Once that is possible we will deprecate this function. */ public func asAny() -> Promise<Any> { return Promise<Any>(passthru: pipe) } /** Promise<AnyObject> is more flexible, and often needed. However Swift won't cast <T> to <AnyObject> directly. Once that is possible we will deprecate this function. */ public func asAnyObject() -> Promise<AnyObject> { return Promise<AnyObject>(passthru: pipe) } /** Swift (1.2) seems to be much less fussy about Void promises. */ public func asVoid() -> Promise<Void> { return then(on: zalgo) { _ in return } } } extension Promise: DebugPrintable { public var debugDescription: String { return "Promise: \(state)" } } /** Firstly can make chains more readable. Compare: NSURLConnection.GET(url1).then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } With: firstly { NSURLConnection.GET(url1) }.then { NSURLConnection.GET(url2) }.then { NSURLConnection.GET(url3) } */ public func firstly<T>(promise: () -> Promise<T>) -> Promise<T> { return promise() }
mit
0d866f88e648a5ab3ef450031952f4ba
31.1258
124
0.604301
4.472247
false
false
false
false
nathan-hekman/Stupefy
Stupefy/MainViewController.swift
1
5378
// // MainViewController.swift // Stupefy // // Created by Nathan Hekman on 10/22/16. // Copyright © 2016 NTH. All rights reserved. // import UIKit class MainViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var launchScreenView: UIView! var isEditingPhoto = false var originalImage: UIImage? var zoomedImage: UIImage? override var prefersStatusBarHidden: Bool { return true } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !isEditingPhoto { self.showCamera() } } func showCamera() { let croppingEnabled = false let cameraViewController = CameraViewController(croppingEnabled: croppingEnabled) { [weak self] zoomedImage,originalImage, asset in // Do something with your image here. // If cropping is enabled this image will be the cropped version self?.imageView.image = zoomedImage self?.originalImage = originalImage //self?.zoomedImage = zoomedImage self?.zoomedImage = self?.cropToBounds(image: zoomedImage!, width: Double(self!.view.frame.width), height: Double(self!.view.frame.height)) //compute stupefy zoom with originalImage self?.isEditingPhoto = true self?.dismiss(animated: false, completion: nil) } cameraViewController.closeButton.isHidden = true present(cameraViewController, animated: false, completion: {_ in self.launchScreenView.isHidden = true }) } func cropToBounds(image: UIImage, width: Double, height: Double) -> UIImage { let contextImage: UIImage = UIImage(cgImage: image.cgImage!) let contextSize: CGSize = contextImage.size var posX: CGFloat = 0.0 var posY: CGFloat = 0.0 var cgwidth: CGFloat = CGFloat(width) var cgheight: CGFloat = CGFloat(height) // // See what size is longer and create the center off of that // if contextSize.width > contextSize.height { // posX = ((contextSize.width - contextSize.height) / 2) // posY = 0 // cgwidth = contextSize.height // cgheight = contextSize.height // } else { // posX = 0 // posY = ((contextSize.height - contextSize.width) / 2) // cgwidth = contextSize.width // cgheight = contextSize.width // } let rect: CGRect = CGRect(x:posX, y:posY, width:cgwidth, height:cgheight) // Create bitmap image from context using the rect let imageRef: CGImage = contextImage.cgImage!.cropping(to: rect)! // Create a new image based on the imageRef and rotate back to the original orientation let image: UIImage = UIImage(cgImage: imageRef, scale: 20, orientation: image.imageOrientation) return image } @IBAction func saveTapped(_ sender: Any) { // image to share guard let zoomImage = self.zoomedImage, let original = self.originalImage else { return } // set up activity view controller let imageToShare = [zoomImage, original] let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil) activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // exclude some activity types from the list (optional) activityViewController.excludedActivityTypes = [] // present the view controller self.present(activityViewController, animated: true, completion: nil) //UIImageWriteToSavedPhotosAlbum(zoomImage, nil, nil, nil) } // @IBAction func messageTapped(_ sender: Any) { // // image to share // guard let zoomImage = self.zoomedImage, let original = self.originalImage else { // return // } // // // set up activity view controller // let imageToShare = [zoomImage, original] // let activityViewController = UIActivityViewController(activityItems: imageToShare, applicationActivities: nil) // activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash // // // exclude some activity types from the list (optional) // activityViewController.excludedActivityTypes = [] // // // present the view controller // self.present(activityViewController, animated: true, completion: nil) // } @IBAction func doneTapped(_ sender: Any) { self.isEditingPhoto = false if !isEditingPhoto { self.showCamera() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
5387fd5ae2bca7ac9585acc0cbda0d11
33.690323
151
0.616701
5.130725
false
false
false
false
andela-jejezie/FlutterwavePaymentManager
Rave/Rave/FWPresentation/FWPresentationController.swift
1
3480
// // FWPresentationController.swift // flutterwave // // Created by Johnson Ejezie on 10/12/2016. // Copyright © 2016 johnsonejezie. All rights reserved. // import UIKit class FWPresentationController: UIPresentationController { // MARK: - Properties fileprivate var dimmingView: UIView! override var frameOfPresentedViewInContainerView: CGRect { var frame: CGRect = .zero frame.size = size(forChildContentContainer: presentedViewController, withParentContainerSize: containerView!.bounds.size) frame.origin.y = (containerView!.frame.height - frame.size.height)/2.0 frame.origin.x = (containerView!.frame.width - frame.size.width)/2.0 return frame } // MARK: - Initializers override init(presentedViewController: UIViewController, presenting presentingViewController: UIViewController?) { super.init(presentedViewController: presentedViewController, presenting: presentingViewController) setupDimmingView() } override func presentationTransitionWillBegin() { containerView?.insertSubview(dimmingView, at: 0) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[dimmingView]|", options: [], metrics: nil, views: ["dimmingView": dimmingView])) guard let coordinator = presentedViewController.transitionCoordinator else { dimmingView.alpha = 1.0 return } coordinator.animate(alongsideTransition: { _ in self.dimmingView.alpha = 1.0 }) } override func dismissalTransitionWillBegin() { guard let coordinator = presentedViewController.transitionCoordinator else { dimmingView.alpha = 0.0 return } coordinator.animate(alongsideTransition: { _ in self.dimmingView.alpha = 0.0 }) } override func containerViewWillLayoutSubviews() { presentedView?.frame = frameOfPresentedViewInContainerView } override func size(forChildContentContainer container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { var width = parentSize.width*0.9 let height = parentSize.height*0.8 if UIDevice.current.userInterfaceIdiom == .pad { width = 380 } if UIDevice.current.orientation.isLandscape { return CGSize(width:width, height: height) } if width > 414 { width = 380 } return CGSize(width: width, height: height) } } // MARK: - Private private extension FWPresentationController { func setupDimmingView() { dimmingView = UIView() dimmingView.translatesAutoresizingMaskIntoConstraints = false dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) dimmingView.alpha = 0.0 let recognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(recognizer:))) dimmingView.addGestureRecognizer(recognizer) } dynamic func handleTap(recognizer: UITapGestureRecognizer) { presentingViewController.dismiss(animated: true) } }
mit
c26bd298ceeba2842105fa01c7e6e220
33.107843
170
0.653349
5.722039
false
false
false
false
Huralnyk/rxswift
Networking/Networking/ViewModel.swift
1
1743
// // ViewModel.swift // Networking // // Created by Scott Gardner on 6/6/16. // Copyright © 2016 Scott Gardner. All rights reserved. // import Foundation import RxSwift import RxCocoa class ViewModel { let searchText = Variable("") let disposeBag = DisposeBag() lazy var data: Driver<[Repository]> = { return self.searchText.asObservable() .throttle(0.3, scheduler: MainScheduler.instance) .distinctUntilChanged() .flatMapLatest { self.getRepositories(gitHubID: $0) }.asDriver(onErrorJustReturn: []) }() func getRepositories(gitHubID: String) -> Observable<[Repository]> { guard !gitHubID.isEmpty, let url = URL(string: "https://api.github.com/users/\(gitHubID)/repos") else { return Observable.just([]) } let request = URLRequest(url: url) return URLSession.shared.rx.json(request: request) .retry(3) // .catchErrorJustReturn([]) // .observeOn(ConcurrentDispatchQueueScheduler(qos: .background)) .map { var repositories: [Repository] = [] if let items = $0 as? [[String: AnyObject]] { items.forEach { guard let name = $0["name"] as? String, let url = $0["html_url"] as? String else { return } let repository = Repository(name: name, url: url) repositories.append(repository) } } return repositories } } }
mit
c86cfe79eaeea061179ab160bebee1ee
30.107143
90
0.505741
5.049275
false
false
false
false
huangboju/Moots
Examples/边缘侧滑/MagicMove-master/MagicMove/Transition/MagicMoveTransion.swift
1
2663
// // MagicMoveTransion.swift // MagicMove // // Created by BourneWeng on 15/7/13. // Copyright (c) 2015年 Bourne. All rights reserved. // import UIKit class MagicMoveTransion: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { //1.获取动画的源控制器和目标控制器 let fromVC = transitionContext.viewController(forKey: .from) as! ViewController let toVC = transitionContext.viewController(forKey: .to) as! DetailViewController let container = transitionContext.containerView //2.创建一个 Cell 中 imageView 的截图,并把 imageView 隐藏,造成使用户以为移动的就是 imageView 的假象 let snapshotView = fromVC.selectedCell.imageView.snapshotView(afterScreenUpdates: false) snapshotView?.frame = container.convert(fromVC.selectedCell.imageView.frame, from: fromVC.selectedCell) fromVC.selectedCell.imageView.isHidden = true //3.设置目标控制器的位置,并把透明度设为0,在后面的动画中慢慢显示出来变为1 toVC.view.frame = transitionContext.finalFrame(for: toVC) toVC.view.alpha = 0 //4.都添加到 container 中。注意顺序不能错了 container.addSubview(toVC.view) container.addSubview(snapshotView!) //5.执行动画 /* 这时avatarImageView.frame的值只是跟在IB中一样的, 如果换成屏幕尺寸不同的模拟器运行时avatarImageView会先移动到IB中的frame,动画结束后才会突然变成正确的frame。 所以需要在动画执行前执行一次toVC.avatarImageView.layoutIfNeeded() update一次frame */ toVC.avatarImageView.layoutIfNeeded() UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { () -> Void in snapshotView?.frame = toVC.avatarImageView.frame toVC.view.alpha = 1 }) { (finish: Bool) -> Void in fromVC.selectedCell.imageView.isHidden = false toVC.avatarImageView.image = toVC.image snapshotView?.removeFromSuperview() //一定要记得动画完成后执行此方法,让系统管理 navigation transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
mit
274a57df6f1951509c140d29d6214971
41.425926
146
0.683981
4.792887
false
false
false
false
ArtSabintsev/Freedom
Sources/DolphinFreedomActivity.swift
1
3467
// // DolphinFreedomActivity.swift // Freedom // // Created by Arthur Sabintsev on 7/8/17. // Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved. // import UIKit final class DolphinFreedomActivity: UIActivity, FreedomActivating { override class var activityCategory: UIActivity.Category { return .action } override var activityImage: UIImage? { return UIImage(named: "dolphin", in: Freedom.bundle, compatibleWith: nil) } override var activityTitle: String? { return "Open in Dolphin" } override var activityType: UIActivity.ActivityType? { guard let bundleID = Bundle.main.bundleIdentifier else { Freedom.printDebugMessage("Failed to fetch the bundleID.") return nil } let type = bundleID + "." + String(describing: DolphinFreedomActivity.self) return UIActivity.ActivityType(rawValue: type) } var activityDeepLink: String? = "dolphin://" var activityURL: URL? override func canPerform(withActivityItems activityItems: [Any]) -> Bool { for item in activityItems { guard let deepLinkURLString = activityDeepLink, let deepLinkURL = URL(string: deepLinkURLString), UIApplication.shared.canOpenURL(deepLinkURL) else { return false } guard let url = item as? URL else { continue } guard url.conformToHypertextProtocol() else { Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") return false } Freedom.printDebugMessage("The user has the Dolphin Web Browser installed.") return true } return false } override func prepare(withActivityItems activityItems: [Any]) { activityItems.forEach { item in guard let url = item as? URL, url.conformToHypertextProtocol() else { return Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") } activityURL = url return } } override func perform() { guard let activityURL = activityURL else { Freedom.printDebugMessage("activityURL is missing.") return activityDidFinish(false) } guard let deepLink = activityDeepLink, let formattedURL = activityURL.withoutScheme(), let url = URL(string: deepLink + formattedURL.absoluteString) else { return activityDidFinish(false) } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:]) { [weak self] opened in guard let strongSelf = self else { return } guard opened else { return strongSelf.activityDidFinish(false) } Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Dolphin Browser.") strongSelf.activityDidFinish(true) } } else { UIApplication.shared.openURL(url) Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Dolphin Browser.") activityDidFinish(true) } } }
mit
4729abd017fffc33e88c9b3695b3256d
32.326923
142
0.606174
5.44113
false
false
false
false
Bauer312/ProjectEuler
Sources/Multiples/Multiples.swift
1
2746
/* Copyright (c) 2016 Brian Bauer Licensed under the MIT License (MIT) - Please see License.txt in the top level of this repository for additional information. */ import Foundation public class Multiples { public init () { //Don't need to do anything... } // Create a complete set of numbers, all of which are: // Multiples of number // Below the maximum func multiple(_ number: Int, _ maximum: Int) -> Set<Int> { var result = Set<Int>() for i in 1..<maximum { if i % number == 0 { result.insert(i) } } return result } func setSum(_ setToSum: Set<Int>) -> Int { var sum: Int = 0 for i in setToSum { sum = sum + i } return sum } public func setGroups(components: Set<Int>, maximum: Int) -> Int { var masterSet = Set<Int>() for component in components { masterSet = masterSet.union(multiple(component, maximum)) } return setSum(masterSet) } public func smallestMultiple(_ multiples: [Int64]) -> Int64 { var num: Int64 = 1 var noRemainder: Bool = true while num < Int64.max { for i in multiples { if num % i != 0 { noRemainder = false break } } if noRemainder == true { return num } num = num + 1 noRemainder = true } return -1 } public func largestAdjacentProduct(_ numbers: [Int], digits: Int) -> [Int] { var result : [Int] = Array(repeating: 0, count: digits + 1) var index: Int = 0 while index < numbers.count - digits { var product: Int = 1 for iterator in 0..<digits { product = product * numbers[index + iterator] } if product > result[0] { result[0] = product for iterator in 1...digits { result[iterator] = numbers[index + iterator] } } index = index + 1 } return result } public func numberArrayFromFile(_ fileName: String) -> [Int] { var result : [Int] = Array<Int>() guard fileName.characters.count > 0 else { return result } do { #if os(Linux) let numberString = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8) #else let numberString = try String(contentsOfFile: fileName) #endif for digit in numberString.characters { if let value = Int(String(digit)) { result.append(value) } } } catch { print("Unable to read \(fileName)") return result } return result } public func isPythagoreanTriplet(a: Int, b: Int, c: Int) -> Bool { guard a < b && b < c else { return false } if a * a + b * b == c * c { return true } return false } }
mit
06c0f6122ebd5aa8a47ca124591b4659
21.883333
93
0.56992
3.917261
false
false
false
false
devincoughlin/swift
test/SILGen/property_wrappers.swift
1
19834
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -o %t -enable-library-evolution %S/Inputs/property_wrapper_defs.swift // RUN: %target-swift-emit-silgen -primary-file %s -I %t | %FileCheck %s import property_wrapper_defs @propertyWrapper struct Wrapper<T> { var wrappedValue: T init(value: T) { wrappedValue = value } } @propertyWrapper struct WrapperWithInitialValue<T> { var wrappedValue: T } protocol DefaultInit { init() } extension Int: DefaultInit { } struct HasMemberwiseInit<T: DefaultInit> { @Wrapper(value: false) var x: Bool @WrapperWithInitialValue var y: T = T() @WrapperWithInitialValue(wrappedValue: 17) var z: Int } func forceHasMemberwiseInit() { _ = HasMemberwiseInit(x: Wrapper(value: true), y: 17, z: WrapperWithInitialValue(wrappedValue: 42)) _ = HasMemberwiseInit<Int>(x: Wrapper(value: true)) _ = HasMemberwiseInit(y: 17) _ = HasMemberwiseInit<Int>(z: WrapperWithInitialValue(wrappedValue: 42)) _ = HasMemberwiseInit<Int>() } // CHECK: sil_global private @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}AA4LazyOySaySiGGvpZ : $Lazy<Array<Int>> // HasMemberwiseInit.x.setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1xSbvs : $@convention(method) <T where T : DefaultInit> (Bool, @inout HasMemberwiseInit<T>) -> () { // CHECK: bb0(%0 : $Bool, %1 : $*HasMemberwiseInit<T>): // CHECK: [[MODIFY_SELF:%.*]] = begin_access [modify] [unknown] %1 : $*HasMemberwiseInit<T> // CHECK: [[X_BACKING:%.*]] = struct_element_addr [[MODIFY_SELF]] : $*HasMemberwiseInit<T>, #HasMemberwiseInit._x // CHECK: [[X_BACKING_VALUE:%.*]] = struct_element_addr [[X_BACKING]] : $*Wrapper<Bool>, #Wrapper.wrappedValue // CHECK: assign %0 to [[X_BACKING_VALUE]] : $*Bool // CHECK: end_access [[MODIFY_SELF]] : $*HasMemberwiseInit<T> // variable initialization expression of HasMemberwiseInit._x // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}AA7WrapperVySbGvpfi : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> { // CHECK: integer_literal $Builtin.Int1, 0 // CHECK-NOT: return // CHECK: function_ref @$sSb22_builtinBooleanLiteralSbBi1__tcfC : $@convention(method) (Builtin.Int1, @thin Bool.Type) -> Bool // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers7WrapperV5valueACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin Wrapper<τ_0_0>.Type) -> @out Wrapper<τ_0_0> // user: %9 // CHECK: return {{%.*}} : $Wrapper<Bool> // variable initialization expression of HasMemberwiseInit.$y // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <T where T : DefaultInit> () -> @out // CHECK: bb0(%0 : $*T): // CHECK-NOT: return // CHECK: witness_method $T, #DefaultInit.init!allocator.1 : <Self where Self : DefaultInit> (Self.Type) -> () -> Self : $@convention(witness_method: DefaultInit) <τ_0_0 where τ_0_0 : DefaultInit> (@thick τ_0_0.Type) -> @out τ_0_0 // variable initialization expression of HasMemberwiseInit._z // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> { // CHECK: bb0: // CHECK-NOT: return // CHECK: integer_literal $Builtin.IntLiteral, 17 // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers23WrapperWithInitialValueV07wrappedF0ACyxGx_tcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin WrapperWithInitialValue<τ_0_0>.Type) -> @out WrapperWithInitialValue<τ_0_0> // default argument 0 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA_ : $@convention(thin) <T where T : DefaultInit> () -> Wrapper<Bool> // default argument 1 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA0_ : $@convention(thin) <T where T : DefaultInit> () -> @out T { // default argument 2 of HasMemberwiseInit.init(x:y:z:) // CHECK: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitV1x1y1zACyxGAA7WrapperVySbG_xAA0F16WithInitialValueVySiGtcfcfA1_ : $@convention(thin) <T where T : DefaultInit> () -> WrapperWithInitialValue<Int> { // HasMemberwiseInit.init() // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17HasMemberwiseInitVACyxGycfC : $@convention(method) <T where T : DefaultInit> (@thin HasMemberwiseInit<T>.Type) -> @out HasMemberwiseInit<T> { // Initialization of x // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_x33_{{.*}}7WrapperVySbGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> Wrapper<Bool> // Initialization of y // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_y33_{{.*}}23WrapperWithInitialValueVyxGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> @out τ_0_0 // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV1yxvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@in τ_0_0) -> @out WrapperWithInitialValue<τ_0_0> // Initialization of z // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers17HasMemberwiseInitV2_z33_{{.*}}23WrapperWithInitialValueVySiGvpfi : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> () -> WrapperWithInitialValue<Int> // CHECK: return // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers9HasNestedV2_y33_{{.*}}14PrivateWrapperAELLVyx_SayxGGvpfi : $@convention(thin) <T> () -> @owned Array<T> { // CHECK: bb0: // CHECK: function_ref @$ss27_allocateUninitializedArrayySayxG_BptBwlF struct HasNested<T> { @propertyWrapper private struct PrivateWrapper<U> { var wrappedValue: U } @PrivateWrapper private var y: [T] = [] static func blah(y: [T]) -> HasNested<T> { return HasNested<T>() } } // FIXME: For now, we are only checking that we don't crash. struct HasDefaultInit { @Wrapper(value: true) var x @WrapperWithInitialValue var y = 25 static func defaultInit() -> HasDefaultInit { return HasDefaultInit() } static func memberwiseInit(x: Bool, y: Int) -> HasDefaultInit { return HasDefaultInit(x: Wrapper(value: x), y: y) } } struct WrapperWithAccessors { @Wrapper var x: Int // Synthesized setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers20WrapperWithAccessorsV1xSivs : $@convention(method) (Int, @inout WrapperWithAccessors) -> () // CHECK-NOT: return // CHECK: struct_element_addr {{%.*}} : $*WrapperWithAccessors, #WrapperWithAccessors._x mutating func test() { x = 17 } } func consumeOldValue(_: Int) { } func consumeNewValue(_: Int) { } struct WrapperWithDidSetWillSet { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivs // CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivw // CHECK: struct_element_addr {{%.*}} : $*WrapperWithDidSetWillSet, #WrapperWithDidSetWillSet._x // CHECK-NEXT: struct_element_addr {{%.*}} : $*Wrapper<Int>, #Wrapper.wrappedValue // CHECK-NEXT: assign %0 to {{%.*}} : $*Int // CHECK: function_ref @$s17property_wrappers021WrapperWithDidSetWillF0V1xSivW @Wrapper var x: Int { didSet { consumeNewValue(oldValue) } willSet { consumeOldValue(newValue) } } mutating func test(x: Int) { self.x = x } } @propertyWrapper struct WrapperWithStorageValue<T> { var wrappedValue: T var projectedValue: Wrapper<T> { return Wrapper(value: wrappedValue) } } struct UseWrapperWithStorageValue { // UseWrapperWithStorageValue._x.getter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers26UseWrapperWithStorageValueV2$xAA0D0VySiGvg : $@convention(method) (UseWrapperWithStorageValue) -> Wrapper<Int> // CHECK-NOT: return // CHECK: function_ref @$s17property_wrappers23WrapperWithStorageValueV09projectedF0AA0C0VyxGvg @WrapperWithStorageValue(wrappedValue: 17) var x: Int } @propertyWrapper enum Lazy<Value> { case uninitialized(() -> Value) case initialized(Value) init(wrappedValue initialValue: @autoclosure @escaping () -> Value) { self = .uninitialized(initialValue) } var wrappedValue: Value { mutating get { switch self { case .uninitialized(let initializer): let value = initializer() self = .initialized(value) return value case .initialized(let value): return value } } set { self = .initialized(newValue) } } } struct UseLazy<T: DefaultInit> { @Lazy var foo = 17 @Lazy var bar = T() @Lazy var wibble = [1, 2, 3] // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers7UseLazyV3foo3bar6wibbleACyxGSi_xSaySiGtcfC : $@convention(method) <T where T : DefaultInit> (Int, @in T, @owned Array<Int>, @thin UseLazy<T>.Type) -> @out UseLazy<T> // CHECK: function_ref @$s17property_wrappers7UseLazyV3fooSivpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (Int) -> @owned Lazy<Int> // CHECK: function_ref @$s17property_wrappers7UseLazyV3barxvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@in τ_0_0) -> @out Lazy<τ_0_0> // CHECK: function_ref @$s17property_wrappers7UseLazyV6wibbleSaySiGvpfP : $@convention(thin) <τ_0_0 where τ_0_0 : DefaultInit> (@owned Array<Int>) -> @owned Lazy<Array<Int>> } struct X { } func triggerUseLazy() { _ = UseLazy<Int>() _ = UseLazy<Int>(foo: 17) _ = UseLazy(bar: 17) _ = UseLazy<Int>(wibble: [1, 2, 3]) } struct UseStatic { // CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvgZ // CHECK: sil private [global_init] [ossa] @$s17property_wrappers9UseStaticV13_staticWibble33_{{.*}}4LazyOySaySiGGvau // CHECK: sil hidden [ossa] @$s17property_wrappers9UseStaticV12staticWibbleSaySiGvsZ @Lazy static var staticWibble = [1, 2, 3] } extension WrapperWithInitialValue { func test() { } } class ClassUsingWrapper { @WrapperWithInitialValue var x = 0 } extension ClassUsingWrapper { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers17ClassUsingWrapperC04testcdE01cyAC_tF : $@convention(method) (@guaranteed ClassUsingWrapper, @guaranteed ClassUsingWrapper) -> () { func testClassUsingWrapper(c: ClassUsingWrapper) { // CHECK: ref_element_addr %1 : $ClassUsingWrapper, #ClassUsingWrapper._x self._x.test() } } // @propertyWrapper struct WrapperWithDefaultInit<T> { private var storage: T? init() { self.storage = nil } init(wrappedValue initialValue: T) { self.storage = initialValue } var wrappedValue: T { get { return storage! } set { storage = newValue } } } class UseWrapperWithDefaultInit { @WrapperWithDefaultInit var name: String } // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers25UseWrapperWithDefaultInitC5_name33_F728088E0028E14D18C6A10CF68512E8LLAA0defG0VySSGvpfi : $@convention(thin) () -> @owned WrapperWithDefaultInit<String> // CHECK: function_ref @$s17property_wrappers22WrapperWithDefaultInitVACyxGycfC // CHECK: return {{%.*}} : $WrapperWithDefaultInit<String> // Property wrapper composition. @propertyWrapper struct WrapperA<Value> { var wrappedValue: Value } @propertyWrapper struct WrapperB<Value> { var wrappedValue: Value } @propertyWrapper struct WrapperC<Value> { var wrappedValue: Value? } struct CompositionMembers { // CompositionMembers.p1.getter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p1SiSgvg : $@convention(method) (@guaranteed CompositionMembers) -> Optional<Int> // CHECK: bb0([[SELF:%.*]] : @guaranteed $CompositionMembers): // CHECK: [[P1:%.*]] = struct_extract [[SELF]] : $CompositionMembers, #CompositionMembers._p1 // CHECK: [[P1_VALUE:%.*]] = struct_extract [[P1]] : $WrapperA<WrapperB<WrapperC<Int>>>, #WrapperA.wrappedValue // CHECK: [[P1_VALUE2:%.*]] = struct_extract [[P1_VALUE]] : $WrapperB<WrapperC<Int>>, #WrapperB.wrappedValue // CHECK: [[P1_VALUE3:%.*]] = struct_extract [[P1_VALUE2]] : $WrapperC<Int>, #WrapperC.wrappedValue // CHECK: return [[P1_VALUE3]] : $Optional<Int> @WrapperA @WrapperB @WrapperC var p1: Int? @WrapperA @WrapperB @WrapperC var p2 = "Hello" // variable initialization expression of CompositionMembers.$p2 // CHECK-LABEL: sil hidden [transparent] [ossa] @$s17property_wrappers18CompositionMembersV3_p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi : $@convention(thin) () -> @owned Optional<String> { // CHECK: %0 = string_literal utf8 "Hello" // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers18CompositionMembersV2p12p2ACSiSg_SSSgtcfC : $@convention(method) (Optional<Int>, @owned Optional<String>, @thin CompositionMembers.Type) -> @owned CompositionMembers // CHECK: s17property_wrappers18CompositionMembersV3_p233_{{.*}}8WrapperAVyAA0N1BVyAA0N1CVySSGGGvpfi } func testComposition() { _ = CompositionMembers(p1: nil) } // Observers with non-default mutatingness. @propertyWrapper struct NonMutatingSet<T> { private var fixed: T var wrappedValue: T { get { fixed } nonmutating set { } } init(wrappedValue initialValue: T) { fixed = initialValue } } @propertyWrapper struct MutatingGet<T> { private var fixed: T var wrappedValue: T { mutating get { fixed } set { } } init(wrappedValue initialValue: T) { fixed = initialValue } } struct ObservingTest { // ObservingTest.text.setter // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers13ObservingTestV4textSSvs : $@convention(method) (@owned String, @guaranteed ObservingTest) -> () // CHECK: function_ref @$s17property_wrappers14NonMutatingSetV12wrappedValuexvg @NonMutatingSet var text: String = "" { didSet { } } @NonMutatingSet var integer: Int = 17 { willSet { } } @MutatingGet var text2: String = "" { didSet { } } @MutatingGet var integer2: Int = 17 { willSet { } } } // Tuple initial values. struct WithTuples { // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers10WithTuplesVACycfC : $@convention(method) (@thin WithTuples.Type) -> WithTuples { // CHECK: function_ref @$s17property_wrappers10WithTuplesV10_fractions33_F728088E0028E14D18C6A10CF68512E8LLAA07WrapperC12InitialValueVySd_S2dtGvpfi : $@convention(thin) () -> (Double, Double, Double) // CHECK: function_ref @$s17property_wrappers10WithTuplesV9fractionsSd_S2dtvpfP : $@convention(thin) (Double, Double, Double) -> WrapperWithInitialValue<(Double, Double, Double)> @WrapperWithInitialValue var fractions = (1.3, 0.7, 0.3) static func getDefault() -> WithTuples { return .init() } } // Resilience with DI of wrapperValue assignments. // rdar://problem/52467175 class TestResilientDI { @MyPublished var data: Int? = nil // CHECK: assign_by_wrapper {{%.*}} : $Optional<Int> to {{%.*}} : $*MyPublished<Optional<Int>>, init {{%.*}} : $@callee_guaranteed (Optional<Int>) -> @out MyPublished<Optional<Int>>, set {{%.*}} : $@callee_guaranteed (Optional<Int>) -> () func doSomething() { self.data = Int() } } @propertyWrapper public struct PublicWrapper<T> { public var wrappedValue: T public init(value: T) { wrappedValue = value } } @propertyWrapper public struct PublicWrapperWithStorageValue<T> { public var wrappedValue: T public init(wrappedValue: T) { self.wrappedValue = wrappedValue } public var projectedValue: PublicWrapper<T> { return PublicWrapper(value: wrappedValue) } } public class Container { public init() { } // The accessor cannot be serializable/transparent because it accesses an // internal var. // CHECK-LABEL: sil [ossa] @$s17property_wrappers9ContainerC10$dontCrashAA13PublicWrapperVySiGvg : $@convention(method) (@guaranteed Container) -> PublicWrapper<Int> { // CHECK: bb0(%0 : @guaranteed $Container): // CHECK: ref_element_addr %0 : $Container, #Container._dontCrash @PublicWrapperWithStorageValue(wrappedValue: 0) public var dontCrash : Int { willSet { } didSet { } } } // SR-11303 / rdar://problem/54311335 - crash due to wrong archetype used in generated SIL public protocol TestProtocol {} public class TestClass<T> { @WrapperWithInitialValue var value: T // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers9TestClassC5value8protocolACyxGx_qd__tcAA0C8ProtocolRd__lufc // CHECK: [[BACKING_INIT:%.*]] = function_ref @$s17property_wrappers9TestClassC5valuexvpfP : $@convention(thin) <τ_0_0> (@in τ_0_0) -> @out WrapperWithInitialValue<τ_0_0> // CHECK-NEXT: partial_apply [callee_guaranteed] [[BACKING_INIT]]<T>() init<U: TestProtocol>(value: T, protocol: U) { self.value = value } } // Composition with wrappedValue initializers that have default values. @propertyWrapper struct Outer<Value> { var wrappedValue: Value init(a: Int = 17, wrappedValue: Value, s: String = "hello") { self.wrappedValue = wrappedValue } } @propertyWrapper struct Inner<Value> { var wrappedValue: Value init(wrappedValue: @autoclosure @escaping () -> Value, d: Double = 3.14159) { self.wrappedValue = wrappedValue() } } struct ComposedInit { @Outer @Inner var value: Int // CHECK-LABEL: sil hidden [ossa] @$s17property_wrappers12ComposedInitV5valueSivpfP : $@convention(thin) (Int) -> Outer<Inner<Int>> { // CHECK: function_ref @$s17property_wrappers12ComposedInitV6_value33_F728088E0028E14D18C6A10CF68512E8LLAA5OuterVyAA5InnerVySiGGvpfiSiycfu_ // CHECK: function_ref @$s17property_wrappers5InnerV12wrappedValue1dACyxGxyXA_SdtcfcfA0_ // CHECK: function_ref @$s17property_wrappers5InnerV12wrappedValue1dACyxGxyXA_SdtcfC // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfcfA_ // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfcfA1_ // CHECK: function_ref @$s17property_wrappers5OuterV1a12wrappedValue1sACyxGSi_xSStcfC init() { self.value = 17 } } // rdar://problem/55982409 - crash due to improperly inferred 'final' @propertyWrapper public struct MyWrapper<T> { public var wrappedValue: T public var projectedValue: Self { self } public init(wrappedValue: T) { self.wrappedValue = wrappedValue } } open class TestMyWrapper { public init() {} @MyWrapper open var useMyWrapper: Int? = nil } // rdar://problem/54352235 - crash due to reference to private backing var extension UsesMyPublished { // CHECK-LABEL: sil hidden [ossa] @$s21property_wrapper_defs15UsesMyPublishedC0A9_wrappersE6setFooyySiF : $@convention(method) (Int, @guaranteed UsesMyPublished) -> () // CHECK: class_method %1 : $UsesMyPublished, #UsesMyPublished.foo!setter.1 // CHECK-NOT: assign_by_wrapper // CHECK: return func setFoo(_ x: Int) { foo = x } } // CHECK-LABEL: sil_vtable ClassUsingWrapper { // CHECK-NEXT: #ClassUsingWrapper.x!getter.1: (ClassUsingWrapper) -> () -> Int : @$s17property_wrappers17ClassUsingWrapperC1xSivg // ClassUsingWrapper.x.getter // CHECK-NEXT: #ClassUsingWrapper.x!setter.1: (ClassUsingWrapper) -> (Int) -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivs // ClassUsingWrapper.x.setter // CHECK-NEXT: #ClassUsingWrapper.x!modify.1: (ClassUsingWrapper) -> () -> () : @$s17property_wrappers17ClassUsingWrapperC1xSivM // ClassUsingWrapper.x.modify // CHECK-NEXT: #ClassUsingWrapper.init!allocator.1: (ClassUsingWrapper.Type) -> () -> ClassUsingWrapper : @$s17property_wrappers17ClassUsingWrapperCACycfC // CHECK-NEXT: #ClassUsingWrapper.deinit!deallocator.1: @$s17property_wrappers17ClassUsingWrapperCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable [serialized] TestMyWrapper // CHECK: #TestMyWrapper.$useMyWrapper!getter.1
apache-2.0
fc8c0fcf3f112cca17073e33a28a6871
36.288136
239
0.71904
3.609845
false
false
false
false
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/find/LGScanViewController.swift
1
7646
// // LGScanViewController.swift // LGScanViewController // // Created by jamy on 15/9/22. // Copyright © 2015年 jamy. All rights reserved. // import UIKit import AVFoundation class LGScanViewController: UIViewController , AVCaptureMetadataOutputObjectsDelegate{ let screenWidth = UIScreen.mainScreen().bounds.size.width let screenHeight = UIScreen.mainScreen().bounds.size.height let screenSize = UIScreen.mainScreen().bounds.size var traceNumber = 0 var upORdown = false var timer:NSTimer! var device : AVCaptureDevice! var input : AVCaptureDeviceInput! var output : AVCaptureMetadataOutput! var session: AVCaptureSession! var preView: AVCaptureVideoPreviewLayer! var line : UIImageView! // MARK: - init functions init() { super.init(nibName: nil, bundle: nil) hidesBottomBarWhenPushed = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.title = "二维码扫描" if !setupCamera() { return } setupScanLine() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) session.startRunning() timer = NSTimer(timeInterval: 0.02, target: self, selector: "scanLineAnimation", userInfo: nil, repeats: true) NSRunLoop.mainRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode) } override func viewWillDisappear(animated: Bool) { traceNumber = 0 upORdown = false session.stopRunning() timer.invalidate() timer = nil super.viewWillDisappear(animated) } func setupCamera() -> Bool { device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do { input = try AVCaptureDeviceInput(device: device) } catch let error as NSError { print(error.localizedDescription) return false } output = AVCaptureMetadataOutput() output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) output.rectOfInterest = makeScanReaderInterestRect() session = AVCaptureSession() session.sessionPreset = AVCaptureSessionPresetHigh if session.canAddInput(input) { session.addInput(input) } if session.canAddOutput(output) { session.addOutput(output) } output.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code] preView = AVCaptureVideoPreviewLayer(session: session) preView.videoGravity = AVLayerVideoGravityResizeAspectFill preView.frame = self.view.bounds let shadowView = makeScanCameraShadowView(makeScanReaderRect()) self.view.layer.insertSublayer(preView, atIndex: 0) self.view.addSubview(shadowView) return true } func setupScanLine() { let rect = makeScanReaderRect() var imageSize: CGFloat = 20.0 let imageX = rect.origin.x let imageY = rect.origin.y let width = rect.size.width let height = rect.size.height + 2 /// 四个边角 let imageViewTL = UIImageView(frame: CGRectMake(imageX, imageY, imageSize, imageSize)) imageViewTL.image = UIImage(named: "scan_tl") imageSize = (imageViewTL.image?.size.width)! self.view.addSubview(imageViewTL) let imageViewTR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY, imageSize, imageSize)) imageViewTR.image = UIImage(named: "scan_tr") self.view.addSubview(imageViewTR) let imageViewBL = UIImageView(frame: CGRectMake(imageX, imageY + height - imageSize, imageSize, imageSize)) imageViewBL.image = UIImage(named: "scan_bl") self.view.addSubview(imageViewBL) let imageViewBR = UIImageView(frame: CGRectMake(imageX + width - imageSize, imageY + height - imageSize, imageSize, imageSize)) imageViewBR.image = UIImage(named: "scan_br") self.view.addSubview(imageViewBR) line = UIImageView(frame: CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, 2)) line.image = UIImage(named: "scan_line") self.view.addSubview(line) } // MARK: Rect func makeScanReaderRect() -> CGRect { let scanSize = (min(screenWidth, screenHeight) * 3) / 5 var scanRect = CGRectMake(0, 0, scanSize, scanSize) scanRect.origin.x += (screenWidth / 2) - (scanRect.size.width / 2) scanRect.origin.y += (screenHeight / 2) - (scanRect.size.height / 2) return scanRect } func makeScanReaderInterestRect() -> CGRect { let rect = makeScanReaderRect() let x = rect.origin.x / screenWidth let y = rect.origin.y / screenHeight let width = rect.size.width / screenWidth let height = rect.size.height / screenHeight return CGRectMake(x, y, width, height) } func makeScanCameraShadowView(innerRect: CGRect) -> UIView { let referenceImage = UIImageView(frame: self.view.bounds) UIGraphicsBeginImageContext(referenceImage.frame.size) let context = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(context, 0, 0, 0, 0.5) var drawRect = CGRectMake(0, 0, screenWidth, screenHeight) CGContextFillRect(context, drawRect) drawRect = CGRectMake(innerRect.origin.x - referenceImage.frame.origin.x, innerRect.origin.y - referenceImage.frame.origin.y, innerRect.size.width, innerRect.size.height) CGContextClearRect(context, drawRect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() referenceImage.image = image return referenceImage } // MARK: 定时器 func scanLineAnimation() { let rect = makeScanReaderRect() let lineFrameX = rect.origin.x let lineFrameY = rect.origin.y let downHeight = rect.size.height if upORdown == false { traceNumber++ line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if CGFloat(2 * traceNumber) > downHeight - 2 { upORdown = true } } else { traceNumber-- line.frame = CGRectMake(lineFrameX, lineFrameY + CGFloat(2 * traceNumber), downHeight, 2) if traceNumber == 0 { upORdown = false } } } // MARK: AVCaptureMetadataOutputObjectsDelegate func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects.count == 0 { return } let metadata = metadataObjects[0] as! AVMetadataMachineReadableCodeObject let value = metadata.stringValue showScanCode(value) } // MARK: show result func showScanCode(code: String) { print("\(code)") } }
mit
25b4ec74ac6422560c72f2e0d7b0fefd
31.699571
178
0.62436
5.113423
false
false
false
false
qq456cvb/DeepLearningKitForiOS
iOSDeepLearningKitApp/iOSDeepLearningKitApp/iOSDeepLearningKitApp/ConvolutionLayer.swift
1
15316
// // ConvolutionLayer.swift // MemkiteMetal // // Created by Amund Tveit on 25/11/15. // Copyright © 2015 memkite. All rights reserved. // import Foundation import Metal func getDataFromBlob(_ blob: NSDictionary) -> ([Float], [Float]) { let shape = blob["shape"] as! NSDictionary let data = blob["data"] as! [Float] var FloatData = createFloatNumbersArray(data.count) for i in 0 ..< data.count { FloatData[i] = data[i] } return (shape["dim"] as! [Float], FloatData) } func createConvolutionLayerCached(_ layer: NSDictionary, inputBuffer: MTLBuffer, inputShape: [Float], metalCommandQueue: MTLCommandQueue, metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], blob_cache: inout [Dictionary<String,([Float],[Float])>], layer_number: Int, layer_string: String, caching_mode:Bool) -> (MTLBuffer, MTLCommandBuffer, [Float]) { _ = Date() // let metalCommandBuffer = metalCommandQueue.commandBuffer() let metalCommandBuffer = metalCommandQueue.makeCommandBufferWithUnretainedReferences() var convolution_params_dict:NSDictionary = NSDictionary() var pad:Float = 0.0 var kernel_size:Float = 1.0 var stride:Float = 1.0 var blobs:[NSDictionary] = [] var weights:[Float] = [] var weight_shape:[Float] = [] var bias_data:[Float] = [] var h:Float = 0.0 var w:Float = 0.0 var result_shape:[Float] = [] var outputCount:Int = 0 var input_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var weight_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var result_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var tensor_dimensions:[MetalTensorDimensions] = [] var col_dimensions:MetalTensorDimensions = MetalTensorDimensions(n: 0, channels: 0, width: 0, height:0) var col_output:[Float] = [] var convolution_params:MetalConvolutionParameters = MetalConvolutionParameters(pad:0, kernel_size: 0, stride: 0) if(!caching_mode) { print("NOTCACHINGMODE") convolution_params_dict = layer["convolution_param"] as! NSDictionary pad = 0.0 kernel_size = 1.0 stride = 1.0 if let val = convolution_params_dict["pad"] as? Float{ pad = val } else if convolution_params_dict["pad"] != nil { let val = (convolution_params_dict["pad"] as! [Float])[0] pad = val } if let val = convolution_params_dict["kernel_size"] as? Float{ kernel_size = val } else if convolution_params_dict["kernel_size"] != nil { let val = (convolution_params_dict["kernel_size"] as! [Float])[0] kernel_size = val } _ = Date() if let tmpval = blob_cache[layer_number]["0"] { (weight_shape, weights) = tmpval } else { blobs = layer["blobs"] as! [NSDictionary] (weight_shape, weights) = getDataFromBlob(blobs[0]) // print(weights) blob_cache[layer_number]["0"] = (weight_shape, weights) } // assert(weight_shape[2] == kernel_size) // assert(weight_shape[3] == kernel_size) blobs = layer["blobs"] as! [NSDictionary] (_, bias_data) = getDataFromBlob(blobs[1]) h = (inputShape[2] + 2 * pad - kernel_size) / stride + 1 w = (inputShape[3] + 2 * pad - kernel_size) / stride + 1 result_shape = [inputShape[0], weight_shape[0], h, w] outputCount = Int(result_shape.reduce(1, *)) // Create input and output vectors, and corresponding metal buffer input_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1], width: inputShape[2], height: inputShape[3]) weight_dimensions = MetalTensorDimensions(n: weight_shape[0], channels: weight_shape[1], width: weight_shape[2], height: weight_shape[3]) col_dimensions = MetalTensorDimensions(n: inputShape[0], channels: inputShape[1] * kernel_size * kernel_size, width: inputShape[2], height: inputShape[3]) result_dimensions = MetalTensorDimensions(n: result_shape[0], channels: result_shape[1], width: result_shape[2], height: result_shape[3]) tensor_dimensions = [input_dimensions, weight_dimensions, col_dimensions, result_dimensions] col_output = createFloatNumbersArray(Int(col_dimensions.n * col_dimensions.channels * col_dimensions.height * col_dimensions.width)) convolution_params = MetalConvolutionParameters(pad: pad, kernel_size: kernel_size, stride: stride) } // let resultBuffer = addConvolutionCommandToCommandBufferCached(metalCommandBuffer, inputBuffer: inputBuffer, im2ColCount: col_output.count, weights: weights, outputCount: outputCount, convolution_params: convolution_params, tensor_dimensions: tensor_dimensions, bias: bias_data, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, layer_number: layer_number,layer_string: layer_string, caching_mode: caching_mode) //metalCommandBuffer.commit() let resultBuffer = addFastConvolutionCommandToCommandBufferCached(metalCommandBuffer, inputBuffer: inputBuffer, weights: weights, outputCount: outputCount, convolution_params: convolution_params, tensor_dimensions: tensor_dimensions, bias: bias_data, metalDefaultLibrary: metalDefaultLibrary, metalDevice:metalDevice, layer_data_caches: &layer_data_caches, layer_number: layer_number,layer_string: layer_string, caching_mode: caching_mode) return (resultBuffer, metalCommandBuffer, result_shape) } func addFastConvolutionCommandToCommandBufferCached(_ commandBuffer: MTLCommandBuffer, inputBuffer: MTLBuffer, weights: [Float], outputCount: Int, convolution_params: MetalConvolutionParameters, tensor_dimensions: [MetalTensorDimensions], bias: [Float], metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], layer_number: Int, layer_string: String, caching_mode:Bool) -> MTLBuffer { _ = Date() print("before output and col_output") var output:[Float] = [] if(!caching_mode) { output = createFloatNumbersArray(outputCount) } print("before setupshaderinpipeline") let (_, fastCovComputePipelineState, _) = setupShaderInMetalPipeline("fast_convolution_layer", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) let resultMetalBuffer = createOrReuseFloatMetalBuffer("resultMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) print("after resultmetalbuffer") let weightMetalBuffer = createOrReuseFloatMetalBuffer("weightMetalBuffer", data: weights, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // let convolutionParamsMetalBuffer = createOrReuseConvolutionParametersMetalBuffer("convolutionParamsMetalBuffer", data: convolution_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let tensorDimensionsMetalBuffer = createOrReuseTensorDimensionsVectorMetalBuffer("tensorDimensionsMetalBuffer", data: tensor_dimensions, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let biasMetalBuffer = createOrReuseFloatMetalBuffer("bias", data: bias, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // Create Metal compute command encoder for im2col let metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() metalComputeCommandEncoder.setBuffer(resultMetalBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(weightMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, at: 3) metalComputeCommandEncoder.setBuffer(biasMetalBuffer, offset: 0, at: 4) //metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) metalComputeCommandEncoder.setComputePipelineState(fastCovComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ let threadsPerGroup = MTLSize(width:(fastCovComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup let numThreadgroups = MTLSize(width:(outputCount-1)/(fastCovComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) // Finalize configuration metalComputeCommandEncoder.endEncoding() return resultMetalBuffer } func addConvolutionCommandToCommandBufferCached(_ commandBuffer: MTLCommandBuffer, inputBuffer: MTLBuffer, im2ColCount: Int, weights: [Float], outputCount: Int, convolution_params: MetalConvolutionParameters, tensor_dimensions: [MetalTensorDimensions], bias: [Float], metalDefaultLibrary:MTLLibrary, metalDevice:MTLDevice, layer_data_caches: inout [Dictionary<String,MTLBuffer>], layer_number: Int, layer_string: String, caching_mode:Bool) -> MTLBuffer { _ = Date() print("before output and col_output") var output:[Float] = [] var col_output:[Float] = [] if(!caching_mode) { output = createFloatNumbersArray(outputCount) col_output = createFloatNumbersArray(im2ColCount) } print("before setupshaderinpipeline") let (_, im2colComputePipelineState, _) = setupShaderInMetalPipeline("im2col", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) let resultMetalBuffer = createOrReuseFloatMetalBuffer("resultMetalBuffer", data: output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) print("after resultmetalbuffer") let weightMetalBuffer = createOrReuseFloatMetalBuffer("weightMetalBuffer", data: weights, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) let convolutionParamsMetalBuffer = createOrReuseConvolutionParametersMetalBuffer("convolutionParamsMetalBuffer", data: convolution_params, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let tensorDimensionsMetalBuffer = createOrReuseTensorDimensionsVectorMetalBuffer("tensorDimensionsMetalBuffer", data: tensor_dimensions, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let colOutputMetalBuffer = createOrReuseFloatMetalBuffer("colOutputMetalBuffer", data: col_output, cache: &layer_data_caches, layer_number: layer_number, metalDevice: metalDevice) let biasMetalBuffer = createOrReuseFloatMetalBuffer("bias", data: bias, cache: &layer_data_caches, layer_number:layer_number, metalDevice: metalDevice) // Create Metal compute command encoder for im2col var metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() metalComputeCommandEncoder.setBuffer(inputBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(convolutionParamsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, at: 3) //metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(im2colComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ var threadsPerGroup = MTLSize(width:(im2colComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup print("before mtlsize 2") var numThreadgroups = MTLSize(width:(col_output.count-1)/(im2colComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) print("after dispatch") // Finalize configuration metalComputeCommandEncoder.endEncoding() let (_, convolutionComputePipelineState, _) = setupShaderInMetalPipeline("convolution_layer", metalDefaultLibrary: metalDefaultLibrary, metalDevice: metalDevice) metalComputeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Create Metal Compute Command Encoder and add input and output buffers to it metalComputeCommandEncoder.setBuffer(resultMetalBuffer, offset: 0, at: 0) metalComputeCommandEncoder.setBuffer(weightMetalBuffer, offset: 0, at: 1) metalComputeCommandEncoder.setBuffer(tensorDimensionsMetalBuffer, offset: 0, at: 2) metalComputeCommandEncoder.setBuffer(colOutputMetalBuffer, offset: 0, at: 3) metalComputeCommandEncoder.setBuffer(biasMetalBuffer, offset: 0, at: 4) // Set the shader function that Metal will use metalComputeCommandEncoder.setComputePipelineState(convolutionComputePipelineState!) // Set up thread groups on GPU // TODO: check out http://metalbyexample.com/introduction-to-compute/ threadsPerGroup = MTLSize(width:(convolutionComputePipelineState?.threadExecutionWidth)!,height:1,depth:1) // ensure at least 1 threadgroup numThreadgroups = MTLSize(width:(outputCount-1)/(convolutionComputePipelineState?.threadExecutionWidth)! + 1, height:1, depth:1) metalComputeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) // Finalize configuration metalComputeCommandEncoder.endEncoding() return resultMetalBuffer }
apache-2.0
70da67293dc0c61d85409f68c244759d
50.565657
476
0.669083
5.250257
false
false
false
false
hulinSun/MyRx
MyRx/Pods/Moya/Source/Response.swift
1
3082
import Foundation public final class Response: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: Data public let request: URLRequest? public let response: URLResponse? public init(statusCode: Int, data: Data, request: URLRequest? = nil, response: URLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } public var debugDescription: String { return description } public static func == (lhs: Response, rhs: Response) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.data == rhs.data && lhs.response == rhs.response } } public extension Response { /// Filters out responses that don't fall within the given range, generating errors when others are encountered. public func filter(statusCodes: ClosedRange<Int>) throws -> Response { guard statusCodes.contains(statusCode) else { throw Error.statusCode(self) } return self } public func filter(statusCode: Int) throws -> Response { return try filter(statusCodes: statusCode...statusCode) } public func filterSuccessfulStatusCodes() throws -> Response { return try filter(statusCodes: 200...299) } public func filterSuccessfulStatusAndRedirectCodes() throws -> Response { return try filter(statusCodes: 200...399) } /// Maps data received from the signal into a UIImage. func mapImage() throws -> Image { guard let image = Image(data: data) else { throw Error.imageMapping(self) } return image } /// Maps data received from the signal into a JSON object. func mapJSON(failsOnEmptyData: Bool = true) throws -> Any { do { return try JSONSerialization.jsonObject(with: data, options: .allowFragments) } catch { if data.count < 1 && !failsOnEmptyData { return NSNull() } throw Error.jsonMapping(self) } } /// Maps data received from the signal into a String. /// /// - parameter atKeyPath: Optional key path at which to parse string. public func mapString(atKeyPath keyPath: String? = nil) throws -> String { if let keyPath = keyPath { // Key path was provided, try to parse string at key path guard let jsonDictionary = try mapJSON() as? NSDictionary, let string = jsonDictionary.value(forKeyPath:keyPath) as? String else { throw Error.stringMapping(self) } return string } else { // Key path was not provided, parse entire response as string guard let string = String(data: data, encoding: .utf8) else { throw Error.stringMapping(self) } return string } } }
mit
c9caf3b4d6a580a9196555d948c7ebd2
32.5
116
0.615185
5.003247
false
false
false
false
zhenghao58/On-the-road
OnTheRoadB/CurrentTripViewController.swift
1
3675
// // ViewController.swift // OnTheRoadB // // Created by Cunqi.X on 14/10/24. // Copyright (c) 2014年 CS9033. All rights reserved. // import UIKit import CoreData class CurrentTripViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var tableView: UITableView! var selectedTrip:Trip! var detailArr : [TripDetail]! var fileHelper : FileHelper! var databaseHelper : DataBaseHelper! override func viewDidLoad() { super.viewDidLoad() fileHelper = FileHelper() databaseHelper = DataBaseHelper() self.title = selectedTrip.name fileHelper.setCurrentFolderPath(selectedTrip.name) refreshData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refreshData() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "addNewTripDetail") { let viewController = segue.destinationViewController as AddNewTripDetailViewController viewController.navigationItem.title = "Add New Day" viewController.currentTrip = self.selectedTrip viewController.currentDay = detailArr.count + 1 println(selectedTrip.masterDetail.count) } if(segue.identifier == "showEachDetail"){ let index = self.tableView.indexPathForSelectedRow()!.row let viewController = segue.destinationViewController as DetailTableViewController viewController.selectedTripDetail = self.detailArr[index] viewController.fileHelper = self.fileHelper viewController.navigationItem.title = detailArr[index].name } } /* The code below here are the simple code to show what I want the current trip screen looks like, we can use the first row as an indicator, and rest rows to show the records of current trip. change the row hight to make the first row and the rest rows diffierent. */ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return detailArr.count } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 198 } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete){ let data = detailArr[indexPath.row] databaseHelper.deleteData(data) refreshData() tableView.reloadData() } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tripDetails", forIndexPath: indexPath) as CardTableViewCell cell.useMember(detailArr[indexPath.row], fileHelper: fileHelper) return cell } func refreshData(){ detailArr = selectedTrip.masterDetail.allObjects as [TripDetail] detailArr.sort { (TripDetail A, TripDetail B) -> Bool in return A.name > B.name } tableView.reloadData() } }
mit
4db3a100ee99f835bd339951d9659093
30.663793
148
0.678464
5.346434
false
false
false
false
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/Extensions/NSFileManagerExtension.swift
1
20729
// // NSFileManagerExtension.swift // Pods // // Created by MacMini-2 on 13/09/17. // // import Foundation /// This extension adds some useful functions to NSFileManager public extension FileManager { // MARK: - Enums - static func createDirectory(at directoryURL: URL) throws { return try self.default.createDirectory(at: directoryURL) } func createDirectory(at directoryUrl: URL) throws { let fileManager = FileManager.default var isDir: ObjCBool = false let fileExists = fileManager.fileExists(atPath: directoryUrl.path, isDirectory: &isDir) if fileExists == false || isDir.boolValue != false { try fileManager.createDirectory(at: directoryUrl, withIntermediateDirectories: true, attributes: nil) } } static func removeTemporaryFiles(at path: String) throws { return try self.default.removeTemporaryFiles() } static var document: URL { return self.default.document } var document: URL { #if os(OSX) // On OS X it is, so put files in Application Support. If we aren't running // in a sandbox, put it in a subdirectory based on the bundle identifier // to avoid accidentally sharing files between applications var defaultURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first if ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil { var identifier = Bundle.main.bundleIdentifier if identifier?.length == 0 { identifier = Bundle.main.executableURL?.lastPathComponent } defaultURL = defaultURL?.appendingPathComponent(identifier ?? "", isDirectory: true) } return defaultURL ?? URL(fileURLWithPath: "") #else // On iOS the Documents directory isn't user-visible, so put files there return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] #endif } func removeTemporaryFiles() throws { let contents = try contentsOfDirectory(atPath: NSTemporaryDirectory()) for file in contents { try removeItem(atPath: NSTemporaryDirectory() + file) } } static func removeDocumentFiles(at path: String) throws { return try self.default.removeDocumentFiles() } func removeDocumentFiles() throws { let documentPath = document.path let contents = try contentsOfDirectory(atPath: documentPath) for file in contents { try removeItem(atPath: documentPath + file) } } /** Directory type enum - MainBundle: Main bundle directory - Library: Library directory - Documents: Documents directory - Cache: Cache directory */ enum DirectoryType : Int { case MainBundle case Library case Documents case Cache } // MARK: - Class functions - /** Read a file an returns the content as String - parameter file: File name - parameter ofType: File type - returns: Returns the content of the file a String */ static func readTextFile(file: String, ofType: String) throws -> String? { return try String(contentsOfFile: Bundle.main.path(forResource: file, ofType: ofType)!, encoding: String.Encoding.utf8) } /** Save a given array into a PLIST with the given filename - parameter directory: Path of the PLIST - parameter filename: PLIST filename - parameter array: Array to save into PLIST - returns: Returns true if the operation was successful, otherwise false */ static func saveArrayToPath(directory: DirectoryType, filename: String, array: Array<AnyObject>) -> Bool { var finalPath: String switch directory { case .MainBundle: finalPath = self.getBundlePathForFile(file: "\(filename).plist") case .Library: finalPath = self.getLibraryDirectoryForFile(file: "\(filename).plist") case .Documents: finalPath = self.getDocumentsDirectoryForFile(file: "\(filename).plist") case .Cache: finalPath = self.getCacheDirectoryForFile(file: "\(filename).plist") } return NSKeyedArchiver.archiveRootObject(array, toFile: finalPath) } /** Load array from a PLIST with the given filename - parameter directory: Path of the PLIST - parameter filename: PLIST filename - returns: Returns the loaded array */ static func loadArrayFromPath(directory: DirectoryType, filename: String) -> AnyObject? { var finalPath: String switch directory { case .MainBundle: finalPath = self.getBundlePathForFile(file: filename) case .Library: finalPath = self.getLibraryDirectoryForFile(file: filename) case .Documents: finalPath = self.getDocumentsDirectoryForFile(file: filename) case .Cache: finalPath = self.getCacheDirectoryForFile(file: filename) } return NSKeyedUnarchiver.unarchiveObject(withFile: finalPath) as AnyObject? } /** Get the Bundle path for a filename - parameter file: Filename - returns: Returns the path as a String */ static func getBundlePathForFile(file: String) -> String { let fileExtension = file.pathExtension var stringdata = "" do { stringdata = try Bundle.main.path(forResource: file.stringByReplacingWithRegex(regexString: String(format: ".%@", file) as NSString, withString: "") as String, ofType: fileExtension)! } catch _ { // Error handling } return stringdata } /** Get the Documents directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getDocumentsDirectoryForFile(file: String) -> String { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return documentsDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Get the Library directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getLibraryDirectoryForFile(file: String) -> String { let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] return libraryDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Get the Cache directory for a filename - parameter file: Filename - returns: Returns the directory as a String */ static func getCacheDirectoryForFile(file: String) -> String { let cacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] return cacheDirectory.stringByAppendingPathComponent(path: String(format: "%@/", file)) } /** Returns the size of the file - parameter file: Filename - parameter directory: Directory of the file - returns: Returns the file size */ static func fileSize(file: String, fromDirectory directory: DirectoryType) throws -> NSNumber? { if file.count != 0 { var path: String switch directory { case .MainBundle: path = self.getBundlePathForFile(file: file) case .Library: path = self.getLibraryDirectoryForFile(file: file) case .Documents: path = self.getDocumentsDirectoryForFile(file: file) case .Cache: path = self.getCacheDirectoryForFile(file: file) } if FileManager.default.fileExists(atPath: path) { let fileAttributes: NSDictionary? = try FileManager.default.attributesOfItem(atPath: file) as NSDictionary? if let _fileAttributes = fileAttributes { return NSNumber(value: _fileAttributes.fileSize()) } } } return nil } /** Delete a file with the given filename - parameter file: Filename to delete - parameter directory: Directory of the file - returns: Returns true if the operation was successful, otherwise false */ static func deleteFile(file: String, fromDirectory directory: DirectoryType) throws -> Bool { if file.count != 0 { var path: String switch directory { case .MainBundle: path = self.getBundlePathForFile(file: file) case .Library: path = self.getLibraryDirectoryForFile(file: file) case .Documents: path = self.getDocumentsDirectoryForFile(file: file) case .Cache: path = self.getCacheDirectoryForFile(file:file) } if FileManager.default.fileExists(atPath: path) { do { try FileManager.default.removeItem(atPath: path) return true } catch { return false } } } return false } /** Move a file from a directory to another - parameter file: Filename to move - parameter origin: Origin directory of the file - parameter destination: Destination directory of the file - parameter folderName: Folder name where to move the file. If folder not exist it will be created automatically - returns: Returns true if the operation was successful, otherwise false */ static func moveLocalFile(file: String, fromDirectory origin: DirectoryType, toDirectory destination: DirectoryType, withFolderName folderName: String? = nil) throws -> Bool { var originPath: String switch origin { case .MainBundle: originPath = self.getBundlePathForFile(file: file) case .Library: originPath = self.getLibraryDirectoryForFile(file: file) case .Documents: originPath = self.getDocumentsDirectoryForFile(file: file) case .Cache: originPath = self.getCacheDirectoryForFile(file: file) } var destinationPath: String = "" if folderName != nil { destinationPath = String(format: "%@/%@", destinationPath, folderName!) } else { destinationPath = file } switch destination { case .MainBundle: destinationPath = self.getBundlePathForFile(file: destinationPath) case .Library: destinationPath = self.getLibraryDirectoryForFile(file: destinationPath) case .Documents: destinationPath = self.getDocumentsDirectoryForFile(file: destinationPath) case .Cache: destinationPath = self.getCacheDirectoryForFile(file: destinationPath) } if folderName != nil { let folderPath: String = String(format: "%@/%@", destinationPath, folderName!) if !FileManager.default.fileExists(atPath: originPath) { try FileManager.default.createDirectory(atPath: folderPath, withIntermediateDirectories: false, attributes: nil) } } var copied: Bool = false, deleted: Bool = false if FileManager.default.fileExists(atPath: originPath) { do { try FileManager.default.copyItem(atPath: originPath, toPath: destinationPath) copied = true } catch { copied = false } } if destination != .MainBundle { if FileManager.default.fileExists(atPath: originPath) { do { try FileManager.default.removeItem(atPath: originPath) deleted = true } catch { deleted = false } } } if copied && deleted { return true } return false } /** Move a file from a directory to another - parameter file: Filename to move - parameter origin: Origin directory of the file - parameter destination: Destination directory of the file - returns: Returns true if the operation was successful, otherwise false */ static func moveLocalFile(file: String, fromDirectory origin: DirectoryType, toDirectory destination: DirectoryType) throws -> Bool { return try self.moveLocalFile(file: file, fromDirectory: origin, toDirectory: destination, withFolderName: nil) } /** Duplicate a file into another directory - parameter origin: Origin path - parameter destination: Destination path - returns: Returns true if the operation was successful, otherwise false */ static func duplicateFileAtPath(origin: String, toNewPath destination: String) -> Bool { if FileManager.default.fileExists(atPath: origin) { do { try FileManager.default.copyItem(atPath: origin, toPath: destination) return true } catch { return false } } return false } /** Rename a file with another filename - parameter origin: Origin path - parameter path: Subdirectory path - parameter oldName: Old filename - parameter newName: New filename - returns: Returns true if the operation was successful, otherwise false */ static func renameFileFromDirectory(origin: DirectoryType, atPath path: String, withOldName oldName: String, andNewName newName: String) -> Bool { var originPath: String switch origin { case .MainBundle: originPath = self.getBundlePathForFile(file: path) case .Library: originPath = self.getLibraryDirectoryForFile(file: path) case .Documents: originPath = self.getDocumentsDirectoryForFile(file: path) case .Cache: originPath = self.getCacheDirectoryForFile(file: path) } if FileManager.default.fileExists(atPath: originPath) { var newNamePath: String = "" do { newNamePath = try originPath.stringByReplacingWithRegex(regexString: oldName as NSString, withString: newName as NSString) as String try FileManager.default.copyItem(atPath: originPath, toPath: newNamePath) do { try FileManager.default.removeItem(atPath: originPath) return true } catch { return false } } catch { return false } } return false } /** Get the given settings for a given key - parameter settings: Settings filename - parameter objectForKey: Key to set the object - returns: Returns the object for the given key */ static func getSettings(settings: String, objectForKey: String) -> AnyObject? { var path: String = self.getLibraryDirectoryForFile(file: "") path = path.stringByAppendingPathExtension(ext: "/Preferences/")! path = path.stringByAppendingPathExtension(ext: "\(settings)-Settings.plist")! var loadedPlist: NSMutableDictionary if FileManager.default.fileExists(atPath: path) { loadedPlist = NSMutableDictionary(contentsOfFile: path)! } else { return nil } return loadedPlist.object(forKey: objectForKey) as AnyObject? } /** Set the given settings for a given object and key. The file will be saved in the Library directory - parameter settings: Settings filename - parameter object: Object to set - parameter objKey: Key to set the object - returns: Returns true if the operation was successful, otherwise false */ static func setSettings(settings: String, object: AnyObject, forKey objKey: String) -> Bool { var path: String = self.getLibraryDirectoryForFile(file: "") path = path.stringByAppendingPathExtension(ext: "/Preferences/")! path = path.stringByAppendingPathExtension(ext: "\(settings)-Settings.plist")! var loadedPlist: NSMutableDictionary if FileManager.default.fileExists(atPath: path) { loadedPlist = NSMutableDictionary(contentsOfFile: path)! } else { loadedPlist = NSMutableDictionary() } loadedPlist[objKey] = object return loadedPlist.write(toFile: path, atomically: true) } /** Set the App settings for a given object and key. The file will be saved in the Library directory - parameter object: Object to set - parameter objKey: Key to set the object - returns: Returns true if the operation was successful, otherwise false */ static func setAppSettingsForObject(object: AnyObject, forKey objKey: String) -> Bool { return self.setSettings(settings: App.name, object: object, forKey: objKey) } /** Get the App settings for a given key - parameter objKey: Key to get the object - returns: Returns the object for the given key */ static func getAppSettingsForObjectWithKey(objKey: String) -> AnyObject? { return self.getSettings(settings: App.name, objectForKey: objKey) } /** Get URL of Document directory. - returns: Document directory URL. */ class func ts_documentURL() -> URL { return ts_URLForDirectory(.documentDirectory)! } /** Get String of Document directory. - returns: Document directory String. */ class func ts_documentPath() -> String { return ts_pathForDirectory(.documentDirectory)! } /** Get URL of Library directory - returns: Library directory URL */ class func ts_libraryURL() -> URL { return ts_URLForDirectory(.libraryDirectory)! } /** Get String of Library directory - returns: Library directory String */ class func ts_libraryPath() -> String { return ts_pathForDirectory(.libraryDirectory)! } /** Get URL of Caches directory - returns: Caches directory URL */ class func ts_cachesURL() -> URL { return ts_URLForDirectory(.cachesDirectory)! } /** Get String of Caches directory - returns: Caches directory String */ class func ts_cachesPath() -> String { return ts_pathForDirectory(.cachesDirectory)! } /** Adds a special filesystem flag to a file to avoid iCloud backup it. - parameter filePath: Path to a file to set an attribute. */ class func ts_addSkipBackupAttributeToFile(_ filePath: String) { let url: URL = URL(fileURLWithPath: filePath) do { try (url as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey) } catch {} } /** Check available disk space in MB - returns: Double in MB */ class func ts_availableDiskSpaceMb() -> Double { let fileAttributes = try? `default`.attributesOfFileSystem(forPath: ts_documentPath()) if let fileSize = (fileAttributes![FileAttributeKey.systemSize] as AnyObject).doubleValue { return fileSize / Double(0x100000) } return 0 } fileprivate class func ts_URLForDirectory(_ directory: FileManager.SearchPathDirectory) -> URL? { return `default`.urls(for: directory, in: .userDomainMask).last } fileprivate class func ts_pathForDirectory(_ directory: FileManager.SearchPathDirectory) -> String? { return NSSearchPathForDirectoriesInDomains(directory, .userDomainMask, true)[0] } }
mit
7773135204ecb4038b0a563f125cb2af
33.548333
195
0.608085
5.605462
false
false
false
false
SmallElephant/FESwiftDemo
11-FMDBDemo/11-FMDBDemo/DataManager.swift
1
724
// // DataManager.swift // 11-FMDBDemo // // Created by keso on 2017/3/25. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class DataManager { static let shareIntance:DataManager = DataManager() var db:FMDatabase = FMDatabase() func createDataBase(dataName:String) { let path:String = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] let finalPath:String = path.appending("/\(dataName)") print("数据存储地址:\(finalPath)") db = FMDatabase(path: finalPath) if db.open() { print("数据库打开成功") } } }
mit
cfff0d1eccdbc2f6e6b00c061d15e98d
20.71875
106
0.588489
4.602649
false
false
false
false
aojet/Aojet
Sources/Aojet/actors/dispatch/queue/Queue.swift
1
351
// // Queue.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // class Queue<T>: Equatable { final let id: Int final var queue = Array<T>() var isLocked = false init(id: Int) { self.id = id } } func ==<T>(lhs: Queue<T>, rhs: Queue<T>) -> Bool { return lhs.id == rhs.id }
mit
6771b19ecf75b66b6c2f22260850673c
14.909091
52
0.582857
2.713178
false
false
false
false
gouyz/GYZBaking
baking/Classes/Home/View/GYZCategoryHeaderView.swift
1
1703
// // GYZCategoryHeaderView.swift // baking // 商品分类header // Created by gouyz on 2017/3/30. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZCategoryHeaderView: UITableViewHeaderFooterView { override init(reuseIdentifier: String?){ super.init(reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ bgView.backgroundColor = kBackgroundColor contentView.addSubview(bgView) bgView.addSubview(nameLab) bgView.addSubview(clearLab) bgView.snp.makeConstraints { (make) in make.edges.equalTo(0) } nameLab.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.top.bottom.equalTo(bgView) make.right.equalTo(clearLab.snp.left).offset(-kMargin) } clearLab.snp.makeConstraints { (make) in make.right.equalTo(-kMargin) make.top.bottom.equalTo(nameLab) make.width.equalTo(60) } } fileprivate lazy var bgView : UIView = UIView() /// 商品分类名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k13Font lab.textColor = kHeightGaryFontColor return lab }() /// lazy var clearLab : UILabel = { let lab = UILabel() lab.font = k15Font lab.textColor = kHeightGaryFontColor lab.text = "清空" lab.textAlignment = .right lab.isHidden = true return lab }() }
mit
e91ee4efd1495c55ba8115221d59fc42
25.1875
66
0.581146
4.505376
false
false
false
false
myhyazid/WordPress-iOS
WordPress/WordPressTest/PushAuthenticationManagerTests.swift
13
6488
import Foundation import XCTest import WordPress class PushAuthenticationManagerTests : XCTestCase { class MockUIAlertViewProxy : UIAlertViewProxy { var titlePassedIn:String? var messagePassedIn:String? var cancelButtonTitlePassedIn:String? var otherButtonTitlesPassedIn:[AnyObject]? var tapBlockPassedIn:UIAlertViewCompletionBlock? var showWithTitleCalled = false override func showWithTitle(title: String!, message: String!, cancelButtonTitle: String!, otherButtonTitles: [AnyObject]!, tapBlock: UIAlertViewCompletionBlock!) -> UIAlertView! { showWithTitleCalled = true titlePassedIn = title messagePassedIn = message cancelButtonTitlePassedIn = cancelButtonTitle otherButtonTitlesPassedIn = otherButtonTitles tapBlockPassedIn = tapBlock return UIAlertView() } } class MockPushAuthenticationService : PushAuthenticationService { var tokenPassedIn:String? var completionBlockPassedIn:((Bool) -> ())? var authorizedLoginCalled = false var numberOfTimesAuthorizedLoginCalled = 0 override func authorizeLogin(token: String, completion: ((Bool) -> ())) { authorizedLoginCalled = true numberOfTimesAuthorizedLoginCalled++ tokenPassedIn = token completionBlockPassedIn = completion } } var mockPushAuthenticationService = MockPushAuthenticationService(managedObjectContext: TestContextManager().mainContext) var mockAlertViewProxy = MockUIAlertViewProxy() var pushAuthenticationManager:PushAuthenticationManager? override func setUp() { super.setUp() pushAuthenticationManager = PushAuthenticationManager(pushAuthenticationService: mockPushAuthenticationService) pushAuthenticationManager?.alertViewProxy = mockAlertViewProxy; } func testIsPushAuthenticationNotificationReturnsTrueWhenPassedTheCorrectPushAuthenticationNoteType() { let result = pushAuthenticationManager!.isPushAuthenticationNotification(["type": "push_auth"]) XCTAssertTrue(result, "Should be true when the type is 'push_auth'") } func testIsPushAuthenticationNotificationReturnsFalseWhenPassedIncorrectPushAuthenticationNoteType() { let result = pushAuthenticationManager!.isPushAuthenticationNotification(["type": "not_push"]) XCTAssertFalse(result, "Should be false when the type is not 'push_auth'") } func expiredPushNotificationDictionary() -> NSDictionary { return ["expires": NSTimeInterval(3)] } func validPushAuthenticationDictionary() -> NSMutableDictionary { return ["push_auth_token" : "token", "aps" : [ "alert" : "an alert"]] } func testHandlePushAuthenticationNotificationShowsTheLoginExpiredAlertIfNotificationHasExpired(){ pushAuthenticationManager!.handlePushAuthenticationNotification(expiredPushNotificationDictionary()) XCTAssertTrue(mockAlertViewProxy.showWithTitleCalled, "Should show the login expired alert if the notification has expired") XCTAssertEqual(mockAlertViewProxy.titlePassedIn!, NSLocalizedString("Login Request Expired", comment:""), "") } func testHandlePushAuthenticationNotificationDoesNotShowTheLoginExpiredAlertIfNotificationHasNotExpired(){ pushAuthenticationManager!.handlePushAuthenticationNotification([:]) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login expired alert if the notification hasn't expired") } func testHandlePushAuthenticationNotificationWithBlankTokenDoesNotShowLoginVerificationAlert(){ var pushNotificationDictionary = validPushAuthenticationDictionary() pushNotificationDictionary.removeObjectForKey("push_auth_token") pushAuthenticationManager!.handlePushAuthenticationNotification(pushNotificationDictionary) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login verification") } func testHandlePushAuthenticationNotificationWithBlankMessageDoesNotShowLoginVerificationAlert(){ pushAuthenticationManager!.handlePushAuthenticationNotification(["push_auth_token" : "token"]) XCTAssertFalse(mockAlertViewProxy.showWithTitleCalled, "Should not show the login verification") } func testHandlePushAuthenticationNotificationWithValidDataShouldShowLoginVerification() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) XCTAssertTrue(mockAlertViewProxy.showWithTitleCalled, "Should show the login verification") XCTAssertEqual(mockAlertViewProxy.titlePassedIn!, NSLocalizedString("Verify Sign In", comment: ""), "") } func testHandlePushAuthenticationNotificationShouldAttemptToAuthorizeTheLoginIfTheUserIndicatesTheyWantTo() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, 1) XCTAssertTrue(mockPushAuthenticationService.authorizedLoginCalled, "Should have attempted to authorize the login") } func testHandlePushAuthenticationNotificationWhenAttemptingToLoginShouldAttemptToRetryTheLoginIfItFailed() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, 1) mockPushAuthenticationService.completionBlockPassedIn?(false) XCTAssertEqual(mockPushAuthenticationService.numberOfTimesAuthorizedLoginCalled, 2, "Should have attempted to retry a failed login") } func testHandlePushAuthenticationNotificationShouldNotAttemptToAuthorizeTheLoginIfTheUserIndicatesTheyDontWantTo() { pushAuthenticationManager!.handlePushAuthenticationNotification(validPushAuthenticationDictionary()) let alertView = UIAlertView() mockAlertViewProxy.tapBlockPassedIn?(alertView, alertView.cancelButtonIndex) XCTAssertFalse(mockPushAuthenticationService.authorizedLoginCalled, "Should not have attempted to authorize the login") } }
gpl-2.0
abb4f31078379ffa32583a34a2ad7f8f
48.151515
187
0.74738
7.232999
false
true
false
false
zhugejunwei/LeetCode
7. Reverse Integer.swift
1
778
import UIKit func reverse(x: Int) -> Int { var myX = x var myOutput:Double = 0 while ((myX > 9 || myX < -9) && myX % 10 == 0) { myX = myX / 10 } while myX != 0 { myOutput = myOutput * 10 + Double(myX % 10) myX = myX / 10 } if myOutput > Double(Int32.max) || myOutput < Double(Int32.min) { return 0 }else { return Int(myOutput) } } reverse(-12120) /* func reverse(x: Int) -> Int { var sign = 1 var mx = x if mx < 0 { sign = -1 mx *= -1 } while mx % 10 == 0 && mx != 0 { mx /= 10 } var rx = 0.0 var stop = 0 while stop == 0 { if mx < 10 { stop = 1 } rx = rx * 10 + Double(mx) % 10 mx /= 10 } if rx > Double(INT32_MAX) { return 0 }else { return Int(rx) * sign } } */
mit
3e9b06b0783a647cff061defd6503ecb
14.58
69
0.482005
2.870849
false
false
false
false
arttuperala/kmbmpdc
kmbmpdc/Preferences.swift
1
3859
import Cocoa class Preferences: NSViewController { @IBOutlet weak var hostField: NSTextField! @IBOutlet weak var portField: NSTextField! @IBOutlet weak var passwordField: NSSecureTextField! @IBOutlet weak var musicDirectoryPath: NSPathControl! @IBOutlet weak var notificationEnableButton: NSButton! var owner: AppDelegate? let defaults = UserDefaults.standard var mpdHost: String { get { return defaults.string(forKey: Constants.Preferences.mpdHost) ?? "" } set(stringValue) { defaults.set(stringValue, forKey: Constants.Preferences.mpdHost) } } var mpdPassword: String { get { return defaults.string(forKey: Constants.Preferences.mpdPass) ?? "" } set(stringValue) { if stringValue.isEmpty { defaults.set(nil, forKey: Constants.Preferences.mpdPass) } else { defaults.set(stringValue, forKey: Constants.Preferences.mpdPass) } } } var mpdPort: String { get { let port = defaults.integer(forKey: Constants.Preferences.mpdPort) if port > 0 { return String(port) } else { return "" } } set(stringValue) { if let port = Int(stringValue) { defaults.set(port, forKey: Constants.Preferences.mpdPort) } else { portField.stringValue = "" defaults.set(0, forKey: Constants.Preferences.mpdPort) } } } var musicDirectory: URL { get { if let url = defaults.url(forKey: Constants.Preferences.musicDirectory) { return url } else { return URL(fileURLWithPath: NSHomeDirectory()) } } set(url) { defaults.set(url, forKey: Constants.Preferences.musicDirectory) } } var notificationsDisabled: NSControl.StateValue { get { let disabled = defaults.bool(forKey: Constants.Preferences.notificationsDisabled) return disabled ? .off : .on } set(state) { let disabled = state == .off ? true : false defaults.set(disabled, forKey: Constants.Preferences.notificationsDisabled) } } override func viewDidLoad() { super.viewDidLoad() hostField.stringValue = mpdHost portField.stringValue = mpdPort passwordField.stringValue = mpdPassword musicDirectoryPath.url = musicDirectory notificationEnableButton.state = notificationsDisabled } override func viewWillDisappear() { mpdHost = hostField.stringValue mpdPort = portField.stringValue mpdPassword = passwordField.stringValue } override func viewDidDisappear() { super.viewDidDisappear() owner?.preferenceWindow = nil } @IBAction func changedHost(_ sender: NSTextField) { mpdHost = sender.stringValue } @IBAction func changedPassword(_ sender: NSTextField) { mpdPassword = sender.stringValue } @IBAction func changedPort(_ sender: NSTextField) { mpdPort = sender.stringValue } @IBAction func notificationsToggled(_ sender: NSButton) { notificationsDisabled = sender.state } @IBAction func openMusicDirectorySelector(_ sender: Any) { let panel = NSOpenPanel() panel.allowsMultipleSelection = false panel.canChooseDirectories = true panel.canChooseFiles = false panel.directoryURL = musicDirectoryPath.url let panelAction = panel.runModal() if panelAction == .OK { musicDirectoryPath.url = panel.url musicDirectory = panel.url! } } }
apache-2.0
5c79a4e40585ac75696b0e03261d43ce
29.385827
93
0.599896
5.097754
false
false
false
false
AnRanScheme/MagiRefresh
MagiRefresh/Classes/Extension/CALayer+MagiRefresh.swift
3
2983
// // CALayer+Magi.swift // magiLoadingPlaceHolder // // Created by 安然 on 2018/8/10. // Copyright © 2018年 anran. All rights reserved. // import UIKit extension CALayer { //frame.origin.x var magi_left: CGFloat { get { return self.frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } //frame.origin.y var magi_top: CGFloat { get { return self.frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } //frame.origin.x + frame.size.width var magi_right: CGFloat { get { return self.frame.origin.x + self.frame.size.width } set { var frame = self.frame frame.origin.x = newValue - frame.size.width self.frame = frame } } //frame.origin.y + frame.size.height var magi_bottom: CGFloat { get { return self.frame.origin.y + self.frame.size.height } set { var frame = self.frame frame.origin.y = newValue - frame.origin.y self.frame = frame } } //frame.size.width var magi_width: CGFloat { get { return self.frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } //frame.size.height var magi_height: CGFloat { get { return self.frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } //center.x var magi_positionX: CGFloat { get { return self.position.x } set { self.position = CGPoint(x: newValue, y: self.position.y) } } //center.y var magi_positionY: CGFloat { get { return self.position.y } set { self.position = CGPoint(x: self.position.x, y: newValue) } } //frame.origin var magi_origin: CGPoint { get { return self.frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } //frame.size var magi_size: CGSize { get { return self.frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } //maxX var magi_maxX: CGFloat { get { return self.frame.origin.x + self.frame.size.width } } //maxY var magi_maxY: CGFloat { get { return self.frame.origin.y + self.frame.size.height } } }
mit
752d01de9e66e11acd526ad7b107b164
19.811189
68
0.476815
4.144847
false
false
false
false
k-thorat/Dotzu
Framework/Dotzu/Dotzu/DotzuManager.swift
1
2077
// // Manager.swift // exampleWindow // // Created by Remi Robert on 02/12/2016. // Copyright © 2016 Remi Robert. All rights reserved. // import UIKit public class Dotzu: NSObject { public static let sharedManager = Dotzu() private var window: ManagerWindow? fileprivate var controller: ManagerViewController? private let cache = NSCache<AnyObject, AnyObject>() private let userDefault = UserDefaults.standard var displayedList = false func initLogsManager() { if LogsSettings.shared.resetLogsStart { let _ = StoreManager<Log>(store: .log).reset() let _ = StoreManager<LogRequest>(store: .network).reset() } } public func enable() { initLogsManager() if LogsSettings.shared.showBubbleHead { self.window = ManagerWindow(frame: UIScreen.main.bounds) self.controller = ManagerViewController() } self.window?.rootViewController = self.controller self.window?.makeKeyAndVisible() self.window?.delegate = self LoggerNetwork.shared.enable = LogsSettings.shared.network Logger.shared.enable = true LoggerCrash.shared.enable = true } public func disable() { self.window?.rootViewController = nil self.window?.resignKey() self.window?.removeFromSuperview() Logger.shared.enable = false LoggerCrash.shared.enable = false LoggerNetwork.shared.enable = false } public func addLogger(session: URLSessionConfiguration) { session.protocolClasses?.insert(LoggerNetwork.self, at: 0) } public func viewController () -> UIViewController? { let storyboard = UIStoryboard(name: "Manager", bundle: Bundle(for: ManagerViewController.self)) return storyboard.instantiateInitialViewController() } override init() { super.init() } } extension Dotzu: ManagerWindowDelegate { func isPointEvent(point: CGPoint) -> Bool { return self.controller?.shouldReceive(point: point) ?? false } }
mit
7ca2c90205df8f746989e11d1a5a35e7
28.657143
103
0.66185
4.665169
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/EtherClient/ENS/ENSRecord.swift
1
864
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift final class ENSRecord: Object { @objc dynamic var name: String = "" @objc dynamic var owner: String = "" @objc dynamic var resolver: String = "" @objc dynamic var address: String = "" @objc dynamic var ttl: Int = 0 @objc dynamic var updatedAt: Date = Date() @objc dynamic var isReverse: Bool = false convenience init(name: String, address: String, owner: String = "", resolver: String = "", isReverse: Bool = false, updatedAt: Date = Date()) { self.init() self.name = name self.owner = owner self.address = address self.resolver = resolver self.updatedAt = updatedAt self.isReverse = isReverse } override class func primaryKey() -> String? { return "name" } }
gpl-3.0
98516a0460796553d9f989afcf9550cb
27.8
147
0.62963
4.430769
false
false
false
false
conversant/conversant-ios-sdk
ConversantSDKSampleAppSwift/ConversantSDKSampleAppSwift/ViewController.swift
1
5134
// // ViewController.swift // ConversantSDKSampleAppSwift // // Created by Daniel Kanaan on 4/14/17. // Copyright © 2017 Daniel Kanaan. All rights reserved. // import UIKit import ConversantSDK class ViewController: UIViewController, ConversantInterstitialAdDelegate, ConversantBannerAdDelegate { @IBOutlet weak var feedbackTextView: UITextView! @IBOutlet weak var bannerButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func loadAd () { //Create an Interstitial Ad let interstitialAd = ConversantInterstitialAd(delegate: self) //Fetch the interstitial Ad interstitialAd.fetch() appendFeedback(text: "Fetching interstitial") } @IBAction func bannerAd(_ sender: UIButton) { ConversantConfiguration.defaultConfiguration.autoDisplay = false var adView:ConversantAdView! //Check if the ad already exists if let currentAd = view.viewWithTag(9) as? ConversantAdView { adView = currentAd if adView.isReady { adView.display() sender.setTitle("Fetch again", for: .normal) return } } else { //If there is no ad, create an ad adView = ConversantAdView(adFormat: .mobileBannerAd, delegate: self) //Add it to the view heirarchy view.addSubview(adView) //Give it a tag so we can get it later adView.tag = 9 } //Set the frame of the ad to center below the button let newFrame = CGRect(x:sender.frame.origin.x + (sender.frame.width / 2) - (ConversantAdFormat.mobileBannerAd.width / 2), y:sender.frame.origin.y + sender.frame.height + 5, width: ConversantAdFormat.mobileBannerAd.width, height: ConversantAdFormat.mobileBannerAd.height) adView.frame = newFrame //fetch the ad adView.fetch() appendFeedback(text: "Fetching banner") //set the button to new text sender.setTitle("Display", for: .normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Delegate function for successful load func interstitialAdLoadComplete(ad: ConversantInterstitialAd) { //Present the interstitial ad from this view controller ad.present(from: self) appendFeedback(text: "Interstitial Loaded") } //Delegate function for load failure. Here we will present an Alert func interstitialAdLoadFailed(ad: ConversantInterstitialAd, error: ConversantError) { //Create a message using the error.description property let alert = UIAlertController(title: "Failed", message: "Ad Load Failed with error: \(error.description)", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { (_) in alert.dismiss(animated: true, completion: nil) } alert.addAction(ok) present(alert, animated: true, completion: nil) } func bannerAdLoadComplete(ad: ConversantAdView) { appendFeedback(text: "Banner Loaded") if ad.isReady { ad.display() bannerButton.setTitle("Fetch again", for: .normal) } else { bannerButton.setTitle("Display", for:.normal) } } //Delegate function for banner load failure. Here we will present an Alert func bannerAdLoadFailed(ad: ConversantAdView, error: ConversantError) { //Create a message using the error.description property let alert = UIAlertController(title: "Failed", message: "Ad Load Failed with error: \(error.description)", preferredStyle: .alert) let ok = UIAlertAction(title: "OK", style: .default) { (_) in alert.dismiss(animated: true, completion: nil) } alert.addAction(ok) present(alert, animated: true, completion: nil) } //Other Delegate Functions func bannerAdWillPresentScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func bannerAdDidDismissScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func bannerAdWillDismissScreen(ad: ConversantAdView) { appendFeedback(text: "\(#function)") } func interstitialAdWillAppear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } func interstitialAdWillDisappear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } func interstitialAdDidDisappear(ad: ConversantInterstitialAd) { appendFeedback(text: "\(#function)") } //Helper functions func appendFeedback(text:String) { feedbackTextView.text = feedbackTextView.text + text + "\n" let bottom = feedbackTextView.contentSize.height - feedbackTextView.bounds.size.height feedbackTextView.setContentOffset(CGPoint(x: 0, y: bottom), animated: true) } }
apache-2.0
6ec5a819c1d1cb293279b517ea394d96
38.790698
278
0.654393
4.930836
false
false
false
false
IngmarStein/swift
stdlib/public/core/Mirror.swift
3
35536
//===--- Mirror.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME: ExistentialCollection needs to be supported before this will work // without the ObjC Runtime. /// Representation of the sub-structure and optional "display style" /// of any arbitrary subject instance. /// /// Describes the parts---such as stored properties, collection /// elements, tuple elements, or the active enumeration case---that /// make up a particular instance. May also supply a "display style" /// property that suggests how this structure might be rendered. /// /// Mirrors are used by playgrounds and the debugger. public struct Mirror { /// Representation of descendant classes that don't override /// `customMirror`. /// /// Note that the effect of this setting goes no deeper than the /// nearest descendant class that overrides `customMirror`, which /// in turn can determine representation of *its* descendants. internal enum _DefaultDescendantRepresentation { /// Generate a default mirror for descendant classes that don't /// override `customMirror`. /// /// This case is the default. case generated /// Suppress the representation of descendant classes that don't /// override `customMirror`. /// /// This option may be useful at the root of a class cluster, where /// implementation details of descendants should generally not be /// visible to clients. case suppressed } /// Representation of ancestor classes. /// /// A `CustomReflectable` class can control how its mirror will /// represent ancestor classes by initializing the mirror with a /// `AncestorRepresentation`. This setting has no effect on mirrors /// reflecting value type instances. public enum AncestorRepresentation { /// Generate a default mirror for all ancestor classes. /// /// This case is the default. /// /// - Note: This option generates default mirrors even for /// ancestor classes that may implement `CustomReflectable`'s /// `customMirror` requirement. To avoid dropping an ancestor class /// customization, an override of `customMirror` should pass /// `ancestorRepresentation: .Customized(super.customMirror)` when /// initializing its `Mirror`. case generated /// Use the nearest ancestor's implementation of `customMirror` to /// create a mirror for that ancestor. Other classes derived from /// such an ancestor are given a default mirror. /// /// The payload for this option should always be /// "`{ super.customMirror }`": /// /// var customMirror: Mirror { /// return Mirror( /// self, /// children: ["someProperty": self.someProperty], /// ancestorRepresentation: .Customized({ super.customMirror })) // <== /// } case customized(() -> Mirror) /// Suppress the representation of all ancestor classes. The /// resulting `Mirror`'s `superclassMirror` is `nil`. case suppressed } /// Reflect upon the given `subject`. /// /// If the dynamic type of `subject` conforms to `CustomReflectable`, /// the resulting mirror is determined by its `customMirror` property. /// Otherwise, the result is generated by the language. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if case let customized as CustomReflectable = subject { self = customized.customMirror } else { self = Mirror( legacy: _reflect(subject), subjectType: type(of: subject)) } } /// An element of the reflected instance's structure. The optional /// `label` may be used when appropriate, e.g. to represent the name /// of a stored property or of an active `enum` case, and will be /// used for lookup when `String`s are passed to the `descendant` /// method. public typealias Child = (label: String?, value: Any) /// The type used to represent sub-structure. /// /// Depending on your needs, you may find it useful to "upgrade" /// instances of this type to `AnyBidirectionalCollection` or /// `AnyRandomAccessCollection`. For example, to display the last /// 20 children of a mirror if they can be accessed efficiently, you /// might write: /// /// if let b = AnyBidirectionalCollection(someMirror.children) { /// var i = xs.index(b.endIndex, offsetBy: -20, /// limitedBy: b.startIndex) ?? b.startIndex /// while i != xs.endIndex { /// print(b[i]) /// b.formIndex(after: &i) /// } /// } public typealias Children = AnyCollection<Child> /// A suggestion of how a `Mirror`'s `subject` is to be interpreted. /// /// Playgrounds and the debugger will show a representation similar /// to the one used for instances of the kind indicated by the /// `DisplayStyle` case name when the `Mirror` is used for display. public enum DisplayStyle { case `struct`, `class`, `enum`, tuple, optional, collection case dictionary, `set` } static func _noSuperclassMirror() -> Mirror? { return nil } /// Returns the legacy mirror representing the part of `subject` /// corresponding to the superclass of `staticSubclass`. internal static func _legacyMirror( _ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? { // get a legacy mirror and the most-derived type var cls: AnyClass = type(of: subject) var clsMirror = _reflect(subject) // Walk up the chain of mirrors/classes until we find staticSubclass while let superclass: AnyClass = _getSuperclass(cls) { guard let superclassMirror = clsMirror._superMirror() else { break } if superclass == targetSuperclass { return superclassMirror } clsMirror = superclassMirror cls = superclass } return nil } internal static func _superclassIterator<Subject>( _ subject: Subject, _ ancestorRepresentation: AncestorRepresentation ) -> () -> Mirror? { if let subjectClass = Subject.self as? AnyClass, let superclass = _getSuperclass(subjectClass) { switch ancestorRepresentation { case .generated: return { self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map { Mirror(legacy: $0, subjectType: superclass) } } case .customized(let makeAncestor): return { Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass, ancestor: makeAncestor()) } case .suppressed: break } } return Mirror._noSuperclassMirror } /// Represent `subject` with structure described by `children`, /// using an optional `displayStyle`. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, children: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where C.Iterator.Element == Child, // FIXME(ABI)#47 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.Iterator.Element == Child, C.SubSequence.Index == C.Index, C.SubSequence.Indices : Collection, C.SubSequence.Indices.Iterator.Element == C.Index, C.SubSequence.Indices.Index == C.Index, C.SubSequence.Indices.SubSequence == C.SubSequence.Indices, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children(children) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with child values given by /// `unlabeledChildren`, using an optional `displayStyle`. The /// result's child labels will all be `nil`. /// /// This initializer is especially useful for the mirrors of /// collections, e.g.: /// /// extension MyArray : CustomReflectable { /// var customMirror: Mirror { /// return Mirror(self, unlabeledChildren: self, displayStyle: .collection) /// } /// } /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .Customized({ super.customMirror }) /// /// - Note: The traversal protocol modeled by `children`'s indices /// (`ForwardIndex`, `BidirectionalIndex`, or /// `RandomAccessIndex`) is captured so that the resulting /// `Mirror`'s `children` may be upgraded later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject, C : Collection>( _ subject: Subject, unlabeledChildren: C, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) where // FIXME(ABI)#48 (Associated Types with where clauses): these constraints should be applied to // associated types of Collection. C.SubSequence : Collection, C.SubSequence.SubSequence == C.SubSequence, C.Indices : Collection, C.Indices.Iterator.Element == C.Index, C.Indices.Index == C.Index, C.Indices.SubSequence == C.Indices { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) self.children = Children( unlabeledChildren.lazy.map { Child(label: nil, value: $0) } ) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// Represent `subject` with labeled structure described by /// `children`, using an optional `displayStyle`. /// /// Pass a dictionary literal with `String` keys as `children`. Be /// aware that although an *actual* `Dictionary` is /// arbitrarily-ordered, the ordering of the `Mirror`'s `children` /// will exactly match that of the literal you pass. /// /// If `subject` is not a class instance, `ancestorRepresentation` /// is ignored. Otherwise, `ancestorRepresentation` determines /// whether ancestor classes will be represented and whether their /// `customMirror` implementations will be used. By default, a /// representation is automatically generated and any `customMirror` /// implementation is bypassed. To prevent bypassing customized /// ancestors, `customMirror` overrides should initialize the /// `Mirror` with: /// /// ancestorRepresentation: .customized({ super.customMirror }) /// /// - Note: The resulting `Mirror`'s `children` may be upgraded to /// `AnyRandomAccessCollection` later. See the failable /// initializers of `AnyBidirectionalCollection` and /// `AnyRandomAccessCollection` for details. public init<Subject>( _ subject: Subject, children: DictionaryLiteral<String, Any>, displayStyle: DisplayStyle? = nil, ancestorRepresentation: AncestorRepresentation = .generated ) { self.subjectType = Subject.self self._makeSuperclassMirror = Mirror._superclassIterator( subject, ancestorRepresentation) let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) } self.children = Children(lazyChildren) self.displayStyle = displayStyle self._defaultDescendantRepresentation = subject is CustomLeafReflectable ? .suppressed : .generated } /// The static type of the subject being reflected. /// /// This type may differ from the subject's dynamic type when `self` /// is the `superclassMirror` of another mirror. public let subjectType: Any.Type /// A collection of `Child` elements describing the structure of the /// reflected subject. public let children: Children /// Suggests a display style for the reflected subject. public let displayStyle: DisplayStyle? public var superclassMirror: Mirror? { return _makeSuperclassMirror() } internal let _makeSuperclassMirror: () -> Mirror? internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation } /// A type that explicitly supplies its own mirror. /// /// You can create a mirror for any type using the `Mirror(reflect:)` /// initializer, but if you are not satisfied with the mirror supplied for /// your type by default, you can make it conform to `CustomReflectable` and /// return a custom `Mirror` instance. public protocol CustomReflectable { /// The custom mirror for this instance. /// /// If this type has value semantics, the mirror should be unaffected by /// subsequent mutations of the instance. var customMirror: Mirror { get } } /// A type that explicitly supplies its own mirror, but whose /// descendant classes are not represented in the mirror unless they /// also override `customMirror`. public protocol CustomLeafReflectable : CustomReflectable {} //===--- Addressing -------------------------------------------------------===// /// A protocol for legitimate arguments to `Mirror`'s `descendant` /// method. /// /// Do not declare new conformances to this protocol; they will not /// work as expected. // FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to // create conformances. public protocol MirrorPath {} extension IntMax : MirrorPath {} extension Int : MirrorPath {} extension String : MirrorPath {} extension Mirror { internal struct _Dummy : CustomReflectable { var mirror: Mirror var customMirror: Mirror { return mirror } } /// Return a specific descendant of the reflected subject, or `nil` /// Returns a specific descendant of the reflected subject, or `nil` /// if no such descendant exists. /// /// A `String` argument selects the first `Child` with a matching label. /// An integer argument *n* select the *n*th `Child`. For example: /// /// var d = Mirror(reflecting: x).descendant(1, "two", 3) /// /// is equivalent to: /// /// var d = nil /// let children = Mirror(reflecting: x).children /// if let p0 = children.index(children.startIndex, /// offsetBy: 1, limitedBy: children.endIndex) { /// let grandChildren = Mirror(reflecting: children[p0].value).children /// SeekTwo: for g in grandChildren { /// if g.label == "two" { /// let greatGrandChildren = Mirror(reflecting: g.value).children /// if let p1 = greatGrandChildren.index( /// greatGrandChildren.startIndex, /// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) { /// d = greatGrandChildren[p1].value /// } /// break SeekTwo /// } /// } /// } /// /// As you can see, complexity for each element of the argument list /// depends on the argument type and capabilities of the collection /// used to initialize the corresponding subject's parent's mirror. /// Each `String` argument results in a linear search. In short, /// this function is suitable for exploring the structure of a /// `Mirror` in a REPL or playground, but don't expect it to be /// efficient. public func descendant( _ first: MirrorPath, _ rest: MirrorPath... ) -> Any? { var result: Any = _Dummy(mirror: self) for e in [first] + rest { let children = Mirror(reflecting: result).children let position: Children.Index if case let label as String = e { position = children.index { $0.label == label } ?? children.endIndex } else if let offset = (e as? Int).map({ IntMax($0) }) ?? (e as? IntMax) { position = children.index(children.startIndex, offsetBy: offset, limitedBy: children.endIndex) ?? children.endIndex } else { _preconditionFailure( "Someone added a conformance to MirrorPath; that privilege is reserved to the standard library") } if position == children.endIndex { return nil } result = children[position].value } return result } } //===--- Legacy _Mirror Support -------------------------------------------===// extension Mirror.DisplayStyle { /// Construct from a legacy `_MirrorDisposition` internal init?(legacy: _MirrorDisposition) { switch legacy { case .`struct`: self = .`struct` case .`class`: self = .`class` case .`enum`: self = .`enum` case .tuple: self = .tuple case .aggregate: return nil case .indexContainer: self = .collection case .keyContainer: self = .dictionary case .membershipContainer: self = .`set` case .container: preconditionFailure("unused!") case .optional: self = .optional case .objCObject: self = .`class` } } } internal func _isClassSuperMirror(_ t: Any.Type) -> Bool { #if _runtime(_ObjC) return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self #else return t == _ClassSuperMirror.self #endif } extension _Mirror { internal func _superMirror() -> _Mirror? { if self.count > 0 { let childMirror = self[0].1 if _isClassSuperMirror(type(of: childMirror)) { return childMirror } } return nil } } /// When constructed using the legacy reflection infrastructure, the /// resulting `Mirror`'s `children` collection will always be /// upgradable to `AnyRandomAccessCollection` even if it doesn't /// exhibit appropriate performance. To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal extension Mirror { /// An adapter that represents a legacy `_Mirror`'s children as /// a `Collection` with integer `Index`. Note that the performance /// characteristics of the underlying `_Mirror` may not be /// appropriate for random access! To avoid this pitfall, convert /// mirrors to use the new style, which only present forward /// traversal in general. internal struct LegacyChildren : RandomAccessCollection { typealias Indices = CountableRange<Int> init(_ oldMirror: _Mirror) { self._oldMirror = oldMirror } var startIndex: Int { return _oldMirror._superMirror() == nil ? 0 : 1 } var endIndex: Int { return _oldMirror.count } subscript(position: Int) -> Child { let (label, childMirror) = _oldMirror[position] return (label: label, value: childMirror.value) } internal let _oldMirror: _Mirror } /// Initialize for a view of `subject` as `subjectClass`. /// /// - parameter ancestor: A Mirror for a (non-strict) ancestor of /// `subjectClass`, to be injected into the resulting hierarchy. /// /// - parameter legacy: Either `nil`, or a legacy mirror for `subject` /// as `subjectClass`. internal init( _ subject: AnyObject, subjectClass: AnyClass, ancestor: Mirror, legacy legacyMirror: _Mirror? = nil ) { if ancestor.subjectType == subjectClass || ancestor._defaultDescendantRepresentation == .suppressed { self = ancestor } else { let legacyMirror = legacyMirror ?? Mirror._legacyMirror( subject, asClass: subjectClass)! self = Mirror( legacy: legacyMirror, subjectType: subjectClass, makeSuperclassMirror: { _getSuperclass(subjectClass).map { Mirror( subject, subjectClass: $0, ancestor: ancestor, legacy: legacyMirror._superMirror()) } }) } } internal init( legacy legacyMirror: _Mirror, subjectType: Any.Type, makeSuperclassMirror: (() -> Mirror?)? = nil ) { if let makeSuperclassMirror = makeSuperclassMirror { self._makeSuperclassMirror = makeSuperclassMirror } else if let subjectSuperclass = _getSuperclass(subjectType) { self._makeSuperclassMirror = { legacyMirror._superMirror().map { Mirror(legacy: $0, subjectType: subjectSuperclass) } } } else { self._makeSuperclassMirror = Mirror._noSuperclassMirror } self.subjectType = subjectType self.children = Children(LegacyChildren(legacyMirror)) self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition) self._defaultDescendantRepresentation = .generated } } //===--- QuickLooks -------------------------------------------------------===// /// The sum of types that can be used as a Quick Look representation. public enum PlaygroundQuickLook { /// Plain text. case text(String) /// An integer numeric value. case int(Int64) /// An unsigned integer numeric value. case uInt(UInt64) /// A single precision floating-point numeric value. case float(Float32) /// A double precision floating-point numeric value. case double(Float64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An image. case image(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A sound. case sound(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A color. case color(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A bezier path. case bezierPath(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// An attributed string. case attributedString(Any) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A rectangle. case rectangle(Float64, Float64, Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A point. case point(Float64, Float64) // FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type. /// A size. case size(Float64, Float64) /// A boolean value. case bool(Bool) // FIXME: Uses explicit values to avoid coupling a particular Cocoa type. /// A range. case range(Int64, Int64) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A GUI view. case view(Any) // FIXME: Uses an Any to avoid coupling a particular Cocoa type. /// A graphical sprite. case sprite(Any) /// A Uniform Resource Locator. case url(String) /// Raw data that has already been encoded in a format the IDE understands. case _raw([UInt8], String) } extension PlaygroundQuickLook { /// Initialize for the given `subject`. /// /// If the dynamic type of `subject` conforms to /// `CustomPlaygroundQuickLookable`, returns the result of calling /// its `customPlaygroundQuickLook` property. Otherwise, returns /// a `PlaygroundQuickLook` synthesized for `subject` by the /// language. Note that in some cases the result may be /// `.Text(String(reflecting: subject))`. /// /// - Note: If the dynamic type of `subject` has value semantics, /// subsequent mutations of `subject` will not observable in /// `Mirror`. In general, though, the observability of such /// mutations is unspecified. public init(reflecting subject: Any) { if let customized = subject as? CustomPlaygroundQuickLookable { self = customized.customPlaygroundQuickLook } else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable { self = customized._defaultCustomPlaygroundQuickLook } else { if let q = _reflect(subject).quickLookObject { self = q } else { self = .text(String(reflecting: subject)) } } } } /// A type that explicitly supplies its own playground Quick Look. /// /// A Quick Look can be created for an instance of any type by using the /// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied /// with the representation supplied for your type by default, you can make it /// conform to the `CustomPlaygroundQuickLookable` protocol and provide a /// custom `PlaygroundQuickLook` instance. public protocol CustomPlaygroundQuickLookable { /// A custom playground Quick Look for this instance. /// /// If this type has value semantics, the `PlaygroundQuickLook` instance /// should be unaffected by subsequent mutations. var customPlaygroundQuickLook: PlaygroundQuickLook { get } } // A workaround for <rdar://problem/26182650> // FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib. public protocol _DefaultCustomPlaygroundQuickLookable { var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get } } //===--- General Utilities ------------------------------------------------===// // This component could stand alone, but is used in Mirror's public interface. /// A lightweight collection of key-value pairs. /// /// Use a `DictionaryLiteral` instance when you need an ordered collection of /// key-value pairs and don't require the fast key lookup that the /// `Dictionary` type provides. Unlike key-value pairs in a true dictionary, /// neither the key nor the value of a `DictionaryLiteral` instance must /// conform to the `Hashable` protocol. /// /// You initialize a `DictionaryLiteral` instance using a Swift dictionary /// literal. Besides maintaining the order of the original dictionary literal, /// `DictionaryLiteral` also allows duplicates keys. For example: /// /// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49, /// "Evelyn Ashford": 10.76, /// "Evelyn Ashford": 10.79, /// "Marlies Gohr": 10.81] /// print(recordTimes.first!) /// // Prints "("Florence Griffith-Joyner", 10.49)" /// /// Some operations that are efficient on a dictionary are slower when using /// `DictionaryLiteral`. In particular, to find the value matching a key, you /// must search through every element of the collection. The call to /// `index(where:)` in the following example must traverse the whole /// collection to make sure that no element matches the given predicate: /// /// let runner = "Marlies Gohr" /// if let index = recordTimes.index(where: { $0.0 == runner }) { /// let time = recordTimes[index].1 /// print("\(runner) set a 100m record of \(time) seconds.") /// } else { /// print("\(runner) couldn't be found in the records.") /// } /// // Prints "Marlies Gohr set a 100m record of 10.81 seconds." /// /// Dictionary Literals as Function Parameters /// ------------------------------------------ /// /// When calling a function with a `DictionaryLiteral` parameter, you can pass /// a Swift dictionary literal without causing a `Dictionary` to be created. /// This capability can be especially important when the order of elements in /// the literal is significant. /// /// For example, you could create an `IntPairs` structure that holds a list of /// two-integer tuples and use an initializer that accepts a /// `DictionaryLiteral` instance. /// /// struct IntPairs { /// var elements: [(Int, Int)] /// /// init(_ elements: DictionaryLiteral<Int, Int>) { /// self.elements = Array(elements) /// } /// } /// /// When you're ready to create a new `IntPairs` instance, use a dictionary /// literal as the parameter to the `IntPairs` initializer. The /// `DictionaryLiteral` instance preserves the order of the elements as /// passed. /// /// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1]) /// print(pairs.elements) /// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]" public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral { /// Creates a new `DictionaryLiteral` instance from the given dictionary /// literal. /// /// The order of the key-value pairs is kept intact in the resulting /// `DictionaryLiteral` instance. public init(dictionaryLiteral elements: (Key, Value)...) { self._elements = elements } internal let _elements: [(Key, Value)] } /// `Collection` conformance that allows `DictionaryLiteral` to /// interoperate with the rest of the standard library. extension DictionaryLiteral : RandomAccessCollection { public typealias Indices = CountableRange<Int> /// The position of the first element in a nonempty collection. /// /// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to /// `endIndex`. public var startIndex: Int { return 0 } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to /// `startIndex`. public var endIndex: Int { return _elements.endIndex } // FIXME: a typealias is needed to prevent <rdar://20248032> /// The element type of a `DictionaryLiteral`: a tuple containing an /// individual key-value pair. public typealias Element = (key: Key, value: Value) /// Accesses the element at the specified position. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. /// - Returns: The key-value pair at position `position`. public subscript(position: Int) -> Element { return _elements[position] } } extension String { /// Creates a string representing the given value. /// /// Use this initializer to convert an instance of any type to its preferred /// representation as a `String` instance. The initializer creates the /// string representation of `instance` in one of the following ways, /// depending on its protocol conformance: /// /// - If `instance` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `instance.write(to: s)` on an empty /// string `s`. /// - If `instance` conforms to the `CustomStringConvertible` protocol, the /// result is `instance.description`. /// - If `instance` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `instance.debugDescription`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(describing: p)) /// // Prints "Point(x: 21, y: 30)" /// /// After adding `CustomStringConvertible` conformance by implementing the /// `description` property, `Point` provides its own custom representation. /// /// extension Point: CustomStringConvertible { /// var description: String { /// return "(\(x), \(y))" /// } /// } /// /// print(String(describing: p)) /// // Prints "(21, 30)" /// /// - SeeAlso: `String.init<Subject>(reflecting: Subject)` public init<Subject>(describing instance: Subject) { self.init() _print_unlocked(instance, &self) } /// Creates a string with a detailed representation of the given value, /// suitable for debugging. /// /// Use this initializer to convert an instance of any type to its custom /// debugging representation. The initializer creates the string /// representation of `instance` in one of the following ways, depending on /// its protocol conformance: /// /// - If `subject` conforms to the `CustomDebugStringConvertible` protocol, /// the result is `subject.debugDescription`. /// - If `subject` conforms to the `CustomStringConvertible` protocol, the /// result is `subject.description`. /// - If `subject` conforms to the `TextOutputStreamable` protocol, the /// result is obtained by calling `subject.write(to: s)` on an empty /// string `s`. /// - An unspecified result is supplied automatically by the Swift standard /// library. /// /// For example, this custom `Point` struct uses the default representation /// supplied by the standard library. /// /// struct Point { /// let x: Int, y: Int /// } /// /// let p = Point(x: 21, y: 30) /// print(String(reflecting: p)) /// // Prints "p: Point = { /// // x = 21 /// // y = 30 /// // }" /// /// After adding `CustomDebugStringConvertible` conformance by implementing /// the `debugDescription` property, `Point` provides its own custom /// debugging representation. /// /// extension Point: CustomDebugStringConvertible { /// var debugDescription: String { /// return "Point(x: \(x), y: \(y))" /// } /// } /// /// print(String(reflecting: p)) /// // Prints "Point(x: 21, y: 30)" /// /// - SeeAlso: `String.init<Subject>(Subject)` public init<Subject>(reflecting subject: Subject) { self.init() _debugPrint_unlocked(subject, &self) } } /// Reflection for `Mirror` itself. extension Mirror : CustomStringConvertible { public var description: String { return "Mirror for \(self.subjectType)" } } extension Mirror : CustomReflectable { public var customMirror: Mirror { return Mirror(self, children: [:]) } } @available(*, unavailable, renamed: "MirrorPath") public typealias MirrorPathType = MirrorPath
apache-2.0
5b082f2647b9f59567404c99f31ae12b
36.485232
106
0.663046
4.689364
false
false
false
false
wwq0327/iOS9Example
DemoLists/DemoLists/BackTextViewController.swift
1
1546
// // BackTextViewController.swift // DemoLists // // Created by wyatt on 15/12/19. // Copyright © 2015年 Wanqing Wang. All rights reserved. // import UIKit class BackTextViewController: UIViewController { @IBOutlet weak var textLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() addBackgroundColorToText() } func addBackgroundColorToText() { let style = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle style.firstLineHeadIndent = 10.0 style.headIndent = 10 style.tailIndent = 0 style.lineSpacing = 20.0 let attributes = [NSParagraphStyleAttributeName: style] textLabel.attributedText = NSAttributedString(string: textLabel.text!, attributes: attributes) let textbackgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.6) textLabel.backgroundColor = textbackgroundColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
a8eeded905cd4512acb0a19b3290b3ef
28.113208
109
0.666235
5.3391
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/UploadItemAsset.swift
1
1739
// // UploadItemAsset.swift // MT_iOS // // Created by CHEEBOW on 2016/02/08. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit class UploadItemAsset: UploadItemImage { private(set) var asset: PHAsset! init(asset: PHAsset) { super.init() self.asset = asset } override func setup(completion: (() -> Void)) { let manager = PHImageManager.defaultManager() manager.requestImageDataForAsset(self.asset, options: nil, resultHandler: {(imageData: NSData?, dataUTI: String?, orientation: UIImageOrientation, info: [NSObject : AnyObject]?) in if let data = imageData { if let image = UIImage(data: data) { let jpeg = Utils.convertJpegData(image, width: self.width, quality: self.quality) self.data = jpeg completion() } } else { completion() } } ) } override func thumbnail(size: CGSize, completion: (UIImage->Void)) { let manager = PHImageManager.defaultManager() manager.requestImageForAsset(self.asset, targetSize: size, contentMode: .Default, options: nil, resultHandler: {image, Info in if let image = image { completion(image) } } ) } override func makeFilename()->String { if let date = asset.creationDate { self._filename = Utils.makeJPEGFilename(date) } else { self._filename = Utils.makeJPEGFilename(NSDate()) } return self._filename } }
mit
7e8fd032516f674a6c1968e94b0df678
29.45614
133
0.538018
4.862745
false
false
false
false
stringcode86/SCUtilities
SCUtilitiesCore/Utils.swift
1
1010
// // File.swift // SCUtilities // // Created by Michal Inger on 18/11/2015. // Copyright © 2015 stringCode ltd. All rights reserved. // import Foundation public func dispatch_after(delay:Double, _ closure:(()->())? = nil) { if let closure = closure { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))),dispatch_get_main_queue(), closure) } } public func dispatch_async_on_main_queue(block: ()->()) { dispatch_async(dispatch_get_main_queue()) { block() } } public func saveFileToDocumentsWithName(name: String, contents: NSData) { var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as String! path = path + "/" + name contents.writeToFile(path, atomically: false) } public func testBuildConfiguration() -> String { #if RELEASEF let text = "Release SC " #else let text = "Debug SC" #endif return text }
mit
289dd65fd415f6de502903edbea07b0c
27.055556
152
0.675917
3.92607
false
false
false
false
tensorflow/swift-apis
Sources/TensorFlow/Core/LazyTensorOperation.swift
1
40853
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import CTensorFlow @usableFromInline class LazyTensorHandle: _AnyTensorHandle { enum Handle { /// Bool indicates if this concrete TFETensorhandle was a result of /// materialization. case concrete(TFETensorHandle, materialized: Bool) /// Bool indicates whether this is a live tensor. This flag is used to /// heuristically determine whether this symbolic tensor should also be /// materialized whenever materialization of any other tensor is triggered. case symbolic(LazyTensorOperation, index: Int, isLive: Bool) } let handle: Handle @usableFromInline var _tfeTensorHandle: TFETensorHandle { switch handle { case .concrete(let h, _): return h case .symbolic(let op, let index, _): return op.materialized(index: index) } } init(_ base: TFETensorHandle) { handle = Handle.concrete(base, materialized: false) } init(_materialized base: TFETensorHandle) { handle = Handle.concrete(base, materialized: true) } init(_lazy op: LazyTensorOperation, index: Int) { precondition( index < op.outputCount, "Symbolic Tensor Index is out-of-bounds") handle = Handle.symbolic(op, index: index, isLive: false) LazyTensorContext.local.operationsTracker.incrementRefCount(op, isLive: false) } init(_lazyLive op: LazyTensorOperation, index: Int) { precondition( index < op.outputCount, "Symbolic Tensor Index is out-of-bounds") handle = Handle.symbolic(op, index: index, isLive: true) LazyTensorContext.local.operationsTracker.incrementRefCount(op, isLive: true) } deinit { if case let .symbolic(op, _, isLive) = handle { LazyTensorContext.local.operationsTracker.decrementRefCount(op, isLive: isLive) } } /// The number of dimensions of the underlying `Tensor`. @usableFromInline var rank: Int { @_semantics("autodiff.nonvarying") get { shape.rank } } /// The shape of the underlying `Tensor`. @usableFromInline var shape: TensorShape { @_semantics("autodiff.nonvarying") get { switch handle { case .symbolic(let op, let index, _): precondition( LazyTensorContext.local.isShapeTrackingEnabled, "Shape tracking is not enabled in this context.") if let shape = op.outputShapes[index] { return shape } // Materialize and get the shape from concrete tensor handle. op.outputShapes[index] = _tfeTensorHandle.shape return op.outputShapes[index]! case .concrete(let tfeHandle, _): return tfeHandle.shape } } } /// Returns the underlying `LazyTensorOperation` if this is a symbolic `LazyTensorHandle`. var lazyTensorOperation: LazyTensorOperation? { switch handle { case .symbolic(let op, _, _): return op case .concrete: return nil } } @usableFromInline var backend: Device.Backend { return .TF_EAGER } // Liveness tracking for LazyTensorOperations // static func isLive(_ op: LazyTensorOperation) -> Bool { return LazyTensorContext.local.operationsTracker.isLive(op) } static func forEachLiveOperation( _ perform: (LazyTensorOperation) throws -> Void ) rethrows { try LazyTensorContext.local.operationsTracker.forEachLiveOperation(perform) } static func forEachOperation( _ perform: (LazyTensorOperation) throws -> Void ) rethrows { try LazyTensorContext.local.operationsTracker.forEachOperation(perform) } @usableFromInline static var _materializationCallback: (String) -> Void = { _ in } } extension _AnyTensorHandle { /// Returns a concrete `LazyTensorHandle` with an additional constraint that the /// underlying concrete `LazyTensorHandle` should be marked to be promoted as an /// input when used in an extracted trace. This provides a **temporary** /// mechanism to promote a concrete lazy tensor to an input in extracted /// traces. (Note that this may trigger materialization.) var _concreteInputLazyTensor: LazyTensorHandle { LazyTensorHandle(_materialized: self._tfeTensorHandle) } } extension TensorHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: TensorHandle { TensorHandle(handle: handle._concreteInputLazyTensor) } } extension Tensor { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: Tensor { Tensor(handle: handle._concreteInputLazyTensor) } } extension StringTensor { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: StringTensor { StringTensor(handle: handle._concreteInputLazyTensor) } } extension VariantHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: VariantHandle { VariantHandle(handle: handle._concreteInputLazyTensor) } } extension ResourceHandle { /// Returns `Self` that wraps `_concreteInputLazyTensor` of the underlying /// `_AnyTensorHandle` public var _concreteInputLazyTensor: ResourceHandle { ResourceHandle(handle: handle._concreteInputLazyTensor) } } class LazyTensorOperation: TensorOperation { typealias TensorValueHandle = LazyTensorHandle enum Input { case single(LazyTensorHandle) case list([LazyTensorHandle]) } enum Attribute: Equatable { case boolValue(Bool) case intValue(Int) case floatValue(Float) case doubleValue(Double) case stringValue(String) case boolArray([Bool]) case intArray([Int]) case floatArray([Float]) case doubleArray([Double]) case stringArray([String]) case constTensor(TFETensorHandle) case tensorDataTypeValue(TensorDataType) case tensorFunctionPointer(_TensorFunctionPointer) case tensorDataTypeArray([TensorDataType]) case optionalTensorShape(TensorShape?) case optionalTensorShapeArray([TensorShape?]) } var name: String let outputCount: Int var inputs: [Input] var attributes: [String: Attribute] var outputShapes: [TensorShape?] var deviceName: String? var outputs: [TFETensorHandle]? var id: String? var nameWithID: String { if let id = self.id { return "\(name)_\(id)" } else { return "\(name)_\(ObjectIdentifier(self))" } } func outputName(at index: Int) -> String { precondition( index < outputCount, "Output index out of bounds when getting outputName.") let ssaID = id ?? "\(ObjectIdentifier(self))" var ssaName = "%\(ssaID)" if outputCount > 1 { ssaName += ".\(index)" } return ssaName } var outputName: String { switch outputCount { case 0: return "" case 1: return outputName(at: 0) default: let outputNames = (0..<outputCount).lazy.map { self.outputName(at: $0) } let aggregateName = outputNames.joined(separator: ", ") return "(\(aggregateName))" } } static var liveOperations: Int = 0 init(_id id: String?, name: String, outputCount: Int) { self.name = name self.inputs = [] self.attributes = [:] self.deviceName = _ExecutionContext.global.currentDeviceName self.outputCount = outputCount self.outputShapes = [] self.outputs = nil self.id = id LazyTensorOperation.liveOperations += 1 } required convenience init(_ name: String, _ outputCount: Int) { self.init(_id: nil, name: name, outputCount: outputCount) } deinit { LazyTensorOperation.liveOperations -= 1 } func evaluate() -> [LazyTensorHandle] { if LazyTensorContext.local.isShapeTrackingEnabled { updateOutputShapes() } return (0..<outputCount).map { LazyTensorHandle(_lazyLive: self, index: $0) } } func addInput(_ input: LazyTensorHandle) { inputs.append(Input.single(input)) } func updateAttribute(_ name: String, _ value: Bool) { attributes[name] = Attribute.boolValue(value) } func updateAttribute(_ name: String, _ value: Int) { attributes[name] = Attribute.intValue(value) } func updateAttribute(_ name: String, _ value: Int32) { attributes[name] = Attribute.intValue(Int(value)) } func updateAttribute(_ name: String, _ value: Int64) { attributes[name] = Attribute.intValue(Int(value)) } func updateAttribute(_ name: String, _ value: Float) { attributes[name] = Attribute.floatValue(value) } func updateAttribute(_ name: String, _ value: Double) { attributes[name] = Attribute.doubleValue(value) } func updateAttribute(_ name: String, _ value: String) { attributes[name] = Attribute.stringValue(value) } func updateAttribute(_ name: String, _ value: [Bool]) { attributes[name] = Attribute.boolArray(value) } func updateAttribute(_ name: String, _ value: [Int]) { attributes[name] = Attribute.intArray(value) } func updateAttribute(_ name: String, _ value: [Int32]) { attributes[name] = Attribute.intArray(value.map { Int($0) }) } func updateAttribute(_ name: String, _ value: [Int64]) { attributes[name] = Attribute.intArray(value.map { Int($0) }) } func updateAttribute(_ name: String, _ value: [Float]) { attributes[name] = Attribute.floatArray(value) } func updateAttribute(_ name: String, _ value: [Double]) { attributes[name] = Attribute.doubleArray(value) } func updateAttribute(_ name: String, _ value: [String]) { attributes[name] = Attribute.stringArray(value) } } extension LazyTensorOperation: TFTensorOperation { private func lazyTensorHandle(_ input: _AnyTensorHandle) -> LazyTensorHandle { if let lazyHandle = input as? LazyTensorHandle { if case let LazyTensorHandle.Handle.symbolic( op, index, true) = lazyHandle.handle { // We turn off liveness for the constructed LazyTensorHandle, // because it is only referenced internally as a part // of the LazyTensorOperation input. return LazyTensorHandle(_lazy: op, index: index) } else { return lazyHandle } } else { return LazyTensorHandle(input._tfeTensorHandle) } } func addInput(_ input: _AnyTensorHandle) { addInput(lazyTensorHandle(input)) } func addInput<Scalar: TensorFlowScalar>(_ input: Tensor<Scalar>) { addInput(input.handle.handle) } func addInput(_ input: StringTensor) { addInput(input.handle.handle) } func addInput(_ input: VariantHandle) { addInput(input.handle) } func addInput(_ input: ResourceHandle) { addInput(input.handle) } func addInputList<T: TensorArrayProtocol>(_ input: T) { let lazyHandles = input._tensorHandles.map { lazyTensorHandle($0) } inputs.append(Input.list(lazyHandles)) } func updateAttribute(_ name: String, _ value: TensorDataType) { attributes[name] = Attribute.tensorDataTypeValue(value) } func updateAttribute(_ name: String, _ value: TensorShape) { attributes[name] = Attribute.optionalTensorShape(value) } func updateAttribute(_ name: String, _ value: TensorShape?) { attributes[name] = Attribute.optionalTensorShape(value) } func updateAttribute(_ name: String, _ value: [TensorDataType]) { attributes[name] = Attribute.tensorDataTypeArray(value) } func updateAttribute(_ name: String, _ value: [TensorShape]) { attributes[name] = Attribute.optionalTensorShapeArray(value) } func updateAttribute(_ name: String, _ value: [TensorShape?]) { attributes[name] = Attribute.optionalTensorShapeArray(value) } func updateAttribute(_ name: String, _ value: _TensorFunctionPointer) { attributes[name] = Attribute.tensorFunctionPointer(value) } func updateAttribute(_ name: String, _ value: TFETensorHandle) { attributes[name] = Attribute.constTensor(value) } func updateAttribute<In: TensorGroup, Out: TensorGroup>( _ name: String, _ value: (In) -> Out ) { updateAttribute(name, _TensorFunctionPointer(name: _tffunc(value))) } func execute() { // If we want to stage this, we will need to add control dependencies. // For the time-being, just build a TFE_Op and run it. // // Collect all the unmaterialized inputs. var unmaterializedInputs = [LazyTensorOperation]() unmaterializedInputs.reserveCapacity(inputs.count) for input in inputs { switch input { case .single(let v): if let lazyOperation = v.lazyTensorOperation { unmaterializedInputs.append(lazyOperation) } case .list(let values): unmaterializedInputs.append( contentsOf: values.lazy.compactMap { $0.lazyTensorOperation } ) } } // Materialize the inputs now. LazyTensorOperation.materialize(targets: unmaterializedInputs) // Build the TFEOp and execute. let op = TFE_Op(name, outputCount) for input in inputs { switch input { case .single(let v): op.addInput(v._tfeTensorHandle) case .list(let values): for v in values { op.addInput(v._tfeTensorHandle) } } } for (name, value) in attributes { switch value { case .boolValue(let v): op.updateAttribute(name, v) case .intValue(let v): op.updateAttribute(name, v) case .floatValue(let v): op.updateAttribute(name, v) case .doubleValue(let v): op.updateAttribute(name, v) case .stringValue(let v): op.updateAttribute(name, v) case .boolArray(let v): op.updateAttribute(name, v) case .intArray(let v): op.updateAttribute(name, v) case .floatArray(let v): op.updateAttribute(name, v) case .doubleArray(let v): op.updateAttribute(name, v) case .stringArray(let v): op.updateAttribute(name, v) case .constTensor(_): fatalError("Const Tensor cannot be eager attribute.") case .tensorDataTypeValue(let v): op.updateAttribute(name, v) case .tensorDataTypeArray(let v): op.updateAttribute(name, v) case .optionalTensorShape(let v): op.updateAttribute(name, v) case .optionalTensorShapeArray(let v): op.updateAttribute(name, v) case .tensorFunctionPointer(let v): op.updateAttribute(name, v) } } op.execute() } func execute<T0: TensorArrayProtocol>( _ count0: Int ) -> (T0) { let outputs = evaluate() let offset0 = 0 let result = (T0.init(_handles: outputs[offset0..<count0])) return result } func execute<T0: TensorArrayProtocol, T1: TensorArrayProtocol>( _ count0: Int, _ count1: Int ) -> (T0, T1) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<outputs.count]) ) return result } func execute<T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol>( _ count0: Int, _ count1: Int, _ count2: Int ) -> (T0, T1, T2) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int ) -> (T0, T1, T2, T3) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int ) -> (T0, T1, T2, T3, T4) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int ) -> (T0, T1, T2, T3, T4, T5) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int ) -> (T0, T1, T2, T3, T4, T5, T6) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol, T13: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int, _ count13: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let offset13 = offset12 + count12 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<offset13]), T13.init(_handles: outputs[offset13..<outputs.count]) ) return result } func execute< T0: TensorArrayProtocol, T1: TensorArrayProtocol, T2: TensorArrayProtocol, T3: TensorArrayProtocol, T4: TensorArrayProtocol, T5: TensorArrayProtocol, T6: TensorArrayProtocol, T7: TensorArrayProtocol, T8: TensorArrayProtocol, T9: TensorArrayProtocol, T10: TensorArrayProtocol, T11: TensorArrayProtocol, T12: TensorArrayProtocol, T13: TensorArrayProtocol, T14: TensorArrayProtocol >( _ count0: Int, _ count1: Int, _ count2: Int, _ count3: Int, _ count4: Int, _ count5: Int, _ count6: Int, _ count7: Int, _ count8: Int, _ count9: Int, _ count10: Int, _ count11: Int, _ count12: Int, _ count13: Int, _ count14: Int ) -> (T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) { let outputs = evaluate() let offset0 = 0 let offset1 = offset0 + count0 let offset2 = offset1 + count1 let offset3 = offset2 + count2 let offset4 = offset3 + count3 let offset5 = offset4 + count4 let offset6 = offset5 + count5 let offset7 = offset6 + count6 let offset8 = offset7 + count7 let offset9 = offset8 + count8 let offset10 = offset9 + count9 let offset11 = offset10 + count10 let offset12 = offset11 + count11 let offset13 = offset12 + count12 let offset14 = offset13 + count13 let result = ( T0.init(_handles: outputs[offset0..<offset1]), T1.init(_handles: outputs[offset1..<offset2]), T2.init(_handles: outputs[offset2..<offset3]), T3.init(_handles: outputs[offset3..<offset4]), T4.init(_handles: outputs[offset4..<offset5]), T5.init(_handles: outputs[offset5..<offset6]), T6.init(_handles: outputs[offset6..<offset7]), T7.init(_handles: outputs[offset7..<offset8]), T8.init(_handles: outputs[offset8..<offset9]), T9.init(_handles: outputs[offset9..<offset10]), T10.init(_handles: outputs[offset10..<offset11]), T11.init(_handles: outputs[offset11..<offset12]), T12.init(_handles: outputs[offset12..<offset13]), T13.init(_handles: outputs[offset13..<offset14]), T14.init(_handles: outputs[offset14..<outputs.count]) ) return result } } extension TFETensorHandle { public var valueDescription: String { let dtype = TFE_TensorHandleDataType(self._cTensorHandle) switch dtype { case TF_FLOAT: return Tensor(handle: TensorHandle<Float>(handle: self)).description case TF_DOUBLE: return Tensor(handle: TensorHandle<Double>(handle: self)).description case TF_BFLOAT16: return Tensor(handle: TensorHandle<BFloat16>(handle: self)).description case TF_INT64: return Tensor(handle: TensorHandle<Int64>(handle: self)).description case TF_INT32: return Tensor(handle: TensorHandle<Int32>(handle: self)).description case TF_INT16: return Tensor(handle: TensorHandle<Int16>(handle: self)).description case TF_INT8: return Tensor(handle: TensorHandle<Int8>(handle: self)).description case TF_UINT64: return Tensor(handle: TensorHandle<UInt64>(handle: self)).description case TF_UINT32: return Tensor(handle: TensorHandle<UInt32>(handle: self)).description case TF_UINT16: return Tensor(handle: TensorHandle<UInt16>(handle: self)).description case TF_UINT8: return Tensor(handle: TensorHandle<UInt8>(handle: self)).description case TF_BOOL: return Tensor(handle: TensorHandle<Bool>(handle: self)).description case TF_STRING: // TODO(https://bugs.swift.org/browse/TF-561): The current // implementation of ShapedArray<String> is not correct, which // causes seg faults. return "\"string\"" default: return TFETensorHandle.tfDataTypeAsString(dtype) } } static func tfDataTypeAsString(_ cDataType: TF_DataType) -> String { switch cDataType { case TF_FLOAT: return "float" case TF_DOUBLE: return "double" case TF_INT32: return "int32" case TF_UINT8: return "uint8" case TF_INT16: return "int16" case TF_INT8: return "int8" case TF_STRING: return "string" case TF_COMPLEX64, TF_COMPLEX: return "complex" case TF_INT64: return "int64" case TF_BOOL: return "bool" case TF_QINT8: return "qint8" case TF_QUINT8: return "quint8" case TF_QINT32: return "qint32" case TF_BFLOAT16: return "bfloat16" case TF_QINT16: return "qint16" case TF_QUINT16: return "quint16" case TF_UINT16: return "uint16" case TF_COMPLEX128: return "complex128" case TF_HALF: return "half" case TF_RESOURCE: return "resource" case TF_VARIANT: return "variant" case TF_UINT32: return "uint32" case TF_UINT64: return "uint64" default: fatalError("Unhandled type: \(cDataType)") } } } extension LazyTensorOperation.Attribute: CustomStringConvertible { var description: String { switch self { case .boolValue(let v): return "\(v)" case .intValue(let v): return "Int(\(v))" case .floatValue(let v): return "Float(\(v))" case .doubleValue(let v): return "Double(\(v))" case .stringValue(let v): return "\"\(v)\"" case .boolArray(let values): return arrayAsString("", values) case .intArray(let values): return arrayAsString("Int", values) case .floatArray(let values): return arrayAsString("Float", values) case .doubleArray(let values): return arrayAsString("Double", values) case .stringArray(let values): return arrayAsString("String", values) case .constTensor(let v): return v.valueDescription case .tensorDataTypeValue(let v): return dataTypeAsString(v) case .tensorFunctionPointer(let v): return "TFFunction(\(v.name))" case .tensorDataTypeArray(let values): let descriptions = values.map { dataTypeAsString($0) } let descString = descriptions.joined(separator: ", ") return "[\(descString)]" case .optionalTensorShape(let t): return String(describing: t) case .optionalTensorShapeArray(let t): return "\(t)" } } private func arrayAsString<T>(_ desc: String, _ values: [T]) -> String { let arrayDesc = (values.map { "\($0)" }).joined(separator: ", ") return "\(desc)[\(arrayDesc)]" } private func dataTypeAsString(_ dataType: TensorDataType) -> String { return TFETensorHandle.tfDataTypeAsString(dataType._cDataType) } } extension LazyTensorHandle: CustomStringConvertible { public var description: String { switch self.handle { case .concrete(let h, let isMaterialized): return isMaterialized ? "\(h.valueDescription)*" : "\(h.valueDescription)" case .symbolic(let op, let index, let isLive): return op.outputName(at: index) + (isLive ? "*" : "") } } } extension LazyTensorOperation: CustomStringConvertible { public var description: String { let attributesDesc = attributes.sorted(by: { $0.key < $1.key }).map { "\($0): \($1)" } let inputsDesc = inputs.map { input -> String in switch input { case Input.single(let lazyTensor): return "\(lazyTensor)" case Input.list(let lazyTensorList): let lazyTensors = lazyTensorList.map { "\($0)" } let lazyTensorsDesc = lazyTensors.joined(separator: ", ") return "[\(lazyTensorsDesc)]" } } var desc = "\(outputName) = \(name)" if !attributes.isEmpty { desc += "[" desc += attributesDesc.joined(separator: ", ") desc += "]" } desc += "(" desc += inputsDesc.joined(separator: ", ") desc += ")" return desc } } extension LazyTensorOperation { /// Returns the materialized value at the given output `index`. func materialized(index: Int) -> TFETensorHandle { precondition(index < outputCount) return materialized()[index] } /// Materializes all the outputs. func materialized() -> [TFETensorHandle] { // Return materialized outputs if any. if let outputs = outputs { return outputs } LazyTensorOperation.materialize(targets: [self]) // Our outputs should have been updated by now. Otherwise, // something terrible happened! precondition(outputs != nil, "Materialization failed!") return outputs! } /// Converts symbolic tensor inputs to concrete inputs if the associated `LazyTensorOperation` /// has been materialized. func maybeMaterializeInputs() { /// If `lazyTensor` is symbolic and the associated `LazyTensorOperation` /// has been materialized, return the corresponding concrete `LazyTensorHandle`. /// Otherwise, return `lazyTensor` untouched. func materializedAsNeeded(lazyTensor: LazyTensorHandle) -> LazyTensorHandle { let handle = lazyTensor.handle if case let .symbolic(lazyOp, index, _) = handle, let outputs = lazyOp.outputs { return LazyTensorHandle(_materialized: outputs[index]) } return lazyTensor } /// Returns an input that is rewritten such that all symbolic values /// that have been materialized have been replaced by the corresponding /// concerete inputs. If no symbolic values have been materialized or if /// there are no symbolic values, return the `input` untouched. func materializedAsNeeded(input: Input) -> Input { switch input { case .single(let h): return .single(materializedAsNeeded(lazyTensor: h)) case .list(let elements): return .list(elements.map { materializedAsNeeded(lazyTensor: $0) }) } } inputs = inputs.map { materializedAsNeeded(input: $0) } } static func materialize(targets: [LazyTensorOperation]) { let traceInfo = LazyTensorTraceBuilder.materializationTraceInfo(targets) debugLog("Extracted trace:\n\(traceInfo.trace)") let function = TFFunction(trace: traceInfo.trace) debugLog("Generated TFFunction:\n\(function)") let allOutputs = function.execute(traceInfo.concreteInputs) // Slice up the outputs to various lazy tensors var start = 0 for lazyOp in traceInfo.lazyOperations { let end = start + lazyOp.outputCount lazyOp.outputs = Array(allOutputs[start..<end]) lazyOp.outputShapes = lazyOp.outputs!.map { $0.shape } start = end } } }
apache-2.0
9f0d6451e4e88857043b01db1d16dfaf
32.987521
96
0.663329
3.868289
false
false
false
false
natecook1000/swift
test/SILGen/same_type_abstraction.swift
3
2504
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s protocol Associated { associatedtype Assoc } struct Abstracted<T: Associated, U: Associated> { let closure: (T.Assoc) -> U.Assoc } struct S1 {} struct S2 {} // CHECK-LABEL: sil hidden @$S21same_type_abstraction28callClosureWithConcreteTypes{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @$S{{.*}}TR : func callClosureWithConcreteTypes<T: Associated, U: Associated>(x: Abstracted<T, U>, arg: S1) -> S2 where T.Assoc == S1, U.Assoc == S2 { return x.closure(arg) } // Problem when a same-type constraint makes an associated type into a tuple protocol MyProtocol { associatedtype ReadData associatedtype Data func readData() -> ReadData } extension MyProtocol where Data == (ReadData, ReadData) { // CHECK-LABEL: sil hidden @$S21same_type_abstraction10MyProtocolPAA8ReadDataQz_AEt0G0RtzrlE07currentG0AE_AEtyF : $@convention(method) <Self where Self : MyProtocol, Self.Data == (Self.ReadData, Self.ReadData)> (@in_guaranteed Self) -> (@out Self.ReadData, @out Self.ReadData) func currentData() -> Data { // CHECK: bb0(%0 : @trivial $*Self.ReadData, %1 : @trivial $*Self.ReadData, %2 : @trivial $*Self): // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%0, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: [[READ_FN:%.*]] = witness_method $Self, #MyProtocol.readData!1 : {{.*}} : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: apply [[READ_FN]]<Self>(%1, %2) : $@convention(witness_method: MyProtocol) <τ_0_0 where τ_0_0 : MyProtocol> (@in_guaranteed τ_0_0) -> @out τ_0_0.ReadData // CHECK: return return (readData(), readData()) } } // Problem with protocol typealiases, which are modeled as same-type // constraints protocol Refined : Associated { associatedtype Key typealias Assoc = Key init() } extension Refined { // CHECK-LABEL: sil hidden @$S21same_type_abstraction7RefinedPAAE12withElementsx5AssocQz_tcfC : $@convention(method) <Self where Self : Refined> (@in Self.Assoc, @thick Self.Type) -> @out Self init(withElements newElements: Key) { self.init() } }
apache-2.0
724bea86a8d5f8fa2e299386a13d5ae9
42.649123
278
0.676849
3.295364
false
false
false
false
jariz/Noti
Noti/IntroViewController.swift
1
2469
// // IntroViewController.swift // Noti // // Created by Jari on 29/06/16. // Copyright © 2016 Jari Zwarts. All rights reserved. // import Cocoa class IntroViewController: NSViewController { var awc:NSWindowController?; override func viewDidAppear() { if (self.view.window != nil) { self.view.window!.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark) self.view.window!.titlebarAppearsTransparent = true; self.view.window!.isMovableByWindowBackground = true self.view.window!.invalidateShadow() } NotificationCenter.default.addObserver(self, selector: #selector(IntroViewController.authSuccess(_:)), name:NSNotification.Name(rawValue: "AuthSuccess"), object: nil) } @IBOutlet weak var authBtn:NSButton!; @IBOutlet weak var authTxt:NSTextField!; @IBOutlet weak var authImg:NSImageView!; @objc func authSuccess(_ notification: Notification) { authBtn.isEnabled = false self.authTxt.alphaValue = 1 self.authTxt.alphaValue = self.authBtn.alphaValue //self.view.window!.styleMask.subtract(NSClosableWindowMask) NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.50 self.authTxt.animator().alphaValue = 0 self.authBtn.animator().alphaValue = 0 }, completionHandler: { () -> Void in self.authTxt.isHidden = true self.authBtn.isHidden = true self.authImg.isHidden = false self.authImg.alphaValue = 0 NSAnimationContext.runAnimationGroup({ (context) -> Void in context.duration = 0.50 self.authImg.animator().alphaValue = 1 }, completionHandler: nil) }) Timer.scheduledTimer(timeInterval: 3, target: BlockOperation(block: self.view.window!.close), selector: #selector(Operation.main), userInfo: nil, repeats: false) } @IBAction func startAuth(_ sender: AnyObject) { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Main"), bundle: nil) awc = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier(rawValue: "AuthWindowController")) as? NSWindowController print("showWindow") awc!.showWindow(self) } }
mit
0a87d96cb719cf66a9bb289f30aa5e5c
37.5625
174
0.627229
4.936
false
false
false
false
nProdanov/FuelCalculator
Fuel economy smart calc./Fuel economy smart calc./CurrentChargeViewController.swift
1
3632
// // CurrentChargeViewController.swift // Fuel economy smart calc. // // Created by Nikolay Prodanow on 3/24/17. // Copyright © 2017 Nikolay Prodanow. All rights reserved. // import UIKit class CurrentChargeViewController: UIViewController { @IBOutlet weak var tripQuantityTextField: UITextField! @IBOutlet weak var journeyQuantityTextField: UITextField! @IBOutlet weak var gasStationNameLabel: UILabel! @IBOutlet weak var dateChargedlabel: UILabel! @IBOutlet weak var fuelChargedQuantityLabel: UILabel! @IBOutlet weak var fuelPriceLabel: UILabel! @IBOutlet weak var fuelChargedUnitLabel: UILabel! @IBOutlet weak var fuelPriceCurrencyUnitLabel: UILabel! @IBOutlet weak var fuelPriceUnitLabel: UILabel! @IBOutlet weak var tripUnitLabel: UILabel! @IBOutlet weak var journeyUnitLabel: UILabel! @IBAction func addTripToJourney() { let trip = Double(tripQuantityTextField.text!) if let currentCharge = self.currentCharge, let tripDistance = trip { self.currentCharge?.journey += tripDistance self.chargesData?.updadeCurrentCharge(with: currentCharge.journey) } tripQuantityTextField.text = "" journeyQuantityTextField.text = self.currentCharge?.journey.description dismissKeyboard() } var chargesData: BaseChargesData? var currentCharge: CurrentCharge? { didSet { self.updateUI() } } override func viewDidLoad() { super.viewDidLoad() addGestureForDismissingKeyboard() addSaveButtonToNavBar() } override func viewWillAppear(_ animated: Bool) { chargesData?.setDelegate(self) if currentCharge == nil { self.chargesData?.getCurrentCharge() } } func save() { if let currentCharge = self.currentCharge { self.chargesData?.createCharge(fromCurrentCharge: currentCharge) } } private func updateUI() { if let charge = currentCharge { gasStationNameLabel.text = charge.gasStation.fullName let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MMMM YYYY" dateChargedlabel.text = dateFormatter.string(from: charge.chargingDate) fuelChargedQuantityLabel.text = charge.chargedFuel.description fuelChargedUnitLabel.text = charge.fuelunit fuelPriceLabel.text = charge.price.description fuelPriceCurrencyUnitLabel.text = charge.priceUnit fuelPriceUnitLabel.text = charge.fuelunit tripUnitLabel.text = charge.distanceUnit journeyUnitLabel.text = charge.distanceUnit journeyQuantityTextField.text = charge.journey.description } } private func addSaveButtonToNavBar() { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .plain, target: self, action: #selector(save)) } } extension CurrentChargeViewController: ChargesDataDelegate { func didReceiveCurrentCharge(_ currentCharge: CurrentCharge?) { if currentCharge != nil { self.currentCharge = currentCharge } else { self.tabBarController?.selectedIndex = 1 } } func didCreateCharge() { self.currentCharge = nil self.chargesData?.deleteCurrentCharge() } func didReceiceDeleteCurrentCharge(){ self.tabBarController?.selectedIndex = 3 } }
mit
b74b4a4b58471e61bcc31fcb41fa3d92
30.850877
128
0.649408
5.34757
false
false
false
false
gerardogrisolini/Webretail
Sources/Webretail/Authentication/TurnstilePerfectRealm.swift
1
771
// // TurnstilePerfectRealm.swift // Webretail // // Created by Gerardo Grisolini on 26/02/17. // // import Turnstile import TurnstileWeb import PerfectHTTP public class TurnstilePerfectRealm { public var requestFilter: (HTTPRequestFilter, HTTPFilterPriority) public var responseFilter: (HTTPResponseFilter, HTTPFilterPriority) public let turnstile: Turnstile public init(sessionManager: SessionManager = PerfectSessionManager(), realm: Realm = CustomRealm()) { turnstile = Turnstile(sessionManager: sessionManager, realm: realm) let filter = TurnstileFilter(turnstile: turnstile) requestFilter = (filter, HTTPFilterPriority.high) responseFilter = (filter, HTTPFilterPriority.high) } }
apache-2.0
5e1ab88dd3a11cb62195ed647bfe7c4e
27.555556
105
0.718547
4.616766
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Room/View/ShowAnchorHeadFollowPersonCell.swift
1
1416
// // ShowAnchorHeadFollowPersonCell.swift // DYZB // // Created by xiudou on 16/11/8. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit import SDWebImage // MARK:- 常量 private let iconImageViewWH :CGFloat = 30 class ShowAnchorHeadFollowPersonCell: UICollectionViewCell { // MARK:- 懒加载 fileprivate lazy var iconImageView : UIImageView = { let iconImageView = UIImageView() iconImageView.frame = CGRect(x: 0, y: 0, width: iconImageViewWH, height: iconImageViewWH) return iconImageView }() // MARK:- SET var roomFollowPerson : RoomFollowPerson?{ didSet{ guard let model = roomFollowPerson else { return } iconImageView.sd_setImage(with: URL(string: model.photo), placeholderImage: UIImage(named: "placeholder_head"), options: .allowInvalidSSLCertificates) } } // MARK:- 系统回调 override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(iconImageView) iconImageView.layer.cornerRadius = iconImageViewWH * 0.5 iconImageView.clipsToBounds = true iconImageView.layer.borderWidth = 5 iconImageView.layer.borderColor = UIColor.green.cgColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
94220fc1c03d8ae8fa583e6dbf73884c
26.9
162
0.648029
4.728814
false
false
false
false
Marquis103/RecipeFinder
RecipeFinder/FavoriteRecipeTableViewControllerDataSource.swift
1
4137
// // FavoriteRecipeTableViewControllerDataSource.swift // RecipeFinder // // Created by Marquis Dennis on 5/11/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit import CoreData class FavoriteRecipeTableViewControllerDataSource:NSObject, UITableViewDataSource { private weak var tableView:UITableView! //data source initializer init(withTableView tableView:UITableView) { super.init() self.tableView = tableView self.tableView.dataSource = self } //MARK: UITableViewDataSource func numberOfSectionsInTableView(tableView: UITableView) -> Int { if let sections = fetchedResultsController.sections { return sections.count } return 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let sections = fetchedResultsController.sections { let sectionInfo = sections[section] return sectionInfo.numberOfObjects } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("recipeCell", forIndexPath: indexPath) as! RecipeTableViewCell let recipe = fetchedResultsController.objectAtIndexPath(indexPath) as! RecipeEntity cell.userInteractionEnabled = true cell.configureCell(recipe.convertToRecipe()) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let recipe = fetchedResultsController.objectAtIndexPath(indexPath) let coreData = CoreDataStack.defaultStack coreData.managedObjectContext.deleteObject(recipe as! NSManagedObject) do { try coreData.saveContext() } catch let error as NSError { print(error) } } } //MARK: FetchRequest func entryListFetchRequest() -> NSFetchRequest { let fetchRequest = NSFetchRequest(entityName: "RecipeEntity") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: false)] return fetchRequest } func performFetch() throws { do { try fetchedResultsController.performFetch() } catch let error as NSError { tableView = nil NSLog("Error during fetch\n \(error)") throw error } } //MARK: NSFetchedResultsController lazy var fetchedResultsController:NSFetchedResultsController = { let coreData = CoreDataStack.defaultStack let fetchedResultsController = NSFetchedResultsController(fetchRequest: self.entryListFetchRequest(), managedObjectContext: coreData.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController.delegate = self return fetchedResultsController }() } //MARK: NSFetchedResultsControllerDelegate extension FavoriteRecipeTableViewControllerDataSource: NSFetchedResultsControllerDelegate { func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch(type) { case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) break case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic) break case .Update: tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic) break default: break } } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) break case .Delete: tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic) break default: break } } }
gpl-3.0
1803bb00e320a5b45b44c58f4e1f9bf8
28.971014
208
0.776112
5.03163
false
false
false
false
davecom/ClassicComputerScienceProblemsInSwift
Classic Computer Science Problems in Swift.playground/Pages/Chapter 8.xcplaygroundpage/Contents.swift
1
12013
//: [Previous](@previous) // Classic Computer Science Problems in Swift Chapter 8 Source // Copyright 2017 David Kopec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Knapsack struct Item { let name: String let weight: Int let value: Float } // originally based on Algorithms in C by Sedgewick, Second Edition, p 596 func knapsack(items: [Item], maxCapacity: Int) -> [Item] { //build up dynamic programming table var table: [[Float]] = [[Float]](repeating: [Float](repeating: 0.0, count: maxCapacity + 1), count: items.count + 1) //initialize table - overshooting in size for (i, item) in items.enumerated() { for capacity in 1...maxCapacity { let previousItemsValue = table[i][capacity] if capacity >= item.weight { // item fits in knapsack let valueFreeingWeightForItem = table[i][capacity - item.weight] table[i + 1][capacity] = max(valueFreeingWeightForItem + item.value, previousItemsValue) // only take if more valuable than previous combo } else { // no room for this item table[i + 1][capacity] = previousItemsValue //use prior combo } } } // figure out solution from table var solution: [Item] = [Item]() var capacity = maxCapacity for i in stride(from: items.count, to: 0, by: -1) { // work backwards if table[i - 1][capacity] != table[i][capacity] { // did we use this item? solution.append(items[i - 1]) capacity -= items[i - 1].weight // if we used an item, remove its weight } } return solution } let items = [Item(name: "television", weight: 50, value: 500), Item(name: "candlesticks", weight: 2, value: 300), Item(name: "stereo", weight: 35, value: 400), Item(name: "laptop", weight: 3, value: 1000), Item(name: "food", weight: 15, value: 50), Item(name: "clothing", weight: 20, value: 800), Item(name: "jewelry", weight: 1, value: 4000), Item(name: "books", weight: 100, value: 300), Item(name: "printer", weight: 18, value: 30), Item(name: "refrigerator", weight: 200, value: 700), Item(name: "painting", weight: 10, value: 1000)] knapsack(items: items, maxCapacity: 75) /// Travelling Salesman let vtCities = ["Rutland", "Burlington", "White River Junction", "Bennington", "Brattleboro"] let vtDistances = [ "Rutland": ["Burlington": 67, "White River Junction": 46, "Bennington": 55, "Brattleboro": 75], "Burlington": ["Rutland": 67, "White River Junction": 91, "Bennington": 122, "Brattleboro": 153], "White River Junction": ["Rutland": 46, "Burlington": 91, "Bennington": 98, "Brattleboro": 65], "Bennington": ["Rutland": 55, "Burlington": 122, "White River Junction": 98, "Brattleboro": 40], "Brattleboro": ["Rutland": 75, "Burlington": 153, "White River Junction": 65, "Bennington": 40] ] // backtracking permutations algorithm func allPermutationsHelper<T>(contents: [T], permutations: inout [[T]], n: Int) { guard n > 0 else { permutations.append(contents); return } var tempContents = contents for i in 0..<n { tempContents.swapAt(i, n - 1) // move the element at i to the end // move everything else around, holding the end constant allPermutationsHelper(contents: tempContents, permutations: &permutations, n: n - 1) tempContents.swapAt(i, n - 1) // backtrack } } // find all of the permutations of a given array func allPermutations<T>(_ original: [T]) -> [[T]] { var permutations = [[T]]() allPermutationsHelper(contents: original, permutations: &permutations, n: original.count) return permutations } // test allPermutations let abc = ["a","b","c"] let testPerms = allPermutations(abc) print(testPerms) print(testPerms.count) // make complete paths for tsp func tspPaths<T>(_ permutations: [[T]]) -> [[T]] { return permutations.map { if let first = $0.first { return ($0 + [first]) // append first to end } else { return [] // empty is just itself } } } print(tspPaths(testPerms)) func solveTSP<T>(cities: [T], distances: [T: [T: Int]]) -> (solution: [T], distance: Int) { let possiblePaths = tspPaths(allPermutations(cities)) // all potential paths var bestPath: [T] = [] // shortest path by distance var minDistance: Int = Int.max // distance of the shortest path for path in possiblePaths { if path.count < 2 { continue } // must be at least one city pair to calculate var distance = 0 var last = path.first! // we know there is one becuase of above line for next in path[1..<path.count] { // add up all pair distances distance += distances[last]![next]! last = next } if distance < minDistance { // found a new best path minDistance = distance bestPath = path } } return (solution: bestPath, distance: minDistance) } let vtTSP = solveTSP(cities: vtCities, distances: vtDistances) print("The shortest path is \(vtTSP.solution) in \(vtTSP.distance) miles.") /// Phone Number Mnemonics let phoneMapping: [Character: [Character]] = ["1": ["1"], "2": ["a", "b", "c"], "3": ["d", "e", "f"], "4": ["g", "h", "i"], "5": ["j", "k", "l"], "6": ["m", "n", "o"], "7": ["p", "q", "r", "s"], "8": ["t", "u", "v"], "9": ["w", "x", "y", "z"], "0": ["0"]] // return all of the possible characters combos, given a mapping, for a given number func stringToPossibilities(_ s: String, mapping: [Character: [Character]]) -> [[Character]]{ let possibilities = s.compactMap{ mapping[$0] } print(possibilities) return combineAllPossibilities(possibilities) } // takes a set of possible characters for each position and finds all possible permutations func combineAllPossibilities(_ possibilities: [[Character]]) -> [[Character]] { guard let possibility = possibilities.first else { return [[]] } var permutations: [[Character]] = possibility.map { [$0] } // turn each into an array for possibility in possibilities[1..<possibilities.count] where possibility != [] { let toRemove = permutations.count // temp for permutation in permutations { for c in possibility { // try adding every letter var newPermutation: [Character] = permutation // need a mutable copy newPermutation.append(c) // add character on the end permutations.append(newPermutation) // new combo ready } } permutations.removeFirst(toRemove) // remove combos missing new last letter } return permutations } let permutations = stringToPossibilities("1440787", mapping: phoneMapping) /// Tic-tac-toe enum Piece: String { case X = "X" case O = "O" case E = " " var opposite: Piece { switch self { case .X: return .O case .O: return .X case .E: return .E } } } // a move is an integer 0-8 indicating a place to put a piece typealias Move = Int struct Board { let position: [Piece] let turn: Piece let lastMove: Move // by default the board is empty and X goes first // lastMove being -1 is a marker of a start position init(position: [Piece] = [.E, .E, .E, .E, .E, .E, .E, .E, .E], turn: Piece = .X, lastMove: Int = -1) { self.position = position self.turn = turn self.lastMove = lastMove } // location can be 0-8, indicating where to move // return a new board with the move played func move(_ location: Move) -> Board { var tempPosition = position tempPosition[location] = turn return Board(position: tempPosition, turn: turn.opposite, lastMove: location) } // the legal moves in a position are all of the empty squares var legalMoves: [Move] { return position.indices.filter { position[$0] == .E } } var isWin: Bool { return position[0] == position[1] && position[0] == position[2] && position[0] != .E || // row 0 position[3] == position[4] && position[3] == position[5] && position[3] != .E || // row 1 position[6] == position[7] && position[6] == position[8] && position[6] != .E || // row 2 position[0] == position[3] && position[0] == position[6] && position[0] != .E || // col 0 position[1] == position[4] && position[1] == position[7] && position[1] != .E || // col 1 position[2] == position[5] && position[2] == position[8] && position[2] != .E || // col 2 position[0] == position[4] && position[0] == position[8] && position[0] != .E || // diag 0 position[2] == position[4] && position[2] == position[6] && position[2] != .E // diag 1 } var isDraw: Bool { return !isWin && legalMoves.count == 0 } } // Find the best possible outcome for originalPlayer func minimax(_ board: Board, maximizing: Bool, originalPlayer: Piece) -> Int { // Base case — evaluate the position if it is a win or a draw if board.isWin && originalPlayer == board.turn.opposite { return 1 } // win else if board.isWin && originalPlayer != board.turn.opposite { return -1 } // loss else if board.isDraw { return 0 } // draw // Recursive case — maximize your gains or minimize the opponent's gains if maximizing { var bestEval = Int.min for move in board.legalMoves { // find the move with the highest evaluation let result = minimax(board.move(move), maximizing: false, originalPlayer: originalPlayer) bestEval = max(result, bestEval) } return bestEval } else { // minimizing var worstEval = Int.max for move in board.legalMoves { let result = minimax(board.move(move), maximizing: true, originalPlayer: originalPlayer) worstEval = min(result, worstEval) } return worstEval } } // Run minimax on every possible move to find the best one func findBestMove(_ board: Board) -> Move { var bestEval = Int.min var bestMove = -1 for move in board.legalMoves { let result = minimax(board.move(move), maximizing: false, originalPlayer: board.turn) if result > bestEval { bestEval = result bestMove = move } } return bestMove } // win in 1 move let toWinEasyPosition: [Piece] = [.X, .O, .X, .X, .E, .O, .E, .E, .O] let testBoard1: Board = Board(position: toWinEasyPosition, turn: .X, lastMove: 8) let answer1 = findBestMove(testBoard1) print(answer1) // must block O's win let toBlockPosition: [Piece] = [.X, .E, .E, .E, .E, .O, .E, .X, .O] let testBoard2: Board = Board(position: toBlockPosition, turn: .X, lastMove: 8) let answer2 = findBestMove(testBoard2) print(answer2) // find the best move to win in 2 moves let toWinHardPosition: [Piece] = [.X, .E, .E, .E, .E, .O, .O, .X, .E] let testBoard3: Board = Board(position: toWinHardPosition, turn: .X, lastMove: 6) let answer3 = findBestMove(testBoard3) print(answer3) //: [Next](@next)
apache-2.0
730e831e2814e7249714cfe2d75b8966
38.117264
255
0.601632
3.852743
false
false
false
false
taktamur/followKeyboardView
viewWithKeyboard/ViewController.swift
1
5746
// // ViewController.swift // viewWithKeyboard // // Created by 田村孝文 on 2015/08/24. // Copyright (c) 2015年 田村孝文. All rights reserved. // /* 前提: - Storyboard+AutoLayoutで配置 - キーボード追従するViewの下側に制約を配置し、この制約をアニメーションさせる。 ポイント: - キーボードの表示/非表示は、NSNotificationCenterでUIKeyboardWill{Show|Hide}Notification を監視すれば良い。 - Notificationの監視は、「ViewControllerが表示されている時」だけにするのが良い。他の画面でのキーボード表示に反応してしまう場合があるから - Notificationには「キーボード表示アニメーションの時間」と「どの位置にキーボードが表示されるのか」の情報がuserInfoに含まれるので、それを使ってAutoLayoutの制約の値をアニメーションで変化させる - AutoLayoutの制約をアニメーションさせるには、制約の値を書き換えた後、UIView.animationでlayoutIfNeed()を呼び出す - タブバーが表示されているかどうかを考慮する必要がある。ViewControllerのbottomLayoutGuide.lengthでタブバーの高さが取れるので、これを使う - もしも「テーブルビューで」これを行う場合には、UITableViewControllerは使えない。これはキーボード追従するViewを、「画面下に貼り付ける」というStoryboardが作れないから。 */ import UIKit class ViewController: UIViewController { @IBOutlet weak var textView: UITextView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.startObserveKeyboardNotification() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.stopOberveKeyboardNotification() } /** キーボードを閉じるIBAction */ @IBAction func tapView(sender: AnyObject) { self.textView.resignFirstResponder() } } /** キーボード追従に関連する処理をまとめたextenstion */ extension ViewController{ /** キーボードのNotificationを購読開始 */ func startObserveKeyboardNotification(){ let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector:"willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector:"willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil) } /** キーボードのNotificationの購読停止 */ func stopOberveKeyboardNotification(){ let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } /** キーボードが開いたときに呼び出されるメソッド */ func willShowKeyboard(notification:NSNotification){ NSLog("willShowKeyboard called.") let duration = notification.duration() let rect = notification.rect() if let duration=duration,rect=rect { // ここで「self.bottomLayoutGuide.length」を使っている理由: // tabBarの表示/非表示に応じて制約の高さを変えないと、 // viewとキーボードの間にtabBar分の隙間が空いてしまうため、 // ここでtabBar分の高さを計算に含めています。 // - tabBarが表示されていない場合、self.bottomLayoutGuideは0となる // - tabBarが表示されている場合、self.bottomLayoutGuideにはtabBarの高さが入る // layoutIfNeeded()→制約を更新→UIView.animationWithDuration()の中でlayoutIfNeeded() の流れは // 以下を参考にしました。 // http://qiita.com/caesar_cat/items/051cda589afe45255d96 self.view.layoutIfNeeded() self.bottomConstraint.constant=rect.size.height - self.bottomLayoutGuide.length; UIView.animateWithDuration(duration, animations: { () -> Void in self.view.layoutIfNeeded() // ここ、updateConstraint()でも良いのかと思ったけど動かなかった。 }) } } /** キーボードが閉じたときに呼び出されるメソッド */ func willHideKeyboard(notification:NSNotification){ NSLog("willHideKeyboard called.") let duration = notification.duration() if let duration=duration { self.view.layoutIfNeeded() self.bottomConstraint.constant=0 UIView.animateWithDuration(duration,animations: { () -> Void in self.view.layoutIfNeeded() }) } } } /** キーボード表示通知の便利拡張 */ extension NSNotification{ /** 通知から「キーボードの開く時間」を取得 */ func duration()->NSTimeInterval?{ let duration:NSTimeInterval? = self.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double return duration; } /** 通知から「表示されるキーボードの表示位置」を取得 */ func rect()->CGRect?{ let rowRect:NSValue? = self.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue let rect:CGRect? = rowRect?.CGRectValue() return rect } }
mit
c5fd625fe7d01426964559363893e0b0
36.982759
125
0.705402
3.980126
false
false
false
false
64characters/Telephone
UseCases/SystemDefaultingSoundIO.swift
1
1369
// // SystemDefaultingSoundIO.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone 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 Domain public struct SystemDefaultingSoundIO { public let input: Item public let output: Item public let ringtoneOutput: Item public init(input: Item, output: Item, ringtoneOutput: Item) { self.input = input self.output = output self.ringtoneOutput = ringtoneOutput } public init(_ soundIO: SoundIO) { input = Item(soundIO.input) output = Item(soundIO.output) ringtoneOutput = Item(soundIO.ringtoneOutput) } public enum Item { case systemDefault case device(name: String) init(_ device: SystemAudioDevice) { self = device.isNil ? .systemDefault : .device(name: device.name) } } }
gpl-3.0
78fd5fa38f9b5ea3d85a3448e402e110
28.717391
77
0.680322
4.46732
false
false
false
false
benlangmuir/swift
stdlib/public/core/OptionSet.swift
25
15462
//===--- OptionSet.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that presents a mathematical set interface to a bit set. /// /// You use the `OptionSet` protocol to represent bitset types, where /// individual bits represent members of a set. Adopting this protocol in /// your custom types lets you perform set-related operations such as /// membership tests, unions, and intersections on those types. What's more, /// when implemented using specific criteria, adoption of this protocol /// requires no extra work on your part. /// /// When creating an option set, include a `rawValue` property in your type /// declaration. For your type to automatically receive default implementations /// for set-related operations, the `rawValue` property must be of a type that /// conforms to the `FixedWidthInteger` protocol, such as `Int` or `UInt8`. /// Next, create unique options as static properties of your custom type using /// unique powers of two (1, 2, 4, 8, 16, and so forth) for each individual /// property's raw value so that each property can be represented by a single /// bit of the type's raw value. /// /// For example, consider a custom type called `ShippingOptions` that is an /// option set of the possible ways to ship a customer's purchase. /// `ShippingOptions` includes a `rawValue` property of type `Int` that stores /// the bit mask of available shipping options. The static members `nextDay`, /// `secondDay`, `priority`, and `standard` are unique, individual options. /// /// struct ShippingOptions: OptionSet { /// let rawValue: Int /// /// static let nextDay = ShippingOptions(rawValue: 1 << 0) /// static let secondDay = ShippingOptions(rawValue: 1 << 1) /// static let priority = ShippingOptions(rawValue: 1 << 2) /// static let standard = ShippingOptions(rawValue: 1 << 3) /// /// static let express: ShippingOptions = [.nextDay, .secondDay] /// static let all: ShippingOptions = [.express, .priority, .standard] /// } /// /// Declare additional preconfigured option set values as static properties /// initialized with an array literal containing other option values. In the /// example, because the `express` static property is assigned an array /// literal with the `nextDay` and `secondDay` options, it will contain those /// two elements. /// /// Using an Option Set Type /// ======================== /// /// When you need to create an instance of an option set, assign one of the /// type's static members to your variable or constant. Alternatively, to /// create an option set instance with multiple members, assign an array /// literal with multiple static members of the option set. To create an empty /// instance, assign an empty array literal to your variable. /// /// let singleOption: ShippingOptions = .priority /// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority] /// let noOptions: ShippingOptions = [] /// /// Use set-related operations to check for membership and to add or remove /// members from an instance of your custom option set type. The following /// example shows how you can determine free shipping options based on a /// customer's purchase price: /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [] /// if purchasePrice > 50 { /// freeOptions.insert(.priority) /// } /// /// if freeOptions.contains(.priority) { /// print("You've earned free priority shipping!") /// } else { /// print("Add more to your cart for free priority shipping!") /// } /// // Prints "You've earned free priority shipping!" public protocol OptionSet: SetAlgebra, RawRepresentable { // We can't constrain the associated Element type to be the same as // Self, but we can do almost as well with a default and a // constrained extension /// The element type of the option set. /// /// To inherit all the default implementations from the `OptionSet` protocol, /// the `Element` type must be `Self`, the default. associatedtype Element = Self // FIXME: This initializer should just be the failable init from // RawRepresentable. Unfortunately, current language limitations // that prevent non-failable initializers from forwarding to // failable ones would prevent us from generating the non-failing // default (zero-argument) initializer. Since OptionSet's main // purpose is to create convenient conformances to SetAlgebra, // we opt for a non-failable initializer. /// Creates a new option set from the given raw value. /// /// This initializer always succeeds, even if the value passed as `rawValue` /// exceeds the static properties declared as part of the option set. This /// example creates an instance of `ShippingOptions` with a raw value beyond /// the highest element, with a bit mask that effectively contains all the /// declared static members. /// /// let extraOptions = ShippingOptions(rawValue: 255) /// print(extraOptions.isStrictSuperset(of: .all)) /// // Prints "true" /// /// - Parameter rawValue: The raw value of the option set to create. Each bit /// of `rawValue` potentially represents an element of the option set, /// though raw values may include bits that are not defined as distinct /// values of the `OptionSet` type. init(rawValue: RawValue) } /// `OptionSet` requirements for which default implementations /// are supplied. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet { /// Returns a new option set of the elements contained in this set, in the /// given set, or in both. /// /// This example uses the `union(_:)` method to add two more shipping options /// to the default set. /// /// let defaultShipping = ShippingOptions.standard /// let memberShipping = defaultShipping.union([.secondDay, .priority]) /// print(memberShipping.contains(.priority)) /// // Prints "true" /// /// - Parameter other: An option set. /// - Returns: A new option set made up of the elements contained in this /// set, in `other`, or in both. @inlinable // generic-performance public func union(_ other: Self) -> Self { var r: Self = Self(rawValue: self.rawValue) r.formUnion(other) return r } /// Returns a new option set with only the elements contained in both this /// set and the given set. /// /// This example uses the `intersection(_:)` method to limit the available /// shipping options to what can be used with a PO Box destination. /// /// // Can only ship standard or priority to PO Boxes /// let poboxShipping: ShippingOptions = [.standard, .priority] /// let memberShipping: ShippingOptions = /// [.standard, .priority, .secondDay] /// /// let availableOptions = memberShipping.intersection(poboxShipping) /// print(availableOptions.contains(.priority)) /// // Prints "true" /// print(availableOptions.contains(.secondDay)) /// // Prints "false" /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in both this /// set and `other`. @inlinable // generic-performance public func intersection(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formIntersection(other) return r } /// Returns a new option set with the elements contained in this set or in /// the given set, but not in both. /// /// - Parameter other: An option set. /// - Returns: A new option set with only the elements contained in either /// this set or `other`, but not in both. @inlinable // generic-performance public func symmetricDifference(_ other: Self) -> Self { var r = Self(rawValue: self.rawValue) r.formSymmetricDifference(other) return r } } /// `OptionSet` requirements for which default implementations are /// supplied when `Element == Self`, which is the default. /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where Element == Self { /// Returns a Boolean value that indicates whether a given element is a /// member of the option set. /// /// This example uses the `contains(_:)` method to check whether next-day /// shipping is in the `availableOptions` instance. /// /// let availableOptions = ShippingOptions.express /// if availableOptions.contains(.nextDay) { /// print("Next day shipping available") /// } /// // Prints "Next day shipping available" /// /// - Parameter member: The element to look for in the option set. /// - Returns: `true` if the option set contains `member`; otherwise, /// `false`. @inlinable // generic-performance public func contains(_ member: Self) -> Bool { return self.isSuperset(of: member) } /// Adds the given element to the option set if it is not already a member. /// /// In the following example, the `.secondDay` shipping option is added to /// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For /// the `ShippingOptions` declaration, see the `OptionSet` protocol /// discussion. /// /// let purchasePrice = 87.55 /// /// var freeOptions: ShippingOptions = [.standard, .priority] /// if purchasePrice > 50 { /// freeOptions.insert(.secondDay) /// } /// print(freeOptions.contains(.secondDay)) /// // Prints "true" /// /// - Parameter newMember: The element to insert. /// - Returns: `(true, newMember)` if `newMember` was not contained in /// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is /// the member of the set equal to `newMember`. @inlinable // generic-performance @discardableResult public mutating func insert( _ newMember: Element ) -> (inserted: Bool, memberAfterInsert: Element) { let oldMember = self.intersection(newMember) let shouldInsert = oldMember != newMember let result = ( inserted: shouldInsert, memberAfterInsert: shouldInsert ? newMember : oldMember) if shouldInsert { self.formUnion(newMember) } return result } /// Removes the given element and all elements subsumed by it. /// /// In the following example, the `.priority` shipping option is removed from /// the `options` option set. Attempting to remove the same shipping option /// a second time results in `nil`, because `options` no longer contains /// `.priority` as a member. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let priorityOption = options.remove(.priority) /// print(priorityOption == .priority) /// // Prints "true" /// /// print(options.remove(.priority)) /// // Prints "nil" /// /// In the next example, the `.express` element is passed to `remove(_:)`. /// Although `.express` is not a member of `options`, `.express` subsumes /// the remaining `.secondDay` element of the option set. Therefore, /// `options` is emptied and the intersection between `.express` and /// `options` is returned. /// /// let expressOption = options.remove(.express) /// print(expressOption == .express) /// // Prints "false" /// print(expressOption == .secondDay) /// // Prints "true" /// /// - Parameter member: The element of the set to remove. /// - Returns: The intersection of `[member]` and the set, if the /// intersection was nonempty; otherwise, `nil`. @inlinable // generic-performance @discardableResult public mutating func remove(_ member: Element) -> Element? { let intersectionElements = intersection(member) guard !intersectionElements.isEmpty else { return nil } self.subtract(member) return intersectionElements } /// Inserts the given element into the set. /// /// If `newMember` is not contained in the set but subsumes current members /// of the set, the subsumed members are returned. /// /// var options: ShippingOptions = [.secondDay, .priority] /// let replaced = options.update(with: .express) /// print(replaced == .secondDay) /// // Prints "true" /// /// - Returns: The intersection of `[newMember]` and the set if the /// intersection was nonempty; otherwise, `nil`. @inlinable // generic-performance @discardableResult public mutating func update(with newMember: Element) -> Element? { let r = self.intersection(newMember) self.formUnion(newMember) return r.isEmpty ? nil : r } } /// `OptionSet` requirements for which default implementations are /// supplied when `RawValue` conforms to `FixedWidthInteger`, /// which is the usual case. Each distinct bit of an option set's /// `.rawValue` corresponds to a disjoint value of the `OptionSet`. /// /// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s /// - `intersection` is implemented as a bitwise "and" (`&`) of /// `rawValue`s /// - `symmetricDifference` is implemented as a bitwise "exclusive or" /// (`^`) of `rawValue`s /// /// - Note: A type conforming to `OptionSet` can implement any of /// these initializers or methods, and those implementations will be /// used in lieu of these defaults. extension OptionSet where RawValue: FixedWidthInteger { /// Creates an empty option set. /// /// This initializer creates an option set with a raw value of zero. @inlinable // generic-performance public init() { self.init(rawValue: 0) } /// Inserts the elements of another set into this option set. /// /// This method is implemented as a `|` (bitwise OR) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formUnion(_ other: Self) { self = Self(rawValue: self.rawValue | other.rawValue) } /// Removes all elements of this option set that are not /// also present in the given set. /// /// This method is implemented as a `&` (bitwise AND) operation on the /// two sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formIntersection(_ other: Self) { self = Self(rawValue: self.rawValue & other.rawValue) } /// Replaces this set with a new set containing all elements /// contained in either this set or the given set, but not in both. /// /// This method is implemented as a `^` (bitwise XOR) operation on the two /// sets' raw values. /// /// - Parameter other: An option set. @inlinable // generic-performance public mutating func formSymmetricDifference(_ other: Self) { self = Self(rawValue: self.rawValue ^ other.rawValue) } }
apache-2.0
5e24becd375abbaf0a9855ddc9f55960
40.12234
80
0.668219
4.432913
false
false
false
false
marcelganczak/swift-js-transpiler
test/binary-expression/custom-operators.swift
1
1412
prefix operator +++ infix operator +-: AdditionPrecedence struct Vector2D { var x = 0, y = 0 static func + (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y + right.y) } static prefix func - (vector: Vector2D) -> Vector2D { return Vector2D(x: -vector.x, y: -vector.y) } static func += (left: inout Vector2D, right: Vector2D) { left = left + right } static prefix func +++ (vector: inout Vector2D) -> Vector2D { vector += vector return vector } static func +- (left: Vector2D, right: Vector2D) -> Vector2D { return Vector2D(x: left.x + right.x, y: left.y - right.y) } } let vector = Vector2D(x: 3, y: 1) let anotherVector = Vector2D(x: 2, y: 4) let combinedVector = vector + anotherVector print(combinedVector.x) print(combinedVector.y) let inverseCombinedVector = -combinedVector print(inverseCombinedVector.x) print(inverseCombinedVector.y) var original = Vector2D(x: 1, y: 2) let vectorToAdd = Vector2D(x: 3, y: 4) original += vectorToAdd print(original.x) print(original.y) var toBeDoubled = Vector2D(x: 1, y: 4) let afterDoubling = +++toBeDoubled print(afterDoubling.x) print(afterDoubling.y) let firstVector = Vector2D(x: 1, y: 2) let secondVector = Vector2D(x: 3, y: 4) let plusMinusVector = firstVector +- secondVector print(plusMinusVector.x) print(plusMinusVector.y)
mit
4dd3fa0d87cec550fae2f9f9cf8db5c6
31.860465
66
0.677054
3.069565
false
false
false
false
trifl/TKit
Pod/Classes/TKTimer.swift
1
1395
import Foundation open class TKTimer { open var fps = 60.0 fileprivate var initialDate: Date! fileprivate var timer = Timer() fileprivate var timeFunction: ((Double) -> Bool)? fileprivate var duration = 0.0 fileprivate var usesDuration = false public init(fps: Double) { self.fps = fps } open func fire(_ function:@escaping (_ time: Double) -> Bool) { fire(function, duration: 0) usesDuration = false } open func fire(_ function:@escaping (_ time: Double) -> Bool, duration: TimeInterval) { invalidate() timeFunction = function initialDate = Date() self.duration = duration timer = Timer.scheduledTimer( timeInterval: 1.0 / fps, target: self, selector: Selector(("fireTimeFunction")), userInfo: nil, repeats: true ) } open func invalidate() { timer.invalidate() duration = 0.0 usesDuration = true } fileprivate func fireTimeFunction() { if let timeFunction = timeFunction { var time = Date().timeIntervalSince(initialDate) // This makes sure it always ends at duration where you are intending it to end, unless // explicitly stopped if usesDuration { time = min(time, duration) } let stop = !timeFunction(time) if stop || (usesDuration && time == duration) { invalidate() } } } }
mit
d879c3e8fc8eac61da91a6a4c8e6ed1f
23.473684
93
0.622939
4.471154
false
false
false
false
steelwheels/KiwiControls
UnitTest/OSX/UTTerminal/TerminalViewController.swift
1
3341
/* * @file TerminalViewController.swift * @brief Define TerminalViewController class * @par Copyright * Copyright (C) 2020 Steel Wheels Project */ import KiwiControls import CoconutData import CoconutShell import Foundation open class UTShellThread: CNShellThread { public var terminalView: KCTerminalView? = nil open override func execute(command cmd: String) { #if false CNExecuteInMainThread(doSync: true, execute: { () -> Void in if let view = self.terminalView { let offset = view.verticalOffset() self.console.print(string: "vOffset = \(offset)\n") } }) #endif } } public class TerminalViewController: KCSingleViewController { private var mTerminalView: KCTerminalView? = nil private var mShell: UTShellThread? = nil open override func loadContext() -> KCView? { let termview = KCTerminalView() /* Allocate shell */ CNLog(logLevel: .detail, message: "Launch terminal") let procmgr : CNProcessManager = CNProcessManager() let infile : CNFile = termview.inputFile let outfile : CNFile = termview.outputFile let errfile : CNFile = termview.errorFile let terminfo = CNTerminalInfo(width: 80, height: 25) let environment = CNEnvironment() CNLog(logLevel: .detail, message: "Allocate shell") let shell = UTShellThread(processManager: procmgr, input: infile, output: outfile, error: errfile, terminalInfo: terminfo, environment: environment) mShell = shell shell.terminalView = termview mTerminalView = termview #if true let box = KCStackView() box.axis = .vertical box.addArrangedSubView(subView: termview) return box #else return termview #endif } public override func viewDidAppear() { super.viewDidAppear() guard let termview = mTerminalView else { CNLog(logLevel: .error, message: "No terminal view") return } /* Start shell */ if let shell = mShell { CNLog(logLevel: .detail, message: "Start shell") shell.start(argument: .nullValue) } /* Receive key input */ let infile = termview.inputFile let outfile = termview.outputFile let errfile = termview.errorFile /* Print to output */ let red = CNEscapeCode.foregroundColor(CNColor.red).encode() outfile.put(string: red + "Red\n") let blue = CNEscapeCode.foregroundColor(CNColor.blue).encode() outfile.put(string: blue + "Blue\n") let green = CNEscapeCode.foregroundColor(CNColor.green).encode() outfile.put(string: green + "Green\n") let reset = CNEscapeCode.resetCharacterAttribute.encode() let under = CNEscapeCode.underlineCharacter(true).encode() outfile.put(string: reset + under + "Underline\n") let bold = CNEscapeCode.boldCharacter(true).encode() outfile.put(string: bold + "Bold\n" + reset) let terminfo = termview.terminalInfo //let width = terminfo.width //let height = terminfo.height let console = CNFileConsole(input: infile, output: outfile, error: errfile) let curses = CNCurses(console: console, terminalInfo: terminfo) curses.begin() curses.fill(x: 0, y: 0, width: terminfo.width, height: terminfo.height, char: "x") /* for i in 0..<10 { curses.moveTo(x: i, y: i) curses.put(string: "o") } for x in 0..<width { curses.moveTo(x: x, y: 0) console.print(string: "+") curses.moveTo(x: x, y: height-1) console.print(string: "+") }*/ } }
lgpl-2.1
a4f09c20bdb8731ba53a75fc9e9b616a
27.07563
154
0.701586
3.451446
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAProfileInfoForm.swift
1
14551
// // SBARegistrationForm.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. 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 the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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 ResearchKit public enum SBAProfileInfoOption : String { case email = "email" case password = "password" case externalID = "externalID" case name = "name" case birthdate = "birthdate" case gender = "gender" } enum SBAProfileInfoOptionsError: Error { case missingRequiredOptions case missingEmail case missingExternalID case missingName case notConsented case unrecognizedSurveyItemType } struct SBAExternalIDOptions { static let defaultAutocapitalizationType: UITextAutocapitalizationType = .allCharacters static let defaultKeyboardType: UIKeyboardType = .asciiCapable let autocapitalizationType: UITextAutocapitalizationType let keyboardType: UIKeyboardType init() { self.autocapitalizationType = SBAExternalIDOptions.defaultAutocapitalizationType self.keyboardType = SBAExternalIDOptions.defaultKeyboardType } init(autocapitalizationType: UITextAutocapitalizationType, keyboardType: UIKeyboardType) { self.autocapitalizationType = autocapitalizationType self.keyboardType = keyboardType } init(options: [AnyHashable: Any]?) { self.autocapitalizationType = { if let autocap = options?["autocapitalizationType"] as? String { return UITextAutocapitalizationType(key: autocap) } else { return SBAExternalIDOptions.defaultAutocapitalizationType } }() self.keyboardType = { if let keyboard = options?["keyboardType"] as? String { return UIKeyboardType(key: keyboard) } else { return SBAExternalIDOptions.defaultKeyboardType } }() } } public struct SBAProfileInfoOptions { public let includes: [SBAProfileInfoOption] public let customOptions: [Any] let externalIDOptions: SBAExternalIDOptions public init(includes: [SBAProfileInfoOption]) { self.includes = includes self.externalIDOptions = SBAExternalIDOptions() self.customOptions = [] } init(externalIDOptions: SBAExternalIDOptions) { self.includes = [.externalID] self.externalIDOptions = externalIDOptions self.customOptions = [] } public init?(inputItem: SBASurveyItem?) { guard let surveyForm = inputItem as? SBAFormStepSurveyItem, let items = surveyForm.items else { return nil } // Map the includes, and if it is an external ID then also map the keyboard options var externalIDOptions = SBAExternalIDOptions(autocapitalizationType: .none, keyboardType: .default) var customOptions: [Any] = [] self.includes = items.mapAndFilter({ (obj) -> SBAProfileInfoOption? in if let str = obj as? String { return SBAProfileInfoOption(rawValue: str) } else if let dictionary = obj as? [String : AnyObject], let identifier = dictionary["identifier"] as? String, let option = SBAProfileInfoOption(rawValue: identifier) { if option == .externalID { externalIDOptions = SBAExternalIDOptions(options: dictionary) } return option } else { customOptions.append(obj) } return nil }) self.externalIDOptions = externalIDOptions self.customOptions = customOptions } func makeFormItems(surveyItemType: SBASurveyItemType) -> [ORKFormItem] { var formItems: [ORKFormItem] = [] for option in self.includes { switch option { case .email: let formItem = makeEmailFormItem(option) formItems.append(formItem) case .password: let (formItem, answerFormat) = makePasswordFormItem(option) formItems.append(formItem) // confirmation if (surveyItemType == .account(.registration)) { let confirmFormItem = makeConfirmationFormItem(formItem, answerFormat: answerFormat) formItems.append(confirmFormItem) } case .externalID: let formItem = makeExternalIDFormItem(option) formItems.append(formItem) case .name: let formItem = makeNameFormItem(option) formItems.append(formItem) case .birthdate: let formItem = makeBirthdateFormItem(option) formItems.append(formItem) case .gender: let formItem = makeGenderFormItem(option) formItems.append(formItem) } } return formItems } func makeEmailFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.emailAnswerFormat() let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("EMAIL_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("EMAIL_FORM_ITEM_PLACEHOLDER") return formItem } func makePasswordFormItem(_ option: SBAProfileInfoOption) -> (ORKFormItem, ORKTextAnswerFormat) { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.isSecureTextEntry = true answerFormat.autocapitalizationType = .none answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("PASSWORD_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("PASSWORD_FORM_ITEM_PLACEHOLDER") return (formItem, answerFormat) } func makeConfirmationFormItem(_ formItem: ORKFormItem, answerFormat: ORKTextAnswerFormat) -> ORKFormItem { // If this is a registration, go ahead and set the default password verification let minLength = SBARegistrationStep.defaultPasswordMinLength let maxLength = SBARegistrationStep.defaultPasswordMaxLength answerFormat.validationRegex = "[[:ascii:]]{\(minLength),\(maxLength)}" answerFormat.invalidMessage = Localization.localizedStringWithFormatKey("SBA_REGISTRATION_INVALID_PASSWORD_LENGTH_%@_TO_%@", NSNumber(value: minLength), NSNumber(value: maxLength)) // Add a confirmation field let confirmIdentifier = SBARegistrationStep.confirmationIdentifier let confirmText = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_TITLE") let confirmError = Localization.localizedString("CONFIRM_PASSWORD_ERROR_MESSAGE") let confirmFormItem = formItem.confirmationAnswer(withIdentifier: confirmIdentifier, text: confirmText, errorMessage: confirmError) confirmFormItem.placeholder = Localization.localizedString("CONFIRM_PASSWORD_FORM_ITEM_PLACEHOLDER") return confirmFormItem } func makeExternalIDFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = self.externalIDOptions.autocapitalizationType answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = self.externalIDOptions.keyboardType let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_EXTERNALID_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_EXTERNALID_PLACEHOLDER") return formItem } func makeNameFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let answerFormat = ORKAnswerFormat.textAnswerFormat() answerFormat.multipleLines = false answerFormat.autocapitalizationType = .words answerFormat.autocorrectionType = .no answerFormat.spellCheckingType = .no answerFormat.keyboardType = .default let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("SBA_REGISTRATION_FULLNAME_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("SBA_REGISTRATION_FULLNAME_PLACEHOLDER") return formItem } func makeBirthdateFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { // Calculate default date (20 years old). let defaultDate = (Calendar.current as NSCalendar).date(byAdding: .year, value: -20, to: Date(), options: NSCalendar.Options(rawValue: 0)) let answerFormat = ORKAnswerFormat.dateAnswerFormat(withDefaultDate: defaultDate, minimumDate: nil, maximumDate: Date(), calendar: Calendar.current) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("DOB_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("DOB_FORM_ITEM_PLACEHOLDER") return formItem } func makeGenderFormItem(_ option: SBAProfileInfoOption) -> ORKFormItem { let textChoices: [ORKTextChoice] = [ ORKTextChoice(text: Localization.localizedString("GENDER_FEMALE"), value: HKBiologicalSex.female.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_MALE"), value: HKBiologicalSex.male.rawValue as NSNumber), ORKTextChoice(text: Localization.localizedString("GENDER_OTHER"), value: HKBiologicalSex.other.rawValue as NSNumber), ] let answerFormat = ORKValuePickerAnswerFormat(textChoices: textChoices) let formItem = ORKFormItem(identifier: option.rawValue, text: Localization.localizedString("GENDER_FORM_ITEM_TITLE"), answerFormat: answerFormat, optional: false) formItem.placeholder = Localization.localizedString("GENDER_FORM_ITEM_PLACEHOLDER") return formItem } } public protocol SBAFormProtocol : class { var identifier: String { get } var title: String? { get set } var text: String? { get set } var formItems: [ORKFormItem]? { get set } init(identifier: String) } extension SBAFormProtocol { public func formItemForIdentifier(_ identifier: String) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == identifier }) } } extension ORKFormStep: SBAFormProtocol { } public protocol SBAProfileInfoForm : SBAFormProtocol { var surveyItemType: SBASurveyItemType { get } func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] } extension SBAProfileInfoForm { public var options: [SBAProfileInfoOption]? { return self.formItems?.mapAndFilter({ SBAProfileInfoOption(rawValue: $0.identifier) }) } public func formItemForProfileInfoOption(_ profileInfoOption: SBAProfileInfoOption) -> ORKFormItem? { return self.formItems?.find({ $0.identifier == profileInfoOption.rawValue }) } func commonInit(_ inputItem: SBASurveyItem?) { self.title = inputItem?.stepTitle self.text = inputItem?.stepText if let formStep = self as? ORKFormStep { formStep.footnote = inputItem?.stepFootnote } let options = SBAProfileInfoOptions(inputItem: inputItem) ?? SBAProfileInfoOptions(includes: defaultOptions(inputItem)) self.formItems = options.makeFormItems(surveyItemType: self.surveyItemType) } }
bsd-3-clause
1ea61a9ffd2516c172356b59b5b44c20
42.562874
188
0.645704
5.895462
false
false
false
false
i-schuetz/SwiftCharts
Examples/Examples/NotificationsExample.swift
1
6128
// // NotificationsExample.swift // SwiftCharts // // Created by ischuetz on 04/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit import SwiftCharts class NotificationsExample: UIViewController { fileprivate var chart: Chart? // arc override func viewDidLoad() { super.viewDidLoad() let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont) let chartPoints: [ChartPoint] = [(1, 3), (2, 4), (4, 1), (5, 6), (6, 4), (7, 9), (8, 0), (10, 4), (12, 2)].map{ChartPoint(x: ChartAxisValueInt($0.0, labelSettings: labelSettings), y: ChartAxisValueInt($0.1))} let xValues = chartPoints.map{$0.x} let yValues = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false) let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.red, animDuration: 1, animDelay: 0) let notificationViewWidth: CGFloat = Env.iPad ? 30 : 20 let notificationViewHeight: CGFloat = Env.iPad ? 30 : 20 let notificationGenerator = {[weak self] (chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in let (chartPoint, screenLoc) = (chartPointModel.chartPoint, chartPointModel.screenLoc) if chartPoint.y.scalar <= 1 { let chartPointView = HandlingView(frame: CGRect(x: screenLoc.x + 5, y: screenLoc.y - notificationViewHeight - 5, width: notificationViewWidth, height: notificationViewHeight)) let label = UILabel(frame: chartPointView.bounds) label.layer.cornerRadius = Env.iPad ? 15 : 10 label.clipsToBounds = true label.backgroundColor = UIColor.red label.textColor = UIColor.white label.textAlignment = NSTextAlignment.center label.font = UIFont.boldSystemFont(ofSize: Env.iPad ? 22 : 18) label.text = "!" chartPointView.addSubview(label) label.transform = CGAffineTransform(scaleX: 0, y: 0) chartPointView.movedToSuperViewHandler = { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIView.AnimationOptions(), animations: { label.transform = CGAffineTransform(scaleX: 1, y: 1) }, completion: nil) } chartPointView.touchHandler = { let title = "Lorem" let message = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua." let ok = "Ok" if #available(iOS 8.0, *) { let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: ok, style: UIAlertAction.Style.default, handler: nil)) self!.present(alert, animated: true, completion: nil) } else { let alert = UIAlertView() alert.title = title alert.message = message alert.addButton(withTitle: ok) alert.show() } } return chartPointView } return nil } let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings)) let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())) let chartFrame = ExamplesDefaults.chartFrame(view.bounds) let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel) let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame) let chartPointsNotificationsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: chartPoints, viewGenerator: notificationGenerator, displayDelay: 1, mode: .custom) // To preserve the offset of the notification views from the chart point they represent, during transforms, we need to pass mode: .custom along with this custom transformer. chartPointsNotificationsLayer.customTransformer = {(model, view, layer) -> Void in let screenLoc = layer.modelLocToScreenLoc(x: model.chartPoint.x.scalar, y: model.chartPoint.y.scalar) view.frame.origin = CGPoint(x: screenLoc.x + 5, y: screenLoc.y - notificationViewHeight - 5) } let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel]) let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth) let guidelinesLayer = ChartGuideLinesDottedLayer(xAxisLayer: xAxisLayer, yAxisLayer: yAxisLayer, settings: settings) let chart = Chart( frame: chartFrame, innerFrame: innerFrame, settings: chartSettings, layers: [ xAxisLayer, yAxisLayer, guidelinesLayer, chartPointsLineLayer, chartPointsNotificationsLayer] ) view.addSubview(chart.view) self.chart = chart } }
apache-2.0
b7bcaee45e13fc1d6cbfa36823aa17a0
52.286957
265
0.620757
5.565849
false
false
false
false
saagarjha/Swimat
CLI/OptionParser.swift
2
3520
import Foundation struct Option { let options: [String] let helpArguments: String let helpText: String let number: Int let setter: ([String]) -> Void } class Options { static var shared = Options() var recursive = false var verbose = false init() { Indent.char = "\t" } static let options: [Option] = [ Option(options: ["-h", "--help"], helpArguments: "", helpText: "Display this help message.", number: 0, setter: { _ in printHeader() printOptions() exit(.success) }), Option(options: ["-i", "--indent"], helpArguments: "<value>=-1", helpText: "Set the number of spaces to indent; use -1 for tabs.", number: 1, setter: { indentSize in guard indentSize.count == 1, let indentSize = Int(indentSize[0]) else { printToError("Invalid indent size") exit(.invalidIndent) } if indentSize < 0 { Indent.char = "\t" } else { Indent.char = String(repeating: " ", count: indentSize) } }), Option(options: ["-r", "--recursive"], helpArguments: "", helpText: "Search and format directories recursively.", number: 0, setter: { _ in shared.recursive = true }), Option(options: ["-v", "--verbose"], helpArguments: "", helpText: "Enable verbose output.", number: 0, setter: { _ in shared.verbose = true }) ] static func printHeader() { printToError("The Swimat Swift formatter") printToError() printToError("USAGE: swimat [options] <inputs...>") printToError() printToError("OPTIONS:") } static func printOptions() { for option in options { let optionsString = " \(option.options.joined(separator: ", ")) \(option.helpArguments)" .padding(toLength: 25, withPad: " ", startingAt: 0) printToError("\(optionsString)\(option.helpText)") } } func parseArguments(_ arguments: [String]) -> [String] { if arguments.isEmpty { Options.printHeader() Options.printOptions() exit(.noArguments) } var files = [String]() var i = 0 while i < arguments.count { let argument = arguments[i] i += 1 if argument.hasPrefix("-") { var validOption = false for option in Options.options { if option.options.contains(argument) { let startIndex = min(i, arguments.count) let endIndex = min(i + option.number, arguments.count) option.setter(Array(arguments[startIndex..<endIndex])) i = endIndex validOption = true } } if !validOption { printToError("Invalid option \(argument). Valid options are:") Options.printOptions() exit(.invalidOption) } } else { files.append(argument) } } return files } }
mit
ebba5bbc9d934204f698f7d860ca781b
29.608696
100
0.471591
5.285285
false
false
false
false
muvetian/acquaintest00
ChatRoom/ChatRoom/LoginController+handlers.swift
1
3925
// // LoginController+handlers.swift // ChatRoom // // Created by Binwei Xu on 3/23/17. // Copyright © 2017 Binwei Xu. All rights reserved. // import UIKit import Firebase extension LoginController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func handleRegister() { guard let email = emailTextField.text, let password = passwordTextField.text, let name = nameTextField.text else { print("Form is not valid") return } FIRAuth.auth()?.createUser(withEmail: email, password: password, completion: { (user: FIRUser?, error) in if error != nil { print(error) return } guard let uid = user?.uid else { return } // upload image to firebase storage using the reference let imageName = NSUUID().uuidString //gives a unique string // add more child directory to reconstruct the storage space let storageRef = FIRStorage.storage().reference().child("profile_images").child("\(imageName).png") if let profileImage = self.profileImageView.image, let uploadData = UIImageJPEGRepresentation(profileImage, 0.1) { storageRef.put(uploadData, metadata: nil, completion: { (metadata, error) in //metadata is description of the data uploaded if error != nil { print(error) return } if let profileImageUrl = metadata?.downloadURL()?.absoluteString { let values = ["name": name, "email": email, "profileImageUrl": profileImageUrl] self.registerUserIntoDatabaseWithUID(uid: uid, values: values) } }) } }) } private func registerUserIntoDatabaseWithUID(uid : String, values: [String: Any]) { //successfully authenticated user let ref = FIRDatabase.database().reference(fromURL: "https://chatroom-29e51.firebaseio.com/") let usersReference = ref.child("users").child(uid) usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in if err != nil { print(err) return } //update nav bar title let user = User() //this setter potentially crash if keys don't match the model User's user.setValuesForKeys(values) self.messagesController?.setupNavBarWithUser(user: user) self.dismiss(animated: true, completion: nil) }) } func handleSelectProfileImage() { let picker = UIImagePickerController() picker.delegate = self picker.allowsEditing = true present(picker, animated: true, completion: nil) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { var selectedImageFromPicker: UIImage? if let editedImage = info["UIImagePickerControllerEditedImage"] as? UIImage { selectedImageFromPicker = editedImage } else if let originalImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { selectedImageFromPicker = originalImage } if let selectedImage = selectedImageFromPicker { profileImageView.image = selectedImage } dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } }
mit
cf15e56557ff49a68e500c61fdc8ceec
34.672727
126
0.567533
5.856716
false
false
false
false
dmegahan/Destiny.gg-for-iOS
Destiny.gg/iphoneViewController.swift
1
13333
// // ViewController.swift // Destiny.gg // // Created by Daniel Megahan on 1/31/16. // Copyright © 2016 Daniel Megahan. All rights reserved. // import UIKit import WebKit //inherit from UIWebViewDelegate so we can track when the webviews have loaded/not loaded class iphoneViewController: UIViewController, UIWebViewDelegate { @IBOutlet var myChatWebView: WKWebView! @IBOutlet var myStreamWebView: UIWebView! //When a double tap gesture is done, this will be used to determine how we should change the chat and stream frames var isChatFullScreen = true; var defaultPortraitChatFrame = CGRect.null; var defaultPortraitStreamFrame = CGRect.null; override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //set up the gesture recognition /* these aren't currently being used, but we might want ot use them later let swipeDown = UISwipeGestureRecognizer(target: self, action: "OnSwipeGesture:"); swipeDown.direction = UISwipeGestureRecognizerDirection.Down; self.view.addGestureRecognizer(swipeDown); let swipeUp = UISwipeGestureRecognizer(target: self, action: "OnSwipeGesture:") swipeUp.direction = UISwipeGestureRecognizerDirection.Up; self.view.addGestureRecognizer(swipeUp); let doubleTap = UITapGestureRecognizer(target: self, action: "OnDoubleTapGesture:"); doubleTap.numberOfTapsRequired = 2; doubleTap.numberOfTouchesRequired = 2; view.addGestureRecognizer(doubleTap); */ //let panSwipe = UIPanGestureRecognizer(target: self, action: "OnPanSwipe:"); //self.view.addGestureRecognizer(panSwipe); let streamer = "destiny"; //let streamOnline = RestAPIManager.sharedInstance.isStreamOnline(streamer); self.defaultPortraitChatFrame = self.myChatWebView.frame; self.defaultPortraitStreamFrame = self.myStreamWebView.frame; /* if(streamOnline){ //if online, send request for stream. embedStream(streamer); }else{ embedStream(streamer); //will eventually display splash image and label that says offline } */ //embed chat whether or not stream is online embedChat(); print("We in iphone view control"); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func embedStream(_ streamer : String){ let url = URL(string: "http://player.twitch.tv/?channel=" + streamer); let requestObj = URLRequest(url: url!); myStreamWebView.loadRequest(requestObj); self.myStreamWebView.allowsInlineMediaPlayback = true; //attempt at figuring out inline media playback, apparently just turning the above to true doesnt work //let embeddedHTML = "<video width=\"640\" height=\"360\" id=\"player1\" preload=\"none\" webkit-playsinline><source type=\"video/youtube\" src=\"" + url + "\" /></video>"; //self.myStreamWebView.loadHTMLString(embeddedHTML, baseURL: NSBundle.mainBundle().bundleURL); } func embedChat(){ //chat embed URL let url = URL(string: "https://www.destiny.gg/embed/chat"); let requestObj = URLRequest(url: url!); let connectionObj = NSURLConnection(request: requestObj, delegate: self)! myChatWebView.load(requestObj); } /* func OnDoubleTapGesture(gesture: UIGestureRecognizer) { print("double tap"); if let doubleTapGesture = gesture as? UITapGestureRecognizer{ if(!isChatFullScreen){ //In both portait mode and landscape mode, an up swipe will full screen the caht //when we get an upward swipe, we want to fullscreen the chat //to do this, we move the origin.y up to 0 and change the height to match the screen height let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, 0, myChatWebView.frame.width, UIScreen.mainScreen().bounds.height); myChatWebView.frame = newChatFrame; //change the height of the stream to 0 so it doesnt appear anymore let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, 0); myStreamWebView.frame = newStreamFrame; }else if(isChatFullScreen){ //down swipes have a different function depending on the orientation if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){ //a down swipe in landscape mode will full screen the stream //to do this, we need to adjust the chat origin back to the original, which is //at the bottom of the screen (so we set origin.y to the height of the screen) and make the height of the frame to 0 let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, UIScreen.mainScreen().bounds.height, myChatWebView.frame.width, 0); myChatWebView.frame = newChatFrame; //full screen the stream, set origin to 0 and height to size of screen let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, 0, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height); myStreamWebView.frame = newStreamFrame; }else if(UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)){ //this may change later, but a double tap in portrait mode, with the chat full screened, //will cause the stream to take up half the window. So we're going to change the origin.y to halfway //down the screen for the chat and halve the hieght as well let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, UIScreen.mainScreen().bounds.height/2, myChatWebView.bounds.width, UIScreen.mainScreen().bounds.height/2); myChatWebView.frame = newChatFrame; //stream origin.y stays at 0 but we change the height to half the screen let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height/2) myStreamWebView.frame = newStreamFrame; } } } } //when a swipe is detected, resize the webviews depending on direction func OnSwipeGesture(gesture: UIGestureRecognizer) { print("swipe detected"); if let swipeGesture = gesture as? UISwipeGestureRecognizer{ switch swipeGesture.direction{ case UISwipeGestureRecognizerDirection.Up: //In both portait mode and landscape mode, an up swipe will full screen the caht //when we get an upward swipe, we want to fullscreen the chat //to do this, we move the origin.x up to 0 and change the height to match the screen height let newChatFrame = CGRectMake(0, myChatWebView.frame.origin.y, myChatWebView.frame.width, UIScreen.mainScreen().bounds.height); myChatWebView.frame = newChatFrame; //change the height of the stream to 0 so it doesnt appear anymore let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, 0); myStreamWebView.frame = newStreamFrame; case UISwipeGestureRecognizerDirection.Down: //down swipes have a different function depending on the orientation if(UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)){ //a down swipe in landscape mode will full screen the stream //to do this, we need to adjust the chat origin back to the original, which is //at the bottom of the screen (so we set origin.x to the height of the screen) and make the height of the frame to 0 let newChatFrame = CGRectMake(UIScreen.mainScreen().bounds.height, myChatWebView.frame.origin.y, myChatWebView.frame.width, 0); myChatWebView.frame = newChatFrame; //full screen the stream, set origin to 0 and height to size of screen let newStreamFrame = CGRectMake(0, myStreamWebView.frame.origin.y, myStreamWebView.frame.width, UIScreen.mainScreen().bounds.height); myStreamWebView.frame = newStreamFrame; } myChatWebView.frame = chatDefaultFrame; myStreamWebView.frame = streamDefaultFrame; default: break; } } } func OnPanSwipe(gesture: UIPanGestureRecognizer){ if (gesture.state == UIGestureRecognizerState.Began){ startPanLocation = gesture.translationInView(self.view); }else if (gesture.state == UIGestureRecognizerState.Changed){ let currentPanLocation = gesture.translationInView(self.view) let distanceY = currentPanLocation.y - startPanLocation.y; let newChatFrame = CGRectMake(myChatWebView.frame.origin.x, myChatWebView.frame.origin.y + distanceY, myChatWebView.frame.width, myChatWebView.frame.height - distanceY) //we do a check to determine if the chat will go offscreen (too far up or down). If it will, we don't move it anymore if(myChatWebView.frame.origin.y + distanceY >= 1 && myChatWebView.frame.origin.y + distanceY <= UIScreen.mainScreen().bounds.height){ myChatWebView.frame = newChatFrame; } let newStreamFrame = CGRectMake(myStreamWebView.frame.origin.x, myStreamWebView.frame.origin.y, myStreamWebView.frame.width + distanceY, myStreamWebView.frame.height) //no point in panning the stream if the width + distanceX is smaller than 0 or if the stream > the width of the screen if(myStreamWebView.frame.width + distanceY > -1 && myStreamWebView.frame.width + distanceY <= UIScreen.mainScreen().bounds.width){ myStreamWebView.frame = newStreamFrame; } startPanLocation = currentPanLocation; } } */ override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation){ //were going to do some lazy programming here. We're going to take the web views that we have //and resize them based on the orientation, rather than use a different storyboard if(UIDeviceOrientationIsLandscape(UIDevice.current.orientation)){ //minimize the chat web view and make the stream web view full screen //new chat frame will have a height of 0, and a width to match the screen size (so we can bring it up using //a swipe easily if we want to) //We also construct a new origin.y, so the chat frame is at the bottom of the screen, instead of at the top let newChatFrame = CGRect(x: myChatWebView.frame.origin.x, y: myChatWebView.frame.origin.y + UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: 0); myChatWebView.frame = newChatFrame; //max out the height so it becomes full screened let newStreamFrame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) myStreamWebView.frame = newStreamFrame; isChatFullScreen = false; //unhide it if it is hidden myStreamWebView.isHidden = false; } else if(UIDeviceOrientationIsPortrait(UIDevice.current.orientation)){ print("portraitmode"); //try putting delay on when to resize //set height to 0, we want it to be hidden at the start self.myStreamWebView.frame = self.defaultPortraitStreamFrame; //minimize the stream web view and make the chat web view full screen self.myChatWebView.frame = self.defaultPortraitChatFrame; self.isChatFullScreen = true; //self.myStreamWebView.mediaPlaybackRequiresUserAction = false; //self.myChatWebView.reload(); //self.myChatWebView.reload() //self.myStreamWebView.reload() } } func webView(_ webView: UIWebView, didFailLoadWithError error: Error){ print("Webview fail with error \(error)"); } }
apache-2.0
c6f84e8dbbabadcdc9c2b9cf426ddb47
52.758065
180
0.625938
5.484163
false
false
false
false
jwfriese/FrequentFlyer
FrequentFlyerTests/Jobs/PublicJobsDataStreamSpec.swift
1
3614
import XCTest import Quick import Nimble import RxSwift @testable import FrequentFlyer class PublicJobsDataStreamSpec: QuickSpec { class MockJobsService: JobsService { var capturedPipeline: Pipeline? var capturedConcourseURL: String? var jobsSubject = PublishSubject<[Job]>() override func getPublicJobs(forPipeline pipeline: Pipeline, concourseURL: String) -> Observable<[Job]> { capturedPipeline = pipeline capturedConcourseURL = concourseURL return jobsSubject } } override func spec() { describe("PublicJobsDataStream") { var subject: PublicJobsDataStream! var mockJobsService: MockJobsService! beforeEach { subject = PublicJobsDataStream(concourseURL: "concourseURL") mockJobsService = MockJobsService() subject.jobsService = mockJobsService } describe("Opening a data stream") { var jobSection$: Observable<[JobGroupSection]>! var jobSectionStreamResult: StreamResult<JobGroupSection>! beforeEach { let pipeline = Pipeline(name: "turtle pipeline", isPublic: true, teamName: "turtle team") jobSection$ = subject.open(forPipeline: pipeline) jobSectionStreamResult = StreamResult(jobSection$) } it("calls out to the \(JobsService.self)") { let expectedPipeline = Pipeline(name: "turtle pipeline", isPublic: true, teamName: "turtle team") expect(mockJobsService.capturedPipeline).toEventually(equal(expectedPipeline)) expect(mockJobsService.capturedConcourseURL).toEventually(equal("concourseURL")) } describe("When the \(JobsService.self) resolves with jobs") { var turtleJob: Job! var crabJob: Job! var anotherCrabJob: Job! var puppyJob: Job! beforeEach { let finishedTurtleBuild = BuildBuilder().withStatus(.failed).withEndTime(1000).build() turtleJob = Job(name: "turtle job", nextBuild: nil, finishedBuild: finishedTurtleBuild, groups: ["turtle-group"]) let nextCrabBuild = BuildBuilder().withStatus(.pending).withStartTime(500).build() crabJob = Job(name: "crab job", nextBuild: nextCrabBuild, finishedBuild: nil, groups: ["crab-group"]) let anotherCrabBuild = BuildBuilder().withStatus(.aborted).withStartTime(501).build() anotherCrabJob = Job(name: "another crab job", nextBuild: anotherCrabBuild, finishedBuild: nil, groups: ["crab-group"]) puppyJob = Job(name: "puppy job", nextBuild: nil, finishedBuild: nil, groups: []) mockJobsService.jobsSubject.onNext([turtleJob, crabJob, anotherCrabJob, puppyJob]) mockJobsService.jobsSubject.onCompleted() } it("organizes the jobs into sections by group name and emits them") { expect(jobSectionStreamResult.elements[0].items).to(equal([turtleJob])) expect(jobSectionStreamResult.elements[1].items).to(equal([crabJob, anotherCrabJob])) expect(jobSectionStreamResult.elements[2].items).to(equal([puppyJob])) } } } } } }
apache-2.0
cb8aa97258ad85379cc8f5ada600b7b9
43.073171
143
0.585501
5.56
false
false
false
false
eelstork/Start-Developing-IOS-Apps-Today
ToDoList/ToDoList/TodoListTableViewController.swift
1
1820
import UIKit class TodoListTableViewController:UITableViewController{ var todoItems:[ToDoItem]=[] @IBAction func unwindToList(segue:UIStoryboardSegue) { let source = segue.sourceViewController as AddToDoItemViewController var item = source.toDoItem if(item != nil){ todoItems.append(item!) tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() loadInitialData() } func loadInitialData(){ let item1 = ToDoItem(name: "Buy milk" ) let item2 = ToDoItem(name: "Buy eggs" ) let item3 = ToDoItem(name: "Read a book" ) todoItems.append(item1) todoItems.append(item2) todoItems.append(item3) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoItems.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let cell = tableView.dequeueReusableCellWithIdentifier("ListPrototypeCell", forIndexPath: indexPath) as UITableViewCell let toDoItem = todoItems[indexPath.row] cell.textLabel?.text = toDoItem.itemName if(toDoItem.completed){ cell.accessoryType = UITableViewCellAccessoryType.Checkmark }else{ cell.accessoryType = UITableViewCellAccessoryType.None } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) var tappedItem = todoItems[indexPath.row] tappedItem.completed = !tappedItem.completed tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) } }
cc0-1.0
317e19e00967d3d3eedd374263f7be2b
21.75
121
0.767033
4.292453
false
false
false
false
briceZhao/ZXRefresh
ZXRefreshExample/ZXRefreshExample/Default/DefaultScrollViewController.swift
1
1506
// // DefaultScrollViewController.swift // ZXRefreshExample // // Created by briceZhao on 2017/8/22. // Copyright © 2017年 chengyue. All rights reserved. // import UIKit class DefaultScrollViewController: UIViewController { var scrollView: UIScrollView? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.automaticallyAdjustsScrollViewInsets = false setUpScrollView() self.scrollView?.addRefreshHeaderView { [unowned self] in self.refresh() } self.scrollView?.addLoadMoreFooterView { [unowned self] in self.loadMore() } } func refresh() { perform(#selector(endRefresing), with: nil, afterDelay: 3) } func endRefresing() { self.scrollView?.endRefreshing(isSuccess: true) } func loadMore() { perform(#selector(endLoadMore), with: nil, afterDelay: 3) } func endLoadMore() { self.scrollView?.endLoadMore(isNoMoreData: true) } func setUpScrollView(){ self.scrollView = UIScrollView(frame: CGRect(x: 0,y: 0,width: 300,height: 300)) self.scrollView?.backgroundColor = UIColor.lightGray self.scrollView?.center = self.view.center self.scrollView?.contentSize = CGSize(width: 300,height: 600) self.view.addSubview(self.scrollView!) } }
mit
909804cc2f28611fdcaaa9030017ce52
24.474576
87
0.605456
4.682243
false
false
false
false
Incipia/IncSpinner
IncSpinner/Classes/IncSpinner.swift
1
9017
// // IncipiaSpinner.swift // IncipiaSpinner // // Created by Gregory Klein on 10/25/16. // Copyright © 2016 Incipia. All rights reserved. // import UIKit // TODO: Use this class to wrap the replicator layer private class IncSpinner_PlusingCircleView: UIView { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, circleCount count: Int) { self.init(frame: frame) } } private class IncSpinner_PulsingCircleReplicatorLayer: CAReplicatorLayer { private let _padding: CGFloat = 20 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() } convenience init(circleCount count: Int, circleSize size: CGFloat, circleColor color: UIColor, animationDuration: CFTimeInterval) { self.init() _setupFrame(withCircleCount: CGFloat(count), circleSize: size) let layer = _addShapeLayer(withCircleSize: size, color: color) _addAnimation(toShapeLayer: layer, withDuration: animationDuration) instanceCount = count instanceDelay = animationDuration / CFTimeInterval(count) instanceTransform = CATransform3DMakeTranslation(size + _padding, 0, 0) } private func _setupFrame(withCircleCount count: CGFloat, circleSize size: CGFloat) { frame = CGRect(x: 0, y: 0, width: (size + _padding) * count - _padding, height: size) } private func _addShapeLayer(withCircleSize size: CGFloat, color: UIColor) -> CAShapeLayer { let lineWidth: CGFloat = 4.0 let pathFrame = CGRect(origin: .zero, size: CGSize(width: size, height: size)) let circleLayer = CAShapeLayer() circleLayer.path = UIBezierPath(ovalIn: pathFrame).cgPath circleLayer.frame = pathFrame circleLayer.cornerRadius = size * 0.5 circleLayer.borderWidth = lineWidth circleLayer.borderColor = UIColor(white: 1, alpha: 0.2).cgColor circleLayer.fillColor = color.cgColor circleLayer.opacity = 0 addSublayer(circleLayer) return circleLayer } private func _addAnimation(toShapeLayer layer: CAShapeLayer, withDuration duration: TimeInterval) { let group = CAAnimationGroup() group.animations = [CABasicAnimation.incSpinner_scale, CABasicAnimation.incSpinner_fadeIn] group.duration = duration group.repeatCount = Float.infinity group.autoreverses = true layer.add(group, forKey: nil) } } public class IncSpinner { private static let shared = IncSpinner() public static var pulseDuration: TimeInterval = 0.8 public static var fadeDuration: TimeInterval = 0.8 private weak var container: UIView? private var blurredEffectView: UIVisualEffectView? private var vibrancyEffectView: UIVisualEffectView? private var replicatorLayer: CAReplicatorLayer? private var textLabel: UILabel? private var tapToDismissLabel: UILabel? public class func show(inView view: UIView? = nil, withTitle title: String? = nil, usingFont font: UIFont? = nil, style: UIBlurEffectStyle = .dark, color: UIColor) { let container = view ?? UIApplication.shared.keyWindow guard let unwrappedContainer = container else { return } shared._startUsing(container: unwrappedContainer) let blurredEffectView = shared._addEffectView(toContainer: unwrappedContainer) shared.blurredEffectView = blurredEffectView let layer = shared._addSpinnerLayer(to: blurredEffectView.contentView, withCircleColor: color, pulseDuration: pulseDuration) let yOffset: CGFloat = title != nil ? -20 : 0 layer.position = CGPoint(x: unwrappedContainer.bounds.midX, y: unwrappedContainer.bounds.midY + yOffset) shared.replicatorLayer = layer if let title = title { let label = UILabel(incSpinnerText: title, font: font) let vibrancyEffectView = shared._addEffectView(toContainer: unwrappedContainer) vibrancyEffectView.contentView.addSubview(label) label.translatesAutoresizingMaskIntoConstraints = false [label.centerYAnchor.constraint(equalTo: vibrancyEffectView.centerYAnchor, constant: 60), label.centerXAnchor.constraint(equalTo: vibrancyEffectView.centerXAnchor), label.leftAnchor.constraint(equalTo: vibrancyEffectView.leftAnchor, constant: 40), label.rightAnchor.constraint(equalTo: vibrancyEffectView.rightAnchor, constant: -40) ].forEach { $0.isActive = true } label.textAlignment = .center shared.textLabel = label shared.vibrancyEffectView = vibrancyEffectView } if let effectView = shared.vibrancyEffectView { let tapToDismissLabel = UILabel(tapToDismissText: "Tap to dismiss", fontName: font?.fontName) tapToDismissLabel.translatesAutoresizingMaskIntoConstraints = false effectView.contentView.addSubview(tapToDismissLabel) tapToDismissLabel.topAnchor.constraint(equalTo: effectView.topAnchor, constant: 40).isActive = true tapToDismissLabel.centerXAnchor.constraint(equalTo: effectView.centerXAnchor).isActive = true shared.tapToDismissLabel = tapToDismissLabel } shared._animateBlurIn(withDuration: fadeDuration, style: style) } public class func hide(completion: (() -> Void)? = nil) { shared._fadeReplicatorLayerOut(withDuration: fadeDuration * 0.8) DispatchQueue.main.incSpinner_delay(fadeDuration * 0.5) { shared._animateBlurOut(withDuration: fadeDuration) { DispatchQueue.main.async { shared._reset() completion?() } } } } private func _startUsing(container c: UIView) { _reset() container = c } private func _reset() { replicatorLayer?.removeFromSuperlayer() blurredEffectView?.removeFromSuperview() vibrancyEffectView?.removeFromSuperview() replicatorLayer = nil blurredEffectView = nil vibrancyEffectView = nil container = nil } private func _addEffectView(toContainer container: UIView) -> UIVisualEffectView { let effectView = UIVisualEffectView(effect: nil) container.incSpinner_addAndFill(subview: effectView) return effectView } private func _addSpinnerLayer(to view: UIView, withCircleColor color: UIColor, pulseDuration: TimeInterval) -> CAReplicatorLayer { let replicatorLayer = IncSpinner_PulsingCircleReplicatorLayer(circleCount: 3, circleSize: 60, circleColor: color, animationDuration: pulseDuration) view.layer.addSublayer(replicatorLayer) return replicatorLayer } private func _animateBlurIn(withDuration duration: TimeInterval, style: UIBlurEffectStyle) { textLabel?.textColor = .clear tapToDismissLabel?.textColor = .clear let blurEffect = UIBlurEffect(style: style) UIView.animate(withDuration: duration, animations: { self.blurredEffectView?.effect = blurEffect }) { finished in guard let effectView = self.vibrancyEffectView, let label = self.textLabel, let tapToDismissLabel = self.tapToDismissLabel else { return } UIView.animate(withDuration: duration * 0.5, animations: { effectView.effect = UIVibrancyEffect(blurEffect: blurEffect) label.alpha = 1.0 label.textColor = .white tapToDismissLabel.alpha = 1.0 tapToDismissLabel.textColor = .white }) } } private func _animateBlurOut(withDuration duration: TimeInterval, completion: (() -> Void)?) { UIView.animate(withDuration: duration, animations: { self.blurredEffectView?.effect = nil self.vibrancyEffectView?.effect = nil self.textLabel?.alpha = 0.0 self.tapToDismissLabel?.alpha = 0.0 }) { (finished) in completion?() } } private func _fadeReplicatorLayerOut(withDuration duration: TimeInterval) { let anim = CABasicAnimation.incSpinner_fadeOut anim.duration = duration anim.fillMode = kCAFillModeForwards anim.isRemovedOnCompletion = false replicatorLayer?.add(anim, forKey: nil) } private func _addTapToDismissLabel(using font: UIFont) { } }
mit
c84718fa9aad12468adf422915dc824e
37.695279
150
0.645186
5.441159
false
false
false
false
jisudong/study
Study/Study/Study_RxSwift/AnyObserver.swift
1
1088
// // AnyObserver.swift // Study // // Created by syswin on 2017/7/28. // Copyright © 2017年 syswin. All rights reserved. // public struct AnyObserver<Element> : ObserverType { public typealias E = Element public typealias EventHandler = (Event<Element>) -> Void private let observer: EventHandler public init(eventHandler: @escaping EventHandler) { self.observer = eventHandler } public init<O : ObserverType>(_ observer: O) where O.E == Element { self.observer = observer.on } public func on(_ event: Event<Element>) { return self.observer(event) } public func asObserver() -> AnyObserver<E> { return self } } extension AnyObserver { // TODO: 需要修改 } extension ObserverType { public func asObserver() -> AnyObserver<E> { return AnyObserver(self) } public func mapObserver<R>(_ transform: @escaping (R) throws -> E) -> AnyObserver<R> { return AnyObserver { e in self.on(e.map(transform)) } } }
mit
df1c6daff645dade94835c1679b7a97b
20.979592
90
0.601671
4.308
false
false
false
false
ahoppen/swift
test/stdlib/SIMD.swift
7
2872
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // UNSUPPORTED: freestanding import Foundation import StdlibUnittest let SIMDCodableTests = TestSuite("SIMDCodable") // Round an integer to the closest representable JS integer value func jsInteger<T>(_ value: T) -> T where T : SIMD, T.Scalar : FixedWidthInteger { // Attempt to round-trip though Double; if that fails it's because the // rounded value is too large to fit in T, so use the largest value that // does fit instead. let upperBound = T.Scalar(Double(T.Scalar.max).nextDown) var result = T() for i in result.indices { result[i] = T.Scalar(exactly: Double(value[i])) ?? upperBound } return result } func testRoundTrip<T>(_ for: T.Type) where T : SIMD, T.Scalar : FixedWidthInteger { let input = jsInteger(T.random(in: T.Scalar.min ... T.Scalar.max)) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } func testRoundTrip<T>(_ for: T.Type) where T : SIMD, T.Scalar : BinaryFloatingPoint, T.Scalar.RawSignificand : FixedWidthInteger { let input = T.random(in: -16 ..< 16) let encoder = JSONEncoder() let decoder = JSONDecoder() do { let data = try encoder.encode(input) let output = try decoder.decode(T.self, from: data) expectEqual(input, output) } catch { expectUnreachableCatch(error) } } // Very basic round-trip test. We can be much more sophisticated in the future, // but we want to at least exercise the API. Also need to add some negative // tests for the error paths, and test a more substantial set of types. SIMDCodableTests.test("roundTrip") { testRoundTrip(SIMD2<Int8>.self) testRoundTrip(SIMD3<Int8>.self) testRoundTrip(SIMD4<Int8>.self) testRoundTrip(SIMD2<UInt8>.self) testRoundTrip(SIMD3<UInt8>.self) testRoundTrip(SIMD4<UInt8>.self) testRoundTrip(SIMD2<Int32>.self) testRoundTrip(SIMD3<Int32>.self) testRoundTrip(SIMD4<Int32>.self) testRoundTrip(SIMD2<UInt32>.self) testRoundTrip(SIMD3<UInt32>.self) testRoundTrip(SIMD4<UInt32>.self) testRoundTrip(SIMD2<Int>.self) testRoundTrip(SIMD3<Int>.self) testRoundTrip(SIMD4<Int>.self) testRoundTrip(SIMD2<UInt>.self) testRoundTrip(SIMD3<UInt>.self) testRoundTrip(SIMD4<UInt>.self) /* Apparently these fail to round trip not only for i386 but also on older macOS versions, so we'll disable them entirely for now. #if !arch(i386) // https://bugs.swift.org/browse/SR-9759 testRoundTrip(SIMD2<Float>.self) testRoundTrip(SIMD3<Float>.self) testRoundTrip(SIMD4<Float>.self) testRoundTrip(SIMD2<Double>.self) testRoundTrip(SIMD3<Double>.self) testRoundTrip(SIMD4<Double>.self) #endif */ } runAllTests()
apache-2.0
4b970d9f93e3ffd6369af968befdc230
30.217391
79
0.722493
3.585518
false
true
false
false
idapgroup/IDPDesign
Tests/iOS/iOSTests/Specs/Lens+UITableViewCellSpec.swift
1
12756
// // Lens+UITableViewCellSpec.swift // iOSTests // // Created by Oleksa 'trimm' Korin on 9/2/17. // Copyright © 2017 Oleksa 'trimm' Korin. All rights reserved. // import Quick import Nimble import UIKit @testable import IDPDesign extension UITableViewCell: UITableViewCellProtocol { } class LensUITableViewCellSpec: QuickSpec { override func spec() { describe("Lens+UITableViewCellSpec") { context("imageView") { it("should get and set") { let lens: Lens<UITableViewCell, UIImageView?> = imageView() let object = UITableViewCell() let value: UIImageView = UIImageView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.imageView).to(equal(resultValue)) } } context("textLabel") { it("should get and set") { let lens: Lens<UITableViewCell, UILabel?> = textLabel() let object = UITableViewCell() let value: UILabel = UILabel() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.textLabel).to(equal(resultValue)) } } context("detailTextLabel") { it("should get and set") { let lens: Lens<UITableViewCell, UILabel?> = detailTextLabel() let object = UITableViewCell(style: .value2, reuseIdentifier: nil) let value: UILabel = UILabel() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.detailTextLabel).to(equal(resultValue)) } } context("contentView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView> = contentView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).toNot(equal(value)) expect(resultObject.contentView).to(equal(resultValue)) } } context("backgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = backgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.backgroundView).to(equal(value)) } } context("selectedBackgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = selectedBackgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.selectedBackgroundView).to(equal(value)) } } context("multipleSelectionBackgroundView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = multipleSelectionBackgroundView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.multipleSelectionBackgroundView).to(equal(value)) } } context("selectionStyle") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.SelectionStyle> = selectionStyle() let object = UITableViewCell() let value: UITableViewCell.SelectionStyle = .none let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.selectionStyle).to(equal(value)) } } context("isSelected") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isSelected() let object = UITableViewCell() let value: Bool = !object.isSelected let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isSelected).to(equal(value)) } } context("isHighlighted") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isHighlighted() let object = UITableViewCell() let value: Bool = !object.isHighlighted let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isHighlighted).to(equal(value)) } } context("showsReorderControl") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = showsReorderControl() let object = UITableViewCell() let value: Bool = !object.showsReorderControl let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.showsReorderControl).to(equal(value)) } } context("shouldIndentWhileEditing") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = shouldIndentWhileEditing() let object = UITableViewCell() let value: Bool = !object.shouldIndentWhileEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.shouldIndentWhileEditing).to(equal(value)) } } context("accessoryType") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.AccessoryType> = accessoryType() let object = UITableViewCell() let value: UITableViewCell.AccessoryType = .checkmark let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.accessoryType).to(equal(value)) } } context("accessoryView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = accessoryView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.accessoryView).to(equal(value)) } } context("editingAccessoryType") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.AccessoryType> = editingAccessoryType() let object = UITableViewCell() let value: UITableViewCell.AccessoryType = .checkmark let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.editingAccessoryType).to(equal(value)) } } context("editingAccessoryView") { it("should get and set") { let lens: Lens<UITableViewCell, UIView?> = editingAccessoryView() let object = UITableViewCell() let value: UIView = UIView() let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.editingAccessoryView).to(equal(value)) } } context("indentationLevel") { it("should get and set") { let lens: Lens<UITableViewCell, Int> = indentationLevel() let object = UITableViewCell() let value: Int = 2 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.indentationLevel).to(equal(value)) } } context("indentationWidth") { it("should get and set") { let lens: Lens<UITableViewCell, CGFloat> = indentationWidth() let object = UITableViewCell() let value: CGFloat = 0.5 let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.indentationWidth).to(equal(value)) } } context("separatorInset") { it("should get and set") { let lens: Lens<UITableViewCell, UIEdgeInsets> = separatorInset() let object = UITableViewCell(style: .subtitle, reuseIdentifier: nil) let value: UIEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) // UITableViewCell automatically adds 8 pixels for left inset on top of the inset let referenceValue = UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 10) expect(resultValue).to(equal(referenceValue)) expect(resultObject.separatorInset).to(equal(referenceValue)) } } context("isEditing") { it("should get and set") { let lens: Lens<UITableViewCell, Bool> = isEditing() let object = UITableViewCell() let value: Bool = !object.isEditing let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.isEditing).to(equal(value)) } } context("focusStyle") { it("should get and set") { let lens: Lens<UITableViewCell, UITableViewCell.FocusStyle> = focusStyle() let object = UITableViewCell() let value: UITableViewCell.FocusStyle = .custom let resultObject = lens.set(object, value) let resultValue = lens.get(resultObject) expect(resultValue).to(equal(value)) expect(resultObject.focusStyle).to(equal(value)) } } } } }
bsd-3-clause
8849f78316dde9f068abfcbbf2dad57c
36.404692
107
0.510074
5.927045
false
false
false
false
velvetroom/columbus
Source/View/Settings/VSettingsListCellTravelModeList.swift
1
3152
import UIKit final class VSettingsListCellTravelModeList:VCollection< ArchSettings, VSettingsListCellTravelModeListCell> { weak var model:MSettingsTravelMode? weak var viewSelector:VSettingsListCellTravelModeListSelector! weak var layoutSelectorLeft:NSLayoutConstraint! weak var layoutSelectorTop:NSLayoutConstraint! let selectorSize_2:CGFloat private var cellSize:CGSize? required init(controller:CSettings) { selectorSize_2 = VSettingsListCellTravelModeList.Constants.selectorSize / 2.0 super.init(controller:controller) config() selectCurrent() } required init?(coder:NSCoder) { return nil } override func collectionView( _ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { guard let cellSize:CGSize = self.cellSize else { let width:CGFloat = collectionView.bounds.width let height:CGFloat = collectionView.bounds.height let items:Int = collectionView.numberOfItems(inSection:0) let itemsFloat:CGFloat = CGFloat(items) let widthPerItem:CGFloat = width / itemsFloat let cellSize:CGSize = CGSize( width:widthPerItem, height:height) self.cellSize = cellSize return cellSize } return cellSize } override func collectionView( _ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { guard let count:Int = model?.items.count else { return 0 } return count } override func collectionView( _ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MSettingsTravelModeProtocol = modelAtIndex(index:indexPath) let cell:VSettingsListCellTravelModeListCell = cellAtIndex(indexPath:indexPath) cell.config(model:item) return cell } override func collectionView( _ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool { guard let model:MSettingsTravelMode = self.model else { return false } let item:MSettingsTravelModeProtocol = modelAtIndex( index:indexPath) guard model.settings.travelMode == item.mode else { return true } return false } override func collectionView( _ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { model?.selected(index:indexPath.item) updateSelector(animationDuration:VSettingsListCellTravelModeList.Constants.animationDuration) } }
mit
325427072f0f63fd0778412ef1e5e27e
25.487395
101
0.596447
6.108527
false
false
false
false
iOS-mamu/SS
P/Library/Eureka/Source/Core/InlineRowType.swift
1
5277
// InlineRowType.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol BaseInlineRowType { /** Method that can be called to expand (open) an inline row */ func expandInlineRow() /** Method that can be called to collapse (close) an inline row */ func collapseInlineRow() /** Method that can be called to change the status of an inline row (expanded/collapsed) */ func toggleInlineRow() } /** * Protocol that every inline row type has to conform to. */ public protocol InlineRowType: TypedRowType, BaseInlineRowType { associatedtype InlineRow: BaseRow, RowType, TypedRowType /** This function is responsible for setting up an inline row before it is first shown. */ func setupInlineRow(_ inlineRow: InlineRow) } extension InlineRowType where Self: BaseRow, Self.InlineRow : BaseRow, Self.Cell.Value == Self.Value, Self.InlineRow.Cell.Value == Self.InlineRow.Value, Self.InlineRow.Value == Self.Value { /// The row that will be inserted below after the current one when it is selected. public var inlineRow : Self.InlineRow? { return _inlineRow as? Self.InlineRow } /** Method that can be called to expand (open) an inline row. */ public func expandInlineRow() { if let _ = inlineRow { return } if var section = section, let form = section.form { let inline = InlineRow.init() { _ in } inline.value = value inline.onChange { [weak self] in self?.value = $0.value self?.updateCell() } setupInlineRow(inline) if (form.inlineRowHideOptions ?? Form.defaultInlineRowHideOptions).contains(.AnotherInlineRowIsShown) { for row in form.allRows { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } if let onExpandInlineRowCallback = onExpandInlineRowCallback { onExpandInlineRowCallback(cell, self, inline) } if let indexPath = indexPath() { section.insert(inline, at: indexPath.row + 1) _inlineRow = inline cell.formViewController()?.makeRowVisible(inline) } } } /** Method that can be called to collapse (close) an inline row. */ public func collapseInlineRow() { if let selectedRowPath = indexPath(), let inlineRow = _inlineRow { if let onCollapseInlineRowCallback = onCollapseInlineRowCallback { onCollapseInlineRowCallback(cell, self, inlineRow as! InlineRow) } section?.remove(at: selectedRowPath.row + 1) _inlineRow = nil } } /** Method that can be called to change the status of an inline row (expanded/collapsed). */ public func toggleInlineRow() { if let _ = inlineRow { collapseInlineRow() } else{ expandInlineRow() } } /** Sets a block to be executed when a row is expanded. */ public func onExpandInlineRow(_ callback: @escaping (Cell, Self, InlineRow)->()) -> Self { callbackOnExpandInlineRow = callback return self } /** Sets a block to be executed when a row is collapsed. */ public func onCollapseInlineRow(_ callback: @escaping (Cell, Self, InlineRow)->()) -> Self { callbackOnCollapseInlineRow = callback return self } /// Returns the block that will be executed when this row expands public var onCollapseInlineRowCallback: ((Cell, Self, InlineRow)->())? { return callbackOnCollapseInlineRow as! ((Cell, Self, InlineRow)->())? } /// Returns the block that will be executed when this row collapses public var onExpandInlineRowCallback: ((Cell, Self, InlineRow)->())? { return callbackOnExpandInlineRow as! ((Cell, Self, InlineRow)->())? } }
mit
4a5df5743ba1e5b378c6b75102557e8f
35.393103
189
0.636536
5.054598
false
false
false
false
Yalantis/StarWars.iOS
Example/StarWarsAnimations/Controller/MainSettingsViewController.swift
1
1829
// // MainSettingsViewController.swift // StarWarsAnimations // // Created by Artem Sidorenko on 10/19/15. // Copyright © 2015 Yalantis. All rights reserved. // import UIKit class MainSettingsViewController: UIViewController { @IBOutlet fileprivate weak var saveButton: UIButton! var theme: SettingsTheme! { didSet { settingsViewController?.theme = theme saveButton?.backgroundColor = theme.primaryColor } } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() } fileprivate func setupNavigationBar() { navigationController!.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) navigationController!.navigationBar.shadowImage = UIImage() navigationController!.navigationBar.isTranslucent = true navigationController!.navigationBar.titleTextAttributes = [ NSAttributedString.Key.font: UIFont(name: "GothamPro", size: 20)!, NSAttributedString.Key.foregroundColor: UIColor.white ] } fileprivate var settingsViewController: SettingsViewController? override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let settings = segue.destination as? SettingsViewController { settingsViewController = settings settings.themeChanged = { [unowned self, unowned settings] darkside, center in let center = self.view.convert(center, from: settings.view) self.view.animateCircular(withDuration: 0.5, center: center, revert: darkside ? false : true, animations: { self.theme = darkside ? .dark : .light }) } } } override var prefersStatusBarHidden : Bool { return true } }
mit
b23107d181b71ba2b2d69d049b51c425
32.851852
123
0.655908
5.506024
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLockTests/ProcessedFileModelsComparison.swift
1
2074
// // ProcessedFileModelsComparison.swift // GroupLock // // Created by Sergej Jaskiewicz on 26.07.16. // Copyright © 2016 Lanit-Tercom School. All rights reserved. // @testable import GroupLock // We are using this methods and not the `==` operator so that in tests we can define equality in a diferent way. extension ProcessedFile.Share.Response: EquatableModel { func isEqualTo(_ response: ProcessedFile.Share.Response) -> Bool { return self.dataToShare.count == response.dataToShare.count && !zip(self.dataToShare.sorted(), response.dataToShare.sorted()).contains { $0 != $1 } && ((self.excludedActivityTypes == nil && response.excludedActivityTypes == nil) || (self.excludedActivityTypes != nil && response.excludedActivityTypes != nil // swiftlint:disable:next force_unwrapping && !zip(self.excludedActivityTypes!.sorted(by: { $0.rawValue < $1.rawValue }), // swiftlint:disable:next force_unwrapping response.excludedActivityTypes!.sorted(by: { $0.rawValue < $1.rawValue })) .contains { $0 != $1 })) } } extension ProcessedFile.Fetch.ViewModel.FileInfo: EquatableModel { func isEqualTo(_ fileInfo: ProcessedFile.Fetch.ViewModel.FileInfo) -> Bool { return self.fileName == fileInfo.fileName && self.encrypted == fileInfo.encrypted && self.fileThumbnail.isEqualToImage(fileInfo.fileThumbnail) } } extension ProcessedFile.Fetch.ViewModel: EquatableModel { func isEqualTo(_ viewModel: ProcessedFile.Fetch.ViewModel) -> Bool { return self.fileInfo.count == viewModel.fileInfo.count && !zip(self.fileInfo, viewModel.fileInfo).contains { !$0.isEqualTo($1) } } } extension ProcessedFile.Fetch.Response: EquatableModel { func isEqualTo(_ response: ProcessedFile.Fetch.Response) -> Bool { return self.files.count == response.files.count && !zip(self.files, response.files).contains { $0 != $1 } } }
apache-2.0
bc89c02907de8e8ff56a9410bd602f78
39.647059
113
0.65316
4.526201
false
false
false
false
adrfer/swift
test/SourceKit/SourceDocInfo/cursor_info.swift
1
10370
import Foo import FooSwiftModule var glob : Int func foo(x: Int) {} func goo(x: Int) { foo(glob+x+Int(fooIntVar)+fooSwiftFunc()) } /// Aaa. S1. Bbb. struct S1 {} var w : S1 func test2(x: S1) {} class CC { init(x: Int) { self.init(x:0) } } var testString = "testString" let testLetString = "testString" func testLetParam(arg1 : Int) { } func testVarParam(var arg1 : Int) { } func testDefaultParam(arg1: Int = 0) { } fooSubFunc1(0) func myFunc(arg1: String) { } func myFunc(arg1: String, options: Int) { } var derivedObj = FooClassDerived() typealias MyInt = Int var x: MyInt import FooHelper.FooHelperSub class C2 { lazy var lazy_bar : Int = { return x }() } func test1(foo: FooUnavailableMembers) { foo.availabilityIntroduced() foo.swiftUnavailable() foo.unavailable() foo.availabilityIntroducedMsg() foo.availabilityDeprecated() } public class SubscriptCursorTest { public subscript (i: Int) -> Int { return 0 } public static func test() { let s = SubscriptCursorTest() let a = s[1234] + s[4321] } } // RUN: rm -rf %t.tmp // RUN: mkdir %t.tmp // RUN: %swiftc_driver -emit-module -o %t.tmp/FooSwiftModule.swiftmodule %S/Inputs/FooSwiftModule.swift // RUN: %sourcekitd-test -req=cursor -pos=9:8 %s -- -F %S/../Inputs/libIDE-mock-sdk %mcp_opt %s | FileCheck -check-prefix=CHECK1 %s // CHECK1: source.lang.swift.ref.var.global (4:5-4:9) // CHECK1-NEXT: glob // CHECK1-NEXT: s:v11cursor_info4globSi{{$}} // CHECK1-NEXT: Int // RUN: %sourcekitd-test -req=cursor -pos=9:11 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK2 %s // CHECK2: source.lang.swift.ref.function.operator.infix () // CHECK2-NEXT: + // CHECK2-NEXT: s:ZFsoi1pFTSiSi_Si // CHECK2-NEXT: (Int, Int) -> Int{{$}} // CHECK2-NEXT: Swift{{$}} // CHECK2-NEXT: SYSTEM // CHECK2-NEXT: <Declaration>func +(lhs: <Type usr="s:Si">Int</Type>, rhs: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=9:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK3 %s // CHECK3: source.lang.swift.ref.var.local (8:10-8:11) // CHECK3-NEXT: x{{$}} // CHECK3-NEXT: s:vF11cursor_info3gooFSiT_L_1xSi{{$}} // CHECK3-NEXT: Int{{$}} // RUN: %sourcekitd-test -req=cursor -pos=9:18 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK4 %s // CHECK4: source.lang.swift.ref.var.global ({{.*}}Foo.framework/Headers/Foo.h:62:12-62:21) // CHECK4-NEXT: fooIntVar{{$}} // CHECK4-NEXT: c:@fooIntVar{{$}} // CHECK4-NEXT: Int32{{$}} // CHECK4-NEXT: Foo{{$}} // CHECK4-NEXT: <Declaration>var fooIntVar: <Type usr="s:Vs5Int32">Int32</Type></Declaration> // CHECK4-NEXT: <Variable file="{{[^"]+}}Foo.h" line="{{[0-9]+}}" column="{{[0-9]+}}"><Name>fooIntVar</Name><USR>c:@fooIntVar</USR><Declaration>var fooIntVar: Int32</Declaration><Abstract><Para> Aaa. fooIntVar. Bbb.</Para></Abstract></Variable> // RUN: %sourcekitd-test -req=cursor -pos=8:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK5 %s // CHECK5: source.lang.swift.decl.function.free (8:6-8:17) // CHECK5-NEXT: goo(_:){{$}} // CHECK5-NEXT: s:F11cursor_info3gooFSiT_{{$}} // CHECK5-NEXT: (Int) -> (){{$}} // RUN: %sourcekitd-test -req=cursor -pos=9:32 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK6 %s // CHECK6: source.lang.swift.ref.function.free () // CHECK6-NEXT: fooSwiftFunc // CHECK6-NEXT: s:F14FooSwiftModule12fooSwiftFuncFT_Si // CHECK6-NEXT: () -> Int // CHECK6-NEXT: FooSwiftModule // CHECK6-NEXT: <Declaration>func fooSwiftFunc() -&gt; <Type usr="s:Si">Int</Type></Declaration> // CHECK6-NEXT: {{^}}<Function><Name>fooSwiftFunc()</Name><USR>s:F14FooSwiftModule12fooSwiftFuncFT_Si</USR><Declaration>func fooSwiftFunc() -&gt; Int</Declaration><Abstract><Para>This is &apos;fooSwiftFunc&apos; from &apos;FooSwiftModule&apos;.</Para></Abstract></Function>{{$}} // RUN: %sourcekitd-test -req=cursor -pos=14:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK7 %s // CHECK7: source.lang.swift.ref.struct (13:8-13:10) // CHECK7-NEXT: S1 // CHECK7-NEXT: s:V11cursor_info2S1 // CHECK7-NEXT: S1.Type // CHECK7-NEXT: <Declaration>struct S1</Declaration> // CHECK7-NEXT: <Class file="{{[^"]+}}cursor_info.swift" line="13" column="8"><Name>S1</Name><USR>s:V11cursor_info2S1</USR><Declaration>struct S1</Declaration><Abstract><Para>Aaa. S1. Bbb.</Para></Abstract></Class> // RUN: %sourcekitd-test -req=cursor -pos=19:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK8 %s // CHECK8: source.lang.swift.ref.function.constructor (18:3-18:15) // CHECK8-NEXT: init // CHECK8-NEXT: s:FC11cursor_info2CCcFT1xSi_S0_ // CHECK8-NEXT: CC.Type -> (x: Int) -> CC // RUN: %sourcekitd-test -req=cursor -pos=23:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK9 %s // CHECK9: source.lang.swift.decl.var.global (23:5-23:15) // CHECK9: <Declaration>var testString: <Type usr="s:SS">String</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=24:6 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK10 %s // CHECK10: source.lang.swift.decl.var.global (24:5-24:18) // CHECK10: <Declaration>let testLetString: <Type usr="s:SS">String</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=26:20 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK11 %s // CHECK11: source.lang.swift.decl.var.local (26:19-26:23) // CHECK11: <Declaration>let arg1: <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=28:24 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK12 %s // CHECK12: source.lang.swift.decl.var.local (28:23-28:27) // CHECK12: <Declaration>let arg1: <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=31:7 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK13 %s // CHECK13: source.lang.swift.decl.function.free (31:6-31:37) // CHECK13: <Declaration>func testDefaultParam(arg1: <Type usr="s:Si">Int</Type> = default)</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=34:4 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK14 %s // CHECK14: source.lang.swift.ref.function.free ({{.*}}Foo.framework/Frameworks/FooSub.framework/Headers/FooSub.h:4:5-4:16) // CHECK14: fooSubFunc1 // CHECK14: c:@F@fooSubFunc1 // CHECK14: Foo.FooSub{{$}} // RUN: %sourcekitd-test -req=cursor -pos=38:8 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK15 %s // CHECK15: source.lang.swift.decl.function.free (38:6-38:40) // CHECK15: myFunc // CHECK15: <Declaration>func myFunc(arg1: <Type usr="s:SS">String</Type>, options: <Type usr="s:Si">Int</Type>)</Declaration> // CHECK15: RELATED BEGIN // CHECK15-NEXT: <RelatedName usr="s:F11cursor_info6myFuncFSST_">myFunc(_:)</RelatedName> // CHECK15-NEXT: RELATED END // RUN: %sourcekitd-test -req=cursor -pos=41:26 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK16 %s // CHECK16: source.lang.swift.ref.class ({{.*}}Foo.framework/Headers/Foo.h:157:12-157:27) // CHECK16-NEXT: FooClassDerived // CHECK16-NEXT: c:objc(cs)FooClassDerived // RUN: %sourcekitd-test -req=cursor -pos=1:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK17 %s // CHECK17: source.lang.swift.ref.module () // CHECK17-NEXT: Foo{{$}} // RUN: %sourcekitd-test -req=cursor -pos=44:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK18 %s // CHECK18: source.lang.swift.ref.typealias (43:11-43:16) // CHECK18: <Declaration>typealias MyInt = <Type usr="s:Si">Int</Type></Declaration> // RUN: %sourcekitd-test -req=cursor -pos=46:10 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK19 %s // CHECK19: source.lang.swift.ref.module () // CHECK19-NEXT: FooHelper{{$}} // RUN: %sourcekitd-test -req=cursor -pos=46:25 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK20 %s // CHECK20: source.lang.swift.ref.module () // CHECK20-NEXT: FooHelperSub{{$}} // RUN: %sourcekitd-test -req=cursor -pos=50:12 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK21 %s // CHECK21: source.lang.swift.ref.var.global (44:5-44:6) // CHECK21-NEXT: {{^}}x{{$}} // RUN: %sourcekitd-test -req=cursor -pos=55:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK22 %s // CHECK22: <Declaration>func availabilityIntroduced()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=56:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK23 %s // CHECK23-NOT: <Declaration>func swiftUnavailable()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=57:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK24 %s // CHECK24-NOT: <Declaration>func unavailable()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=58:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK25 %s // CHECK25: <Declaration>func availabilityIntroducedMsg()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=59:15 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK26 %s // CHECK26-NOT: <Declaration>func availabilityDeprecated()</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=69:14 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK27 %s // CHECK27: <Declaration>public subscript (i: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type> { get }</Declaration> // RUN: %sourcekitd-test -req=cursor -pos=69:19 %s -- -F %S/../Inputs/libIDE-mock-sdk -I %t.tmp %mcp_opt %s | FileCheck -check-prefix=CHECK28 %s // CHECK28: <Declaration>public subscript (i: <Type usr="s:Si">Int</Type>) -&gt; <Type usr="s:Si">Int</Type> { get }</Declaration>
apache-2.0
5339c9f1a3c2b8288bd3d26d20161410
47.457944
278
0.668177
2.806495
false
true
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/FittingLoadoutsPresenter.swift
2
8636
// // FittingLoadoutsPresenter.swift // Neocom // // Created by Artem Shimanski on 11/23/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController import Expressible import CoreData class FittingLoadoutsPresenter: TreePresenter { typealias View = FittingLoadoutsViewController typealias Interactor = FittingLoadoutsInteractor typealias Presentation = [AnyTreeItem] weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? var loadouts: Atomic<[Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>]?> = Atomic(nil) required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.TreeDefaultCell.default]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } switch view?.input { case .ship?: view?.title = NSLocalizedString("Ships", comment: "") case .structure?: view?.title = NSLocalizedString("Structures", comment: "") default: break } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { guard let input = view?.input else {return .init(.failure(NCError.invalidInput(type: type(of: self))))} let treeController = view?.treeController let storageContext = interactor.storageContext return storageContext.perform { [weak self] () -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] in guard let strongSelf = self else {throw NCError.cancelled(type: type(of: self), function: #function)} let loadouts = try storageContext.managedObjectContext .from(Loadout.self) .fetch() return strongSelf.presentation(for: loadouts, categoryID: input, treeController: treeController) }.then(on: .main) { [weak self] result -> Presentation in self?.loadouts.value = result let menu: [Tree.Item.RoutableRow<Tree.Content.Default>] switch input { case .ship: let category = Services.sde.viewContext.dgmppItemCategory(categoryID: .ship)! let typePickerRoute = Router.Fitting.dgmTypePicker(.init(category: category, completion: { (controller, type) in })) menu = [ Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("New Ship Fit", comment: ""), image:Image( #imageLiteral(resourceName: "fitting")), accessoryType: .disclosureIndicator), route: typePickerRoute), Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("Import/Export", comment: ""), image:Image( #imageLiteral(resourceName: "browser")), accessoryType: .disclosureIndicator), route: nil) ] case .structure: menu = [ Tree.Item.RoutableRow(Tree.Content.Default(title: NSLocalizedString("New Structure Fit", comment: ""), image:Image( #imageLiteral(resourceName: "station")), accessoryType: .disclosureIndicator), route: nil) ] default: menu = [] } return [Tree.Item.Virtual(children: menu, diffIdentifier: "Menu").asAnyItem, Tree.Item.Virtual(children: result, diffIdentifier: "Loadouts").asAnyItem ] } } private func presentation(for loadouts: [Loadout], categoryID: SDECategoryID, treeController: TreeController?) -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] { let context = Services.sde.newBackgroundContext() return context.performAndWait { () -> [Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow>] in let items = loadouts.compactMap { i -> (loadout: Loadout, type: SDEInvType)? in context.invType(Int(i.typeID)).map {(loadout: i, type: $0)} }.filter {$0.type.group?.category?.categoryID == categoryID.rawValue} .sorted {$0.type.typeName ?? "" < $1.type.typeName ?? ""} let groups = Dictionary(grouping: items) {$0.type.group}.sorted {$0.key?.groupName ?? "" < $1.key?.groupName ?? ""} return groups.map { i -> Tree.Item.Section<Tree.Content.LoadoutsSection, Tree.Item.LoadoutRow> in let rows = i.value.sorted{$0.0.name ?? "" < $1.0.name ?? ""} .map{ Tree.Item.LoadoutRow(Tree.Content.Loadout(loadoutID: $0.loadout.objectID, loadoutName: $0.loadout.name ?? "", typeID: $0.type.objectID), diffIdentifier: $0.loadout.objectID) } let section = Tree.Content.LoadoutsSection(groupID: Int(i.key!.groupID), groupName: i.key?.groupName?.uppercased() ?? NSLocalizedString("Unknown", comment: "").uppercased()) return Tree.Item.Section(section, diffIdentifier: i.key!.objectID, expandIdentifier: i.key!.objectID, treeController: treeController, children: rows) } } } func didUpdateLoaoduts(updated: [Loadout]?, inserted: [Loadout]?, deleted: [Loadout]?) { guard var loadouts = loadouts.value else {return} guard let input = view?.input else {return} if let updated = updated, !updated.isEmpty { let pairs = loadouts.enumerated().compactMap { i in i.element.children?.enumerated().map { j in (j.element.content.loadoutID, IndexPath(row: j.offset, section: i.offset)) } }.joined() let map = Dictionary(pairs, uniquingKeysWith: { a, _ in a}) for i in updated { guard let indexPath = map[i.objectID], let row = loadouts[indexPath.section].children?[indexPath.row] else {continue} let new = Tree.Item.LoadoutRow(Tree.Content.Loadout(loadoutID: i.objectID, loadoutName: i.name ?? "", typeID: row.content.typeID), diffIdentifier: i.objectID) loadouts[indexPath.section].children?[indexPath.row] = new } } deleted?.forEach { i in for (j, section) in loadouts.enumerated() { if let index = section.children?.firstIndex(where: {$0.content.loadoutID == i.objectID}) { section.children?.remove(at: index) if section.children?.isEmpty == true { loadouts.remove(at: j) } return } } } let treeController = (try? DispatchQueue.main.async {self.view?.treeController}.get()) ?? nil if let inserted = inserted, !inserted.isEmpty { let newSections = presentation(for: inserted, categoryID: input, treeController: treeController) for i in newSections { let r = loadouts.lowerBound(where: {$0.content.groupName <= i.content.groupName }) if let j = r.last, j.content == i.content { let children = [j.children, i.children].compactMap{$0}.joined().sorted(by: {$0.content.loadoutName < $1.content.loadoutName}) j.children? = children } else { loadouts.insert(i, at: r.indices.upperBound) } } } DispatchQueue.main.async { guard var presentation = self.presentation, presentation.count == 2 else {return} presentation[1] = Tree.Item.Virtual(children: loadouts, diffIdentifier: "Loadouts").asAnyItem self.presentation = presentation self.loadouts.value = loadouts self.view?.present(presentation, animated: true) } } } extension Tree.Item { class LoadoutRow: Row<Tree.Content.Loadout> { override var prototype: Prototype? { return Prototype.TreeDefaultCell.default } lazy var type: SDEInvType = try! Services.sde.viewContext.existingObject(with: content.typeID) override func configure(cell: UITableViewCell, treeController: TreeController?) { super.configure(cell: cell, treeController: treeController) guard let cell = cell as? TreeDefaultCell else {return} cell.accessoryType = .disclosureIndicator cell.titleLabel?.text = type.typeName cell.subtitleLabel?.text = content.loadoutName cell.subtitleLabel?.isHidden = false cell.iconView?.image = type.icon?.image?.image ?? Services.sde.viewContext.eveIcon(.defaultType)?.image?.image } } } extension Tree.Content { struct Loadout: Hashable { var loadoutID: NSManagedObjectID var loadoutName: String var typeID: NSManagedObjectID } struct LoadoutsSection: Hashable, CellConfigurable { var prototype: Prototype? = Prototype.TreeSectionCell.default var groupID: Int var groupName: String func configure(cell: UITableViewCell, treeController: TreeController?) { guard let cell = cell as? TreeSectionCell else {return} cell.titleLabel?.text = groupName } init(groupID: Int, groupName: String) { self.groupID = groupID self.groupName = groupName } } }
lgpl-2.1
ce8de8ca3c53e2865af0052b7a813b97
37.039648
219
0.712334
3.891393
false
false
false
false
tmandry/Swindler
Sources/AXPropertyDelegate.swift
1
6308
import Foundation import AXSwift import PromiseKit import Cocoa /// Implements PropertyDelegate using the AXUIElement API. class AXPropertyDelegate<T: Equatable, UIElement: UIElementType>: PropertyDelegate { typealias InitDict = [AXSwift.Attribute: Any] let axElement: UIElement let attribute: AXSwift.Attribute let initPromise: Promise<InitDict> init(_ axElement: UIElement, _ attribute: AXSwift.Attribute, _ initPromise: Promise<InitDict>) { self.axElement = axElement self.attribute = attribute self.initPromise = initPromise } func readFilter(_ value: T?) -> T? { return value } func readValue() throws -> T? { do { let value: T? = try traceRequest(axElement, "attribute", attribute) { try axElement.attribute(attribute) } return readFilter(value) } catch AXError.cannotComplete { // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) } catch AXError.invalidUIElement { log.debug("Got invalidUIElement for element \(axElement) " + "when attempting to read \(attribute)") throw PropertyError.invalidObject(cause: AXError.invalidUIElement) } catch let error { log.warn("Got unexpected error for element \(axElement) " + "when attempting to read \(attribute)") //unexpectedError(error) throw PropertyError.invalidObject(cause: error) } } func writeValue(_ newValue: T) throws { do { return try traceRequest(axElement, "setAttribute", attribute, newValue) { try axElement.setAttribute(attribute, value: newValue) } } catch AXError.illegalArgument { throw PropertyError.illegalValue } catch AXError.cannotComplete { // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) } catch AXError.failure { throw PropertyError.failure(cause: AXError.failure) } catch AXError.invalidUIElement { log.debug("Got invalidUIElement for element \(axElement) " + "when attempting to write \(attribute)") throw PropertyError.invalidObject(cause: AXError.invalidUIElement) } catch let error { unexpectedError(error) throw PropertyError.invalidObject(cause: error) } } func initialize() -> Promise<T?> { return initPromise.map { dict in guard let value = dict[self.attribute] else { return nil } return self.readFilter(Optional(value as! T)) }.recover { error -> Promise<T?> in switch error { case AXError.cannotComplete: // If messaging timeout unspecified, we'll pass -1. var time = UIElement.globalMessagingTimeout if time == 0 { time = -1.0 } throw PropertyError.timeout(time: TimeInterval(time)) default: log.debug("Got error while initializing attribute \(self.attribute) " + "for element \(self.axElement)") throw PropertyError.invalidObject(cause: error) } } } } // Non-generic protocols of generic types make it easy to store (or cast) objects. protocol AXPropertyDelegateType { var attribute: AXSwift.Attribute { get } } extension AXPropertyDelegate: AXPropertyDelegateType {} protocol PropertyType { func issueRefresh() var delegate: Any { get } var initialized: Promise<Void>! { get } } extension Property: PropertyType { func issueRefresh() { refresh() } } /// Asynchronously fetches all the element attributes. func fetchAttributes<UIElement: UIElementType>(_ attributeNames: [Attribute], forElement axElement: UIElement, after: Promise<Void>, seal: Resolver<[Attribute: Any]>) { // Issue a request in the background. after.done(on: .global()) { let attributes = try traceRequest(axElement, "getMultipleAttributes", attributeNames) { try axElement.getMultipleAttributes(attributeNames) } seal.fulfill(attributes) }.catch { error in seal.reject(error) } } /// Returns a promise that resolves when all the provided properties are initialized. /// Adds additional error information for AXPropertyDelegates. func initializeProperties(_ properties: [PropertyType]) -> Promise<Void> { let propertiesInitialized: [Promise<Void>] = Array(properties.map({ $0.initialized })) return when(fulfilled: propertiesInitialized) } /// Tracks how long `requestFunc` takes, and logs it if needed. /// - Parameter object: The object the request is being made on (usually, a UIElement). func traceRequest<T>( _ object: Any, _ request: String, _ arg1: Any, _ arg2: Any? = nil, requestFunc: () throws -> T ) throws -> T { var result: T? var error: Error? let start = Date() do { result = try requestFunc() } catch let err { error = err } let end = Date() let elapsed = end.timeIntervalSince(start) log.trace({ () -> String in // This closure won't be evaluated if tracing is disabled. let formatElapsed = String(format: "%.1f", elapsed * 1000) let formatArgs = (arg2 == nil) ? "\(arg1)" : "\(arg1), \(arg2!)" let formatResult = (error == nil) ? "responded with \(result!)" : "failed with \(error!)" return "\(request)(\(formatArgs)) on \(object) \(formatResult) in \(formatElapsed)ms" }()) // TODO: if more than some threshold, log as info if let error = error { throw error } return result! }
mit
a2e0f62a1b4a134652ca00b655fe15f7
35.462428
100
0.597337
4.931978
false
false
false
false
devpunk/punknote
punknote/Controller/Home/CHome.swift
1
3068
import UIKit class CHome:Controller<VHome> { let model:MHome override init() { model = MHome() super.init() } required init?(coder:NSCoder) { return nil } override func viewDidLoad() { super.viewDidLoad() MSession.sharedInstance.loadSession() } override func viewDidAppear(_ animated:Bool) { super.viewDidAppear(animated) model.reload(controller:self) } private func confirmDelete(item:MHomeItem) { model.deleteNote(controller:self, item:item) } //MARK: public func newNote() { editNote(item:nil) } func notesLoaded() { DispatchQueue.main.async { [weak self] in guard let view:VHome = self?.view as? VHome else { return } view.stopLoading() } } func deleteNote(item:MHomeItem) { let alert:UIAlertController = UIAlertController( title:NSLocalizedString("CHome_deleteAlertTitle", comment:""), message:nil, preferredStyle:UIAlertControllerStyle.actionSheet) let actionCancel:UIAlertAction = UIAlertAction( title: NSLocalizedString("CHome_deleteAlertCancel", comment:""), style: UIAlertActionStyle.cancel) let actionDelete:UIAlertAction = UIAlertAction( title: NSLocalizedString("CHome_deleteAlertDelete", comment:""), style: UIAlertActionStyle.destructive) { [weak self] (action:UIAlertAction) in self?.confirmDelete(item:item) } alert.addAction(actionDelete) alert.addAction(actionCancel) if let popover:UIPopoverPresentationController = alert.popoverPresentationController { popover.sourceView = view popover.sourceRect = CGRect.zero popover.permittedArrowDirections = UIPopoverArrowDirection.up } present(alert, animated:true, completion:nil) } func editNote(item:MHomeItem?) { guard let parent:ControllerParent = self.parent as? ControllerParent else { return } let controller:CCreate = CCreate(modelHomeItem:item) parent.push( controller:controller, horizontal:ControllerParent.Horizontal.right) } func shareNote(item:MHomeItem) { guard let parent:ControllerParent = self.parent as? ControllerParent else { return } let controller:CShare = CShare(modelHomeItem:item) parent.push( controller:controller, horizontal:ControllerParent.Horizontal.right) } }
mit
14630d2d6790080d5002b72cf17d50b1
22.6
92
0.537484
5.59854
false
false
false
false
programersun/HiChongSwift
HiChongSwift/LCYNetworking.swift
1
13494
// // LCYNetworking.swift // HiChongSwift // // Created by eagle on 14/12/4. // Copyright (c) 2014年 Duostec. All rights reserved. // enum LCYApi: String { case TwitterAdd = "Twitter/twitter_add" case TwitterList = "Twitter/twitter_list" case TwitterKeeperInfo = "Twitter/keeper_info" case twitterPersonal = "Twitter/twitter_personal" case TwitterStar = "Twitter/twitter_star" case TwitterCommentList = "Twitter/twitter_comment_list" case TwitterCommentAdd = "Twitter/twitter_comment_add" case TwitterStarDel = "Twitter/twitter_star_del" case TwitterRemindInfo = "Twitter/twitter_remind_info" case TwitterDelete = "Twitter/twitter_del" case SquareGetSquareCategory = "Square/getSquareCategory" /// Deprecated case SquareHome = "Square/home" case SquaregetSquareList = "Square/getSquareList" case SquareMerchantInfo = "Square/merchant_info" case SquareCommentAdd = "Square/comment_add" case SquareCommentList = "Square/comment_list" case UserLogin = "User/login" case UserAuthcode = "User/register_authcode" case UserRegister = "User/register" case UserGetInfo = "User/getUserInfoByID" case UserModifySingle = "User/modifySingleProperty" case UserModifyLocation = "User/modifyLocation" case UserModifyInfo = "User/modifyInfo" case UserChangeLocation = "User/changeLocation" case UserAttention = "User/attention" case UserFansList = "User/fans_list" case UserFriendList = "User/friend_list" case UserSearchFriend = "User/search_friend" case UserSearchFriend2 = "User/search_friend2" case UserResetPasswordAuthcode = "User/reset_password_authcode" case UserSetPassword = "User/setPassword" case UserModifyBackgroundImage = "User/modifyBackgroundImage" case UserModifyImage = "User/modifyImage" case PetGetDetail = "Pet/GetPetDetailByID" case PetAllType = "PetStyle/searchAllTypePets" case PetSubType = "PetStyle/searchDetailByID" case PetAdd = "Pet/petAdd" case PetUpdatePetInfo = "Pet/updatePetInfo" case PetUploadPetImage = "Pet/UploadPetImage" case WikiToday = "Ency/getTodayEncy" case WikiIsCollect = "Ency/is_collect" case WikiCollect = "Ency/setCollect" case WikiCollectList = "Ency/getCollectArticle" case WikiMore = "Ency/searchEncy" case WikiGetAD = "/Ency/getAd" } enum LCYMimeType: String { case PNG = "image/png" case JPEG = "image/jpeg" } class LCYNetworking { private let hostURL = "http://123.57.7.88/admin/index.php/Api/" private let commonURL = "http://123.57.7.88/admin/index.php/Common/Upload/ios" private let ArticleHTMLComponent = "Ency/ency_article/ency_id/" private let WikiHtmlComponent = "Ency/category_article/cate_id/" /** 百度地图ak,由开发者 icylydia 提供 */ private let BaiduAK = "0G8SXbO2PwwGRLTzsIMj0dxi" /** 大众点评,由开发者 icylydia 提供 */ private let DianpingHost = "http://api.dianping.com/v1/business/find_businesses" private let DianpingAppKey = "0900420225" private let DianpingAppSecret = "c3385423913745e992079187dc08d33d" private enum RequestType { case GET case POST } class var sharedInstance: LCYNetworking { struct Singleton { static let instance = LCYNetworking() } return Singleton.instance } func Dianping(parameters: [String: String], success: ((object: NSDictionary) -> ())?, failure: ((error: NSError) -> ())?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() var mutpara = parameters mutpara.extend(["platform": "2"]) let keys = sorted(mutpara.keys) let signStringA = reduce(keys, DianpingAppKey) { (prefix, element) -> String in prefix + element + mutpara[element]! } let signStringB = signStringA + DianpingAppSecret let sign = signStringB.SHA_1() mutpara.extend(["appkey": DianpingAppKey, "sign": sign]) println("request 大众点评 with parameters: \(mutpara)") manager.GET(DianpingHost, parameters: mutpara, success: { (operation, object) -> Void in println("success in dianping ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTAndGET(Api: LCYApi, GETParameters: [String: String]?, POSTParameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { var URLString = Api.rawValue if let get = GETParameters { URLString += "?" URLString += reduce(get.keys, "", { $0 + $1 + "=" + get[$1]! + "&" }) requestWith(.POST, Api: URLString, parameters: POSTParameters, success: success, failure: failure) } else { if let unwrapped = failure { unwrapped(error: NSError()) } } } func POST(Api: LCYApi, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { requestWith(.POST, Api: Api.rawValue, parameters: parameters, success: success, failure: failure) } func GET(Api: LCYApi, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { requestWith(.GET, Api: Api.rawValue, parameters: parameters, success: success, failure: failure) } func POSTNONEJSON(Api: LCYApi, parameters: NSDictionary!, success: ((responseString: String) -> Void)?, failure: ((error: NSError!)->Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFHTTPResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue manager.POST(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(responseString: operation.responseString) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } private func requestWith(type: RequestType, Api: String, parameters: NSDictionary!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError!)->Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api println("Request: \(absoluteURL)\nwith Parameters: \(parameters)") switch type { case .GET: manager.GET(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } case .POST: manager.POST(absoluteURL, parameters: parameters, success: { (operation, object) -> Void in println("success in \"\(Api)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") println("\(operation.responseString)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } } func POSTFile(Api: LCYApi, parameters: NSDictionary!, fileKey: String!, fileData: NSData!, fileName: String!, mimeType: LCYMimeType, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue manager.POST(absoluteURL, parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(fileData, name: fileKey, fileName: fileName, mimeType: mimeType.rawValue) return }, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTMultipleFile(Api: LCYApi, parameters: NSDictionary!, fileKey: String!, fileData: [NSData]!, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = hostURL + Api.rawValue println("posting file, please wait!") manager.POST(absoluteURL, parameters: parameters, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in for data in fileData { formData.appendPartWithFileData(data, name: fileKey, fileName: "\(data.hash).jpg", mimeType: LCYMimeType.JPEG.rawValue) } return }, success: { (operation, object) -> Void in println("success in \"\(Api.rawValue)\" ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func POSTCommonFile(fileKey: String!, fileData: NSData!, fileName: String!, mimeType: LCYMimeType, success: ((object: NSDictionary) -> Void)?, failure: ((error: NSError) -> Void)?) { let manager = AFHTTPRequestOperationManager() manager.responseSerializer = AFJSONResponseSerializer() manager.responseSerializer.acceptableContentTypes = NSSet(objects: "text/html", "text/plain") as Set<NSObject> let absoluteURL = commonURL manager.POST(absoluteURL, parameters: nil, constructingBodyWithBlock: { (formData: AFMultipartFormData!) -> Void in formData.appendPartWithFileData(fileData, name: fileKey, fileName: fileName, mimeType: mimeType.rawValue) return }, success: { (operation, object) -> Void in println("success in upload ====> \(operation.responseString)") if let unwrappedSuccess = success { unwrappedSuccess(object: object as! NSDictionary) } }) { (operation, error) -> Void in println("error \(error)") if let unwrappedFailure = failure { unwrappedFailure(error: error) } } } func WikiHTMLAddress(cateID: String) -> String { return "\(hostURL)\(ArticleHTMLComponent)\(cateID)" } func WikiDetailHTMLAddress(cateID: String) -> String { return "\(hostURL)\(WikiHtmlComponent)\(cateID)" } }
apache-2.0
db00a2695044b2237e7eb826df270d73
47.175627
220
0.591369
4.964906
false
false
false
false
iOSreverse/DWWB
DWWB/DWWB/Classes/Home(首页)/HomeModel/Status.swift
1
1278
// // Status.swift // DWWB // // Created by xmg on 16/4/9. // Copyright © 2016年 NewDee. All rights reserved. // import UIKit class Status: NSObject { // MARK: - 属性 var created_at : String? //微博创建时间 var source : String? //微博来源 var text : String? //微博的正文 var mid : Int = 0 //微博的ID var user : User? //微博对应的用户 var pic_urls : [[String : String]]? //微博的配图 var retweeted_status : Status? //微博对应的转发的微博 // MARK: - 自定义构造函数 init(dict : [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) // 1.将用户字典转成用户模型对象 if let userDict = dict["user"] as? [String : AnyObject] { user = User(dict: userDict) } // 2将转发微博字典转成转发微博模型对象 if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] { retweeted_status = Status(dict: retweetedStatusDict) } } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
apache-2.0
d95773c068c00434c1ea7bbf0bff46f2
25.595238
88
0.528201
4.061818
false
false
false
false
ifabijanovic/swtor-holonet
ios/HoloNet/Module/Forum/UI/CollectionViewCell/ForumThreadCollectionViewCell.swift
1
1469
// // ForumThreadCollectionViewCell.swift // SWTOR HoloNet // // Created by Ivan Fabijanovic on 20/03/15. // Copyright (c) 2015 Ivan Fabijanović. All rights reserved. // import UIKit class ForumThreadCollectionViewCell: UICollectionViewCell { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var authorLabel: UILabel! @IBOutlet weak var devImageView: UIImageView! @IBOutlet weak var stickyImageView: UIImageView! @IBOutlet weak var repliesViewsLabel: UILabel! @IBOutlet weak var accessoryView: UIImageView! override func apply(theme: Theme) { self.titleLabel.textColor = theme.contentTitle self.titleLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue) self.authorLabel.textColor = theme.contentText self.authorLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue - 2.0) self.repliesViewsLabel.textColor = theme.contentText self.repliesViewsLabel.font = UIFont.systemFont(ofSize: theme.textSize.rawValue - 2.0) if self.accessoryView.image == nil { self.accessoryView.image = UIImage(named: "Forward")?.withRenderingMode(.alwaysTemplate) } self.accessoryView.tintColor = theme.contentTitle let selectedBackgroundView = UIView() selectedBackgroundView.backgroundColor = theme.contentHighlightBackground self.selectedBackgroundView = selectedBackgroundView } }
gpl-3.0
0f97e89425da48e4a6fe2a49efddfbe4
37.631579
100
0.713896
4.877076
false
false
false
false
LarsStegman/helios-for-reddit
Sources/Authorization/Token/UserToken.swift
1
3090
// // UserToken.swift // Helios // // Created by Lars Stegman on 13-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation struct UserToken: Token, Equatable { let username: String? let accessToken: String let refreshToken: String? let scopes: [Scope] let expiresAt: Date var authorizationType: Authorization { if let name = username { return .user(name: name) } else { return .application } } var refreshable: Bool { return refreshToken != nil } init(username: String?, accessToken: String, refreshToken: String?, scopes: [Scope], expiresAt: Date) { self.username = username self.accessToken = accessToken self.refreshToken = refreshToken self.scopes = scopes self.expiresAt = expiresAt } init(username: String?, token: UserToken) { self.init(username: username, accessToken: token.accessToken, refreshToken: token.refreshToken, scopes: token.scopes, expiresAt: token.expiresAt) } private enum CodingKeys: String, CodingKey { case username case accessToken = "access_token" case refreshToken = "refresh_token" case scopes = "scope" case expiresAt case expiresIn = "expires_in" } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) if let name = username { try container.encode(name, forKey: .username) } else { try container.encodeNil(forKey: .username) } try container.encode(accessToken, forKey: .accessToken) try container.encode(refreshToken, forKey: .refreshToken) try container.encode(scopes, forKey: .scopes) try container.encode(expiresAt, forKey: .expiresAt) } init(from: Decoder) throws { let container = try from.container(keyedBy: CodingKeys.self) username = try container.decodeIfPresent(String.self, forKey: .username) accessToken = try container.decode(String.self, forKey: .accessToken) refreshToken = try container.decodeIfPresent(String.self, forKey: .refreshToken) if let scopesFromList = try? container.decode([Scope].self, forKey: .scopes) { scopes = scopesFromList } else { scopes = Scope.scopes(from: try container.decode(String.self, forKey: .scopes)) } if let expirationDate = try? container.decode(Date.self, forKey: .expiresAt) { expiresAt = expirationDate } else { expiresAt = Date(timeIntervalSinceNow: try container.decode(TimeInterval.self, forKey: .expiresIn)) } } static func ==(lhs: UserToken, rhs: UserToken) -> Bool { print("Equal!") return lhs.username == rhs.username && lhs.accessToken == rhs.accessToken && lhs.refreshToken == rhs.refreshToken && lhs.scopes == rhs.scopes && lhs.expiresAt == rhs.expiresAt } }
mit
264b7eb2ce8e38e46f9437a106ed03b4
32.576087
111
0.622855
4.673222
false
false
false
false
naokits/my-programming-marathon
TrySwift/TrySwiftExample/TrySwiftExample/MasterViewController.swift
1
3590
// // MasterViewController.swift // TrySwiftExample // // Created by Naoki Tsutsui on 9/1/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
0fcb9eb736dd0e489d7c6ac461985e7e
37.180851
157
0.694065
5.770096
false
false
false
false
zmarvin/EnjoyMusic
Pods/Macaw/Source/model/draw/LinearGradient.swift
1
804
import Foundation open class LinearGradient: Gradient { open let x1: Double open let y1: Double open let x2: Double open let y2: Double public init(x1: Double = 0, y1: Double = 0, x2: Double = 0, y2: Double = 0, userSpace: Bool = false, stops: [Stop] = []) { self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 super.init( userSpace: userSpace, stops: stops ) } public init(degree: Double = 0, from: Color, to: Color) { self.x1 = degree >= 135 && degree < 270 ? 1 : 0 self.y1 = degree < 225 ? 0 : 1 self.x2 = degree < 90 || degree >= 315 ? 1 : 0 self.y2 = degree >= 45 && degree < 180 ? 1 : 0 super.init( userSpace: false, stops: [Stop(offset: 0, color: from), Stop(offset: 1, color: to)] ) } }
mit
2485015fcf9f849d6a8d7dd72bac64bf
24.125
123
0.55597
2.902527
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactory/NSDictionary+Utilities.swift
1
2433
// // NSDictionary+Utilities.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. 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 the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // 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 Foundation extension NSDictionary { public func objectWithResourceDictionary() -> Any? { guard let resourceName = self["resourceName"] as? String else { return nil } let bundleName = self["resourceBundle"] as? String let bundle = (bundleName != nil) ? Bundle(identifier: bundleName!) : nil guard let json = SBAResourceFinder.shared.json(forResource: resourceName, bundle: bundle) else { return nil } guard let classType = self["classType"] as? String else { return json } return SBAClassTypeMap.shared.object(with: json, classType: classType) } }
bsd-3-clause
6aad0e8bca61ce7ff632b058a122591a
44.886792
104
0.729852
4.854291
false
false
false
false
pr0gramm3r8hai/DGSegmentedControl
DGSegmentedControl/ViewController.swift
1
1792
// // ViewController.swift // DGSegmentedControl // // Created by dip on 2/17/16. // Copyright © 2016 apple. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var segmentedControl: DGSegmentedControl! @IBOutlet weak var displayGround: UIView! @IBOutlet weak var info: UILabel! override func viewDidLoad() { super.viewDidLoad() decorateSegmentedControl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK:- Action @IBAction func segmentValueChanged(_ sender: AnyObject) { if sender.selectedIndex == 0{ self.displayGround.backgroundColor = UIColor.gray self.info.text = "First Segment selected" } else { self.displayGround.backgroundColor = UIColor(red: 0.761, green: 0.722, blue: 0.580, alpha: 1.00) self.info.text = "Second Segment selected" } } //MARK:- Segment control func decorateSegmentedControl(){ segmentedControl.items = ["First Segment","Second Segment"] segmentedControl.font = UIFont(name: "Avenir-Black", size: 12) segmentedControl.borderColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedIndex = 0 segmentedControl.borderSize = 2 segmentedControl.thumbColor = UIColor(red: 0.988, green: 0.820, blue: 0.447, alpha: 1.00) segmentedControl.selectedLabelColor = UIColor.black segmentedControl.thumUnderLineSize = 8 segmentedControl.font = UIFont.systemFont(ofSize: 18) self.segmentValueChanged(self.segmentedControl) } }
mit
e48515b02a0d2a04fdc017119d72ef06
32.166667
108
0.651033
4.615979
false
false
false
false
icapps/ios_objective_c_workshop
Teacher/General Objective-C example/Pods/Faro/Sources/ServiceConvenienceExtension.swift
1
5980
import Foundation /// The perform methods are preferred but these methods are for convenience. /// They do some default error handling. /// These functions are deprecated!!! extension Service { // MARK: - Results transformed to Model(s) // MARK: - Update /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized model @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performUpdate<ModelType: Deserializable & Updatable>(_ call: Call, on updateModel: ModelType, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, on: updateModel, autoStart: autoStart) { (result) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "UpdateModel \(updateModel) could not be updated. Maybe you did not implement update correctly failed?") self.print(faroError, and: fail) return } ok(model) case .models( _ ): let faroError = FaroError.malformed(info: "Requested a single response be received a collection.") self.print(faroError, and: fail) default: self.handle(result, and: fail) } } } // MARK: - Create // MARK: - Single model response /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized model @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performSingle<ModelType: Deserializable>(_ call: Call, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(model) case .models( _ ): let faroError = FaroError.malformed(info: "Requested a single response be received a collection.") self.print(faroError, and: fail) default: self.handle(result, and: fail) } } } // MARK: - Collection model response /// Performs the call to the server. Provide a model /// - parameter call: where can the server be found? /// - parameter fail: if we cannot initialize the model this call will fail and print the failure. /// - parameter ok: returns initialized array of models @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performCollection<ModelType: Deserializable>(_ call: Call, autoStart: Bool = true, fail: @escaping (FaroError)->(), ok:@escaping ([ModelType])->()) { perform(call, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .models(let models): guard let models = models else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(models) default: self.handle(result, and: fail) } } } // MARK: - With Paging information @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performSingle<ModelType: Deserializable, PagingType: Deserializable>(_ call: Call, autoStart: Bool = true, page: @escaping(PagingType?)->(), fail: @escaping (FaroError)->(), ok:@escaping (ModelType)->()) { perform(call, page: page, autoStart: autoStart) { (result: Result<ModelType>) in switch result { case .model(let model): guard let model = model else { let faroError = FaroError.malformed(info: "Model could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(model) default: self.handle(result, and: fail) } } } @available(*, deprecated: 1.1, obsoleted: 2.0, message: "You should use the `perform` functions in `Service` with result enum.") open func performCollection<ModelType: Deserializable, PagingType: Deserializable>(_ call: Call, page: @escaping(PagingType?)->(), fail: @escaping (FaroError)->(), ok:@escaping ([ModelType])->()) { perform(call, page: page) { (result: Result<ModelType>) in switch result { case .models(let models): guard let models = models else { let faroError = FaroError.malformed(info: "Models could not be initialized. Maybe your init(from raw:) failed?") self.print(faroError, and: fail) return } ok(models) default: self.handle(result, and: fail) } } } }
mit
9932b6d553b59c8a3ae611b28cd85908
47.617886
219
0.587458
4.826473
false
false
false
false
realm/SwiftLint
Tests/SwiftLintFrameworkTests/ObjectLiteralRuleTests.swift
1
2865
@testable import SwiftLintFramework import XCTest class ObjectLiteralRuleTests: XCTestCase { // MARK: - Instance Properties private let imageLiteralTriggeringExamples = ["", ".init"].flatMap { (method: String) -> [Example] in ["UI", "NS"].flatMap { (prefix: String) -> [Example] in [ Example("let image = ↓\(prefix)Image\(method)(named: \"foo\")") ] } } private let colorLiteralTriggeringExamples = ["", ".init"].flatMap { (method: String) -> [Example] in ["UI", "NS"].flatMap { (prefix: String) -> [Example] in [ Example("let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)"), Example("let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)"), Example("let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)") ] } } private var allTriggeringExamples: [Example] { return imageLiteralTriggeringExamples + colorLiteralTriggeringExamples } // MARK: - Test Methods func testObjectLiteralWithImageLiteral() { // Verify ObjectLiteral rule for when image_literal is true. let baseDescription = ObjectLiteralRule.description let nonTriggeringColorLiteralExamples = colorLiteralTriggeringExamples.removingViolationMarkers() let nonTriggeringExamples = baseDescription.nonTriggeringExamples + nonTriggeringColorLiteralExamples let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples) .with(triggeringExamples: imageLiteralTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": true, "color_literal": false]) } func testObjectLiteralWithColorLiteral() { // Verify ObjectLiteral rule for when color_literal is true. let baseDescription = ObjectLiteralRule.description let nonTriggeringImageLiteralExamples = imageLiteralTriggeringExamples.removingViolationMarkers() let nonTriggeringExamples = baseDescription.nonTriggeringExamples + nonTriggeringImageLiteralExamples let description = baseDescription.with(nonTriggeringExamples: nonTriggeringExamples) .with(triggeringExamples: colorLiteralTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": false, "color_literal": true]) } func testObjectLiteralWithImageAndColorLiteral() { // Verify ObjectLiteral rule for when image_literal & color_literal are true. let description = ObjectLiteralRule.description.with(triggeringExamples: allTriggeringExamples) verifyRule(description, ruleConfiguration: ["image_literal": true, "color_literal": true]) } }
mit
96b71f4bc3c094b8f39cfb618f17716d
48.258621
120
0.672034
5.400756
false
true
false
false
Stitch7/Instapod
Instapod/Player/Remote/ProgressSlider/PlayerRemoteProgressSlider.swift
1
4010
// // PlayerRemoteProgressSlider.swift // Instapod // // Created by Christopher Reitz on 07.03.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit import PKHUD @IBDesignable class PlayerRemoteProgressSlider: UISlider { // MARK: - Properties var isMoving = false var scrubbingSpeed = PlayerRemoteProgressSliderScrubbingSpeed.high var realPositionValue: Float = 0.0 var beganTrackingLocation = CGPoint(x: 0.0, y: 0.0) // MARK: - Touch tracking override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let beginTracking = super.beginTracking(touch, with: event) if beginTracking { // Set the beginning tracking location to the centre of the current // position of the thumb. This ensures that the thumb is correctly re-positioned // when the touch position moves back to the track after tracking in one // of the slower tracking zones. let thumbRect = self.thumbRect(forBounds: bounds, trackRect: trackRect(forBounds: bounds), value: value) let x = thumbRect.origin.x + thumbRect.size.width / 2.0 let y = thumbRect.origin.y + thumbRect.size.height / 2.0 beganTrackingLocation = CGPoint(x: x, y: y) realPositionValue = value } return beginTracking } override func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { guard isTracking else { return false } let previousLocation = touch.previousLocation(in: self) let currentLocation = touch.location(in: self) let trackingOffset = currentLocation.x - previousLocation.x // Find the scrubbing speed that curresponds to the touch's vertical offset let verticalOffset = fabs(currentLocation.y - beganTrackingLocation.y) if let lowerScrubbingSpeed = scrubbingSpeed.lowerScrubbingSpeed(forOffset: verticalOffset) { scrubbingSpeed = lowerScrubbingSpeed if scrubbingSpeed == .high { HUD.hide(animated: true) } else { HUD.allowsInteraction = true HUD.show(.label(scrubbingSpeed.stringValue)) } } let trackRect = self.trackRect(forBounds: bounds) realPositionValue = realPositionValue + (maximumValue - minimumValue) * Float(trackingOffset / trackRect.size.width) let valueAdjustment: Float = scrubbingSpeed.rawValue * (maximumValue - minimumValue) * Float(trackingOffset / trackRect.size.width) var thumbAdjustment: Float = 0.0 if ((beganTrackingLocation.y < currentLocation.y) && (currentLocation.y < previousLocation.y)) || ((beganTrackingLocation.y > currentLocation.y) && (currentLocation.y > previousLocation.y)) { thumbAdjustment = (realPositionValue - value) / Float(1 + fabs(currentLocation.y - beganTrackingLocation.y)) } value += valueAdjustment + thumbAdjustment if isContinuous { sendActions(for: .valueChanged) } return true } override func endTracking(_ touch: UITouch?, with event: UIEvent?) { guard isTracking else { return } scrubbingSpeed = .high sendActions(for: .touchUpInside) HUD.hide(animated: true) } // MARK: - Styling override func trackRect(forBounds bounds: CGRect) -> CGRect { var trackRect = super.trackRect(forBounds: bounds) trackRect.size.width = bounds.width trackRect.origin.x = 0 trackRect.origin.y = 0 trackRect.size.height = 4 return trackRect } override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { var rect = super.thumbRect(forBounds: bounds, trackRect: rect, value: value) let x = rect.origin.x - 4 let y = rect.origin.y + 6 rect.origin = CGPoint(x: x, y: y) return rect } }
mit
62ec0e12eea9f51d46aae1303d827b10
35.117117
139
0.647543
4.727594
false
false
false
false
finngaida/wwdc
2016/Pods/PeekPop/PeekPop/PeekPopManager.swift
1
4615
// // PeekPopManager.swift // PeekPop // // Created by Roy Marmelstein on 12/03/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation class PeekPopManager { let peekPop: PeekPop var viewController: UIViewController { get {return peekPop.viewController} } var targetViewController: UIViewController? var index: Int = 0 private var peekPopView: PeekPopView? private lazy var peekPopWindow: UIWindow = { let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.windowLevel = UIWindowLevelAlert window.rootViewController = UIViewController() return window }() init(peekPop: PeekPop) { self.peekPop = peekPop } //MARK: PeekPop /// Prepare peek pop view if peek and pop gesture is possible func peekPopPossible(context: PreviewingContext, touchLocation: CGPoint, tag: Int) -> Bool { // Return early if no target view controller is provided by delegate method guard let targetVC = context.delegate.previewingContext(context, viewControllerForLocation: touchLocation, tag: tag) else { return false } // Create PeekPopView let view = PeekPopView() peekPopView = view // Take view controller screenshot if let viewControllerScreenshot = viewController.view.screenshotView() { peekPopView?.viewControllerScreenshot = viewControllerScreenshot peekPopView?.blurredScreenshots = self.generateBlurredScreenshots(viewControllerScreenshot) } // Take source view screenshot let rect = viewController.view.convertRect(context.sourceRect, fromView: context.sourceView) peekPopView?.sourceViewScreenshot = viewController.view.screenshotView(true, rect: rect) peekPopView?.sourceViewRect = rect // Take target view controller screenshot targetVC.view.frame = viewController.view.bounds peekPopView?.targetViewControllerScreenshot = targetVC.view.screenshotView(false) targetViewController = targetVC return true } func generateBlurredScreenshots(image: UIImage) -> [UIImage] { var images = [UIImage]() images.append(image) for i in 1...3 { let radius: CGFloat = CGFloat(Double(i) * 8.0 / 3.0) if let blurredScreenshot = blurImageWithRadius(image, radius: radius) { images.append(blurredScreenshot) } } return images } func blurImageWithRadius(image: UIImage, radius: CGFloat) -> UIImage? { return image.applyBlurWithRadius(CGFloat(radius), tintColor: nil, saturationDeltaFactor: 1.0, maskImage: nil) } /// Add window to heirarchy when peek pop begins func peekPopBegan() { peekPopWindow.alpha = 0.0 peekPopWindow.hidden = false peekPopWindow.makeKeyAndVisible() if let peekPopView = peekPopView { peekPopWindow.addSubview(peekPopView) } peekPopView?.frame = viewController.view.bounds peekPopView?.didAppear() UIView.animateWithDuration(0.2, animations: { () -> Void in self.peekPopWindow.alpha = 1.0 }) } /** Animated progress for context - parameter progress: A value between 0.0 and 1.0 - parameter context: PreviewingContext */ func animateProgressForContext(progress: CGFloat, context: PreviewingContext?) { (progress < 0.99) ? peekPopView?.animateProgress(progress) : commitTarget(context) } /** Commit target. - parameter context: PreviewingContext */ func commitTarget(context: PreviewingContext?){ guard let targetViewController = targetViewController, context = context else { return } context.delegate.previewingContext(context, commitViewController: targetViewController) peekPopEnded() } /** Peek pop ended - parameter animated: whether or not window removal should be animated */ func peekPopEnded() { UIView.animateWithDuration(0.2, animations: { () -> Void in self.peekPopWindow.alpha = 0.0 }) { (finished) -> Void in self.peekPop.peekPopGestureRecognizer?.resetValues() self.peekPopWindow.hidden = true self.peekPopView?.removeFromSuperview() self.peekPopView = nil } } }
gpl-2.0
5d698bd3da6c7a1ed971aaeda03202c2
31.964286
131
0.635891
5.352668
false
false
false
false
fluidsonic/JetPack
Sources/Extensions/MapKit/MKMapRect.swift
1
2311
import MapKit public extension MKMapRect { init(region: MKCoordinateRegion) { let bottomLeft = MKMapPoint(CLLocationCoordinate2D(latitude: region.center.latitude + region.span.latitudeDelta / 2, longitude: region.center.longitude - region.span.longitudeDelta / 2)) let topRight = MKMapPoint(CLLocationCoordinate2D(latitude: region.center.latitude - region.span.latitudeDelta / 2, longitude: region.center.longitude + region.span.longitudeDelta / 2)) self = MKMapRect( x: min(bottomLeft.x, topRight.x), y: min(bottomLeft.y, topRight.y), width: abs(bottomLeft.x - topRight.x), height: abs(bottomLeft.y - topRight.y) ) } @available(*, unavailable, message: "use .insetBy(dx:dy)") mutating func insetBy(horizontally horizontal: Double, vertically vertical: Double = 0) { self = insetBy(dx: horizontal, dy: vertical) } @available(*, unavailable, message: "use .insetBy(dx:dy)") mutating func insetBy(vertically vertical: Double) { self = insetBy(dx: 0, dy: vertical) } @available(*, unavailable, renamed: "insetBy(dx:dy:)") func insettedBy(horizontally horizontal: Double, vertically vertical: Double = 0) -> MKMapRect { return insetBy(dx: horizontal, dy: vertical) } @available(*, unavailable, message: "use .insetBy(dx:dy)") func insettedBy(vertically vertical: Double) -> MKMapRect { return insetBy(dx: 0, dy: vertical) } mutating func scaleBy(_ scale: Double) { scaleBy(horizontally: scale, vertically: scale) } mutating func scaleBy(horizontally horizontal: Double, vertically vertical: Double = 1) { self = scaledBy(horizontally: horizontal, vertically: vertical) } mutating func scaleBy(vertically vertical: Double) { scaleBy(horizontally: 1, vertically: vertical) } func scaledBy(_ scale: Double) -> MKMapRect { return scaledBy(horizontally: scale, vertically: scale) } func scaledBy(horizontally horizontal: Double, vertically vertical: Double = 1) -> MKMapRect { return insetBy(dx: (size.width / 2) * horizontal, dy: (size.height / 2) * vertical) } func scaledBy(vertically vertical: Double) -> MKMapRect { return scaledBy(horizontally: 1, vertically: vertical) } } extension MKMapRect: Equatable { public static func == (a: MKMapRect, b: MKMapRect) -> Bool { return MKMapRectEqualToRect(a, b) } }
mit
8db0d15a27356142f06328a0b156f042
28.253165
188
0.721765
3.733441
false
false
false
false
zhuhaow/NEKit
test/Utils/IPRangeSpec.swift
2
3470
import Quick import Nimble @testable import NEKit class IPRangeSpec: QuickSpec { override func spec() { let cidrWrongSamples = [ ("127.0.0.132", IPRangeError.invalidCIDRFormat), ("13.1242.1241.1/3", IPRangeError.invalidCIDRFormat), ("123.122.33.21/35", IPRangeError.invalidMask), ("123.123.131.12/-1", IPRangeError.invalidCIDRFormat), ("123.123.131.12/", IPRangeError.invalidCIDRFormat) ] let cidrCorrectSamples = [ ("127.0.0.0/32", [IPAddress(fromString: "127.0.0.1")!]), ("127.0.0.0/31", [IPAddress(fromString: "127.0.0.1")!]), ("127.0.0.0/1", [IPAddress(fromString: "127.0.0.1")!]) ] let rangeWrongSamples = [ ("127.0.0.132", IPRangeError.invalidRangeFormat), ("13.1242.1241.1+3", IPRangeError.invalidRangeFormat), ("255.255.255.255+1", IPRangeError.invalidRange), ("0.0.0.1+4294967295", IPRangeError.invalidRange), ("123.123.131.12+", IPRangeError.invalidRangeFormat), ("12.124.51.23-1", IPRangeError.invalidRangeFormat) ] let rangeCorrectSamples = [ ("127.0.0.1+3", [IPAddress(fromString: "127.0.0.1")!]), ("255.255.255.255+0", [IPAddress(fromString: "255.255.255.255")!]), ("0.0.0.0+4294967295", [IPAddress(fromString: "0.0.0.0")!]) ] let ipSamples = [ ("127.0.0.1", [IPAddress(fromString: "127.0.0.1")!]) ] describe("IPRange initailization") { it("can be initailized with CIDR IP representation") { for sample in cidrWrongSamples { expect {try IPRange(withCIDRString: sample.0)}.to(throwError(sample.1)) } for sample in cidrCorrectSamples { expect {try IPRange(withCIDRString: sample.0)}.toNot(throwError()) } } it("can be initailized with IP range representation") { for sample in rangeWrongSamples { expect {try IPRange(withRangeString: sample.0)}.to(throwError(sample.1)) } for sample in rangeCorrectSamples { expect {try IPRange(withRangeString: sample.0)}.toNot(throwError()) } } it("can select the best way to initailize") { for sample in cidrCorrectSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } for sample in rangeCorrectSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } for sample in ipSamples { expect {try IPRange(withString: sample.0)}.toNot(throwError()) } } } describe("IPRange matching") { it ("Can match IPv4 address with mask") { let range = try! IPRange(withString: "8.8.8.8/24") expect(range.contains(ip: IPAddress(fromString: "8.8.8.0")!)).to(beTrue()) expect(range.contains(ip: IPAddress(fromString: "8.8.8.255")!)).to(beTrue()) expect(range.contains(ip: IPAddress(fromString: "8.8.7.255")!)).to(beFalse()) expect(range.contains(ip: IPAddress(fromString: "8.8.9.0")!)).to(beFalse()) } } } }
bsd-3-clause
e572c18ff2c9a95f43d9c5446fc2db9c
38.885057
93
0.533429
4.106509
false
false
false
false
ethanneff/organize
Organize/SettingViewController.swift
1
6794
import UIKit protocol SettingsDelegate: class { func settingsButtonPressed(button button: SettingViewController.Button) } class SettingViewController: UIViewController { // MARK: - properties weak var menu: SettingsDelegate? weak var delegate: SettingsDelegate? var buttons: [Int: Button] = [:] struct Button { let button: UIButton let detail: Detail } enum Detail: Int { case Notebook case NotebookTitle case NotebookChange case NotebookUncollapse case NotebookCollapse case NotebookHideReminder case NotebookDeleteCompleted case App case AppTutorial case AppColor case AppTimer case AppFeedback case AppShare case Cloud case CloudUpload case CloudDownload case Account case AccountAchievements case AccountEmail case AccountPassword case AccountDelete case AccountLogout case Upgrade case UpgradeBuy static var count: Int { return UpgradeBuy.hashValue+1 } var header: Bool { switch self { case .Notebook, .App, .Cloud, .Account, .Upgrade: return true default: return false } } var active: Bool { switch self { case .NotebookChange, .NotebookHideReminder, .AccountAchievements, .Upgrade, .UpgradeBuy, .Cloud, .CloudUpload, .CloudDownload: return false default: return true } } var highlighted: Bool { switch self { case .UpgradeBuy: return true default: return false } } var title: String { switch self { case .Notebook: return "Notebook" case .NotebookTitle: return "Change title" case .NotebookChange: return "Change notebook" case .NotebookCollapse: return "Collapse all" case .NotebookUncollapse: return "Expand all" case .NotebookHideReminder: return Constant.UserDefault.get(key: Constant.UserDefault.Key.IsRemindersHidden) as? Bool ?? false ? "Hide reminders" : "Show reminders" case .NotebookDeleteCompleted: return "Delete completed" case .App: return "App" case .AppTutorial: return "View tutorial" case .AppTimer: return Constant.UserDefault.get(key: Constant.UserDefault.Key.IsTimerActive) as? Bool ?? false ? "Modify timer" : "Activate timer" case .AppColor: return "Change color" case .AppFeedback: return "Send feedback" case .AppShare: return "Share with a friend" case .Cloud: return "Cloud" case .CloudUpload: return "Upload" case .CloudDownload: return "Download" case .Account: return "Account" case .AccountAchievements: return "View achievements" case .AccountEmail: return "Change email" case .AccountPassword: return "Change password" case .AccountDelete: return "Delete account" case .AccountLogout: return "Logout" case .Upgrade: return "Upgrade" case .UpgradeBuy: return "Buy the dev a coffee" } } } // MARK: - load override func loadView() { super.loadView() setupView() } private func setupView() { var constraints: [NSLayoutConstraint] = [] view.backgroundColor = Constant.Color.background // scroll view let scrollView = UIScrollView() var scrollViewContentSizeHeight: CGFloat = Constant.Button.padding scrollView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) // buttons var prev: UIButton = UIButton() for i in 0..<Detail.count { if let detail = Detail(rawValue: i) { let button = UIButton() let enabled: Bool = detail.header ? false : true let color: UIColor = detail.header ? Constant.Color.border : Constant.Color.button let topItem: UIView = i == 0 ? scrollView : prev let topAttribute: NSLayoutAttribute = i == 0 ? .Top : .Bottom let topConstant: CGFloat = i == 0 ? Constant.Button.padding : detail.header ? Constant.Button.padding*2 : 0 button.tag = detail.rawValue button.hidden = !detail.active button.backgroundColor = Constant.Color.background button.layer.cornerRadius = 5 button.clipsToBounds = true button.setTitle(detail.title, forState: .Normal) button.setTitleColor(color, forState: .Normal) button.addTarget(self, action: #selector(buttonPressed(_:)), forControlEvents: .TouchUpInside) button.enabled = enabled button.contentHorizontalAlignment = detail.header ? .Center : .Left button.titleLabel?.font = .systemFontOfSize(Constant.Button.fontSize) button.translatesAutoresizingMaskIntoConstraints = false buttons[detail.rawValue] = Button(button: button, detail: detail) if !detail.active { continue } scrollView.addSubview(button) constraints.append(NSLayoutConstraint(item: button, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: Constant.Button.padding*2)) constraints.append(NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -Constant.Button.padding*2)) constraints.append(NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: Constant.Button.height)) constraints.append(NSLayoutConstraint(item: button, attribute: .Top, relatedBy: .Equal, toItem: topItem, attribute: topAttribute, multiplier: 1, constant: topConstant)) scrollViewContentSizeHeight += topConstant + Constant.Button.height prev = button } } // scroll view constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: scrollView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0)) scrollView.contentSize = CGSize(width: 0, height: scrollViewContentSizeHeight) NSLayoutConstraint.activateConstraints(constraints) } // MARK: - button func buttonPressed(button: UIButton) { Util.animateButtonPress(button: button) if let button = buttons[button.tag] { delegate?.settingsButtonPressed(button: button) } } }
mit
265d7541b24b2a6e860982e4142bd8eb
36.744444
190
0.681925
4.688751
false
false
false
false
PeterWang0124/PWSideViewControlSwift
Source/PWSideViewControlSwift.swift
1
12977
// // PWSideViewControlSwift.swift // PWSideViewControlSwift // // Created by PeterWang on 7/16/15. // Copyright (c) 2015 PeterWang. All rights reserved. // import UIKit // // MARK: - Public Enum // public enum PWSideViewCoverMode { case FullInSuperView case CoverNavigationBarView } public enum PWSideViewSizeMode { case Scale case Constant } public enum PWSideViewHorizontalDirection: Int { case Center case Left case Right } public enum PWSideViewVerticalDirection: Int { case Center case Top case Bottom } // // MARK: - PWSideViewDirection // public struct PWSideViewDirection { var horizontal: PWSideViewHorizontalDirection = .Left var vertical: PWSideViewVerticalDirection = .Center public init() {} public init(horizontal: PWSideViewHorizontalDirection, vertical: PWSideViewVerticalDirection) { self.horizontal = horizontal self.vertical = vertical } } // // MARK: - PWSideViewSize // public struct PWSideViewSize { var widthValue: CGFloat = 1 var widthSizeMode: PWSideViewSizeMode = .Scale var heightValue: CGFloat = 1 var heightSizeMode: PWSideViewSizeMode = .Scale public init() {} public init(widthValue: CGFloat, widthSizeMode: PWSideViewSizeMode, heightValue: CGFloat, heightSizeMode: PWSideViewSizeMode) { self.widthValue = widthValue self.widthSizeMode = widthSizeMode self.heightValue = heightValue self.heightSizeMode = heightSizeMode } } // // MARK: - PWSideViewAnimationItem // public struct PWSideViewAnimationItem { var path: UIBezierPath var duration: CFTimeInterval } // // MARK: - PWSideViewItem // public class PWSideViewItem: Equatable { private(set) var view: UIView! var hiddenPosition = PWSideViewDirection() var shownPosition = PWSideViewDirection() var size = PWSideViewSize() private var constraints = [NSLayoutConstraint]() private var canShowHideSideView: Bool = true private var hidden: Bool = true public init(embedView: UIView, hiddenPosition: PWSideViewDirection = PWSideViewDirection(), shownPosition: PWSideViewDirection = PWSideViewDirection(), size: PWSideViewSize = PWSideViewSize()) { self.view = embedView if hiddenPosition.horizontal == .Center && hiddenPosition.vertical == .Center { NSException(name: "Hidden position error", reason: "PWSideViewItem not support 'center' hidden, please set one of horizontal or vertical to be NOT 'center'.", userInfo: nil).raise() } if shownPosition.horizontal == .Center && shownPosition.vertical == .Center { NSException(name: "Shown position error", reason: "PWSideViewItem not support 'center' shown, please set one of horizontal or vertical to be NOT 'center'.", userInfo: nil).raise() } self.hiddenPosition = hiddenPosition self.shownPosition = shownPosition self.size = size } } public func ==(lhs: PWSideViewItem, rhs: PWSideViewItem) -> Bool { return lhs.view == rhs.view } // // MARK: - PWSideViewControlSwift // public class PWSideViewControlSwift: UIView, UIGestureRecognizerDelegate { // MARK: - Public Variables var coverMode: PWSideViewCoverMode = .FullInSuperView { didSet { addToView() } } var maskColor: UIColor = UIColor(white: 0, alpha: 0.5) { didSet { configView() } } var maskViewDidTapped: (() -> Void)? // MARK: - Private Variables private var embeddedView: UIView! private var sideViewItems = [PWSideViewItem]() // MARK: - Initializer public init(embeddedView: UIView) { super.init(frame: embeddedView.frame) self.embeddedView = embeddedView setupView() } public override init(frame: CGRect) { super.init(frame: frame) self.embeddedView = defaultEmbeddedView() setupView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.embeddedView = defaultEmbeddedView() setupView() } private func defaultEmbeddedView() -> UIView { if let currendtWindow = UIApplication.sharedApplication().keyWindow { return currendtWindow } else { let defaultEmbeddedView = UIView(frame: UIScreen.mainScreen().bounds) return defaultEmbeddedView } } // MARK: - Public functioins public func addSideViewItem(item: PWSideViewItem) -> Int { let index = self.sideViewItems.count self.sideViewItems.append(item) addSubview(item.view) setupSideViewLayoutConstraintsByItem(item, hidden: true) return index } public func isSideViewItemHiddenAtIndex(itemIndex: Int) -> Bool { if 0..<self.sideViewItems.count ~= itemIndex { return self.sideViewItems[itemIndex].hidden } return true } public func sideViewItemAtIndex(itemIndex: Int, hidden: Bool, withDuration duration: NSTimeInterval, animated: Bool, completed: (() -> Void)?) { guard 0..<self.sideViewItems.count ~= itemIndex else { return } let item = self.sideViewItems[itemIndex] guard item.canShowHideSideView else { return } item.canShowHideSideView = false item.hidden = hidden removeConstraints(item.constraints) item.view.removeConstraints(item.constraints) setupSideViewLayoutConstraintsByItem(item, hidden: hidden) if animated { if !hidden { self.hidden = false } UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { _ in self.alpha = hidden ? 0 : 1 self.layoutIfNeeded() }, completion: { _ in item.canShowHideSideView = true self.hidden = hidden completed?() }) } else { self.alpha = hidden ? 0 : 1 item.canShowHideSideView = true self.hidden = hidden layoutIfNeeded() completed?() } } public func hideAllSideViewItemWithDuration(duration: NSTimeInterval, animated: Bool, completed: (() -> Void)?) { var needHideSideViewItems = [PWSideViewItem]() for item in self.sideViewItems { if !item.hidden { needHideSideViewItems.append(item) } } for item in needHideSideViewItems { item.canShowHideSideView = false item.hidden = true removeConstraints(item.constraints) item.view.removeConstraints(item.constraints) setupSideViewLayoutConstraintsByItem(item, hidden: true) } if animated { UIView.animateWithDuration(duration, delay: 0, options: .CurveEaseOut, animations: { _ in self.alpha = 0 self.layoutIfNeeded() }, completion: { _ in for item in needHideSideViewItems { item.canShowHideSideView = true } self.hidden = true completed?() }) } else { self.alpha = 0 for item in needHideSideViewItems { item.canShowHideSideView = true } self.hidden = true layoutIfNeeded() completed?() } } // MARK: - Private functions private func setupView() { self.hidden = true self.alpha = 0 let tapGR = UITapGestureRecognizer(target: self, action: #selector(PWSideViewControlSwift.maskViewTapped(_:))) tapGR.delegate = self addGestureRecognizer(tapGR) configView() // Add view to addToView() } private func addToView() { switch self.coverMode { case .CoverNavigationBarView: if let currendtWindow = UIApplication.sharedApplication().delegate?.window ?? nil { currendtWindow.addSubview(self) setupViewLayoutConstraints() } default: self.embeddedView.addSubview(self) setupViewLayoutConstraints() } } private func setupViewLayoutConstraints() { if let superView = self.superview { self.translatesAutoresizingMaskIntoConstraints = false let topConstraint = NSLayoutConstraint(item: self, attribute: .Top, relatedBy: .Equal, toItem: superView, attribute: .Top, multiplier: 1, constant: 0) superView.addConstraint(topConstraint) let bottomConstraint = NSLayoutConstraint(item: self, attribute: .Bottom, relatedBy: .Equal, toItem: superView, attribute: .Bottom, multiplier: 1, constant: 0) superView.addConstraint(bottomConstraint) let leadingConstraint = NSLayoutConstraint(item: self, attribute: .Leading, relatedBy: .Equal, toItem: superView, attribute: .Leading, multiplier: 1, constant: 0) superView.addConstraint(leadingConstraint) let trailingConstraint = NSLayoutConstraint(item: self, attribute: .Trailing, relatedBy: .Equal, toItem: superView, attribute: .Trailing, multiplier: 1, constant: 0) superView.addConstraint(trailingConstraint) } } private func setupSideViewLayoutConstraintsByItem(sideViewItem: PWSideViewItem, hidden: Bool) { sideViewItem.view.translatesAutoresizingMaskIntoConstraints = false let pos: PWSideViewDirection if hidden { pos = sideViewItem.hiddenPosition } else { pos = sideViewItem.shownPosition } // Horizontal. switch pos.horizontal { case .Center: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Left: let attribute: NSLayoutAttribute = hidden ? .Trailing : .Leading let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Right: let attribute: NSLayoutAttribute = hidden ? .Leading : .Trailing let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) } // Vertical. switch pos.vertical { case .Center: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Top: let attribute: NSLayoutAttribute = hidden ? .Bottom : .Top let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Bottom: let attribute: NSLayoutAttribute = hidden ? .Top : .Bottom let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: attribute, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) } // Width. switch sideViewItem.size.widthSizeMode { case .Scale: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: sideViewItem.size.widthValue, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Constant: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: sideViewItem.size.widthValue) sideViewItem.view.addConstraint(constraint) sideViewItem.constraints.append(constraint) } switch sideViewItem.size.heightSizeMode { case .Scale: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: sideViewItem.size.heightValue, constant: 0) addConstraint(constraint) sideViewItem.constraints.append(constraint) case .Constant: let constraint = NSLayoutConstraint(item: sideViewItem.view, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: sideViewItem.size.heightValue) sideViewItem.view.addConstraint(constraint) sideViewItem.constraints.append(constraint) } } // MARK: - Configure private func configView() { self.backgroundColor = self.maskColor setNeedsDisplay() } // MARK: - Gesture Recognizer Action func maskViewTapped(recognizer: UITapGestureRecognizer) { if self.maskViewDidTapped != nil { self.maskViewDidTapped!() } else { } } public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if let touchView = touch.view where (touchView.isDescendantOfView(self) && touchView != self) { return false } return true } }
mit
8e8f83c2d4796574ed33670261225590
31.4425
196
0.695384
4.824164
false
false
false
false
Johennes/firefox-ios
Client/Frontend/Browser/OpenWithSettingsViewController.swift
1
4793
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared class OpenWithSettingsViewController: UITableViewController { typealias MailtoProviderEntry = (name: String, scheme: String, enabled: Bool) var mailProviderSource = [MailtoProviderEntry]() private let prefs: Prefs private var currentChoice: String = "mailto" private let BasicCheckmarkCell = "BasicCheckmarkCell" init(prefs: Prefs) { self.prefs = prefs super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() title = Strings.SettingsOpenWithSectionName tableView.accessibilityIdentifier = "OpenWithPage.Setting.Options" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: BasicCheckmarkCell) tableView.backgroundColor = UIConstants.TableViewHeaderBackgroundColor let headerFooterFrame = CGRect(origin: CGPointZero, size: CGSize(width: self.view.frame.width, height: UIConstants.TableViewHeaderFooterHeight)) let headerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) headerView.titleLabel.text = Strings.SettingsOpenWithPageTitle headerView.showTopBorder = false headerView.showBottomBorder = true let footerView = SettingsTableSectionHeaderFooterView(frame: headerFooterFrame) footerView.showTopBorder = true footerView.showBottomBorder = false tableView.tableHeaderView = headerView tableView.tableFooterView = footerView NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(OpenWithSettingsViewController.appDidBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) appDidBecomeActive() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.prefs.setString(currentChoice, forKey: PrefsKeys.KeyMailToOption) } func appDidBecomeActive() { reloadMailProviderSource() updateCurrentChoice() tableView.reloadData() } func updateCurrentChoice() { var previousChoiceAvailable: Bool = false if let prefMailtoScheme = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { mailProviderSource.forEach({ (name, scheme, enabled) in if scheme == prefMailtoScheme { previousChoiceAvailable = enabled } }) } if !previousChoiceAvailable { self.prefs.setString(mailProviderSource[0].scheme, forKey: PrefsKeys.KeyMailToOption) } if let updatedMailToClient = self.prefs.stringForKey(PrefsKeys.KeyMailToOption) { self.currentChoice = updatedMailToClient } } func reloadMailProviderSource() { if let path = NSBundle.mainBundle().pathForResource("MailSchemes", ofType: "plist"), let dictRoot = NSArray(contentsOfFile: path) { mailProviderSource = dictRoot.map { dict in (name: dict["name"] as! String, scheme: dict["scheme"] as! String, enabled: canOpenMailScheme(dict["scheme"] as! String)) } } } func canOpenMailScheme(scheme: String) -> Bool { if let url = NSURL(string: scheme) { return UIApplication.sharedApplication().canOpenURL(url) } return false } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(BasicCheckmarkCell, forIndexPath: indexPath) let option = mailProviderSource[indexPath.row] cell.textLabel?.attributedText = NSAttributedString.tableRowTitle(option.name) cell.accessoryType = (currentChoice == option.scheme && option.enabled) ? .Checkmark : .None cell.textLabel?.textColor = option.enabled ? UIConstants.TableViewRowTextColor : UIConstants.TableViewDisabledRowTextColor cell.userInteractionEnabled = option.enabled return cell } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mailProviderSource.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.currentChoice = mailProviderSource[indexPath.row].scheme tableView.reloadData() } }
mpl-2.0
8e150116e259825b785a81db3f879333
38.61157
195
0.704986
5.753902
false
false
false
false
andyyhope/Elbbbird
Elbbbird/Controller/ShotViewController.swift
1
2816
// // ShotViewController.swift // Elbbbird // // Created by Andyy Hope on 20/03/2016. // Copyright © 2016 Andyy Hope. All rights reserved. // import UIKit class ShotViewController: UIViewController { @IBOutlet var shotImageView: UIImageView! @IBOutlet var visualEffectContainerView: UIView! @IBOutlet var visualEffectView: UIVisualEffectView! @IBOutlet var tableView: UITableView! @IBOutlet var activityIndicatorView: UIActivityIndicatorView! var viewModel: ShotViewModel? { didSet { if tableView != nil { tableView.reloadData() activityIndicatorView.stopAnimating() } } } override func viewDidLoad() { super.viewDidLoad() tableView.register(ShotCommentTableViewCell) requestShot() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension ShotViewController : UITableViewDataSource { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel?.comments.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: ShotCommentTableViewCell = tableView.dequeueReusableCell(forIndexPath: indexPath) guard let viewModel = viewModel?.viewModelForCommentCell(atIndexPath: indexPath) else { return cell } cell.usernameLabel.text = viewModel.username cell.commentLabel.text = viewModel.body // cell.likesLabel.text = viewModel.likes return cell } } extension ShotViewController : UITableViewDelegate { func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return ShotCommentTableViewCell.defaultHeight } } // MARK: - Request extension ShotViewController { func requestShot() { guard let shotID = viewModel?.shot.id else { return } DribbbleRequester.requestShot(forShotID: shotID) { [weak self] (shot) -> Void in guard let shot = shot else { return } self?.viewModel = ShotViewModel(shot: shot) self?.requestComments() } } func requestComments() { guard let shotID = viewModel?.shot.id else { return } DribbbleRequester.requestComments(forShotID: shotID) { [weak self] (comments) -> Void in guard let shot = self?.viewModel?.shot else { return } self?.viewModel = ShotViewModel(shot: shot, comments: comments) } } }
gpl-3.0
210bb8d8222171d42b4eedbc5d968b55
27.15
112
0.641918
5.434363
false
false
false
false
Tyrant2013/LeetCodePractice
LeetCodePractice/Easy/58_Length_Of_Last_Word.swift
1
1343
// // Length_Of_Last_Word.swift // LeetCodePractice // // Created by 庄晓伟 on 2018/2/11. // Copyright © 2018年 Zhuang Xiaowei. All rights reserved. // import UIKit //Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. // //If the last word does not exist, return 0. // //Note: A word is defined as a character sequence consists of non-space characters only. // //Example: // //Input: "Hello World" //Output: 5 class Length_Of_Last_Word: Solution { override func ExampleTest() { [ "Hello World", // 5 "a", // 1 "b ", // 1 ].forEach { str in print("str: \(str), last word len: \(self.lengthOfLastWord(str))") } } func lengthOfLastWord(_ s: String) -> Int { if s.count == 0 { return 0 } var len = s.count - 1 let sequeue = s.map({ $0 }) var ret = 0 while len >= 0 { if sequeue[len] != " " { ret += 1 } else { if ret == 0 && sequeue[len] == " " { len -= 1 continue } return ret } len -= 1 } return ret } }
mit
7c783595066de69791caf1feb7c91236
22.821429
135
0.474513
3.935103
false
false
false
false
legendecas/Rocket.Chat.iOS
Rocket.Chat.Shared/Extensions/UIColor+Hex.swift
1
11021
// // Color+HexAndCSSColorNames.swift // // Created by Norman Basham on 12/8/15. // Copyright © 2015 Black Labs. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit // swiftlint:disable force_unwrapping control_statement syntactic_sugar extension UIColor { /** Creates an immuatble UIColor instance specified by a hex string, CSS color name, or nil. - parameter hexString: A case insensitive String? representing a hex or CSS value e.g. - **"abc"** - **"abc7"** - **"#abc7"** - **"00FFFF"** - **"#00FFFF"** - **"00FFFF77"** - **"Orange", "Azure", "Tomato"** Modern browsers support 140 color names (<http://www.w3schools.com/cssref/css_colornames.asp>) - **"Clear"** [UIColor clearColor] - **"Transparent"** [UIColor clearColor] - **nil** [UIColor clearColor] - **empty string** [UIColor clearColor] */ convenience init(hex: String?) { let normalizedHexString: String = UIColor.normalize(hex) var c: CUnsignedInt = 0 Scanner(string: normalizedHexString).scanHexInt32(&c) self.init(red:UIColorMasks.redValue(c), green:UIColorMasks.greenValue(c), blue:UIColorMasks.blueValue(c), alpha:UIColorMasks.alphaValue(c)) } /** Returns a hex equivalent of this UIColor. - Parameter includeAlpha: Optional parameter to include the alpha hex. color.hexDescription() -> "ff0000" color.hexDescription(true) -> "ff0000aa" - Returns: A new string with `String` with the color's hexidecimal value. */ func hexDescription(_ includeAlpha: Bool = false) -> String { if self.cgColor.numberOfComponents == 4 { let components = self.cgColor.components let red = Float((components?[0])!) * 255.0 let green = Float((components?[1])!) * 255.0 let blue = Float((components?[2])!) * 255.0 let alpha = Float((components?[3])!) * 255.0 if (includeAlpha) { return String.init(format: "%02x%02x%02x%02x", Int(red), Int(green), Int(blue), Int(alpha)) } else { return String.init(format: "%02x%02x%02x", Int(red), Int(green), Int(blue)) } } else { return "Color not RGB." } } fileprivate enum UIColorMasks: CUnsignedInt { case redMask = 0xff000000 case greenMask = 0x00ff0000 case blueMask = 0x0000ff00 case alphaMask = 0x000000ff static func redValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & redMask.rawValue) >> 24 let f: CGFloat = CGFloat(i)/255.0 return f } static func greenValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & greenMask.rawValue) >> 16 let f: CGFloat = CGFloat(i)/255.0 return f } static func blueValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = (value & blueMask.rawValue) >> 8 let f: CGFloat = CGFloat(i)/255.0 return f } static func alphaValue(_ value: CUnsignedInt) -> CGFloat { let i: CUnsignedInt = value & alphaMask.rawValue let f: CGFloat = CGFloat(i)/255.0 return f } } fileprivate static func normalize(_ hex: String?) -> String { guard var hexString = hex else { return "00000000" } let cssColor = cssToHexDictionairy[hexString.uppercased()] if cssColor != nil { return cssColor! + "ff" } let hasHash: Bool = hexString.hasPrefix("#") if (hasHash) { hexString = String(hexString.characters.dropFirst()) } if hexString.characters.count == 3 || hexString.characters.count == 4 { let redHex = hexString.substring(to: hexString.characters.index(hexString.startIndex, offsetBy: 1)) let greenHex = hexString.substring(with: Range<String.Index>(hexString.characters.index(hexString.startIndex, offsetBy: 1) ..< hexString.characters.index(hexString.startIndex, offsetBy: 2))) let blueHex = hexString.substring(with: Range<String.Index>(hexString.characters.index(hexString.startIndex, offsetBy: 2) ..< hexString.characters.index(hexString.startIndex, offsetBy: 3))) var alphaHex = "" if hexString.characters.count == 4 { alphaHex = hexString.substring(from: hexString.characters.index(hexString.startIndex, offsetBy: 3)) } hexString = redHex + redHex + greenHex + greenHex + blueHex + blueHex + alphaHex + alphaHex } let hasAlpha = hexString.characters.count > 7 if (!hasAlpha) { hexString += "ff" } return hexString } /** All modern browsers support the following 140 color names (see http://www.w3schools.com/cssref/css_colornames.asp) */ fileprivate static func hexFromCssName(_ cssName: String) -> String { let key = cssName.uppercased() let hex = cssToHexDictionairy[key] if hex == nil { return cssName } return hex! } fileprivate static let cssToHexDictionairy: Dictionary<String, String> = [ "CLEAR": "00000000", "TRANSPARENT": "00000000", "": "00000000", "ALICEBLUE": "F0F8FF", "ANTIQUEWHITE": "FAEBD7", "AQUA": "00FFFF", "AQUAMARINE": "7FFFD4", "AZURE": "F0FFFF", "BEIGE": "F5F5DC", "BISQUE": "FFE4C4", "BLACK": "000000", "BLANCHEDALMOND": "FFEBCD", "BLUE": "0000FF", "BLUEVIOLET": "8A2BE2", "BROWN": "A52A2A", "BURLYWOOD": "DEB887", "CADETBLUE": "5F9EA0", "CHARTREUSE": "7FFF00", "CHOCOLATE": "D2691E", "CORAL": "FF7F50", "CORNFLOWERBLUE": "6495ED", "CORNSILK": "FFF8DC", "CRIMSON": "DC143C", "CYAN": "00FFFF", "DARKBLUE": "00008B", "DARKCYAN": "008B8B", "DARKGOLDENROD": "B8860B", "DARKGRAY": "A9A9A9", "DARKGREY": "A9A9A9", "DARKGREEN": "006400", "DARKKHAKI": "BDB76B", "DARKMAGENTA": "8B008B", "DARKOLIVEGREEN": "556B2F", "DARKORANGE": "FF8C00", "DARKORCHID": "9932CC", "DARKRED": "8B0000", "DARKSALMON": "E9967A", "DARKSEAGREEN": "8FBC8F", "DARKSLATEBLUE": "483D8B", "DARKSLATEGRAY": "2F4F4F", "DARKSLATEGREY": "2F4F4F", "DARKTURQUOISE": "00CED1", "DARKVIOLET": "9400D3", "DEEPPINK": "FF1493", "DEEPSKYBLUE": "00BFFF", "DIMGRAY": "696969", "DIMGREY": "696969", "DODGERBLUE": "1E90FF", "FIREBRICK": "B22222", "FLORALWHITE": "FFFAF0", "FORESTGREEN": "228B22", "FUCHSIA": "FF00FF", "GAINSBORO": "DCDCDC", "GHOSTWHITE": "F8F8FF", "GOLD": "FFD700", "GOLDENROD": "DAA520", "GRAY": "808080", "GREY": "808080", "GREEN": "008000", "GREENYELLOW": "ADFF2F", "HONEYDEW": "F0FFF0", "HOTPINK": "FF69B4", "INDIANRED": "CD5C5C", "INDIGO": "4B0082", "IVORY": "FFFFF0", "KHAKI": "F0E68C", "LAVENDER": "E6E6FA", "LAVENDERBLUSH": "FFF0F5", "LAWNGREEN": "7CFC00", "LEMONCHIFFON": "FFFACD", "LIGHTBLUE": "ADD8E6", "LIGHTCORAL": "F08080", "LIGHTCYAN": "E0FFFF", "LIGHTGOLDENRODYELLOW": "FAFAD2", "LIGHTGRAY": "D3D3D3", "LIGHTGREY": "D3D3D3", "LIGHTGREEN": "90EE90", "LIGHTPINK": "FFB6C1", "LIGHTSALMON": "FFA07A", "LIGHTSEAGREEN": "20B2AA", "LIGHTSKYBLUE": "87CEFA", "LIGHTSLATEGRAY": "778899", "LIGHTSLATEGREY": "778899", "LIGHTSTEELBLUE": "B0C4DE", "LIGHTYELLOW": "FFFFE0", "LIME": "00FF00", "LIMEGREEN": "32CD32", "LINEN": "FAF0E6", "MAGENTA": "FF00FF", "MAROON": "800000", "MEDIUMAQUAMARINE": "66CDAA", "MEDIUMBLUE": "0000CD", "MEDIUMORCHID": "BA55D3", "MEDIUMPURPLE": "9370DB", "MEDIUMSEAGREEN": "3CB371", "MEDIUMSLATEBLUE": "7B68EE", "MEDIUMSPRINGGREEN": "00FA9A", "MEDIUMTURQUOISE": "48D1CC", "MEDIUMVIOLETRED": "C71585", "MIDNIGHTBLUE": "191970", "MINTCREAM": "F5FFFA", "MISTYROSE": "FFE4E1", "MOCCASIN": "FFE4B5", "NAVAJOWHITE": "FFDEAD", "NAVY": "000080", "OLDLACE": "FDF5E6", "OLIVE": "808000", "OLIVEDRAB": "6B8E23", "ORANGE": "FFA500", "ORANGERED": "FF4500", "ORCHID": "DA70D6", "PALEGOLDENROD": "EEE8AA", "PALEGREEN": "98FB98", "PALETURQUOISE": "AFEEEE", "PALEVIOLETRED": "DB7093", "PAPAYAWHIP": "FFEFD5", "PEACHPUFF": "FFDAB9", "PERU": "CD853F", "PINK": "FFC0CB", "PLUM": "DDA0DD", "POWDERBLUE": "B0E0E6", "PURPLE": "800080", "RED": "FF0000", "ROSYBROWN": "BC8F8F", "ROYALBLUE": "4169E1", "SADDLEBROWN": "8B4513", "SALMON": "FA8072", "SANDYBROWN": "F4A460", "SEAGREEN": "2E8B57", "SEASHELL": "FFF5EE", "SIENNA": "A0522D", "SILVER": "C0C0C0", "SKYBLUE": "87CEEB", "SLATEBLUE": "6A5ACD", "SLATEGRAY": "708090", "SLATEGREY": "708090", "SNOW": "FFFAFA", "SPRINGGREEN": "00FF7F", "STEELBLUE": "4682B4", "TAN": "D2B48C", "TEAL": "008080", "THISTLE": "D8BFD8", "TOMATO": "FF6347", "TURQUOISE": "40E0D0", "VIOLET": "EE82EE", "WHEAT": "F5DEB3", "WHITE": "FFFFFF", "WHITESMOKE": "F5F5F5", "YELLOW": "FFFF00", "YELLOWGREEN": "9ACD32" ] }
mit
16d064e168105e2769a73b588be84525
34.779221
202
0.565517
3.473054
false
false
false
false
jensmeder/DarkLightning
Examples/Messenger/iOS/Sources/AppDelegate.swift
1
1079
// // AppDelegate.swift // Messenger-iOS // // Created by Jens Meder on 05.04.17. // // import UIKit import DarkLightning @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var port: DarkLightning.Port? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let textView = Memory<UITextView?>(initialValue: nil) let navigationItem = Memory<UINavigationItem?>(initialValue: nil) port = DevicePort(delegate: MessengerDelegate(textView: textView, navigationItem: navigationItem)) port?.open() window = UIWindow() window?.rootViewController = UINavigationController( rootViewController: ViewController( title: "Disconnected", textView: textView, header: navigationItem, port: port! ) ) window?.makeKeyAndVisible() application.isIdleTimerDisabled = true return true } }
mit
b94572f8b3d0e38c7fbcc553f9aab673
26.666667
144
0.661724
5.477157
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/GraphQLModel/BubbleQuizGraphQLModel.swift
1
2109
// // BubbleQuizGraphQLModel.swift // AwesomeCore // // Created by Leonardo Vinicius Kaminski Ferreira on 25/02/19. // import Foundation public struct BubbleQuizGraphQLModel { fileprivate static let cardModel = "id subtitle title description position type media{id title author { id name } type channel { id title }} settings { start_date theme_color icon } content_asset {id duration contentType filesize url renditions(labels: [\"mp4\", \"hls\"]) {id url status} captions {id is_default label language url} } small_cover_asset { url } large_cover_asset { url }" fileprivate static let quizCategoriesModelSrt: String = "{ ftuQuiz(id: 1) { id title subtitle questions{ id icon name title subtitle answers{ id title } } } }" static func quizCategoriesModel() -> [String: AnyObject] { return ["query": BubbleQuizGraphQLModel.quizCategoriesModelSrt as AnyObject] } // MARK: - Update bubble answers mutation fileprivate static var cardLimitText: String = ", cardLimit: 3" fileprivate static let mutateSubmitAnswers = "mutation { submitQuizResponse(distinctId: \"%@\", answers: [%@]%@){ startedAt, cards{ \(cardModel) }, currentCard{ \(cardModel) } } }" public static func submitAnswers(_ distinctId: String, answerIds: [Int], cardLimit: Bool = false) -> [String: AnyObject] { var ids: String = "" for id in answerIds { ids.append(contentsOf: ",\(id)") } let limit: String = cardLimit ? cardLimitText : "" return ["query": String(format: mutateSubmitAnswers, arguments: [distinctId, ids, limit]) as AnyObject] } // MARK: - User Journey Model private static let journeyModel = "{ journey(identifier: \"%@\"%@){ startedAt, cards{ \(cardModel) }, currentCard{ \(cardModel) } } }" public static func queryUserJourney(withIdentifier id: String, cardLimit: Bool = false) -> [String: AnyObject] { let limit: String = cardLimit ? cardLimitText : "" return ["query": String(format: journeyModel, arguments: [id, limit]) as AnyObject] } }
mit
a5431b4dd8a57ba7cd35e329fba57bbd
48.046512
393
0.667141
4.36646
false
false
false
false
frajaona/LiFXSwiftKit
Pods/socks/Sources/SocksCore/Select.swift
1
3820
// Copyright (c) 2016, Kyle Fuller // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #if os(Linux) import Glibc @_exported import struct Glibc.timeval private let system_select = Glibc.select #else import Darwin @_exported import struct Darwin.timeval private let system_select = Darwin.select #endif extension timeval { public init(seconds: Int) { self = timeval(tv_sec: seconds, tv_usec: 0) } public init(seconds: Double) { let sec = Int(seconds) #if os(Linux) let intType = Int.self #else let intType = Int32.self #endif let microsec = intType.init((seconds - Double(sec)) * pow(10.0, 6)) self = timeval(tv_sec: sec, tv_usec: microsec) } } private func filter(_ sockets: [Descriptor]?, _ set: inout fd_set) -> [Descriptor] { return sockets?.filter { fdIsSet($0, &set) } ?? [] } public func select(reads: [Descriptor] = [], writes: [Descriptor] = [], errors: [Descriptor] = [], timeout: timeval? = nil) throws -> (reads: [Descriptor], writes: [Descriptor], errors: [Descriptor]) { var readFDs = fd_set() fdZero(&readFDs) reads.forEach { fdSet($0, &readFDs) } var writeFDs = fd_set() fdZero(&writeFDs) writes.forEach { fdSet($0, &writeFDs) } var errorFDs = fd_set() fdZero(&errorFDs) errors.forEach { fdSet($0, &errorFDs) } let maxFD = (reads + writes + errors).reduce(0, max) let result: Int32 if let timeout = timeout { var timeout = timeout result = system_select(maxFD + 1, &readFDs, &writeFDs, &errorFDs, &timeout) } else { result = system_select(maxFD + 1, &readFDs, &writeFDs, &errorFDs, nil) } if result == 0 { return ([], [], []) } else if result > 0 { return ( filter(reads, &readFDs), filter(writes, &writeFDs), filter(errors, &errorFDs) ) } throw SocksError(.selectFailed(reads: reads, writes: writes, errors: errors)) } extension RawSocket { /// Allows user to wait for the socket to have readable bytes for /// up to the specified timeout. Nil timeout means wait forever. /// Returns true if data is ready to be read, false if timed out. public func waitForReadableData(timeout: timeval?) throws -> Bool { let (readables, _, _) = try select(reads: [descriptor], timeout: timeout) return !readables.isEmpty } }
apache-2.0
57f0a792db1ec20e4393e42720167b45
35.037736
84
0.65
4.244444
false
false
false
false