repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
MNTDeveloppement/MNTAppAnimations
MNTApp/Controllers/HomeViewController.swift
1
1447
// // HomeViewController.swift // MNTApp // // Created by Mehdi Sqalli on 30/12/14. // Copyright (c) 2014 MNT Developpement. All rights reserved. // import UIKit import QuartzCore class HomeViewController: UIViewController { // let logo = UIImageView(image: UIImage(named: "MNTDev")!) override func viewDidLoad() { super.viewDidLoad() // logo.layer.position = CGPoint(x: view.layer.bounds.size.width / 2, y: view.layer.bounds.size.height / 2) // view.layer.mask = logo.layer } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // view.layer.mask = nil } @IBAction func logoutClicked(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
itsaboutcode/WordPress-iOS
WordPress/WordPressShareExtension/SharedCoreDataStack.swift
2
13559
import Foundation import CoreData import WordPressKit /// NSPersistentContainer subclass that defaults to the shared container directory /// final class SharedPersistentContainer: NSPersistentContainer { internal override class func defaultDirectoryURL() -> URL { var url = super.defaultDirectoryURL() if let newURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: WPAppGroupName) { url = newURL } return url } } class SharedCoreDataStack { // MARK: - Private Properties fileprivate let modelName: String fileprivate lazy var storeContainer: SharedPersistentContainer = { let container = SharedPersistentContainer(name: self.modelName) container.loadPersistentStores { (storeDescription, error) in if let error = error as NSError? { DDLogError("Error loading persistent stores: \(error), \(error.userInfo)") } } return container }() // MARK: - Public Properties /// Returns the managed context associated with the main queue /// lazy var managedContext: NSManagedObjectContext = { return self.storeContainer.viewContext }() // MARK: - Initializers /// Initialize the SharedPersistentContainer using the standard Extensions model. /// convenience init() { self.init(modelName: Constants.sharedModelName) } /// Initialize the core data stack with the given model name. /// /// This initializer is meant for testing. You probably want to use the convenience `init()` that uses the standard Extensions model /// /// - Parameters: /// - modelName: Name of the model to initialize the SharedPersistentContainer with. /// init(modelName: String) { self.modelName = modelName } // MARK: - Public Funcntions /// Commit unsaved changes (if any exist) using the main queue's managed context /// func saveContext() { guard managedContext.hasChanges else { return } do { try managedContext.save() } catch let error as NSError { DDLogError("Error saving context: \(error), \(error.userInfo)") } } } // MARK: - Persistence Helpers - Fetching extension SharedCoreDataStack { /// Fetches the group ID for the provided session ID. /// /// - Parameter sessionID: the session ID /// - Returns: group ID or nil if session does not have an associated group /// func fetchGroupID(for sessionID: String) -> String? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "UploadOperation") request.predicate = NSPredicate(format: "(backgroundSessionIdentifier == %@)", sessionID) request.fetchLimit = 1 guard let results = (try? managedContext.fetch(request)) as? [UploadOperation], let groupID = results.first?.groupID else { return nil } return groupID } /// Fetch the post upload op for the provided managed object ID string /// /// - Parameter objectID: Managed object ID string for a given post upload op /// - Returns: PostUploadOperation or nil /// func fetchPostUploadOp(withObjectID objectID: String) -> PostUploadOperation? { guard let storeCoordinator = managedContext.persistentStoreCoordinator, let url = URL(string: objectID), let managedObjectID = storeCoordinator.managedObjectID(forURIRepresentation: url) else { return nil } return fetchPostUploadOp(withObjectID: managedObjectID) } /// Fetch the post upload op for the provided managed object ID /// /// - Parameter postUploadOpObjectID: Managed object ID for a given post upload op /// - Returns: PostUploadOperation or nil /// func fetchPostUploadOp(withObjectID postUploadOpObjectID: NSManagedObjectID) -> PostUploadOperation? { var postUploadOp: PostUploadOperation? do { postUploadOp = try managedContext.existingObject(with: postUploadOpObjectID) as? PostUploadOperation } catch { DDLogError("Error loading PostUploadOperation Object with ID: \(postUploadOpObjectID)") } return postUploadOp } /// Fetch the upload op that represents a post for a given group ID. /// /// NOTE: There will only ever be one post associated with a group of upload ops. /// /// - Parameter groupID: group ID for a set of upload ops /// - Returns: post PostUploadOperation or nil /// func fetchPostUploadOp(for groupID: String) -> PostUploadOperation? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "PostUploadOperation") request.predicate = NSPredicate(format: "(groupID == %@)", groupID) request.fetchLimit = 1 guard let results = (try? managedContext.fetch(request)) as? [PostUploadOperation] else { return nil } return results.first } /// Fetch the media upload ops for a given group ID. /// /// - Parameter groupID: group ID for a set of upload ops /// - Returns: An array of MediaUploadOperations or nil /// func fetchMediaUploadOps(for groupID: String) -> [MediaUploadOperation]? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MediaUploadOperation") request.predicate = NSPredicate(format: "(groupID == %@)", groupID) guard let results = (try? managedContext.fetch(request)) as? [MediaUploadOperation] else { DDLogError("Failed to fetch MediaUploadOperation for group ID: \(groupID)") return nil } return results } /// Fetch the media upload op that matches the provided filename and background session ID /// /// - Parameters: /// - fileName: the name of the local (and remote) file associated with a upload op /// - sessionID: background session ID /// - Returns: MediaUploadOperation or nil /// func fetchMediaUploadOp(for fileName: String, with sessionID: String) -> MediaUploadOperation? { guard let fileNameWithoutExtension = URL(string: fileName)?.deletingPathExtension().lastPathComponent else { return nil } let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MediaUploadOperation") request.predicate = NSPredicate(format: "(fileName BEGINSWITH %@ AND backgroundSessionIdentifier == %@)", fileNameWithoutExtension.lowercased(), sessionID) request.fetchLimit = 1 guard let results = (try? managedContext.fetch(request)) as? [MediaUploadOperation] else { return nil } return results.first } /// Fetch the post and media upload ops for a given URLSession taskIdentifier. /// /// NOTE: Because the WP API allows us to upload multiple media files in a single request, there /// will most likely be multiple upload ops for a given task id. /// /// - Parameters: /// - taskIdentifier: the taskIdentifier from a URLSessionTask /// - sessionID: background session ID /// - Returns: An array of UploadOperations or nil /// func fetchSessionUploadOps(for taskIdentifier: Int, with sessionID: String) -> [UploadOperation]? { var uploadOps: [UploadOperation]? let request = NSFetchRequest<NSFetchRequestResult>(entityName: "UploadOperation") request.predicate = NSPredicate(format: "(backgroundSessionTaskID == %d AND backgroundSessionIdentifier == %@)", taskIdentifier, sessionID) do { uploadOps = try managedContext.fetch(request) as! [MediaUploadOperation] } catch { DDLogError("Failed to fetch MediaUploadOperation: \(error)") } return uploadOps } } // MARK: - Persistence Helpers - Saving and Updating extension SharedCoreDataStack { /// Updates the status using the given uploadOp's ObjectID. /// /// - Parameters: /// - status: New status /// - uploadOpObjectID: Managed object ID for a given upload op /// func updateStatus(_ status: UploadOperation.UploadStatus, forUploadOpWithObjectID uploadOpObjectID: NSManagedObjectID) { var uploadOp: UploadOperation? do { uploadOp = try managedContext.existingObject(with: uploadOpObjectID) as? UploadOperation } catch { DDLogError("Error setting \(status.stringValue) status for UploadOperation Object with ID: \(uploadOpObjectID) — could not fetch object.") return } uploadOp?.currentStatus = status saveContext() } /// Saves a new media upload operation with the provided values /// /// - Parameters: /// - remoteMedia: RemoteMedia object containing the values to persist /// - sessionID: background session ID /// - groupIdentifier: group ID for a set of upload ops /// - siteID: New site ID /// - status: New status /// - Returns: Managed object ID of newly saved media upload operation object /// func saveMediaOperation(_ remoteMedia: RemoteMedia, sessionID: String, groupIdentifier: String, siteID: NSNumber, with status: UploadOperation.UploadStatus) -> NSManagedObjectID { let mediaUploadOp = MediaUploadOperation(context: managedContext) mediaUploadOp.updateWithMedia(remote: remoteMedia) mediaUploadOp.backgroundSessionIdentifier = sessionID mediaUploadOp.groupID = groupIdentifier mediaUploadOp.created = NSDate() mediaUploadOp.currentStatus = status mediaUploadOp.siteID = siteID.int64Value saveContext() return mediaUploadOp.objectID } /// Updates the remote media URL and remote media ID on an upload op that corresponds with the provided /// file name. If a parameter is nil, that specific param will not be updated. /// /// Note: We are searching for the upload op using a filename because a given task ID can have /// multiple files associated with it. /// /// - Parameters: /// - fileName: the fileName from a URLSessionTask /// - sessionID: background session ID /// - remoteMediaID: remote media ID /// - remoteURL: remote media URL string /// func updateMediaOperation(for fileName: String, with sessionID: String, remoteMediaID: Int64?, remoteURL: String?, width: Int32?, height: Int32?) { guard let mediaUploadOp = fetchMediaUploadOp(for: fileName, with: sessionID) else { DDLogError("Error loading UploadOperation Object with File Name: \(fileName)") return } if let remoteMediaID = remoteMediaID { mediaUploadOp.remoteMediaID = remoteMediaID } if let width = width { mediaUploadOp.width = width } if let height = height { mediaUploadOp.height = height } mediaUploadOp.remoteURL = remoteURL saveContext() } /// Saves a new post upload operation with the provided values /// /// - Parameters: /// - remotePost: RemotePost object containing the values to persist. /// - groupIdentifier: group ID for a set of upload ops /// - status: New status /// - Returns: Managed object ID of newly saved post upload operation object /// func savePostOperation(_ remotePost: RemotePost, groupIdentifier: String, with status: UploadOperation.UploadStatus) -> NSManagedObjectID { let postUploadOp = PostUploadOperation(context: managedContext) postUploadOp.updateWithPost(remote: remotePost) postUploadOp.groupID = groupIdentifier postUploadOp.created = NSDate() postUploadOp.currentStatus = status saveContext() return postUploadOp.objectID } /// Update an existing post upload operation with a new status and remote post ID /// /// - Parameters: /// - status: New status /// - remotePostID: New remote post ID /// - postUploadOpObjectID: Managed object ID for a given post upload op /// func updatePostOperation(with status: UploadOperation.UploadStatus, remotePostID: Int64, forPostUploadOpWithObjectID postUploadOpObjectID: NSManagedObjectID) { guard let postUploadOp = (try? managedContext.existingObject(with: postUploadOpObjectID)) as? PostUploadOperation else { DDLogError("Error loading PostUploadOperation Object with ID: \(postUploadOpObjectID)") return } postUploadOp.currentStatus = status postUploadOp.remotePostID = remotePostID saveContext() } /// Update an existing upload operations with a new background session task ID /// /// - Parameters: /// - taskID: New background session task ID /// - uploadOpObjectID: Managed object ID for a given upload op /// func updateTaskID(_ taskID: NSNumber, forUploadOpWithObjectID uploadOpObjectID: NSManagedObjectID) { var uploadOp: UploadOperation? do { uploadOp = try managedContext.existingObject(with: uploadOpObjectID) as? UploadOperation } catch { DDLogError("Error loading UploadOperation Object with ID: \(uploadOpObjectID)") return } uploadOp?.backgroundSessionTaskID = taskID.int32Value saveContext() } } // MARK: - Constants extension SharedCoreDataStack { struct Constants { static let sharedModelName = "Extensions" } }
gpl-2.0
abertelrud/swift-package-manager
Sources/PackageModel/Product.swift
2
8476
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2021 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 // //===----------------------------------------------------------------------===// import Basics import TSCBasic import struct TSCUtility.PolymorphicCodableArray public class Product: Codable { /// The name of the product. public let name: String /// Fully qualified name for this product: package ID + name of this product public let identity: String /// The type of product to create. public let type: ProductType /// The list of targets to combine to form the product. /// /// This is never empty, and is only the targets which are required to be in /// the product, but not necessarily their transitive dependencies. @PolymorphicCodableArray public var targets: [Target] /// The path to test entry point file. public let testEntryPointPath: AbsolutePath? /// The suffix for REPL product name. public static let replProductSuffix: String = "__REPL" public init(package: PackageIdentity, name: String, type: ProductType, targets: [Target], testEntryPointPath: AbsolutePath? = nil) throws { guard !targets.isEmpty else { throw InternalError("Targets cannot be empty") } if type == .executable { guard targets.executables.count == 1 else { throw InternalError("Executable products should have exactly one executable target.") } } if testEntryPointPath != nil { guard type == .test else { throw InternalError("Test entry point path should only be set on test products") } } self.name = name self.type = type self.identity = package.description.lowercased() + "_" + name self._targets = .init(wrappedValue: targets) self.testEntryPointPath = testEntryPointPath } } extension Product: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } public static func == (lhs: Product, rhs: Product) -> Bool { ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } } /// The type of product. public enum ProductType: Equatable, Hashable { /// The type of library. public enum LibraryType: String, Codable { /// Static library. case `static` /// Dynamic library. case `dynamic` /// The type of library is unspecified and should be decided by package manager. case automatic } /// A library product. case library(LibraryType) /// An executable product. case executable /// An executable code snippet. case snippet /// An plugin product. case plugin /// A test product. case test public var isLibrary: Bool { guard case .library = self else { return false } return true } } /// The products requested of a package. /// /// Any product which matches the filter will be used for dependency resolution, whereas unrequested products will be ignored. /// /// Requested products need not actually exist in the package. Under certain circumstances, the resolver may request names whose package of origin are unknown. The intended package will recognize and fulfill the request; packages that do not know what it is will simply ignore it. public enum ProductFilter: Equatable, Hashable { /// All products, targets, and tests are requested. /// /// This is used for root packages. case everything /// A set of specific products requested by one or more client packages. case specific(Set<String>) /// No products, targets, or tests are requested. public static var nothing: ProductFilter { .specific([]) } public func union(_ other: ProductFilter) -> ProductFilter { switch self { case .everything: return .everything case .specific(let set): switch other { case .everything: return .everything case .specific(let otherSet): return .specific(set.union(otherSet)) } } } public mutating func formUnion(_ other: ProductFilter) { self = self.union(other) } public func contains(_ product: String) -> Bool { switch self { case .everything: return true case .specific(let set): return set.contains(product) } } public func merge(_ other: ProductFilter) -> ProductFilter { switch (self, other) { case (.everything, _): return .everything case (_, .everything): return .everything case (.specific(let mine), .specific(let other)): return .specific(mine.union(other)) } } } // MARK: - CustomStringConvertible extension Product: CustomStringConvertible { public var description: String { return "<Product: \(name)>" } } extension ProductType: CustomStringConvertible { public var description: String { switch self { case .executable: return "executable" case .snippet: return "snippet" case .test: return "test" case .library(let type): switch type { case .automatic: return "library" case .dynamic: return "dynamic library" case .static: return "static library" } case .plugin: return "plugin" } } } extension ProductFilter: CustomStringConvertible { public var description: String { switch self { case .everything: return "[everything]" case .specific(let set): return "[\(set.sorted().joined(separator: ", "))]" } } } // MARK: - Codable extension ProductType: Codable { private enum CodingKeys: String, CodingKey { case library, executable, snippet, plugin, test } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case let .library(a1): var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .library) try unkeyedContainer.encode(a1) case .executable: try container.encodeNil(forKey: .executable) case .snippet: try container.encodeNil(forKey: .snippet) case .plugin: try container.encodeNil(forKey: .plugin) case .test: try container.encodeNil(forKey: .test) } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) guard let key = values.allKeys.first(where: values.contains) else { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key")) } switch key { case .library: var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key) let a1 = try unkeyedValues.decode(ProductType.LibraryType.self) self = .library(a1) case .test: self = .test case .executable: self = .executable case .snippet: self = .snippet case .plugin: self = .plugin } } } extension ProductFilter: Codable { public func encode(to encoder: Encoder) throws { let optionalSet: Set<String>? switch self { case .everything: optionalSet = nil case .specific(let set): optionalSet = set } var container = encoder.singleValueContainer() try container.encode(optionalSet?.sorted()) } public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .everything } else { self = .specific(Set(try container.decode([String].self))) } } }
apache-2.0
shawnirvin/Terminal-iOS-Swift
Terminal/Models/DefaultsFunction.swift
1
1935
// // DefaultsFunction.swift // Terminal // // Created by Shawn Irvin on 12/4/15. // Copyright © 2015 Shawn Irvin. All rights reserved. // import Foundation class DefaultsFunction: Function, Helpful { init() { super.init(identifier: "^defaults (write \\S+.*|read \\S+.*|restore)", name: "defaults") } override func execute(command: Command, completion: (response: String?) -> Void) { if command.rawValue.lowercaseString == "defaults restore" { TerminalViewController.currentInstance.terminalTextView.getInput("Type 1 to confirm, 0 to cancel: ", inputType: .Normal) { input in var output = "" if input == "1" { Setting.restoreDefaults() output = "Defaults restored" } else { output = "Restore cancelled" } completion(response: output) } return } else { let action = command.elements[1] let term = command.elements[2] var output: String? if action == "read" { if let value = Setting.defaultForSettingType(SettingType(rawValue: term)) { output = value.description } else { output = "Invalid default" } } else if action == "write" { if term == "time" { let stringValue = NSString(string: command.elements[3]) let value = stringValue.boolValue Setting.setDefaultForSettingType(value, type: SettingType(rawValue: term)) } } completion(response: output) } } func help() -> String { return "" } }
mit
pauljohanneskraft/Math
CoreMath/Classes/Functions/Zeros.swift
1
4697
// // Zeros.swift // Math // // Created by Paul Kraft on 18.12.17. // Copyright © 2017 pauljohanneskraft. All rights reserved. // import Foundation extension Double { public static var floatLeastNonzeroMagnitude: Double { return Double(Float.leastNonzeroMagnitude) } } extension Function { public func newtonsMethod(at x: Double, maxCount: Int = 1_000, tolerance: Double = .floatLeastNonzeroMagnitude) -> Double? { let derivative = self.derivative var x = x for _ in 0..<maxCount { let y = call(x: x) guard abs(y) > tolerance else { return x } let dy = derivative.call(x: x) x -= y / dy } return nil } /* public func roots(in range: SamplingRange, alreadyFound: Set<Double> = []) -> (roots: Set<Double>, result: Function) { print("checking for roots", self) guard !(self is Constant) else { return ([], self) } var zeros = Set<Double>() var function: Function = self range.forEach { x in guard let root = Double(guessZero(at: x).reducedDescription), root.isReal, !alreadyFound.contains(root) else { return } zeros.insert(findZeroUsingFloatAccuracy(at: root)) function = function / PolynomialFunction(Polynomial([-root, 1])) let functionZeros = function.roots(in: range, alreadyFound: alreadyFound) zeros.formUnion(functionZeros.roots) function = functionZeros.result } print("found", zeros) return (zeros, function) } */ public func secantMethod(x0: Double, x1: Double, maxIterations: Int = 1_000, tolerance: Double = .floatLeastNonzeroMagnitude) -> Double { var x0 = x0, x1 = x1, y0 = call(x: x0) for _ in 0..<maxIterations { let y1 = call(x: x1) guard y1.isReal else { return x0 } guard abs(y1) > tolerance else { return x1 } let prevX1 = x1 x1 -= y1 * (x1 - x0) / (y1 - y0) x0 = prevX1 y0 = y1 } return x1 } public func bisectionMethod(range: ClosedRange<Double>, maxIterations: Int = 10_000, tolerance: Double = .floatLeastNonzeroMagnitude) -> ClosedRange<Double> { guard maxIterations > 1, range.length > tolerance else { return range } let midpoint = range.midpoint let y = call(x: midpoint) guard abs(y) != 0 else { return midpoint...midpoint } let isEqual = (range.lowerBound.sign == y.sign) return bisectionMethod(range: isEqual ? midpoint...range.upperBound : range.lowerBound...midpoint, maxIterations: maxIterations - 1, tolerance: tolerance) } public func findZeroUsingFloatAccuracy(at doubleX: Double) -> Double { let floatX = Double(Float(doubleX)) let floatY = abs(call(x: floatX)) let doubleY = abs(call(x: doubleX)) return doubleY < floatY ? doubleX : floatX } public func findZeroUsingFloatAccuracy(range: ClosedRange<Double>) -> Double { let newRange = Float(range.lowerBound)...Float(range.upperBound) guard !newRange.isPoint else { return findZeroUsingFloatAccuracy(at: range.midpoint) } let a = Double(newRange.lowerBound), ay = abs(call(x: a)) let b = Double(newRange.midpoint ), by = abs(call(x: b)) let c = Double(newRange.upperBound), cy = abs(call(x: c)) if ay < by { return ay < cy ? a : c } else { return by < cy ? b : c } } } extension ClosedRange where Bound: FixedWidthInteger { public var midpoint: Bound { let (value, overflow) = upperBound.addingReportingOverflow(lowerBound) guard overflow else { return value } let rest = (upperBound & 1) + (lowerBound & 1) return (upperBound >> 1) + (lowerBound >> 1) + (rest >> 1) } public var length: Bound { let sub = upperBound.subtractingReportingOverflow(lowerBound) return sub.overflow ? Bound.max : sub.partialValue } public var isPoint: Bool { return upperBound == lowerBound } } extension ClosedRange where Bound: FloatingPoint { public var midpoint: Bound { return (upperBound + lowerBound) / 2 } public var length: Bound { return upperBound - lowerBound } public var isPoint: Bool { return upperBound == lowerBound } }
mit
googlemaps/ios-on-demand-rides-deliveries-samples
swift/consumer_swiftui/App/Views/ContentView.swift
1
819
/* * Copyright 2022 Google LLC. 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 SwiftUI struct ContentView: View { var body: some View { JourneySharingView() } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
apache-2.0
forgot/FAAlertController
Source/FAAlertAction.swift
1
1373
// // FAAlertAction.swift // FAPlacemarkPicker // // Created by Jesse Cox on 8/20/16. // Copyright © 2016 Apprhythmia LLC. All rights reserved. // import UIKit protocol FAAlertActionDelegate { func didPerformAction(_ action: FAAlertAction) } public enum FAAlertActionStyle : Int { case `default` case cancel case destructive } public class FAAlertAction: NSObject { public var title: String? public let style: FAAlertActionStyle public var handler: ((FAAlertAction) -> ())? var isPreferredAction = false var isEnabled = true var delegate: FAAlertActionDelegate? public init(title: String?, style: FAAlertActionStyle, handler: ((FAAlertAction) -> Void)? = nil) { guard let _title = title else { preconditionFailure("Actions added to FAAlertController must have a title") } self.title = _title self.style = style self.handler = handler let button = UIButton(frame: .zero) button.translatesAutoresizingMaskIntoConstraints = false button.titleLabel?.text = title button.addTarget(nil, action: #selector(self.performAction), for: .touchUpInside) } @objc func performAction() { if let _handler = handler { _handler(self) } delegate?.didPerformAction(self) } }
mit
VikingDen/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsPrivacyViewController.swift
24
4971
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class SettingsPrivacyViewController: AATableViewController { // MARK: - // MARK: Private vars private let CellIdentifier = "CellIdentifier" private var authSessions: [ARApiAuthSession]? // MARK: - // MARK: Constructors init() { super.init(style: UITableViewStyle.Grouped) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title") tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier) tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.separatorStyle = UITableViewCellSeparatorStyle.None execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in var list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession) } self.tableView.reloadData() }, failureBlock: nil) } // MARK: - // MARK: Getters private func terminateSessionsCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("PrivacyTerminate", comment: "Terminate action")) cell.style = .Normal // cell.showTopSeparator() // cell.showBottomSeparator() return cell } private func sessionsCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell var session = authSessions![indexPath.row] cell.setContent(session.getDeviceTitle()) cell.style = .Normal // if (indexPath.row == 0) { // cell.showTopSeparator() // } else { // cell.hideTopSeparator() // } // cell.showBottomSeparator() return cell } // MARK: - // MARK: UITableView Data Source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if authSessions != nil { if count(authSessions!) > 0 { return 2 } } return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return count(authSessions!) } return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 && indexPath.row == 0 { return terminateSessionsCell(indexPath) } else if (indexPath.section == 1) { return sessionsCell(indexPath) } return UITableViewCell() } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section > 0 { return nil } return NSLocalizedString("PrivacyTerminateHint", comment: "Terminate hint") } // MARK: - // MARK: UITableView Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 0 { execute(Actor.terminateAllSessionsCommand()) } else if (indexPath.section == 1) { execute(Actor.terminateSessionCommandWithId(authSessions![indexPath.row].getId()), successBlock: { (val) -> Void in self.execute(Actor.loadSessionsCommand(), successBlock: { (val) -> Void in var list = val as! JavaUtilList self.authSessions = [] for i in 0..<list.size() { self.authSessions!.append(list.getWithInt(jint(i)) as! ARApiAuthSession) } self.tableView.reloadData() }, failureBlock: nil) }, failureBlock: nil) } } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.sectionColor } func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.hintColor } }
mit
apple/swift
benchmark/single-source/Memset.swift
10
947
//===--- Memset.swift -----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = BenchmarkInfo( name: "Memset", runFunction: run_Memset, tags: [.validation, .unstable]) @inline(never) func memset(_ a: inout [Int], _ c: Int) { for i in 0..<a.count { a[i] = c } } @inline(never) public func run_Memset(_ n: Int) { var a = [Int](repeating: 0, count: 10_000) for _ in 1...50*n { memset(&a, 1) memset(&a, 0) } check(a[87] == 0) }
apache-2.0
apple/swift
validation-test/compiler_crashers_fixed/28717-result-case-not-implemented.swift
60
444
// 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 // RUN: not %target-swift-frontend %s -emit-ir A:{ struct A{func a(UInt=1 + 1 + 1 + 1 as?Int){
apache-2.0
bustoutsolutions/siesta
Examples/GithubBrowser/Source/API/GithubAPI.swift
1
10914
import Siesta import Foundation // Depending on your taste, a Service can be a global var, a static var singleton, or a piece of more carefully // controlled shared state passed between pieces of the app. let GitHubAPI = _GitHubAPI() class _GitHubAPI { // MARK: - Configuration private let service = Service( baseURL: "https://api.github.com", standardTransformers: [.text, .image]) // No .json because we use Swift 4 JSONDecoder instead of older JSONSerialization fileprivate init() { #if DEBUG // Bare-bones logging of which network calls Siesta makes: SiestaLog.Category.enabled = [.network] // For more info about how Siesta decides whether to make a network call, // and which state updates it broadcasts to the app: //SiestaLog.Category.enabled = .common // For the gory details of what Siesta’s up to: //SiestaLog.Category.enabled = .detailed // To dump all requests and responses: // (Warning: may cause Xcode console overheating) //SiestaLog.Category.enabled = .all #endif // –––––– Global configuration –––––– let jsonDecoder = JSONDecoder() service.configure { // Custom transformers can change any response into any other — including errors. // Here we replace the default error message with the one provided by the GitHub API (if present). $0.pipeline[.cleanup].add( GitHubErrorMessageExtractor(jsonDecoder: jsonDecoder)) } // –––––– Resource-specific configuration –––––– service.configure("/search/**") { // Refresh search results after 10 seconds (Siesta default is 30) $0.expirationTime = 10 } // –––––– Auth configuration –––––– // Note the "**" pattern, which makes this config apply only to subpaths of baseURL. // This prevents accidental credential leakage to untrusted servers. service.configure("**") { // This header configuration gets reapplied whenever the user logs in or out. // How? See the basicAuthHeader property’s didSet. $0.headers["Authorization"] = self.basicAuthHeader } // –––––– Mapping from specific paths to models –––––– // These all use Swift 4’s JSONDecoder, but you can configure arbitrary transforms on arbitrary data types. service.configureTransformer("/users/*") { // Input type inferred because the from: param takes Data. // Output type inferred because jsonDecoder.decode() will return User try jsonDecoder.decode(User.self, from: $0.content) } service.configureTransformer("/users/*/repos") { try jsonDecoder.decode([Repository].self, from: $0.content) } service.configureTransformer("/search/repositories") { try jsonDecoder.decode(SearchResults<Repository>.self, from: $0.content) .items // Transformers can do arbitrary post-processing } service.configureTransformer("/repos/*/*") { try jsonDecoder.decode(Repository.self, from: $0.content) } service.configureTransformer("/repos/*/*/contributors") { try jsonDecoder.decode([User].self, from: $0.content) } service.configureTransformer("/repos/*/*/languages") { // For this request, GitHub gives a response of the form {"Swift": 421956, "Objective-C": 11000, ...}. // Instead of using a custom model class for this one, we just model it as a raw dictionary. try jsonDecoder.decode([String:Int].self, from: $0.content) } service.configure("/user/starred/*/*") { // GitHub gives 202 for “starred” and 404 for “not starred.” $0.pipeline[.model].add( // This custom transformer turns that curious convention into TrueIfResourceFoundTransformer()) // a resource whose content is a simple boolean. } // Note that you can use Siesta without these sorts of model mappings. By default, Siesta parses JSON, text, // and images based on content type — and a resource will contain whatever the server happened to return, in a // parsed but unstructured form (string, dictionary, etc.). If you prefer to work with raw dictionaries instead // of models (good for rapid prototyping), then no additional transformer config is necessary. // // If you do apply a path-based mapping like the ones above, then any request for that path that does not return // the expected type becomes an error. For example, "/users/foo" _must_ return a JSON response because that's // what jsonDecoder.decode(…) expects. } // MARK: - Authentication func logIn(username: String, password: String) { if let auth = "\(username):\(password)".data(using: String.Encoding.utf8) { basicAuthHeader = "Basic \(auth.base64EncodedString())" } } func logOut() { basicAuthHeader = nil } var isAuthenticated: Bool { return basicAuthHeader != nil } private var basicAuthHeader: String? { didSet { // These two calls are almost always necessary when you have changing auth for your API: service.invalidateConfiguration() // So that future requests for existing resources pick up config change service.wipeResources() // Scrub all unauthenticated data // Note that wipeResources() broadcasts a “no data” event to all observers of all resources. // Therefore, if your UI diligently observes all the resources it displays, this call prevents sensitive // data from lingering in the UI after logout. } } // MARK: - Endpoint Accessors // You can turn your REST API into a nice Swift API using lightweight wrappers that return Siesta resources. // // Note that this class keeps its Service private, making these methods the only entry points for the API. // You could also choose to subclass Service, which makes methods like service.resource(…) available to // your whole app. That approach is sometimes better for quick and dirty prototyping. // // If this section gets too long for your taste, you can move it to a separate file by putting a helper method // in an extension. var activeRepositories: Resource { return service .resource("/search/repositories") .withParams([ "q": "stars:>0", "sort": "updated", "order": "desc" ]) } func user(_ username: String) -> Resource { return service .resource("/users") .child(username.lowercased()) } func repository(ownedBy login: String, named name: String) -> Resource { return service .resource("/repos") .child(login) .child(name) } func repository(_ repositoryModel: Repository) -> Resource { return repository( ownedBy: repositoryModel.owner.login, named: repositoryModel.name) } func currentUserStarred(_ repositoryModel: Repository) -> Resource { return service .resource("/user/starred") .child(repositoryModel.owner.login) .child(repositoryModel.name) } func setStarred(_ isStarred: Bool, repository repositoryModel: Repository) -> Request { let starredResource = currentUserStarred(repositoryModel) return starredResource .request(isStarred ? .put : .delete) .onSuccess { _ in // Update succeeded. Directly update the locally cached “starred / not starred” state. starredResource.overrideLocalContent(with: isStarred) // Ask server for an updated star count. Note that we only need to trigger the load here, not handle // the response! Any UI that is displaying the star count will be observing this resource, and thus // will pick up the change. The code that knows _when_ to trigger the load is decoupled from the code // that knows _what_ to do with the updated data. This is the magic of Siesta. for delay in [0.1, 1.0, 2.0] { // Github propagates the updated star count slowly DispatchQueue.main.asyncAfter(deadline: .now() + delay) { // This ham-handed repeated loading is not as expensive as it first appears, thanks to the fact // that Siesta magically takes care of ETag / If-modified-since / HTTP 304 for us. self.repository(repositoryModel).load() } } } } } // MARK: - Custom transformers /// If the response is JSON and has a "message" value, use it as the user-visible error message. private struct GitHubErrorMessageExtractor: ResponseTransformer { let jsonDecoder: JSONDecoder func process(_ response: Response) -> Response { guard case .failure(var error) = response, // Unless the response is a failure... let errorData: Data = error.typedContent(), // ...with data... let githubError = try? jsonDecoder.decode( // ...that encodes a standard GitHub error envelope... GitHubErrorEnvelope.self, from: errorData) else { return response // ...just leave it untouched. } error.userMessage = githubError.message // GitHub provided an error message. Show it to the user! return .failure(error) } private struct GitHubErrorEnvelope: Decodable { let message: String } } /// Special handling for detecting whether repo is starred; see "/user/starred/*/*" config above private struct TrueIfResourceFoundTransformer: ResponseTransformer { func process(_ response: Response) -> Response { switch response { case .success(var entity): entity.content = true // Any success → true return logTransformation( .success(entity)) case .failure(let error): if error.httpStatusCode == 404, var entity = error.entity { entity.content = false // 404 → false return logTransformation( .success(entity)) } else { return response // Any other error remains unchanged } } } }
mit
lorentey/swift
test/SILOptimizer/access_marker_verify_repl.swift
19
449
// RUN: %target-repl-run-simple-swift -enable-verify-exclusivity -enforce-exclusivity=checked | %FileCheck %s // REQUIRES: asserts // REQUIRES: OS=macosx // REQUIRES: swift_repl // Test the combination of SILGen + DiagnoseStaticExclusivity with verification. // // This augments access_marker_verify with tests that require the repl. // Global variable initialization is different in the repl. // CHECK: glob_i8 : Int8 = 8 var glob_i8: Int8 = 8
apache-2.0
lorentey/swift
test/attr/attr_originally_definedin_backward_compatibility.swift
3
2960
// REQUIRES: OS=macosx // // RUN: %empty-directory(%t) // // ----------------------------------------------------------------------------- // --- Prepare SDK (.swiftmodule). // RUN: %empty-directory(%t/SDK) // // --- Build original high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevelOriginal.swift -Xlinker -install_name -Xlinker @rpath/HighLevel.framework/HighLevel -enable-library-evolution // --- Build an executable using the original high level framework // RUN: %target-build-swift -emit-executable %s -g -o %t/HighlevelRunner -F %t/SDK/Frameworks/ -framework HighLevel \ // RUN: -Xlinker -rpath -Xlinker %t/SDK/Frameworks // --- Run the executable // RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=BEFORE_MOVE // --- Build low level framework. // RUN: mkdir -p %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/LowLevel.framework/LowLevel) -module-name LowLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/LowLevel.framework/Modules/LowLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/LowLevel.swift -Xlinker -install_name -Xlinker @rpath/LowLevel.framework/LowLevel -enable-library-evolution // --- Build high level framework. // RUN: mkdir -p %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule // RUN: %target-build-swift-dylib(%t/SDK/Frameworks/HighLevel.framework/HighLevel) -module-name HighLevel -emit-module \ // RUN: -emit-module-path %t/SDK/Frameworks/HighLevel.framework/Modules/HighLevel.swiftmodule/%module-target-triple.swiftmodule \ // RUN: %S/Inputs/SymbolMove/HighLevel.swift -F %t/SDK/Frameworks -Xlinker -reexport_framework -Xlinker LowLevel -enable-library-evolution // --- Run the executable // RUN: %t/HighlevelRunner | %FileCheck %s -check-prefix=AFTER_MOVE import HighLevel printMessage() printMessageMoved() // BEFORE_MOVE: Hello from HighLevel // BEFORE_MOVE: Hello from HighLevel // AFTER_MOVE: Hello from LowLevel // AFTER_MOVE: Hello from LowLevel let e = Entity() print(e.location()) // BEFORE_MOVE: Entity from HighLevel // AFTER_MOVE: Entity from LowLevel print(CandyBox(Candy()).ItemKind) // BEFORE_MOVE: candy // AFTER_MOVE: candy print(CandyBox(Candy()).shape()) // BEFORE_MOVE: square // AFTER_MOVE: round print(LanguageKind.Cpp.rawValue) // BEFORE_MOVE: -1 // AFTER_MOVE: 1 print("\(Vehicle().currentSpeed)") // BEFORE_MOVE: -40 // AFTER_MOVE: 40 class Bicycle: Vehicle {} let bicycle = Bicycle() bicycle.currentSpeed = 15.0 print("\(bicycle.currentSpeed)") // BEFORE_MOVE: 15.0 // AFTER_MOVE: 15.0
apache-2.0
sebbean/ExSwift
ExSwiftTests/DoubleExtensionsTests.swift
25
4054
// // DoubleExtensionsTests.swift // ExSwift // // Created by pNre on 10/07/14. // Copyright (c) 2014 pNre. All rights reserved. // import Quick import Nimble class DoubleExtensionsSpec: QuickSpec { override func spec() { /** * Double.abs */ it("abs") { expect(Double(0).abs()) == Double(0) expect(Double(-1).abs()).to(beCloseTo(1, within: 0.001)) expect(Double(1).abs()).to(beCloseTo(1, within: 0.001)) expect(Double(-111.2).abs()).to(beCloseTo(111.2, within: 0.001)) expect(Double(111.2).abs()).to(beCloseTo(111.2, within: 0.001)) } /** * Double.sqrt */ it("sqrt") { expect(Double(0).sqrt()) == Double(0) expect(Double(4).sqrt()).to(beCloseTo(2, within: 0.001)) expect(Double(111.2).sqrt()).to(beCloseTo(sqrt(111.2), within: 0.001)) expect(isnan(Double(-10).sqrt())).to(beTrue()) } /** * Double.floor */ it("floor") { expect(Double(0).floor()) == Double(0) expect(Double(4.99999999).floor()).to(beCloseTo(4, within: 0.001)) expect(Double(4.001).floor()).to(beCloseTo(4, within: 0.001)) expect(Double(4.5).floor()).to(beCloseTo(4, within: 0.001)) expect(Double(-4.99999999).floor()).to(beCloseTo(-5, within: 0.001)) expect(Double(-4.001).floor()).to(beCloseTo(-5, within: 0.001)) expect(Double(-4.5).floor()).to(beCloseTo(-5, within: 0.001)) } /** * Double.ceil */ it("ceil") { expect(Double(0).ceil()) == Double(0) expect(Double(4.99999999).ceil()).to(beCloseTo(5, within: 0.001)) expect(Double(4.001).ceil()).to(beCloseTo(5, within: 0.001)) expect(Double(4.5).ceil()).to(beCloseTo(5, within: 0.001)) expect(Double(-4.99999999).ceil()).to(beCloseTo(-4, within: 0.001)) expect(Double(-4.001).ceil()).to(beCloseTo(-4, within: 0.001)) expect(Double(-4.5).ceil()).to(beCloseTo(-4, within: 0.001)) } /** * Double.round */ it("round") { expect(Double(0).round()) == Double(0) expect(Double(4.99999999).round()).to(beCloseTo(5, within: 0.001)) expect(Double(4.001).round()).to(beCloseTo(4, within: 0.001)) expect(Double(4.5).round()).to(beCloseTo(5, within: 0.001)) expect(Double(4.3).round()).to(beCloseTo(4, within: 0.001)) expect(Double(4.7).round()).to(beCloseTo(5, within: 0.001)) expect(Double(-4.99999999).round()).to(beCloseTo(-5, within: 0.001)) expect(Double(-4.001).round()).to(beCloseTo(-4, within: 0.001)) expect(Double(-4.5).round()).to(beCloseTo(-5, within: 0.001)) } /** * Double.roundToNearest */ it("roundToNearest") { expect(2.5.roundToNearest(0.3)).to(beCloseTo(2.4, within: 0.01)) expect(0.roundToNearest(0.3)).to(beCloseTo(0.0, within: 0.01)) expect(4.0.roundToNearest(2)).to(beCloseTo(4.0, within: 0.01)) expect(10.0.roundToNearest(3)).to(beCloseTo(9.0, within: 0.01)) expect(-2.0.roundToNearest(3)).to(beCloseTo(-3.0, within: 0.01)) } /** * Double.clamp */ it("clamp") { expect(Double(0.25).clamp(0, 0.5)).to(beCloseTo(0.25, within: 0.01)) expect(Double(2).clamp(0, 0.5)).to(beCloseTo(0.5, within: 0.01)) expect(Double(-2).clamp(0, 0.5)).to(beCloseTo(0, within: 0.01)) } } }
bsd-2-clause
ryanspillsbury90/HaleMeditates
ios/Hale Meditates/WebViewController.swift
1
4169
// // WebViewController.swift // // Created by Ryan Pillsbury on 7/5/15. // Copyright (c) 2015 koait. All rights reserved. // import UIKit import MediaPlayer class WebViewController: UIViewController, UIWebViewDelegate, UIGestureRecognizerDelegate, UINavigationBarDelegate, ScrollViewListener { var url: NSURL? var request: NSURLRequest? @IBOutlet weak var webView: WebView! @IBOutlet weak var loaderView: UIActivityIndicatorView! @IBOutlet weak var navBar: UINavigationBar! var timer: NSTimer? override func viewDidLoad() { super.viewDidLoad() self.webView.delegate = self; self.webView.scrollViewDelegate = self; if (url != nil) { request = NSURLRequest(URL: url!); webView.loadRequest(request!); } let tapGesture = UITapGestureRecognizer(target: self, action: "handleTap:") tapGesture.delegate = self; self.webView.addGestureRecognizer(tapGesture); let navitem = UINavigationItem(); let _ = UIButton(type: UIButtonType.Custom) navBar.pushNavigationItem(navitem, animated: false); self.navigationItem.title = ""; navBar.pushNavigationItem(self.navigationItem, animated: false); navBar.tintColor = UIColor.blackColor(); navBar.delegate = self; } func handleTap(sender: UITapGestureRecognizer) { timer?.invalidate(); showNavBar(); scheduleNavigationBarToHide(); } func scrolled() { self.hideNavBar(); } func navigationBar(navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool { self.dismissViewControllerAnimated(true, completion: nil); return false; } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { if (otherGestureRecognizer is UITapGestureRecognizer) { let tapRecognizer = (otherGestureRecognizer as! UITapGestureRecognizer) } return true; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webViewDidFinishLoad(webView: UIWebView) { self.loaderView.stopAnimating(); scheduleNavigationBarToHide(); } func scheduleNavigationBarToHide() { self.timer = NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "hideNavBar:", userInfo: nil, repeats: false); } func hideNavBar(timer: NSTimer) { self.hideNavBar(); } func showNavBar() { if (self.navBar.frame.origin.y < 0 ) { UIView.animateWithDuration(0.4, animations: ({ self.navBar.frame = CGRectMake(0, 0, self.navBar.frame.width, self.navBar.frame.height) })); } } func hideNavBar() { if (self.navBar.frame.origin.y >= 0 ) { UIView.animateWithDuration(0.4, animations: ({ self.navBar.frame = CGRectMake(0, -self.navBar.frame.height, self.navBar.frame.width, self.navBar.frame.height) })); } } func webViewDidStartLoad(webView: UIWebView) { loaderView.startAnimating(); } /* // 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. } */ } protocol ScrollViewListener { // func startedScrolling(to: CGFloat, from: CGFloat); func scrolled() } class WebView: UIWebView { var lastOffSetY: CGFloat = 0; var scrollViewDelegate: ScrollViewListener? override func scrollViewDidScroll(scrollView: UIScrollView) { super.scrollViewDidScroll(scrollView); self.scrollViewDelegate?.scrolled(); } }
mit
ferranabello/Viperit
Example/modules/Perfect/PerfectPresenter.swift
1
604
// // PerfectPresenter.swift // Viperit // // Created by Ferran on 16/09/2019. // Copyright © 2019 Ferran Abelló. All rights reserved. // import Foundation import Viperit // MARK: - PerfectPresenter Class final class PerfectPresenter: Presenter { } // MARK: - PerfectPresenter API extension PerfectPresenter: PerfectPresenterApi { } // MARK: - Perfect Viper Components private extension PerfectPresenter { var interactor: PerfectInteractorApi { return _interactor as! PerfectInteractorApi } var router: PerfectRouterApi { return _router as! PerfectRouterApi } }
mit
OpenMindBR/swift-diversidade-app
Diversidade/CentersViewController.swift
1
5590
// // CentersViewController.swift // Diversidade // // Created by Francisco José A. C. Souza on 24/02/16. // Copyright © 2016 Francisco José A. C. Souza. All rights reserved. // import UIKit import MapKit import Alamofire import SwiftyJSON class CentersViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { @IBOutlet weak var menuItem: UIBarButtonItem! @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() let searchRadius = 1000 var nucleos:[Nucleo]? override func viewDidLoad() { super.viewDidLoad() self.configureSideMenu(self.menuItem) self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.distanceFilter = kCLDistanceFilterNone self.locationManager.requestWhenInUseAuthorization() mapView.showsUserLocation = true mapView.showsCompass = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillAppear(animated: Bool) { if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() locationManager.startMonitoringSignificantLocationChanges() } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == .AuthorizedWhenInUse { locationManager.startUpdatingLocation() locationManager.startMonitoringSignificantLocationChanges() } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) in if let placemark = placemarks?.first, let state = placemark.administrativeArea { self.fetchPlacesForRegion(state) } }) let region = MKCoordinateRegionMakeWithDistance(location.coordinate, 6000, 6000) mapView.setRegion(region, animated: true) locationManager.stopUpdatingLocation() locationManager.stopMonitoringSignificantLocationChanges() } } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if let annotation = annotation as? PlaceAnnotation { let identifier = "pin" var view: MKPinAnnotationView if let dequeedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as? MKPinAnnotationView { dequeedView.annotation = annotation view = dequeedView } else { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) let button = UIButton(type: .DetailDisclosure) button.addTarget(self, action: #selector(CentersViewController.onDisclosureButtonTap(_:)), forControlEvents: .TouchUpInside) button.tag = Int(annotation.placeId)! view.canShowCallout = true view.calloutOffset = CGPoint(x: -5, y: 5) view.pinTintColor = UIColor(red: 155.0/255, green: 47.0/255, blue: 245.0/255, alpha: 1.0) view.rightCalloutAccessoryView = button as UIView } return view } return nil } func fetchPlacesForRegion(region: String){ let requestUrl = UrlFormatter.urlForCentersWithState(region) Alamofire.request(.GET, requestUrl).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json: Array<JSON> = JSON(value).arrayValue let places = json.map({ (nucleo) -> PlaceAnnotation in let id = nucleo["id"].stringValue let name = nucleo["name"].stringValue let address = nucleo["address"].stringValue let latitude = nucleo["latitude"].doubleValue let longitude = nucleo["longitude"].doubleValue let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) return PlaceAnnotation(placeId: id, placeName: name, placeAddress: address, coordinate: coord) }) self.mapView.addAnnotations(places) } case .Failure(let error): print(error) } } } func onDisclosureButtonTap(sender: UIButton) { performSegueWithIdentifier("toDetalheNucleo", sender: sender.tag) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let viewController = segue.destinationViewController as? DetailCenterViewController { viewController.centerId = sender as? Int } } }
mit
mleiv/SerializableData
SerializableDataDemo/SerializableDataDemo/Core Data/SimpleSerializedCoreDataStorable.swift
1
11464
// // CoreDataStorable.swift // // Copyright 2017 Emily Ivie // Licensed under The MIT License // For full copyright and license information, please see http://opensource.org/licenses/MIT // Redistributions of files must retain the above copyright notice. import CoreData public protocol SimpleSerializedCoreDataStorable: SerializedDataStorable, SerializedDataRetrievable { // MARK: Required /// Type of the core data entity. associatedtype EntityType: NSManagedObject /// Alters the predicate to retrieve only the row equal to this object. func setIdentifyingPredicate( fetchRequest: NSFetchRequest<EntityType> ) /// Sets core data values to match struct values (specific). func setAdditionalColumnsOnSave( coreItem: EntityType ) /// Initializes value type from core data object with serialized data. init?(coreItem: EntityType) // MARK: Optional /// A reference to the current core data manager. static var defaultManager: SimpleSerializedCoreDataManageable { get } /// Returns the CoreData row that is equal to this object. func entity(context: NSManagedObjectContext?) -> EntityType? /// String description of EntityType. static var entityName: String { get } /// String description of serialized data column in entity static var serializedDataKey: String { get } /// Sets core data values to match struct values (general). /// /// DON'T OVERRIDE. func setColumnsOnSave( coreItem: EntityType ) /// Gets the struct to match the core data request. static func get( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Self? /// Gets the struct to match the core data request. static func getCount( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Int /// Gets all structs that match the core data request. static func getAll( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> [Self] /// Saves the struct to core data. mutating func save( with manager: SimpleSerializedCoreDataManageable? ) -> Bool /// Saves all the structs to core data. static func saveAll( items: [Self], with manager: SimpleSerializedCoreDataManageable? ) -> Bool /// Deletes the struct's core data equivalent. mutating func delete( with manager: SimpleSerializedCoreDataManageable? ) -> Bool /// Deletes all rows that match the core data request. static func deleteAll( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Bool } extension SimpleSerializedCoreDataStorable { /// The closure type for editing fetch requests. public typealias AlterFetchRequest<T: NSManagedObject> = ((NSFetchRequest<T>) -> Void) /// Convenience - get the static version for easy instance reference. public var defaultManager: SimpleSerializedCoreDataManageable { return Self.defaultManager } /// (Protocol default) /// Returns the CoreData row that is equal to this object. public func entity(context: NSManagedObjectContext?) -> EntityType? { let manager = type(of: defaultManager).init(context: context) return manager.getObject(item: self) } /// (Protocol default) /// String description of EntityType public static var entityName: String { return EntityType.description() } /// (Protocol default) /// String description of serialized data column in entity public static var serializedDataKey: String { return "serializedData" } /// (Protocol default) /// Initializes value type from core data object with serialized data. public init?(coreItem: EntityType) { // Warning: make sure parent runs this in the correct context/thread for this entity if let serializedData = coreItem.value(forKey: Self.serializedDataKey) as? Data { self.init(serializedData: serializedData) return } return nil } /// Sets core data values to match struct values (general). /// /// DON'T OVERRIDE. public func setColumnsOnSave( coreItem: EntityType ) { coreItem.setValue(self.serializedData, forKey: Self.serializedDataKey) setAdditionalColumnsOnSave(coreItem: coreItem) } /// (Protocol default) /// Gets the struct to match the core data request. public static func get( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Self? { return _get(with: manager, alterFetchRequest: alterFetchRequest) } /// Convenience version of get:manager:AlterFetchRequest<EntityType> (manager not required). public static func get( alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Self? { return get(with: nil, alterFetchRequest: alterFetchRequest) } /// Convenience version of get:manager:AlterFetchRequest<EntityType> (no parameters required). public static func get( with manager: SimpleSerializedCoreDataManageable? = nil ) -> Self? { return get(with: manager) { _ in } } /// Root version of get:manager:AlterFetchRequest<EntityType> (you can still call this if you override that). /// /// DO NOT OVERRIDE. internal static func _get( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Self? { let manager = manager ?? defaultManager let one: Self? = manager.getValue(alterFetchRequest: alterFetchRequest) return one } /// (Protocol default) /// Gets the struct to match the core data request. public static func getCount( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Int { let manager = manager ?? defaultManager return manager.getCount(alterFetchRequest: alterFetchRequest) } /// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (manager not required). public static func getCount( alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Int { return getCount(with: nil, alterFetchRequest: alterFetchRequest) } /// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (AlterFetchRequest<EntityType> not required). public static func getCount( with manager: SimpleSerializedCoreDataManageable? ) -> Int { return getCount(with: manager, alterFetchRequest: { _ in }) } /// Convenience version of getCount:manager:AlterFetchRequest<EntityType> (no parameters required). public static func getCount() -> Int { return getCount(with: nil) { (fetchRequest: NSFetchRequest<EntityType>) in } } /// (Protocol default) /// Gets all structs that match the core data request. public static func getAll( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> [Self] { return _getAll(with: manager, alterFetchRequest: alterFetchRequest) } /// Convenience version of getAll:manager:AlterFetchRequest<EntityType> (manager not required). public static func getAll( alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> [Self] { return getAll(with: nil, alterFetchRequest: alterFetchRequest) } /// Convenience version of getAll:manager:AlterFetchRequest<EntityType> (no parameters required). public static func getAll( with manager: SimpleSerializedCoreDataManageable? = nil ) -> [Self] { return getAll(with: manager) { _ in } } /// Root version of getAll:manager:AlterFetchRequest<EntityType> (you can still call this if you override that). /// /// DO NOT OVERRIDE. internal static func _getAll( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> [Self] { let manager = manager ?? defaultManager let all: [Self] = manager.getAllValues(alterFetchRequest: alterFetchRequest) return all } /// (Protocol default) /// Saves the struct to core data. public mutating func save( with manager: SimpleSerializedCoreDataManageable? ) -> Bool { let manager = manager ?? defaultManager let isSaved = manager.saveValue(item: self) return isSaved } /// Convenience version of save:manager (no parameters required). public mutating func save() -> Bool { return save(with: nil) } /// (Protocol default) /// Saves all the structs to core data. public static func saveAll( items: [Self], with manager: SimpleSerializedCoreDataManageable? ) -> Bool { guard !items.isEmpty else { return true } let manager = manager ?? defaultManager let isSaved = manager.saveAllValues(items: items) return isSaved } /// Convenience version of saveAll:items:manager (manager not required). public static func saveAll( items: [Self] ) -> Bool { return saveAll(items: items, with: nil) } /// (Protocol default) /// Deletes the struct's core data equivalent. public mutating func delete( with manager: SimpleSerializedCoreDataManageable? ) -> Bool { let manager = manager ?? defaultManager let isDeleted = manager.deleteValue(item: self) return isDeleted } /// Convenience version of delete:manager (no parameters required). public mutating func delete() -> Bool { return delete(with: nil) } /// (Protocol default) /// Deletes all rows that match the core data request. public static func deleteAll( with manager: SimpleSerializedCoreDataManageable?, alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Bool { let manager = manager ?? defaultManager let isDeleted = manager.deleteAll(alterFetchRequest: alterFetchRequest) return isDeleted } /// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (manager not required). public static func deleteAll( alterFetchRequest: @escaping AlterFetchRequest<EntityType> ) -> Bool { return deleteAll(with: nil, alterFetchRequest: alterFetchRequest) } /// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (AlterFetchRequest<EntityType> not required). public static func deleteAll( with manager: SimpleSerializedCoreDataManageable? ) -> Bool { return deleteAll(with: manager) { _ in } } /// Convenience version of deleteAll:manager:AlterFetchRequest<EntityType> (no parameters required). public static func deleteAll() -> Bool { return deleteAll(with: nil) { _ in } } }
mit
alexaubry/BulletinBoard
Sources/Support/Views/Internal/BulletinBackgroundView.swift
1
3233
/** * BulletinBoard * Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license. */ import UIKit /** * The view to display behind the bulletin. */ class BulletinBackgroundView: UIView { let style: BLTNBackgroundViewStyle // MARK: - Content View enum ContentView { case dim(UIView, CGFloat) case blur(UIVisualEffectView, UIBlurEffect) var instance: UIView { switch self { case .dim(let dimmingView, _): return dimmingView case .blur(let blurView, _): return blurView } } } private(set) var contentView: ContentView! // MARK: - Initialization init(style: BLTNBackgroundViewStyle) { self.style = style super.init(frame: .zero) initialize() } override init(frame: CGRect) { style = .dimmed super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { style = .dimmed super.init(coder: aDecoder) initialize() } private func initialize() { translatesAutoresizingMaskIntoConstraints = false func makeDimmingView() -> UIView { let dimmingView = UIView() dimmingView.alpha = 0.0 dimmingView.backgroundColor = UIColor(white: 0.0, alpha: 0.5) dimmingView.translatesAutoresizingMaskIntoConstraints = false return dimmingView } switch style.rawValue { case .none: let dimmingView = makeDimmingView() addSubview(dimmingView) contentView = .dim(dimmingView, 0.0) case .dimmed: let dimmingView = makeDimmingView() addSubview(dimmingView) contentView = .dim(dimmingView, 1.0) case .blurred(let blurredBackground, _): let blurEffect = UIBlurEffect(style: blurredBackground) let blurEffectView = UIVisualEffectView(effect: nil) blurEffectView.translatesAutoresizingMaskIntoConstraints = false addSubview(blurEffectView) contentView = .blur(blurEffectView, blurEffect) } let contentViewInstance = contentView.instance contentViewInstance.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true contentViewInstance.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true contentViewInstance.topAnchor.constraint(equalTo: topAnchor).isActive = true contentViewInstance.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true } // MARK: - Interactions /// Shows the background view. Animatable. func show() { switch contentView! { case .dim(let dimmingView, let maxAlpha): dimmingView.alpha = maxAlpha case .blur(let blurView, let blurEffect): blurView.effect = blurEffect } } /// Hides the background view. Animatable. func hide() { switch contentView! { case .dim(let dimmingView, _): dimmingView.alpha = 0 case .blur(let blurView, _): blurView.effect = nil } } }
mit
egosapien/SSASideMenu
Examples/Simple/SSASideMenuExample/FirstViewController.swift
1
887
// // FirstViewController.swift // SSASideMenuExample // // Created by Sebastian Andersen on 20/10/14. // Copyright (c) 2015 Sebastian Andersen. All rights reserved. // import UIKit class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() title = "Home" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Left", style: .Plain, target: self, action: #selector(SSASideMenu.presentLeftMenuViewController)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Right", style: .Plain, target: self, action: #selector(SSASideMenu.presentRightMenuViewController)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
visenze/visearch-sdk-swift
ViSearchSDK/Carthage/Checkouts/visenze-tracking-swift/ViSenzeAnalytics/ViSenzeAnalytics/Classes/Request/VaDeviceData.swift
1
9443
// // VaDeviceData.swift // ViSenzeAnalytics // // Created by Hung on 9/9/20. // Copyright © 2020 ViSenze. All rights reserved. // import UIKit // https://stackoverflow.com/questions/26028918/how-to-determine-the-current-iphone-device-model public extension UIDevice { static let modelName: String = { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity #if os(iOS) switch identifier { case "iPod5,1": return "iPod touch (5th generation)" case "iPod7,1": return "iPod touch (6th generation)" case "iPod9,1": return "iPod touch (7th generation)" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone8,4": return "iPhone SE" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPhone12,1": return "iPhone 11" case "iPhone12,3": return "iPhone 11 Pro" case "iPhone12,5": return "iPhone 11 Pro Max" case "iPhone12,8": return "iPhone SE (2nd generation)" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)" case "iPad6,11", "iPad6,12": return "iPad (5th generation)" case "iPad7,5", "iPad7,6": return "iPad (6th generation)" case "iPad7,11", "iPad7,12": return "iPad (7th generation)" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad11,4", "iPad11,5": return "iPad Air (3rd generation)" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3" case "iPad5,1", "iPad5,2": return "iPad mini 4" case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch) (1st generation)" case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)" case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #endif } return mapToDevice(identifier: identifier) }() } public class VaDeviceData: NSObject { public static let UNKNOWN = "Unknown" public let platform: String = "Mobile" public let os: String // OS version public let osv: String public let appBundleId: String public let appName: String public let appVersion: String public let deviceBrand: String public let deviceModel: String public let userAgent: String public let sdkVersion: String public let sdk: String = "iOS SDK" public let screenResolution: String // these can change anytime public var language: String public static let sharedInstance = VaDeviceData() private override init(){ let info = Bundle.main.infoDictionary let executable = (info?[kCFBundleExecutableKey as String] as? String) ?? (ProcessInfo.processInfo.arguments.first?.split(separator: "/").last.map(String.init)) ?? VaDeviceData.UNKNOWN let bundle = info?[kCFBundleIdentifierKey as String] as? String ?? VaDeviceData.UNKNOWN let appVersion = info?["CFBundleShortVersionString"] as? String ?? VaDeviceData.UNKNOWN let appBuild = info?[kCFBundleVersionKey as String] as? String ?? VaDeviceData.UNKNOWN let appBundleName = info?[kCFBundleNameKey as String] as? String ?? VaDeviceData.UNKNOWN let appDisplayName = info?["CFBundleDisplayName"] as? String ?? appBundleName let osVersion = ProcessInfo.processInfo.operatingSystemVersion let osVersionString = "\(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)" let osName: String = { #if os(iOS) #if targetEnvironment(macCatalyst) return "macOS(Catalyst)" #else return "iOS" #endif #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "macOS" #elseif os(Linux) return "Linux" #elseif os(Windows) return "Windows" #else return "Unknown" #endif }() let osNameVersion = "\(osName) \(osVersionString)" self.sdkVersion = Bundle(for:VaDeviceData.self).infoDictionary?["CFBundleShortVersionString"] as? String ?? VaDeviceData.UNKNOWN let trackerVersionString = "ViSenzeTracker/\(self.sdkVersion)" /// Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 13.0.0) ViSenzeTracker/5.0.0` self.userAgent = "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(trackerVersionString)" self.os = StringHelper.limitMaxLength(osName, 32) self.osv = StringHelper.limitMaxLength(osVersionString, 32) self.appBundleId = StringHelper.limitMaxLength(bundle, 32) self.appVersion = StringHelper.limitMaxLength(appVersion, 32) self.appName = StringHelper.limitMaxLength(appDisplayName, 32) self.deviceBrand = "Apple" self.deviceModel = StringHelper.limitMaxLength(UIDevice.modelName, 32) let nWidth = Int(UIScreen.main.nativeBounds.width) let nHeight = Int(UIScreen.main.nativeBounds.height) self.screenResolution = "\(nWidth)x\(nHeight)" self.language = Locale.current.languageCode ?? VaDeviceData.UNKNOWN super.init() } }
mit
between40and2/XALG
frameworks/Framework-XALG/Linear/Rep/XALG_Rep_Queue__LinkedList.swift
1
553
// // XALG_Rep_Queue__LinkedList.swift // XALG // // Created by Juguang Xiao on 04/03/2017. // import Swift struct XALG_Rep_Queue__LinkedList { } // http://blog.jasonkim.ca/blog/2014/06/07/simple-linked-list-queue-in-swift/ //struct XALG_Rep_Queue_LinkedList <Element> : XALG_ADT_Queue { // typealias ElementType = Element // // struct Node<Element> { // var value : Element // var next : UnsafePointer<Node<Element>>? // } // // // // //} //https://github.com/clarkeaa/swift-examples/blob/master/linked-list/main.swift
mit
vl4298/mah-income
Mah Income/Mah Income/CollectionView Layout/CardBaseCollectionViewLayout.swift
1
4124
// // CardBaseCollectionViewLayout.swift // Mah Income // // Created by Van Luu on 4/17/17. // Copyright © 2017 Van Luu. All rights reserved. // import UIKit typealias AttributeHandler = (UICollectionViewLayoutAttributes, CGFloat?) -> (Void) class CardBaseCollectionViewLayout: UICollectionViewFlowLayout { fileprivate var handlerAttributeWithFactor: AttributeHandler! init(attributeHandler: @escaping AttributeHandler) { super.init() self.handlerAttributeWithFactor = attributeHandler } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override class var layoutAttributesClass: Swift.AnyClass { return CategoryLayoutAttribute.self } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let collectionView = self.collectionView else { return CGPoint.zero } var offsetAdjust: CGFloat = 10000 let horizontalCenter = proposedContentOffset.x + collectionView.bounds.width/2 let proposedRect = CGRect(x: proposedContentOffset.x, y: 0, width: collectionView.bounds.width, height: collectionView.bounds.height) guard let attributesArray = super.layoutAttributesForElements(in: proposedRect) else { return proposedContentOffset } for attribute in attributesArray { if case UICollectionElementCategory.supplementaryView = attribute.representedElementCategory { continue } let itemHorizontalCenter = attribute.center.x if fabs(itemHorizontalCenter - horizontalCenter) < fabs(offsetAdjust) { offsetAdjust = itemHorizontalCenter - horizontalCenter } } return CGPoint(x: proposedContentOffset.x + offsetAdjust, y: proposedContentOffset.y + offsetAdjust) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let attributesArray = super.layoutAttributesForElements(in: rect) else { return nil } guard let collectionView = self.collectionView else { return attributesArray } let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) for attribute in attributesArray { apply(layoutAttribute: attribute, for: visibleRect) } return attributesArray } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let attribute = super.layoutAttributesForItem(at: indexPath) else { return nil } guard let collectionView = self.collectionView else { return attribute } let visibleRect = CGRect(x: collectionView.contentOffset.x, y: collectionView.contentOffset.y, width: collectionView.bounds.width, height: collectionView.bounds.height) apply(layoutAttribute: attribute, for: visibleRect) return attribute } func apply(layoutAttribute attribute: UICollectionViewLayoutAttributes, for visibleRect: CGRect) { guard let collectionView = self.collectionView else { return} let activeDistance = collectionView.bounds.width // skip supplementary kind if case UICollectionElementCategory.supplementaryView = attribute.representedElementCategory { return } let distanceFromVisibleRectToItem: CGFloat = visibleRect.midX - attribute.center.x if fabs(distanceFromVisibleRectToItem) < activeDistance { let normalizeDistance = (fabs(distanceFromVisibleRectToItem) / activeDistance) handlerAttributeWithFactor(attribute, normalizeDistance) } else { handlerAttributeWithFactor(attribute, nil) } } }
mit
SpriteKitAlliance/SKAButton
Source/SKAButton.swift
1
14965
// // SKAButton.swift // SKAToolKit // // Copyright (c) 2015 Sprite Kit Alliance // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // import Foundation import SpriteKit /** Insets for the texture/color of the node - Note: Inset direction will move the texture/color towards that edge at the given amount. - SKButtonEdgeInsets(top: 10, right: 0, bottom: 0, left: 0) Top will move the texture/color towards the top - SKButtonEdgeInsets(top: 10, right: 0, bottom: 10, left: 0) Top and Bottom will cancel each other out */ struct SKButtonEdgeInsets { let top:CGFloat let right:CGFloat let bottom:CGFloat let left:CGFloat init() { top = 0.0 right = 0.0 bottom = 0.0 left = 0.0 } init(top:CGFloat, right:CGFloat, bottom:CGFloat, left:CGFloat) { self.top = top self.right = right self.bottom = bottom self.left = left } } /** SKSpriteNode set up to mimic the utility of UIButton - Note: Supports Texture per state, normal Texture per state, and color per state */ class SKAButtonSprite : SKAControlSprite { fileprivate var textures = [SKAControlState: SKTexture]() fileprivate var normalTextures = [SKAControlState: SKTexture]() fileprivate var colors = [SKAControlState: SKColor]() fileprivate var colorBlendFactors = [SKAControlState: CGFloat]() fileprivate var backgroundColor = SKColor.clear fileprivate var childNode: SKSpriteNode //Child node to act as our real node, the child node gets all of the updates the normal node would, and we keep the actual node as a clickable area only. /// Will restore the size of the texture node to the button size every time the button is updated var restoreSizeAfterAction = true var touchTarget:CGSize // MARK: - Initializers override init(texture: SKTexture?, color: UIColor, size: CGSize) { childNode = SKSpriteNode(texture: nil, color: color, size: size) touchTarget = size super.init(texture: texture, color: color, size: size) ///Set the default color and texture for Normal State setColor(color, forState: .Normal) setTexture(texture, forState: .Normal) setColorBlendFactor(0.0, forState: .Normal) self.addChild(childNode) } /** Use this method for initing with normal Map textures, SKSpriteNode's version will not persist the .Normal Textures correctly */ convenience init(texture: SKTexture?, normalMap: SKTexture?) { self.init(texture: texture, color: UIColor.clear, size: texture?.size() ?? CGSize()) setNormalTexture(normalMap, forState: .Normal) } required init?(coder aDecoder: NSCoder) { childNode = SKSpriteNode() touchTarget = CGSize() super.init(coder: aDecoder) self.addChild(childNode) } /** Update the button based on the state of the button. Since the button can hold more than one state at a time, determine the most important state and display the correct texture/color - Note: Disabled > Highlighted > Selected > Normal - Warning: SKActions can override setting the textures - Returns: void */ override func updateControl() { var newNormalTexture:SKTexture? var newTexture:SKTexture? var newColor = childNode.color var newColorBlendFactor = colorBlendFactors[.Normal] ?? colorBlendFactor if controlState.contains(.Disabled) { if let disabledNormal = normalTextures[.Disabled] { newNormalTexture = disabledNormal } if let disabled = textures[.Disabled] { newTexture = disabled } if let disabledColor = colors[.Disabled] { newColor = disabledColor } if let colorBlend = colorBlendFactors[.Disabled] { newColorBlendFactor = colorBlend } } else if controlState.contains(.Highlighted){ if let highlightedNormal = normalTextures[.Highlighted] { newNormalTexture = highlightedNormal } if let highlighted = textures[.Highlighted] { newTexture = highlighted } if let highlightedColor = colors[.Highlighted] { newColor = highlightedColor } if let colorBlend = colorBlendFactors[.Highlighted] { newColorBlendFactor = colorBlend } } else if controlState.contains(.Selected) { if let selectedNormal = normalTextures[.Selected] { newNormalTexture = selectedNormal } if let selected = textures[.Selected] { newTexture = selected } if let selectedColor = colors[.Selected] { newColor = selectedColor } if let colorBlend = colorBlendFactors[.Selected] { newColorBlendFactor = colorBlend } } else { //If .Normal if let normalColor = colors[.Normal] { newColor = normalColor } if let colorBlend = colorBlendFactors[.Normal] { newColorBlendFactor = colorBlend } } //Don't need to check if .Normal for textures, if nil set to .Normal textures if newNormalTexture == nil { newNormalTexture = normalTextures[.Normal] } if newTexture == nil { newTexture = textures[.Normal] } childNode.normalTexture = newNormalTexture childNode.texture = newTexture childNode.color = newColor childNode.colorBlendFactor = newColorBlendFactor if restoreSizeAfterAction { childNode.size = childNode.size } } // MARK: - Control States /** Sets the node's background color for the specified control state - Parameter color: The specified color - Parameter state: The specified control state to trigger the color change - Returns: void */ func setColor(_ color:SKColor?, forState state:SKAControlState) { if let color = color { colors[state] = color } else { for controlState in SKAControlState.AllOptions { if colors.keys.contains(controlState) { colors.removeValue(forKey: controlState) } } } updateControl() } /** Sets the node's colorBlendFactor for the specified control state - Parameter colorBlend: The specified colorBlendFactor - Parameter state: The specefied control state to trigger the color change - Returns: void */ func setColorBlendFactor(_ colorBlend:CGFloat?, forState state:SKAControlState){ if let colorBlend = colorBlend { colorBlendFactors[state] = colorBlend } else { for controlState in SKAControlState.AllOptions { if colorBlendFactors.keys.contains(controlState) { colorBlendFactors.removeValue(forKey: controlState) } } } updateControl() } /** Sets the node's texture for the specified control state - Parameter texture: The specified texture, if nil it clears the texture for the control state - Parameter state: The specified control state to trigger the texture change - Returns: void */ func setTexture(_ texture:SKTexture?, forState state:SKAControlState) { if let texture = texture { textures[state] = texture } else { for controlState in SKAControlState.AllOptions { if textures.keys.contains(controlState) { textures.removeValue(forKey: controlState) } } } updateControl() } /** Sets the node's normal texture for the specified control state - Parameter texture: The specified texture, if nil it clears the texture for the control state - Parameter state: The specified control state to trigger the normal texture change - Returns: void */ func setNormalTexture(_ texture:SKTexture?, forState state:SKAControlState) { if let texture = texture { normalTextures[state] = texture } else { for controlState in SKAControlState.AllOptions { if normalTextures.keys.contains(controlState) { normalTextures.removeValue(forKey: controlState) } } } updateControl() } /// Private variable to tell us when to update the button size or the child size fileprivate var updatingTargetSize = false /** Insets for the texture/color of the node - Note: Inset direction will move the texture/color towards that edge at the given amount. - SKButtonEdgeInsets(top: 10, right: 0, bottom: 0, left: 0) Top will move the texture/color towards the top - SKButtonEdgeInsets(top: 10, right: 0, bottom: 10, left: 0) Top and Bottom will cancel each other out */ var insets = SKButtonEdgeInsets() { didSet{ childNode.position = CGPoint(x: -insets.left + insets.right, y: -insets.bottom + insets.top) } } /** Sets the touchable area for the button - Parameter size: The size of the touchable area - Returns: void */ func setButtonTargetSize(_ size:CGSize) { updatingTargetSize = true self.size = size } /** Sets the touchable area for the button - Parameter size: The size of the touchable area - Parameter insets: The edge insets for the texture/color of the node - Returns: void - Note: Inset direction will move the texture/color towards that edge at the given amount. */ func setButtonTargetSize(_ size:CGSize, insets:SKButtonEdgeInsets) { self.insets = insets self.setButtonTargetSize(size) } // MARK: Shortcuts /** Shortcut to handle button highlighting Sets the colorBlendFactor to 0.2 for the Hightlighted State Sets the color to a slightly lighter version of the Normal State color for the Highlighted State */ func setAdjustsSpriteOnHighlight() { setColorBlendFactor(0.2, forState: .Highlighted) setColor(lightenColor(colors[.Normal] ?? color), forState: .Highlighted) } /** Shortcut to handle button disabling Sets the colorBlendFactor to 0.2 for the Disabled State Sets the color to a slightly darker version of the Normal State color for the Disabled State */ func setAdjustsSpriteOnDisable() { setColorBlendFactor(0.2, forState: .Disabled) setColor(darkenColor(colors[.Normal] ?? color), forState: .Disabled) } // MARK: Override basic functions and pass them to our child node override func action(forKey key: String) -> SKAction? { return childNode.action(forKey: key) } override func run(_ action: SKAction) { childNode.run(action) } override func run(_ action: SKAction, completion block: @escaping () -> Void) { childNode.run(action, completion: block) } override func run(_ action: SKAction, withKey key: String) { childNode.run(action, withKey: key) } override func removeAction(forKey key: String) { childNode.removeAction(forKey: key) updateControl() } override func removeAllActions() { childNode.removeAllActions() updateControl() } override func removeAllChildren() { childNode.removeAllChildren() } override var texture: SKTexture? { get { return childNode.texture } set { childNode.texture = newValue } } override var normalTexture: SKTexture? { get { return childNode.normalTexture } set { childNode.normalTexture = newValue } } override var color: SKColor { get { return childNode.color } set { super.color = SKColor.clear childNode.color = newValue } } override var colorBlendFactor: CGFloat { get { return childNode.colorBlendFactor } set { super.colorBlendFactor = 0.0 childNode.colorBlendFactor = newValue } } override var size: CGSize { willSet { if updatingTargetSize { if self.size != newValue { super.size = newValue } updatingTargetSize = false } else { childNode.size = newValue } } } // Mark: Color Functions /** Takes a color and slightly darkens it (if it can) - Parameter color: Color to darken - Returns: UIColor - Darkened Color */ fileprivate func darkenColor(_ color: UIColor) -> UIColor { var redComponent: CGFloat = 0.0 var blueComponent: CGFloat = 0.0 var greenComponent: CGFloat = 0.0 var alphaComponent: CGFloat = 0.0 if color.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent) { let defaultValue: CGFloat = 0.0 redComponent = max(redComponent - 0.2, defaultValue) blueComponent = max(blueComponent - 0.2, defaultValue) greenComponent = max(greenComponent - 0.2, defaultValue) alphaComponent = max(alphaComponent - 0.2, defaultValue) return UIColor(colorLiteralRed: Float(redComponent), green: Float(greenComponent), blue: Float(blueComponent), alpha: Float(alphaComponent)) } else { return color } } /** Takes a color and slightly lightens it (if it can) - Parameter color: Color to darken - Returns: UIColor - Lightened Color */ fileprivate func lightenColor(_ color: UIColor) -> UIColor { var redComponent: CGFloat = 1.0 var blueComponent: CGFloat = 1.0 var greenComponent: CGFloat = 1.0 var alphaComponent: CGFloat = 1.0 if color.getRed(&redComponent, green: &greenComponent, blue: &blueComponent, alpha: &alphaComponent) { let defaultValue: CGFloat = 1.0 redComponent = min(redComponent + 0.2, defaultValue) blueComponent = min(blueComponent + 0.2, defaultValue) greenComponent = min(greenComponent + 0.2, defaultValue) alphaComponent = min(alphaComponent + 0.2, defaultValue) return UIColor(colorLiteralRed: Float(redComponent), green: Float(greenComponent), blue: Float(blueComponent), alpha: Float(alphaComponent)) } else { return color } } /// Remove unneeded textures deinit { textures.removeAll() normalTextures.removeAll() removeAllChildren() } }
mit
CRivlaldo/MailCoreSwift
MailCoreSwiftTest/MailCoreSwiftTest/ViewController.swift
1
526
// // ViewController.swift // MailCoreSwiftTest // // Created by Vladimir Vlasov on 27/10/2017. // Copyright © 2017 MobilityLab, LLC. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
MakeZL/MLImagePickerController
Swift2.0+/MLImagePickerController-master/Demo/MLImagePickerController/MLImagePickerController/Classes/Extension/ML+UIImageExtension.swift
1
399
// // ML+UIImageExtension.swift // MLImagePickerController // // Created by 张磊 on 16/3/27. // Copyright © 2016年 zhanglei. All rights reserved. // import UIKit extension UIImage{ class func ml_imageFromBundleNamed(named:String)->UIImage{ let image = UIImage(named: "MLImagePickerController.bundle".stringByAppendingString("/"+(named as String)))! return image } }
mit
slq0378/SimpleMemo
Memo/Memo/MemoCell.swift
10
2836
// // MemoCell.swift // EverMemo // // Created by  李俊 on 15/8/5. // Copyright (c) 2015年  李俊. All rights reserved. // import UIKit class MemoCell: UICollectionViewCell, UIGestureRecognizerDelegate { var deleteMemo: ((memo: Memo) -> ())? var memo: Memo? { didSet{ contentLabel.text = memo!.text contentLabel.preferredMaxLayoutWidth = itemWidth - 2 * margin } } private let contentLabel: LJLabel = { let label = LJLabel() label.numberOfLines = 0 label.preferredMaxLayoutWidth = itemWidth - 2 * margin label.font = UIFont.systemFontOfSize(15) // label.textColor = UIColor.darkGrayColor() label.verticalAlignment = .Top label.sizeToFit() return label }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.whiteColor() setUI() // 设置阴影 layer.shadowOffset = CGSize(width: 0, height: 1); layer.shadowOpacity = 0.2; } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setUI(){ contentView.addSubview(contentLabel) contentLabel.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -5)) contentView.addConstraint(NSLayoutConstraint(item: contentLabel, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -5)) addGestureRecognizer() } private var getsureRecognizer: UIGestureRecognizer? private func addGestureRecognizer() { getsureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress") getsureRecognizer!.delegate = self contentView.addGestureRecognizer(getsureRecognizer!) } func longPress(){ // 添加一个判断,防止触发两次 if getsureRecognizer?.state == .Began{ deleteMemo?(memo: memo!) } } override func prepareForReuse() { deleteMemo = nil } }
mit
yangboz/SwiftTutorials
CookieCrunch/CookieCrunch/Tile.swift
1
416
// // Tile.swift // CookieCrunch // // Created by Matthijs on 19-06-14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // class Tile { // Note: To support different types of tiles, you can add properties here that // indicate how this tile should behave. For example, if a cookie is matched // that sits on a jelly tile, you'd set isJelly to NO to make it a normal tile. //var isJelly: Bool }
mit
TimurBK/SwiftSampleProject
swiftsampleproject/Code/Common/Architecture/Controllers/DataSources/DataSourceObject.swift
1
428
// // DataSourceObject.swift // swiftsampleproject // // Created by Timur Kuchkarov on 01.02.17. // Copyright © 2017 Timur Kuchkarov. All rights reserved. // import Foundation //class SectionDescriptionObject: NSObject, SectionDescription { // var title: String = "" // var rows: [AnyObject] = [] //} // //class DataSourceObject: NSObject, DataSource { // var arrayOfSectionDescriptions: [SectionDescription] = [] // //}
mit
oacastefanita/PollsFramework
PollsFramework/Classes/Utils/Extensions.swift
1
10110
#if os(iOS) || os(watchOS) import UIKit #endif import CryptoSwift //Primitive data types used to get all properties and values for any given object let primitiveDataTypes: Dictionary<String, Any> = [ "c" : Int8.self, "s" : Int16.self, "i" : Int32.self, "q" : Int.self, //also: Int64, NSInteger, only true on 64 bit platforms "S" : UInt16.self, "I" : UInt32.self, "Q" : UInt.self, //also UInt64, only true on 64 bit platforms "B" : Bool.self, "d" : Double.self, "f" : Float.self, "{" : Decimal.self ] #if os(iOS) || os(watchOS) #elseif os(OSX) //MARK: NSImage to PNG extension NSBitmapImageRep { var png: Data? { return representation(using: .png, properties: [:]) } } extension Data { var bitmap: NSBitmapImageRep? { return NSBitmapImageRep(data: self) } } extension NSImage { var png: Data? { return tiffRepresentation?.bitmap?.png } func savePNG(to url: URL) -> Bool { do { try png?.write(to: url) return true } catch { print(error) return false } } } #endif ///Iterate through the enum values func iterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> { var i = 0 return AnyIterator { let next = withUnsafeBytes(of: &i) { $0.load(as: T.self) } if next.hashValue != i { return nil } i += 1 return next } } extension NSObject { //MARK: Reflexion methods used to retrieve all object properties and values #if os(iOS) || os(watchOS) || os(tvOS) public var className: String { return String(describing: type(of: self)) } public class var className: String { return String(describing: self) } #endif public class func classFromString(_ className: String) -> AnyClass? { let namespace = Bundle(identifier: "org.cocoapods.PollsFramework")!.infoDictionary!["CFBundleExecutable"] as! String var cls = NSClassFromString("\(className)") if cls == nil{ cls = NSClassFromString("\(namespace).\(className)") } return cls; } public func getUsedProperties()->[String]{ var s = [String]() for c in Mirror(reflecting: self).children { if let name = c.label{ s.append(name) } if let value = c.value as Any! { if let st: String = value as? String { s.append(String(describing: st)) } if let st: Int = value as? Int { s.append(String(describing: st)) } if let st: Bool = value as? Bool { s.append(String(describing: st)) } } } return s } class func getNameOf(property: objc_property_t) -> String? { guard let name: NSString = NSString(utf8String: property_getName(property)) else { return nil } return name as String } public class func getTypesOfProperties(in clazz: NSObject.Type) -> Dictionary<String, Any>? { var count = UInt32() var types: Dictionary<String, Any> = [:] guard let properties = class_copyPropertyList(clazz, &count) else { return types } for i in 0..<Int(count) { guard let property: objc_property_t = properties[i], let name = getNameOf(property: property) else { continue } let type = getTypeOf(property: property) types[name] = type } free(properties) return types } class func getTypeOf(property: objc_property_t) -> Any { guard let attributesAsNSString: NSString = NSString(utf8String: property_getAttributes(property)!) else { return Any.self } let attributes = attributesAsNSString as String let slices = attributes.components(separatedBy: "\"") guard slices.count > 1 else { return getPrimitiveDataType(withAttributes: attributes) } let objectClassName = slices[1] let objectClass = NSClassFromString(objectClassName) as! NSObject.Type return objectClass } class func getPrimitiveDataType(withAttributes attributes: String) -> Any { let start = attributes.index(attributes.startIndex, offsetBy: 1) let end = attributes.index(attributes.startIndex, offsetBy: 2) let range = start..<end let letter = attributes.substring(with:range) let type = primitiveDataTypes[letter] return type ?? NSObject.self } } #if os(iOS) || os(tvOS) extension UIView { func snapshot() -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale) drawHierarchy(in: bounds, afterScreenUpdates: true) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } } public extension UIWindow { /// Replaces the root controller with the given view controller func replaceRootViewControllerWith(_ replacementController: UIViewController, animated: Bool, completion: (() -> Void)?) { let snapshotImageView = UIImageView(image: self.snapshot()) self.addSubview(snapshotImageView) let dismissCompletion = { () -> Void in // dismiss all modal view controllers self.rootViewController = replacementController self.bringSubview(toFront: snapshotImageView) if animated { UIView.animate(withDuration: 0.4, animations: { () -> Void in snapshotImageView.alpha = 0 }, completion: { (success) -> Void in snapshotImageView.removeFromSuperview() completion?() }) } else { snapshotImageView.removeFromSuperview() completion?() } } if self.rootViewController!.presentedViewController != nil { self.rootViewController!.dismiss(animated: false, completion: dismissCompletion) } else { dismissCompletion() } } /// Retrives the visible view controller of the window public var visibleViewController: UIViewController? { return UIWindow.getVisibleViewControllerFrom(self.rootViewController) } public static func getVisibleViewControllerFrom(_ vc: UIViewController?) -> UIViewController? { if let nc = vc as? UINavigationController { return UIWindow.getVisibleViewControllerFrom(nc.visibleViewController) } else if let tc = vc as? UITabBarController { return UIWindow.getVisibleViewControllerFrom(tc.selectedViewController) } else { if let pvc = vc?.presentedViewController { return UIWindow.getVisibleViewControllerFrom(pvc) } else { return vc } } } } #endif extension Date { /// Calculate age from Date var age:Int { return NSCalendar.current.dateComponents(Set<Calendar.Component>([.year]), from: self, to: Date()).year! } /// Create String using the "dateFormatForServer" format /// /// - Returns: A string containing the Date using the "dateFormatForServer" format func dateForServer() -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormatForServer let outputDate = dateFormatter.string(from: self) return outputDate } } extension String{ /// Returns the Date from value of the string using the "dateFormatForServer" as format /// /// - Returns: <#return value description#> func dateFromServer() -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = dateFormatForServer let date = dateFormatter.date(from: self) as Date! if date == nil{ return nil } return date! } //MARK: Phone validation func isValidPhone() -> Bool { if(self.characters.count < 6){ return false } let charcter = CharacterSet(charactersIn: "0123456789").inverted var filtered:String! let inputString:[String] = self.components(separatedBy: charcter) filtered = inputString.joined(separator: "") return self == filtered } //MARK: Validation regex for email func isValidEmail() -> Bool { // println("validate calendar: \(testStr)") let emailRegEx = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: self) } //Base64 encription and decription func encryptedAndBase64(_ key:String, iv:String) -> String { let passEnc:[UInt8] = try! AES(key: key, iv: iv).encrypt(pad(self.data(using: String.Encoding.utf8)!.bytes)) return Data(bytes: passEnc).base64EncodedString(options: NSData.Base64EncodingOptions.endLineWithCarriageReturn) } private func pad(_ value: [UInt8]) -> [UInt8] { var value = value let BLOCK_SIZE = 16 let length: Int = value.count let padSize = BLOCK_SIZE - (length % BLOCK_SIZE) let padArray = [UInt8](repeating: 0, count: padSize) value.append(contentsOf: padArray) return value } func decryptedAndBase64(_ key:String, iv:String) -> String { let baseToData = Data(base64Encoded: self, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) let decrypted:[UInt8] = try! AES(key: key, iv: iv).decrypt((baseToData?.bytes)!) return NSString(data: Data(bytes: decrypted), encoding:String.Encoding.utf8.rawValue)! as String } }
mit
WSDOT/wsdot-ios-app
wsdot/AmtrakCascadesServiceStopItem.swift
2
1327
// // AmtrakCascadesServiceItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation // Stop item represents an item from the Amtrak API. It is eitehr an arriavl or desprature. class AmtrakCascadesServiceStopItem{ var stationId: String = "" var stationName: String = "" var trainNumber: Int = -1 var tripNumer: Int = -1 var sortOrder: Int = -1 var arrivalComment: String? = nil var departureComment: String? = nil var scheduledArrivalTime: Date? = nil var scheduledDepartureTime: Date? = nil var updated = Date(timeIntervalSince1970: 0) }
gpl-3.0
shridharmalimca/iOSDev
iOS/Swift 3.0/Core Data/CoreDataTutorial/CoreDataTutorial/AppDelegate.swift
2
4701
// // AppDelegate.swift // CoreDataTutorial // // Created by Shridhar Mali on 2/1/17. // Copyright © 2017 Shridhar Mali. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var isAddPatient: Bool = false var selectedPatient = NSManagedObject() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "CoreDataTutorial") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
Swift-Squirrel/Squirrel
Sources/Squirrel/Router.swift
1
1061
// // Router.swift // Squirrel // // Created by Filip Klembara on 9/13/17. // import Foundation /// Router public protocol Router: RouteGroup { } struct CommonRouter: Router { var url: String var middlewareGroup: [Middleware] init(_ url: String, middlewares: [Middleware]) { middlewareGroup = middlewares self.url = url } } /// Route descriptor public struct RouteDescriptor { /// Route url public let route: String /// Used methods public let methods: [RequestLine.Method] } // MARK: - Router + routes public extension Router { /// Returns all routes public var routes: [RouteDescriptor] { return ResponseManager.sharedInstance.allRoutes } } // MARK: - Router + drop public extension Router { /// Drops handler for given method and route /// /// - Parameters: /// - method: Method type /// - route: Route url public func drop(method: RequestLine.Method, on route: String) { ResponseManager.sharedInstance.drop(method: method, on: route) } }
apache-2.0
Flinesoft/BartyCrouch
Sources/BartyCrouchConfiguration/Options/UpdateOptions/TranslateOptions.swift
1
2010
import BartyCrouchUtility import Foundation import MungoHealer import Toml public enum Translator: String { case microsoftTranslator case deepL } public struct TranslateOptions { public let paths: [String] public let subpathsToIgnore: [String] public let secret: Secret public let sourceLocale: String } extension TranslateOptions: TomlCodable { static func make(toml: Toml) throws -> TranslateOptions { let update: String = "update" let translate: String = "translate" if let secretString: String = toml.string(update, translate, "secret") { let translator = toml.string(update, translate, "translator") ?? "" let paths = toml.filePaths(update, translate, singularKey: "path", pluralKey: "paths") let subpathsToIgnore = toml.array(update, translate, "subpathsToIgnore") ?? Constants.defaultSubpathsToIgnore let sourceLocale: String = toml.string(update, translate, "sourceLocale") ?? "en" let secret: Secret switch Translator(rawValue: translator) { case .microsoftTranslator, .none: secret = .microsoftTranslator(secret: secretString) case .deepL: secret = .deepL(secret: secretString) } return TranslateOptions( paths: paths, subpathsToIgnore: subpathsToIgnore, secret: secret, sourceLocale: sourceLocale ) } else { throw MungoError( source: .invalidUserInput, message: "Incomplete [update.translate] options provided, ignoring them all." ) } } func tomlContents() -> String { var lines: [String] = ["[update.translate]"] lines.append("paths = \(paths)") lines.append("subpathsToIgnore = \(subpathsToIgnore)") switch secret { case let .deepL(secret): lines.append("secret = \"\(secret)\"") case let .microsoftTranslator(secret): lines.append("secret = \"\(secret)\"") } lines.append("sourceLocale = \"\(sourceLocale)\"") return lines.joined(separator: "\n") } }
mit
kstaring/swift
validation-test/compiler_crashers_fixed/26381-swift-genericsignature-genericsignature.swift
11
468
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct A{ let a{ func a{{ protocol A{ protocol c{ class A{var b{class case,
apache-2.0
kstaring/swift
validation-test/compiler_crashers_fixed/01716-swift-type-walk.swift
11
522
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse func a<T where I) -> String { A<T where T>) -> String { } protocol A : a { typealias e : a { } } struct e { } class a<l : A = d()
apache-2.0
jeden/kocomojo-kit
KocomojoKit/KocomojoKit/api/Jsonizable.swift
1
2436
// // Jsonizable.swift // KocomojoKit // // Created by Antonio Bello on 1/26/15. // Copyright (c) 2015 Elapsus. All rights reserved. // import Foundation public protocol JsonDecodable { class func decode(json: JsonType) -> Self? } public protocol JsonEncodable { func encode() -> JsonDictionary } public protocol Jsonizable : JsonDecodable, JsonEncodable { } public typealias JsonType = AnyObject public typealias JsonDictionary = Dictionary<String, JsonType> public typealias JsonArray = Array<JsonType> public func JsonString(object: JsonType?) -> String? { return object as? String } public func JsonInt(object: JsonType?) -> Int? { return object as? Int } public func JsonDouble(object: JsonType?) -> Double? { return object as? Double } public func JsonBool(object: JsonType?) -> Bool? { return object as? Bool } public func JsonDate(object: JsonType?) -> NSDate? { return NSDate.dateFromIso8610(JsonString(object)) } public func JsonObject(object: JsonType?) -> JsonDictionary? { return object as? JsonDictionary } public func JsonArrayType(object: JsonType?) -> JsonArray? { return object as? JsonArray } public func JsonEntity<T: JsonDecodable>(object: JsonType?) -> T? { if let object: JsonType = object { return T.decode(object) } return .None } infix operator >>> { associativity left precedence 150 } public func >>> <A, B>(a: A?, f: A -> B?) -> B? { if let x = a { return f(x) } return .None } infix operator <^> { associativity left } public func <^> <A, B>(f: A -> B, a: A?) -> B? { if let x = a { return f(x) } return .None } infix operator <&&> { associativity left } public func <&&> <A, B>(f: (A -> B)?, a: A?) -> B? { if let x = a { if let fx = f { return fx(x) } } return .None } infix operator <||> { associativity left } public func <||> <A, B>(f: (A? -> B)? , a: A?) -> B? { if let fx = f { return fx(a != nil ? a : .None) } return .None } extension NSDate { public class func dateFromIso8610(jsonDate: String?) -> NSDate? { if let jsonDate = jsonDate { let iso8610DateFormatter = NSDateFormatter() iso8610DateFormatter.timeStyle = .FullStyle iso8610DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z" return iso8610DateFormatter.dateFromString(jsonDate) } return .None } }
mit
Baglan/MCViewport
MCViewport/AppDelegate.swift
1
2172
// // AppDelegate.swift // MCViewport // // Created by Baglan on 2/11/16. // Copyright © 2016 Mobile Creators. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
CodaFi/swift-compiler-crashes
fixed/04279-swift-typebase-gettypeofmember.swift
11
217
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class b{func a<T:A struct A<T where f:A{struct A
mit
exercism/xswift
exercises/queen-attack/Package.swift
2
445
// swift-tools-version:4.2 import PackageDescription let package = Package( name: "QueenAttack", products: [ .library( name: "QueenAttack", targets: ["QueenAttack"]), ], dependencies: [], targets: [ .target( name: "QueenAttack", dependencies: []), .testTarget( name: "QueenAttackTests", dependencies: ["QueenAttack"]), ] )
mit
SunLiner/FleaMarket
FleaMarketGuideSwift/FleaMarketGuideSwift/Classes/NewFeature/FlowLayout/ALinFlowLayout.swift
1
663
// // ALinFlowLayout.swift // FleaMarketGuideSwift // // Created by ALin on 16/6/12. // Copyright © 2016年 ALin. All rights reserved. // import UIKit class ALinFlowLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() scrollDirection = .Horizontal minimumLineSpacing = 0 minimumInteritemSpacing = 0 itemSize = collectionView!.bounds.size collectionView!.showsVerticalScrollIndicator = false collectionView!.showsHorizontalScrollIndicator = false collectionView!.bounces = false collectionView!.pagingEnabled = true } }
mit
nuclearace/SwiftDiscord
Sources/SwiftDiscord/Gateway/DiscordEvent.swift
1
4218
// The MIT License (MIT) // Copyright (c) 2016 Erik Little // 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. /// /// An enum that represents the dispatch events Discord sends. /// /// If one of these events is handled specifically by the client then it will be turned into an event with the form /// `myEventName`. If it is not handled, then the associated enum string will be the event name. /// public enum DiscordDispatchEvent : String { /// Ready (Handled) case ready = "READY" /// Resumed (Handled) case resumed = "RESUMED" // Messaging /// Message Create (Handled) case messageCreate = "MESSAGE_CREATE" /// Message Delete (Not handled) case messageDelete = "MESSAGE_DELETE" /// Message Delete Bulk (Not handled) case messageDeleteBulk = "MESSAGE_DELETE_BULK" /// Message Reaction Add (Not handled) case messageReactionAdd = "MESSAGE_REACTION_ADD" /// Message Reaction Remove All (Not handled) case messageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL" /// Message Reaction Remove (Not handled) case messageReactionRemove = "MESSAGE_REACTION_REMOVE" /// Message Update (Not handled) case messageUpdate = "MESSAGE_UPDATE" // Guilds /// Guild Ban Add (Not handled) case guildBanAdd = "GUILD_BAN_ADD" /// Guild Ban Remove (Not handled) case guildBanRemove = "GUILD_BAN_REMOVE" /// Guild Create (Handled) case guildCreate = "GUILD_CREATE" /// GuildDelete (Handled) case guildDelete = "GUILD_DELETE" /// Guild Emojis Update (Handled) case guildEmojisUpdate = "GUILD_EMOJIS_UPDATE" /// Guild Integrations Update (Not handled) case guildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE" /// Guild Member Add (Handled) case guildMemberAdd = "GUILD_MEMBER_ADD" /// Guild Member Remove (Handled) case guildMemberRemove = "GUILD_MEMBER_REMOVE" /// Guild Member Update (Handled) case guildMemberUpdate = "GUILD_MEMBER_UPDATE" /// Guild Members Chunk (Handled) case guildMembersChunk = "GUILD_MEMBERS_CHUNK" /// Guild Role Create (Handled) case guildRoleCreate = "GUILD_ROLE_CREATE" /// Guild Role Delete (Handled) case guildRoleDelete = "GUILD_ROLE_DELETE" /// Guild Role Update (Handled) case guildRoleUpdate = "GUILD_ROLE_UPDATE" /// Guild Update (Handled) case guildUpdate = "GUILD_UPDATE" // Channels /// Channel Create (Handled) case channelCreate = "CHANNEL_CREATE" /// Channel Delete (Handled) case channelDelete = "CHANNEL_DELETE" /// Channel Pins Update (Not Handled) case channelPinsUpdate = "CHANNEL_PINS_UPDATE" /// Channel Update (Handled) case channelUpdate = "CHANNEL_UPDATE" // Voice /// Voice Server Update (Handled but no event emitted) case voiceServerUpdate = "VOICE_SERVER_UPDATE" /// Voice State Update (Handled) case voiceStateUpdate = "VOICE_STATE_UPDATE" /// Presence Update (Handled) case presenceUpdate = "PRESENCE_UPDATE" /// Typing Start (Not handled) case typingStart = "TYPING_START" // Webhooks /// Webhooks Update (Not handled) case webhooksUpdate = "WEBHOOKS_UPDATE" }
mit
S7Vyto/Mobile
iOS/SVNewsletter/SVNewsletter/Modules/Newsletter/View/NewsletterTableViewCell.swift
1
3022
// // NewsletterTableViewCell.swift // SVNewsletter // // Created by Sam on 22/11/2016. // Copyright © 2016 Semyon Vyatkin. All rights reserved. // import UIKit let backgroundColors = [ 0: [UIColor.rgb(169.0, 166.0, 168.0).cgColor, UIColor.rgb(209.0, 207.0, 209.0).cgColor], 1: [UIColor.rgb(51.0, 43.0, 77.0).cgColor, UIColor.rgb(51.0, 43.0, 77.0).cgColor] ] class NewsletterTableViewCell: UITableViewCell { @IBOutlet weak private var descLabel: UILabel! static var identifier: String { return NSStringFromClass(self).replacingOccurrences(of: "SVNewsletter.", with: "") } override var bounds: CGRect { didSet { self.contentView.bounds = bounds } } var desc: String? { didSet { descLabel.text = desc } } var isTouched: Bool = false { didSet { if oldValue != isTouched { updateContentAppearance(isTouched) } } } private lazy var backgroundLayer: CAGradientLayer = { let bgLayer = CAGradientLayer() bgLayer.shouldRasterize = true bgLayer.rasterizationScale = UIScreen.main.scale bgLayer.isOpaque = true bgLayer.opacity = 0.08 bgLayer.masksToBounds = true bgLayer.cornerRadius = 4.0 bgLayer.shadowColor = UIColor.black.cgColor bgLayer.shadowOffset = CGSize(width: 1.5, height: 1.5) bgLayer.shadowRadius = 6.0 bgLayer.shadowOpacity = 0.5 bgLayer.startPoint = CGPoint(x: 0.0, y: 0.5) bgLayer.endPoint = CGPoint(x: 1.0, y: 0.5) bgLayer.colors = backgroundColors[0]! return bgLayer }() // MARK: - Cell LifeCycle override func awakeFromNib() { super.awakeFromNib() configAppearance() } override func layoutSubviews() { super.layoutSubviews() let rect = CGRect(x: 10.0, y: 5.0, width: self.bounds.size.width - 20.0, height: self.bounds.size.height - 10.0) backgroundLayer.frame = rect backgroundLayer.shadowPath = UIBezierPath(roundedRect: rect, cornerRadius: 2.0).cgPath } // MARK: - Cell Appearance private func configAppearance() { self.selectionStyle = .none self.backgroundColor = UIColor.clear self.layer.masksToBounds = true self.layer.insertSublayer(backgroundLayer, at: 0) } private func updateContentAppearance(_ isSelected: Bool) { let index = isSelected ? 1 : 0 UIView.animate(withDuration: 0.3, animations: { [weak self] in self?.backgroundLayer.colors = backgroundColors[index]! }) { [weak self] completed in if completed { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { self?.isTouched = false }) } } } }
apache-2.0
codebrewer/HillListsBackupLibrary
Tests/HillListsBackupLibraryTests/HillAscentsTests.swift
1
4976
//----------------------------------------------------------------------------// // // Copyright 2017 Mark Scott // // 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. // //----------------------------------------------------------------------------// @testable import HillListsBackupLibrary import XCTest /// Tests of the `HillAscents` type. class HillAscentsTests: XCTestCase { private func createHillAscents(hillNumbers: [String], ascentsData: [[[String: Any]]]) -> [AscendedHill] { guard hillNumbers.count == ascentsData.count else { return [AscendedHill]() } var data = [String: [[String: Any]]]() for i in 0..<hillNumbers.count { data[hillNumbers[i]] = ascentsData[i] } return AscendedHill.readAscendedHills(data: data) } private func createAscentData(date: Date?, notes: String?) -> [String: Any] { var data = [String: Any]() data[BackupKey.AscentsKey.date.rawValue] = date data[BackupKey.AscentsKey.notes.rawValue] = notes return data } func testOneHillWithoutAscents() { // A hill number but no ascents should return an empty array of ascents // (although it shouldn't be seen in practice) // XCTAssertEqual(0, createHillAscents(hillNumbers: ["H1"], ascentsData: []).count) } func testOneHillWithOneAscent() { let now = Date() let hillNumber = "H1" let ascentData = createAscentData(date: now, notes: nil) let hillAscents = createHillAscents(hillNumbers: [hillNumber], ascentsData: [[ascentData]]) XCTAssertEqual(1, hillAscents.count) XCTAssertEqual(hillNumber, hillAscents[0].hillNumber) XCTAssertEqual(1, hillAscents[0].ascents.count) XCTAssertEqual(now, hillAscents[0].ascents[0].date) XCTAssertNil(hillAscents[0].ascents[0].notes) } func testOneHillWithTwoAscents() { let now = Date() let anHourAgo = now.addingTimeInterval(-3600.0) let hillNumber = "H1" let notes2 = "A note" let ascentData1 = createAscentData(date: now, notes: nil) let ascentData2 = createAscentData(date: anHourAgo, notes: notes2) let hillAscents = createHillAscents(hillNumbers: [hillNumber], ascentsData: [[ascentData1, ascentData2]]) XCTAssertEqual(1, hillAscents.count) XCTAssertEqual(hillNumber, hillAscents[0].hillNumber) XCTAssertEqual(2, hillAscents[0].ascents.count) XCTAssertEqual(now, hillAscents[0].ascents[0].date) XCTAssertNil(hillAscents[0].ascents[0].notes) XCTAssertEqual(anHourAgo, hillAscents[0].ascents[1].date) XCTAssertEqual(notes2, hillAscents[0].ascents[1].notes) } func testTwoHillsWithDifferingNumbersOfAscents() { // Hill 1 with two ascents // let hill_1_Number = "H1" let hill_1_Ascent_1_Date = Date().addingTimeInterval(-7200.0) let hill_1_Ascent_1_Notes: String? = nil let hill_1_Ascent_1_Data = createAscentData(date: hill_1_Ascent_1_Date, notes: hill_1_Ascent_1_Notes) let hill_1_Ascent_2_Date = hill_1_Ascent_1_Date.addingTimeInterval(3600.0) let hill_1_Ascent_2_Notes = "A note" let hill_1_Ascent_2_Data = createAscentData(date: hill_1_Ascent_2_Date, notes: hill_1_Ascent_2_Notes) // Hill 2 with one ascent // let hill_2_Number = "H2" let hill_2_Ascent_1_Date: Date? = nil let hill_2_Ascent_1_Notes = "A note for H2 ascent 1" let hill_2_Ascent_1_Data = createAscentData(date: hill_2_Ascent_1_Date, notes: hill_2_Ascent_1_Notes) // Store the input data for later comparison // var inputData = [String: [(date: Date?, notes: String?)]]() inputData[hill_1_Number] = [(hill_1_Ascent_1_Date, hill_1_Ascent_1_Notes), (hill_1_Ascent_2_Date, hill_1_Ascent_2_Notes)] inputData[hill_2_Number] = [(hill_2_Ascent_1_Date, hill_2_Ascent_1_Notes)] // Create the `HillAscents` objects to test // let hillAscents = createHillAscents( hillNumbers: [hill_1_Number, hill_2_Number], ascentsData: [[hill_1_Ascent_1_Data, hill_1_Ascent_2_Data], [hill_2_Ascent_1_Data]]) XCTAssertEqual(2, hillAscents.count) for i in 0..<hillAscents.count { let actualData = hillAscents[i] let expectedData = inputData[actualData.hillNumber] XCTAssertNotNil(expectedData) XCTAssertEqual(expectedData!.count, actualData.ascents.count) for j in 0..<expectedData!.count { XCTAssertEqual(expectedData![j].date, actualData.ascents[j].date) XCTAssertEqual(expectedData![j].notes, actualData.ascents[j].notes) } } } }
apache-2.0
v-braun/VBPiledView
VBPiledView/VBPiledView/VBPiledView.swift
1
4267
// // VBPiledView.swift // VBPiledView // // Created by Viktor Braun (v-braun@live.de) on 02.07.16. // Copyright © 2016 dev-things. All rights reserved. // public protocol VBPiledViewDataSource{ func piledView(_ numberOfItemsForPiledView: VBPiledView) -> Int func piledView(_ viewForPiledView: VBPiledView, itemAtIndex index: Int) -> UIView } open class VBPiledView: UIView, UIScrollViewDelegate { fileprivate let _scrollview = UIScrollView() open var dataSource : VBPiledViewDataSource? override init(frame: CGRect) { super.init(frame: frame) initInternal(); } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initInternal(); } override open func layoutSubviews() { _scrollview.frame = self.bounds self.layoutContent() super.layoutSubviews() } open func scrollViewDidScroll(_ scrollView: UIScrollView) { layoutContent() } fileprivate func initInternal(){ _scrollview.showsVerticalScrollIndicator = true _scrollview.showsHorizontalScrollIndicator = false _scrollview.isScrollEnabled = true _scrollview.delegate = self self.addSubview(_scrollview) } open var expandedContentHeightInPercent : Float = 80 open var collapsedContentHeightInPercent : Float = 5 fileprivate func layoutContent(){ guard let data = dataSource else {return} let currentScrollPoint = CGPoint(x:0, y: _scrollview.contentOffset.y) let contentMinHeight = (CGFloat(collapsedContentHeightInPercent) * _scrollview.bounds.height) / 100 let contentMaxHeight = (CGFloat(expandedContentHeightInPercent) * _scrollview.bounds.height) / 100 var lastElementH = CGFloat(0) var lastElementY = currentScrollPoint.y let subViewNumber = data.piledView(self) _scrollview.contentSize = CGSize(width: self.bounds.width, height: _scrollview.bounds.height * CGFloat(subViewNumber)) for index in 0..<subViewNumber { let v = data.piledView(self, itemAtIndex: index) if !v.isDescendant(of: _scrollview){ _scrollview.addSubview(v) } let y = lastElementY + lastElementH let currentViewUntransformedLocation = CGPoint(x: 0, y: (CGFloat(index) * _scrollview.bounds.height) + _scrollview.bounds.height) let prevViewUntransformedLocation = CGPoint(x: 0, y: currentViewUntransformedLocation.y - _scrollview.bounds.height) let slidingWindow = CGRect(origin: currentScrollPoint, size: _scrollview.bounds.size) var h = contentMinHeight if index == subViewNumber-1 { h = _scrollview.bounds.size.height if(currentScrollPoint.y > CGFloat(index) * _scrollview.bounds.size.height){ h = h + (currentScrollPoint.y - CGFloat(index) * _scrollview.bounds.size.height) } } else if slidingWindow.contains(currentViewUntransformedLocation){ let relativeScrollPos = currentScrollPoint.y - (CGFloat(index) * _scrollview.bounds.size.height) let scaleFactor = (relativeScrollPos * 100) / _scrollview.bounds.size.height let diff = (scaleFactor * contentMaxHeight) / 100 h = contentMaxHeight - diff } else if slidingWindow.contains(prevViewUntransformedLocation){ h = contentMaxHeight - lastElementH if currentScrollPoint.y < 0 { h = h + abs(currentScrollPoint.y) } else if(h < contentMinHeight){ h = contentMinHeight } } else if slidingWindow.origin.y > currentViewUntransformedLocation.y { h = 0 } v.frame = CGRect(origin: CGPoint(x: 0, y: y), size: CGSize(width: _scrollview.bounds.width, height: h)) lastElementH = v.frame.size.height lastElementY = v.frame.origin.y } } }
mit
malt03/DebugHead
DebugHead/Classes/DebugMenuExit.swift
1
821
// // DebugMenuExit.swift // Pods // // Created by Koji Murata on 2016/05/28. // // open class DebugMenuExit: DebugMenu { public let debugMenuTitle = "Exit" public let debugMenuDangerLevel = DebugMenuDangerLevel.extreme public let debugMenuAccessoryType = UITableViewCell.AccessoryType.none public func debugMenuSelected(_ debugHead: UIView, tableViewController: UITableViewController, indexPath: IndexPath) -> UIViewController? { let alert = UIAlertController(title: "Exit", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .destructive) { _ in exit(1) }) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) tableViewController.present(alert, animated: true, completion: nil) return nil } public init() {} }
mit
mmick66/KDRearrangeableCollectionViewFlowLayout
KDRearrangeableCollectionViewFlowLayout/KDRearrangeableCollectionViewFlowLayout.swift
1
13361
// // KDRearrangeableCollectionViewFlowLayout.swift // KDRearrangeableCollectionViewFlowLayout // // Created by Michael Michailidis on 16/03/2015. // Copyright (c) 2015 Karmadust. All rights reserved. // import UIKit protocol KDRearrangeableCollectionViewDelegate : UICollectionViewDelegate { func canMoveItem(at indexPath : IndexPath) -> Bool func moveDataItem(from source : IndexPath, to destination: IndexPath) -> Void } extension KDRearrangeableCollectionViewDelegate { func canMoveItem(at indexPath : IndexPath) -> Bool { return true } } enum KDDraggingAxis { case free case x case y case xy } class KDRearrangeableCollectionViewFlowLayout: UICollectionViewFlowLayout, UIGestureRecognizerDelegate { var animating : Bool = false var draggable : Bool = true var collectionViewFrameInCanvas : CGRect = CGRect.zero var hitTestRectagles = [String:CGRect]() var canvas : UIView? { didSet { if canvas != nil { self.calculateBorders() } } } var axis : KDDraggingAxis = .free struct Bundle { var offset : CGPoint = CGPoint.zero var sourceCell : UICollectionViewCell var representationImageView : UIView var currentIndexPath : IndexPath } var bundle : Bundle? override init() { super.init() self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { super.awakeFromNib() self.setup() } func setup() { if let collectionView = self.collectionView { let longPressGestureRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(KDRearrangeableCollectionViewFlowLayout.handleGesture(_:))) longPressGestureRecogniser.minimumPressDuration = 0.2 longPressGestureRecogniser.delegate = self collectionView.addGestureRecognizer(longPressGestureRecogniser) if self.canvas == nil { self.canvas = self.collectionView!.superview } } } override func prepare() { super.prepare() self.calculateBorders() } fileprivate func calculateBorders() { if let collectionView = self.collectionView { collectionViewFrameInCanvas = collectionView.frame if self.canvas != collectionView.superview { collectionViewFrameInCanvas = self.canvas!.convert(collectionViewFrameInCanvas, from: collectionView) } var leftRect : CGRect = collectionViewFrameInCanvas leftRect.size.width = 20.0 hitTestRectagles["left"] = leftRect var topRect : CGRect = collectionViewFrameInCanvas topRect.size.height = 20.0 hitTestRectagles["top"] = topRect var rightRect : CGRect = collectionViewFrameInCanvas rightRect.origin.x = rightRect.size.width - 20.0 rightRect.size.width = 20.0 hitTestRectagles["right"] = rightRect var bottomRect : CGRect = collectionViewFrameInCanvas bottomRect.origin.y = bottomRect.origin.y + rightRect.size.height - 20.0 bottomRect.size.height = 20.0 hitTestRectagles["bottom"] = bottomRect } } // MARK: - UIGestureRecognizerDelegate func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if draggable == false { return false } guard let ca = self.canvas else { return false } guard let cv = self.collectionView else { return false } let pointPressedInCanvas = gestureRecognizer.location(in: ca) for cell in cv.visibleCells { guard let indexPath:IndexPath = cv.indexPath(for: cell) else { return false } let cellInCanvasFrame = ca.convert(cell.frame, from: cv) if cellInCanvasFrame.contains(pointPressedInCanvas ) { if cv.delegate is KDRearrangeableCollectionViewDelegate { let d = cv.delegate as! KDRearrangeableCollectionViewDelegate if d.canMoveItem(at: indexPath) == false { return false } } if let kdcell = cell as? KDRearrangeableCollectionViewCell { // Override he dragging setter to apply and change in style that you want kdcell.dragging = true } UIGraphicsBeginImageContextWithOptions(cell.bounds.size, cell.isOpaque, 0) cell.layer.render(in: UIGraphicsGetCurrentContext()!) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let representationImage = UIImageView(image: img) representationImage.frame = cellInCanvasFrame let offset = CGPoint(x: pointPressedInCanvas.x - cellInCanvasFrame.origin.x, y: pointPressedInCanvas.y - cellInCanvasFrame.origin.y) self.bundle = Bundle(offset: offset, sourceCell: cell, representationImageView:representationImage, currentIndexPath: indexPath) break } } return (self.bundle != nil) } func checkForDraggingAtTheEdgeAndAnimatePaging(_ gestureRecognizer: UILongPressGestureRecognizer) { if self.animating == true { return } if let bundle = self.bundle { var nextPageRect : CGRect = self.collectionView!.bounds if self.scrollDirection == UICollectionViewScrollDirection.horizontal { if bundle.representationImageView.frame.intersects(hitTestRectagles["left"]!) { nextPageRect.origin.x -= nextPageRect.size.width if nextPageRect.origin.x < 0.0 { nextPageRect.origin.x = 0.0 } } else if bundle.representationImageView.frame.intersects(hitTestRectagles["right"]!) { nextPageRect.origin.x += nextPageRect.size.width if nextPageRect.origin.x + nextPageRect.size.width > self.collectionView!.contentSize.width { nextPageRect.origin.x = self.collectionView!.contentSize.width - nextPageRect.size.width } } } else if self.scrollDirection == UICollectionViewScrollDirection.vertical { if bundle.representationImageView.frame.intersects(hitTestRectagles["top"]!) { nextPageRect.origin.y -= nextPageRect.size.height if nextPageRect.origin.y < 0.0 { nextPageRect.origin.y = 0.0 } } else if bundle.representationImageView.frame.intersects(hitTestRectagles["bottom"]!) { nextPageRect.origin.y += nextPageRect.size.height if nextPageRect.origin.y + nextPageRect.size.height > self.collectionView!.contentSize.height { nextPageRect.origin.y = self.collectionView!.contentSize.height - nextPageRect.size.height } } } if !nextPageRect.equalTo(self.collectionView!.bounds){ let delayTime = DispatchTime.now() + Double(Int64(0.8 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: delayTime, execute: { self.animating = false self.handleGesture(gestureRecognizer) }); self.animating = true self.collectionView!.scrollRectToVisible(nextPageRect, animated: true) } } } @objc func handleGesture(_ gesture: UILongPressGestureRecognizer) -> Void { guard let bundle = self.bundle else { return } func endDraggingAction(_ bundle: Bundle) { bundle.sourceCell.isHidden = false if let kdcell = bundle.sourceCell as? KDRearrangeableCollectionViewCell { kdcell.dragging = false } bundle.representationImageView.removeFromSuperview() // if we have a proper data source then we can reload and have the data displayed correctly if let cv = self.collectionView, cv.delegate is KDRearrangeableCollectionViewDelegate { cv.reloadData() } self.bundle = nil } let dragPointOnCanvas = gesture.location(in: self.canvas) switch gesture.state { case .began: bundle.sourceCell.isHidden = true self.canvas?.addSubview(bundle.representationImageView) var imageViewFrame = bundle.representationImageView.frame var point = CGPoint.zero point.x = dragPointOnCanvas.x - bundle.offset.x point.y = dragPointOnCanvas.y - bundle.offset.y imageViewFrame.origin = point bundle.representationImageView.frame = imageViewFrame break case .changed: // Update the representation image var imageViewFrame = bundle.representationImageView.frame var point = CGPoint(x: dragPointOnCanvas.x - bundle.offset.x, y: dragPointOnCanvas.y - bundle.offset.y) if self.axis == .x { point.y = imageViewFrame.origin.y } if self.axis == .y { point.x = imageViewFrame.origin.x } imageViewFrame.origin = point bundle.representationImageView.frame = imageViewFrame var dragPointOnCollectionView = gesture.location(in: self.collectionView) if self.axis == .x { dragPointOnCollectionView.y = bundle.representationImageView.center.y } if self.axis == .y { dragPointOnCollectionView.x = bundle.representationImageView.center.x } if let indexPath : IndexPath = self.collectionView?.indexPathForItem(at: dragPointOnCollectionView) { self.checkForDraggingAtTheEdgeAndAnimatePaging(gesture) if (indexPath == bundle.currentIndexPath) == false { // If we have a collection view controller that implements the delegate we call the method first if let delegate = self.collectionView!.delegate as? KDRearrangeableCollectionViewDelegate { delegate.moveDataItem(from: bundle.currentIndexPath, to: indexPath) } self.collectionView!.moveItem(at: bundle.currentIndexPath, to: indexPath) self.bundle!.currentIndexPath = indexPath } } break case .ended: endDraggingAction(bundle) break case .cancelled: endDraggingAction(bundle) break case .failed: endDraggingAction(bundle) break case .possible: break } } }
mit
wjk930726/weibo
weiBo/weiBo/iPhone/AppDelegate/AppDelegate+AppService.swift
1
1592
// // AppDelegate+AppService.swift // weiBo // // Created by 王靖凯 on 2017/11/16. // Copyright © 2017年 王靖凯. All rights reserved. // import UIKit import XCGLogger extension AppDelegate { /// 初始化 window internal func initWindow() { window = UIWindow() let root = WBRootViewController() window?.rootViewController = root window?.makeKeyAndVisible() UITabBar.appearance().tintColor = globalColor UINavigationBar.appearance().tintColor = globalColor if #available(iOS 11.0, *) { // UIScrollView.appearance().contentInsetAdjustmentBehavior = .never } } /// 初始化XCGLogger对象,并进行设置 internal func initLogger(logger: XCGLogger) { logger.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: "path/to/file", fileLevel: .debug) } /// 一些请求 internal func requestForSomething() { NetworkManager.shared.requestForWeather(parameters: ["location": "ip"]) { obj in if let dict = obj { let res = Results.deserialize(from: dict) WBUserInfo.shared.weatherInfo = res?.results?.first } else { NetworkManager.shared.requestForWeather(parameters: ["location": "beijing"], networkCompletionHandler: { obj in let res = Results.deserialize(from: obj) WBUserInfo.shared.weatherInfo = res?.results?.first }) } } } }
mit
Starscream27/Logger
Logger/Logger.swift
1
2383
// // Logger.swift // Logger // // Created by Mathieu Meylan on 14/01/15. // The MIT License (MIT) // // Copyright (c) 2014 Mathieu Meylan // // 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 class Logger: NSObject { class func debug(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) { #if DEBUG self.__log__(message, "DEBUG", fileName, functionName, line) #endif } class func notice(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) { self.__log__(message, "NOTICE", fileName, functionName, line) } class func warn(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) { self.__log__(message, "WARN", fileName, functionName, line) } class func error(message: String, fileName: String = __FILE__, functionName: String = __FUNCTION__, line: Int = __LINE__) { self.__log__(message, "ERROR", fileName, functionName, line) } private class func __log__(message: String, _ header:String, _ fileName: String, _ functionName: String , _ line: Int) { NSLog("\(header) [\(fileName.lastPathComponent.stringByDeletingPathExtension).\(functionName):\(line)]: "+message) } }
mit
hjanuschka/fastlane
fastlane/swift/SnapshotfileProtocol.swift
2
2612
protocol SnapshotfileProtocol: class { var workspace: String? { get } var project: String? { get } var xcargs: String? { get } var devices: [String]? { get } var languages: [String] { get } var launchArguments: [String] { get } var outputDirectory: String { get } var outputSimulatorLogs: Bool { get } var iosVersion: String? { get } var skipOpenSummary: Bool { get } var skipHelperVersionCheck: Bool { get } var clearPreviousScreenshots: Bool { get } var reinstallApp: Bool { get } var eraseSimulator: Bool { get } var localizeSimulator: Bool { get } var appIdentifier: String? { get } var addPhotos: [String]? { get } var addVideos: [String]? { get } var buildlogPath: String { get } var clean: Bool { get } var configuration: String? { get } var xcprettyArgs: String? { get } var sdk: String? { get } var scheme: String? { get } var numberOfRetries: Int { get } var stopAfterFirstError: Bool { get } var derivedDataPath: String? { get } var testTargetName: String? { get } var namespaceLogFiles: String? { get } var concurrentSimulators: Bool { get } } extension SnapshotfileProtocol { var workspace: String? { return nil } var project: String? { return nil } var xcargs: String? { return nil } var devices: [String]? { return nil } var languages: [String] { return ["en-US"] } var launchArguments: [String] { return [""] } var outputDirectory: String { return "screenshots" } var outputSimulatorLogs: Bool { return false } var iosVersion: String? { return nil } var skipOpenSummary: Bool { return false } var skipHelperVersionCheck: Bool { return false } var clearPreviousScreenshots: Bool { return false } var reinstallApp: Bool { return false } var eraseSimulator: Bool { return false } var localizeSimulator: Bool { return false } var appIdentifier: String? { return nil } var addPhotos: [String]? { return nil } var addVideos: [String]? { return nil } var buildlogPath: String { return "~/Library/Logs/snapshot" } var clean: Bool { return false } var configuration: String? { return nil } var xcprettyArgs: String? { return nil } var sdk: String? { return nil } var scheme: String? { return nil } var numberOfRetries: Int { return 1 } var stopAfterFirstError: Bool { return false } var derivedDataPath: String? { return nil } var testTargetName: String? { return nil } var namespaceLogFiles: String? { return nil } var concurrentSimulators: Bool { return true } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.1]
mit
firebase/quickstart-ios
config/ConfigExample/Extensions.swift
1
3503
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit extension UIColor { var highlighted: UIColor { withAlphaComponent(0.8) } var image: UIImage { let pixel = CGSize(width: 1, height: 1) return UIGraphicsImageRenderer(size: pixel).image { context in self.setFill() context.fill(CGRect(origin: .zero, size: pixel)) } } } extension NSMutableAttributedString { /// Convenience init for generating attributred string with SF Symbols /// - Parameters: /// - text: The text for the attributed string. /// Add a `%@` at the location for the SF Symbol. /// - symbol: the name of the SF symbol convenience init(text: String, textColor: UIColor = .label, symbol: String? = nil, symbolColor: UIColor = .label) { var symbolAttachment: NSAttributedString? if let symbolName = symbol, let symbolImage = UIImage(systemName: symbolName) { let configuredSymbolImage = symbolImage.withTintColor( symbolColor, renderingMode: .alwaysOriginal ) let imageAttachment = NSTextAttachment(image: configuredSymbolImage) symbolAttachment = NSAttributedString(attachment: imageAttachment) } let splitStrings = text.components(separatedBy: "%@") let attributedString = NSMutableAttributedString() if let symbolAttachment = symbolAttachment, let range = text.range(of: "%@") { let shouldAddSymbolAtEnd = range.contains(text.endIndex) splitStrings.enumerated().forEach { index, string in let attributedPart = NSAttributedString(string: string) attributedString.append(attributedPart) if index < splitStrings.endIndex - 1 { attributedString.append(symbolAttachment) } else if index == splitStrings.endIndex - 1, shouldAddSymbolAtEnd { attributedString.append(symbolAttachment) } } } let attributes: [NSAttributedString.Key: Any] = [.foregroundColor: textColor] attributedString.addAttributes( attributes, range: NSRange(location: 0, length: attributedString.length) ) self.init(attributedString: attributedString) } func setColorForText(text: String, color: UIColor) { let range = mutableString.range(of: text, options: .caseInsensitive) addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: range) } } extension UIViewController { public func displayError(_ error: Error?, from function: StaticString = #function) { guard let error = error else { return } print("🚨 Error in \(function): \(error.localizedDescription)") let message = "\(error.localizedDescription)\n\n Ocurred in \(function)" let errorAlertController = UIAlertController( title: "Error", message: message, preferredStyle: .alert ) errorAlertController.addAction(UIAlertAction(title: "OK", style: .default)) present(errorAlertController, animated: true, completion: nil) } }
apache-2.0
hardikdevios/HKKit
Pod/Classes/HKExtras/HKProtocols.swift
1
309
// // HKProtocols.swift // HKKit // // Created by Hardik Shah on 08/09/17. // Copyright © 2017 Hardik. All rights reserved. // import Foundation public protocol ViewPager{ var title:String { get } } public protocol HKQueueConfirmation { func completed(operation:HKOperation) }
mit
xiaoxinghu/swift-org
Sources/Regex.swift
1
3774
// // Regex.swift // SwiftOrg // // Created by Xiaoxing Hu on 14/08/16. // Copyright © 2016 Xiaoxing Hu. All rights reserved. // import Foundation #if !os(Linux) typealias RegularExpression = NSRegularExpression typealias TextCheckingResult = NSTextCheckingResult #else extension TextCheckingResult { func rangeAt(_ idx: Int) -> NSRange { return range(at: idx) } } #endif var expressions = [String: RegularExpression]() public extension String { /// Cache regex (for performance and resource sake) /// /// - Parameters: /// - regex: regex pattern /// - options: options /// - Returns: the regex private func getExpression(_ regex: String, options: RegularExpression.Options) -> RegularExpression { let expression: RegularExpression if let exists = expressions[regex] { expression = exists } else { expression = try! RegularExpression(pattern: regex, options: options) expressions[regex] = expression } return expression } private func getMatches(_ match: TextCheckingResult) -> [String?] { var matches = [String?]() switch match.numberOfRanges { case 0: return [] case let n where n > 0: for i in 0..<n { let r = match.rangeAt(i) matches.append(r.length > 0 ? NSString(string: self).substring(with: r) : nil) } default: return [] } return matches } public func match(_ regex: String, options: RegularExpression.Options = []) -> [String?]? { let expression = self.getExpression(regex, options: options) if let match = expression.firstMatch(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) { return getMatches(match) } return nil } public func matchSplit(_ regex: String, options: RegularExpression.Options) -> [String] { let expression = self.getExpression(regex, options: options) let matches = expression.matches(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) var splitted = [String]() var cursor = 0 for m in matches { if m.range.location > cursor { splitted.append(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.characters.index(self.startIndex, offsetBy: m.range.location))) } splitted.append(NSString(string: self).substring(with: m.range)) cursor = (m.range.toRange()?.upperBound)! + 1 } if cursor <= self.characters.count { splitted.append(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.endIndex)) } return splitted } public func tryMatch(_ regex: String, options: RegularExpression.Options = [], match: ([String?]) -> Void, or: (String) -> Void) { let expression = self.getExpression(regex, options: options) let matches = expression.matches(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) var cursor = 0 for m in matches { if m.range.location > cursor { or(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.characters.index(self.startIndex, offsetBy: m.range.location))) } match(getMatches(m)) cursor = (m.range.toRange()?.upperBound)! } if cursor < self.characters.count { or(self.substring(with: self.characters.index(self.startIndex, offsetBy: cursor)..<self.endIndex)) } } }
mit
Trxy/TRX
Sources/morphable/Morphable+CGRect.swift
1
745
import CoreGraphics /** Adds Morphable conformance to CGRect */ extension CGRect: Morphable { /** Returns the value converted by ratio */ public static func morph(from: CGRect, to: CGRect, ratio: Double) -> CGRect { return CGRect(origin: CGPoint.morph(from: from.origin, to: to.origin, ratio: ratio), size: CGSize.morph(from: from.size, to: to.size, ratio: ratio)) } /// Initial normalized value (usually 0.0 or self if Double convertible) public var initialValue: Double { return 0 } /// Final normalized value (usually 1.0 or self if Double convertible) public var finalValue: Double { return Double(morpher.precision) } }
mit
lee0741/Glider
Glider/CommentController.swift
1
4165
// // CommentController.swift // Glider // // Created by Yancen Li on 2/24/17. // Copyright © 2017 Yancen Li. All rights reserved. // import UIKit class CommentController: UITableViewController, UIViewControllerPreviewingDelegate { let defaults = UserDefaults.standard let infoCellId = "storyInfoCell" let commentCellId = "commentCell" var comments = [Comment]() var story: Story? var itemId: Int? override func viewDidLoad() { super.viewDidLoad() configUi() Comment.getComments(from: itemId!) { comments, story in self.story = story self.comments = comments UIApplication.shared.isNetworkActivityIndicatorVisible = false self.tableView.reloadData() } } // MARK: - Config UI func configUi() { title = "Comment" tableView.register(HomeCell.self, forCellReuseIdentifier: infoCellId) tableView.register(CommentCell.self, forCellReuseIdentifier: commentCellId) tableView.separatorColor = .separatorColor let shareBarButtonItem = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(CommentController.shareAction)) navigationItem.setRightBarButton(shareBarButtonItem, animated: true) UIApplication.shared.statusBarStyle = .lightContent UIApplication.shared.isNetworkActivityIndicatorVisible = true if traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self as UIViewControllerPreviewingDelegate, sourceView: view) } } // MARK: - Share Action func shareAction() { let defaultText = "Discuss on HN: \(story!.title) https://news.ycombinator.com/item?id=\(story!.id)" let activityController = UIActivityViewController(activityItems: [defaultText], applicationActivities: nil) self.present(activityController, animated: true, completion: nil) } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return story == nil ? comments.count : comments.count+1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard story != nil else { return tableView.dequeueReusableCell(withIdentifier: commentCellId) as! CommentCell } if indexPath.row == 0 { let cell = tableView.dequeueReusableCell(withIdentifier: infoCellId) as! HomeCell cell.story = story cell.layoutIfNeeded() return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: commentCellId, for: indexPath) as! CommentCell cell.comment = comments[indexPath.row-1] cell.layoutIfNeeded() return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return 120 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == 0, let url = URL(string: story!.url) { let safariController = MySafariViewContoller(url: url) present(safariController, animated: true, completion: nil) } } // MARK: - 3D Touch func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location) else { return nil } if indexPath.row == 0, let cell = tableView.cellForRow(at: indexPath), let url = URL(string: story!.url) { let safariController = MySafariViewContoller(url: url) previewingContext.sourceRect = cell.frame return safariController } else { return nil } } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { present(viewControllerToCommit, animated: true, completion: nil) } }
mit
thomaspaulmann/EmojiTimeFormatter
Package.swift
1
139
import PackageDescription let package = Package( name: "EmojiTimeFormatter", exclude: ["EmojiTimeFormatter.xcodeproj", "Tests"] )
mit
eTilbudsavis/native-ios-eta-sdk
Sources/PagedPublication/PagedPublicationView+ContentsView.swift
1
8011
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit import Verso extension PagedPublicationView { /// The view containing the pages and the page number label /// This will fill the entirety of the publicationView, but will use layoutMargins for pageLabel alignment class ContentsView: UIView { struct Properties { var pageLabelString: String? var isBackgroundBlack: Bool = false var showAdditionalLoading: Bool = false } var properties = Properties() func update(properties: Properties) { self.properties = properties updatePageNumberLabel(with: properties.pageLabelString) var spinnerFrame = additionalLoadingSpinner.frame spinnerFrame.origin.x = self.layoutMarginsGuide.layoutFrame.maxX - spinnerFrame.width spinnerFrame.origin.y = pageNumberLabel.frame.midY - (spinnerFrame.height / 2) additionalLoadingSpinner.frame = spinnerFrame additionalLoadingSpinner.color = properties.isBackgroundBlack ? .white : UIColor(white: 0, alpha: 0.7) additionalLoadingSpinner.alpha = properties.showAdditionalLoading ? 1 : 0 } // MARK: Views var versoView = VersoView() fileprivate var pageNumberLabel = PageNumberLabel() fileprivate var additionalLoadingSpinner: UIActivityIndicatorView = { let view = UIActivityIndicatorView(style: .white) view.hidesWhenStopped = false view.startAnimating() return view }() // MARK: UIView Lifecycle override init(frame: CGRect) { super.init(frame: frame) versoView.frame = frame addSubview(versoView) addSubview(pageNumberLabel) addSubview(additionalLoadingSpinner) // initial state is invisible pageNumberLabel.alpha = 0 additionalLoadingSpinner.alpha = 0 setNeedsLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() versoView.frame = bounds self.update(properties: self.properties) } } } // MARK: - private typealias ContentsPageNumberLabel = PagedPublicationView.ContentsView extension ContentsPageNumberLabel { fileprivate func updatePageNumberLabel(with text: String?) { if let pageLabelString = text { // update the text & show label if pageNumberLabel.text != pageLabelString && self.pageNumberLabel.text != nil && self.pageNumberLabel.alpha != 0 { UIView.transition(with: pageNumberLabel, duration: 0.15, options: [.transitionCrossDissolve, .beginFromCurrentState], animations: { self.pageNumberLabel.text = text self.layoutPageNumberLabel() }) } else { pageNumberLabel.text = text self.layoutPageNumberLabel() } showPageNumberLabel() } else { // hide the label NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dimPageNumberLabel), object: nil) UIView.animate(withDuration: 0.2, delay: 0, options: [.beginFromCurrentState], animations: { self.pageNumberLabel.alpha = 0 }) } } fileprivate func layoutPageNumberLabel() { // layout page number label var lblFrame = pageNumberLabel.frame lblFrame.size = pageNumberLabel.sizeThatFits(bounds.size) lblFrame.size.width = ceil(lblFrame.size.width) lblFrame.size.height = round(lblFrame.size.height) lblFrame.origin.x = round(bounds.midX - (lblFrame.width / 2)) // change the bottom offset of the pageLabel when on iPhoneX let pageLabelBottomOffset: CGFloat if #available(iOS 11.0, *), UIDevice.current.userInterfaceIdiom == .phone, UIScreen.main.nativeBounds.height == 2436 { // iPhoneX // position above the home indicator on iPhoneX pageLabelBottomOffset = bounds.maxY - safeAreaLayoutGuide.layoutFrame.maxY } else { pageLabelBottomOffset = 11 } lblFrame.origin.y = round(bounds.maxY - pageLabelBottomOffset - lblFrame.height) pageNumberLabel.frame = lblFrame } @objc fileprivate func dimPageNumberLabel() { UIView.animate(withDuration: 1.0, delay: 0, options: [.beginFromCurrentState], animations: { self.pageNumberLabel.alpha = 0.2 }, completion: nil) } fileprivate func showPageNumberLabel() { NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dimPageNumberLabel), object: nil) UIView.animate(withDuration: 0.5, delay: 0, options: [.beginFromCurrentState], animations: { self.pageNumberLabel.alpha = 1.0 }, completion: nil) self.perform(#selector(dimPageNumberLabel), with: nil, afterDelay: 1.0) } fileprivate class PageNumberLabel: UILabel { override init(frame: CGRect) { super.init(frame: frame) layer.cornerRadius = 6 layer.masksToBounds = true textColor = .white layer.backgroundColor = UIColor(white: 0, alpha: 0.3).cgColor textAlignment = .center // monospaced numbers let fontDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: UIFont.TextStyle.headline) let features: [[UIFontDescriptor.FeatureKey: Any]] = [ [.featureIdentifier: kNumberSpacingType, .typeIdentifier: kMonospacedNumbersSelector], [.featureIdentifier: kStylisticAlternativesType, .typeIdentifier: kStylisticAltOneOnSelector], [.featureIdentifier: kStylisticAlternativesType, .typeIdentifier: kStylisticAltTwoOnSelector] ] let monospacedNumbersFontDescriptor = fontDescriptor.addingAttributes([.featureSettings: features]) //TODO: dynamic font size font = UIFont(descriptor: monospacedNumbersFontDescriptor, size: 16) numberOfLines = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var labelEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 4, left: 22, bottom: 4, right: 22) override func textRect(forBounds bounds: CGRect, limitedToNumberOfLines numberOfLines: Int) -> CGRect { var rect = super.textRect(forBounds: bounds.inset(by: labelEdgeInsets), limitedToNumberOfLines: numberOfLines) rect.origin.x -= labelEdgeInsets.left rect.origin.y -= labelEdgeInsets.top rect.size.width += labelEdgeInsets.left + labelEdgeInsets.right rect.size.height += labelEdgeInsets.top + labelEdgeInsets.bottom return rect } override func drawText(in rect: CGRect) { super.drawText(in: rect.inset(by: labelEdgeInsets)) } } }
mit
theprangnetwork/PSAnimation
PSBackgroundColorAnimation.swift
1
946
// PSAnimation by Pranjal Satija import UIKit struct PSBackgroundColorAnimation: PSAnimation { var duration: Double var toValue: AnyObject func performOnView(view: UIView, completion: (() -> ())?) { guard let toValue = (toValue as? UIColor)?.CGColor else { fatalError("PSBackgroundColorAnimation: toValue must be of type UIColor") } let animation = CABasicAnimation(keyPath: "backgroundColor") animation.fromValue = view.layer.backgroundColor animation.toValue = toValue CATransaction.setAnimationDuration(duration) if let completion = completion { CATransaction.setCompletionBlock(completion) } CATransaction.begin() view.layer.addAnimation(animation, forKey: nil) view.layer.backgroundColor = toValue CATransaction.commit() } }
apache-2.0
giridharvc7/ScreenRecord
ScreenRecordDemo/MasterViewController.swift
1
3840
// // MasterViewController.swift // ScreenRecordDemo // // Created by Giridhar on 21/06/17. // Copyright © 2017 Jambav. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [Any]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.leftBarButtonItem = editButtonItem let screenRecord = ScreenRecordCoordinator() screenRecord.viewOverlay.stopButtonColor = UIColor.red let randomNumber = arc4random_uniform(9999); screenRecord.startRecording(withFileName: "coolScreenRecording\(randomNumber)", recordingHandler: { (error) in print("Recording in progress") }) { (error) in print("Recording Complete") } let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) navigationItem.rightBarButtonItem = addButton if let split = splitViewController { let controllers = split.viewControllers detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(_ animated: Bool) { clearsSelectionOnViewWillAppear = splitViewController!.isCollapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @objc func insertNewObject(_ sender: Any) { objects.insert(NSDate(), at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = tableView.indexPathForSelectedRow { let object = objects[indexPath.row] as! NSDate let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .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
isnine/HutHelper-Open
HutHelper/SwiftApp/User/UseInfoViewModel.swift
1
2849
// // UseInfoViewModel.swift // HutHelperSwift // // Created by 张驰 on 2020/1/13. // Copyright © 2020 张驰. All rights reserved. // import Foundation import Alamofire import Moya import HandyJSON import SwiftyJSON class UseInfoViewModel { var classesDatas: [ClassModel] = [] } // - MARK: 网络请求 extension UseInfoViewModel { // 获取所有班级 func getAllClassesRequst(callback: @escaping () -> Void) { Alamofire.request(getAllclassesAPI).responseJSON { (response) in guard response.result.isSuccess else { return } let value = response.value let json = JSON(value!) if json["code"] == 200 { if let datas = json["data"].dictionaryObject { for (key, value) in datas { var data = ClassModel() data.depName = key data.classes = value as! [String] self.classesDatas.append(data) callback() } } } } } // 修改个人信息 func alterUseInfo(type: UserInfoAPI, callback: @escaping (_ result: Bool) -> Void) { UserInfoProvider .request(type) { (result) in if case let .success(response) = result { let data = try? response.mapJSON() let json = JSON(data!) print(json) if json["code"] == 200 { callback(true) } else if json["code"] == -1 { } } } } // 修改头像 func alterUseHeadImg(image: UIImage, callback: @escaping (_ result: String?) -> Void) { let imageData = UIImage.jpegData(image)(compressionQuality: 0.5) Alamofire.upload(multipartFormData: { (multipartFormData) in let now = Date() let timeForMatter = DateFormatter() timeForMatter.dateFormat = "yyyyMMddHHmmss" let id = timeForMatter.string(from: now) multipartFormData.append(imageData!, withName: "file", fileName: "\(id).jpg", mimeType: "image/jpeg") }, to: getUploadImages(type: 3)) { (encodingResult) in print("个人图片上传地址:\(getUploadImages(type: 3))") switch encodingResult { case .success(let upload, _, _): upload.responseString { response in if let data = response.data { let json = JSON(data) if json["code"] == 200 { callback(json["data"].stringValue) } } } case .failure: print("上传失败") } } } }
lgpl-2.1
ashfurrow/Moya
Examples/Multi-Target/ViewController.swift
1
5096
import UIKit import Moya let provider = MoyaProvider<MultiTarget>(plugins: [NetworkLoggerPlugin(configuration: .init(logOptions: .verbose))]) class ViewController: UITableViewController { var progressView = UIView() var repos = NSArray() override func viewDidLoad() { super.viewDidLoad() progressView.frame = CGRect(origin: .zero, size: CGSize(width: 0, height: 2)) progressView.backgroundColor = .blue navigationController?.navigationBar.addSubview(progressView) downloadRepositories("ashfurrow") } fileprivate func showAlert(_ title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertController.addAction(okAction) present(alertController, animated: true, completion: nil) } // MARK: - API Stuff func downloadRepositories(_ username: String) { provider.request(MultiTarget(GitHub.userRepositories(username))) { result in do { let response = try result.get() let value = try response.mapNSArray() self.repos = value self.tableView.reloadData() } catch { let printableError = error as CustomStringConvertible let errorMessage = printableError.description self.showAlert("GitHub Fetch", message: errorMessage) } } } func downloadZen() { provider.request(MultiTarget(GitHub.zen)) { result in var message = "Couldn't access API" if case let .success(response) = result { let jsonString = try? response.mapString() message = jsonString ?? message } self.showAlert("Zen", message: message) } } func uploadGiphy() { provider.request(MultiTarget(Giphy.upload(gif: Giphy.animatedBirdData)), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } func downloadMoyaLogo() { provider.request(MultiTarget(GitHubUserContent.downloadMoyaWebContent("logo_github.png")), callbackQueue: DispatchQueue.main, progress: progressClosure, completion: progressCompletionClosure) } // MARK: - Progress Helpers lazy var progressClosure: ProgressBlock = { response in UIView.animate(withDuration: 0.3) { self.progressView.frame.size.width = self.view.frame.size.width * CGFloat(response.progress) } } lazy var progressCompletionClosure: Completion = { result in let color: UIColor switch result { case .success: color = .green case .failure: color = .red } UIView.animate(withDuration: 0.3) { self.progressView.backgroundColor = color self.progressView.frame.size.width = self.view.frame.size.width } UIView.animate(withDuration: 0.3, delay: 1, options: [], animations: { self.progressView.alpha = 0 }, completion: { _ in self.progressView.backgroundColor = .blue self.progressView.frame.size.width = 0 self.progressView.alpha = 1 } ) } // MARK: - User Interaction @IBAction func giphyWasPressed(_ sender: UIBarButtonItem) { uploadGiphy() } @IBAction func searchWasPressed(_ sender: UIBarButtonItem) { var usernameTextField: UITextField? let promptController = UIAlertController(title: "Username", message: nil, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { _ in if let username = usernameTextField?.text { self.downloadRepositories(username) } } promptController.addAction(okAction) promptController.addTextField { textField in usernameTextField = textField } present(promptController, animated: true, completion: nil) } @IBAction func zenWasPressed(_ sender: UIBarButtonItem) { downloadZen() } @IBAction func downloadWasPressed(_ sender: UIBarButtonItem) { downloadMoyaLogo() } // MARK: - Table View override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return repos.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell let repo = repos[indexPath.row] as? NSDictionary cell.textLabel?.text = repo?["name"] as? String return cell } }
mit
chuck1991/QuickActionExample
QuickActionExample/ViewController.swift
1
504
// // ViewController.swift // QuickActionExample // // Created by Chuck on 1/25/16. // Copyright © 2016 kaichu. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
OscarSwanros/swift
validation-test/compiler_crashers/28797-declbits-beingvalidated-ibv.swift
14
477
// 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 // REQUIRES: asserts // RUN: not --crash %target-swift-frontend %s -emit-ir {typealias e:P.a protocol P{typealias a=a.b:class a
apache-2.0
ashfurrow/pragma-2015-rx-workshop
Session 4/Signup Demo/Pods/RxSwift/RxSwift/Observables/Implementations/AsObservable.swift
12
1188
// // AsObservable.swift // Rx // // Created by Krunoslav Zaher on 2/27/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class AsObservableSink<O: ObserverType> : Sink<O>, ObserverType { typealias Element = O.E override init(observer: O, cancel: Disposable) { super.init(observer: observer, cancel: cancel) } func on(event: Event<Element>) { observer?.on(event) switch event { case .Error, .Completed: self.dispose() default: break } } } class AsObservable<Element> : Producer<Element> { let source: Observable<Element> init(source: Observable<Element>) { self.source = source } func omega() -> Observable<Element> { return self } func eval() -> Observable<Element> { return source } override func run<O: ObserverType where O.E == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { let sink = AsObservableSink(observer: observer, cancel: cancel) setSink(sink) return source.subscribeSafe(sink) } }
mit
Nyx0uf/MPDRemote
src/common/extensions/CGContext+Extensions.swift
1
2860
// CGContext+Extensions.swift // Copyright (c) 2017 Nyx0uf // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import CoreGraphics // MARK: - Public constants public let kNYXNumberOfComponentsPerARBGPixel = 4 public let kNYXNumberOfComponentsPerRGBAPixel = 4 extension CGContext { // MARK: - ARGB bitmap context class func ARGBBitmapContext(width: Int, height: Int, withAlpha: Bool, wideGamut: Bool) -> CGContext? { let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedFirst : CGImageAlphaInfo.noneSkipFirst let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * kNYXNumberOfComponentsPerARBGPixel, space: wideGamut ? CGColorSpace.NYXAppropriateColorSpace() : CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) return bmContext } // MARK: - RGBA bitmap context class func RGBABitmapContext(width: Int, height: Int, withAlpha: Bool, wideGamut: Bool) -> CGContext? { let alphaInfo = withAlpha ? CGImageAlphaInfo.premultipliedLast : CGImageAlphaInfo.noneSkipLast let bmContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * kNYXNumberOfComponentsPerRGBAPixel, space: wideGamut ? CGColorSpace.NYXAppropriateColorSpace() : CGColorSpaceCreateDeviceRGB(), bitmapInfo: alphaInfo.rawValue) return bmContext } } extension CGColorSpace { class func NYXAppropriateColorSpace() -> CGColorSpace { if UIScreen.main.traitCollection.displayGamut == .P3 { if let p3ColorSpace = CGColorSpace(name: CGColorSpace.displayP3) { return p3ColorSpace } } return CGColorSpaceCreateDeviceRGB() } } struct RGBAPixel { var r: UInt8 var g: UInt8 var b: UInt8 var a: UInt8 init(r: UInt8, g: UInt8, b: UInt8, a: UInt8) { self.r = r self.g = g self.b = b self.a = a } }
mit
Intell/question
question/Utility/YRHttpRequest.swift
1
1337
// // YRHttpRequest.swift // JokeClient-Swift // // Created by YANGReal on 14-6-5. // Copyright (c) 2014年 YANGReal. All rights reserved. // import UIKit import Foundation //class func connectionWithRequest(request: NSURLRequest!, delegate: AnyObject!) -> NSURLConnection! class YRHttpRequest: NSObject { init() { super.init(); } class func requestWithURL(urlString:String,completionHandler:(data:AnyObject)->Void) { var URL = NSURL.URLWithString(urlString) var req = NSURLRequest(URL: URL) var queue = NSOperationQueue(); NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler: { response, data, error in if error { dispatch_async(dispatch_get_main_queue(), { println(error) completionHandler(data:NSNull()) }) } else { let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary dispatch_async(dispatch_get_main_queue(), { completionHandler(data:jsonData) }) } }) } }
apache-2.0
CodePath-Parse/MiAR
Playgrounds/SceneKit.playground/Contents.swift
2
3895
//: Playground - noun: a place where people can play import SceneKit import PlaygroundSupport struct Angle { static func rad(_ angle: Float) -> CGFloat { return CGFloat(angle) } static func deg(_ angle: Float) -> CGFloat { return CGFloat(Float.pi * angle / 180) } } extension SCNVector3 { func four(_ value: CGFloat) -> SCNVector4 { return SCNVector4Make(self.x, self.y, self.z, Float(value)) } } extension SCNVector4 { func three() -> SCNVector3 { return SCNVector3Make(self.x, self.y, self.z) } } extension SCNMatrix4 { static public func *(left: SCNMatrix4, right: SCNMatrix4) -> SCNMatrix4 { return SCNMatrix4Mult(left, right) } static public func *(left: SCNMatrix4, right: SCNVector4) -> SCNVector4 { let x = left.m11*right.x + left.m21*right.y + left.m31*right.z let y = left.m12*right.x + left.m22*right.y + left.m32*right.z let z = left.m13*right.x + left.m23*right.y + left.m33*right.z return SCNVector4(x: x, y: y, z: z, w: right.w * left.m44) } func inverted() -> SCNMatrix4 { return SCNMatrix4Invert(self) } } class Responder { init(node: SCNNode) { self.node = node } var node: SCNNode // Create the rotation let x = SCNVector3Make(1, 0, 0) let y = SCNVector3Make(0, 1, 0) let z = SCNVector3Make(0, 0, 1) @objc func rotateX() { rotate(node, around: x, by: Angle.deg(5), duration: 0.5) } @objc func rotateY() { rotate(node, around: y, by: Angle.deg(5), duration: 0.5) } @objc func rotateZ() { rotate(node, around: z, by: Angle.deg(5), duration: 0.5) } func rotate(_ node: SCNNode, around axis: SCNVector3, by angle: CGFloat, duration: TimeInterval, completionBlock: (()->())?) { let rotation = SCNMatrix4MakeRotation(Float(angle), axis.x, axis.y, axis.z) let newTransform = node.worldTransform * rotation // Animate the transaction SCNTransaction.begin() // Set the duration and the completion block SCNTransaction.animationDuration = duration SCNTransaction.completionBlock = completionBlock // Set the new transform if let parent = node.parent { node.transform = parent.convertTransform(newTransform, from: nil) } else { node.transform = newTransform } SCNTransaction.commit() } func rotate(_ node: SCNNode, around axis: SCNVector3, by angle: CGFloat, duration: TimeInterval) { rotate(node, around: axis, by: angle, duration: duration, completionBlock: nil) } } // Create a view, a scene and enable live view let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 500, height: 600)) let view = SCNView(frame: CGRect(x: 0, y: 0, width: 500, height: 500)) containerView.addSubview(view) let scene = SCNScene() view.scene = scene view.autoenablesDefaultLighting = true PlaygroundPage.current.liveView = containerView // Create the box let box = SCNBox(width: 50, height: 50, length: 50, chamferRadius: 5) let boxNode = SCNNode(geometry: box) let subnode = SCNNode() subnode.transform = SCNMatrix4MakeRotation(Float(Angle.deg(30)), 1, 1, 0) boxNode.rotation = SCNVector4Make(1, 0, 0, Float(Angle.deg(30))) scene.rootNode.addChildNode(subnode) subnode.addChildNode(boxNode) let responder = Responder(node: boxNode) let buttonX = UIButton() buttonX.titleLabel?.text = "Rotate X" buttonX.addTarget(responder, action: #selector(Responder.rotateX), for: .touchUpInside) let buttonY = UIButton() buttonY.titleLabel?.text = "Rotate Y" buttonY.addTarget(responder, action: #selector(Responder.rotateY), for: .touchUpInside) let stackView = UIStackView(arrangedSubviews: [buttonX, buttonY]) stackView.distribution = .equalSpacing stackView.axis = .horizontal containerView.addSubview(stackView)
apache-2.0
28stephlim/Heartbeat-Analyser
VoiceMemos/Controller/ApexSupineOutputViewController.swift
2
5038
// // ApexSupineOutputViewController.swift // VoiceMemos // // Created by Stephanie Lim on 02/10/2016. // Copyright © 2016 Zhouqi Mo. All rights reserved. // import UIKit import FDWaveformView import Foundation class ApexSupineOutputViewController: UIViewController { var URL : NSURL! ///TEST ONLY///// ////CHANGE AFTER//////// var apexsup = "nothing" var supine = ["AS-ESM", "AS-HSM","AS-LSM", "AS-MSC","AS-MSM","AS-Normal","AS-SplitS1"] //var supine = ["AS-SplitS1"] //unwind segue @IBAction func unwindtoASOutput(segue: UIStoryboardSegue){ } //Setting up waveform view and waeform target connection @IBOutlet weak var WaveformView: FDWaveformView! //Diagnosis labels target connections @IBOutlet weak var Diagnosis1: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //preparing data for 2nd VC override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "asout" { let VC2 : ApexSupineConditionViewController = segue.destinationViewController as! ApexSupineConditionViewController VC2.condition = apexsup VC2.URL = self.URL } } override func viewDidAppear(animated: Bool) { self.WaveformView.audioURL = URL self.WaveformView.progressSamples = 0 self.WaveformView.doesAllowScroll = true self.WaveformView.doesAllowStretch = true self.WaveformView.doesAllowScrubbing = false self.WaveformView.wavesColor = UIColor.blueColor() signalCompare(self.supine) } func signalCompare(type: [String]){ let bundle = NSBundle.mainBundle() var matchArray = [Float]() var match: Float = 0.0 for name in type { let sequenceURL = bundle.URLForResource(name, withExtension: "aiff")! match = compareFingerprint(self.URL, sequenceURL) print("Match = \(match)") matchArray.append(match) } let maxMatch = matchArray.maxElement() //this is the max match let maxLocationIndex = matchArray.indexOf(maxMatch!) //this is the index of the max match if you want to use it for something //var maxLocationInt = matchArray.startIndex.distanceTo(maxLocationIndex!) //this is the index cast as an int if you need to use it if (maxMatch<0.6) { self.Diagnosis1.text = "Error have occured. Please re-record the audio file." } else{ self.Diagnosis1.text = type[maxLocationIndex!] apexsup = type[maxLocationIndex!] } } } /* self.Diagnosis1.text = type[0] + ": \(matchArray[0])" self.Diagnosis2.text = type[1] + ": \(matchArray[1])" self.Diagnosis3.text = type[2] + ": \(matchArray[2])" self.Diagnosis4.text = type[3] + ": \(matchArray[3])" if (typeSize>4){ self.Diagnosis5.text = type[4] + ": \(matchArray[4])" self.Diagnosis6.text = type[5] + ": \(matchArray[5])" if (typeSize>6){ // These if statements make sure the data shows properly since we have self.Diagnosis7.text = type[6] + ": \(matchArray[6])" //different amounts of audio files for each category } } self.apexsup = type[maxLocationIndex!] switch maxLocationInt { case 0: self.Diagnosis1.textColor = UIColor.redColor() case 1: self.Diagnosis2.textColor = UIColor.redColor() case 2: self.Diagnosis3.textColor = UIColor.redColor() case 3: self.Diagnosis4.textColor = UIColor.redColor() case 4: self.Diagnosis5.textColor = UIColor.redColor() case 5: self.Diagnosis6.textColor = UIColor.redColor() case 6: self.Diagnosis7.textColor = UIColor.redColor() default: print("error has occurred changing text colour") //This probably wont happen } //let diagnosisAlert = UIAlertController(title: "Diagnosis", message: "\(type[maxLocation!])", preferredStyle: .Alert) //let okButton = UIAlertAction(title: "OK", style: .Default){(diagnosisAlert: UIAlertAction!)->Void in } //diagnosisAlert.addAction(okButton) //self.presentViewController(diagnosisAlert, animated: true, completion: nil) }) } */
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/00920-swift-typechecker-typecheckexpression.swift
1
235
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B { let end = f } enum a<T where T: T { { } typealias F = B
mit
VBVMI/VerseByVerse-iOS
VBVMI/Model/Video.swift
1
2574
import Foundation import CoreData import Decodable @objc(Video) open class Video: _Video { class func decodeJSON(_ JSONDict: NSDictionary, context: NSManagedObjectContext, index: Int) throws -> (Video) { guard let identifier = JSONDict["ID"] as? String else { throw APIDataManagerError.missingID } guard let video = Video.findFirstOrCreateWithDictionary(["identifier": identifier], context: context) as? Video else { throw APIDataManagerError.modelCreationFailed } video.identifier = try JSONDict => "ID" video.thumbnailSource = try JSONDict => "thumbnailSource" video.videoIndex = Int32(index) video.serviceVideoIdentifier = try? JSONDict => "serviceVideoID" video.service = try? JSONDict => "service" let channelDescription: String = try JSONDict => "description" video.descriptionText = channelDescription.stringByDecodingHTMLEntities video.thumbnailAltText = nullOrString(try JSONDict => "thumbnailAltText") if let dateString: String = try JSONDict => "postedDate" { video.postedDate = Date.dateFromTimeString(dateString) } if let dateString: String = try JSONDict => "recordedDate" { video.recordedDate = Date.dateFromTimeString(dateString) } video.averageRating = try JSONDict => "averageRating" video.videoSource = try JSONDict => "videoSource" video.videoLength = try JSONDict => "videoLength" video.url = nullOrString(try JSONDict => "url") let studyTitle: String = try JSONDict => "title" video.title = studyTitle.stringByDecodingHTMLEntities video.averageRating = nullOrString(try JSONDict => "averageRating") // if let topicsArray: [NSDictionary] = try JSONDict => "topics" as? [NSDictionary] { // //Then lets process the topics // var myTopics = Set<Topic>() // // topicsArray.forEach({ (topicJSONDict) -> () in // do { // if let topic = try Topic.decodeJSON(topicJSONDict, context: context) { // myTopics.insert(topic) // } // } catch let error { // logger.error("Error decoding Topic \(error)... Skippping...") // } // }) // // video.topics = myTopics // } return video } }
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/00570-swift-declcontext-lookupqualified.swift
12
216
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing let a { struct Q<T where T = c { struct S<c: N
mit
Fenrikur/ef-app_ios
Eurofurence/Director/ApplicationDirector.swift
1
4519
import EurofurenceModel import UIKit class ApplicationDirector: RootModuleDelegate, TutorialModuleDelegate, PreloadModuleDelegate { private var performAnimations: Bool { return animate && UIApplication.shared.applicationState == .active } private let animate: Bool private let moduleRepository: ModuleRepository private let navigationControllerFactory: NavigationControllerFactory private let tabModuleProviding: TabModuleProviding private let linkLookupService: ContentLinksService private let urlOpener: URLOpener private let orderingPolicy: ModuleOrderingPolicy private let windowWireframe: WindowWireframe private var newsController: UIViewController? private var scheduleViewController: UIViewController? private var knowledgeListController: UIViewController? private var dealersViewController: UIViewController? private var mapsModule: UIViewController? private var tabController: UITabBarController? private var tabBarDirector: TabBarDirector? init(animate: Bool, moduleRepository: ModuleRepository, linkLookupService: ContentLinksService, urlOpener: URLOpener, orderingPolicy: ModuleOrderingPolicy, windowWireframe: WindowWireframe, navigationControllerFactory: NavigationControllerFactory, tabModuleProviding: TabModuleProviding) { self.animate = animate self.moduleRepository = moduleRepository self.navigationControllerFactory = navigationControllerFactory self.tabModuleProviding = tabModuleProviding self.linkLookupService = linkLookupService self.urlOpener = urlOpener self.orderingPolicy = orderingPolicy self.windowWireframe = windowWireframe moduleRepository.makeRootModule(self) } // MARK: Public func openAnnouncement(_ announcement: AnnouncementIdentifier) { tabBarDirector?.openAnnouncement(announcement) } func openEvent(_ event: EventIdentifier) { tabBarDirector?.openEvent(event) } func openDealer(_ dealer: DealerIdentifier) { tabBarDirector?.openDealer(dealer) } func openMessage(_ message: MessageIdentifier) { tabBarDirector?.openMessage(message) } func openKnowledgeGroups() { tabBarDirector?.openKnowledgeGroups() } func showInvalidatedAnnouncementAlert() { tabBarDirector?.showInvalidatedAnnouncementAlert() } func openKnowledgeEntry(_ knowledgeEntry: KnowledgeEntryIdentifier) { tabBarDirector?.openKnowledgeEntry(knowledgeEntry) } func openKnowledgeEntry(_ knowledgeEntry: KnowledgeEntryIdentifier, parentGroup: KnowledgeGroupIdentifier) { tabBarDirector?.openKnowledgeEntry(knowledgeEntry, parentGroup: parentGroup) } // MARK: RootModuleDelegate func rootModuleDidDetermineTutorialShouldBePresented() { showTutorial() } func rootModuleDidDetermineStoreShouldRefresh() { showPreloadModule() } func rootModuleDidDetermineRootModuleShouldBePresented() { showTabModule() } // MARK: TutorialModuleDelegate func tutorialModuleDidFinishPresentingTutorial() { showPreloadModule() } // MARK: PreloadModuleDelegate func preloadModuleDidCancelPreloading() { showTutorial() } func preloadModuleDidFinishPreloading() { showTabModule() } // MARK: Private private func showPreloadModule() { let preloadViewController = moduleRepository.makePreloadModule(self) windowWireframe.setRoot(preloadViewController) } private func showTutorial() { let tutorialViewController = moduleRepository.makeTutorialModule(self) windowWireframe.setRoot(tutorialViewController) } private func showTabModule() { tabBarDirector = TabBarDirector(animate: animate, moduleRepository: moduleRepository, linkLookupService: linkLookupService, urlOpener: urlOpener, orderingPolicy: orderingPolicy, windowWireframe: windowWireframe, navigationControllerFactory: navigationControllerFactory, tabModuleProviding: tabModuleProviding) } }
mit
JohnEstropia/CoreStore
Demo/Sources/Demos/Classic/Classic.swift
1
171
// // Demo // Copyright © 2020 John Rommel Estropia, Inc. All rights reserved. // MARK: - Classic /** Sample usages for `NSManagedObject` subclasses */ enum Classic {}
mit
vczhou/twitter_feed
TwitterDemo/TwitterClient.swift
1
6996
// // TwitterClient.swift // TwitterDemo // // Created by Victoria Zhou on 2/22/17. // Copyright © 2017 Victoria Zhou. All rights reserved. // import UIKit import BDBOAuth1Manager class TwitterClient: BDBOAuth1SessionManager { static let sharedInstance = TwitterClient(baseURL: URL(string: "https://api.twitter.com")!, consumerKey: "PdPOZuL0M99HamGyjwZesURzT", consumerSecret: "OYHSMf5kre6891O1aHVcSKgUvBfdXDmHcQTtvhFcskpsga1ovI")! var loginSuccess: (() -> ())? var loginFailure: ((Error) -> ())? func login(success: @escaping () -> (), failure: @escaping (Error) -> ()) { loginSuccess = success loginFailure = failure TwitterClient.sharedInstance.deauthorize() TwitterClient.sharedInstance.fetchRequestToken(withPath: "oauth/request_token", method: "GET", callbackURL: URL(string: "twitterdemo://oauth"), scope: nil,success: { (requestToken: BDBOAuth1Credential?) -> Void in let authURL = URL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken!.token!)") UIApplication.shared.open(authURL!) }) { (error: Error?) -> Void in print("Failed to get request token") self.loginFailure?(error!) } } func logout() { User.currentUser = nil deauthorize() NotificationCenter.default.post(name: NSNotification.Name(rawValue: User.userDidLogoutNotification), object: nil) } func handleOpenUrl(url: URL) { let requestToken = BDBOAuth1Credential(queryString: url.query) fetchAccessToken(withPath: "oauth/access_token", method: "POST", requestToken: requestToken, success: { (accessToken: BDBOAuth1Credential?) -> Void in print("Got access token") self.currentAccount(sucess: { (user: User) -> () in User.currentUser = user self.loginSuccess?() }, failure: { (error: Error) -> () in print(error.localizedDescription) self.loginFailure?(error) }) }) { (error: Error?) -> Void in print("Failed to get access token") self.loginFailure?(error!) } } func currentAccount(sucess: @escaping (User) -> (), failure: @escaping (Error) -> ()) { get("1.1/account/verify_credentials.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let userDictionary = response as! NSDictionary let user = User(dictionary: userDictionary) sucess(user) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to verify credentials") failure(error) }) } func homeTimeline(success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { get("1.1/statuses/home_timeline.json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let dictionaries = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(dictionaries: dictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to get home timeline") failure(error) }) } func userTimeline(screenname: String, success: @escaping ([Tweet]) -> (), failure: @escaping (Error) -> ()) { let params = ["screen_name": screenname] get("1.1/statuses/user_timeline.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let dictionaries = response as! [NSDictionary] let tweets = Tweet.tweetsWithArray(dictionaries: dictionaries) success(tweets) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to get home timeline") failure(error) }) } func retweet(id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) { post("1.1/statuses/retweet/\(id).json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) success(tweet) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to retweet on id: \(id)") failure(error) }) } func unretweet(id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) { post("1.1/statuses/unretweet/\(id).json", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) success(tweet) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to unretweet on id: \(id)") failure(error) }) } func favorite(id: Int, success: @escaping(NSDictionary) -> (), failure: @escaping (Error) -> ()) { post("1.1/favorites/create.json?id=\(id)", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let favSuccess = response as! NSDictionary success(favSuccess) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to favorite on id: \(id)") failure(error) }) } func unfavorite(id: Int, success: @escaping(NSDictionary) -> (), failure: @escaping (Error) -> ()) { post("1.1/favorites/destroy.json?id=\(id)", parameters: nil, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let unfavSuccess = response as! NSDictionary success(unfavSuccess) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to unfavorite on id: \(id)") failure(error) }) } func tweet(tweet: String, isReply: Bool, id: Int, success: @escaping(Tweet) -> (), failure: @escaping (Error) -> ()) { var params = ["status": tweet] if(isReply) { params.updateValue("\(id)", forKey: "in_reply_to_status_id") } post("1.1/statuses/update.json", parameters: params, progress: nil, success: { (task: URLSessionDataTask?, response: Any?) -> Void in let status = response as! NSDictionary let tweet = Tweet(dictionary: status) success(tweet) }, failure: { (task: URLSessionDataTask?, error: Error) -> Void in print("Failed to post tweet on id: \(id)") print(error.localizedDescription) failure(error) }) } }
apache-2.0
thiagotmb/BEPiD-Challenges-2016
2016-04-05-Glance/2016-03-17-BackpackerChallenge WatchKit Extension/ShowMovieIC.swift
4
1185
// // ShowMovieIC.swift // 2016-03-17-BackpackerChallenge // // Created by Thiago-Bernardes on 3/18/16. // Copyright © 2016 TB. All rights reserved. // import WatchKit import Foundation class ShowMovieIC: WKInterfaceController { @IBOutlet var moviePlayer: WKInterfaceMovie! @IBOutlet var videoNameLabel: WKInterfaceLabel! var videoName : String! { didSet { videoNameLabel.setText(videoName) } } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) videoName = context as! String let urlLocal = NSBundle.mainBundle().URLForResource(videoName, withExtension: "3gp") moviePlayer.setMovieURL(urlLocal!) // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } }
mit
sarahspins/Loop
Loop/Models/ShareGlucose+GlucoseKit.swift
2
483
// // ShareGlucose+GlucoseKit.swift // Naterade // // Created by Nathan Racklyeft on 5/8/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit import LoopKit import ShareClient extension ShareGlucose: GlucoseValue { public var startDate: NSDate { return timestamp } public var quantity: HKQuantity { return HKQuantity(unit: HKUnit.milligramsPerDeciliterUnit(), doubleValue: Double(glucose)) } }
apache-2.0
stal888/RBQFetchedResultsController
Dynamic/Swift/FetchRequest.swift
1
166
// // FetchRequest.swift // RBQFRCSwiftExample // // Created by Adam Fish on 7/23/15. // Copyright (c) 2015 Adam Fish. All rights reserved. // import Foundation
mit
donmichael41/helloVapor
Package.swift
1
405
import PackageDescription let package = Package( name: "hello", dependencies: [ .Package(url: "https://github.com/vapor/vapor.git", majorVersion: 2), .Package(url: "https://github.com/vapor-community/postgresql-provider", majorVersion: 2, minor:0) ], exclude: [ "Config", "Database", "Localization", "Public", "Resources", ] )
mit
faraazkhan/kops
vendor/github.com/googleapis/gnostic/plugins/swift/gnostic_swift_sample/Sources/plugin.pb.swift
51
18490
/* * DO NOT EDIT. * * Generated by the protocol buffer compiler. * Source: plugin.proto * */ // Copyright 2016 Google Inc. 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. // openapic (aka the OpenAPI Compiler) can be extended via plugins. // A plugin is just a program that reads a Request from stdin // and writes a Response to stdout. // // A plugin executable needs only to be placed somewhere in the path. The // plugin should be named "openapi_$NAME", and will then be used when the // flag "--${NAME}_out" is passed to openapic. import Foundation import SwiftProtobuf /// The version number of OpenAPI compiler. public struct Openapi_Plugin_V1_Version: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_Version"} public var protoMessageName: String {return "Version"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "major": 1, "minor": 2, "patch": 3, "suffix": 4, ]} public var protoFieldNames: [String: Int] {return [ "major": 1, "minor": 2, "patch": 3, "suffix": 4, ]} public var major: Int32 = 0 public var minor: Int32 = 0 public var patch: Int32 = 0 /// A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should /// be empty for mainline stable releases. public var suffix: String = "" public init() {} public init(major: Int32? = nil, minor: Int32? = nil, patch: Int32? = nil, suffix: String? = nil) { if let v = major { self.major = v } if let v = minor { self.minor = v } if let v = patch { self.patch = v } if let v = suffix { self.suffix = v } } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeSingularField(fieldType: ProtobufInt32.self, value: &major) case 2: handled = try setter.decodeSingularField(fieldType: ProtobufInt32.self, value: &minor) case 3: handled = try setter.decodeSingularField(fieldType: ProtobufInt32.self, value: &patch) case 4: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &suffix) default: handled = false } return handled } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if major != 0 { try visitor.visitSingularField(fieldType: ProtobufInt32.self, value: major, protoFieldNumber: 1, protoFieldName: "major", jsonFieldName: "major", swiftFieldName: "major") } if minor != 0 { try visitor.visitSingularField(fieldType: ProtobufInt32.self, value: minor, protoFieldNumber: 2, protoFieldName: "minor", jsonFieldName: "minor", swiftFieldName: "minor") } if patch != 0 { try visitor.visitSingularField(fieldType: ProtobufInt32.self, value: patch, protoFieldNumber: 3, protoFieldName: "patch", jsonFieldName: "patch", swiftFieldName: "patch") } if suffix != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: suffix, protoFieldNumber: 4, protoFieldName: "suffix", jsonFieldName: "suffix", swiftFieldName: "suffix") } } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_Version) -> Bool { if major != other.major {return false} if minor != other.minor {return false} if patch != other.patch {return false} if suffix != other.suffix {return false} return true } } /// A parameter passed to the plugin from (or through) the OpenAPI compiler. public struct Openapi_Plugin_V1_Parameter: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_Parameter"} public var protoMessageName: String {return "Parameter"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "name": 1, "value": 2, ]} public var protoFieldNames: [String: Int] {return [ "name": 1, "value": 2, ]} /// The name of the parameter as specified in the option string public var name: String = "" /// The parameter value as specified in the option string public var value: String = "" public init() {} public init(name: String? = nil, value: String? = nil) { if let v = name { self.name = v } if let v = value { self.value = v } } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &name) case 2: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &value) default: handled = false } return handled } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if name != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: name, protoFieldNumber: 1, protoFieldName: "name", jsonFieldName: "name", swiftFieldName: "name") } if value != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: value, protoFieldNumber: 2, protoFieldName: "value", jsonFieldName: "value", swiftFieldName: "value") } } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_Parameter) -> Bool { if name != other.name {return false} if value != other.value {return false} return true } } /// An encoded Request is written to the plugin's stdin. public struct Openapi_Plugin_V1_Request: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_Request"} public var protoMessageName: String {return "Request"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "wrapper": 1, "outputPath": 2, "parameters": 3, "compilerVersion": 4, ]} public var protoFieldNames: [String: Int] {return [ "wrapper": 1, "output_path": 2, "parameters": 3, "compiler_version": 4, ]} private class _StorageClass { typealias ProtobufExtendedMessage = Openapi_Plugin_V1_Request var _wrapper: Openapi_Plugin_V1_Wrapper? = nil var _outputPath: String = "" var _parameters: [Openapi_Plugin_V1_Parameter] = [] var _compilerVersion: Openapi_Plugin_V1_Version? = nil init() {} func decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeSingularMessageField(fieldType: Openapi_Plugin_V1_Wrapper.self, value: &_wrapper) case 2: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &_outputPath) case 3: handled = try setter.decodeRepeatedMessageField(fieldType: Openapi_Plugin_V1_Parameter.self, value: &_parameters) case 4: handled = try setter.decodeSingularMessageField(fieldType: Openapi_Plugin_V1_Version.self, value: &_compilerVersion) default: handled = false } return handled } func traverse(visitor: inout ProtobufVisitor) throws { if let v = _wrapper { try visitor.visitSingularMessageField(value: v, protoFieldNumber: 1, protoFieldName: "wrapper", jsonFieldName: "wrapper", swiftFieldName: "wrapper") } if _outputPath != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: _outputPath, protoFieldNumber: 2, protoFieldName: "output_path", jsonFieldName: "outputPath", swiftFieldName: "outputPath") } if !_parameters.isEmpty { try visitor.visitRepeatedMessageField(value: _parameters, protoFieldNumber: 3, protoFieldName: "parameters", jsonFieldName: "parameters", swiftFieldName: "parameters") } if let v = _compilerVersion { try visitor.visitSingularMessageField(value: v, protoFieldNumber: 4, protoFieldName: "compiler_version", jsonFieldName: "compilerVersion", swiftFieldName: "compilerVersion") } } func isEqualTo(other: _StorageClass) -> Bool { if _wrapper != other._wrapper {return false} if _outputPath != other._outputPath {return false} if _parameters != other._parameters {return false} if _compilerVersion != other._compilerVersion {return false} return true } func copy() -> _StorageClass { let clone = _StorageClass() clone._wrapper = _wrapper clone._outputPath = _outputPath clone._parameters = _parameters clone._compilerVersion = _compilerVersion return clone } } private var _storage = _StorageClass() /// A wrapped OpenAPI document to process. public var wrapper: Openapi_Plugin_V1_Wrapper { get {return _storage._wrapper ?? Openapi_Plugin_V1_Wrapper()} set {_uniqueStorage()._wrapper = newValue} } /// Output path specified in the plugin invocation. public var outputPath: String { get {return _storage._outputPath} set {_uniqueStorage()._outputPath = newValue} } /// Plugin parameters parsed from the invocation string. public var parameters: [Openapi_Plugin_V1_Parameter] { get {return _storage._parameters} set {_uniqueStorage()._parameters = newValue} } /// The version number of openapi compiler. public var compilerVersion: Openapi_Plugin_V1_Version { get {return _storage._compilerVersion ?? Openapi_Plugin_V1_Version()} set {_uniqueStorage()._compilerVersion = newValue} } public init() {} public init(wrapper: Openapi_Plugin_V1_Wrapper? = nil, outputPath: String? = nil, parameters: [Openapi_Plugin_V1_Parameter] = [], compilerVersion: Openapi_Plugin_V1_Version? = nil) { let storage = _uniqueStorage() storage._wrapper = wrapper if let v = outputPath { storage._outputPath = v } if !parameters.isEmpty { storage._parameters = parameters } storage._compilerVersion = compilerVersion } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { return try _uniqueStorage().decodeField(setter: &setter, protoFieldNumber: protoFieldNumber) } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { try _storage.traverse(visitor: &visitor) } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_Request) -> Bool { return _storage === other._storage || _storage.isEqualTo(other: other._storage) } private mutating func _uniqueStorage() -> _StorageClass { if !isKnownUniquelyReferenced(&_storage) { _storage = _storage.copy() } return _storage } } /// The plugin writes an encoded Response to stdout. public struct Openapi_Plugin_V1_Response: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_Response"} public var protoMessageName: String {return "Response"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "errors": 1, "files": 2, ]} public var protoFieldNames: [String: Int] {return [ "errors": 1, "files": 2, ]} /// Error message. If non-empty, the plugin failed. /// The plugin process should exit with status code zero /// even if it reports an error in this way. /// /// This should be used to indicate errors which prevent the plugin from /// operating as intended. Errors which indicate a problem in openapic /// itself -- such as the input Document being unparseable -- should be /// reported by writing a message to stderr and exiting with a non-zero /// status code. public var errors: [String] = [] /// file output, each file will be written by openapic to an appropriate location. public var files: [Openapi_Plugin_V1_File] = [] public init() {} public init(errors: [String] = [], files: [Openapi_Plugin_V1_File] = []) { if !errors.isEmpty { self.errors = errors } if !files.isEmpty { self.files = files } } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeRepeatedField(fieldType: ProtobufString.self, value: &errors) case 2: handled = try setter.decodeRepeatedMessageField(fieldType: Openapi_Plugin_V1_File.self, value: &files) default: handled = false } return handled } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if !errors.isEmpty { try visitor.visitRepeatedField(fieldType: ProtobufString.self, value: errors, protoFieldNumber: 1, protoFieldName: "errors", jsonFieldName: "errors", swiftFieldName: "errors") } if !files.isEmpty { try visitor.visitRepeatedMessageField(value: files, protoFieldNumber: 2, protoFieldName: "files", jsonFieldName: "files", swiftFieldName: "files") } } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_Response) -> Bool { if errors != other.errors {return false} if files != other.files {return false} return true } } /// File describes a file generated by a plugin. public struct Openapi_Plugin_V1_File: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_File"} public var protoMessageName: String {return "File"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "name": 1, "data": 2, ]} public var protoFieldNames: [String: Int] {return [ "name": 1, "data": 2, ]} /// name of the file public var name: String = "" /// data to be written to the file public var data: Data = Data() public init() {} public init(name: String? = nil, data: Data? = nil) { if let v = name { self.name = v } if let v = data { self.data = v } } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &name) case 2: handled = try setter.decodeSingularField(fieldType: ProtobufBytes.self, value: &data) default: handled = false } return handled } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if name != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: name, protoFieldNumber: 1, protoFieldName: "name", jsonFieldName: "name", swiftFieldName: "name") } if data != Data() { try visitor.visitSingularField(fieldType: ProtobufBytes.self, value: data, protoFieldNumber: 2, protoFieldName: "data", jsonFieldName: "data", swiftFieldName: "data") } } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_File) -> Bool { if name != other.name {return false} if data != other.data {return false} return true } } /// Wrapper wraps an OpenAPI document with its version. public struct Openapi_Plugin_V1_Wrapper: ProtobufGeneratedMessage { public var swiftClassName: String {return "Openapi_Plugin_V1_Wrapper"} public var protoMessageName: String {return "Wrapper"} public var protoPackageName: String {return "openapi.plugin.v1"} public var jsonFieldNames: [String: Int] {return [ "name": 1, "version": 2, "value": 3, ]} public var protoFieldNames: [String: Int] {return [ "name": 1, "version": 2, "value": 3, ]} /// filename or URL of the wrapped document public var name: String = "" /// version of the OpenAPI specification that is used by the wrapped document public var version: String = "" /// valid serialized protocol buffer of the named OpenAPI specification version public var value: Data = Data() public init() {} public init(name: String? = nil, version: String? = nil, value: Data? = nil) { if let v = name { self.name = v } if let v = version { self.version = v } if let v = value { self.value = v } } public mutating func _protoc_generated_decodeField(setter: inout ProtobufFieldDecoder, protoFieldNumber: Int) throws -> Bool { let handled: Bool switch protoFieldNumber { case 1: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &name) case 2: handled = try setter.decodeSingularField(fieldType: ProtobufString.self, value: &version) case 3: handled = try setter.decodeSingularField(fieldType: ProtobufBytes.self, value: &value) default: handled = false } return handled } public func _protoc_generated_traverse(visitor: inout ProtobufVisitor) throws { if name != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: name, protoFieldNumber: 1, protoFieldName: "name", jsonFieldName: "name", swiftFieldName: "name") } if version != "" { try visitor.visitSingularField(fieldType: ProtobufString.self, value: version, protoFieldNumber: 2, protoFieldName: "version", jsonFieldName: "version", swiftFieldName: "version") } if value != Data() { try visitor.visitSingularField(fieldType: ProtobufBytes.self, value: value, protoFieldNumber: 3, protoFieldName: "value", jsonFieldName: "value", swiftFieldName: "value") } } public func _protoc_generated_isEqualTo(other: Openapi_Plugin_V1_Wrapper) -> Bool { if name != other.name {return false} if version != other.version {return false} if value != other.value {return false} return true } }
apache-2.0
tschob/HSAudioPlayer
HSAudioPlayer/Core/Public/Track/HSURLAudioPlayerItem.swift
1
4751
// // HSURLAudioPlayerItem.swift // HSAudioPlayer // // Created by Hans Seiffert on 02.08.16. // Copyright © 2016 Hans Seiffert. All rights reserved. // import Foundation import AVFoundation import MediaPlayer public class HSURLAudioPlayerItem: HSAudioPlayerItem { // MARK: - Properties public var url : NSURL? // MARK: - Initialization public convenience init?(urlString: String) { self.init(url: NSURL(string: urlString)) } public convenience init?(url: NSURL?) { guard url != nil else { return nil } self.init() self.url = url } public class func playerItems(urlStrings: [String], startPosition: Int) -> (playerItems: [HSURLAudioPlayerItem], startPosition: Int) { return self.playerItems(HSURLAudioPlayerItem.convertToURLs(urlStrings), startPosition: startPosition) } public class func playerItems(urls: [NSURL?], startPosition: Int) -> (playerItems: [HSURLAudioPlayerItem], startPosition: Int) { var reducedPlayerItems = [HSURLAudioPlayerItem]() var reducedStartPosition = startPosition // Iterate through all given URLs and create the player items for index in 0..<urls.count { let _url = urls[index] if let _playerItem = HSURLAudioPlayerItem(url: _url) { reducedPlayerItems.append(_playerItem) } else if (index <= startPosition && reducedStartPosition > 0) { // There is a problem with the URL. Ignore the URL and shift the start position if it is higher than the current index reducedStartPosition -= 1 } } return (playerItems: reducedPlayerItems, startPosition: reducedStartPosition) } // MARK: - Lifecycle override func prepareForPlaying(avPlayerItem: AVPlayerItem) { super.prepareForPlaying(avPlayerItem) // Listen to the timedMetadata initialization. We can extract the meta data then self.avPlayerItem?.addObserver(self, forKeyPath: Keys.TimedMetadata, options: NSKeyValueObservingOptions.Initial, context: nil) } override func cleanupAfterPlaying() { // Remove the timedMetadata observer as the AVPlayerItem will be released now self.avPlayerItem?.removeObserver(self, forKeyPath: Keys.TimedMetadata, context: nil) super.cleanupAfterPlaying() } public override func getAVPlayerItem() -> AVPlayerItem? { if let _url = self.url { return AVPlayerItem(URL: _url) } return nil } // MARK: - Now playing info public override func initNowPlayingInfo() { super.initNowPlayingInfo() self.nowPlayingInfo?[MPMediaItemPropertyTitle] = self.url?.lastPathComponent } // MARK: - Helper public override func identifier() -> String? { if let _urlAbsoluteString = self.url?.absoluteString { return _urlAbsoluteString } return super.identifier() } public class func convertToURLs(strings: [String]) -> [NSURL?] { var urls: [NSURL?] = [] for string in strings { urls.append(NSURL(string: string)) } return urls } public class func firstPlayableItem(urls: [NSURL?], startPosition: Int) -> (playerItem: HSURLAudioPlayerItem, index: Int)? { // Iterate through all URLs and check whether it's not nil for index in startPosition..<urls.count { if let _playerItem = HSURLAudioPlayerItem(url: urls[index]) { // Create the player item from the first playable URL and return it. return (playerItem: _playerItem, index: index) } } // There is no playable URL -> reuturn nil then return nil } // MARK: - PRIVATE - private struct Keys { static let TimedMetadata = "timedMetadata" } private func extractMetadata() { HSAudioPlayerLog("Extracting meta data of player item with url: \(url)") for metadataItem in (self.avPlayerItem?.asset.commonMetadata ?? []) { if let _key = metadataItem.commonKey { switch _key { case AVMetadataCommonKeyTitle : self.nowPlayingInfo?[MPMediaItemPropertyTitle] = metadataItem.stringValue case AVMetadataCommonKeyAlbumName : self.nowPlayingInfo?[MPMediaItemPropertyAlbumTitle] = metadataItem.stringValue case AVMetadataCommonKeyArtist : self.nowPlayingInfo?[MPMediaItemPropertyArtist] = metadataItem.stringValue case AVMetadataCommonKeyArtwork : if let _data = metadataItem.dataValue, _image = UIImage(data: _data) { self.nowPlayingInfo?[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(image: _image) } default : continue } } } // Inform the player about the updated meta data HSAudioPlayer.sharedInstance.didUpdateMetadata() } } // MARK: - KVO extension HSURLAudioPlayerItem { override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if (keyPath == Keys.TimedMetadata) { // Extract the meta data if the timedMetadata changed self.extractMetadata() } } }
mit
romankisil/eqMac2
native/app/Source/Audio/Sources/Input/InputSource.swift
1
830
// // DeviceInput.swift // eqMac // // Created by Roman Kisil on 06/11/2018. // Copyright © 2018 Roman Kisil. All rights reserved. // import Foundation import AMCoreAudio import AVFoundation class InputSource { let device: AudioDevice public init(device: AudioDevice) { self.device = device } static var hasPermission: Bool { get { if #available(OSX 10.14, *) { let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) return status == .authorized } else { return true } } } static func requestPermission (_ callback: @escaping (Bool) -> Void) { if #available(OSX 10.14, *) { AVCaptureDevice.requestAccess(for: AVMediaType.audio) { granted in callback(granted) } } else { callback(true) } } }
mit
cenfoiOS/ImpesaiOSCourse
CleanSwiftExample/CleanSwiftExample/Scenes/AddToDoTask/AddToDoTaskInteractor.swift
1
1062
// // AddToDoTaskInteractor.swift // CleanSwiftExample // // Created by Cesar Brenes on 6/6/17. // Copyright (c) 2017 César Brenes Solano. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol AddToDoTaskInteractorInput{ func doSomething(request: AddToDoTask.Request) } protocol AddToDoTaskInteractorOutput{ func presentSomething(response: AddToDoTask.Response) } class AddToDoTaskInteractor: AddToDoTaskInteractorInput{ var output: AddToDoTaskInteractorOutput! var worker: AddToDoTaskWorker! // MARK: Business logic func doSomething(request: AddToDoTask.Request){ // NOTE: Create some Worker to do the work worker = AddToDoTaskWorker() worker.doSomeWork() // NOTE: Pass the result to the Presenter let response = AddToDoTask.Response() output.presentSomething(response: response) } }
mit
emilstahl/swift
validation-test/compiler_crashers_fixed/25678-llvm-bitstreamcursor-read.swift
13
254
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing {init{ class A{protocol a{ class case,
apache-2.0
velvetroom/columbus
Source/View/Store/VStoreStatusReadyListCell.swift
1
1002
import UIKit class VStoreStatusReadyListCell:UICollectionViewCell { weak var imageView:UIImageView! weak var labelTitle:UILabel! weak var labelDescr:UILabel! weak var layoutDescrHeight:NSLayoutConstraint! private(set) weak var controller:CStore? let attributesDescr:[NSAttributedStringKey:Any] override init(frame:CGRect) { attributesDescr = VStoreStatusReadyListCell.factoryAttributesDescr( fontSize:VStoreStatusReadyListCell.Constants.descrFontSize) super.init(frame:frame) backgroundColor = UIColor.white clipsToBounds = true factoryViews() } required init?(coder:NSCoder) { return nil } //MARK: internal func config( controller:CStore, model:MStorePerkProtocol) { self.controller = controller imageView.image = model.icon labelTitle.text = model.title addDescr(model:model) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/00754-x.swift
1
502
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck nc e(self] == { typealias e = c(" let start = a(() print() protocol b : a { protocol C { } class func a
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/26639-void.swift
1
436
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class A{var:Collection} }{class case,
apache-2.0
Beaconstac/iOS-SDK
BeaconstacSampleApp/Pods/EddystoneScanner/EddystoneScanner/RSSIFilters/RunningAverageFilter.swift
1
2688
// // RunningAverageFilter.swift // EddystoneScanner // // Created by Sachin Vas on 26/02/18. // Copyright © 2018 Amit Prabhu. All rights reserved. // import Foundation /// /// The running average algorithm takes 20 seconds worth of samples /// and ignores the top and bottom 10 percent of the RSSI readings /// and takes the mean of the remainder. /// Similar to how iOS averages samples. https://stackoverflow.com/a/37391517/3106978 /// Very slow, there is a considerable lag before it moves on to the next beacon. /// Suitable for applications where the device is stationary /// internal class RunningAverageFilter: RSSIFilter { // Measurement struct used by the RunningAverageFilter internal struct Measurement: Comparable, Hashable { func hash(into hasher: inout Hasher) { hasher.combine(rssi) hasher.combine(timeStamp) } static func <(lhs: Measurement, rhs: Measurement) -> Bool { return lhs.rssi < rhs.rssi } static func ==(lhs: Measurement, rhs: Measurement) -> Bool { return lhs.rssi == rhs.rssi } var rssi: Int var timeStamp: TimeInterval } /// Stores the filter type internal var filterType: RSSIFilterType /// Filtered RSSI value internal var filteredRSSI: Int? { get { guard measurements.count > 0 else { return nil } let size = measurements.count var startIndex = measurements.startIndex var endIndex = measurements.endIndex if (size > 2) { startIndex = measurements.startIndex + measurements.index(measurements.startIndex, offsetBy: size / 10 + 1) endIndex = measurements.startIndex + measurements.index(measurements.startIndex, offsetBy: size - size / 10 - 2) } var sum = 0.0 for i in startIndex..<endIndex { sum += Double(measurements[i].rssi) } let runningAverage = sum / Double(endIndex - startIndex + 1) return Int(runningAverage) } } internal var measurements: [Measurement] = [] internal init() { self.filterType = .runningAverage } internal func calculate(forRSSI rssi: Int) { let measurement = Measurement(rssi: rssi, timeStamp: Date().timeIntervalSince1970) measurements.append(measurement) measurements = measurements.filter({ ($0.timeStamp - Date().timeIntervalSince1970) < 20000 }) measurements.sort(by: { $0 > $1 }) } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/26628-swift-type-subst.swift
1
454
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class T{{}init(){struct Q<a{class B:A{class d:d}class A
apache-2.0
instacrate/tapcrate-api
Sources/api/Controllers/CustomerController.swift
1
2529
// // UserController.swift // tapcrate-api // // Created by Hakon Hanesand on 11/12/16. // // import Vapor import HTTP import AuthProvider enum FetchType: String, TypesafeOptionsParameter { case stripe case shipping static let key = "type" static let values = [FetchType.stripe.rawValue, FetchType.shipping.rawValue] static var defaultValue: FetchType? = nil } final class CustomerController { func detail(_ request: Request) throws -> ResponseRepresentable { let customer = try request.customer() try Customer.ensure(action: .read, isAllowedOn: customer, by: request) if let expander: Expander<Customer> = try request.extract() { return try expander.expand(for: customer, mappings: { (relation, identifier: Identifier) -> [NodeRepresentable] in switch relation.path { case "cards": return try Stripe.paymentInformation(for: customer.stripeId()) case "shipping": return try customer.shippingAddresses().all() default: throw Abort.custom(status: .badRequest, message: "Could not find expansion for \(relation.path) on \(type(of: self)).") } }).makeResponse() } return try customer.makeResponse() } func create(_ request: Request) throws -> ResponseRepresentable { let customer: Customer = try request.extractModel() try Customer.ensure(action: .create, isAllowedOn: customer, by: request) if try Customer.makeQuery().filter("email", customer.email).count() > 0 { throw Abort.custom(status: .badRequest, message: "Username is taken.") } try customer.save() request.multipleUserAuth.authenticate(customer) return try customer.makeResponse() } func modify(_ request: Request, customer: Customer) throws -> ResponseRepresentable { try Customer.ensure(action: .write, isAllowedOn: customer, by: request) let customer: Customer = try request.patchModel(customer) try customer.save() return try customer.makeResponse() } } extension CustomerController: ResourceRepresentable { func makeResource() -> Resource<Customer> { return Resource( index: detail, store: create, update: modify ) } }
mit
sevenapps/SVNTheme
SVNThemeTests/SVNThemeTests.swift
1
946
// // SVNThemeTests.swift // SVNThemeTests // // Created by Aaron Dean Bikis on 4/10/17. // Copyright © 2017 7apps. All rights reserved. // import XCTest class SVNThemeTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
apache-2.0
abellono/IssueReporter
IssueReporter/Core/File.swift
1
395
// // File.swift // IssueReporter // // Created by Hakon Hanesand on 12/13/17. // import Foundation internal class File { var name: String var data: Data var state: State = .initial var htmlURL: URL? = nil init(name: String, data: Data) { assert(data.count > 0) assert(name.count > 0) self.name = name self.data = data } }
mit
hughbe/phone-number-picker
PhoneNumberPickerExample/PhoneNumberPickerExampleTests/PhoneNumberPickerExampleTests.swift
1
1042
// // PhoneNumberPickerExampleTests.swift // PhoneNumberPickerExampleTests // // Created by Lucas Farah on 3/28/16. // Copyright © 2016 Lucas Farah. All rights reserved. // import XCTest @testable import PhoneNumberPickerExample class PhoneNumberPickerExampleTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
kusl/swift
validation-test/compiler_crashers_fixed/0033-error.swift
12
225
// RUN: %target-swift-frontend %s -emit-ir // Test case submitted to project by https://github.com/practicalswift (practicalswift) // rdar://17240924 struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h }
apache-2.0
geekskool/JSONSwift
JSONSwift/JsonTest.swift
1
800
// // JsonTest.swift // JSONSwift // // Created by Ankit Goel on 18/09/15. // Copyright © 2015 geekschool. All rights reserved. // import Foundation let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first { let path = dir.stringByAppendingPathComponent(file); //writing do { try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} //reading do { let text2 = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} }
mit
angelolloqui/SwiftKotlin
Dummy/Sema.swift
1
186
// // Sema.swift // Dummy // // Created by Tomohiro Matsuzawa on 9/14/18. // import Foundation // Sema.framework build fails because it doesn't import Foundation, so import it here
mit
jisudong555/swift
weibo/weibo/Classes/Home/HomeViewController.swift
1
8675
// // HomeViewController.swift // weibo // // Created by jisudong on 16/4/8. // Copyright © 2016年 jisudong. All rights reserved. // import UIKit class HomeViewController: BaseViewController { var statuses: [Status]? { didSet { tableView.reloadData() } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.init(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1) if !userLogin { visitorView?.setupVisitorView(true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜") return } setupNavigationBar() // 注册通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(changeTitleArrow), name: PopoverAnimatorWillDismiss, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showPhotoBrowser(_:)), name: SDStatusPictureViewSelected, object: nil) tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: StatusCellReuseIdentifier.Forward.rawValue) tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellReuseIdentifier.Normal.rawValue) // tableView.estimatedRowHeight = 200 // tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = UITableViewCellSeparatorStyle.None refreshControl = HomeRefreshControl() refreshControl?.addTarget(self, action: #selector(loadData), forControlEvents: UIControlEvents.ValueChanged) loadData() // let instance = NetworkingManager.sharedInstance() // let instance1 = NetworkingManager.sharedInstance() // let instance2 = NetworkingManager() // // print("NetworkingManager: \(instance), \(instance1), \(instance2)") } func showPhotoBrowser(noti: NSNotification) { guard let indexPath = noti.userInfo![SDStatusPictureViewIndexKey] as? NSIndexPath else { return } guard let urls = noti.userInfo![SDStatusPictureViewURLsKey] as? [NSURL] else { return } let vc = PhotoBrowserController(index: indexPath.item, ulrs: urls) presentViewController(vc, animated: true, completion: nil) } private var pullupRefreshFlag = false @objc private func loadData() { var since_id = statuses?.first?.id ?? 0 var max_id = 0 if pullupRefreshFlag { since_id = 0 max_id = statuses?.last?.id ?? 0 } Status.loadStatues(since_id, max_id: max_id) { (models, error) in self.refreshControl?.endRefreshing() if error != nil { return } if since_id > 0 { self.statuses = models! + self.statuses! self.showNewStatusCount(models?.count ?? 0) } else if max_id > 0 { self.statuses = self.statuses! + models! } else { self.statuses = models } } } private func showNewStatusCount(count : Int) { newStatusLabel.hidden = false newStatusLabel.text = (count == 0) ? "没有刷新到新的微博数据" : "刷新到\(count)条微博数据" UIView.animateWithDuration(2, animations: { () -> Void in self.newStatusLabel.transform = CGAffineTransformMakeTranslation(0, self.newStatusLabel.frame.height) }) { (_) -> Void in UIView.animateWithDuration(2, animations: { () -> Void in self.newStatusLabel.transform = CGAffineTransformIdentity }, completion: { (_) -> Void in self.newStatusLabel.hidden = true }) } } func changeTitleArrow() { let titleButton = navigationItem.titleView as! TitleButton titleButton.selected = !titleButton.selected } private func setupNavigationBar() { navigationItem.leftBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_friendattention", target: self, action: #selector(leftItemClick)) navigationItem.rightBarButtonItem = UIBarButtonItem.createBarButtonItem("navigationbar_pop", target: self, action: #selector(rightItemClick)) let titleBtn = TitleButton() titleBtn.setTitle("素东", forState: UIControlState.Normal) titleBtn.addTarget(self, action: #selector(titleButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside) navigationItem.titleView = titleBtn } func titleButtonClick(button: TitleButton) { button.selected = !button.selected let sb = UIStoryboard(name: "PopoverViewController", bundle: nil) let vc = sb.instantiateInitialViewController() vc?.transitioningDelegate = popoverAnimator vc?.modalPresentationStyle = UIModalPresentationStyle.Custom presentViewController(vc!, animated: true, completion: nil) } func leftItemClick() { print(#function) } func rightItemClick() { print(#function) let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil) let vc = sb.instantiateInitialViewController() presentViewController(vc!, animated: true, completion: nil) } private lazy var popoverAnimator: PopoverAnimator = { let pa = PopoverAnimator() let popoverFrameW: CGFloat = 200.0 let popoverFrameX = (UIScreen.mainScreen().bounds.size.width - popoverFrameW) * 0.5 pa.presentFrame = CGRect(x: popoverFrameX, y: 56, width: popoverFrameW, height: 300) return pa }() /// 刷新提醒控件 private lazy var newStatusLabel: UILabel = { let label = UILabel() let height: CGFloat = 44 // label.frame = CGRect(x: 0, y: -2 * height, width: UIScreen.mainScreen().bounds.width, height: height) label.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: height) label.backgroundColor = UIColor.orangeColor() label.textColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center // 加载 navBar 上面,不会随着 tableView 一起滚动 self.navigationController?.navigationBar.insertSubview(label, atIndex: 0) label.hidden = true return label }() // 缓存cell高度 private var cellHeightCache = [Int: CGFloat]() override func didReceiveMemoryWarning() { cellHeightCache.removeAll() } } extension HomeViewController { override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statuses?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let status = statuses![indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellReuseIdentifier.cellID(status), forIndexPath: indexPath) as! StatusCell cell.status = status let count = statuses?.count ?? 0 if indexPath.row == (count - 1) { pullupRefreshFlag = true loadData() } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let status = statuses![indexPath.row] // if let cacheHeight = cellHeightCache[status.id] // { // print("缓存中获取") // return cacheHeight // } print("重新计算") var height: CGFloat = 0 switch StatusCellReuseIdentifier.cellID(status) { case StatusCellReuseIdentifier.Normal.rawValue: height = StatusNormalCell.cellHeightWithModel(status) default: height = StatusForwardCell.cellHeightWithModel(status) } cellHeightCache[status.id] = height return height } }
mit
michael-lehew/swift-corelibs-foundation
TestFoundation/TestNSNumberFormatter.swift
1
14350
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif import CoreFoundation class TestNSNumberFormatter: XCTestCase { static var allTests: [(String, (TestNSNumberFormatter) -> () throws -> Void)] { return [ ("test_currencyCode", test_currencyCode), ("test_decimalSeparator", test_decimalSeparator), ("test_currencyDecimalSeparator", test_currencyDecimalSeparator), ("test_alwaysShowDecimalSeparator", test_alwaysShowDecimalSeparator), ("test_groupingSeparator", test_groupingSeparator), ("test_percentSymbol", test_percentSymbol), ("test_zeroSymbol", test_zeroSymbol), ("test_notANumberSymbol", test_notANumberSymbol), ("test_positiveInfinitySymbol", test_positiveInfinitySymbol), ("test_minusSignSymbol", test_minusSignSymbol), ("test_plusSignSymbol", test_plusSignSymbol), ("test_currencySymbol", test_currencySymbol), ("test_exponentSymbol", test_exponentSymbol), ("test_minimumIntegerDigits", test_minimumIntegerDigits), ("test_maximumIntegerDigits", test_maximumIntegerDigits), ("test_minimumFractionDigits", test_minimumFractionDigits), ("test_maximumFractionDigits", test_maximumFractionDigits), ("test_groupingSize", test_groupingSize), ("test_secondaryGroupingSize", test_secondaryGroupingSize), ("test_roundingMode", test_roundingMode), ("test_roundingIncrement", test_roundingIncrement), ("test_formatWidth", test_formatWidth), ("test_formatPosition", test_formatPosition), ("test_multiplier", test_multiplier), ("test_positivePrefix", test_positivePrefix), ("test_positiveSuffix", test_positiveSuffix), ("test_negativePrefix", test_negativePrefix), ("test_negativeSuffix", test_negativeSuffix), ("test_internationalCurrencySymbol", test_internationalCurrencySymbol), ("test_currencyGroupingSeparator", test_currencyGroupingSeparator), ("test_lenient", test_lenient), ("test_minimumSignificantDigits", test_minimumSignificantDigits), ("test_maximumSignificantDigits", test_maximumSignificantDigits), ("test_stringFor", test_stringFor) ] } func test_currencyCode() { // Disabled due to [SR-250] /* let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .CurrencyStyle numberFormatter.currencyCode = "T" numberFormatter.currencyDecimalSeparator = "_" let formattedString = numberFormatter.stringFromNumber(42) XCTAssertEqual(formattedString, "T 42_00") */ } func test_decimalSeparator() { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.decimalSeparator = "-" let formattedString = numberFormatter.string(from: 42.42) XCTAssertEqual(formattedString, "42-42") } func test_currencyDecimalSeparator() { // Disabled due to [SR-250] /* let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .CurrencyStyle numberFormatter.currencyDecimalSeparator = "-" numberFormatter.currencyCode = "T" let formattedString = numberFormatter.stringFromNumber(42.42) XCTAssertEqual(formattedString, "T 42-42") */ } func test_alwaysShowDecimalSeparator() { let numberFormatter = NumberFormatter() numberFormatter.decimalSeparator = "-" numberFormatter.alwaysShowsDecimalSeparator = true let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "42-") } func test_groupingSeparator() { let numberFormatter = NumberFormatter() numberFormatter.usesGroupingSeparator = true numberFormatter.groupingSeparator = "_" let formattedString = numberFormatter.string(from: 42_000) XCTAssertEqual(formattedString, "42_000") } func test_percentSymbol() { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .percent numberFormatter.percentSymbol = "💯" let formattedString = numberFormatter.string(from: 0.42) XCTAssertEqual(formattedString, "42💯") } func test_zeroSymbol() { let numberFormatter = NumberFormatter() numberFormatter.zeroSymbol = "⚽️" let formattedString = numberFormatter.string(from: 0) XCTAssertEqual(formattedString, "⚽️") } var unknownZero: Int = 0 func test_notANumberSymbol() { let numberFormatter = NumberFormatter() numberFormatter.notANumberSymbol = "👽" let number: Double = -42 let numberObject = NSNumber(value: sqrt(number)) let formattedString = numberFormatter.string(from: numberObject) XCTAssertEqual(formattedString, "👽") } func test_positiveInfinitySymbol() { let numberFormatter = NumberFormatter() numberFormatter.positiveInfinitySymbol = "🚀" let numberObject = NSNumber(value: Double(42.0) / Double(0)) let formattedString = numberFormatter.string(from: numberObject) XCTAssertEqual(formattedString, "🚀") } func test_minusSignSymbol() { let numberFormatter = NumberFormatter() numberFormatter.minusSign = "👎" let formattedString = numberFormatter.string(from: -42) XCTAssertEqual(formattedString, "👎42") } func test_plusSignSymbol() { //FIXME: How do we show the plus sign from a NSNumberFormatter? // let numberFormatter = NumberFormatter() // numberFormatter.plusSign = "👍" // let formattedString = numberFormatter.stringFromNumber(42) // XCTAssertEqual(formattedString, "👍42") } func test_currencySymbol() { // Disabled due to [SR-250] /* let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .CurrencyStyle numberFormatter.currencySymbol = "🍯" numberFormatter.currencyDecimalSeparator = "_" let formattedString = numberFormatter.stringFromNumber(42) XCTAssertEqual(formattedString, "🍯 42_00") */ } func test_exponentSymbol() { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .scientific numberFormatter.exponentSymbol = "⬆️" let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "4.2⬆️1") } func test_minimumIntegerDigits() { let numberFormatter = NumberFormatter() numberFormatter.minimumIntegerDigits = 3 let formattedString = numberFormatter.string(from: 0) XCTAssertEqual(formattedString, "000") } func test_maximumIntegerDigits() { let numberFormatter = NumberFormatter() numberFormatter.maximumIntegerDigits = 3 let formattedString = numberFormatter.string(from: 1_000) XCTAssertEqual(formattedString, "000") } func test_minimumFractionDigits() { let numberFormatter = NumberFormatter() numberFormatter.minimumFractionDigits = 3 numberFormatter.decimalSeparator = "-" let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "42-000") } func test_maximumFractionDigits() { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = 3 numberFormatter.decimalSeparator = "-" let formattedString = numberFormatter.string(from: 42.4242) XCTAssertEqual(formattedString, "42-424") } func test_groupingSize() { let numberFormatter = NumberFormatter() numberFormatter.groupingSize = 4 numberFormatter.groupingSeparator = "_" numberFormatter.usesGroupingSeparator = true let formattedString = numberFormatter.string(from: 42_000) XCTAssertEqual(formattedString, "4_2000") } func test_secondaryGroupingSize() { let numberFormatter = NumberFormatter() numberFormatter.secondaryGroupingSize = 2 numberFormatter.groupingSeparator = "_" numberFormatter.usesGroupingSeparator = true let formattedString = numberFormatter.string(from: 42_000_000) XCTAssertEqual(formattedString, "4_20_00_000") } func test_roundingMode() { let numberFormatter = NumberFormatter() numberFormatter.maximumFractionDigits = 0 numberFormatter.roundingMode = .ceiling let formattedString = numberFormatter.string(from: 41.0001) XCTAssertEqual(formattedString, "42") } func test_roundingIncrement() { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.roundingIncrement = 0.2 let formattedString = numberFormatter.string(from: 4.25) XCTAssertEqual(formattedString, "4.2") } func test_formatWidth() { let numberFormatter = NumberFormatter() numberFormatter.paddingCharacter = "_" numberFormatter.formatWidth = 5 let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "___42") } func test_formatPosition() { let numberFormatter = NumberFormatter() numberFormatter.paddingCharacter = "_" numberFormatter.formatWidth = 5 numberFormatter.paddingPosition = .afterPrefix let formattedString = numberFormatter.string(from: -42) XCTAssertEqual(formattedString, "-__42") } func test_multiplier() { let numberFormatter = NumberFormatter() numberFormatter.multiplier = 2 let formattedString = numberFormatter.string(from: 21) XCTAssertEqual(formattedString, "42") } func test_positivePrefix() { let numberFormatter = NumberFormatter() numberFormatter.positivePrefix = "👍" let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "👍42") } func test_positiveSuffix() { let numberFormatter = NumberFormatter() numberFormatter.positiveSuffix = "👍" let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "42👍") } func test_negativePrefix() { let numberFormatter = NumberFormatter() numberFormatter.negativePrefix = "👎" let formattedString = numberFormatter.string(from: -42) XCTAssertEqual(formattedString, "👎42") } func test_negativeSuffix() { let numberFormatter = NumberFormatter() numberFormatter.negativeSuffix = "👎" let formattedString = numberFormatter.string(from: -42) XCTAssertEqual(formattedString, "-42👎") } func test_internationalCurrencySymbol() { // Disabled due to [SR-250] /* let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .CurrencyPluralStyle numberFormatter.internationalCurrencySymbol = "💵" numberFormatter.currencyDecimalSeparator = "_" let formattedString = numberFormatter.stringFromNumber(42) XCTAssertEqual(formattedString, "💵 42_00") */ } func test_currencyGroupingSeparator() { // Disabled due to [SR-250] /* let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .CurrencyStyle numberFormatter.currencyGroupingSeparator = "_" numberFormatter.currencyCode = "T" numberFormatter.currencyDecimalSeparator = "/" let formattedString = numberFormatter.stringFromNumber(42_000) XCTAssertEqual(formattedString, "T 42_000/00") */ } //FIXME: Something is wrong with numberFromString implementation, I don't know exactly why, but it's not working. func test_lenient() { // let numberFormatter = NumberFormatter() // numberFormatter.numberStyle = .CurrencyStyle // let nilNumberBeforeLenient = numberFormatter.numberFromString("42") // XCTAssertNil(nilNumberBeforeLenient) // numberFormatter.lenient = true // let numberAfterLenient = numberFormatter.numberFromString("42.42") // XCTAssertEqual(numberAfterLenient, 42.42) } func test_minimumSignificantDigits() { let numberFormatter = NumberFormatter() numberFormatter.usesSignificantDigits = true numberFormatter.minimumSignificantDigits = 3 let formattedString = numberFormatter.string(from: 42) XCTAssertEqual(formattedString, "42.0") } func test_maximumSignificantDigits() { let numberFormatter = NumberFormatter() numberFormatter.usesSignificantDigits = true numberFormatter.maximumSignificantDigits = 3 let formattedString = numberFormatter.string(from: 42.42424242) XCTAssertEqual(formattedString, "42.4") } func test_stringFor() { let numberFormatter = NumberFormatter() XCTAssertEqual(numberFormatter.string(for: 10)!, "10") XCTAssertEqual(numberFormatter.string(for: 3.14285714285714)!, "3") XCTAssertEqual(numberFormatter.string(for: true)!, "1") XCTAssertEqual(numberFormatter.string(for: false)!, "0") XCTAssertNil(numberFormatter.string(for: [1,2])) XCTAssertEqual(numberFormatter.string(for: NSNumber(value: 99.1))!, "99") XCTAssertNil(numberFormatter.string(for: "NaN")) XCTAssertNil(numberFormatter.string(for: NSString(string: "NaN"))) } }
apache-2.0
radex/swift-compiler-crashes
crashes-fuzzing/23071-swift-ide-printdeclusr.swift
11
233
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing if true{var f=""[1)let a{enum a{class B<T where h:d{class B<h:a
mit
TalkingBibles/Talking-Bible-iOS
TalkingBible/_Collection.swift
1
3128
// DO NOT EDIT. This file is machine-generated and constantly overwritten. // Make changes to Collection.swift instead. import CoreData enum CollectionAttributes: String { case collectionId = "collectionId" case copyright = "copyright" case englishName = "englishName" case position = "position" case version = "version" } enum CollectionRelationships: String { case books = "books" case language = "language" } @objc class _Collection: NSManagedObject { // MARK: - Class methods class func entityName () -> String { return "Collection" } class func entity(managedObjectContext: NSManagedObjectContext!) -> NSEntityDescription! { return NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: managedObjectContext); } // MARK: - Life cycle methods override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext!) { super.init(entity: entity, insertIntoManagedObjectContext: context) } convenience init(managedObjectContext: NSManagedObjectContext!) { let entity = _Collection.entity(managedObjectContext) self.init(entity: entity, insertIntoManagedObjectContext: managedObjectContext) } // MARK: - Properties @NSManaged var collectionId: String // func validateCollectionId(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} @NSManaged var copyright: String? // func validateCopyright(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} @NSManaged var englishName: String // func validateEnglishName(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} @NSManaged var position: NSNumber? // func validatePosition(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} @NSManaged var version: String? // func validateVersion(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} // MARK: - Relationships @NSManaged var books: NSOrderedSet @NSManaged var language: Language? // func validateLanguage(value: AutoreleasingUnsafePointer<AnyObject>, error: NSErrorPointer) {} } extension _Collection { func addBooks(objects: NSOrderedSet) { let mutable = self.books.mutableCopy() as! NSMutableOrderedSet mutable.unionOrderedSet(objects) self.books = mutable.copy() as! NSOrderedSet } func removeBooks(objects: NSOrderedSet) { let mutable = self.books.mutableCopy() as! NSMutableOrderedSet mutable.minusOrderedSet(objects) self.books = mutable.copy() as! NSOrderedSet } func addBooksObject(value: Book!) { let mutable = self.books.mutableCopy() as! NSMutableOrderedSet mutable.addObject(value) self.books = mutable.copy() as! NSOrderedSet } func removeBooksObject(value: Book!) { let mutable = self.books.mutableCopy() as! NSMutableOrderedSet mutable.removeObject(value) self.books = mutable.copy() as! NSOrderedSet } }
apache-2.0
jlandon/Alexandria
Sources/Alexandria/UIViewController+Extensions.swift
2
2714
// // UIViewController+Extensions.swift // // Created by Jonathan Landon on 4/15/15. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Oven Bits, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension UIViewController { /// Retrieve the view controller currently on-screen /// /// Based off code here: http://stackoverflow.com/questions/24825123/get-the-current-view-controller-from-the-app-delegate @available(iOSApplicationExtension, unavailable) public static var current: UIViewController? { if let controller = UIApplication.shared.keyWindow?.rootViewController { return findCurrent(controller) } return nil } private static func findCurrent(_ controller: UIViewController) -> UIViewController { if let controller = controller.presentedViewController { return findCurrent(controller) } else if let controller = controller as? UISplitViewController, let lastViewController = controller.viewControllers.first, controller.viewControllers.count > 0 { return findCurrent(lastViewController) } else if let controller = controller as? UINavigationController, let topViewController = controller.topViewController, controller.viewControllers.count > 0 { return findCurrent(topViewController) } else if let controller = controller as? UITabBarController, let selectedViewController = controller.selectedViewController, (controller.viewControllers?.count ?? 0) > 0 { return findCurrent(selectedViewController) } else { return controller } } }
mit