repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
dnevera/IMProcessing
IMProcessing/Classes/Convolutions/IMPIIRGaussianBlurFilter.swift
1
9892
// // IMPIIRFilter.swift // IMProcessing // // Created by denis svinarchuk on 15.01.16. // Copyright © 2016 Dehancer.photo. All rights reserved. // import Accelerate import simd public class IMPIIRGaussianBlurFilter: IMPFilter { public var radius:Int!{ didSet{ update() dirty = true } } public required init(context: IMPContext) { super.init(context: context) kernel_iirFilterHorizontal = IMPFunction(context: context, name: "kernel_iirFilterHorizontal") kernel_iirFilterVertical = IMPFunction(context: context, name: "kernel_iirFilterVertical") defer{ radius = 0 } } override public func apply() -> IMPImageProvider { if radius <= 1 { return super.apply() } if dirty { if let t = source?.texture{ executeSourceObservers(source) let inputTexture:MTLTexture! = self.source!.texture let width = inputTexture.width let height = inputTexture.height let threadgroupCounts = MTLSizeMake(1, 1, 1); let threadgroupsX = MTLSizeMake(1, t.height,1); let threadgroupsY = MTLSizeMake(t.width,1,1); if self._destination.texture?.width != width || self._destination.texture?.height != height { let descriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( inputTexture.pixelFormat, width: width, height: height, mipmapped: false) self._destination.texture = self.context.device.newTextureWithDescriptor(descriptor) } let forwardWidth = width+radius*3 let forwardHeight = height+radius*3 let length = forwardWidth * forwardHeight * 4 * sizeof(Float) if self.inoutBuffer?.length != length { self.inoutBuffer = context.device.newBufferWithLength(length, options: .CPUCacheModeDefaultCache) } if self.inoutBuffer2?.length != length { self.inoutBuffer2 = context.device.newBufferWithLength(length, options: .CPUCacheModeDefaultCache) } self.bsizeBuffer = self.bsizeBuffer ?? self.context.device.newBufferWithLength(sizeof(int2), options: .CPUCacheModeDefaultCache) var bsize:int2 = int2(Int32(forwardWidth),Int32(forwardHeight)) memcpy(self.bsizeBuffer!.contents(), &bsize, self.bsizeBuffer!.length) context.execute{ (commandBuffer) -> Void in // // horizontal stage // var blitEncoder = commandBuffer.blitCommandEncoder() blitEncoder.fillBuffer(self.inoutBuffer!, range: NSRange(location: 0, length: self.inoutBuffer!.length), value: 0) blitEncoder.fillBuffer(self.inoutBuffer2!,range: NSRange(location: 0, length:self.inoutBuffer2!.length), value: 0) blitEncoder.endEncoding() var commandEncoder = commandBuffer.computeCommandEncoder() commandEncoder.setComputePipelineState(self.kernel_iirFilterHorizontal.pipeline!) commandEncoder.setTexture(inputTexture, atIndex: 0) commandEncoder.setTexture(self._destination.texture, atIndex: 1) commandEncoder.setTexture(self.bTexture, atIndex: 2) commandEncoder.setTexture(self.aTexture, atIndex: 3) commandEncoder.setBuffer(self.inoutBuffer, offset: 0, atIndex: 0) commandEncoder.setBuffer(self.inoutBuffer2, offset: 0, atIndex: 1) commandEncoder.setBuffer(self.bsizeBuffer, offset: 0, atIndex: 2) commandEncoder.setBuffer(self.radiusBuffer, offset: 0, atIndex: 3) commandEncoder.dispatchThreadgroups(threadgroupsX, threadsPerThreadgroup:threadgroupCounts) commandEncoder.endEncoding() // // vertical stage // blitEncoder = commandBuffer.blitCommandEncoder() blitEncoder.fillBuffer(self.inoutBuffer!, range: NSRange(location: 0, length: self.inoutBuffer!.length), value: 0) blitEncoder.fillBuffer(self.inoutBuffer2!,range: NSRange(location: 0, length:self.inoutBuffer2!.length), value: 0) blitEncoder.endEncoding() commandEncoder = commandBuffer.computeCommandEncoder() commandEncoder.setComputePipelineState(self.kernel_iirFilterVertical.pipeline!) commandEncoder.setTexture(self._destination.texture, atIndex: 0) commandEncoder.setTexture(self._destination.texture, atIndex: 1) commandEncoder.setTexture(self.bTexture, atIndex: 2) commandEncoder.setTexture(self.aTexture, atIndex: 3) commandEncoder.setBuffer(self.inoutBuffer, offset: 0, atIndex: 0) commandEncoder.setBuffer(self.inoutBuffer2, offset: 0, atIndex: 1) commandEncoder.setBuffer(self.bsizeBuffer, offset: 0, atIndex: 2) commandEncoder.setBuffer(self.radiusBuffer, offset: 0, atIndex: 3) commandEncoder.dispatchThreadgroups(threadgroupsY, threadsPerThreadgroup:threadgroupCounts) commandEncoder.endEncoding() } executeDestinationObservers(_destination) } } dirty = false return _destination } lazy var _destination:IMPImageProvider = { return IMPImageProvider(context: self.context) }() // private var destinationContainer:IMPImageProvider? // // internal func getDestination() -> IMPImageProvider? { // if !enabled{ // return source // } // if let t = self.texture{ // if let d = destinationContainer{ // d.texture=t // } // else{ // destinationContainer = IMPImageProvider(context: self.context, texture: t) // } // } // return destinationContainer // } func update(){ if radius>1{ radiusBuffer = radiusBuffer ?? context.device.newBufferWithLength(sizeofValue(radius), options: .CPUCacheModeDefaultCache) memcpy(radiusBuffer.contents(), &radius, radiusBuffer.length) let (b,a) = radius.float.iirGaussianCoefficients bTexture = context.device.texture1D(b) aTexture = context.device.texture1D(a) } } private var kernel_iirFilterHorizontal:IMPFunction! private var kernel_iirFilterVertical:IMPFunction! private var radiusBuffer:MTLBuffer! private var inoutBuffer :MTLBuffer? private var inoutBuffer2:MTLBuffer? //private var texture :MTLTexture? private var bsizeBuffer:MTLBuffer? var bTexture:MTLTexture! var aTexture:MTLTexture! } public extension Float { public var iirGaussianCoefficients: (b:[Float],a:[Float]) { get { // // https://www.researchgate.net/publication/222453003_Recursive_implementation_of_the_Gaussian_filter // var q = self if 0.5 <= self && self <= 2.5 { q = 3.97156 - 4.14554 * sqrt(1.0 - 0.26891*self) } else if self > 2.5 { q = 0.98711 * self - 0.96330 } let q2 = pow(q, 2) let q3 = pow(q, 3) let a0 = 1.57825 + (2.44413 * q) + (1.4281 * q2) + (0.422205 * q3) let a1 = (2.44413 * q) + (2.85619 * q2) + (1.26661 * q3) let a2 = (-1.4281 * q2) + (-1.26661 * q3) let a3 = (0.422205 * q3) let b = [1 - ((a1 + a2 + a3) / a0)] let a = [a0, a1, a2, a3] / a0 return (b,a) } } public var iirGaussianCoefficients2: (b:[Float],a:[Float]) { // // http://habrahabr.ru/post/151157/ // let q = self var q4 = pow(self,2); q4 = 1.0/pow(q4,2) let coef_A = q4*(q*(q*(q*1.1442707+0.0130625)-0.7500910)+0.2546730) let coef_W = q4*(q*(q*(q*1.3642870+0.0088755)-0.3255340)+0.3016210) let coef_B = q4*(q*(q*(q*1.2397166-0.0001644)-0.6363580)-0.0536068) let z0 = exp(coef_A) let z0_real = z0 * cos(coef_W) let z2 = exp(coef_B) let z02 = pow(z0, 2) let a2 = 1.0 / (z2 * z02) let a0 = (z02 + 2*z0_real * z2) * a2 let a1 = -(2*z0_real + z2) * a2 let b0 = 1.0 - (a0 + a1 + a2) return ([b0],[1, a0,a1,a2]) }; } public func / (left:[Float],right:Float) -> [Float] { var ret = [Float](count: left.count, repeatedValue: 0) var denom = right vDSP_vsdiv(left, 1, &denom, &ret, 1, vDSP_Length(ret.count)) return ret } public func * (left:[Float],right:Float) -> [Float] { var ret = [Float](count: left.count, repeatedValue: 0) var denom = right vDSP_vsmul(left, 1, &denom, &ret, 1, vDSP_Length(ret.count)) return ret }
mit
0870112702e10e5cab47c189eaabe5e0
38.25
144
0.542412
4.363035
false
false
false
false
fabiomassimo/eidolon
Kiosk/Admin/AuctionWebViewController.swift
1
900
import UIKit class AuctionWebViewController: WebViewController { override func viewDidLoad() { super.viewDidLoad() let toolbarButtons = self.toolbarItems let flexibleSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: "") let exitImage = UIImage(named: "toolbar_close") let backwardBarItem = UIBarButtonItem(image: exitImage, style: .Plain, target: self, action: "exit"); let allItems = self.toolbarItems! + [flexibleSpace, backwardBarItem] as [AnyObject] toolbarItems = allItems } func exit() { let passwordVC = PasswordAlertViewController.alertView { [weak self] () -> () in self?.navigationController?.popViewControllerAnimated(true) return } self.presentViewController(passwordVC, animated: true) {} } }
mit
86da8d00a732f8e2776e79add2937154
36.5
126
0.666667
5.389222
false
false
false
false
ghotjunwoo/Tiat
AppDelegate.swift
1
4120
// // AppDelegate.swift // Tiat // // Created by JWPC1 on 2016. 8. 1.. // Copyright © 2016년 JW. All rights reserved. // import UIKit import UserNotifications import Firebase import FirebaseInstanceID import FirebaseMessaging @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var appToken: String? var window: UIWindow? override init() { FIRApp.configure() FIRDatabase.database().persistenceEnabled = true } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { if #available(iOS 10.0, *) { let authOptions : UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_,_ in }) // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self // For iOS 10 data message (sent via FCM) FIRMessaging.messaging().remoteMessageDelegate = self } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() // [END register_for_notifications] // Add observer for InstanceID token refresh callback. NotificationCenter.default.addObserver(self, selector: #selector(self.tokenRefreshNotification), name: NSNotification.Name.firInstanceIDTokenRefresh, object: nil) func applicationDidBecomeActive(_ application: UIApplication) { connectToFcm() } // [START disconnect_from_fcm] return true } // [START receive_message] func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { print("%@", userInfo) } func tokenRefreshNotification(notification: NSNotification) { if let refreshedToken = FIRInstanceID.instanceID().token() { print("InstanceID token: \(refreshedToken)") appToken = refreshedToken } connectToFcm() } // [END refresh_token] // [START connect_to_fcm] func connectToFcm() { FIRMessaging.messaging().connect { (error) in if (error != nil) { print("Unable to connect with FCM. \(error?.localizedDescription)") } else { print("Connected to FCM.") } } } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("!!!!!!!!!" + deviceToken.description) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("sd" + error.localizedDescription) } // [END connect_to_fcm] // [END disconnect_from_fcm] } // [START ios_10_message_handling] @available(iOS 10, *) extension AppDelegate : UNUserNotificationCenterDelegate { // Receive displayed notifications for iOS 10 devices. private func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo // Print message ID. print("Message ID: \(userInfo["gcm.message_id"]!)") // Print full message. print("%@", userInfo) } } extension AppDelegate : FIRMessagingDelegate { // Receive data message on iOS 10 devices. func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) { print("%@", remoteMessage.appData) } }
gpl-3.0
fd7c2102b24d40a625591745a027e241
33.024793
170
0.640272
5.504011
false
false
false
false
vmanot/swift-package-manager
Sources/Build/ToolProtocol.swift
1
5032
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import PackageModel import Utility /// Describes a tool which can be understood by llbuild's BuildSystem library. protocol ToolProtocol { /// The list of inputs to declare. var inputs: [String] { get } /// The list of outputs to declare. var outputs: [String] { get } /// Write a description of the tool to the given output `stream`. /// /// This should append JSON or YAML content; if it is YAML it should be indented by 4 spaces. func append(to stream: OutputByteStream) } struct PhonyTool: ToolProtocol { let inputs: [String] let outputs: [String] func append(to stream: OutputByteStream) { stream <<< " tool: phony\n" stream <<< " inputs: " <<< Format.asJSON(inputs) <<< "\n" stream <<< " outputs: " <<< Format.asJSON(outputs) <<< "\n" } } struct ShellTool: ToolProtocol { let description: String let inputs: [String] let outputs: [String] let args: [String] func append(to stream: OutputByteStream) { stream <<< " tool: shell\n" stream <<< " description: " <<< Format.asJSON(description) <<< "\n" stream <<< " inputs: " <<< Format.asJSON(inputs) <<< "\n" stream <<< " outputs: " <<< Format.asJSON(outputs) <<< "\n" // If one argument is specified we assume pre-escaped and have llbuild // execute it passed through to the shell. if let arg = self.args.only { stream <<< " args: " <<< Format.asJSON(arg) <<< "\n" } else { stream <<< " args: " <<< Format.asJSON(args) <<< "\n" } } } struct ClangTool: ToolProtocol { let desc: String let inputs: [String] let outputs: [String] let args: [String] let deps: String? func append(to stream: OutputByteStream) { stream <<< " tool: clang\n" stream <<< " description: " <<< Format.asJSON(desc) <<< "\n" stream <<< " inputs: " <<< Format.asJSON(inputs) <<< "\n" stream <<< " outputs: " <<< Format.asJSON(outputs) <<< "\n" stream <<< " args: " <<< Format.asJSON(args) <<< "\n" if let deps = deps { stream <<< " deps: " <<< Format.asJSON(deps) <<< "\n" } } } struct ArchiveTool: ToolProtocol { let inputs: [String] let outputs: [String] func append(to stream: OutputByteStream) { stream <<< " tool: archive\n" stream <<< " inputs: " <<< Format.asJSON(inputs) <<< "\n" stream <<< " outputs: " <<< Format.asJSON(outputs) <<< "\n" } } /// Swift compiler llbuild tool. struct SwiftCompilerTool: ToolProtocol { /// Inputs to the tool. let inputs: [String] /// Outputs produced by the tool. var outputs: [String] { return target.objects.map({ $0.asString }) + [target.moduleOutputPath.asString] } /// The underlying Swift build target. let target: SwiftTargetDescription static let numThreads = 8 init(target: SwiftTargetDescription, inputs: [String]) { self.target = target self.inputs = inputs } func append(to stream: OutputByteStream) { stream <<< " tool: swift-compiler\n" stream <<< " executable: " <<< Format.asJSON(target.buildParameters.toolchain.swiftCompiler.asString) <<< "\n" stream <<< " module-name: " <<< Format.asJSON(target.target.c99name) <<< "\n" stream <<< " module-output-path: " <<< Format.asJSON(target.moduleOutputPath.asString) <<< "\n" stream <<< " inputs: " <<< Format.asJSON(inputs) <<< "\n" stream <<< " outputs: " <<< Format.asJSON(outputs) <<< "\n" stream <<< " import-paths: " <<< Format.asJSON([target.buildParameters.buildPath.asString]) <<< "\n" stream <<< " temps-path: " <<< Format.asJSON(target.tempsPath.asString) <<< "\n" stream <<< " objects: " <<< Format.asJSON(target.objects.map({ $0.asString })) <<< "\n" stream <<< " other-args: " <<< Format.asJSON(target.compileArguments()) <<< "\n" stream <<< " sources: " <<< Format.asJSON(target.target.sources.paths.map({ $0.asString })) <<< "\n" stream <<< " is-library: " <<< Format.asJSON(target.target.type == .library || target.target.type == .test) <<< "\n" stream <<< " enable-whole-module-optimization: " <<< Format.asJSON(target.buildParameters.configuration == .release) <<< "\n" stream <<< " num-threads: " <<< Format.asJSON("\(SwiftCompilerTool.numThreads)") <<< "\n" } }
apache-2.0
b293f8daf496f17fa78780a7a11cca8b
34.43662
101
0.565779
4.012759
false
false
false
false
mownier/photostream
Photostream/Utils/Handlers/ScrollHandler.swift
1
2763
// // ScrollHandler.swift // Photostream // // Created by Mounir Ybanez on 01/11/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit protocol ScrollEventListener: class { func didScrollUp(with delta: CGFloat, offsetY: CGFloat) func didScrollDown(with delta: CGFloat, offsetY: CGFloat) } enum ScrollDirection { case none case down case up } struct ScrollHandler { weak var scrollView: UIScrollView? var offsetY: CGFloat = 0.0 var offsetDelta: CGFloat { return abs(offsetY) - abs(currentOffsetY) } var isScrollable: Bool { guard scrollView != nil else { return false } return scrollView!.contentSize.height > scrollView!.height - scrollView!.contentInset.top } var currentOffsetY: CGFloat { guard scrollView != nil else { return 0.0 } return scrollView!.contentOffset.y } var isScrollingUp: Bool { guard scrollView != nil else { return false } let con1 = offsetY > currentOffsetY let con2 = offsetY < (scrollView!.contentSize.height - scrollView!.height) return con1 && con2 } var isScrollingDown: Bool { guard scrollView != nil else { return false } let con1 = offsetY < currentOffsetY let con2 = currentOffsetY > -(scrollView!.contentInset.top + scrollView!.contentInset.bottom) return con1 && con2 } var maximumOffsetY: CGFloat { guard scrollView != nil else { return 0 } return scrollView!.contentSize.height - scrollView!.frame.height } var percentageOffsetY: CGFloat { guard scrollView != nil else { return 0 } let offset = scrollView!.contentOffset.y + scrollView!.contentInset.top let percentage = min(abs(offset / maximumOffsetY), 1.0) return offset > 0 ? percentage : 0 } var isBottomReached: Bool { guard scrollView != nil else { return false } return currentOffsetY + scrollView!.frame.height >= scrollView!.contentSize.height } var direction: ScrollDirection { if isScrollingDown { return .down } else if isScrollingUp { return .up } return .none } mutating func update() { offsetY = currentOffsetY } func killScroll() { guard scrollView != nil else { return } scrollView!.setContentOffset(scrollView!.contentOffset, animated: false) } }
mit
4fd1162207c41612672db8b3b2bddab6
22.810345
101
0.570239
5.172285
false
false
false
false
malt03/DebugHead
DebugHead/Classes/DebugMenuTableViewController.swift
1
2395
// // DebugMenuTableViewController.swift // Pods // // Created by Koji Murata on 2016/05/27. // // import UIKit final class DebugMenuTableViewController: UITableViewController { @IBAction func close() { DebugHead.shared.close() } func prepare(_ m: [DebugMenu], _ fv: UIView?) { menus = m footerView = fv } private var menus = [DebugMenu]() private var footerView: UIView? override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.barTintColor = .darkGray navigationController?.navigationBar.tintColor = .white navigationController?.navigationBar.titleTextAttributes = [ NSAttributedString.Key.foregroundColor: UIColor.white ] } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menus.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "default", for: indexPath) let menuClass = menus[indexPath.row] cell.textLabel?.textColor = UIColor.fromDangerLevel(menuClass.debugMenuDangerLevel) cell.textLabel?.text = menuClass.debugMenuTitle cell.accessoryType = menuClass.debugMenuAccessoryType return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let vc = menus[indexPath.row].debugMenuSelected(DebugHead.shared.debugHeadWindow!, tableViewController: self, indexPath: indexPath) else { tableView.deselectRow(at: indexPath, animated: true) return } navigationController?.pushViewController(vc, animated: true) } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return footerView?.frame.height ?? 0 } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return footerView } } extension UIColor { static func fromDangerLevel(_ level: DebugMenuDangerLevel) -> UIColor { switch level { case .none: return .black case .low: return UIColor(red: 0, green: 0.3843, blue: 0.1451, alpha: 1) case .high: return UIColor(red: 0.9961, green: 0.8078, blue: 0, alpha: 1) case .extreme: return UIColor(red: 0.7490, green: 0.1922, blue: 0.1059, alpha: 1) } } }
mit
05b720862f49edea31d8f60bb21ebe90
32.263889
148
0.714405
4.418819
false
false
false
false
mbeloded/beaconDemo
PassKitApp/PassKitApp/Classes/UI/MainMenu/MainCell/MainCollectionViewCell.swift
1
1191
// // MainCollectionViewCell.swift // PassKitApp // // Created by Alexandr Chernyy on 10/3/14. // Copyright (c) 2014 Alexandr Chernyy. All rights reserved. // import UIKit class MainCollectionViewCell: UICollectionViewCell { @IBOutlet weak var nameLabel: UILabel! { didSet { println(nameLabel.text) } } @IBOutlet weak var imageView: PFImageView! var category:CategoryModel! { didSet { nameLabel.text = category.name var url:NSString = category.icon! var pngPath:NSString = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(url.lastPathComponent)"); imageView.image = UIImage(named: pngPath) imageView.backgroundColor = UIColor.blackColor() imageView.layer.cornerRadius = imageView.frame.size.width/2; } } override func drawRect(rect: CGRect) { imageView.frame = CGRectMake(0, 0, self.frame.size.width/1.5, self.frame.size.width/1.5) imageView.center = CGPointMake(self.frame.size.width/2, self.frame.size.height/2.8) imageView.layer.cornerRadius = imageView.frame.size.width/2; } }
gpl-2.0
5d4e7477df8ccfa3fd7b0c0212e03e42
31.189189
124
0.649034
4.330909
false
false
false
false
firebase/firebase-ios-sdk
FirebaseFunctions/Sources/FunctionsError.swift
1
8266
// Copyright 2022 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 Foundation /// The error domain for codes in the `FunctionsErrorCode` enum. public let FunctionsErrorDomain: String = "com.firebase.functions" /// The key for finding error details in the `NSError` userInfo. public let FunctionsErrorDetailsKey: String = "details" /** * The set of error status codes that can be returned from a Callable HTTPS tigger. These are the * canonical error codes for Google APIs, as documented here: * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto#L26 */ @objc(FIRFunctionsErrorCode) public enum FunctionsErrorCode: Int { /** The operation completed successfully. */ case OK = 0 /** The operation was cancelled (typically by the caller). */ case cancelled = 1 /** Unknown error or an error from a different error domain. */ case unknown = 2 /** * Client specified an invalid argument. Note that this differs from `FailedPrecondition`. * `InvalidArgument` indicates arguments that are problematic regardless of the state of the * system (e.g., an invalid field name). */ case invalidArgument = 3 /** * Deadline expired before operation could complete. For operations that change the state of the * system, this error may be returned even if the operation has completed successfully. For * example, a successful response from a server could have been delayed long enough for the * deadline to expire. */ case deadlineExceeded = 4 /** Some requested document was not found. */ case notFound = 5 /** Some document that we attempted to create already exists. */ case alreadyExists = 6 /** The caller does not have permission to execute the specified operation. */ case permissionDenied = 7 /** * Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system * is out of space. */ case resourceExhausted = 8 /** * Operation was rejected because the system is not in a state required for the operation's * execution. */ case failedPrecondition = 9 /** * The operation was aborted, typically due to a concurrency issue like transaction aborts, etc. */ case aborted = 10 /** Operation was attempted past the valid range. */ case outOfRange = 11 /** Operation is not implemented or not supported/enabled. */ case unimplemented = 12 /** * Internal errors. Means some invariant expected by underlying system has been broken. If you * see one of these errors, something is very broken. */ case `internal` = 13 /** * The service is currently unavailable. This is a most likely a transient condition and may be * corrected by retrying with a backoff. */ case unavailable = 14 /** Unrecoverable data loss or corruption. */ case dataLoss = 15 /** The request does not have valid authentication credentials for the operation. */ case unauthenticated = 16 } /** * Takes an HTTP status code and returns the corresponding `FIRFunctionsErrorCode` error code. * This is the standard HTTP status code -> error mapping defined in: * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto * - Parameter status An HTTP status code. * - Returns: The corresponding error code, or `FIRFunctionsErrorCodeUnknown` if none. */ internal func FunctionsCodeForHTTPStatus(_ status: NSInteger) -> FunctionsErrorCode { switch status { case 200: return .OK case 400: return .invalidArgument case 401: return .unauthenticated case 403: return .permissionDenied case 404: return .notFound case 409: return .alreadyExists case 429: return .resourceExhausted case 499: return .cancelled case 500: return .internal case 501: return .unimplemented case 503: return .unavailable case 504: return .deadlineExceeded default: return .internal } } extension FunctionsErrorCode { static func errorCode(forName name: String) -> FunctionsErrorCode { switch name { case "OK": return .OK case "CANCELLED": return .cancelled case "UNKNOWN": return .unknown case "INVALID_ARGUMENT": return .invalidArgument case "DEADLINE_EXCEEDED": return .deadlineExceeded case "NOT_FOUND": return .notFound case "ALREADY_EXISTS": return .alreadyExists case "PERMISSION_DENIED": return .permissionDenied case "RESOURCE_EXHAUSTED": return .resourceExhausted case "FAILED_PRECONDITION": return .failedPrecondition case "ABORTED": return .aborted case "OUT_OF_RANGE": return .outOfRange case "UNIMPLEMENTED": return .unimplemented case "INTERNAL": return .internal case "UNAVAILABLE": return .unavailable case "DATA_LOSS": return .dataLoss case "UNAUTHENTICATED": return .unauthenticated default: return .internal } } var descriptionForErrorCode: String { switch self { case .OK: return "OK" case .cancelled: return "CANCELLED" case .unknown: return "UNKNOWN" case .invalidArgument: return "INVALID ARGUMENT" case .deadlineExceeded: return "DEADLINE EXCEEDED" case .notFound: return "NOT FOUND" case .alreadyExists: return "ALREADY EXISTS" case .permissionDenied: return "PERMISSION DENIED" case .resourceExhausted: return "RESOURCE EXHAUSTED" case .failedPrecondition: return "FAILED PRECONDITION" case .aborted: return "ABORTED" case .outOfRange: return "OUT OF RANGE" case .unimplemented: return "UNIMPLEMENTED" case .internal: return "INTERNAL" case .unavailable: return "UNAVAILABLE" case .dataLoss: return "DATA LOSS" case .unauthenticated: return "UNAUTHENTICATED" } } func generatedError(userInfo: [String: Any]? = nil) -> NSError { return NSError(domain: FunctionsErrorDomain, code: rawValue, userInfo: userInfo ?? [NSLocalizedDescriptionKey: descriptionForErrorCode]) } } internal func FunctionsErrorForResponse(status: NSInteger, body: Data?, serializer: FUNSerializer) -> NSError? { // Start with reasonable defaults from the status code. var code = FunctionsCodeForHTTPStatus(status) var description = code.descriptionForErrorCode var details: AnyObject? // Then look through the body for explicit details. if let body = body, let json = try? JSONSerialization.jsonObject(with: body) as? NSDictionary, let errorDetails = json["error"] as? NSDictionary { if let status = errorDetails["status"] as? String { code = FunctionsErrorCode.errorCode(forName: status) // If the code in the body is invalid, treat the whole response as malformed. guard code != .internal else { return code.generatedError(userInfo: nil) } } if let message = errorDetails["message"] as? String { description = message } else { description = code.descriptionForErrorCode } details = errorDetails["details"] as AnyObject? if let innerDetails = details { // Just ignore the details if there an error decoding them. details = try? serializer.decode(innerDetails) } } if code == .OK { // Technically, there's an edge case where a developer could explicitly return an error code of // OK, and we will treat it as success, but that seems reasonable. return nil } var userInfo = [String: Any]() userInfo[NSLocalizedDescriptionKey] = description if let details = details { userInfo[FunctionsErrorDetailsKey] = details } return code.generatedError(userInfo: userInfo) }
apache-2.0
b7a7e7c43e5a374ac4f8ddbd7b552886
30.915058
99
0.69683
4.541758
false
false
false
false
Zewo/Zewo
Sources/IO/TCPHost.swift
2
1705
#if os(Linux) import Glibc #else import Darwin.C #endif import Venice import Core import CLibdill // TODO: Create TCP errors public enum TCPError : Error {} public final class TCPHost : Host { private typealias Handle = Int32 private let handle: Handle public let ip: IP private init(handle: Handle, ip: IP) { self.handle = handle self.ip = ip } deinit { hclose(handle) } public convenience init(ip: IP, backlog: Int, reusePort: Bool) throws { var address = ip.address let result = tcp_listen(&address, Int32(backlog)) // TODO: Set reusePort guard result != -1 else { switch errno { default: throw SystemError.lastOperationError } } self.init(handle: result, ip: ip) } public convenience init( host: String = "", port: Int = 8080, backlog: Int = 128, reusePort: Bool = false ) throws { let ip: IP if host == "" { ip = try IP(port: port) } else { ip = try IP(local: host, port: port) } try self.init(ip: ip, backlog: backlog, reusePort: reusePort) } public func accept(deadline: Deadline) throws -> DuplexStream { var address = ipaddr() let result = tcp_accept(handle, &address, deadline.value) guard result != -1 else { switch errno { default: throw SystemError.lastOperationError } } return TCPStream(handle: result, ip: IP(address: &address), open: true) } }
mit
d4ceb4ec23c1a04b143c633b9208c248
21.733333
79
0.533138
4.338422
false
false
false
false
hdinhof1/CheckSplit
CheckSplit/ViewController.swift
1
11186
// // ViewController.swift // CheckSplit // // Created by Henry Dinhofer on 12/22/16. // Copyright © 2016 Henry Dinhofer. All rights reserved. // import UIKit import Crashlytics // instead of reloadTable() look into func insertRows(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate { @IBOutlet weak var foodPeopleToggle: UISegmentedControl! @IBOutlet weak var itemTableView: UITableView! @IBOutlet weak var itemTextView: UITextView! @IBOutlet weak var priceTextView: UITextView! let store = MealDataStore.sharedInstance var lastSelectedIndexPath : IndexPath? override func viewDidLoad() { super.viewDidLoad() itemTableView.delegate = self itemTableView.dataSource = self itemTableView.allowsSelection = true priceTextView.accessibilityIdentifier = "Price" itemTextView.accessibilityIdentifier = "Item" priceTextView.delegate = self itemTextView.delegate = self print("Toggle is currently \(foodPeopleToggle.selectedSegmentIndex)") //Crashlytics force crash button let button = UIButton(type: .roundedRect) button.frame = CGRect(x: 20, y: 50, width: 100, height: 30) button.setTitle("Crash", for: .normal) button.addTarget(self, action: #selector(self.crashButtonTapped(sender:)), for: .touchUpInside) view.addSubview(button) // Do any additional setup after loading the view, typically from a nib. } @IBAction func crashButtonTapped(sender: AnyObject) { Crashlytics.sharedInstance().crash() } override func viewWillAppear(_ animated: Bool) { if let indexPath = itemTableView.indexPathForSelectedRow { itemTableView.deselectRow(at: indexPath, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: IBActions @IBAction func toggleTapped(_ sender: Any) { let toggleTitle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) ?? "" priceTextView.isHidden = toggleTitle == "People" ? true : false itemTextView.text = toggleTitle == "Food" ? "Enter food name" : "Enter person's name" priceTextView.text = "Price" itemTableView.reloadData() } @IBAction func resetTapped(_ sender: Any) { store.clear() itemTableView.reloadData() } @IBAction func editTapped(_ sender: Any) { if itemTableView.isEditing { itemTableView.setEditing(false, animated: true) } else { itemTableView.setEditing(true, animated: true) } } @IBAction func addItemTapped(_ sender: Any) { let name = itemTextView.text ?? "" let priceText = priceTextView.text ?? "" let toggleTitle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) ?? "" var badInfoEntered : Bool = false var price : Double = 0 if name == "" || name == "Enter food name" { badInfoEntered = true } if toggleTitle != "People" { if priceText == "" || priceText == "Price" { badInfoEntered = true } if Double(priceText) == nil { badInfoEntered = true } else { price = Double(priceText)! } } guard badInfoEntered == false else { let controller = UIAlertController(title: "Error", message: "Incorrect information entered", preferredStyle: .alert) controller.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) self.present(controller, animated: true, completion: nil) return } switch toggleTitle { case "Food": store.add(item: Food(name: name, cost: price)) case "Drinks": store.add(item: Drink(name: name, cost: price)) case "People": store.add(item: Person(name: name)) default: fatalError("Couldn't add item to store") } // reset views itemTextView.text = "" priceTextView.text = "Price" self.tabBarController?.tabBar.items?.first?.badgeValue = "\(store.patrons.count)" itemTableView.reloadData() itemTextView.becomeFirstResponder() } // MARK: - Tableview data source func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var numberOfRows : Int = 0 let toggleTitle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) ?? "Error" switch toggleTitle { case "Food": numberOfRows = store.food.count case "People": numberOfRows = store.patrons.count case "Drinks": numberOfRows = store.drinks.count default: fatalError("Number of Rows couldn't be deciphered!") } return numberOfRows } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = itemTableView.dequeueReusableCell(withIdentifier: "itemCell"), let toggleTitle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) else { return UITableViewCell() } let row = indexPath.row let label : String switch toggleTitle { case "Food": label = store.food[row].description case "People": label = "\(store.patrons[row].name) $\(store.patrons[row].totalTally)" case "Drinks": label = store.drinks[row].description default: fatalError("Number of Rows couldn't be deciphered!") } cell.textLabel?.text = label return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) } // MARK: - Tableview delegate func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let toggleTitle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex), let cell = itemTableView.cellForRow(at: indexPath), let text = cell.textLabel?.text, lastSelectedIndexPath?.row != indexPath.row else { itemTableView.deselectRow(at: indexPath, animated: true) lastSelectedIndexPath = nil return } lastSelectedIndexPath = indexPath // if lastSelectedIndexPath?.row == indexPath.row { // itemTableView.deselectRow(at: indexPath, animated: true) // lastSelectedIndexPath = nil // } // else { lastSelectedIndexPath = indexPath } var itemComponents : [String] if toggleTitle == "People" { itemComponents = text.components(separatedBy: " $") } else { itemComponents = text.components(separatedBy: " - ") } itemTextView.text = itemComponents[0] priceTextView.text = itemComponents[1] /* let controller = UIAlertController(title: "Edit", message: nil, preferredStyle: .alert) let save = UIAlertAction(title: "Save", style: .default) { (action) in // hit save let nameTextField = controller.textFields![0] as UITextField let priceTextField = controller.textFields![1] as UITextField let newName = nameTextField.text ?? "Error" let newPriceText = priceTextField.text ?? "0.0" let newPrice = Double(newPriceText) ?? 0.0 if toggleTitle == "People" { let person = self.store.patrons[indexPath.row] person.name = newName self.store.patrons[indexPath.row] = person } else { let food = self.store.food[indexPath.row] food.name = newName food.cost = newPrice self.store.food[indexPath.row] = food } self.itemTableView.reloadData() } let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) controller.addTextField { (textField : UITextField) in textField.placeholder = "Enter food name" } controller.addTextField { (textField : UITextField) in textField.placeholder = "Price" } controller.addAction(save) controller.addAction(cancel) self.present(controller, animated: true, completion: nil) */ } // MARK: - Textview delegate func textViewDidBeginEditing(_ textView: UITextView) { guard let identifier = textView.accessibilityIdentifier else { return } if identifier == "Item" { if itemTextView.text == "Enter food name" || itemTextView.text == "Enter person's name" { itemTextView.text = "" } if priceTextView.text == "" { priceTextView.text = "Price" } } else if identifier == "Price" { if priceTextView.text == "Price" { priceTextView.text = "" } if itemTextView.text == "" { itemTextView.text = "Enter food name" } } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let toggle = foodPeopleToggle.titleForSegment(at: foodPeopleToggle.selectedSegmentIndex) else { return false } if text == "\n", let indexPath = itemTableView.indexPathForSelectedRow { let name = itemTextView.text ?? "Error" let price = Double(priceTextView.text) ?? 0 if toggle == "People" { let person = self.store.patrons[indexPath.row] person.name = name self.store.patrons[indexPath.row] = person } else { let food = self.store.food[indexPath.row] food.name = name food.cost = price self.store.food[indexPath.row] = food } self.view.endEditing(true) itemTableView.reloadRows(at: [indexPath], with: .automatic) return false } if text == "\n" { if itemTextView.text == "" { itemTextView.text = "Enter food name" } self.view.endEditing(true) return false } return true } }
apache-2.0
270c9356c8950061527716e604f5184e
36.036424
132
0.596871
5.004474
false
false
false
false
aamays/Yelp
Yelp/Business.swift
1
5185
// // Business.swift // Yelp // // Created by Timothy Lee on 4/23/15. // Copyright (c) 2015 Timothy Lee. All rights reserved. // import UIKit import CoreLocation import MapKit class Business: NSObject, MKAnnotation { let name: String? let address: String? let imageURL: NSURL? let categories: String? let distance: String? let ratingImageURL: NSURL? let reviewCount: NSNumber? let businessLocation: CLLocation? let open: Bool? let displayPhone: String? let displayAddress: String? static let MapAnnotationIdentifier = "BusinessAnnotation" var title: String? { return name } var subtitle: String? var latitude: Double { return (businessLocation?.coordinate.latitude)! } var longitude: Double { return (businessLocation?.coordinate.longitude)! } var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = NSURL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" var dispAddr = "" var tempBusinessLocation: CLLocation? = nil if location != nil { let addressArray = location!["address"] as? NSArray // var street: String? = "" if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } // get restaurent location coordinates from response if let coordinateDict = location!["coordinate"] as? NSDictionary { let lat = coordinateDict["latitude"] as! CLLocationDegrees let long = coordinateDict["longitude"] as! CLLocationDegrees tempBusinessLocation = CLLocation(latitude: lat, longitude: long) } if let addr = location!["display_address"] as? [String] { dispAddr = addr.joinWithSeparator(", ") } } self.displayAddress = dispAddr self.businessLocation = tempBusinessLocation self.address = address if let isClosed = dictionary["is_closed"] as? Bool { open = !isClosed } else { open = false } if let phone = dictionary["display_phone"] as? String { displayPhone = phone } else { displayPhone = nil } let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joinWithSeparator(", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = NSURL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber } class func businesses(array array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } class func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) { YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, deals: Bool?, filters: [YelpFilters]?, completion: ([Business]!, NSError!) -> Void) -> Void { YelpClient.sharedInstance.searchWithTerm(term, sort: sort, categories: categories, deals: deals, filters: filters, completion: completion) } class func searchWithTerm(term: String, location: CLLocation, filters: [YelpFilters]?, offset: Int?, completion: ([Business]!, NSError!) -> Void) -> Void { YelpClient.sharedInstance.searchWithTerm(term, atLocation: location, withFilters: filters, offset: offset, completion: completion) } }
mit
5ed2898d16f197d63cb813ba36fe85d9
33.566667
181
0.592478
5.033981
false
false
false
false
ken0nek/swift
validation-test/Reflection/reflect_Int64.swift
1
2123
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/reflect_Int64 // RUN: %target-run %target-swift-reflection-test %t/reflect_Int64 2>&1 | FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop import SwiftReflectionTest class TestClass { var t: Int64 init(t: Int64) { self.t = t } } var obj = TestClass(t: 123) reflect(object: obj) // CHECK-64: Reflecting an object. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Int64.TestClass) // CHECK-64: Type info: // CHECK-64: (class_instance size=24 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-64: (field name=t offset=16 // CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-64: (field name=_value offset=0 // CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) // CHECK-32: Reflecting an object. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Int64.TestClass) // CHECK-32: Type info: // CHECK-32: (class_instance size=24 alignment=16 stride=32 num_extra_inhabitants=0 // CHECK-32: (field name=t offset=16 // CHECK-32: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 // CHECK-32: (field name=_value offset=0 // CHECK-32: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))) reflect(any: obj) // CHECK-64: Reflecting an existential. // CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-64: Type reference: // CHECK-64: (class reflect_Int64.TestClass) // CHECK-64: Type info: // CHECK-64: (reference kind=strong refcounting=native) // CHECK-32: Reflecting an existential. // CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}} // CHECK-32: Type reference: // CHECK-32: (class reflect_Int64.TestClass) // CHECK-32: Type info: // CHECK-32: (reference kind=strong refcounting=native) doneReflecting() // CHECK-64: Done. // CHECK-32: Done.
apache-2.0
e0230bc11ed8ace1764bf83c88794c4a
31.661538
123
0.68488
3.067919
false
true
false
false
ken0nek/swift
test/Reflection/typeref_decoding_objc.swift
1
6038
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-build-swift %S/Inputs/ObjectiveCTypes.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | FileCheck %s --check-prefix=CHECK-%target-ptrsize // REQUIRES: objc_interop // CHECK-32: FIELDS: // CHECK-32: ======= // CHECK-32: TypesToReflect.OC // CHECK-32: ----------------- // CHECK-32: TypesToReflect.GenericOC // CHECK-32: ------------------------ // CHECK-32: TypesToReflect.HasObjCClasses // CHECK-32: ----------------------------- // CHECK-32: url: __ObjC.NSURL // CHECK-32: (class __ObjC.NSURL) // CHECK-32: integer: Swift.Int // CHECK-32: (struct Swift.Int) // CHECK-32: __ObjC.NSURL // CHECK-32: ------------ // CHECK-32: ASSOCIATED TYPES: // CHECK-32: ================= // CHECK-32: - TypesToReflect.OC : Swift.AnyObject // CHECK-32: - TypesToReflect.OC : __ObjC.NSObjectProtocol // CHECK-32: - TypesToReflect.OC : Swift.Equatable // CHECK-32: - TypesToReflect.OC : Swift.Hashable // CHECK-32: - TypesToReflect.OC : Swift.CVarArg // CHECK-32: - TypesToReflect.OC : Swift.CustomStringConvertible // CHECK-32: - TypesToReflect.OC : Swift.CustomDebugStringConvertible // CHECK-32: - TypesToReflect.GenericOC : Swift.AnyObject // CHECK-32: - TypesToReflect.GenericOC : __ObjC.NSObjectProtocol // CHECK-32: - TypesToReflect.GenericOC : Swift.Equatable // CHECK-32: - TypesToReflect.GenericOC : Swift.Hashable // CHECK-32: - TypesToReflect.GenericOC : Swift.CVarArg // CHECK-32: - TypesToReflect.GenericOC : Swift.CustomStringConvertible // CHECK-32: - TypesToReflect.GenericOC : Swift.CustomDebugStringConvertible // CHECK-32: - TypesToReflect.HasObjCClasses : Swift.AnyObject // CHECK-32: BUILTIN TYPES: // CHECK-32: ============== // CHECK-32: - __ObjC.NSURL: // CHECK-32: Size: 4 // CHECK-32: Alignment: 4 // CHECK-32: Stride: 4 // CHECK-32: NumExtraInhabitants: 4096 // CHECK-32: CAPTURE DESCRIPTORS: // CHECK-32: ==================== // CHECK-32: - Capture types: // CHECK-32: (struct Swift.StaticString) // CHECK-32: (struct Swift.StaticString) // CHECK-32: (struct Swift.UInt) // CHECK-32: (struct Swift.UInt) // CHECK-32: - Metadata sources: // CHECK-32: - Capture types: // CHECK-32: (function // CHECK-32: (tuple)) // CHECK-32: - Metadata sources: // CHECK-32: - Capture types: // CHECK-32: (struct Swift.StaticString) // CHECK-32: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-32: (struct Swift.UInt8)) // CHECK-32: (struct Swift.UInt) // CHECK-32: (struct Swift.UInt) // CHECK-32: - Metadata sources: // CHECK-32: - Capture types: // CHECK-32: (function // CHECK-32: (tuple)) // CHECK-32: - Metadata sources: // CHECK-32: - Capture types: // CHECK-32: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-32: (struct Swift.UInt8)) // CHECK-32: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-32: (struct Swift.UInt8)) // CHECK-32: (struct Swift.UInt) // CHECK-32: (struct Swift.UInt) // CHECK-32: - Metadata sources: // CHECK-32: - Capture types: // CHECK-32: (function // CHECK-32: (tuple)) // CHECK-32: - Metadata sources: // CHECK-64: FIELDS: // CHECK-64: ======= // CHECK-64: TypesToReflect.OC // CHECK-64: ----------------- // CHECK-64: TypesToReflect.GenericOC // CHECK-64: ------------------------ // CHECK-64: TypesToReflect.HasObjCClasses // CHECK-64: ----------------------------- // CHECK-64: url: __ObjC.NSURL // CHECK-64: (class __ObjC.NSURL) // CHECK-64: integer: Swift.Int // CHECK-64: (struct Swift.Int) // CHECK-64: __ObjC.NSURL // CHECK-64: ------------ // CHECK-64: ASSOCIATED TYPES: // CHECK-64: ================= // CHECK-64: - TypesToReflect.OC : Swift.AnyObject // CHECK-64: - TypesToReflect.OC : __ObjC.NSObjectProtocol // CHECK-64: - TypesToReflect.OC : Swift.Equatable // CHECK-64: - TypesToReflect.OC : Swift.Hashable // CHECK-64: - TypesToReflect.OC : Swift.CVarArg // CHECK-64: - TypesToReflect.OC : Swift.CustomStringConvertible // CHECK-64: - TypesToReflect.OC : Swift.CustomDebugStringConvertible // CHECK-64: - TypesToReflect.GenericOC : Swift.AnyObject // CHECK-64: - TypesToReflect.GenericOC : __ObjC.NSObjectProtocol // CHECK-64: - TypesToReflect.GenericOC : Swift.Equatable // CHECK-64: - TypesToReflect.GenericOC : Swift.Hashable // CHECK-64: - TypesToReflect.GenericOC : Swift.CVarArg // CHECK-64: - TypesToReflect.GenericOC : Swift.CustomStringConvertible // CHECK-64: - TypesToReflect.GenericOC : Swift.CustomDebugStringConvertible // CHECK-64: - TypesToReflect.HasObjCClasses : Swift.AnyObject // CHECK-64: BUILTIN TYPES: // CHECK-64: ============== // CHECK-64: - __ObjC.NSURL: // CHECK-64: Size: 8 // CHECK-64: Alignment: 8 // CHECK-64: Stride: 8 // CHECK-64: NumExtraInhabitants: 2147483647 // CHECK-64: CAPTURE DESCRIPTORS: // CHECK-64: ==================== // CHECK-64: - Capture types: // CHECK-64: (struct Swift.StaticString) // CHECK-64: (struct Swift.StaticString) // CHECK-64: (struct Swift.UInt) // CHECK-64: (struct Swift.UInt) // CHECK-64: - Metadata sources: // CHECK-64: - Capture types: // CHECK-64: (function // CHECK-64: (tuple)) // CHECK-64: - Metadata sources: // CHECK-64: - Capture types: // CHECK-64: (struct Swift.StaticString) // CHECK-64: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-64: (struct Swift.UInt8)) // CHECK-64: (struct Swift.UInt) // CHECK-64: (struct Swift.UInt) // CHECK-64: - Metadata sources: // CHECK-64: - Capture types: // CHECK-64: (function // CHECK-64: (tuple)) // CHECK-64: - Metadata sources: // CHECK-64: - Capture types: // CHECK-64: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-64: (struct Swift.UInt8)) // CHECK-64: (bound_generic_struct Swift.UnsafeBufferPointer // CHECK-64: (struct Swift.UInt8)) // CHECK-64: (struct Swift.UInt) // CHECK-64: (struct Swift.UInt) // CHECK-64: - Metadata sources: // CHECK-64: - Capture types: // CHECK-64: (function // CHECK-64: (tuple)) // CHECK-64: - Metadata sources:
apache-2.0
650d4fce97f0efdabd2dc99830ad83f2
33.306818
180
0.667605
3.422902
false
false
false
false
tsolomko/SWCompression
Sources/swcomp/Extensions/ContainerEntryInfo+CustomStringConvertible.swift
1
4168
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression extension ContainerEntryInfo where Self: CustomStringConvertible { public var description: String { var output = "Name: \(self.name)\n" switch self.type { case .blockSpecial: output += "Type: block device file\n" case .characterSpecial: output += "Type: character device file\n" case .contiguous: output += "Type: contiguous file\n" case .directory: output += "Type: directory\n" case .fifo: output += "Type: fifo file\n" case .hardLink: output += "Type: hard link\n" case .regular: output += "Type: regular file\n" case .socket: output += "Type: socket\n" case .symbolicLink: output += "Type: symbolic link\n" case .unknown: output += "Type: unknown\n" } if let tarEntry = self as? TarEntryInfo { if tarEntry.type == .symbolicLink { output += "Linked path: \(tarEntry.linkName)\n" } if let ownerID = tarEntry.ownerID { output += "Uid: \(ownerID)\n" } if let groupID = tarEntry.groupID { output += "Gid: \(groupID)\n" } if let ownerUserName = tarEntry.ownerUserName { output += "Uname: \(ownerUserName)\n" } if let ownerGroupName = tarEntry.ownerGroupName { output += "Gname: \(ownerGroupName)\n" } if let comment = tarEntry.comment { output += "Comment: \(comment)\n" } if let unknownPaxRecords = tarEntry.unknownExtendedHeaderRecords, unknownPaxRecords.count > 0 { output += "Unknown PAX (extended header) records:\n" for entry in unknownPaxRecords { output += " \(entry.key): \(entry.value)\n" } } } if let zipEntry = self as? ZipEntryInfo { if !zipEntry.comment.isEmpty { output += "Comment: \(zipEntry.comment)\n" } output += String(format: "External File Attributes: 0x%08X\n", zipEntry.externalFileAttributes) output += "Is text file: \(zipEntry.isTextFile)\n" output += "File system type: \(zipEntry.fileSystemType)\n" output += "Compression method: \(zipEntry.compressionMethod)\n" if let ownerID = zipEntry.ownerID { output += "Uid: \(ownerID)\n" } if let groupID = zipEntry.groupID { output += "Gid: \(groupID)\n" } output += String(format: "CRC32: 0x%08X\n", zipEntry.crc) } if let sevenZipEntry = self as? SevenZipEntryInfo { if let winAttrs = sevenZipEntry.winAttributes { output += String(format: "Win attributes: 0x%08X\n", winAttrs) } if let crc = sevenZipEntry.crc { output += String(format: "CRC32: 0x%08X\n", crc) } output += "Has stream: \(sevenZipEntry.hasStream)\n" output += "Is empty: \(sevenZipEntry.isEmpty)\n" output += "Is anti-file: \(sevenZipEntry.isAnti)\n" } if let size = self.size { output += "Size: \(size) bytes\n" } if let mtime = self.modificationTime { output += "Mtime: \(mtime)\n" } if let atime = self.accessTime { output += "Atime: \(atime)\n" } if let ctime = self.creationTime { output += "Ctime: \(ctime)\n" } if let permissions = self.permissions?.rawValue { output += String(format: "Permissions: %o", permissions) } return output } } extension TarEntryInfo: CustomStringConvertible { } extension ZipEntryInfo: CustomStringConvertible { } extension SevenZipEntryInfo: CustomStringConvertible { }
mit
ca5b9388863f8740d255b08dd92fd22f
33.163934
107
0.53191
4.341667
false
false
false
false
danpratt/Simply-Zen
Simply Zen/View Controllers/GuidedZenViewController.swift
1
6931
// // GuidedZenViewController.swift // Simply Zen // // Created by Daniel Pratt on 5/19/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import UIKit import AVFoundation // MARK: - GuidedZenViewController Class class GuidedZenViewController: UIViewController, GuidedZenMenuViewDelegate { // MARK: - Properties @IBOutlet var guidedZenView: GuidedZenMenuView! var guidedCourse: SZCourse! // Delegate let delegate = UIApplication.shared.delegate as! AppDelegate // For sound var soundEffectPlayer: SoundEffect! // For haptics var areHapticsEnabled: Bool! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // hide nav bar navigationController?.navigationBar.isHidden = true // Load sound effect Engine soundEffectPlayer = SoundEffect() // Setup animations and enable button taps guidedZenView.addFloatAnimation() guidedZenView.guidedZenMenuViewDelegate = self // Load haptic settings if let hapticsEnabled = UserDefaults.standard.value(forKey: "areUiHapticsOn") as? Bool { areHapticsEnabled = hapticsEnabled } else { areHapticsEnabled = true UserDefaults.standard.set(areHapticsEnabled, forKey: "areUiHapticsOn") } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) guidedZenView.removeAllAnimations() } // MARK: - Guided Zen Menu View Delegate Methods func relaxPressed(relax: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() guidedZenView.addRelaxTappedAnimation { (finished) in if finished { self.guidedCourse = SZCourse.relaxCourse() self.pushMeditationView() } } } func heartMeditationPressed(heartMeditation: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() guidedZenView.addHeartMeditationTappedAnimation { (finished) in if finished { self.guidedCourse = SZCourse.heartMeditationCourse() self.pushMeditationView() } } } func beginningZenPressed(beginningZen: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() guidedZenView.addBeginningZenTappedAnimation { (finished) in if finished { self.guidedCourse = SZCourse.beginningZenCourse() self.pushMeditationView() } } } func lettingGoPressed(lettingGo: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() guidedZenView.addLettingGoTappedAnimation { (finished) in if finished { self.guidedCourse = SZCourse.lettingGoCourse() self.pushMeditationView() } } } func advancedBreathingPressed(advancedBreathing: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() guidedZenView.addAdvancedBreathingTappedAnimation { (finished) in if finished { self.guidedCourse = SZCourse.advancedBreathingCourse() self.pushMeditationView() } } } // MARK: Push Meditation View // This function can be called from outside to push the meditation view func pushMeditationView(withCourse course: SZCourse) { guidedCourse = course pushMeditationView() } private func pushMeditationView() { // Create variables for VC and course / lesson to load let meditationVC = self.storyboard?.instantiateViewController(withIdentifier: "meditationView") as! MeditationViewController let selectedCourse = guidedCourse.name var level = 0 var addedCourse = false var coreDataCourse: Course! let maxLevel = guidedCourse.lessons.count - 1 // Creating 3D touch shortcut let shortcutTitle = selectedCourse! let guidedCourseShortcut = UIMutableApplicationShortcutItem(type: "com.blaumagier.Simply-Zen.ContinueGuidedShortcut", localizedTitle: shortcutTitle, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: UIApplicationShortcutIconType.favorite), userInfo: ["courseName" : selectedCourse!]) // Set the shortcut items UIApplication.shared.shortcutItems = [guidedCourseShortcut] // Check to see if the user already has a history if let courses = self.delegate.user.courses?.array as? [Course] { for course in courses { if course.courseName == selectedCourse { addedCourse = true coreDataCourse = course level = Int(course.userProgress) break } } } // If the course hasn't been added yet create it and add to the user if !addedCourse { // create course Core Data object and add it to user coreDataCourse = Course(courseName: selectedCourse!, user: delegate.user, insertInto: delegate.stack.context) delegate.user.addToCourses(coreDataCourse) delegate.stack.save() } // Load lesson and attach to meditationVC // Make sure that level is not out of array index // If we have to change it to avoid a crash, update the CoreData model if !(level <= maxLevel) && coreDataCourse.completed { level = 1 coreDataCourse.userProgress = Int64(level) } else if level >= maxLevel { level = maxLevel coreDataCourse.userProgress = Int64(level) } meditationVC.lesson = guidedCourse.lessons[level] meditationVC.lessonFileName = meditationVC.lesson.lessonFileName meditationVC.coreDataCourse = coreDataCourse meditationVC.maxLevel = maxLevel self.navigationController?.pushViewController(meditationVC, animated: true) } }
apache-2.0
1f448ed359cfebcf555215eecc09d0d8
34.721649
303
0.631313
5.4653
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Models/RegionMonitor.swift
1
1013
// // RegionMonitor.swift // CleanStore // // Created by hoi on 29/5/17. // Copyright © 2017 hoi. All rights reserved. // import Foundation import CoreLocation protocol RegionMonitorDelegate: NSObjectProtocol { func onBackgroundLocationAccessDisabled() func didStartMonitoring() func didStopMonitoring() func didEnterRegion(region: CLRegion!) func didExitRegion(region: CLRegion!) func didRangeBeacon(beacon: CLBeacon!, region: CLRegion) func onError(error: NSError) } class RegionMonitor: NSObject, CLLocationManagerDelegate { var locationManager: CLLocationManager! var beaconRegion: CLBeaconRegion? var rangedBeacon: CLBeacon! = CLBeacon() var pendingMonitorRequest: Bool = false weak var delegate: RegionMonitorDelegate? init(delegate: RegionMonitorDelegate) { super.init() self.delegate = delegate self.locationManager = CLLocationManager() self.locationManager!.delegate = self } }
mit
68abe017055f75f6da9626a839d4f568
23.682927
60
0.70751
5.009901
false
false
false
false
gottesmm/swift
benchmark/single-source/StringInterpolation.swift
10
1457
//===--- StringInterpolation.swift ----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils class RefTypePrintable : CustomStringConvertible { var description: String { return "01234567890123456789012345678901234567890123456789" } } @inline(never) public func run_StringInterpolation(_ N: Int) { let reps = 100 let refResult = reps let anInt: Int64 = 0x1234567812345678 let aRefCountedObject = RefTypePrintable() for _ in 1...100*N { var result = 0 for _ in 1...reps { let s = "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}" let utf16 = s.utf16 // FIXME: if String is not stored as UTF-16 on this platform, then the // following operation has a non-trivial cost and needs to be replaced // with an operation on the native storage type. result = result &+ Int(utf16[utf16.index(before: utf16.endIndex)]) } CheckResults(result == refResult, "IncorrectResults in StringInterpolation: \(result) != \(refResult)") } }
apache-2.0
e0086606ad5fffea1386f76e07992f7f
33.690476
107
0.645161
4.428571
false
false
false
false
VBVMI/VerseByVerse-iOS
VBVMI-tvOS/AppDelegate.swift
1
4532
// // AppDelegate.swift // VBVMI-tvOS // // Created by Thomas Carey on 17/10/16. // Copyright © 2016 Tom Carey. All rights reserved. // import UIKit import XCGLogger import AlamofireImage import AVFoundation let logger: XCGLogger = { let logger = XCGLogger.default logger.setup(level: .debug, showThreadName: true, showLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: nil, fileLevel: .debug) // NSLogger support // only log to the external window return logger }() let VBVMIImageCache = AutoPurgingImageCache() @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let imageDownloader = ImageDownloader(configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .fifo, maximumActiveDownloads: 10, imageCache: VBVMIImageCache) UIImageView.af_sharedImageDownloader = imageDownloader let _ = ContextCoordinator.sharedInstance DispatchQueue.global(qos: .background).async { APIDataManager.core() APIDataManager.allTheChannels() } let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayback) } catch { print("Setting category to AVAudioSessionCategoryPlayback failed.") } 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 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:. } fileprivate static var _resourcesURL: URL? = nil static func resourcesURL() -> URL? { if let url = _resourcesURL { return url } let fileManager = FileManager.default let urls = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask) if let documentDirectory: URL = urls.first { // This is where the database should be in the application support directory let rootURL = documentDirectory.appendingPathComponent("resources") let path = rootURL.path if !fileManager.fileExists(atPath: path) { do { try fileManager.createDirectory(at: rootURL, withIntermediateDirectories: true, attributes: nil) } catch let error { logger.error("Error creating resources directory: \(error)") return nil } } _resourcesURL = rootURL return rootURL } else { logger.info("🍕Couldn't get documents directory!") } return nil } }
mit
5bd9d0089c8491bae48301be4cb55cd4
39.792793
285
0.676237
5.827542
false
false
false
false
davidtucker/WaterCooler-Demo
EnterpriseMessenger/MessageTableViewRecipientCell.swift
1
3992
// // MessageTableViewCell.swift // EnterpriseMessenger // // Created by David Tucker on 1/24/15. // Copyright (c) 2015 Universal Mind. All rights reserved. // import Foundation import UIKit /* This class is the cell for the times the user receives a message (is the recipient). */ class MessageTableViewRecipientCell : MessageTableViewCellBase { //MARK: - UIView Components /* This view has a small image of the sender within the cell (showing the profile pic). This is the MaskedImageView instances used for that view. */ lazy var profilePicView:MaskedImageView = { let profilePicView = MaskedImageView() profilePicView.backgroundColor = UIColor.lightGrayColor() profilePicView.setTranslatesAutoresizingMaskIntoConstraints(false) return profilePicView }() //MARK: - Initialization & Creation override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) bubbleColor = InterfaceConfiguration.recipientBubbleColor setupSubviews() } /* This view adds the subviews and sets up the auto-layout constraints. */ func setupSubviews() { contentView.addSubview(messageText) contentView.addSubview(profilePicView) let views = [ "textView" : messageText, "profilePic" : profilePicView ] let metrics = [ "topMargin" : 15.0, "leftMargin" : 10.0, "rightMargin" : 20.0, "bottomMargin" : 20.0, "profilePicWidth" : profilePicSize.width ] let picVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(2)-[profilePic(==profilePicWidth)]", options: nil, metrics: metrics, views: views) let textVerticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-(topMargin)-[textView]-(bottomMargin)-|", options: nil, metrics: metrics, views: views) let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-(leftMargin)-[profilePic(==profilePicWidth)]-(30)-[textView]-(rightMargin)-|", options: nil, metrics: metrics, views: views) contentView.addConstraints(picVerticalConstraints) contentView.addConstraints(textVerticalConstraints) contentView.addConstraints(horizontalConstraints) } //MARK: - Properties /* This property is the user (which sent the message). When set, this value will populate the profile picture. */ var user:KCSUser? = nil { didSet { if let profileImage = user?.getProfileImage() { profilePicView.image = profileImage } else { user?.populateProfileImage { (image) -> () in self.profilePicView.image = image } } } } //MARK: - Drawing /* This method draws the speech bubble for the recipient cell. */ override func drawBubblePath(context: CGContextRef) { let currentFrame = bounds let topY = margin let bottomY = currentFrame.size.height - (2 * margin) let leftX = (margin * 3) + profilePicSize.width + caretSize.width let rightX = currentFrame.size.width - (margin * 3) CGContextMoveToPoint(context, leftX, topY) CGContextAddLineToPoint(context, rightX, topY) CGContextAddLineToPoint(context, rightX, bottomY) CGContextAddLineToPoint(context, leftX, bottomY) CGContextAddLineToPoint(context, leftX, topY + caretTopOffset + caretSize.height) CGContextAddLineToPoint(context, leftX - caretSize.width, topY + caretTopOffset + (caretSize.height / 2)) CGContextAddLineToPoint(context, leftX, topY + caretTopOffset) CGContextAddLineToPoint(context, leftX, topY) } }
mit
fed12176ca7a15163e1a230a6df45b19
35.290909
212
0.64504
5.266491
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/PXCheckoutStore.swift
1
2436
import Foundation /** This class to provides information (like `PXPaymentData` or `PXCheckoutPreference`) about our Checkout. */ @objcMembers open class PXCheckoutStore: NSObject { private enum PXSecurity: String { case NONE = "none" case TWO_FACTOR_AUTHENTICATION = "2fa" } static let sharedInstance = PXCheckoutStore() var checkoutPreference: PXCheckoutPreference? var paymentDatas: [PXPaymentData] = [] var validationProgramId: String? private var data = [String: Any]() } // MARK: - Getters extension PXCheckoutStore { /** Get `PXPaymentData` object. */ public func getPaymentData() -> PXPaymentData { return paymentDatas.first ?? PXPaymentData() } /** Get list of `PXPaymentData` for split payment. */ public func getPaymentDatas() -> [PXPaymentData] { return paymentDatas } /** Get `PXCheckoutPreference` object. */ public func getCheckoutPreference() -> PXCheckoutPreference? { return checkoutPreference } /** Get `validationProgramId` propertie. */ public func getValidationProgramId() -> String? { return validationProgramId } /** Get `PXSecurity` type. */ public func getSecurityType() -> String { return PXConfiguratorManager.hasSecurityValidation() ? PXSecurity.TWO_FACTOR_AUTHENTICATION.rawValue : PXSecurity.NONE.rawValue } } // MARK: - DataStore /** Extra methods to key-value store. You can save any interest value during checkout. Use this under your responsibility. */ extension PXCheckoutStore { /** Add key-value data. - parameter forKey: Key to save. Type: `String` - parameter value: Value to save. Type: `Any` */ public func addData(forKey: String, value: Any) { self.data[forKey] = value } /** Remove data for key. - parameter key: Key to remove. */ public func remove(key: String) { data.removeValue(forKey: key) } /** Clear all key-values. */ public func removeAll() { data.removeAll() } /** Get data for key. - parameter forKey: Key to get data. */ public func getData(forKey: String) -> Any? { return self.data[forKey] } } extension PXCheckoutStore { func clean() { removeAll() checkoutPreference = nil paymentDatas = [] } }
mit
87f4c6a93d0417e096d022b30b14c12d
22.882353
135
0.626437
4.273684
false
false
false
false
iWeslie/Ant
Ant/Ant/LunTan/Detials/Controller/CarBusinessDVC.swift
1
9868
// // CarBusinessDVC.swift // Ant // // Created by Weslie on 2017/8/4. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit class CarBusinessDVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var tableView: UITableView? var modelInfo: LunTanDetialModel? var menuView = Menu() override func viewDidLoad() { super.viewDidLoad() loadCellData(index: 1) loadDetialTableView() self.tabBarController?.tabBar.isHidden = true menuView.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60) self.view.addSubview(menuView) } func loadDetialTableView() { let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60) self.tableView = UITableView(frame: frame, style: .grouped) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1) self.tableView?.separatorStyle = .singleLine tableView?.register(UINib(nibName: "CarBusinessBasicInfo", bundle: nil), forCellReuseIdentifier: "carBusinessBasicInfo") tableView?.register(UINib(nibName: "CarBusinessDetial", bundle: nil), forCellReuseIdentifier: "carBusinessDetial") tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo") tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction") tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions") tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader") tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell") tableView?.separatorStyle = .singleLine self.view.addSubview(tableView!) } func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 3 case 2: return 5 case 4: return 10 default: return 1 } } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 0: let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6) let urls = [ "http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg", "http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png", "http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg", "http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg", "http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png" ] var urlArray: [URL] = [URL]() for str in urls { let url = URL(string: str) urlArray.append(url!) } return LoopView(images: urlArray, frame: frame, isAutoScroll: true) case 1: let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView detialHeader?.DetialHeaderLabel.text = "详情介绍" return detialHeader case 2: let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView connactHeader?.DetialHeaderLabel.text = "联系人方式" return connactHeader default: return nil } } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == 2 { return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView } else { return nil } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 0: return UIScreen.main.bounds.width * 0.6 case 1: return 30 case 2: return 30 case 3: return 10 case 4: return 0.00001 default: return 0.00001 } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == 2 { return 140 } else { return 0.00001 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? switch indexPath.section { case 0: switch indexPath.row { case 0: cell = tableView.dequeueReusableCell(withIdentifier: "carBusinessBasicInfo") if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets.zero } case 1: cell = tableView.dequeueReusableCell(withIdentifier: "carBusinessDetial") if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets.zero } case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo") default: break } case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction") case 2: let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions // guard modelInfo.con else { // <#statements#> // } if let contact = modelInfo?.connactDict[indexPath.row] { if let key = contact.first?.key{ connactoptions.con_Ways.text = key } } if let value = modelInfo?.connactDict[indexPath.row].first?.value { connactoptions.con_Detial.text = value } switch modelInfo?.connactDict[indexPath.row].first?.key { case "联系人"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile") case "电话"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone") menuView.phoneURL = (modelInfo?.connactDict[indexPath.row].first?.value)! case "微信"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat") UIPasteboard.general.string = (modelInfo?.connactDict[indexPath.row].first?.value)! case "QQ"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq") case "邮箱"?: connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email") default: break } cell = connactoptions if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! { cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0) } case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader") case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell") default: break } return cell! } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch indexPath.section { case 0: switch indexPath.row { case 0: return 60 case 1: return 120 case 2: return 40 default: return 20 } case 1: return detialHeight + 10 case 2: return 50 case 3: return 40 case 4: return 120 default: return 20 } } } extension CarBusinessDVC { // MARK:- load data fileprivate func loadCellData(index: Int) { let group = DispatchGroup() //将当前的下载操作添加到组中 group.enter() NetWorkTool.shareInstance.infoDetial(VCType: .car, id: index + 1) { [weak self](result, error) in //在这里异步加载任务 if error != nil { print(error ?? "load house info list failed") return } guard let resultDict = result!["result"] else { return } let basic = LunTanDetialModel(dict: resultDict as! [String : AnyObject]) self?.modelInfo = basic //离开当前组 group.leave() } group.notify(queue: DispatchQueue.main) { //在这里告诉调用者,下完完毕,执行下一步操作 self.tableView?.reloadData() } } }
apache-2.0
27ae46aa135ab94f019b2c140b9803b0
35.062963
130
0.564034
4.927632
false
false
false
false
SoneeJohn/WWDC
WWDC/DateProvider.swift
1
473
// // DateProvider.swift // WWDC // // Created by Guilherme Rambo on 13/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation import ConfCore typealias DateProvider = () -> Date let Today: DateProvider = { if let fakeDate = Arguments.deloreanDate { let formatter = DateFormatter() formatter.dateFormat = ConfCoreDateFormat return formatter.date(from: fakeDate)! } else { return Date() } }
bsd-2-clause
92cf1821f724e66fdfbfc686ced243ac
20.454545
58
0.661017
4.104348
false
false
false
false
tiasn/TXLive
TXLive/TXLive/Classes/Main/View/PageContentview.swift
1
5729
// // PageContentview.swift // TXLive // // Created by LTX on 2016/12/12. // Copyright © 2016年 LTX. All rights reserved. // import UIKit //代理协议 protocol pageContentViewDelegate : class { func pageContentView(contentView : PageContentview, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "ContentCellID" class PageContentview: UIView { //定义属性 子控制器数组 fileprivate var childVcs : [UIViewController] // 属性 父控制器 fileprivate weak var parentViewController : UIViewController? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollViewDelegate : Bool = false weak var delegate : pageContentViewDelegate? //创建collectionView fileprivate lazy var collectionView : UICollectionView = {[weak self] in //创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //创建collectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView; }() //自定义构造函数 init(frame: CGRect, childVcs : [UIViewController], parentViewController : UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) //设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI extension PageContentview { fileprivate func setupUI() { // 添加所有子控制器到父控制器 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //添加collectionView addSubview(collectionView) collectionView.frame = bounds } } // MARK:- collectionView数据源方法 extension PageContentview : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //创建cell let cell = collectionView .dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) //给cell添加内容 for view in cell.contentView.subviews { view .removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } // MARK:- collectionView代理方法 extension PageContentview : UICollectionViewDelegate { //即将滚动 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollViewDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //如果是点击事件 拦截 if isForbidScrollViewDelegate {return} //滑动 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX {//左划 //计算Progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) //计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) //计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } //滑动停止 完全滑过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } }else{//右滑 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } print("progress:\(progress) targetIndex: \(targetIndex) sourceIndex : \(sourceIndex)") delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK:- 对外暴露的方法 extension PageContentview { func setCurrentIndex(index : Int) { isForbidScrollViewDelegate = true let offsetX = CGFloat(index) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x : offsetX, y : 0), animated: false) } }
mit
4df71d38794e3161e9f49b006e7ba541
25.480769
124
0.612019
6.0131
false
false
false
false
ahoppen/swift
test/Frontend/module-alias-invalid-input.swift
8
2270
// Tests for invalid module alias format and values. // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias foo=bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS %s // INVALID_MODULE_ALIAS: error: invalid module alias "foo"; make sure the alias differs from the module name, module ABI name, module link name, and a standard library name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias Swift=Bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS1 %s // INVALID_MODULE_ALIAS1: error: invalid module alias "Swift"; make sure the alias differs from the module name, module ABI name, module link name, and a standard library name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS2 %s // INVALID_MODULE_ALIAS2: error: duplicate module alias; the name "bar" is already used for a module alias or an underlying name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=baz -module-alias baz=cat 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS3 %s // INVALID_MODULE_ALIAS3: error: duplicate module alias; the name "baz" is already used for a module alias or an underlying name // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_ALIAS4 %s // INVALID_MODULE_ALIAS4: error: invalid module alias format "bar"; make sure to use the format '-module-alias alias_name=underlying_name' // RUN: not %target-swift-frontend -emit-silgen -parse-as-library %s -module-name foo -module-alias bar=c-a.t 2>&1 | %FileCheck -check-prefix=INVALID_MODULE_NAME %s // INVALID_MODULE_NAME: error: module name "c-a.t" is not a valid identifier // These should succeed. // RUN: %target-swift-frontend -emit-silgen %s > /dev/null // RUN: %target-swift-frontend -emit-silgen -parse-as-library -module-name foo %s -module-alias bar=cat > /dev/null // RUN: %target-swift-frontend -typecheck -parse-as-library -module-name foo %s -module-alias bar=cat public class Logger { public init() {} public func startLogging() {} }
apache-2.0
1b08f29bd47e3327a4a1f732f719e070
77.275862
186
0.743172
3.398204
false
false
false
false
mlilback/rc2SwiftClient
Rc2Common/themes/Theme.swift
1
7430
// // Theme.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // #if os(OSX) import AppKit #else import UIKit #endif import Foundation import MJLLogger enum ThemeType: String { case syntax case output } public protocol ThemeProperty { var stringValue: String { get } var localizedDescription: String { get } } extension ThemeProperty { public var localizedDescription: String { let key = "\(String(describing: type(of: self))).\(stringValue)" return NSLocalizedString(key, value: stringValue, comment: "") } } extension Notification.Name { /// posted when a SyntaxTheme has been modified. The object is the theme static let SyntaxThemeModified = Notification.Name(rawValue: "SyntaxThemeModified") /// posted when an OutputTheme has been modified. The object is the theme static let OutputThemeModified = Notification.Name(rawValue: "OutputThemeModified") } public protocol Theme: Codable, CustomStringConvertible { /// implemented in protocol extension to allow using AttributeName w/o the type name var attributeName: NSAttributedString.Key { get } /// for user-editable themes, the file location of this theme var fileUrl: URL? { get } /// name of the theme var name: String { get set } /// number of properties var propertyCount: Int { get } /// true if the theme is system-defined and not editable var isBuiltin: Bool { get } /// Updates the attributed string so its attributes use this theme /// /// - Parameter attributedString: The string whose attributes will be updated func update(attributedString: NSMutableAttributedString) } public class BaseTheme: NSObject, Theme { static let encoder = JSONEncoder() static let decoder = JSONDecoder() var themeType: ThemeType { return self is SyntaxTheme ? .syntax : .output } private enum MyKeys: String, CodingKey { case name } public init(name: String) { self.name = name super.init() fileUrl = BaseTheme.themesPath(type: themeType, builtin: false) .appendingPathComponent(UUID().uuidString) .appendingPathExtension("json") DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(1000), execute: { self.saveIngoringError() }) } public required init(from decoder: Decoder) throws { name = "" // let container = try decoder.container(keyedBy: MyKeys.self) // name = try container.decode(String.self, forKey: .name) } public func encode(to encoder: Encoder) throws { // all properties should be encoded by subclass } /// saves user editable theme to disk. public func save() throws { guard !isBuiltin else { throw ThemeError.notEditable } guard let url = fileUrl else { fatalError("why is there no url?") } let data = try BaseTheme.encoder.encode(self) try data.write(to: url) dirty = false } private func saveIngoringError() { do { try save() } catch { Log.error("error saving theme: \(error)", .core) } } public override var description: String { return "Theme \(name)" } /// map the static AttributeName to a non-static property so type name is not required to reference it public let attributeName: NSAttributedString.Key = NSAttributedString.Key("rc2.BaseTheme") public var allProperties: [ThemeProperty] { if type(of: self) == SyntaxTheme.self { return SyntaxThemeProperty.allProperties } return OutputThemeProperty.allProperties } public var name: String { willSet { guard !isBuiltin else { fatalError("can't edit name of builtin theme") } } didSet { if fileUrl != nil { saveIngoringError() } } } public internal(set) var isBuiltin: Bool = false public internal(set) var fileUrl: URL? var dirty: Bool = false public var propertyCount: Int { return 0 } public func color(for property: ThemeProperty) -> PlatformColor { if let syntax = self as? SyntaxTheme, let prop = property as? SyntaxThemeProperty { return syntax.color(for: prop) } else if let output = self as? OutputTheme, let prop = property as? OutputThemeProperty { return output.color(for: prop) } Log.warn("unknown theme property \(property.localizedDescription)", .core) return NSColor.black } public subscript(key: ThemeProperty) -> PlatformColor? { get { return color(for: key) } set (newValue) { guard !isBuiltin else { fatalError("builtin themes are not editable") } guard let newValue = newValue else { fatalError("theme colors cannot be nil") } if let syntax = self as? SyntaxTheme, let prop = key as? SyntaxThemeProperty { guard syntax[prop] != newValue else { return } syntax[prop] = newValue dirty = true NotificationCenter.default.post(name: .SyntaxThemeModified, object: self) } else if let output = self as? OutputTheme, let prop = key as? OutputThemeProperty { guard output[prop] != newValue else { return } output[prop] = newValue dirty = true NotificationCenter.default.post(name: .OutputThemeModified, object: self) } else { Log.warn("unknown theme property \(key.localizedDescription)", .core) } } } /// returns the url to the theme file if builtin, the user dir if not builtin private static func themesPath(type: ThemeType, builtin: Bool) -> URL { let dirName: String switch type { case .syntax: dirName = "SyntaxThemes" case .output: dirName = "OutputThemes" } if builtin { /// at some point in Mojhave Budle.url(forResource) started percent encoding the superscript in the app title. This fixes that guard let rawPath = Bundle(for: ThemeManager.self).url(forResource: dirName, withExtension: "json"), let path = rawPath.path.removingPercentEncoding else { fatalError("failed to find themes") } return URL(fileURLWithPath: path) } // swiftlint:disable:next force_try return try! AppInfo.subdirectory(type: .applicationSupportDirectory, named: dirName) } static public func loadThemes<T: BaseTheme>() -> [T] { let ttype: ThemeType = T.self == SyntaxTheme.self ? .syntax : .output var themes: [T] = loadBuiltinThemes(from: themesPath(type: ttype, builtin: true)) var urls = [URL]() do { urls = try FileManager.default.contentsOfDirectory(at: themesPath(type: ttype, builtin: false), includingPropertiesForKeys: nil, options: .skipsHiddenFiles) } catch { Log.warn("error getting user themes: \(error)", .core) return themes } urls.forEach { aFile in guard aFile.pathExtension == "json" else { return } do { let data = try Data(contentsOf: aFile) let theme: T = try decoder.decode(T.self, from: data) theme.isBuiltin = false theme.fileUrl = aFile themes.append(theme) } catch { Log.warn("error reading theme from \(aFile.lastPathComponent): \(error)", .app) } } return themes } static func loadBuiltinThemes<T: BaseTheme>(from url: URL) -> [T] { do { guard let path = url.path.removingPercentEncoding, let str = try? String(contentsOfFile: path), let data = str.data(using: .utf8) else { fatalError() } let themes: [T] = try decoder.decode([T].self, from: data).sorted(by: { $0.name < $1.name }) themes.forEach { $0.isBuiltin = true } return themes } catch { fatalError("failed to decode builtin themes \(error)") } } /// Updates the attributed string so its attributes use this theme /// /// - Parameter attributedString: The string whose attributes will be updated public func update(attributedString: NSMutableAttributedString) { fatalError("subclass must implement") } }
isc
9b27f0353957d87f205055e4ca5d5273
32.922374
159
0.714093
3.716358
false
false
false
false
warnerbros/cpe-manifest-ios-experience
Source/Shared Views/RadioButton.swift
1
1566
// // RadioButton.swift // import UIKit class RadioButton: UIButton { var section: Int? var index: Int? var selection = CAShapeLayer() override var isSelected: Bool { didSet { toggleButon() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } override init(frame: CGRect) { super.init(frame: frame) initialize() } func initialize() { self.isUserInteractionEnabled = true self.clipsToBounds = true self.layer.borderWidth = 3 self.layer.cornerRadius = 0.5*35 self.layer.borderColor = UIColor.gray.cgColor self.layer.backgroundColor = UIColor.black.cgColor selection.frame = CGRect(x: 5, y: 5, width: 25, height: 25) selection.borderWidth = 3 selection.cornerRadius = 0.5*25 selection.borderColor = UIColor.clear.cgColor self.layer.addSublayer(selection) } func toggleButon() { if self.isSelected { highlight() } else { removeHighlight() } } func highlight() { //self.selected = !self.selected selection.backgroundColor = UIColor.init(red: 255/255, green: 205/255, blue: 77/255, alpha: 1).cgColor self.layer.borderColor = UIColor.white.cgColor } func removeHighlight() { //self.selected = !self.selected selection.backgroundColor = UIColor.clear.cgColor self.layer.borderColor = UIColor.gray.cgColor } }
apache-2.0
7d1d997f03b14870b37118e0408d5bdc
20.75
110
0.600255
4.374302
false
false
false
false
nicolastinkl/swift
ListerAProductivityAppBuiltinSwift/Lister/ListColorCell.swift
1
1815
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A custom cell that allows the user to select between 6 different colors. */ import UIKit import ListerKit // Provides the ability to send a delegate a message about newly created list info objects. @objc protocol ListColorCellDelegate { func listColorCellDidChangeSelectedColor(listColorCell: ListColorCell) } class ListColorCell: UITableViewCell { // MARK: Properties @IBOutlet var gray: UIView @IBOutlet var blue: UIView @IBOutlet var green: UIView @IBOutlet var yellow: UIView @IBOutlet var orange: UIView @IBOutlet var red: UIView weak var delegate: ListColorCellDelegate? var selectedColor: List.Color = .Gray // MARK: Reuse func configure() { // Setup a gesture recognizer to track taps on color views in the cell. let colorGesture = UITapGestureRecognizer(target: self, action: "colorTap:") colorGesture.numberOfTapsRequired = 1 colorGesture.numberOfTouchesRequired = 1 self.addGestureRecognizer(colorGesture) } // MARK: UITapGestureRecognizer Handling func colorTap(tapGestureRecognizer: UITapGestureRecognizer) { if tapGestureRecognizer.state != .Ended { return } let tapLocation = tapGestureRecognizer.locationInView(contentView) let view = contentView!.hitTest(tapLocation, withEvent: nil) // If the user tapped on a color (identified by its tag), notify the delegate. if let color = List.Color.fromRaw(view.tag) { selectedColor = color delegate?.listColorCellDidChangeSelectedColor(self) } } }
mit
f177412bae4ecb216995d503073967a7
29.728814
91
0.675124
5.194842
false
false
false
false
ben-ng/swift
stdlib/public/SDK/CoreLocation/CLError.swift
1
850
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import CoreLocation import Foundation #if os(iOS) extension CLError { /// In a regionMonitoringResponseDelayed error, the region that the /// location services can more effectively monitor. public var alternateRegion: CLRegion? { return userInfo[kCLErrorUserInfoAlternateRegionKey] as? CLRegion } } #endif
apache-2.0
cff79649709e1952eed94b09691e4d5b
34.416667
80
0.614118
5.120482
false
false
false
false
adrfer/swift
stdlib/public/core/OutputStream.swift
1
11595
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Input/Output interfaces //===----------------------------------------------------------------------===// /// A target of text streaming operations. public protocol OutputStreamType { mutating func _lock() mutating func _unlock() /// Append the given `string` to this stream. mutating func write(string: String) } extension OutputStreamType { public mutating func _lock() {} public mutating func _unlock() {} } /// A source of text streaming operations. `Streamable` instances can /// be written to any *output stream*. /// /// For example: `String`, `Character`, `UnicodeScalar`. public protocol Streamable { /// Write a textual representation of `self` into `target`. func writeTo<Target : OutputStreamType>(inout target: Target) } /// A type with a customized textual representation. /// /// This textual representation is used when values are written to an /// *output stream*, for example, by `print`. /// /// - Note: `String(instance)` will work for an `instance` of *any* /// type, returning its `description` if the `instance` happens to be /// `CustomStringConvertible`. Using `CustomStringConvertible` as a /// generic constraint, or accessing a conforming type's `description` /// directly, is therefore discouraged. /// /// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible` public protocol CustomStringConvertible { /// A textual representation of `self`. var description: String { get } } /// A type with a customized textual representation suitable for /// debugging purposes. /// /// This textual representation is used when values are written to an /// *output stream* by `debugPrint`, and is /// typically more verbose than the text provided by a /// `CustomStringConvertible`'s `description` property. /// /// - Note: `String(reflecting: instance)` will work for an `instance` /// of *any* type, returning its `debugDescription` if the `instance` /// happens to be `CustomDebugStringConvertible`. Using /// `CustomDebugStringConvertible` as a generic constraint, or /// accessing a conforming type's `debugDescription` directly, is /// therefore discouraged. /// /// - SeeAlso: `String.init<T>(reflecting: T)`, /// `CustomStringConvertible` public protocol CustomDebugStringConvertible { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } //===----------------------------------------------------------------------===// // Default (ad-hoc) printing //===----------------------------------------------------------------------===// /// Do our best to print a value that cannot be printed directly. internal func _adHocPrint<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream, isDebugPrint: Bool ) { func printTypeName(type: Any.Type) { // Print type names without qualification, unless we're debugPrint'ing. target.write(_typeName(type, qualified: isDebugPrint)) } let mirror = _reflect(value) switch mirror { // Checking the mirror kind is not a good way to implement this, but we don't // have a more expressive reflection API now. case is _TupleMirror: target.write("(") var first = true for i in 0..<mirror.count { if first { first = false } else { target.write(", ") } let (_, elementMirror) = mirror[i] let elt = elementMirror.value debugPrint(elt, terminator: "", toStream: &target) } target.write(")") case is _StructMirror: printTypeName(mirror.valueType) target.write("(") var first = true for i in 0..<mirror.count { if first { first = false } else { target.write(", ") } let (label, elementMirror) = mirror[i] print(label, terminator: "", toStream: &target) target.write(": ") debugPrint(elementMirror.value, terminator: "", toStream: &target) } target.write(")") case let enumMirror as _EnumMirror: if let caseName = String.fromCString(enumMirror.caseName) { // Write the qualified type name in debugPrint. if isDebugPrint { target.write(_typeName(mirror.valueType)) target.write(".") } target.write(caseName) } else { // If the case name is garbage, just print the type name. printTypeName(mirror.valueType) } if mirror.count == 0 { return } let (_, payload) = mirror[0] if payload is _TupleMirror { debugPrint(payload.value, terminator: "", toStream: &target) return } target.write("(") debugPrint(payload.value, terminator: "", toStream: &target) target.write(")") case is _MetatypeMirror: printTypeName(mirror.value as! Any.Type) default: print(mirror.summary, terminator: "", toStream: &target) } } @inline(never) @_semantics("stdlib_binary_only") internal func _print_unlocked<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { // Optional has no representation suitable for display; therefore, // values of optional type should be printed as a debug // string. Check for Optional first, before checking protocol // conformance below, because an Optional value is convertible to a // protocol if its wrapped type conforms to that protocol. if _isOptional(value.dynamicType) { let debugPrintable = value as! CustomDebugStringConvertible debugPrintable.debugDescription.writeTo(&target) return } if case let streamableObject as Streamable = value { streamableObject.writeTo(&target) return } if case let printableObject as CustomStringConvertible = value { printableObject.description.writeTo(&target) return } if case let debugPrintableObject as CustomDebugStringConvertible = value { debugPrintableObject.debugDescription.writeTo(&target) return } _adHocPrint(value, &target, isDebugPrint: false) } /// Returns the result of `print`'ing `x` into a `String`. /// /// Exactly the same as `String`, but annotated 'readonly' to allow /// the optimizer to remove calls where results are unused. /// /// This function is forbidden from being inlined because when building the /// standard library inlining makes us drop the special semantics. @inline(never) @effects(readonly) func _toStringReadOnlyStreamable<T : Streamable>(x: T) -> String { var result = "" x.writeTo(&result) return result } @inline(never) @effects(readonly) func _toStringReadOnlyPrintable<T : CustomStringConvertible>(x: T) -> String { return x.description } //===----------------------------------------------------------------------===// // `debugPrint` //===----------------------------------------------------------------------===// @inline(never) public func _debugPrint_unlocked<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { if let debugPrintableObject = value as? CustomDebugStringConvertible { debugPrintableObject.debugDescription.writeTo(&target) return } if let printableObject = value as? CustomStringConvertible { printableObject.description.writeTo(&target) return } if let streamableObject = value as? Streamable { streamableObject.writeTo(&target) return } _adHocPrint(value, &target, isDebugPrint: true) } //===----------------------------------------------------------------------===// // OutputStreams //===----------------------------------------------------------------------===// internal struct _Stdout : OutputStreamType { mutating func _lock() { _swift_stdlib_flockfile_stdout() } mutating func _unlock() { _swift_stdlib_funlockfile_stdout() } mutating func write(string: String) { // FIXME: buffering? // It is important that we use stdio routines in order to correctly // interoperate with stdio buffering. for c in string.utf8 { _swift_stdlib_putchar(Int32(c)) } } } extension String : OutputStreamType { /// Append `other` to this stream. public mutating func write(other: String) { self += other } } //===----------------------------------------------------------------------===// // Streamables //===----------------------------------------------------------------------===// extension String : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(self) } } extension Character : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(String(self)) } } extension UnicodeScalar : Streamable { /// Write a textual representation of `self` into `target`. public func writeTo<Target : OutputStreamType>(inout target: Target) { target.write(String(Character(self))) } } //===----------------------------------------------------------------------===// // Unavailable APIs //===----------------------------------------------------------------------===// @available(*, unavailable, renamed="CustomDebugStringConvertible") public typealias DebugPrintable = CustomDebugStringConvertible @available(*, unavailable, renamed="CustomStringConvertible") public typealias Printable = CustomStringConvertible @available(*, unavailable, renamed="print") public func println<T, TargetStream : OutputStreamType>( value: T, inout _ target: TargetStream ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="print") public func println<T>(value: T) { fatalError("unavailable function can't be called") } @available(*, unavailable, message="use print(\"\")") public func println() { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="String") public func toString<T>(x: T) -> String { fatalError("unavailable function can't be called") } @available(*, unavailable, message="use debugPrint()") public func debugPrintln<T, TargetStream : OutputStreamType>( x: T, inout _ target: TargetStream ) { fatalError("unavailable function can't be called") } @available(*, unavailable, renamed="debugPrint") public func debugPrintln<T>(x: T) { fatalError("unavailable function can't be called") } /// Returns the result of `debugPrint`'ing `x` into a `String`. @available(*, unavailable, message="use String(reflecting:)") public func toDebugString<T>(x: T) -> String { fatalError("unavailable function can't be called") } /// A hook for playgrounds to print through. public var _playgroundPrintHook : ((String) -> Void)? = {_ in () } internal struct _TeeStream< L : OutputStreamType, R : OutputStreamType > : OutputStreamType { var left: L var right: R /// Append the given `string` to this stream. mutating func write(string: String) { left.write(string); right.write(string) } mutating func _lock() { left._lock(); right._lock() } mutating func _unlock() { left._unlock(); right._unlock() } }
apache-2.0
b9d1708dbfed13f82a8f5e610bfff609
31.030387
80
0.631652
4.730722
false
false
false
false
mmcguill/StrongBox
FavIcon-Swift/FavIcon.swift
1
16789
// // FavIcon // Copyright © 2016 Leon Breedt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation #if os(iOS) import UIKit /// Alias for the iOS image type (`UIImage`). public typealias ImageType = UIImage #elseif os(OSX) import Cocoa /// Alias for the OS X image type (`NSImage`). public typealias ImageType = NSImage #endif /// Represents the result of attempting to download an icon. public enum IconDownloadResult { /// Download successful. /// /// - parameter image: The `ImageType` for the downloaded icon. case success(image: ImageType) /// Download failed for some reason. /// /// - parameter error: The error which can be consulted to determine the root cause. case failure(error: Error) } //@objc public final class URLSessionDelegateIgnoreSSLProblems : NSObject { //} class AuthSessionDelegate: NSObject, URLSessionDelegate { func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { // // let authMethod = challenge.protectionSpace.authenticationMethod // // guard challenge.previousFailureCount < 1, authMethod == NSURLAuthenticationMethodServerTrust, // let trust = challenge.protectionSpace.serverTrust else { // completionHandler(.performDefaultHandling, nil) // return // } guard let serverTrust = challenge.protectionSpace.serverTrust else { print(challenge) completionHandler(.rejectProtectionSpace, nil) return } completionHandler(.useCredential, URLCredential(trust: serverTrust)) } } /// Responsible for detecting all of the different icons supported by a given site. @objc public final class FavIcon : NSObject { // swiftlint:disable function_body_length /// Scans a base URL, attempting to determine all of the supported icons that can /// be used for favicon purposes. /// /// It will do the following to determine possible icons that can be used: /// /// - Check whether or not `/favicon.ico` exists. /// - If the base URL returns an HTML page, parse the `<head>` section and check for `<link>` /// and `<meta>` tags that reference icons using Apple, Microsoft and Google /// conventions. /// - If _Web Application Manifest JSON_ (`manifest.json`) files are referenced, or /// _Microsoft browser configuration XML_ (`browserconfig.xml`) files /// are referenced, download and parse them to check if they reference icons. /// /// All of this work is performed in a background queue. /// /// - parameter url: The base URL to scan. /// - parameter completion: A closure to call when the scan has completed. The closure will be call /// on the main queue. @objc public static func scan(_ url: URL, on queue: OperationQueue? = nil, favIcon: Bool = true, scanHtml: Bool = true, duckDuckGo: Bool = true, google: Bool = true, allowInvalidSSLCerts: Bool = false, completion: @escaping ([DetectedIcon], [String:String]) -> Void) throws { let syncQueue = DispatchQueue(label: "org.bitserf.FavIcon", attributes: []) var icons: [DetectedIcon] = [] var additionalDownloads: [URLRequestWithCallback] = [] let urlSession = allowInvalidSSLCerts ? insecureUrlSessionProvider() : urlSessionProvider() var meta: [String:String] = [:] var operations: [URLRequestWithCallback] = [] if(scanHtml) { let downloadHTMLOperation = DownloadTextOperation(url: url, session: urlSession) let downloadHTML = urlRequestOperation(downloadHTMLOperation) { result in if case let .textDownloaded(actualURL, text, contentType) = result { if contentType == "text/html" { let document = HTMLDocument(string: text) let htmlIcons = extractHTMLHeadIcons(document, baseURL: actualURL) let htmlMeta = examineHTMLMeta(document, baseURL: actualURL) syncQueue.sync { icons.append(contentsOf: htmlIcons) meta = htmlMeta } for manifestURL in extractWebAppManifestURLs(document, baseURL: url) { let downloadOperation = DownloadTextOperation(url: manifestURL, session: urlSession) let download = urlRequestOperation(downloadOperation) { result in if case .textDownloaded(_, let manifestJSON, _) = result { let jsonIcons = extractManifestJSONIcons( manifestJSON, baseURL: actualURL ) syncQueue.sync { icons.append(contentsOf: jsonIcons) } } } additionalDownloads.append(download) } let browserConfigResult = extractBrowserConfigURL(document, baseURL: url) if let browserConfigURL = browserConfigResult.url, !browserConfigResult.disabled { let downloadOperation = DownloadTextOperation(url: browserConfigURL, session: urlSession) let download = urlRequestOperation(downloadOperation) { result in if case let .textDownloaded(_, browserConfigXML, _) = result { let document = LBXMLDocument(string: browserConfigXML) let xmlIcons = extractBrowserConfigXMLIcons( document, baseURL: actualURL ) syncQueue.sync { icons.append(contentsOf: xmlIcons) } } } additionalDownloads.append(download) } } } } operations.append(downloadHTML); } if(favIcon) { let commonFiles : [String] = [ "favicon.ico", "apple-touch-icon.png", "apple-icon-57x57.png", "apple-icon-60x60.png", "apple-icon-72x72.png", "apple-icon-76x76.png", "apple-icon-114x114.png", "apple-icon-120x120.png", "apple-icon-144x144.png", "apple-icon-152x152.png", "apple-icon-180x180.png", "android-icon-192x192.png", "favicon-32x32.png", "favicon-96x96.png", "favicon-16x16.png", "ms-icon-144x144.png"]; for commonFile in commonFiles { //print("Checking: ", commonFile) let favIconURL = URL(string: commonFile, relativeTo: url as URL)!.absoluteURL let checkFavIconOperation = CheckURLExistsOperation(url: favIconURL, session: urlSession) let checkFavIcon = urlRequestOperation(checkFavIconOperation) { result in if case let .success(actualURL) = result { print("Common File Success: ", actualURL) syncQueue.sync { icons.append(DetectedIcon(url: actualURL, type: .classic)) } } } operations.append(checkFavIcon); } } var components = URLComponents(url: url, resolvingAgainstBaseURL: false); components?.path = ""; //@""; components?.query = nil; //@""; components?.user = nil; //@""; components?.password = nil; //@""; components?.fragment = nil; //@""; let domain = components?.host ?? url.absoluteString; let blah = String(format: "https://icons.duckduckgo.com/ip3/%@.ico" , domain.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) if(duckDuckGo) { let ddgUrl = URL(string: blah); if (ddgUrl != nil) { let duckDuckGoURL = ddgUrl!.absoluteURL let checkDuckDuckGoURLOperation = CheckURLExistsOperation(url: duckDuckGoURL, session: urlSession) let checkDuckDuckGoURL = urlRequestOperation(checkDuckDuckGoURLOperation) { result in if case let .success(actualURL) = result { syncQueue.sync { icons.append(DetectedIcon(url: actualURL, type: .classic)) } } } operations.append(checkDuckDuckGoURL); } } // if(google) { let blah2 = String(format: "https://www.google.com/s2/favicons?domain=%@" , domain.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!) let googleURL = URL(string: blah2)?.absoluteURL if (googleURL != nil) { let checkGoogleUrlOperation = CheckURLExistsOperation(url: googleURL!, session: urlSession) let checkGoogleUrl = urlRequestOperation(checkGoogleUrlOperation) { result in if case let .success(actualURL) = result { syncQueue.sync { icons.append(DetectedIcon(url: actualURL, type: .classic)) } } } operations.append(checkGoogleUrl); } } if(operations.count == 0) { DispatchQueue.main.async { completion(icons, meta) } } executeURLOperations(operations, on: queue) { if additionalDownloads.count > 0 { executeURLOperations(additionalDownloads, on: queue) { DispatchQueue.main.async { completion(icons, meta) } } } else { DispatchQueue.main.async { completion(icons, meta) } } } } // swiftlint:enable function_body_length /// Downloads an array of detected icons in the background. /// /// - parameter icons: The icons to download. /// - parameter completion: A closure to call when all download tasks have /// results available (successful or otherwise). The closure /// will be called on the main queue. @objc public static func download(_ icons: [DetectedIcon], completion: @escaping ([ImageType]) -> Void) { let urlSession = urlSessionProvider() let operations: [DownloadImageOperation] = icons.map { DownloadImageOperation(url: $0.url, session: urlSession) } executeURLOperations(operations) { results in let downloadResults: [ImageType] = results.compactMap { result in switch result { case .imageDownloaded(_, let image): return image; case .failed(_): return nil; default: return nil; } } DispatchQueue.main.async { completion(downloadResults) } } } enum MyError: Error { case runtimeError(String) } @objc public static func downloadAll(_ url: URL, favIcon: Bool, scanHtml: Bool, duckDuckGo: Bool, google: Bool, allowInvalidSSLCerts: Bool, completion: @escaping ([ImageType]?) -> Void) throws { do { try scan(url, favIcon: favIcon, scanHtml: scanHtml, duckDuckGo: duckDuckGo, google: google, allowInvalidSSLCerts: allowInvalidSSLCerts ) { icons, meta in let iconMap = icons.reduce(into: [URL:DetectedIcon](), { current,icon in current[icon.url] = icon }) let uniqueIcons = Array(iconMap.values); dl(uniqueIcons) { downloaded in let blah = Array(downloaded.values) DispatchQueue.main.async { completion(blah) } } } } catch { DispatchQueue.main.async { completion([]) } } } @objc public static func dl(_ icons: [DetectedIcon], on queue: OperationQueue? = nil, completion: @escaping ([URL: ImageType]) -> Void) { let urlSession = urlSessionProvider() let operations: [DownloadImageOperation] = icons.map { DownloadImageOperation(url: $0.url, session: urlSession) } var myDictionary = [URL: ImageType]() executeURLOperations(operations, on: queue) { results in for result in results { switch result { case let .imageDownloaded(url, image): myDictionary[url] = image default: continue; } } DispatchQueue.main.async { completion(myDictionary) } } } typealias URLSessionProvider = () -> URLSession @objc static var urlSessionProvider: URLSessionProvider = FavIcon.createDefaultURLSession @objc static var insecureUrlSessionProvider: URLSessionProvider = FavIcon.createInsecureURLSession @objc static func createDefaultURLSession() -> URLSession { return URLSession.shared } @objc static func createInsecureURLSession() -> URLSession { return URLSession (configuration: URLSessionConfiguration.default, delegate: AuthSessionDelegate (), delegateQueue: nil); } } /// Enumerates errors that can be thrown while detecting or downloading icons. enum IconError: Error { /// The base URL specified is not a valid URL. case invalidBaseURL /// At least one icon to must be specified for downloading. case atLeastOneOneIconRequired /// Unexpected response when downloading case invalidDownloadResponse /// No icons were detected, so nothing could be downloaded. case noIconsDetected } extension DetectedIcon { /// The area of a detected icon, if known. var area: Int? { if let width = width, let height = height { return width * height } return nil } }
agpl-3.0
1285c60234452ab3cff28860e74ed6a3
41.936061
171
0.517274
5.679296
false
false
false
false
dornad/RESTModel
Chillax/Sources/Types/HTTPMethod.swift
1
518
// // HTTPMethod.swift // Chillax // // Created by Daniel Rodriguez on 4/28/17. // Copyright © 2017 REST Models. All rights reserved. // import Foundation /// An Swift enumeration providing a type-safe enumeration for the HTTP Method public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" }
apache-2.0
c473888a6870f0eaebdc01931e3abc47
22.5
78
0.622824
3.590278
false
false
false
false
shepting/100Playgrounds
Playground4.playground/contents.swift
2
466
// Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let view = UIView() view.frame = CGRectMake(10, 20, 200, 60) view.backgroundColor = UIColor.redColor() let image = UIImage(named: "Man2") image.frame = CGRectMake(0, 0, 40, 40) view.addSubview(image) view //Define a UILabel with a frame and set some display text let helloLabel = UILabel(frame: CGRectMake(0.0, 0.0, 200.0, 44.0)) helloLabel.text = str; helloLabel
mit
458236f7bdcebfb9340bfeb6177f4e3c
21.190476
66
0.72103
3.213793
false
false
false
false
fousa/trackkit
Sources/Classes/Parser/NMEA/Parser/GPGLLParser.swift
1
1493
// // TrackKit // // Created by Jelle Vandebeeck on 15/03/16. // import CoreLocation class GPGLLParser: NMEAParsable { private(set) var line: [String] private(set) var name: String? private(set) var time: Date? private(set) var coordinate: CLLocationCoordinate2D? private(set) var gpsQuality: GPSQuality? private(set) var navigationReceiverWarning: NavigationReceiverWarning? private(set) var numberOfSatellites: Int? private(set) var horizontalDilutionOfPrecision: Double? private(set) var elevation: Double? private(set) var heightOfGeoid: Double? private(set) var timeSinceLastUpdate: Double? private(set) var speed: Double? private(set) var trackAngle: Double? private(set) var magneticVariation: Double? private(set) var stationId: String? required init?(line: [String]) { self.line = line // Parse the coordinate and invalidate the point when not available. guard let latitude = parseCoordinateValue(from: self[1], direction: self[2], offset: 2), let longitude = parseCoordinateValue(from: self[3], direction: self[4], offset: 3) else { return nil } coordinate = CLLocationCoordinate2DMake(latitude, longitude) // Parse the time. time = self[5]?.nmeaTimeValue // Parse the navigation receiver warning. navigationReceiverWarning = self[6]?.checksumEscapedString?.nmeaNavigationReceiverWarning } }
mit
8662c9002541438879155521f92aa6bb
31.456522
101
0.683858
4.241477
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/ApplicationAutoScaling/ApplicationAutoScaling_Error.swift
1
3921
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for ApplicationAutoScaling public struct ApplicationAutoScalingErrorType: AWSErrorType { enum Code: String { case concurrentUpdateException = "ConcurrentUpdateException" case failedResourceAccessException = "FailedResourceAccessException" case internalServiceException = "InternalServiceException" case invalidNextTokenException = "InvalidNextTokenException" case limitExceededException = "LimitExceededException" case objectNotFoundException = "ObjectNotFoundException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize ApplicationAutoScaling public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Concurrent updates caused an exception, for example, if you request an update to an Application Auto Scaling resource that already has a pending update. public static var concurrentUpdateException: Self { .init(.concurrentUpdateException) } /// Failed access to resources caused an exception. This exception is thrown when Application Auto Scaling is unable to retrieve the alarms associated with a scaling policy due to a client error, for example, if the role ARN specified for a scalable target does not have permission to call the CloudWatch DescribeAlarms on your behalf. public static var failedResourceAccessException: Self { .init(.failedResourceAccessException) } /// The service encountered an internal error. public static var internalServiceException: Self { .init(.internalServiceException) } /// The next token supplied was invalid. public static var invalidNextTokenException: Self { .init(.invalidNextTokenException) } /// A per-account resource limit is exceeded. For more information, see Application Auto Scaling Limits. public static var limitExceededException: Self { .init(.limitExceededException) } /// The specified object could not be found. For any operation that depends on the existence of a scalable target, this exception is thrown if the scalable target with the specified service namespace, resource ID, and scalable dimension does not exist. For any operation that deletes or deregisters a resource, this exception is thrown if the resource cannot be found. public static var objectNotFoundException: Self { .init(.objectNotFoundException) } /// An exception was thrown for a validation issue. Review the available parameters for the API request. public static var validationException: Self { .init(.validationException) } } extension ApplicationAutoScalingErrorType: Equatable { public static func == (lhs: ApplicationAutoScalingErrorType, rhs: ApplicationAutoScalingErrorType) -> Bool { lhs.error == rhs.error } } extension ApplicationAutoScalingErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
dd9d506285da841ff90be4f3b690918f
51.28
372
0.720224
5.327446
false
false
false
false
CoderJackyHuang/IOSCallJsOrJsCallIOS
JavaScriptAndSwift/JavaScriptAndSwift/ViewController.swift
1
3622
// // ViewController.swift // JavaScriptAndSwift // // Created by huangyibiao on 15/10/13. // Copyright © 2015年 huangyibiao. All rights reserved. // import UIKit import JavaScriptCore // All methods that should apply in Javascript, should be in the following protocol. @objc protocol JavaScriptSwiftDelegate: JSExport { func callSystemCamera(); func showAlert(title: String, msg: String); func callWithDict(dict: [String: AnyObject]) func jsCallObjcAndObjcCallJsWithDict(dict: [String: AnyObject]); } @objc class JSObjCModel: NSObject, JavaScriptSwiftDelegate { weak var controller: UIViewController? weak var jsContext: JSContext? func callSystemCamera() { print("js call objc method: callSystemCamera"); let jsFunc = self.jsContext?.objectForKeyedSubscript("jsFunc"); jsFunc?.callWithArguments([]); } func showAlert(title: String, msg: String) { dispatch_async(dispatch_get_main_queue()) { () -> Void in let alert = UIAlertController(title: title, message: msg, preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "ok", style: .Default, handler: nil)) self.controller?.presentViewController(alert, animated: true, completion: nil) } } // JS调用了我们的方法 func callWithDict(dict: [String : AnyObject]) { print("js call objc method: callWithDict, args: %@", dict) } // JS调用了我们的就去 func jsCallObjcAndObjcCallJsWithDict(dict: [String : AnyObject]) { print("js call objc method: jsCallObjcAndObjcCallJsWithDict, args: %@", dict) let jsParamFunc = self.jsContext?.objectForKeyedSubscript("jsParamFunc"); let dict = NSDictionary(dictionary: ["age": 18, "height": 168, "name": "lili"]) jsParamFunc?.callWithArguments([dict]) } } class ViewController: UIViewController, UIWebViewDelegate { var webView: UIWebView! var jsContext: JSContext? override func viewDidLoad() { super.viewDidLoad() self.webView = UIWebView(frame: self.view.bounds); self.view.addSubview(self.webView) self.webView.delegate = self self.webView.scalesPageToFit = true; let url = NSBundle.mainBundle().URLForResource("test", withExtension: "html") let request = NSURLRequest(URL: url!) self.webView.loadRequest(request) // 我们可以不通过模型来调用方法,也可以直接调用方法 let context = JSContext() context.evaluateScript("var num = 10") context.evaluateScript("function square(value) { return value * 2}") // 直接调用 let squareValue = context.evaluateScript("square(num)") print(squareValue) // 通过下标来获取到JS方法。 let squareFunc = context.objectForKeyedSubscript("square") print(squareFunc.callWithArguments(["10"]).toString()); } // MARK: - UIWebViewDelegate func webViewDidFinishLoad(webView: UIWebView) { let context = webView.valueForKeyPath("documentView.webView.mainFrame.javaScriptContext") as? JSContext let model = JSObjCModel() model.controller = self model.jsContext = context self.jsContext = context // 这一步是将OCModel这个模型注入到JS中,在JS就可以通过OCModel调用我们公暴露的方法了。 self.jsContext?.setObject(model, forKeyedSubscript: "OCModel") let url = NSBundle.mainBundle().URLForResource("test", withExtension: "html") self.jsContext?.evaluateScript(try? String(contentsOfURL: url!, encoding: NSUTF8StringEncoding)); self.jsContext?.exceptionHandler = { (context, exception) in print("exception @", exception) } } }
mit
99a8d024b458527c9f096034a280f6f3
31.809524
107
0.706821
4.180825
false
false
false
false
justin999/gitap
gitap/Issue.swift
1
2738
// // Issue.swift // gitap // // Created by Koichi Sato on 1/4/17. // Copyright © 2017 Koichi Sato. All rights reserved. // import Foundation /* [ { "id": 1, "url": "https://api.github.com/repos/octocat/Hello-World/issues/1347", "repository_url": "https://api.github.com/repos/octocat/Hello-World", "labels_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/labels{/name}", "comments_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/comments", "events_url": "https://api.github.com/repos/octocat/Hello-World/issues/1347/events", "html_url": "https://github.com/octocat/Hello-World/issues/1347", "number": 1347, "state": "open", "title": "Found a bug", "body": "I'm having a problem with this.", "user": { ... }, "labels": [ { .... } ], "assignee": { ... }, "milestone": { ... }, "locked": false, "comments": 0, "pull_request": { "url": "https://api.github.com/repos/octocat/Hello-World/pulls/1347", "html_url": "https://github.com/octocat/Hello-World/pull/1347", "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch" }, "closed_at": null, "created_at": "2011-04-22T13:33:48Z", "updated_at": "2011-04-22T13:33:48Z" } ] */ struct Issue: JSONDecodable { var id: Int var url: String var title: String var body: String? var user: User var created_at: Date? var updated_at: Date? init(json: Any) throws { guard let dictionary = json as? [String: Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let userObject = dictionary["user"] else { throw JSONDecodeError.missingValue(key: "user", actualValue: dictionary["user"]) } let dateFormatter = Utils.dateFormatter() do { self.id = try Utils.getValue(from: dictionary, with: "id") self.url = try Utils.getValue(from: dictionary, with: "url") self.title = try Utils.getValue(from: dictionary, with: "title") self.body = dictionary["body"] as? String self.user = try User(json: userObject) // TODO:ここのcreated at とupdated_atをどうするかは要検討 // self.created_at = dateFormatter.date(from: dictionary["created_at"] as? String) } catch { throw error } } }
mit
b4604db7e93c81f29781310c878735e8
30.5
99
0.546696
3.680707
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/SystemManager/Manager/View/MJRefreshManager.swift
1
3291
// // MJRefreshManager.swift // BeeFun // // Created by WengHengcong on 2017/4/13. // Copyright © 2017年 JungleSong. All rights reserved. // import UIKit import MJRefresh protocol MJRefreshManagerAction: class { func headerRefresh() func footerRefresh() } class MJRefreshManager: NSObject { weak var delegate: MJRefreshManagerAction? override init() { super.init() } /// 头部刷新控件 /// /// - Returns: <#return value description#> func header() -> MJRefreshNormalHeader { let header = MJRefreshNormalHeader() header.lastUpdatedTimeLabel.isHidden = true header.stateLabel.isHidden = true // header.setTitle(kHeaderIdelTIP.localized, for: .idle) // header.setTitle(kHeaderPullTip, for: .pulling) // header.setTitle(kHeaderPullingTip, for: .refreshing) header.setRefreshingTarget(self, refreshingAction:#selector(mj_headerRefresh)) return header } /// 头部刷新控件 /// /// - Parameters: /// - target: <#target description#> /// - action: 刷新回调方法 /// - Returns: <#return value description#> func header(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshNormalHeader { let header = MJRefreshNormalHeader() header.lastUpdatedTimeLabel.isHidden = true header.stateLabel.isHidden = true // header.setTitle(kHeaderIdelTIP, for: .idle) // header.setTitle(kHeaderPullTip, for: .pulling) // header.setTitle(kHeaderPullingTip, for: .refreshing) header.setRefreshingTarget(target, refreshingAction:action) return header } /// 内部代理方法 @objc func mj_headerRefresh() { if self.delegate != nil { self.delegate?.headerRefresh() } } /// 底部加载控件 /// /// - Returns: <#return value description#> func footer() -> MJRefreshAutoNormalFooter { let footer = MJRefreshAutoNormalFooter() // footer.isAutomaticallyHidden = true // footer.setTitle(kFooterIdleTip, for: .idle) // footer.setTitle(kFooterLoadTip, for: .refreshing) // footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData) footer.setRefreshingTarget(self, refreshingAction:#selector(mj_footerRefresh)) footer.stateLabel.isHidden = true footer.isRefreshingTitleHidden = true return footer } /// 底部加载控件 /// /// - Parameters: /// - target: <#target description#> /// - action: 加载回调方法 /// - Returns: <#return value description#> func footer(_ target: Any!, refreshingAction action: Selector!) -> MJRefreshAutoNormalFooter { let footer = MJRefreshAutoNormalFooter() // footer.setTitle(kFooterIdleTip, for: .idle) // footer.setTitle(kFooterLoadTip, for: .refreshing) // footer.setTitle(kFooterLoadNoDataTip, for: .noMoreData) footer.setRefreshingTarget(target, refreshingAction:action) footer.stateLabel.isHidden = true footer.isRefreshingTitleHidden = true return footer } /// 内部代理方法 @objc func mj_footerRefresh() { if self.delegate != nil { self.delegate?.footerRefresh() } } }
mit
c09a549d462a67e9603108232d90cc5b
30.294118
98
0.643484
4.427184
false
false
false
false
Ribeiro/SwiftEventBus
libs/Alamofire-xcode-6.3/Tests/RequestTests.swift
1
7103
// RequestTests.swift // // Copyright (c) 2014 Alamofire (http://alamofire.org) // // 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 Alamofire import XCTest class AlamofireRequestInitializationTestCase: XCTestCase { func testRequestClassMethodWithMethodAndURL() { let URL = "http://httpbin.org/" let request = Alamofire.request(.GET, URL) XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request.URL!, NSURL(string: URL)!, "request URL should be equal") XCTAssertNil(request.response, "response should be nil") } func testRequestClassMethodWithMethodAndURLAndParameters() { let URL = "http://httpbin.org/get" let request = Alamofire.request(.GET, URL, parameters: ["foo": "bar"]) XCTAssertNotNil(request.request, "request should not be nil") XCTAssertNotEqual(request.request.URL!, NSURL(string: URL)!, "request URL should be equal") XCTAssertEqual(request.request.URL!.query!, "foo=bar", "query is incorrect") XCTAssertNil(request.response, "response should be nil") } } class AlamofireRequestResponseTestCase: XCTestCase { func testRequestResponse() { let URL = "http://httpbin.org/get" let serializer = Alamofire.Request.stringResponseSerializer(encoding: NSUTF8StringEncoding) let expectation = expectationWithDescription("\(URL)") Alamofire.request(.GET, URL, parameters: ["foo": "bar"]) .response(serializer: serializer){ (request, response, string, error) in expectation.fulfill() XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(string, "string should not be nil") XCTAssertNil(error, "error should be nil") } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } } } class AlamofireRequestDescriptionTestCase: XCTestCase { func testRequestDescription() { let URL = "http://httpbin.org/get" let request = Alamofire.request(.GET, URL) XCTAssertEqual(request.description, "GET http://httpbin.org/get", "incorrect request description") let expectation = expectationWithDescription("\(URL)") request.response { (_, response,_,_) in expectation.fulfill() XCTAssertEqual(request.description, "GET http://httpbin.org/get (\(response!.statusCode))", "incorrect request description") } waitForExpectationsWithTimeout(10) { (error) in XCTAssertNil(error, "\(error)") } } } class AlamofireRequestDebugDescriptionTestCase: XCTestCase { let manager: Alamofire.Manager = { let manager = Alamofire.Manager(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) manager.startRequestsImmediately = false return manager }() // MARK: - func testGETRequestDebugDescription() { let URL = "http://httpbin.org/get" let request = manager.request(.GET, URL) let components = cURLCommandComponents(request) XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal") XCTAssert(!contains(components, "-X"), "command should not contain explicit -X flag") XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal") } func testPOSTRequestDebugDescription() { let URL = "http://httpbin.org/post" let request = manager.request(.POST, URL) let components = cURLCommandComponents(request) XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal") XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag") XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal") } func testPOSTRequestWithJSONParametersDebugDescription() { let URL = "http://httpbin.org/post" let request = manager.request(.POST, URL, parameters: ["foo": "bar"], encoding: .JSON) let components = cURLCommandComponents(request) XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal") XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag") XCTAssert(request.debugDescription.rangeOfString("-H \"Content-Type: application/json\"") != nil) XCTAssert(request.debugDescription.rangeOfString("-d \"{\\\"foo\\\":\\\"bar\\\"}\"") != nil) XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal") } // Temporarily disabled on OS X due to build failure for CocoaPods // See https://github.com/CocoaPods/swift/issues/24 #if !os(OSX) func testPOSTRequestWithCookieDebugDescription() { let URL = "http://httpbin.org/post" let properties = [ NSHTTPCookieDomain: "httpbin.org", NSHTTPCookiePath: "/post", NSHTTPCookieName: "foo", NSHTTPCookieValue: "bar", ] let cookie = NSHTTPCookie(properties: properties)! manager.session.configuration.HTTPCookieStorage?.setCookie(cookie) let request = manager.request(.POST, URL) let components = cURLCommandComponents(request) XCTAssert(components[0..<3] == ["$", "curl", "-i"], "components should be equal") XCTAssert(components[3..<5] == ["-X", "POST"], "command should contain explicit -X flag") XCTAssert(components[5..<6] == ["-b"], "command should contain -b flag") XCTAssert(components.last! == "\"\(URL)\"", "URL component should be equal") } #endif // MARK: - private func cURLCommandComponents(request: Request) -> [String] { return request.debugDescription.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).filter { $0 != "" && $0 != "\\" } } }
mit
7fa631cb778cdea287bc055250558d57
42.576687
161
0.660566
4.805819
false
true
false
false
inket/stts
stts/Services/Super/StatusioV1Service.swift
1
2331
// // StatusioV1Service.swift // stts // import Foundation typealias StatusioV1Service = BaseStatusioV1Service & RequiredServiceProperties & RequiredStatusioV1Properties protocol RequiredStatusioV1Properties { var statusPageID: String { get } } class BaseStatusioV1Service: BaseService { private enum StatusioV1Status: Int { case operational = 100 case plannedMaintenance = 200 case degradedPerformance = 300 case partialServiceDisruption = 400 case serviceDisruption = 500 case securityEvent = 600 var serviceStatus: ServiceStatus { switch self { case .operational: return .good case .plannedMaintenance: return .maintenance case .degradedPerformance: return .minor case .partialServiceDisruption: return .minor case .serviceDisruption, .securityEvent: return .major } } } override func updateStatus(callback: @escaping (BaseService) -> Void) { guard let realSelf = self as? StatusioV1Service else { fatalError("BaseStatusioV1Service should not be used directly.") } let statusURL = URL(string: "https://api.status.io/1.0/status/\(realSelf.statusPageID)")! loadData(with: statusURL) { [weak self] data, _, error in guard let strongSelf = self else { return } defer { callback(strongSelf) } guard let data = data else { return strongSelf._fail(error) } let json = try? JSONSerialization.jsonObject(with: data, options: []) guard let dict = json as? [String: Any], let resultJSON = dict["result"] as? [String: Any], let statusOverallJSON = resultJSON["status_overall"] as? [String: Any], let statusCode = statusOverallJSON["status_code"] as? Int, let status = StatusioV1Status(rawValue: statusCode), let statusMessage = statusOverallJSON["status"] as? String else { return strongSelf._fail("Unexpected data") } self?.status = status.serviceStatus self?.message = statusMessage } } }
mit
9f81d45b3cc4a706955ae1a50f57b7b4
33.279412
110
0.593737
4.846154
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Filters.playground/Pages/Moog Ladder Filter Operation.xcplaygroundpage/Contents.swift
1
661
//: ## Moog Ladder Filter Operation //: import AudioKitPlaygrounds import AudioKit let file = try AKAudioFile(readFileName: playgroundAudioFiles[0]) let player = try AKAudioPlayer(file: file) player.looping = true let effect = AKOperationEffect(player) { player, _ in let frequency = AKOperation.sineWave(frequency: 1).scale(minimum: 500, maximum: 1_000) let resonance = abs(AKOperation.sineWave(frequency: 0.3)) * 0.95 return player.moogLadderFilter(cutoffFrequency: frequency, resonance: resonance) * 3 } AudioKit.output = effect AudioKit.start() player.play() import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true
mit
f97879d359cd15fad48fe0630fc046cd
27.73913
90
0.770045
4.237179
false
false
false
false
zybug/firefox-ios
ClientTests/TabManagerTests.swift
4
2448
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import XCTest import Shared import Storage import WebKit public class TabManagerMockProfile: MockProfile { override func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> { return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs) } } class TabManagerTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testTabManagerStoresChangesInDB() { let profile = TabManagerMockProfile() let manager = TabManager(defaultNewTabRequest: NSURLRequest(URL: NSURL(fileURLWithPath: "http://localhost")), profile: profile) let configuration = WKWebViewConfiguration() configuration.processPool = WKProcessPool() // test that non-private tabs are saved to the db // add some non-private tabs to the tab manager for _ in 0..<3 { let tab = Browser(configuration: configuration) manager.configureTab(tab, request: NSURLRequest(URL: NSURL(string: "http://yahoo.com")!), flushToDisk: false, zombie: false, restoring: false) } manager.storeChanges() let remoteTabs = profile.remoteClientsAndTabs.getTabsForClientWithGUID(nil).value.successValue let count = remoteTabs?.count XCTAssertEqual(count, 3) // now test that the database contains 3 tabs // test that private tabs are not saved to the DB // private tabs are only available in iOS9 so don't execute this part of the test if we're testing against < iOS9 if #available(iOS 9, *) { // create some private tabs for _ in 0..<3 { let tab = Browser(configuration: configuration, isPrivate: true) manager.configureTab(tab, request: NSURLRequest(URL: NSURL(string: "http://yahoo.com")!), flushToDisk: false, zombie: false, restoring: false) } manager.storeChanges() // now test that the database still contains only 3 tabs let remoteTabs = profile.remoteClientsAndTabs.getTabsForClientWithGUID(nil).value.successValue let count = remoteTabs?.count XCTAssertEqual(count ?? 0, 3) } } }
mpl-2.0
4d97de2ba807ca3b6e6a2cc135ee553b
36.661538
158
0.657271
4.837945
false
true
false
false
swiftde/22-AnimationCoreMotion
Animator-Tutorial/Animator-Tutorial/ViewController.swift
2
3960
// // ViewController.swift // Animator-Tutorial // // Created by Benjamin Herzog on 30.07.14. // Copyright (c) 2014 Benjamin Herzog. All rights reserved. // import UIKit import CoreMotion var MAX_X: CGFloat = 0 var MAX_Y: CGFloat = 0 let BOX_SIZE: CGFloat = 5 let NUMBER_OF_BOXES = 400 class ViewController: UIViewController { var boxes = [UIView]() var animator: UIDynamicAnimator? let gravity = UIGravityBehavior() let collider = UICollisionBehavior() let itemBehavior = UIDynamicItemBehavior() let motionQueue = NSOperationQueue() let motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() MAX_X = view.bounds.size.width - BOX_SIZE MAX_Y = view.bounds.size.height - BOX_SIZE createAnimator() generateBoxes(NUMBER_OF_BOXES) } func createAnimator() { animator = UIDynamicAnimator(referenceView: view) gravity.gravityDirection = CGVectorMake(0, 0.8) animator?.addBehavior(gravity) collider.translatesReferenceBoundsIntoBoundary = true animator?.addBehavior(collider) itemBehavior.friction = 0.3 itemBehavior.elasticity = 0.6 animator?.addBehavior(itemBehavior) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) motionManager.startDeviceMotionUpdatesToQueue(motionQueue, withHandler: { motion,error in if error != nil { println("Error: \(error.localizedDescription)") return } let grav = motion.gravity let x = CGFloat(grav.x) let y = CGFloat(grav.y) var p = CGPoint(x: x, y: y) var orientation = UIApplication.sharedApplication().statusBarOrientation switch orientation { case .LandscapeLeft: var t = p.x p.x = 0 - p.y p.y = t case .LandscapeRight: var t = p.x p.x = p.y p.y = 0 - t case .PortraitUpsideDown: p.x *= -1 p.x *= -1 default: break } self.gravity.gravityDirection = CGVectorMake(p.x, 0 - p.y) }) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) motionManager.stopDeviceMotionUpdates() } func generateBoxes(number: Int) { for i in 0..<number { let newBox = UIView(frame: randomRect()) newBox.backgroundColor = UIColor.randomColor() view.addSubview(newBox) gravity.addItem(newBox) collider.addItem(newBox) itemBehavior.addItem(newBox) boxes.append(newBox) } } func randomRect() -> CGRect { var ret = CGRect(x: 0, y: 0, width: BOX_SIZE, height: BOX_SIZE) do { let x = CGFloat(rand()) % MAX_X let y = CGFloat(rand()) % MAX_Y ret = CGRect(x: x, y: y, width: BOX_SIZE, height: BOX_SIZE) } while(!doesNotCollide(ret)) return ret } func doesNotCollide(rect: CGRect) -> Bool { for box in boxes { if(CGRectIntersectsRect(box.frame, rect)) { return false } } return true } } extension UIColor { class func randomColor() -> UIColor { let redValue = Float(rand() % 255) / 255 let greenValue = Float(rand() % 255) / 255 let blueValue = Float(rand() % 255) / 255 return UIColor(red: CGFloat(redValue), green: CGFloat(greenValue), blue: CGFloat(blueValue), alpha: 1) } }
gpl-2.0
57b8876287b8f1ecac9d48edefddf8a9
24.063291
110
0.538384
4.736842
false
false
false
false
anzfactory/QiitaCollection
QiitaCollection/EntryCollectionViewController.swift
1
12884
// // EntryCollectionViewController.swift // QiitaCollection // // Created by ANZ on 2015/02/07. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit import SABlurImageView class EntryCollectionViewController: BaseViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { enum ListType : Int { case New = 1, Search = 2, WeekRanking = 3 } // MARK: UI @IBOutlet weak var collectionView: BaseCollectionView! // MARK: プロパティ var query: String = "" var ShowType: ListType = .New var backgroundImageView: SABlurImageView? = nil // MARK: ライフサイクル override func viewDidLoad() { super.viewDidLoad() let longPressGesture: UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress:") self.collectionView.addGestureRecognizer(longPressGesture) self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.setupRefreshControl { () -> Void in self.refresh() } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // クエリが指定されていたら、保存用のボタンを表示 if !self.query.isEmpty { self.displaySaveSearchCondition() } if self.afterDidLoad { refresh() } // view coverが設定されていたら画像セット if UserDataManager.sharedInstance.hasImageForViewCover() { if self.backgroundImageView != nil { self.backgroundImageView!.removeFromSuperview() } self.backgroundImageView = SABlurImageView(image: UserDataManager.sharedInstance.imageForViewCover()!) if let imageView = self.backgroundImageView { imageView.frame = self.view.frame imageView.contentMode = UIViewContentMode.ScaleAspectFill imageView.addBlurEffect(30, times: 3) self.view.addSubview(imageView) self.view.sendSubviewToBack(imageView) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: メソッド func displaySaveSearchCondition() { let save: UIBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_item_lock"), style: UIBarButtonItemStyle.Plain, target: self, action: "confirmSaveSearchCondition") self.navigationItem.rightBarButtonItem = save save.showGuide(GuideManager.GuideType.SearchConditionSaveIcon) } func refresh() { if !self.isViewLoaded() {return} self.collectionView.page = 1 self.load() } func load() { NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowLoadingWave.rawValue, object: nil) let fin = { (total:Int, items:[EntryEntity]) -> Void in self.collectionView.loadedItems(total, items: items, isError: false, isAppendable: { (item: EntryEntity) -> Bool in return !self.account.existsMuteUser(item.postUser.id) }) NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.HideLoadingWave.rawValue, object: nil) } switch (self.ShowType) { case .New: self.account.newEntries(self.collectionView.page, completion: fin) case .Search: self.account.searchEntries(self.collectionView.page, query: self.query, completion: fin) case .WeekRanking: self.account.weekRanking({ (items) -> Void in self.collectionView.loadedItems(items, isError: items.count == 0) NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.HideLoadingWave.rawValue, object: nil) return }) } } func longPress(gesture: UILongPressGestureRecognizer) { if gesture.state != UIGestureRecognizerState.Began || self.ShowType == .WeekRanking { return } let tapPoint: CGPoint = gesture.locationInView(self.collectionView) let tapIndexPath: NSIndexPath? = self.collectionView.indexPathForItemAtPoint(tapPoint) if tapIndexPath == nil { // collection view 領域外をタップしたってこと return } let tapEntry: EntryEntity = self.collectionView.items[tapIndexPath!.row] as! EntryEntity let actions: [UIAlertAction] = [ UIAlertAction(title: "投稿詳細", style: .Default, handler: { (UIAlertAction) -> Void in self.moveEntryDetail(tapEntry) }), UIAlertAction(title: "コメント", style: .Default, handler: { (UIAlertAction) -> Void in self.moveEntryComment(tapEntry) }), UIAlertAction(title: "ストックユーザー", style: .Default, handler: { (uialertAction) -> Void in self.moveStockers(tapEntry) }), UIAlertAction(title: "タグ", style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in self.openTagList(tapEntry) }), UIAlertAction(title: tapEntry.postUser.displayName, style: .Default, handler: { (UIAlertAction) -> Void in self.moveUserDetail(tapEntry.postUser.id) }), UIAlertAction(title: "キャンセル", style: .Cancel, handler: { (UIAlertAction) -> Void in }) ] // TODO: そのほかメニュー表示 (記事をストックしているユーザーリスト) NSNotificationCenter.defaultCenter() .postNotificationName(QCKeys.Notification.ShowAlertController.rawValue, object: self, userInfo: [ QCKeys.AlertController.Title.rawValue: tapEntry.title + " " + tapEntry.postUser.displayName, QCKeys.AlertController.Description.rawValue: tapEntry.beginning, QCKeys.AlertController.Actions.rawValue: actions ]) } func moveEntryDetail(entry: EntryEntity) { let vc: EntryDetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EntryDetailVC") as! EntryDetailViewController vc.displayEntry = entry NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func moveEntryDetail(entryId: String) { let vc: EntryDetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EntryDetailVC") as! EntryDetailViewController vc.displayEntryId = entryId NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func moveEntryComment(entry: EntryEntity) { let vc: CommentListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("CommentsVC") as! CommentListViewController vc.displayEntryId = entry.id vc.displayEntryTitle = entry.title NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func moveStockers(entry: EntryEntity) { let vc: UserListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UserListVC") as! UserListViewController vc.listType = .Stockers vc.targetEntryId = entry.id NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func moveUserDetail(userId: String) { let vc: UserDetailViewController = self.storyboard?.instantiateViewControllerWithIdentifier("UserDetailVC") as! UserDetailViewController vc.displayUserId = userId NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: vc) } func confirmSaveSearchCondition() { let doAciton: AlertViewSender.AlertActionWithText = {(sender: UITextField) -> Void in self.account.saveQuery(self.query, title: sender.text) Toast.show("検索条件を保存しました", style: JFMinimalNotificationStytle.StyleSuccess) NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ReloadViewPager.rawValue, object: nil) } let validation: AlertViewSender.AlertValidation = {(sender: UITextField) -> Bool in return !sender.text.isEmpty } let action: AlertViewSender = AlertViewSender(validation: validation, action: doAciton, title: "OK") let args: [NSString: AnyObject] = [ QCKeys.AlertView.Title.rawValue: "入力", QCKeys.AlertView.Message.rawValue: "保存名を入力してください。以降、この名前で表示されるようになります", QCKeys.AlertView.YesAction.rawValue: action, QCKeys.AlertView.NoTitle.rawValue: "Cancel", QCKeys.AlertView.PlaceHolder.rawValue: "保存名入力" ] NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.ShowAlertInputText.rawValue, object: nil, userInfo: args) } func openTagList(entity: EntryEntity) { let vc: SimpleListViewController = self.storyboard?.instantiateViewControllerWithIdentifier("SimpleListVC") as! SimpleListViewController vc.items = entity.toTagList() vc.title = "タグリスト" vc.swipableCell = false vc.tapCallback = {(vc: SimpleListViewController, index: Int) -> Void in // タグで検索 let selectedTag: String = vc.items[index] vc.dismissGridMenuAnimated(true, completion: { () -> Void in let searchVC: EntryCollectionViewController = self.storyboard?.instantiateViewControllerWithIdentifier("EntryCollectionVC") as! EntryCollectionViewController searchVC.title = "タグ:" + selectedTag searchVC.query = "tag:" + selectedTag NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PushViewController.rawValue, object: searchVC) }) } NSNotificationCenter.defaultCenter().postNotificationName(QCKeys.Notification.PresentedViewController.rawValue, object: vc) } // MARK: UICollectionViewDataSource func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.collectionView.items.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell: EntryCollectionViewCell = self.collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! EntryCollectionViewCell if let entry: EntryEntity = self.collectionView.items[indexPath.row] as? EntryEntity { cell.display(entry) } else if let rank: RankEntity = self.collectionView.items[indexPath.row] as? RankEntity { cell.display(rank) } return cell } // MARK: UICollectionViewDelegate func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if self.collectionView.page != NSNotFound && (indexPath.row + 1) >= self.collectionView.items.count { self.load() } if indexPath.row == 0 && ShowType != .WeekRanking { cell.showGuide(GuideManager.GuideType.EntryCollectionCell, inView: self.view) } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let tapEntry: EntryEntity = self.collectionView.items[indexPath.row] as? EntryEntity { self.moveEntryDetail(tapEntry) } else if let rank: RankEntity = self.collectionView.items[indexPath.row] as? RankEntity { self.moveEntryDetail(rank.entryId) } } // MARK: UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let colNum: CGFloat = self.view.frame.size.width >= 700 ? 3.0 : 2.0 let width: CGFloat = (self.view.frame.size.width - (1.0 + colNum)) / colNum return CGSize(width: width, height: width) } }
mit
734aa65031ef392ded5f1571c070eabc
44.362319
178
0.665096
5.173554
false
false
false
false
d4rkl0rd3r3b05/Data_Structure_And_Algorithm
GeeksForGeeks_LeadersInArray.swift
1
742
/* * An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader */ public func getLeaders<T : Comparable>(arrayToBeProcessed : [T]) -> [T]? { guard arrayToBeProcessed.count > 0 else { return nil } var leadersArray : [T]? var highestRightElement : T? for element in arrayToBeProcessed.reversed() { if leadersArray == nil { leadersArray = [element] highestRightElement = element } else { if element > highestRightElement! { leadersArray!.append(element) highestRightElement = element } } } return leadersArray }
mit
cf3cdc5b00297e842d9742eb29c6dd12
26.481481
127
0.58221
4.52439
false
false
false
false
superk589/CGSSGuide
DereGuide/Toolbox/EventInfo/Controller/EventChartController.swift
2
5520
// // EventChartController.swift.swift // DereGuide // // Created by zzk on 2017/1/24. // Copyright © 2017 zzk. All rights reserved. // import UIKit import Charts import SnapKit protocol RankingLineChartRepresentable { var chartEntries: [Int: [ChartDataEntry]] { get } var xAxis: [String] { get } var xAxisDetail: [String] { get } var borders: [Int] { get } var xAxisDates: [Date] { get } } extension EventRanking: RankingLineChartRepresentable { var chartEntries: [Int: [ChartDataEntry]] { var borderEntries = [Int: [ChartDataEntry]]() for border in borders { var entries = [ChartDataEntry]() for (index, item) in list.enumerated() { entries.append(ChartDataEntry(x: Double(index), y: Double(item[border]))) } borderEntries[border] = entries } return borderEntries } var xAxis: [String] { var strings = [String]() for i in 0..<list.count { let date = list[i].date.toDate(format: "yyyy-MM-dd'T'HH:mm:ssZZZZZ") var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = TimeZone.current let comp = gregorian.dateComponents([.day, .hour, .minute], from: date) let string = String.init(format: NSLocalizedString("%d日%d时", comment: ""), comp.day!, comp.hour!) strings.append(string) } return strings } var xAxisDetail: [String] { var strings = [String]() for i in 0..<list.count { let date = list[i].date.toDate(format: "yyyy-MM-dd'T'HH:mm:ssZZZZZ") var gregorian = Calendar(identifier: .gregorian) gregorian.timeZone = TimeZone.current let comp = gregorian.dateComponents([.day, .hour, .minute], from: date) let string = String.init(format: NSLocalizedString("%d日%d时%d分", comment: ""), comp.day!, comp.hour!, comp.minute!) strings.append(string) } return strings } var xAxisDates: [Date] { var dates = [Date]() for i in 0..<list.count { let date = list[i].date.toDate(format: "yyyy-MM-dd'T'HH:mm:ssZZZZZ") dates.append(date) } return dates } } class EventChartController: BaseViewController { var rankingList: RankingLineChartRepresentable! private struct Height { static let sv: CGFloat = Screen.height - 113 } override func viewDidLoad() { super.viewDidLoad() let chartView = LineChartView() view.addSubview(chartView) chartView.snp.makeConstraints { (make) in if #available(iOS 11.0, *) { make.edges.equalTo(view.safeAreaLayoutGuide) } else { make.top.equalTo(topLayoutGuide.snp.bottom) make.bottom.equalTo(bottomLayoutGuide.snp.top) make.left.right.equalToSuperview() } } var colors = ChartColorTemplates.vordiplom() var dataSets = [LineChartDataSet]() for border in rankingList.borders.prefix(5) { let set = LineChartDataSet.init(entries: rankingList.chartEntries[border] ?? [], label: String(border)) set.drawCirclesEnabled = false let color = colors.removeLast() set.setColor(color) set.lineWidth = 2 set.drawValuesEnabled = false set.highlightColor = color dataSets.append(set) } let data = LineChartData.init(dataSets: dataSets) chartView.data = data chartView.xAxis.valueFormatter = IndexAxisValueFormatter.init(values: rankingList.xAxis) chartView.chartDescription?.text = "" chartView.chartDescription?.font = UIFont.systemFont(ofSize: 14) chartView.chartDescription?.textColor = UIColor.darkGray chartView.xAxis.labelPosition = .bottom chartView.rightAxis.enabled = false chartView.xAxis.granularity = 1 chartView.scaleYEnabled = false chartView.leftAxis.drawBottomYLabelEntryEnabled = false let nf = NumberFormatter() nf.positiveFormat = "0K" nf.multiplier = 0.001 chartView.leftAxis.valueFormatter = DefaultAxisValueFormatter.init(formatter: nf) chartView.leftAxis.axisMinimum = 0 let marker = BalloonMarker(color: UIColor(hex: 0x343D46), font: UIFont.boldSystemFont(ofSize: 12), textColor: UIColor.white, insets: UIEdgeInsets(top: 5, left: 7.0, bottom: 15, right: 7.0), in: chartView) marker.offset = CGPoint(x: 0, y: -5) marker.dataSource = self chartView.delegate = self } } extension EventChartController: ChartViewDelegate { func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) { // chartView.chartDescription?.text = "\(rankingList.xAxisDetail[Int(entry.x)])\(Int(entry.y))" } } extension EventChartController: BalloonMarkerDataSource { func balloonMarker(_ balloonMarker: BalloonMarker, stringForEntry entry: ChartDataEntry, highlight: Highlight) -> String { let date = rankingList.xAxisDates[Int(entry.x)] let dateString = DateFormatter.localizedString(from: date, dateStyle: .medium, timeStyle: .short) let scoreString = String(Int(round(entry.y))) return "\(dateString)\n\(scoreString)" } }
mit
894aed9147ea7ea7c2c8e0f2bdb3b1a2
35.973154
212
0.617898
4.478862
false
false
false
false
wltrup/iOS-Swift-Circular-Progress-View
CircularProgressView/ViewController.swift
2
3773
// // ViewController.swift // CircularProgressView // // Created by Wagner Truppel on 26/04/2015. // Copyright (c) 2015 Wagner Truppel. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var reloadButton: UIButton! private var dataItems = [NSIndexPath: DataItem]() private var clockwise = true private var reversed = false private var showPercs = true @IBAction func reloadBtnTapped() { reloadButton.enabled = false dataItems = [NSIndexPath: DataItem]() tableView.reloadData() } @IBAction func clockwiseBtnTapped(sender: UIButton) { sender.selected = !sender.selected clockwise = !sender.selected for row in 0..<DataLoader.dataSize() { let indexPath = NSIndexPath(forRow: row, inSection: 0) let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell cell?.progressView.clockwise = clockwise } } @IBAction func progressBtnTapped(sender: UIButton) { sender.selected = !sender.selected reversed = sender.selected for row in 0..<DataLoader.dataSize() { let indexPath = NSIndexPath(forRow: row, inSection: 0) let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell cell?.progressView.reversed = reversed } } @IBAction func percentBtnTapped(sender: UIButton) { sender.selected = !sender.selected showPercs = !sender.selected for row in 0..<DataLoader.dataSize() { let indexPath = NSIndexPath(forRow: row, inSection: 0) let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell cell?.progressView.showPercent = showPercs } } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DataLoader.dataSize() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellID") as? CustomCell cell?.dataItem = dataItems[indexPath] cell?.progressView.clockwise = clockwise cell?.progressView.reversed = reversed cell?.progressView.showPercent = showPercs return cell! } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if let customCell = cell as? CustomCell { if customCell.dataItem != nil { customCell.showContent(true, animated: true) } else { customCell.showContent(false, animated: false) DataLoader.loadDataForIndexPath(indexPath, delegate: self) } } } } extension ViewController: DataLoaderDelegate { func dataLoader(dataLoader: DataLoader, didUpdateDataWithPercentValue value: CGFloat) { let cell = tableView.cellForRowAtIndexPath(dataLoader.loaderIndexPath) as? CustomCell cell?.progressView.value = value } func dataLoaderDidFinishLoadingData(dataLoader: DataLoader) { let indexPath = dataLoader.loaderIndexPath let data = dataLoader.loaderData dataItems[indexPath] = data let cell = tableView.cellForRowAtIndexPath(indexPath) as? CustomCell cell?.dataItem = data if data != nil { cell?.showContent(true, animated: true) } let canReload = (dataItems.count == DataLoader.dataSize()) reloadButton.enabled = canReload } }
mit
4a69ecd91fd770458c5534ca457a768c
29.934426
107
0.658097
5.218534
false
false
false
false
untouchable741/Watches
Watches/WatchesPlayground.playground/Sources/Watches.swift
1
3039
// // Watches.swift // WatchesExample // // Created by HuuTaiVuong on 9/13/16. // Copyright © 2016 Huu Tai Vuong. All rights reserved. // import Foundation public class Watches { /** Callback closure type for tock function */ public typealias TockCallbackClosure = ((String, TimeInterval) -> Void) /** Default callback in case no callback closure specified in tock function */ public static var defaultTockCallbackClosure : TockCallbackClosure = { label , interval -> Void in if printElapsedTimeAutomatically { debugPrint("Elapsed interval for \(label) is \(interval)") } } /** Dictionary that saved tracked time stamps based on id */ static var trackedTimeStamps = [String : Date]() public static var printElapsedTimeAutomatically = true var label : String var startTime : Date? init(label: String) { self.label = label } } // MARK: Instance's tracking /** Chaining tracking e.g: Watches.create("id") .tick { - closure to track - } .tock () */ public extension Watches { /** Create watches instance with specific idenfitifer */ public static func create(label: String) -> Watches { let watchesInstance = Watches(label: label) return watchesInstance } /** Start tracking execution time for closure */ @discardableResult public func tick(closure: () -> Void) -> Watches { self.startTime = Date() closure() return self } /** Start collecting elapsed interval for specific watches's label */ @discardableResult public func tock(callBack: TockCallbackClosure = defaultTockCallbackClosure) -> TimeInterval { guard let validTickTime = startTime else { callBack(label, 0) return 0 } let elapsedTime = Date().timeIntervalSince(validTickTime) callBack(label, elapsedTime) return elapsedTime } } // MARK: Class's tracking /** Use with async callback or delegate e.g: Watches.tick("id") <- Execution code -> Watches.tock("id") */ public extension Watches { /** Start tracking timestamp for specific watches's label */ public static func tick(label: String) { trackedTimeStamps[label] = Date() } /** Collect elapsed interval for specific watches's label */ @discardableResult public static func tock(label: String, callback: TockCallbackClosure = defaultTockCallbackClosure) -> TimeInterval { guard let validTickTime = trackedTimeStamps[label] else { callback(label, 0) return 0 } let elapsedTime = Date().timeIntervalSince(validTickTime) trackedTimeStamps[label] = nil callback(label, elapsedTime) return elapsedTime } }
mit
5816674e90313f190b31fd6c2080da91
23.5
139
0.601053
4.732087
false
false
false
false
mactive/rw-courses-note
ProgrammingInSwift/ControlFlow.playground/Pages/SwitchChallenge.xcplaygroundpage/Contents.swift
1
1012
//: [Previous](@previous) import Foundation let lifeStage: String let age = 80 //switch age { //case ..<0: // lifeStage = "Not born yet" //case 0...2: // lifeStage = "Infant" //case 3...12: // lifeStage = "Child" //case 13...19: // lifeStage = "Teenager" //case 20...39: // lifeStage = "Adult" //case 40...60: // lifeStage = "Middle aged" //case 61...99: // lifeStage = "Eldery" //case let age: // fatalError("Unaccounted for age: \(age)") //} let name = "Jessy" switch (name, age) { case (name, ..<0): lifeStage = "\(name) is Not born yet" case (name, 0...2): lifeStage = "\(name) is Infant" case (name, 3...12): lifeStage = "\(name) is Child" case (name, 13...19): lifeStage = "\(name) is Teenager" case (name, 20...39): lifeStage = "\(name) is Adult" case (name, 40...60): lifeStage = "\(name) is Middle aged" case (name, 61...99): lifeStage = "\(name) is Eldery" case (_, let age): fatalError("Unaccounted for age): \(age)") } //: [Next](@next)
mit
b3f93b59d9837d46d226fb7d8b67a6f5
19.653061
47
0.56917
2.79558
false
false
false
false
wangyuxianglove/TestKitchen1607
Testkitchen1607/Testkitchen1607/classes/ingredient(食材)/recommend(推荐)/view/IngreBannerCell.swift
1
4467
// // IngreBannerCell.swift // Testkitchen1607 // // Created by qianfeng on 16/10/25. // Copyright © 2016年 zhb. All rights reserved. // import UIKit class IngreBannerCell: UITableViewCell { var jumpClosure:IngreJumpClourse? @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var pageControl: UIPageControl! //显示数据 var bannerArray:[IngreRecommendBanner]?{ didSet{ //显示数据 showData() } } //显示数据 private func showData(){ //滚动视图系统默认添加了一些子视图,删除子视图要考虑会不会影响 //删除之前的子视图 for sub in scrollView.subviews{ sub.removeFromSuperview() } //遍历添加图片 let cnt=bannerArray?.count if bannerArray?.count>0{ //滚动视图加约束 //创建一个容器视图 let containerView=UIView.creatView() scrollView.addSubview(containerView) containerView.snp_makeConstraints(closure: { (make) in make.edges.equalTo(scrollView) // 设置高度 make.height.equalTo(scrollView) }) //2.循环设置子视图的约束,子视图是添加到容器视图里面 var lastView:UIView?=nil for i in 0..<cnt!{ let model=bannerArray![i] //创建图片 let tmpImageView=UIImageView() let url=NSURL(string: model.banner_picture!) tmpImageView.kf_setImageWithURL(url, placeholderImage:UIImage(named:"sdefaultImage" ), optionsInfo: nil, progressBlock: nil, completionHandler: nil) containerView.addSubview(tmpImageView) //添加点击事件 tmpImageView.userInteractionEnabled=true tmpImageView.tag=200+i let g = UITapGestureRecognizer(target: self, action: #selector(taoImage(_:))) tmpImageView.addGestureRecognizer(g) //图片的约束 tmpImageView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(scrollView) if lastView==nil{ make.left.equalTo(containerView) }else{ make.left.equalTo((lastView?.snp_right)!) } }) lastView=tmpImageView } //3.修改container的宽度 containerView.snp_makeConstraints(closure: { (make) in make.right.equalTo(lastView!) }) //4.分页控件 pageControl.numberOfPages=cnt! } } func taoImage(g:UIGestureRecognizer){ let index=(g.view?.tag)!-200 //获取点击的数据 let banner=bannerArray![index] if jumpClosure != nil && banner.banner_link != nil{ jumpClosure!(banner.banner_link!) } } //创建cell的方法 class func creatBannerCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,bannerArray:Array<IngreRecommendBanner>?)->IngreBannerCell{ let cellId="ingreBannerCellId" var cell=tableView.dequeueReusableCellWithIdentifier(cellId) as? IngreBannerCell if nil == cell { //IngreBannerCell.xib cell=NSBundle.mainBundle().loadNibNamed("IngreBannerCell", owner: nil, options: nil).last as? IngreBannerCell } //显示数据 cell!.bannerArray=bannerArray return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension IngreBannerCell:UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index=scrollView.contentOffset.x/scrollView.bounds.size.width pageControl.currentPage=Int(index) } }
mit
dd02019b4909c83e5cbf17cd85e1bf9b
29.808824
164
0.550835
5.2375
false
false
false
false
shajrawi/swift
stdlib/public/core/StringCharacterView.swift
1
9269
//===--- StringCharacterView.swift - String's Collection of Characters ----===// // // 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 // //===----------------------------------------------------------------------===// // // String is-not-a Sequence or Collection, but it exposes a // collection of characters. // //===----------------------------------------------------------------------===// // FIXME(ABI)#70 : The character string view should have a custom iterator type // to allow performance optimizations of linear traversals. import SwiftShims extension String: BidirectionalCollection { /// A type that represents the number of steps between two `String.Index` /// values, where one value is reachable from the other. /// /// In Swift, *reachability* refers to the ability to produce one value from /// the other through zero or more applications of `index(after:)`. public typealias IndexDistance = Int public typealias SubSequence = Substring public typealias Element = Character /// The position of the first character in a nonempty string. /// /// In an empty string, `startIndex` is equal to `endIndex`. @inlinable @inline(__always) public var startIndex: Index { return _guts.startIndex } /// A string's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// In an empty string, `endIndex` is equal to `startIndex`. @inlinable @inline(__always) public var endIndex: Index { return _guts.endIndex } /// The number of characters in a string. @inline(__always) public var count: Int { return distance(from: startIndex, to: endIndex) } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Index) -> Index { _precondition(i < endIndex, "String index is out of bounds") // TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc. let stride = _characterStride(startingAt: i) let nextOffset = i._encodedOffset &+ stride let nextStride = _characterStride( startingAt: Index(_encodedOffset: nextOffset)) return Index( encodedOffset: nextOffset, characterStride: nextStride) } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. public func index(before i: Index) -> Index { _precondition(i > startIndex, "String index is out of bounds") // TODO: known-ASCII fast path, single-scalar-grapheme fast path, etc. let stride = _characterStride(endingAt: i) let priorOffset = i._encodedOffset &- stride return Index(encodedOffset: priorOffset, characterStride: stride) } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - Complexity: O(*n*), where *n* is the absolute value of `n`. @inlinable @inline(__always) public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // TODO: known-ASCII and single-scalar-grapheme fast path, etc. return _index(i, offsetBy: n) } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If `n > 0`, /// a limit that is less than `i` has no effect. Likewise, if `n < 0`, a /// limit that is greater than `i` has no effect. /// - Returns: An index offset by `n` from the index `i`, unless that index /// would be beyond `limit` in the direction of movement. In that case, /// the method returns `nil`. /// /// - Complexity: O(*n*), where *n* is the absolute value of `n`. @inlinable @inline(__always) public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // TODO: known-ASCII and single-scalar-grapheme fast path, etc. return _index(i, offsetBy: n, limitedBy: limit) } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. /// /// - Complexity: O(*n*), where *n* is the resulting distance. @inlinable @inline(__always) public func distance(from start: Index, to end: Index) -> IndexDistance { // TODO: known-ASCII and single-scalar-grapheme fast path, etc. return _distance(from: start, to: end) } /// Accesses the character at the given position. /// /// You can use the same indices for subscripting a string and its substring. /// For example, this code finds the first letter after the first space: /// /// let str = "Greetings, friend! How are you?" /// let firstSpace = str.firstIndex(of: " ") ?? str.endIndex /// let substr = str[firstSpace...] /// if let nextCapital = substr.firstIndex(where: { $0 >= "A" && $0 <= "Z" }) { /// print("Capital after a space: \(str[nextCapital])") /// } /// // Prints "Capital after a space: H" /// /// - Parameter i: A valid index of the string. `i` must be less than the /// string's end index. @inlinable @inline(__always) public subscript(i: Index) -> Character { _boundsCheck(i) let i = _guts.scalarAlign(i) let distance = _characterStride(startingAt: i) return _guts.errorCorrectedCharacter( startingAt: i._encodedOffset, endingAt: i._encodedOffset &+ distance) } @inlinable @inline(__always) internal func _characterStride(startingAt i: Index) -> Int { // Fast check if it's already been measured, otherwise check resiliently if let d = i.characterStride { return d } if i == endIndex { return 0 } return _guts._opaqueCharacterStride(startingAt: i._encodedOffset) } @inlinable @inline(__always) internal func _characterStride(endingAt i: Index) -> Int { if i == startIndex { return 0 } return _guts._opaqueCharacterStride(endingAt: i._encodedOffset) } } extension String { @_fixed_layout public struct Iterator: IteratorProtocol { @usableFromInline internal var _guts: _StringGuts @usableFromInline internal var _position: Int = 0 @usableFromInline internal var _end: Int @inlinable internal init(_ guts: _StringGuts) { self._end = guts.count self._guts = guts } @inlinable public mutating func next() -> Character? { guard _fastPath(_position < _end) else { return nil } let len = _guts._opaqueCharacterStride(startingAt: _position) let nextPosition = _position &+ len let result = _guts.errorCorrectedCharacter( startingAt: _position, endingAt: nextPosition) _position = nextPosition return result } } @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_guts) } }
apache-2.0
1d23983cc44d7e28edc01c787d546e35
35.781746
85
0.64268
4.163971
false
false
false
false
lightningkite/LKTabBarController
Pod/Classes/LKTabBarController.swift
1
6987
// // LKTabBarController.swift // // Created by Abraham Done on 3/18/16. // Copyright © 2016 LightningKite. All rights reserved. // import UIKit import SnapKit /** The button must implement this protocol inorder for LKTabBarController to interact with it and the view which will be attached to the button. The button can be formatted or function in any way as desired as long as it has these properties. */ public protocol LKTabBarButtonView { /// When the button is selected and its view is made active this will be true, it is false otherwise. var selected: Bool { get set } /// The index of the button which is set by the tab bar controller. var index: Int { get set } /// Any interaction with the controller will be done through the delegate. var delegate: LKButtonBarIndexDelegate? { get set } } /** This is how the button can interact with the tab bar to change the index and to set custom actions when the button is tapped. */ public protocol LKButtonBarIndexDelegate: class { /// The action to take when the button bar was tapped. The index is the button's own index. func buttonTapped(_ index: Int) /// In case the button needs access to the index of the tab bar controller var index: Int { get set } } /** Simple controller for making a custom tab bar. The buttons are fully customizable, with a simple protocol to implement. */ open class LKTabBarController: LKButtonBarIndexDelegate { // MARK: - Properties /// A button and view that will be paired together public typealias TabButtonViewPair = (button: LKTabBarButtonView, viewController: UIViewController) fileprivate typealias TabButtonNavPair = (button: LKTabBarButtonView, navController: UINavigationController) fileprivate var buttonPairs: [TabButtonNavPair] fileprivate let containerView: UIView fileprivate let parentView: UIViewController fileprivate let insets: UIEdgeInsets /** The initalizer for the tab bar controller - parameter buttonPairs: An array of TabButtonViewPairs - parameter parentView: The parent view of the the container view - parameter containerView: The container that will hold all the tabed views - parameter hideNavBar: Hide the internal navigation bar of the view controller, false by default - parameter insets: Set the insets of all the tabbed views, UIEdgeInsetsZero by default */ public init(buttonPairs: [TabButtonViewPair], parentView: UIViewController, containerView: UIView, hideNavBar: Bool = true, insets: UIEdgeInsets = UIEdgeInsets.zero) { self.buttonPairs = [] self.parentView = parentView self.containerView = containerView self.insets = insets for index in 0..<buttonPairs.count { let view = buttonPairs[index].viewController let navController = UINavigationController(rootViewController: view) navController.isNavigationBarHidden = hideNavBar var button = buttonPairs[index].button button.index = index button.selected = false button.delegate = self self.buttonPairs.append((button, navController)) } buttonTapped(0) } // MARK: - LKButtonBarIndexDelegate implementation /** Function the button can call to change the tab to itself (or another index if desired). - parameter index: The index to change */ open func buttonTapped(_ index: Int) { guard index >= 0 && index < buttonPairs.count else { return } guard self.index != index else { return } self.index = index for index in 0..<self.buttonPairs.count { self.buttonPairs[index].button.selected = false } var pair = self.buttonPairs[index] pair.button.selected = true self.activeViewController = pair.navController } /// The index of the views. It will only change the view to a view that is within the tab bar's range. public var index: Int = 0 { didSet { if index >= 0 && index < buttonPairs.count { buttonTapped(index) } } } // MARK: - Public facing view control /// Clear all the tabs open func clearTabs() { containerView.subviews.forEach { subView in subView.removeFromSuperview() } buttonPairs = [] } /// The currently active view controller public var navigationController: UINavigationController { return self.buttonPairs[index].navController } /// The top view controller of the currently active tab view public var topViewController: UIViewController? { let nav = self.buttonPairs[index].navController return nav.viewControllers.last } /// The number of view controllers are present on the currently active tab view public var topControllerStackCount: Int { let navControl = self.buttonPairs[index].navController return navControl.viewControllers.count } /// Pop the currently active tab view's view controller open func popTopViewControllerAnimated(_ animated: Bool = true) { let navControl = self.buttonPairs[index].navController navControl.popViewController(animated: animated) } /// Pop the currently active tab view to its root controller open func popTopViewControllerToRootAnimated(_ animated: Bool = true) { let navControl = self.buttonPairs[index].navController navControl.popToRootViewController(animated: animated) } // MARK: - Private functions (set active view) fileprivate var activeViewController: UIViewController? { didSet { removeInactiveViewController(oldValue) updateActiveViewController() } } fileprivate func removeInactiveViewController(_ inactiveViewController: UIViewController?) { if parentView.isViewLoaded { if let inActiveVC = inactiveViewController { inActiveVC.willMove(toParentViewController: nil) inActiveVC.view.removeFromSuperview() inActiveVC.removeFromParentViewController() } } } fileprivate func updateActiveViewController() { if parentView.isViewLoaded { if let activeVC = activeViewController { parentView.addChildViewController(activeVC) activeVC.view.frame = containerView.bounds containerView.addSubview(activeVC.view) activeVC.didMove(toParentViewController: parentView) activeVC.view.snp_makeConstraints { make in make.edges.equalTo(containerView).inset(self.insets) } } } } }
mit
5fd7a22d0bce1af0628025c1c0d8318c
36.55914
240
0.658317
5.280423
false
false
false
false
zxwWei/SwfitZeng
XWWeibo接收数据/XWWeibo/Classes/Module(公共模型)/XWUserAccount.swift
1
5705
// // XWUserAccount.swift // XWWeibo // // Created by apple on 15/10/29. // Copyright © 2015年 ZXW. All rights reserved. // import Foundation import UIKit class XWUserAccount: NSObject, NSCoding { //MARK: - define a userlogin method, when switch controller,we can get a true or false from it class func userLogin() -> Bool{ return XWUserAccount.loadAccount() != nil } // 返回值字段 字段类型 字段说明 // access_token string 用于调用access_token,接口获取授权后的access token。 // expires_in string access_token的生命周期,单位是秒数。 // remind_in string access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。 // uid string 当前授权用户的UID。 /// 用于调用access_token,接口获取授权后的access token。 var access_token: String? /// access_token的生命周期,单位是秒数。 var expires_in: NSTimeInterval = 0 { didSet{ expires_date = NSDate(timeIntervalSinceNow: expires_in) //print("expires_date:\(expires_date)") } } /// 当前授权用户的UID。 var uid: String? /// 过期时间 var expires_date: NSDate? /// 友好显示名称 var name: String? /// 头像 var avatar_large: String? // MARK: - 字典转模型 init(dict: [String: AnyObject]) { super.init() // 将字典里面的每一个属性给模型的每一个属性 setValuesForKeysWithDictionary(dict) } // 当字典里面的key在模型里面没有对应的属性 调用此方法 "remind_in"没用到 // ["access_token": 2.00z5K9aCRElhUB0255c5c664pnH2dC, "remind_in": 157679999, "uid": 2370926933, "expires_in": 157679999]) //override func setValue(value: AnyObject?, forKey key: String) {} // MArk: - 要用这个方法 override func setValue(value: AnyObject?, forUndefinedKey key: String) {} // 输出 override var description: String { return "access_token:\(access_token), expires_in:\(expires_in), uid:\(uid): expires_date:\(expires_date) name:\(name) avatar_large:\(avatar_large)" } // MArk: - 保存和读取 static let accountPath = NSSearchPathForDirectoriesInDomains( NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/Account.plist" // 保存 func saveAccount() { NSKeyedArchiver.archiveRootObject(self, toFile: XWUserAccount.accountPath) //print("XWUserAccount.accountPath:\(XWUserAccount.accountPath)") } /// 静态帐号 func loadAccount() -> XWUserAccount? reback a useraccuont private static var userAccount: XWUserAccount? //MARK:- 每次都进来解档账户 现在想只加载一次,保存到内存中以后访问内存中的帐号 // 读取 XWUserAccount?类方法 accountPath: 新的路径 class func loadAccount() -> XWUserAccount? { // 当内存中没有时才解档 if userAccount == nil{ userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? XWUserAccount } else{ // print("加载内存中的帐号") } //&& userAccount?.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending // 判断帐号是否过期 expires_date?.compare > nsdate返回的期限 if userAccount != nil { //print("帐号有效") return userAccount } //print("accountPath:\(accountPath)") return nil } // MARK: - 加载用户信息 不管成功失败都要告诉调用者 func loadUserinfo(finished:(error: NSError?) -> ()){ // 准备闭包 XWNetworkTool.shareInstance.loadUserinfo { (result, error) -> () in if (error != nil) || result == nil{ print("error\(error)") finished(error: error) print("加载用户数据失败") return } // 加载数据成功 将值赋给属性 self.name = result!["name"] as? String self.avatar_large = result!["avatar_large"] as? String // 保存到沙盒 self.saveAccount() // 同步属性到内存中 XWUserAccount.userAccount = self //print("XWUserAccount.userAccount\(XWUserAccount.userAccount)") finished(error: nil) } } // MARK: - 归档和解档 // 归档 func encodeWithCoder(encoder: NSCoder) { encoder.encodeObject(access_token, forKey: "access_token") encoder.encodeDouble(expires_in, forKey: "expires_in") encoder.encodeObject(uid, forKey: "uid") encoder.encodeObject(expires_date, forKey: "expires_date") encoder.encodeObject(name, forKey: "name") encoder.encodeObject(avatar_large, forKey: "avatar_large") } // 解档 required init?(coder decoder: NSCoder) { access_token = decoder.decodeObjectForKey("access_token") as? String expires_in = decoder.decodeDoubleForKey("expires_in") uid = decoder.decodeObjectForKey("uid") as? String expires_date = decoder.decodeObjectForKey("expires_date") as? NSDate // 归档 name = decoder.decodeObjectForKey("name") as? String avatar_large = decoder.decodeObjectForKey("avatar_large") as? String } }
apache-2.0
fed4371257e472f69aa82e578d6f664b
29.75
176
0.590242
4.265651
false
false
false
false
roecrew/AudioKit
Examples/iOS/AnalogSynthX/AnalogSynthX/AudioSystem/Conductor.swift
2
2232
// // Conductor.swift // AnalogSynthX // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit class Conductor: AKMIDIListener { /// Globally accessible singleton static let sharedInstance = Conductor() var core = GeneratorBank() var bitCrusher: AKBitCrusher var fatten: Fatten var filterSection: FilterSection var multiDelay: MultiDelay var multiDelayMixer: AKDryWetMixer var masterVolume = AKMixer() var reverb: AKCostelloReverb var reverbMixer: AKDryWetMixer var midiBendRange: Double = 2.0 init() { AKSettings.audioInputEnabled = true bitCrusher = AKBitCrusher(core) bitCrusher.stop() filterSection = FilterSection(bitCrusher) filterSection.output.stop() fatten = Fatten(filterSection) multiDelay = MultiDelay(fatten) multiDelayMixer = AKDryWetMixer(fatten, multiDelay, balance: 0.0) masterVolume = AKMixer(multiDelayMixer) reverb = AKCostelloReverb(masterVolume) reverb.stop() reverbMixer = AKDryWetMixer(masterVolume, reverb, balance: 0.0) // uncomment this to allow background operation // AKSettings.playbackWhileMuted = true AudioKit.output = reverbMixer AudioKit.start() let midi = AKMIDI() midi.createVirtualPorts() midi.openInput("Session 1") midi.addListener(self) } // MARK: - AKMIDIListener protocol functions func receivedMIDINoteOn(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: Int) { core.play(noteNumber: noteNumber, velocity: velocity) } func receivedMIDINoteOff(noteNumber noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: Int) { core.stop(noteNumber: noteNumber) } func receivedMIDIPitchWheel(pitchWheelValue: Int, channel: Int) { let bendSemi = (Double(pitchWheelValue - 8192) / 8192.0) * midiBendRange core.globalbend = bendSemi } }
mit
c9976690d593808d06e1fae8fe1edc0a
28.746667
81
0.634693
4.746809
false
false
false
false
DeeptanshuM/MHacks9
MHacks9/AppDelegate.swift
1
7502
// // AppDelegate.swift // MHacks9 // // Created by Deetpanshu Malik on 3/25/17. // Copyright © 2017 DeeptanhuRyujiKenanAvi. All rights reserved. // import UIKit import CoreData import Firebase import FBSDKCoreKit import FBSDKLoginKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. FIRApp.configure() FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) if let user = FIRAuth.auth()?.currentUser { print("There is a current user") let storyBoard = UIStoryboard(name: "Main", bundle: nil) let vc = storyBoard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController vc.selectedIndex = 1 window?.rootViewController = vc } NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "userDidLogout"), object: nil, queue: OperationQueue.main) { (Notification) in let storyBoard = UIStoryboard(name: "Main", bundle: nil) let vc = storyBoard.instantiateInitialViewController() self.window?.rootViewController = vc } NotificationCenter.default.addObserver(forName: NSNotification.Name("load"), object: nil, queue: OperationQueue.main) { (Notification) in let storyBoard = UIStoryboard(name: "Main", bundle: nil) let vc = storyBoard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController vc.selectedIndex = 0 self.window?.rootViewController = vc } UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { (accepted, error) in if !accepted { print("access denied") } } return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String! , annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } 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. return FBSDKAppEvents.activateApp() } 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: "MHacks9") 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)") } } } func scheduleNotification(at date: Date, title: String) { let calendar = Calendar(identifier: .gregorian) let components = calendar.dateComponents(in: .current, from: date) let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute) let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false) let content = UNMutableNotificationContent() content.title = title content.body = "Just a reminder that you have \(title) in about an hour" content.sound = UNNotificationSound.default() let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().removeAllPendingNotificationRequests() UNUserNotificationCenter.current().add(request) {(error) in if let error = error { print("Uh oh! We had an error: \(error)") } } } }
apache-2.0
1340e18c086f2c773855a5f6977782af
45.88125
281
0.70124
5.560415
false
false
false
false
denivip/Waveform
Source/View Model/DiagramModel.swift
1
3898
// // DiagramModel.swift // Waveform // // Created by developer on 22/12/15. // Copyright © 2015 developer. All rights reserved. // import Foundation import UIKit class DiagramModel: NSObject, DiagramDataSource { weak var channelsSource: ChannelSource? { didSet{ channelsSource?.onChannelsChanged = { [weak self] in self?.resetChannelsFromDataSources() } self.resetChannelsFromDataSources() } } private var viewModels = [PlotModel]() var geometry = DiagramGeometry() var onPlotUpdate: () -> () = {} var onGeometryUpdate: () -> () = {} var plotDataSourcesCount: Int { return self.viewModels.count } func plotDataSourceAtIndex(index: Int) -> PlotDataSource { return self.viewModels[index] } func resetChannelsFromDataSources() { guard let channelsSource = channelsSource else { onPlotUpdate() return } self.adjustViewModelsCountWithCount(channelsSource.channelsCount) for index in 0..<channelsSource.channelsCount { let channel = channelsSource.channelAtIndex(index) let viewModel = self.viewModels[index] viewModel.diagramModel = self viewModel.channel = channel } onPlotUpdate() } func adjustViewModelsCountWithCount(count: Int) { if viewModels.count == count { return } if viewModels.count < count { for _ in viewModels.count..<count { viewModels.append(PlotModel()) } return } if viewModels.count > count { for _ in count..<viewModels.count { viewModels.removeLast() } } } func viewModelWithIdentifier(identifier: String) -> PlotModel? { for viewModel in self.viewModels { if viewModel.identifier == identifier { return viewModel } } return nil } func maxWafeformBounds() -> CGRect { var maxHeight: CGFloat = 0.1 guard let channelsSource = channelsSource else { return .zero } for index in 0..<channelsSource.channelsCount { let channel = channelsSource.channelAtIndex(index) if CGFloat(channel.maxValue) > maxHeight { maxHeight = CGFloat(channel.maxValue) } } return CGRect(origin: .zero, size: CGSize(width: 1.0, height: maxHeight)) } func absoluteRangeFromRelativeRange(range: DataRange) -> DataRange { return DataRange(location: range.location.convertFromGeometry(self.geometry), length: range.length/self.geometry.scale) } } extension DiagramModel: DiagramDelegate { func zoom(start start: CGFloat, scale: CGFloat) { self.geometry = DiagramGeometry(start: Double(start), scale: Double(scale)) for viewModel in self.viewModels { viewModel.updateGeometry() } } func zoomAt(zoomAreaCenter: CGFloat, relativeScale: CGFloat) { let newScale = max(1.0, relativeScale * CGFloat(self.geometry.scale)) var start = CGFloat(self.geometry.start) + zoomAreaCenter * (1/CGFloat(self.geometry.scale) - 1/newScale) start = max(0, min(start, 1 - 1/newScale)) self.zoom(start: start, scale: newScale) } func moveToPosition(start: CGFloat) { self.geometry.start = max(0, min(Double(start), 1 - 1/self.geometry.scale)) for viewModel in self.viewModels { viewModel.updateGeometry() } } func moveByDistance(relativeDeltaX: CGFloat) { let relativeStart = CGFloat(self.geometry.start) - relativeDeltaX / CGFloat(self.geometry.scale) self.moveToPosition(relativeStart) } }
mit
521a1445c30560c53e6e773398594d19
31.483333
127
0.603541
4.628266
false
false
false
false
modocache/swift
test/NameBinding/Inputs/accessibility_other.swift
5
751
import has_accessibility public let a = 0 // expected-note * {{did you mean 'a'?}} internal let b = 0 // expected-note * {{did you mean 'b'?}} private let c = 0 extension Foo { public static func a() {} internal static func b() {} private static func c() {} // expected-note {{'c' declared here}} } struct PrivateInit { private init() {} // expected-note {{'init' declared here}} } extension Foo { private func method() {} private typealias TheType = Float } extension OriginallyEmpty { func method() {} typealias TheType = Float } private func privateInBothFiles() {} func privateInPrimaryFile() {} // expected-note {{previously declared here}} private func privateInOtherFile() {} // expected-error {{invalid redeclaration}}
apache-2.0
52448fbc060592f7f6c8f545398223f0
24.896552
80
0.681758
3.911458
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/2 - Primitives/PrimarySlider.swift
1
6504
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import SwiftUI #if canImport(UIKit) import UIKit #endif /// A horizontal slider used for picking from a range of values. /// /// PrimarySlider( /// value: $value, /// in: 0...10, /// step: 1 /// ) /// /// # Figma /// /// [Slider](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=6%3A1469) public struct PrimarySlider<Value: BinaryFloatingPoint>: View where Value.Stride: BinaryFloatingPoint { @Binding var value: Value let bounds: ClosedRange<Value> let step: Value.Stride? /// Create a horizontal slider /// - Parameters: /// - value: Binding for the current position of the thumb on the slider /// - bounds: Lower and upper limits for the slider /// - step: Optional step for locking the slider to certain increments. public init( value: Binding<Value>, in bounds: ClosedRange<Value>, step: Value.Stride? = nil ) { _value = value self.bounds = bounds self.step = step } public var body: some View { #if canImport(UIKit) SliderRepresentable( value: $value, bounds: bounds, step: step ) #else if let step = step { Slider( value: $value, in: bounds, step: step ) } else { Slider( value: $value, in: bounds ) } #endif } } #if canImport(UIKit) private struct SliderRepresentable<Value: BinaryFloatingPoint>: UIViewRepresentable where Value.Stride: BinaryFloatingPoint { @Binding var value: Value let bounds: ClosedRange<Value> let step: Value.Stride? func makeCoordinator() -> Coordinator { Coordinator { slider in if let step = step { let newValue = round(slider.value / Float(step)) * Float(step) value = Value(newValue) slider.value = newValue } else { value = Value(slider.value) } } } func makeUIView(context: Context) -> UISlider { let view = CustomSlider() view.minimumTrackTintColor = UIColor(.semantic.primary) view.maximumTrackTintColor = UIColor(.semantic.medium) view.addTarget(context.coordinator, action: #selector(Coordinator.valueDidChange(sender:)), for: .valueChanged) return view } func updateUIView(_ view: UISlider, context: Context) { let colorScheme = context.environment.colorScheme view.setThumbImage(thumbImage(for: colorScheme), for: .normal) view.minimumValue = Float(bounds.lowerBound) view.maximumValue = Float(bounds.upperBound) view.value = Float(value) } private func thumbBackgroundColor(for colorScheme: ColorScheme) -> Color { switch colorScheme { case .dark: return .palette.dark500 default: return .palette.white } } private func thumbBorderColor(for colorScheme: ColorScheme) -> Color { switch colorScheme { case .dark: return .palette.dark900 default: return .palette.grey000 } } private func firstShadow(for colorScheme: ColorScheme) -> Color { switch colorScheme { case .dark: return .black.opacity(0.12) default: return .black.opacity(0.06) } } private func secondShadow(for colorScheme: ColorScheme) -> Color { switch colorScheme { case .dark: return .black.opacity(0.12) default: return .black.opacity(0.15) } } private func thumbImage(for colorScheme: ColorScheme) -> UIImage { let ellipseDiameter: CGFloat = 28 let shadowSize: CGFloat = 10 let totalSize = ellipseDiameter + shadowSize * 2 let renderer = UIGraphicsImageRenderer(size: CGSize(width: totalSize, height: totalSize)) let image = renderer.image { context in let ellipseBounds = context.format.bounds.insetBy(dx: shadowSize, dy: shadowSize) UIColor(thumbBorderColor(for: colorScheme)).setFill() context.cgContext.setShadow( offset: CGSize(width: 0, height: 3), blur: 1, color: firstShadow(for: colorScheme).cgColor ) context.cgContext.fillEllipse(in: ellipseBounds) context.cgContext.setShadow( offset: CGSize(width: 0, height: 3), blur: 8, color: secondShadow(for: colorScheme).cgColor ) context.cgContext.fillEllipse(in: ellipseBounds) context.cgContext.setShadow(offset: .zero, blur: 0, color: nil) UIColor(thumbBackgroundColor(for: colorScheme)).setFill() context.cgContext.fillEllipse(in: ellipseBounds.insetBy(dx: 1, dy: 1)) } return image } class Coordinator: NSObject { let valueChanged: (UISlider) -> Void init(valueChanged: @escaping (UISlider) -> Void) { self.valueChanged = valueChanged } @objc func valueDidChange(sender: UISlider) { valueChanged(sender) } } } private class CustomSlider: UISlider { override func trackRect(forBounds bounds: CGRect) -> CGRect { let rect = super.trackRect(forBounds: bounds) return rect.insetBy(dx: 16, dy: 1) } override func thumbRect(forBounds bounds: CGRect, trackRect rect: CGRect, value: Float) -> CGRect { // Outset track rect so the thumb goes all the way to the edge super.thumbRect(forBounds: bounds, trackRect: rect.insetBy(dx: -16, dy: 0), value: value) } } #endif struct PrimarySlider_Previews: PreviewProvider { static var previews: some View { PreviewContainer() .background(Color.semantic.background) .previewLayout(.sizeThatFits) PreviewContainer() .background(Color.semantic.background) .colorScheme(.dark) .previewLayout(.sizeThatFits) } struct PreviewContainer: View { @State var value: Double = 5 let range: ClosedRange<Double> = 0...10 var body: some View { PrimarySlider(value: $value, in: range) } } }
lgpl-3.0
8232a070fec57e6f4eaebfb98b040c4a
29.38785
119
0.590958
4.612057
false
false
false
false
iOSWizards/AwesomeMedia
AwesomeMedia/Classes/Protocols/AwesomeMediaTrackingObserverProtocol.swift
1
3742
// // AwesomeMediaTrackingObserverProtocol.swift // AwesomeMedia // // Created by Evandro Harrison Hoffmann on 5/9/18. // import Foundation public extension Selector { public static let startedPlaying = #selector(AwesomeMediaTrackingObserver.startedPlaying) public static let stoppedPlaying = #selector(AwesomeMediaTrackingObserver.stoppedPlaying) public static let sliderChanged = #selector(AwesomeMediaTrackingObserver.sliderChanged) public static let toggleFullscreen = #selector(AwesomeMediaTrackingObserver.toggleFullscreen) public static let closeFullscreen = #selector(AwesomeMediaTrackingObserver.closeFullscreen) public static let openedMarkers = #selector(AwesomeMediaTrackingObserver.openedMarkers) public static let closedMarkers = #selector(AwesomeMediaTrackingObserver.closedMarkers) public static let selectedMarker = #selector(AwesomeMediaTrackingObserver.selectedMarker) public static let openedCaptions = #selector(AwesomeMediaTrackingObserver.openedCaptions) public static let closedCaptions = #selector(AwesomeMediaTrackingObserver.closedCaptions) public static let selectedCaption = #selector(AwesomeMediaTrackingObserver.selectedCaption) public static let toggledSpeed = #selector(AwesomeMediaTrackingObserver.toggledSpeed) public static let tappedRewind = #selector(AwesomeMediaTrackingObserver.tappedRewind) public static let tappedAdvance = #selector(AwesomeMediaTrackingObserver.tappedAdvance) public static let tappedAirplay = #selector(AwesomeMediaTrackingObserver.tappedAirplay) public static let changedOrientation = #selector(AwesomeMediaTrackingObserver.changedOrientation) public static let openedFullscreenWithRotation = #selector(AwesomeMediaTrackingObserver.openedFullscreenWithRotation) public static let tappedDownload = #selector(AwesomeMediaTrackingObserver.tappedDownload) public static let deletedDownload = #selector(AwesomeMediaTrackingObserver.deletedDownload) public static let didTimeOut = #selector(AwesomeMediaTrackingObserver.didTimeOut) public static let timeoutCancel = #selector(AwesomeMediaTrackingObserver.timeoutCancel) public static let timeoutWait = #selector(AwesomeMediaTrackingObserver.timeoutWait) public static let playingInBackground = #selector(AwesomeMediaTrackingObserver.playingInBackground) } @objc public protocol AwesomeMediaTrackingObserver { func addObservers() func removeObservers() @objc func startedPlaying(_ sender: Notification?) @objc func stoppedPlaying(_ sender: Notification?) @objc func sliderChanged(_ sender: Notification?) @objc func toggleFullscreen(_ sender: Notification?) @objc func closeFullscreen(_ sender: Notification?) @objc func openedMarkers(_ sender: Notification?) @objc func closedMarkers(_ sender: Notification?) @objc func selectedMarker(_ sender: Notification?) @objc func openedCaptions(_ sender: Notification?) @objc func closedCaptions(_ sender: Notification?) @objc func selectedCaption(_ sender: Notification?) @objc func toggledSpeed(_ sender: Notification?) @objc func tappedRewind(_ sender: Notification?) @objc func tappedAdvance(_ sender: Notification?) @objc func tappedAirplay(_ sender: Notification?) @objc func changedOrientation(_ sender: Notification?) @objc func openedFullscreenWithRotation(_ sender: Notification?) @objc func tappedDownload(_ sender: Notification?) @objc func deletedDownload(_ sender: Notification?) @objc func didTimeOut(_ sender: Notification?) @objc func timeoutCancel(_ sender: Notification?) @objc func timeoutWait(_ sender: Notification?) @objc func playingInBackground(_ sender: Notification?) }
mit
4a8ce43ac62d200f75406f3ec518a104
59.354839
121
0.796633
5.070461
false
false
false
false
mortenjust/nocturnal-traffic
nocturnal/CarScene.swift
1
5744
// // GameScene.swift // gamexperiment // // Created by Morten Just Petersen on 1/11/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import SpriteKit class CarScene: SKScene { // var carThreshold = 10 var removeCarPool = 0 var carEmitter = SKEmitterNode() var redCarEmitter = SKEmitterNode() override func didMoveToView(view: SKView) { /* Setup your scene here */ println("did move to view") self.backgroundColor = SKColor.clearColor() self.size = UIScreen.mainScreen().bounds.size self.physicsWorld.gravity = CGVectorMake(0, 0) //addCars(300) var carPath = NSBundle.mainBundle().pathForResource("Cars", ofType: "sks") carEmitter = NSKeyedUnarchiver.unarchiveObjectWithFile(carPath!) as SKEmitterNode carPath = NSBundle.mainBundle().pathForResource("CarsRed", ofType: "sks") redCarEmitter = NSKeyedUnarchiver.unarchiveObjectWithFile(carPath!) as SKEmitterNode var maxX = CGRectGetMaxX(self.frame) var midY = CGRectGetMidY(self.frame) var minX = CGRectGetMinX(self.frame) // carEmitter.position = CGPointMake(maxX-(maxX*0.25), midY-(midY*0.35)) carEmitter.position = CGPointMake(maxX+300, midY+(midY*0.50)) self.addChild(carEmitter) redCarEmitter.position = CGPointMake(minX-300, midY-(midY*0.50)) self.addChild(redCarEmitter) } func updateRedTravelTime(travelTime : Int, view : UILabel) { println("got red traveltime \(travelTime)") println("got traveltime \(travelTime)") var birthRate : CGFloat = pow(CGFloat(travelTime), 2.5) / 10000 var accelerationX : CGFloat = pow(CGFloat(travelTime), -1.75) * 10000 var accelerationY : CGFloat = accelerationX / 2 self.redCarEmitter.particleBirthRate = birthRate self.redCarEmitter.xAcceleration = accelerationX/15 self.redCarEmitter.yAcceleration = accelerationY/15 view.text = "\(travelTime)m North" } func updateTravelTime(travelTime : Int, view : UILabel) { println("got white traveltime \(travelTime)") var birthRate : CGFloat = pow(CGFloat(travelTime), 2.5) / 10000 var accelerationX : CGFloat = pow(CGFloat(travelTime), -1.75) * 10000 var accelerationY : CGFloat = accelerationX / 2 self.carEmitter.particleBirthRate = birthRate self.carEmitter.xAcceleration = -accelerationX/5 self.carEmitter.yAcceleration = -accelerationY/5 view.text = "\(travelTime)m South" } func setTotalCars(carCount : Int) { println("got total \(carCount)") var birthRate : CGFloat = CGFloat(carCount) / 1000 self.carEmitter.particleBirthRate = birthRate println("setting birthrate \(birthRate)") } func removeRealCars(carCount : Int) { removeCarPool += carCount // add to global counter var removeFromView = 0 if removeCarPool > 10 { // if more than 10, let's remove 1 car per 10 removeFromView = removeCarPool / 10 removeCarPool -= (removeFromView*10) // update the global counter } for counter in 0...removeFromView { delay(Double(counter)*0.001, closure: { () -> () in self.children[0].removeFromParent() }) } } func carAssetName() -> String { var types = ["yellow-car-small", "gray-car-small"] let max = UInt32(2) return types[Int(arc4random_uniform(max))] } func addCars(carCount : Int) { } func removeCars(carCount : Int) { } func addRealCars(carCount : Int) { var checker = 0 for counter in 0...carCount { checker++ delay(Double(counter)*0.01, closure: { () -> () in var car : SKSpriteNode = SKSpriteNode(imageNamed: self.carAssetName()) // car.size = CGSizeMake(25, 15) car.size = CGSizeMake(car.size.width/1, car.size.height/1) car.alpha = 1 // let xPos : CGFloat = CGFloat(Double(counter) % Double(CGRectGetMaxX(self.frame))) // car.position = CGPoint(x:xPos, y:CGRectGetMaxY(self.frame)); car.position = CGPointMake(1, 200) car.blendMode = SKBlendMode.Screen self.addChild(car) // car.physicsBody = SKPhysicsBody(rectangleOfSize: car.frame.size) car.physicsBody = SKPhysicsBody(circleOfRadius: car.frame.size.width/4) self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) //car.physicsBody?.applyImpulse(CGVectorMake(0.5, 0)) car.physicsBody?.applyImpulse(CGVectorMake(CGFloat(counter)+5, 0)) }) } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { addCars(1) } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { } func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
4372fccf7e70c2978308ce3703d19054
31.636364
99
0.58757
4.562351
false
false
false
false
jensmeder/DarkLightning
Sources/Daemon/Sources/Messages/USBMuxMessageDataArray.swift
1
2305
/** * * DarkLightning * * * * The MIT License (MIT) * * Copyright (c) 2017 Jens Meder * * 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 internal final class USBMuxMessageDataArray: OODataArray { private let data: Data private let closure: (Data) -> (OOData) // MARK: Init internal convenience init(data: Data) { self.init( data: data, closure: { (data: Data) -> (OOData) in return RawData(data) } ) } internal required init(data: Data, closure: @escaping (Data) -> (OOData)) { self.data = data self.closure = closure } // MARK: Private private func messages() -> [Data] { var result: [Data] = [] var origin = data let headerSize = 4 * MemoryLayout<UInt32>.size while origin.count >= headerSize { let size: UInt32 = UInt32WithData(data: DataWithRange(data: origin, range: 0..<4)).rawValue if Int(size) <= origin.count { let message = origin.subdata(in: headerSize..<Int(size)) result.append(message) origin.removeSubrange(0..<Int(size)) } else { origin = Data() } } return result } // MARK: OODataArray var count: UInt { return UInt(messages().count) } subscript(index: UInt) -> OOData { return closure(messages()[Int(index)]) } }
mit
911576c819be6d380a6414aeb490bef6
27.8125
94
0.692842
3.664547
false
false
false
false
peteratseneca/dps923winter2015
Week_07/Toronto2015Example/Classes/ExampleList.swift
4
2910
// // ExampleList.swift // Classes // // Created by Peter McIntyre on 2015-02-01. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import UIKit import CoreData // Notice the protocol conformance class ExampleList: UITableViewController, NSFetchedResultsControllerDelegate { // MARK: - Private properties var frc: NSFetchedResultsController! // MARK: - Properties // Passed in by the app delegate during app initialization var model: Model! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() // Configure and load the fetched results controller (frc) frc = model.frc_example // This controller will be the frc delegate frc.delegate = self; // No predicate (which means the results will NOT be filtered) frc.fetchRequest.predicate = nil; // Create an error object var error: NSError? = nil // Perform fetch, and if there's an error, log it if !frc.performFetch(&error) { println(error?.description) } } // MARK: - Table view methods override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.frc.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.frc.sections![section] as NSFetchedResultsSectionInfo return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell self.configureCell(cell, atIndexPath: indexPath) return cell } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let item: AnyObject = frc.objectAtIndexPath(indexPath) cell.textLabel!.text = item.valueForKey("attribute1")! as? String } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "toExampleDetail" { // Get a reference to the destination view controller let vc = segue.destinationViewController as ExampleDetail // From the data source (the fetched results controller)... // Get a reference to the object for the tapped/selected table view row let item: AnyObject = frc.objectAtIndexPath(self.tableView.indexPathForSelectedRow()!) // Pass on the object vc.detailItem = item // Configure the view if you wish vc.title = item.valueForKey("attribute1") as? String } } }
mit
0d1d73f745a76a988000862e309151c0
30.290323
118
0.64433
5.398887
false
false
false
false
jakeshi01/IFlySpeechPackage
IFlyTest/IFlyTest/GCDExtension.swift
1
1086
// // AppDelegate.swift // IFlyTest // // Created by Jake on 2017/6/28. // Copyright © 2017年 Jake. All rights reserved. // import Foundation typealias Task = (_ cancel : Bool) -> Void @discardableResult func delay(_ time: TimeInterval, task: @escaping () -> Void) -> Task? { func dispatch_later(_ block:@escaping () -> Void) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(time * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: block) } var closure: (() -> Void)? = task var result: Task? let delayedClosure: Task = { cancel in if let internalClosure = closure { if (cancel == false) { DispatchQueue.main.async(execute: internalClosure) } } closure = nil result = nil } result = delayedClosure dispatch_later { if let delayedClosure = result { delayedClosure(false) } } return result } func cancel(_ task:Task?) { task?(true) }
mit
bf31a2daaf639099acdbd6516f9b690e
19.826923
109
0.56048
4.247059
false
false
false
false
googlearchive/science-journal-ios
ScienceJournal/UI/ExistingDataOptionsViewController.swift
1
9796
/* * Copyright 2019 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 UIKit import third_party_objective_c_material_components_ios_components_Collections_Collections import third_party_objective_c_material_components_ios_components_Dialogs_Dialogs import third_party_objective_c_material_components_ios_components_Typography_Typography protocol ExistingDataOptionsDelegate: class { /// Delegate method for selecting to save all experiments. func existingDataOptionsViewControllerDidSelectSaveAllExperiments() /// Delegate method for selecting to delete all experiments. func existingDataOptionsViewControllerDidSelectDeleteAllExperiments() /// Delegate method for selecting to select which experiments to save. func existingDataOptionsViewControllerDidSelectSelectExperimentsToSave() } /// The view controller for the existing data options screen, explaining that the user can now sync /// experiments and presents choices for what to do with the existing data on the device. class ExistingDataOptionsViewController: ScienceJournalCollectionViewController { // MARK: - Nested Types private struct DataOption { let icon: UIImage? let title: String let description: String let identifier: String } // MARK: - Properties /// The existing data options delegate. weak var delegate: ExistingDataOptionsDelegate? private enum Metrics { static let cellIdentifier = "ExistingDataOptionsCell" static let headerIdentifier = "ExistingDataOptionsHeaderView" static let cellForSaveAll = "SaveAllCell" static let cellForDeleteAll = "DeleteAllCell" static let cellForSelect = "SelectCell" static let collectionInsets = UIEdgeInsets(top: 0, left: 64, bottom: 0, right: 16) } private let options: [DataOption] = { return [DataOption(icon: UIImage(named: "ic_claim_drive"), title: String.existingDataOptionSaveAllExperimentsTitle, description: String.existingDataOptionSaveAllExperimentsDescription, identifier: Metrics.cellForSaveAll), DataOption(icon: UIImage(named: "ic_claim_delete"), title: String.existingDataOptionDeleteAllExperimentsTitle, description: String.existingDataOptionDeleteAllExperimentsDescription, identifier: Metrics.cellForDeleteAll), DataOption(icon: UIImage(named: "ic_claim_select"), title: String.existingDataOptionSelectExperimentsTitle, description: String.existingDataOptionSelectExperimentsDescription, identifier: Metrics.cellForSelect)] }() private let numberOfExistingExperiments: Int // MARK: - Public /// Designated initializer. /// /// - Parameters: /// - analyticsReporter: The analytics reporter. /// - numberOfExistingExperiments: The number of existing experiments. init(analyticsReporter: AnalyticsReporter, numberOfExistingExperiments: Int) { self.numberOfExistingExperiments = numberOfExistingExperiments super.init(collectionViewLayout: MDCCollectionViewFlowLayout(), analyticsReporter: analyticsReporter) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) is not supported") } override var preferredStatusBarStyle: UIStatusBarStyle { return .default } override func viewDidLoad() { super.viewDidLoad() collectionView?.backgroundColor = .white collectionView?.register(ExistingDataOptionsHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: Metrics.headerIdentifier) collectionView?.register(ExistingDataOptionsCell.self, forCellWithReuseIdentifier: Metrics.cellIdentifier) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) collectionView?.collectionViewLayout.invalidateLayout() } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return Metrics.collectionInsets } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let width = collectionView.bounds.width - Metrics.collectionInsets.left - Metrics.collectionInsets.right let height = ExistingDataOptionsHeaderView.height(inWidth: width, numberOfExperiments: numberOfExistingExperiments) return CGSize(width: collectionView.bounds.width, height: height) } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: Metrics.headerIdentifier, for: indexPath) if let header = header as? ExistingDataOptionsHeaderView { header.setNumberOfExperiments(numberOfExistingExperiments) } return header } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let option = options[indexPath.item] let width = collectionView.bounds.width - Metrics.collectionInsets.left - Metrics.collectionInsets.right let height = ExistingDataOptionsCell.height(withTitle: option.title, description: option.description, inWidth: width) return CGSize(width: width, height: height) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return options.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Metrics.cellIdentifier, for: indexPath) if let cell = cell as? ExistingDataOptionsCell { // The last cell should show the bottom separator. cell.shouldShowBottomSeparator = indexPath.item == options.count - 1 let option = options[indexPath.item] cell.imageView.image = option.icon cell.titleText = option.title cell.descriptionText = option.description } return cell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let option = options[indexPath.item] if option.identifier == Metrics.cellForSaveAll { // Prompt the user to confirm claiming all. let message = String.claimAllExperimentsImmediatelyConfirmationMessage let alertController = MDCAlertController(title: String.claimAllExperimentsMigrationConfirmationTitle, message: message) let claimAction = MDCAlertAction(title: String.claimAllExperimentsConfirmationAction) { _ in self.delegate?.existingDataOptionsViewControllerDidSelectSaveAllExperiments() } let cancelAction = MDCAlertAction(title: String.actionCancel) alertController.addAction(claimAction) alertController.addAction(cancelAction) alertController.accessibilityViewIsModal = true self.present(alertController, animated: true) } else if option.identifier == Metrics.cellForDeleteAll { // Prompt the user to confirm deleting all. let message = String.claimExperimentsDeleteAllMigrationConfirmationMessage let alertController = MDCAlertController(title: String.claimExperimentsDeleteAllMigrationConfirmationTitle, message: message) let deleteAction = MDCAlertAction(title: String.claimExperimentsDeleteAllConfirmationAction) { _ in self.delegate?.existingDataOptionsViewControllerDidSelectDeleteAllExperiments() } let cancelAction = MDCAlertAction(title: String.actionCancel) alertController.addAction(deleteAction) alertController.addAction(cancelAction) alertController.accessibilityViewIsModal = true self.present(alertController, animated: true) } else if option.identifier == Metrics.cellForSelect { delegate?.existingDataOptionsViewControllerDidSelectSelectExperimentsToSave() } } }
apache-2.0
36dd80d9bfa0d0a19db2a270cefebbb8
43.527273
100
0.691405
5.865868
false
false
false
false
banxi1988/BXForm
Pod/Classes/Controller/SelectPickerController.swift
3
2912
// // SingleCompomentPickerController.swift // Pods // // Created by Haizhen Lee on 15/12/23. // // import UIKit open class SelectPickerController<T:CustomStringConvertible>:PickerController,UIPickerViewDataSource,UIPickerViewDelegate where T:Equatable{ fileprivate var options:[T] = [] open var rowHeight:CGFloat = 36{ didSet{ picker.reloadAllComponents() } } open var textColor = UIColor.darkText{ didSet{ picker.reloadAllComponents() } } open var font = UIFont.systemFont(ofSize: 14){ didSet{ picker.reloadAllComponents() } } open var onSelectOption:((T) -> Void)? public init(options:[T]){ self.options = options super.init(nibName: nil, bundle: nil) } public init(){ super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func viewDidLoad() { super.viewDidLoad() picker.delegate = self picker.dataSource = self picker.showsSelectionIndicator = true } open func selectOption(_ option:T){ let index = options.index { $0 == option } if let row = index{ picker.selectRow(row, inComponent: 0, animated: true) } } open func updateOptions(_ options:[T]){ self.options = options if isViewLoaded{ picker.reloadAllComponents() } } open func appendOptions(_ options:[T]){ self.options.append(contentsOf: options) picker.reloadAllComponents() } open func appendOption(_ option:T){ self.options.append(option) picker.reloadAllComponents() } func optionAtRow(_ row:Int) -> T?{ if options.count <= row || row < 0{ return nil } return options[row] } // MARK: UIPickerViewDataSource open func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } open func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return component == 0 ? options.count : 0 } // MARK: UIPickerViewDelegate open func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return rowHeight } open func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { guard let option = optionAtRow(row) else{ return nil } let title = option.description let attributedText = NSAttributedString(string: title, attributes: [ NSForegroundColorAttributeName:textColor, NSFontAttributeName:font ]) return attributedText } // MARK: Base Controller override open func onPickDone() { if options.isEmpty{ return } let selectedRow = picker.selectedRow(inComponent: 0) if let option = optionAtRow(selectedRow){ onSelectOption?(option) } } }
mit
d6272cf142506453f9ad7db804916837
22.674797
140
0.667926
4.55
false
false
false
false
paterik/udacity-ios-silly-song
SillySong/ViewController.swift
1
2213
// // ViewController.swift // SillySong // // Created by Patrick Paechnatz on 06.04.17. // Copyright © 2017 Patrick Paechnatz. All rights reserved. // import UIKit class ViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate { // // MARK: IBOutlet variables // @IBOutlet weak var nameField: UITextField! @IBOutlet weak var lyricsView: UITextView! @IBOutlet weak var lblAppTitle: UILabel! // // MARK: Constants (Special) // let debugMode: Bool = true let appCommon = AppCommon.sharedInstance // // MARK: Constants (Normal) // let vowels = ["a","e","i","o","u"] let lyricFontNames = ["HelveticaNeue-CondensedBlack", "Impact", "Futura-CondensedExtraBold"] let lyricFontNameFallback = "Arial" let lyricFontSize: CGFloat = 28.0 let lyricTemplate = [ "<FULL_NAME>, <FULL_NAME>, Bo B<SHORT_NAME>", "Banana Fana Fo F<SHORT_NAME>", "Me My Mo M<SHORT_NAME>", "<FULL_NAME>"].joined(separator: "\n") // // MARK: Variables // var lyricTextViewAttributes: [String : Any]! var lyricParagraphStyle: NSMutableParagraphStyle! var lyricTextViewAttributedText: NSMutableAttributedString! var lyricFontNameUsed: String! // // MARK: UIView Methods (overrides) // override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent prepareControls( true ) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIApplication.shared.statusBarStyle = UIStatusBarStyle.default // unsubscribe keyboard notification unSubscribeToKeyboardNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // add keyboard notification subscription to handle keyboard movement // on any device direction and prevent input field overlay issue(s) subscribeToKeyboardNotifications() nameField.delegate = self } }
mit
63c74c2d05695dc319a017bb0b93529f
25.333333
96
0.632007
5.038724
false
false
false
false
tranhieutt/Neon
Demo/Neon/Neon/IconButton.swift
16
879
// // IconButton.swift // Neon // // Created by Mike on 9/26/15. // Copyright © 2015 Mike Amaral. All rights reserved. // import UIKit class IconButton: UIView { let imageView : UIImageView = UIImageView() let label : UILabel = UILabel() convenience init() { self.init(frame: CGRectZero) imageView.contentMode = .ScaleAspectFill self.addSubview(imageView) label.textAlignment = .Center label.textColor = UIColor(red: 106/255.0, green: 113/255.0, blue: 127/255.0, alpha: 1.0) label.font = UIFont.systemFontOfSize(13.0) self.addSubview(label) } override func layoutSubviews() { super.layoutSubviews() imageView.anchorToEdge(.Top, padding: 0, width: 24, height: 24) label.align(.UnderCentered, relativeTo: imageView, padding: 5, width: self.width(), height: 15) } }
mit
ff01aa0b4821b6975dea08034af0d4fb
25.606061
103
0.643508
3.919643
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/LowEnergyCommand.swift
1
14078
// // HCILowEnergyCommand.swift // Bluetooth // // Created by Alsey Coleman Miller on 1/14/16. // Copyright © 2016 PureSwift. All rights reserved. // /// Bluetooth Low Energy Command opcode @frozen public enum HCILowEnergyCommand: UInt16, HCICommand { public static let opcodeGroupField = HCIOpcodeGroupField.lowEnergy /// LE Set Event Mask case setEventMask = 0x0001 /// LE Read Buffer Size case readBufferSize = 0x0002 /// LE Read Local Supported Features case readLocalSupportedFeatures = 0x0003 /// LE Set Random Address case setRandomAddress = 0x0005 /// LE Set Advertising Parameters case setAdvertisingParameters = 0x0006 /// LE Read Advertising Channel Tx Power case readAdvertisingChannelTXPower = 0x0007 /// LE Set Advertising Data case setAdvertisingData = 0x0008 /// LE Set Scan Response Data case setScanResponseData = 0x0009 /// LE Set Advertise Enable case setAdvertiseEnable = 0x000A /// LE Set Scan Parameters case setScanParameters = 0x000B /// LE Set Scan Enable case setScanEnable = 0x000C /// LE Create Connection case createConnection = 0x000D /// LE Create Connection Cancel case createConnectionCancel = 0x000E /// LE Read White List Size case readWhiteListSize = 0x000F /// LE Clear White List case clearWhiteList = 0x0010 /// LE Add Device To White List case addDeviceToWhiteList = 0x0011 /// LE Remove Device From White List case removeDeviceFromWhiteList = 0x0012 /// LE Connection Update case connectionUpdate = 0x0013 /// LE Set Host Channel Classification case setHostChannelClassification = 0x0014 /// LE Read Channel Map case readChannelMap = 0x0015 /// LE Read Remote Used Features case readRemoteUsedFeatures = 0x0016 /// LE Encrypt case encrypt = 0x0017 /// LE Rand case random = 0x0018 /// LE Start Encryption case startEncryption = 0x0019 /// LE Remote Connection Parameter Request Reply case remoteConnectionParameterRequestReply = 0x0020 /// LE Remote Connection Parameter Request Negative Reply Command case remoteConnectionParameterRequestNegativeReply = 0x0021 /// LE Set Data Length Command case setDataLengthCommand = 0x0022 /// LE Read Suggested Default Data Length Command case readSuggestedDefaultDataLengthCommand = 0x0023 /// LE Write Suggested Default Data Length Command case writeSuggestedDefaultDataLengthCommand = 0x0024 /// LE Read Local P-256 Public Key Command case readLocalP256PublicKeyCommand = 0x0025 /// LE Generate DHKey Command case generateDHKeyCommand = 0x0026 /// LE Long Term Key Request Reply case longTermKeyReply = 0x001A /// LE Long Term Key Request Negative Reply case longTermKeyNegativeReply = 0x001B /// LE Read Supported States case readSupportedStates = 0x001C /// LE Receiver Test case receiverTest = 0x001D /// LE Transmitter Test case transmitterTest = 0x001E /// LE Test End case testEnd = 0x001F /// LE Add Device To Resolved List case addDeviceToResolvedList = 0x0027 /// LE Remove Device From Resolved List case removeDeviceFromResolvedList = 0x0028 /// LE Clear Resolved List case clearResolvedList = 0x0029 /// LE Read Resolved List Size case readResolvedListSize = 0x002A /// LE Read Peer Resolvable Address case readPeerResolvableAddress = 0x002B /// LE Read Local Resolvable Address case readLocalResolvableAddress = 0x002C /// LE Set Address Resolution Enable case setAddressResolutionEnable = 0x002D /// LE Set Resolvable Private Address Timeout case setResolvablePrivateAddressTimeout = 0x002E /// LE Read Maximum Data Length case readMaximumDataLength = 0x002F /// LE Read PHY case readPhy = 0x0030 /// LE Set Default PHY case setDefaultPhy = 0x0031 /// LE Set Phy case setPhy = 0x0032 /// LE Enhanced Receiver Test case enhancedReceiverTest = 0x0033 /// LE Enhanced Transmitter Test case enhancedTransmitterTest = 0x0034 /// LE Set Advertising Set Random Address case setAdvertisingSetRandomAddress = 0x0035 /// LE Set Extended Advertising Parameters case setExtendedAdvertisingParameters = 0x0036 /// LE Set Extended Advertising Data case setExtendedAdvertisingData = 0x0037 /// LE Set Extended Scan Response Data case setExtendedScanResponseData = 0x0038 /// LE Read Maximum Advertising Data Length Command case readMaximumAdvertisingDataLength = 0x003A /// LE Read Number of Supported Advertising Sets Command case readNumberOfSupportedAdvertisingSets = 0x003B /// LE Remove Advertising Set Command case removeAdvertisingSet = 0x003C /// LE Clear Advertising Sets Command case clearAdvertisingSets = 0x003D /// LE Set Periodic Advertising Parameters Command case setPeriodicAdvertisingParameters = 0x003E /// LE Set Periodic Advertising Data Command case setPeriodicAdvertisingData = 0x003F /// LE Set Extended Advertising Enable Command case setExtendedAdvertisingEnable = 0x0039 /// LE Set Periodic Advertising Enable Command case setPeriodicAdvertisingEnable = 0x0040 /// LE Set Extended Scan Parameters Command case setExtendedScanParameters = 0x0041 /// LE Set Extended Scan Enable Command case setExtendedScanEnable = 0x0042 /// LE Extended Create Connection Command case extendedCreateConnection = 0x0043 /// LE Periodic Advertising Create Sync Command case periodicAdvertisingCreateSync = 0x0044 /// LE Periodic Advertising Create Sync Cancel Command case periodicAdvertisingCreateSyncCancel = 0x0045 /// LE Periodic Advertising Terminate Sync Command case periodicAdvertisingTerminateSync = 0x0046 /// LE Add Device To Periodic Advertiser List Command case addDeviceToPeriodicAdvertiserList = 0x0047 /// LE Remove Device From Periodic Advertiser List Command case removeDeviceFromPeriodicAdvertiserList = 0x0048 /// LE Clear Periodic Advertiser List Command case clearPeriodicAdvertiserList = 0x0049 /// LE Read Periodic Advertiser List Size Command case readPeriodicAdvertiserListSize = 0x004A /// LE Read Transmit Power Command case readTransmitPower = 0x004B /// LE Read RF Path Compensation Command case readRFPathCompensation = 0x004C /// LE Write RF Path Compensation Command case writeRFPathCompensation = 0x004D /// LE Set Privacy Mode Command case setPrivacyMode = 0x004E } // MARK: - Name public extension HCILowEnergyCommand { var name: String { switch self { case .setEventMask: return "LE Set Event Mask" case .readBufferSize: return "LE Read Buffer Size" case .readLocalSupportedFeatures: return "LE Read Local Supported Features" case .setRandomAddress: return "LE Set Random Address" case .setAdvertisingParameters: return "LE Set Advertising Parameters" case .readAdvertisingChannelTXPower: return "LE Read Advertising Channel Tx Power" case .setAdvertisingData: return "LE Set Advertising Data" case .setScanResponseData: return "LE Set Scan Response Data" case .setAdvertiseEnable: return "LE Set Advertise Enable" case .setScanParameters: return "LE Set Scan Parameters" case .setScanEnable: return "LE Set Scan Enable" case .createConnection: return "LE Create Connection" case .createConnectionCancel: return "LE Create Connection Cancel" case .readWhiteListSize: return "LE Read White List Size" case .clearWhiteList: return "LE Clear White List" case .addDeviceToWhiteList: return "LE Add Device To White List" case .removeDeviceFromWhiteList: return "LE Remove Device From White List" case .connectionUpdate: return "LE Connection Update" case .setHostChannelClassification: return "LE Set Host Channel Classification" case .readChannelMap: return "LE Read Channel Map" case .readRemoteUsedFeatures: return "LE Read Remote Used Features" case .encrypt: return "LE Encrypt" case .random: return "LE Rand" case .startEncryption: return "LE Start Encryption" case .longTermKeyReply: return "LE Long Term Key Request Reply" case .longTermKeyNegativeReply: return "LE Long Term Key Request Negative Reply" case .readSupportedStates: return "LE Read Supported States" case .receiverTest: return "LE Receiver Test" case .transmitterTest: return "LE Transmitter Test" case .testEnd: return "LE Test End" case .addDeviceToResolvedList: return "LE Add Device To Resolved List" case .removeDeviceFromResolvedList: return "LE Remove Device From Resolved List" case .clearResolvedList: return "LE Clear Resolved List" case .readResolvedListSize: return "LE Read Resolved List Size" case .readPeerResolvableAddress: return "LE Read Peer Resolvable Address" case .readLocalResolvableAddress: return "LE Read Local Resolvable Address" case .setAddressResolutionEnable: return "LE Set Address Resolution Enable" case .setResolvablePrivateAddressTimeout: return "LE Set Resolvable Private Address Timeout" case .readMaximumDataLength: return "LE Read Maximum Data Length" case .readPhy: return "LE Read PHY" case .setDefaultPhy: return "LE Set Default PHY" case .setPhy: return "LE Set Phy" case .enhancedReceiverTest: return "LE Enhanced Receiver Test" case .enhancedTransmitterTest: return "LE Enhanced Transmitter Test" case .setAdvertisingSetRandomAddress: return "LE Set Advertising Set Random Address" case .setExtendedAdvertisingParameters: return "LE Set Extended Advertising Parameters" case .setExtendedAdvertisingData: return "LE Set Extended Advertising Data" case .setExtendedScanResponseData: return "LE Set Extended Scan Response Data" case .readMaximumAdvertisingDataLength: return "LE Read Maximum Advertising Data Length Command" case .readNumberOfSupportedAdvertisingSets: return "LE Read Number of Supported Advertising Sets Command" case .removeAdvertisingSet: return "LE Remove Advertising Set Command" case .clearAdvertisingSets: return "LE Clear Advertising Sets Command" case .setExtendedAdvertisingEnable: return "LE Set Extended Advertising Enable Command" case .setPeriodicAdvertisingParameters: return "LE Set Periodic Advertising Parameters Command" case .setPeriodicAdvertisingData: return "LE Set Periodic Advertising Data Command" case .setPeriodicAdvertisingEnable: return "LE Set Periodic Advertising Enable Command" case .setExtendedScanParameters: return "LE Set Extended Scan Parameters Command" case .setExtendedScanEnable: return "LE Set Extended Scan Enable Command" case .extendedCreateConnection: return "LE Extended Create Connection Command" case .periodicAdvertisingCreateSync: return "LE Periodic Advertising Create Sync Command" case .periodicAdvertisingCreateSyncCancel: return "LE Periodic Advertising Create Sync Cancel Command" case .periodicAdvertisingTerminateSync: return "LE Periodic Advertising Terminate Sync Command" case .addDeviceToPeriodicAdvertiserList: return "LE Add Device To Periodic Advertiser List Command" case .removeDeviceFromPeriodicAdvertiserList: return "LE Remove Device From Periodic Advertiser List Command" case .clearPeriodicAdvertiserList: return "LE Clear Periodic Advertiser List Command" case .readPeriodicAdvertiserListSize: return "LE Read Periodic Advertiser List Size Command" case .readTransmitPower: return "LE Read Transmit Power Command" case .readRFPathCompensation: return "LE Read RF Path Compensation Command" case .writeRFPathCompensation: return "LE Write RF Path Compensation Command" case .setPrivacyMode: return "LE Set Privacy Mode Command" case .remoteConnectionParameterRequestReply: return "LE Remote Connection Parameter Request Reply" case .remoteConnectionParameterRequestNegativeReply: return "LE Remote Connection Parameter Request Negative Reply Command" case .setDataLengthCommand: return "LE Set Data Length Command" case .readSuggestedDefaultDataLengthCommand: return "LE Read Suggested Default Data Length Command" case .readLocalP256PublicKeyCommand: return "LE Read Local P-256 Public Key Command" case .writeSuggestedDefaultDataLengthCommand: return "LE Write Suggested Default Data Length Command" case .generateDHKeyCommand : return "LE Generate DHKey Command" } } }
mit
0c2d5ecf4f18e78c850ba7151e6316fd
41.146707
131
0.673297
5.060029
false
true
false
false
jorgevila/ioscreator
IOS8SwiftMoveViewKeyboardTutorial/IOS8SwiftMoveViewKeyboardTutorial/ViewController.swift
40
2005
// // ViewController.swift // IOS8SwiftMoveViewKeyboardTutorial // // Created by Arthur Knopper on 23/08/14. // Copyright (c) 2014 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var textField: UITextField! var kbHeight: CGFloat! override func viewDidLoad() { super.viewDidLoad() textField.delegate = self } func animateTextField(up: Bool) { var movement = (up ? -kbHeight : kbHeight) UIView.animateWithDuration(0.3, animations: { self.view.frame = CGRectOffset(self.view.frame, 0, movement) }) } override func viewWillAppear(animated:Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { if let userInfo = notification.userInfo { if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() { kbHeight = keyboardSize.height self.animateTextField(true) } } } func keyboardWillHide(notification: NSNotification) { self.animateTextField(false) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
32758b8ac1fa3143e5b00e24c8b040bc
27.642857
154
0.667332
5.375335
false
false
false
false
sonnygauran/trailer
PocketTrailer/SettingsManager.swift
1
1311
import UIKit let settingsManager = SettingsManager() final class SettingsManager { private func loadSettingsFrom(url: NSURL) { if Settings.readFromURL(url) { atNextEvent { let m = popupManager.getMasterController() m.reloadDataWithAnimation(false) app.preferencesDirty = true Settings.lastSuccessfulRefresh = nil atNextEvent { app.startRefreshIfItIsDue() } } } else { atNextEvent { showMessage("Error", "These settings could not be imported due to an error") } } } func loadSettingsFrom(url: NSURL, confirmFromView: UIViewController?, withCompletion: ((Bool)->Void)?) { if let v = confirmFromView { let a = UIAlertController(title: "Import these settings?", message: "This will overwrite all your current settings, are you sure?", preferredStyle: UIAlertControllerStyle.Alert) a.addAction(UIAlertAction(title: "Yes", style: UIAlertActionStyle.Destructive, handler: { [weak self] action in self!.loadSettingsFrom(url) withCompletion?(true) })) a.addAction(UIAlertAction(title: "No", style: UIAlertActionStyle.Cancel, handler: { action in withCompletion?(false) })) atNextEvent { v.presentViewController(a, animated: true, completion: nil) } } else { loadSettingsFrom(url) withCompletion?(true) } } }
mit
97f1ab13c87c149926f0b8ab95282fc8
26.893617
180
0.71167
3.844575
false
false
false
false
LuizZak/TaskMan
TaskMan/ASTree.swift
1
6970
// // ASTree.swift // TimeCalc // // Created by Luiz Fernando Silva on 19/10/15. // Copyright (c) 2015 Luiz Fernando Silva. All rights reserved. // import Foundation enum ASTreeValueType { case unknown case invalid(message: String) case time case float case string } struct ASTreeValue { var rawString: String var type: ASTreeValueType var source: Token } indirect enum TypedASTreeNode { case unaryExpression(operator: OperatorType, value: TypedASTreeNode, type: ASTreeValueType) case parenthesizedExpression(expression: TypedASTreeNode, type: ASTreeValueType) case binaryExpression(leftValue: TypedASTreeNode, operator: OperatorType, rightValue: TypedASTreeNode, type: ASTreeValueType) case value(value: ASTreeValue, type: ASTreeValueType) /// Fetches the value type for this TypedASTreeNode. func valueType() -> ASTreeValueType { switch(self) { case .unaryExpression(_, _, let type): return type case .parenthesizedExpression(_, let type): return type case .binaryExpression(_, _, _, let type): return type case .value(_, let type): return type } } /// Gets the source range for this node. In case this is a complex recursive expression (e.g. a binary expression), /// it returns the entire range of the expression's inner components. func sourceRange() -> Range<String.Index> { switch(self) { case .value(let value, _): return value.source.inputRange case .binaryExpression(let left, _, let right, _): let lr = left.sourceRange(), rr = right.sourceRange() return (lr.lowerBound..<rr.upperBound) case .unaryExpression(_, let node, _): return node.sourceRange() case .parenthesizedExpression(let node, _): return node.sourceRange() } } /// Returns the entire complex string resulting from collapsing this expression. func stringRepresentation() -> String { switch(self) { case .value(let value, _): return value.source.tokenString case .binaryExpression(let left, let op, let right, _): let lstring = left.stringRepresentation(), rstring = right.stringRepresentation() return "\(lstring)\(op.rawValue)\(rstring)" case .unaryExpression(let op, let node, _): return "\(op.rawValue)\(node.stringRepresentation())" case .parenthesizedExpression(let node, _): return "(\(node.stringRepresentation()))" } } /// Returns the entire complex string resulting from collapsing this expression, on top of a given source string. func sourceString(onString string: String) -> String { return string[sourceRange()] } } indirect enum ASTreeNode { case invalidAST(error: String) case unaryExpression(operator: OperatorType, value: ASTreeNode) case parenthesizedExpression(expression: ASTreeNode) case binaryExpression(leftValue: ASTreeNode, operator: OperatorType, rightValue: ASTreeNode) case value(value: ASTreeValue) /// Returns whether this node is a BinaryExpression case enum func isBinaryExpression() -> Bool { if case .binaryExpression = self { return true } return false } /// Rotates this ASTreeNode left, in case it's a binary expression. /// The right side of the tree has to be a binary expression tree as well /// In case it is not, no operation is performed. func rotateLeft() -> ASTreeNode { guard case .binaryExpression(let left, let op, let right) = self else { return self } guard case .binaryExpression(let rLeft, let rOp, let rRight) = right else { return self } let newLeft = ASTreeNode.binaryExpression(leftValue: left, operator: op, rightValue: rLeft) return .binaryExpression(leftValue: newLeft, operator: rOp, rightValue: rRight) } /// Rotates this ASTreeNode right, in case it's a binary expression. /// In case it is not, no operation is performed func rotateRight() -> ASTreeNode { guard case .binaryExpression(let left, let op, let right) = self else { return self } guard case .binaryExpression(let lLeft, let lOp, let lRight) = left else { return self } let newRight = ASTreeNode.binaryExpression(leftValue: lRight, operator: op, rightValue: right) return .binaryExpression(leftValue: lLeft, operator: lOp, rightValue: newRight) } /// Gets the source range for this node. In case this is a complex recursive expression (e.g. a binary expression), /// it returns the entire range of the expression's inner components. /// In case this is an invalid tree node, nil is returned func sourceRange() -> Range<String.Index>? { switch(self) { case .value(let value): return value.source.inputRange case .binaryExpression(let left, _, let right): guard let lr = left.sourceRange(), let rr = right.sourceRange() else { return nil } return (lr.lowerBound..<rr.upperBound) case .unaryExpression(_, let node): return node.sourceRange() case .parenthesizedExpression(let node): return node.sourceRange() case .invalidAST: return nil } } /// Returns the entire complex string resulting from collapsing this expression. /// Returns nil, if it's an invalid tree. func stringRepresentation() -> String? { switch(self) { case .value(let value): return value.source.tokenString case .binaryExpression(let left, let op, let right): guard let lstring = left.stringRepresentation(), let rstring = right.stringRepresentation() else { return nil } return "\(lstring)\(op.rawValue)\(rstring)" case .unaryExpression(let op, let node): return "\(op.rawValue)\(node.stringRepresentation())" case .parenthesizedExpression(let node): return "(\(node.stringRepresentation()))" case .invalidAST: return nil } } /// Returns the entire complex string resulting from collapsing this expression, on top of a given source string. /// Returns nil, if it's an invalid tree. func sourceString(onString source: String) -> String? { return sourceRange().flatMap { source[$0] } } }
mit
ac423f09435854336eafa485d809f4c5
34.561224
129
0.605739
4.918843
false
false
false
false
apstrand/loggy
LoggyTools/GPSTracker.swift
1
8663
// // GPSTracker.swift // Loggy // // Created by Peter Strand on 2017-06-19. // Copyright © 2017 Peter Strand. All rights reserved. // import Foundation import CoreLocation public class GPSTracker { public typealias TrackPointLogger = (TrackPoint, Bool) -> Void public typealias StateMonitor = (Bool) -> Void var loggers : [(Int,TrackPointLogger)] = [] var locationTrackers: [Int] = [] var loggerId = 0 let loc_mgr : CLLocationManager var pendingTracking = false var pendingOneshotTracking : [((TrackPoint) -> Void)] = [] var loc_delegate : LocDelegate! = nil private var isActive = false var state_callback : StateMonitor? struct Config { var timeThreshold: Double var distThreshold: Double func isSignificant(_ pt1: TrackPoint, _ pt2: TrackPoint) -> Bool { var time_diff = Double.greatestFiniteMagnitude let tm1 = pt1.timestamp let tm2 = pt2.timestamp time_diff = tm1.timeIntervalSince(tm2) let dist_diff = GPSTracker.greatCircleDist(pt1.location, pt2.location) return dist_diff > distThreshold || time_diff > timeThreshold } } var config : Config = Config(timeThreshold: 10, distThreshold: 1) var last_point : TrackPoint? var last_minor_point : TrackPoint? public init() { loc_mgr = CLLocationManager() let delegate = LocDelegate(self) loc_mgr.delegate = delegate loc_delegate = delegate } public func monitorState(callback : @escaping StateMonitor) { self.state_callback = callback self.state_callback?(isActive) } func startPendingTracking() { if pendingTracking || pendingOneshotTracking.count > 0{ loc_mgr.startUpdatingLocation() print("GPS.startUpdatingLocation()") isActive = true pendingTracking = false self.state_callback?(isActive) } } public func requestLocationTracking() -> Token { loggerId += 1 let removeId = loggerId self.locationTrackers.append(removeId) if !isActive { start() } assert((isActive || pendingTracking) == (self.locationTrackers.count > 0)) return TokenImpl { if let ix = self.locationTrackers.index(of: removeId) { self.locationTrackers.remove(at: ix) if self.locationTrackers.isEmpty { self.stop() } } } } public func addTrackPointLogger(_ logger : @escaping TrackPointLogger) -> Token { loggerId += 1 let removeId = loggerId self.loggers.append((removeId,logger)) return TokenImpl { for ix in self.loggers.indices { if self.loggers[ix].0 == removeId { self.loggers.remove(at: ix) break } } } } private func start() { pendingTracking = true internalStart() assert(isActive != pendingTracking); assert((isActive || pendingTracking) == (self.locationTrackers.count > 0)) } private func internalStart() { let status = CLLocationManager.authorizationStatus() print("start: gps status: \(status.rawValue)") switch status { case .notDetermined: // loc_mgr?.requestWhenInUseAuthorization() loc_mgr.requestAlwaysAuthorization() break case .authorizedAlways, .authorizedWhenInUse: startPendingTracking() default: break } } private func stop() { pendingTracking = false internalStop() assert(isActive == (self.locationTrackers.count > 0)) } fileprivate func internalStop() { print("GPS.stopUpdatingLocation()") loc_mgr.stopUpdatingLocation() isActive = false self.state_callback?(isActive) } public func currentLocation() -> TrackPoint? { if let pt = last_minor_point, isActive { return pt } else { return nil } } public func withCurrentLocation(callback: @escaping (TrackPoint) -> Void) { if let pt = last_minor_point, isActive { callback(pt) } else { pendingOneshotTracking.append(callback) internalStart() } } public func isGpsActive() -> Bool { return isActive } func handleNewLocation(_ tp : TrackPoint) { last_minor_point = tp let significant = last_point == nil || config.isSignificant(last_point!, tp) for (_,logger) in loggers { logger(tp, significant) } last_point = tp } class LocDelegate : NSObject, CLLocationManagerDelegate { let parent : GPSTracker init(_ gps : GPSTracker) { parent = gps } func locationManager(_ : CLLocationManager, didUpdateLocations locs: [CLLocation]) { // print("Tells the delegate that new location data is available: [\(locs)]") var last_pt : TrackPoint? for loc in locs { let pt = TrackPoint(location: loc) parent.handleNewLocation(pt) last_pt = pt } if parent.pendingOneshotTracking.count > 0 { if let pt = last_pt { for cb in parent.pendingOneshotTracking { cb(pt) } parent.pendingOneshotTracking.removeAll() } if !parent.pendingTracking { parent.internalStop() } } } func locationManager(_ : CLLocationManager, didFailWithError error: Error) { print("Tells the delegate that the location manager was unable to retrieve a location value.\n\(error)") } func locationManager(_ : CLLocationManager, didFinishDeferredUpdatesWithError: Error?) { print("Tells the delegate that updates will no longer be deferred.") } func locationManagerDidPauseLocationUpdates(_ : CLLocationManager) { print("Tells the delegate that location updates were paused.") } func locationManagerDidResumeLocationUpdates(_ _ : CLLocationManager) { print("Tells the delegate that the delivery of location updates has resumed.\nResponding to Heading Events") } func locationManager(_ : CLLocationManager, didUpdateHeading: CLHeading) { print("Tells the delegate that the location manager received updated heading information.") } func locationManagerShouldDisplayHeadingCalibration(_ : CLLocationManager) -> Bool { print("Asks the delegate whether the heading calibration alert should be displayed.\nResponding to Region Events") return false } func locationManager(_ : CLLocationManager, didEnterRegion: CLRegion) { print("Tells the delegate that the user entered the specified region.") } func locationManager(_ : CLLocationManager, didExitRegion: CLRegion) { print("Tells the delegate that the user left the specified region.") } func locationManager(_ : CLLocationManager, didDetermineState: CLRegionState, for: CLRegion) { print("Tells the delegate about the state of the specified region.") } func locationManager(_ : CLLocationManager, monitoringDidFailFor: CLRegion?, withError: Error) { print("Tells the delegate that a region monitoring error occurred.") } func locationManager(_ : CLLocationManager, didStartMonitoringFor: CLRegion) { print("Tells the delegate that a new region is being monitored.\nResponding to Ranging Events") } func locationManager(_ : CLLocationManager, didRangeBeacons: [CLBeacon], in: CLBeaconRegion) { print("Tells the delegate that one or more beacons are in range.") } func locationManager(_ : CLLocationManager, rangingBeaconsDidFailFor: CLBeaconRegion, withError: Error) { print("Tells the delegate that an error occurred while gathering ranging information for a set of beacons.\nResponding to Visit Events") } func locationManager(_ : CLLocationManager, didVisit: CLVisit) { print("Tells the delegate that a new visit-related event was received.\nResponding to Authorization Changes") } func locationManager(_ : CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { print("didChangeAuthorization: gps status: \(status.rawValue)") switch status { case .authorizedAlways, .authorizedWhenInUse: parent.startPendingTracking() break default: break } } } public static func greatCircleDist(_ loc1: CLLocationCoordinate2D, _ loc2: CLLocationCoordinate2D) -> Double { // Equirectangular approximation // see: http://www.movable-type.co.uk/scripts/latlong.html let lat1 = loc1.latitude let lon1 = loc1.longitude let lat2 = loc2.latitude let lon2 = loc2.longitude let R = 6371000.0 let x = (lon2-lon1) * cos((lat1+lat2)/2); let y = (lat2-lat1); let d = sqrt(x*x + y*y) * R; return d } }
mit
289a829adf91f5a109e2564e2d71d664
30.158273
142
0.664396
4.50442
false
false
false
false
iFallen/HImagePickerUtils-Swift
HImagePickerUtils-Swift/ViewController.swift
1
3905
// // ViewController.swift // HImagePickerUtils-Swift // // Created by JuanFelix on 10/30/15. // Copyright © 2015 SKKJ-JuanFelix. All rights reserved. // import UIKit class ViewController: UIViewController { var image:UIImageView! /// HImagePickerUtils 对象不能为临时变量,不然UIImagePickerController代理方法不会执行 lazy var imagePicker = HImagePickerUtils() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.view.backgroundColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) image = UIImageView(frame: self.view.frame) image.contentMode = .scaleAspectFit self.view.addSubview(image) let center = self.view.center let btnPickPhoto = UIButton(type: UIButtonType.custom) btnPickPhoto.frame = CGRect(x: 0, y: 0, width: 120, height: 30) btnPickPhoto.setTitle("从相册中选", for: UIControlState.normal) btnPickPhoto.addTarget(self, action: #selector(ViewController.buttonAction(button:)), for: .touchUpInside) btnPickPhoto.center = CGPoint(x: center.x, y: center.y - 20) btnPickPhoto.tag = 110 self.view.addSubview(btnPickPhoto) let btnTakePhoto = UIButton(type: UIButtonType.custom) btnTakePhoto.frame = CGRect(x: 0, y: 0, width: 120, height: 30) btnTakePhoto.setTitle("拍一张", for: UIControlState.normal) btnTakePhoto.addTarget(self, action: #selector(ViewController.buttonAction(button:)), for: .touchUpInside) btnTakePhoto.center = CGPoint(x: center.x, y: center.y + 20) btnTakePhoto.tag = 112 self.view.addSubview(btnTakePhoto) } func buttonAction(button:UIButton!){ switch button.tag{ case 110: imagePicker.choosePhoto(presentFrom: self, completion: { [unowned self] (image, status) in if status == .success { self.image.image = image }else{ if status == .denied{ HImagePickerUtils.showTips(at: self,type: .choosePhoto) }else{ let alert = UIAlertController(title: "提示", message: status.description(), preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "好的", style: UIAlertActionStyle.default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) } } }) case 112: imagePicker.takePhoto(presentFrom: self, completion: { [unowned self] (image, status) in if status == .success { self.image.image = image }else{ if status == .denied{ HImagePickerUtils.showTips(at: self,type: .takePhoto) }else{ let alert = UIAlertController(title: "提示", message: status.description(), preferredStyle: UIAlertControllerStyle.alert) let action = UIAlertAction(title: "好的", style: UIAlertActionStyle.default, handler: nil) alert.addAction(action) self.present(alert, animated: true, completion: nil) } } }) default: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
f31b35f608403e6286864eb86cef1b6e
41.577778
147
0.562109
4.893997
false
false
false
false
elkanaoptimove/OptimoveSDK
OptimoveSDK/Optimove/Optimove.swift
1
16994
// // Optimove.swift // iOS-SDK // // Created by Mobile Developer Optimove on 04/09/2017. // Copyright © 2017 Optimove. All rights reserved. // import UIKit import UserNotifications protocol OptimoveNotificationHandling { func didReceiveRemoteNotification(userInfo:[AnyHashable : Any], didComplete:@escaping (UIBackgroundFetchResult) -> Void) func didReceive(response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping (() -> Void)) } @objc protocol OptimoveDeepLinkResponding { @objc func register(deepLinkResponder responder: OptimoveDeepLinkResponder) @objc func unregister(deepLinkResponder responder: OptimoveDeepLinkResponder) } protocol OptimoveEventReporting:class { func report(event: OptimoveEvent,completionHandler: (() -> Void)?) func dispatch() } /** The entry point of Optimove SDK. Initialize and configure Optimove using Optimove.sharedOptimove.configure. */ @objc public final class Optimove: NSObject { //MARK: - Attributes var optiPush: OptiPush var optiTrack: OptiTrack var realTime: RealTime var eventWarehouse: OptimoveEventConfigsWarehouse? private let notificationHandler: OptimoveNotificationHandling private let deviceStateMonitor: OptimoveDeviceStateMonitor static var swiftStateDelegates: [ObjectIdentifier: OptimoveSuccessStateListenerWrapper] = [:] static var objcStateDelegate: [ObjectIdentifier: OptimoveSuccessStateDelegateWrapper] = [:] private let stateDelegateQueue = DispatchQueue(label: "com.optimove.sdk_state_delegates") private var optimoveTestTopic: String { return "test_ios_\(Bundle.main.bundleIdentifier ?? "")" } //MARK: - Deep Link private var deepLinkResponders = [OptimoveDeepLinkResponder]() var deepLinkComponents: OptimoveDeepLinkComponents? { didSet { guard let dlc = deepLinkComponents else { return } for responder in deepLinkResponders { responder.didReceive(deepLinkComponent: dlc) } } } // MARK: - API //MARK: - Initializers /// The shared instance of optimove singleton @objc public static let sharedInstance: Optimove = { let instance = Optimove() return instance }() private init(notificationListener: OptimoveNotificationHandling = OptimoveNotificationHandler(), deviceStateMonitor: OptimoveDeviceStateMonitor = OptimoveDeviceStateMonitor()) { self.deviceStateMonitor = deviceStateMonitor self.notificationHandler = notificationListener self.optiPush = OptiPush(deviceStateMonitor: deviceStateMonitor) self.optiTrack = OptiTrack(deviceStateMonitor: deviceStateMonitor) self.realTime = RealTime(deviceStateMonitor: deviceStateMonitor) } /// The starting point of the Optimove SDK /// /// - Parameter info: Basic client information received on the onboarding process with Optimove @objc public func configure(for tenantInfo: OptimoveTenantInfo) { configureLogger() OptiLogger.debug("Start Configure Optimove SDK") storeTenantInfo(tenantInfo) startNormalInitProcess { (sucess) in guard sucess else { OptiLogger.debug("Normal initializtion failed") return } OptiLogger.debug("Normal Initializtion success") self.didFinishInitializationSuccessfully() } } //MARK: - Private Methods /// stores the user information that was provided during configuration /// /// - Parameter info: user unique info private func storeTenantInfo(_ info: OptimoveTenantInfo) { UserInSession.shared.tenantToken = info.token UserInSession.shared.version = info.version UserInSession.shared.configurationEndPoint = info.url UserInSession.shared.isClientHasFirebase = info.hasFirebase UserInSession.shared.isClientUseFirebaseMessaging = info.useFirebaseMessaging OptiLogger.debug("stored user info in local storage: \ntoken:\(info.token)\nversion:\(info.version)\nend point:\(info.url)\nhas firebase:\(info.hasFirebase)\nuse Messaging: \(info.useFirebaseMessaging)") } private func configureLogger() { OptiLogger.configure() } } // MARK: - Initialization API extension Optimove { func startNormalInitProcess(didSucceed: @escaping ResultBlockWithBool) { OptiLogger.debug("Start Optimove component initialization from remote") if RunningFlagsIndication.isSdkRunning { OptiLogger.error("Skip normal initializtion since SDK already running") didSucceed(true) return } OptimoveSDKInitializer(deviceStateMonitor: deviceStateMonitor).initializeFromRemoteServer { success in guard success else { OptimoveSDKInitializer(deviceStateMonitor: self.deviceStateMonitor).initializeFromLocalConfigs { success in didSucceed(success) } return } didSucceed(success) } } func startUrgentInitProcess(didSucceed: @escaping ResultBlockWithBool) { OptiLogger.debug("Start Optimove urgent initiazlition process") if RunningFlagsIndication.isSdkRunning { OptiLogger.error("Skip urgent initializtion since SDK already running") didSucceed(true) return } OptimoveSDKInitializer(deviceStateMonitor: self.deviceStateMonitor).initializeFromLocalConfigs { success in didSucceed(success) } } func didFinishInitializationSuccessfully() { RunningFlagsIndication.isInitializerRunning = false RunningFlagsIndication.isSdkRunning = true for (_,delegate) in Optimove.swiftStateDelegates { delegate.observer?.optimove(self, didBecomeActiveWithMissingPermissions: deviceStateMonitor.getMissingPermissions()) } } } // MARK: - SDK state observing //TODO: expose to @objc extension Optimove { public func registerSuccessStateListener(_ delegate: OptimoveSuccessStateListener) { if RunningFlagsIndication.isSdkRunning { delegate.optimove(self, didBecomeActiveWithMissingPermissions: self.deviceStateMonitor.getMissingPermissions()) return } stateDelegateQueue.async { Optimove.swiftStateDelegates[ObjectIdentifier(delegate)] = OptimoveSuccessStateListenerWrapper(observer: delegate) } } public func unregisterSuccessStateListener(_ delegate: OptimoveSuccessStateListener) { stateDelegateQueue.async { Optimove.swiftStateDelegates[ObjectIdentifier(delegate)] = nil } } @available(swift, obsoleted: 1.0) @objc public func registerSuccessStateDelegate(_ delegate:OptimoveSuccessStateDelegate) { if RunningFlagsIndication.isSdkRunning { delegate.optimove(self, didBecomeActiveWithMissingPermissions: self.deviceStateMonitor.getMissingPersmissions()) return } stateDelegateQueue.async { Optimove.objcStateDelegate[ObjectIdentifier(delegate)] = OptimoveSuccessStateDelegateWrapper(observer: delegate) } } @available(swift, obsoleted: 1.0) @objc public func unregisterSuccessStateDelegate(_ delegate:OptimoveSuccessStateDelegate) { stateDelegateQueue.async { Optimove.objcStateDelegate[ObjectIdentifier(delegate)] = nil } } } // MARK: - Notification related API extension Optimove { /// Validate user notification permissions and sends the payload to the message handler /// /// - Parameters: /// - userInfo: the data payload as sends by the the server /// - completionHandler: an indication to the OS that the data is ready to be presented by the system as a notification @objc public func didReceiveRemoteNotification(userInfo: [AnyHashable: Any], didComplete: @escaping (UIBackgroundFetchResult) -> Void) -> Bool { OptiLogger.debug("Receive Remote Notification") guard isOptipushNotification(userInfo) else { return false } notificationHandler.didReceiveRemoteNotification(userInfo: userInfo, didComplete: didComplete) return true } /// Report user response to optimove notifications and send the client the related deep link to open /// /// - Parameters: /// - response: The user response /// - completionHandler: Indication about the process ending @objc public func didReceive(response:UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) -> Bool { guard isOptipushNotification(response.notification.request.content.userInfo) else { return false } notificationHandler.didReceive(response: response, withCompletionHandler: completionHandler) return true } } // MARK: - OptiPush related API extension Optimove { /// Request to handle APNS <-> FCM regisration process /// /// - Parameter deviceToken: A token that was received in the appDelegate callback @objc public func application(didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { optiPush.application(didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } /// Request to subscribe to test campaign topics @objc public func startTestMode() { registerToOptipushTopic(optimoveTestTopic) } /// Request to unsubscribe from test campaign topics @objc public func stopTestMode() { unregisterFromOptipushTopic(optimoveTestTopic) } /// Request to register to topic /// /// - Parameter topic: The topic name @objc public func registerToOptipushTopic(_ topic: String, didSucceed: ((Bool)->())? = nil) { if RunningFlagsIndication.isComponentRunning(.optiPush) { optiPush.subscribeToTopic(topic: topic,didSucceed: didSucceed) } } /// Request to unregister from topic /// /// - Parameter topic: The topic name @objc public func unregisterFromOptipushTopic(_ topic: String,didSucceed: ((Bool)->())? = nil) { if RunningFlagsIndication.isComponentRunning(.optiPush) { optiPush.unsubscribeFromTopic(topic: topic,didSucceed: didSucceed) } } @objc public func optimove(didReceiveFirebaseRegistrationToken fcmToken: String ) { optiPush.didReceiveFirebaseRegistrationToken(fcmToken: fcmToken) } func performRegistration() { if RunningFlagsIndication.isComponentRunning(.optiPush) { optiPush.performRegistration() } } } extension Optimove: OptimoveDeepLinkResponding { @objc public func register(deepLinkResponder responder: OptimoveDeepLinkResponder) { if let dlc = self.deepLinkComponents { responder.didReceive(deepLinkComponent: dlc) } else { deepLinkResponders.append(responder) } } @objc public func unregister(deepLinkResponder responder: OptimoveDeepLinkResponder) { if let index = self.deepLinkResponders.index(of: responder) { deepLinkResponders.remove(at: index) } } } extension Optimove:OptimoveEventReporting { func report(event: OptimoveEvent, completionHandler: (() -> Void)? = nil) { guard let config = eventWarehouse?.getConfig(ofEvent: event) else { OptiLogger.error("configurations for event: \(event.name) are missing") return } let eventValidationError = OptimoveEventValidator().validate(event: event, withConfig: config) guard eventValidationError == nil else { OptiLogger.error("report event is invalid with error \(eventValidationError.debugDescription)") return } let group = DispatchGroup() if config.supportedOnOptitrack { group.enter() optiTrack.report(event: event, withConfigs: config) { group.leave() } } if config.supportedOnRealTime { guard RunningFlagsIndication.isComponentRunning(.realtime) else {return} group.enter() realTime.report(event: event, withConfigs: config) { group.leave() } } group.notify(queue: .main) { completionHandler?() } } @objc public func dispatchNow() { dispatch() } func dispatch() { if RunningFlagsIndication.isSdkRunning { optiTrack.dispatchNow() } } } // MARK: - optiTrack related API extension Optimove { /// validate the permissions of the client to use optitrack component and if permit sends the report to the apropriate handler /// /// - Parameters: /// - event: optimove event object @objc public func reportEvent(_ event: OptimoveEvent) { if optiTrack.isEnable { report(event: event) } } @objc public func reportScreenVisit(viewControllersIdentifiers: [String], url: URL? = nil) { optiTrack.setScreenEvent(viewControllersIdentifiers: viewControllersIdentifiers, url: url) } /// validate the permissions of the client to use optitrack component and if permit sends the report to the apropriate handler /// /// - Parameters: /// - event: optimove event object @objc(reportEventWithEvent:) public func objc_reportEvent(event: OptimoveEvent) { self.report(event: event) } } // MARK: - set user id API extension Optimove { /// validate the permissions of the client to use optitrack component and if permit validate the userID content and sends: /// - conversion request to the DB /// - new customer registraion to the registration end point /// /// - Parameter userID: the client unique identifier @objc public func set(userID: String) { set(userID: userID) { (success) in } } func set(userID: String, completionHandler: ((Bool) -> Void)?) { guard OptimoveEventValidator().validate(userId: userID) else { OptiLogger.error("user id \(userID) is not valid") return } let userId = userID.trimmingCharacters(in: .whitespaces) if UserInSession.shared.customerID == nil { UserInSession.shared.customerID = userId UserInSession.shared.isRegistrationSuccess = false } else if userId != UserInSession.shared.customerID { OptiLogger.debug("user id changed from \(String(describing: UserInSession.shared.customerID)) to \(userId)" ) UserInSession.shared.customerID = userId UserInSession.shared.isRegistrationSuccess = false } else { return } let concurrentSetUserIdQueue = DispatchQueue(label: "com.optimove.setUserId", attributes: .concurrent) concurrentSetUserIdQueue.async { self.optiTrack.set(userID: userId) } concurrentSetUserIdQueue.async { self.optiPush.performRegistration() } concurrentSetUserIdQueue.async { self.realTime.set(userId: userId ) { status in completionHandler?(status)} } } } //MARK: RealtimeAdditional events extension Optimove { @objc public func registerUser(email:String, userId:String) { set(userID: userId) { (succeed) in if succeed { self.setUserEmail(email: email) } } } @objc public func setUserEmail(email:String) { guard isValidEmail(email: email) else { OptiLogger.debug("email is not valid") return } report(event: SetEmailEvent(email: email)) } private func isValidEmail(email:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: email) } } // MARK: - Helper Methods extension Optimove { private func isOptipushNotification(_ userInfo: [AnyHashable : Any]) -> Bool { return userInfo[Keys.Notification.isOptipush.rawValue] as? String == "true" || userInfo[Keys.Notification.isOptimoveSdkCommand.rawValue] as? String == "true" } }
mit
fad61c49350926bb793e12f4462dc5e0
33.965021
211
0.653034
4.866266
false
false
false
false
iMetalk/TCZDemo
PresentVCDemo/PresentVCDemo/ThirdViewController.swift
1
1906
// // ThirdViewController.swift // PresentVCDemo // // Created by WangSuyan on 2017/2/9. // Copyright © 2017年 WangSuyan. All rights reserved. // import UIKit class ThirdViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() title = "Third" view.backgroundColor = UIColor.white // Do any additional setup after loading the view. } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print("self") print(self) print("viewControllers") print(self.navigationController?.viewControllers ?? "NULL") print("viewControllers first") print(self.navigationController?.viewControllers.first ?? "NULL") let firstVC = self.navigationController?.viewControllers.first let firstNav = firstVC?.presentingViewController as! UINavigationController print("firstVC presenting") print(firstVC?.presentingViewController ?? "NULL") print("firstNav presenting") print(firstNav.presentingViewController ?? "NULL") print("firstVC viewControllers") print(firstNav.viewControllers) let fourVC = FourViewController() self.navigationController?.pushViewController(fourVC, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
6ebe44840512de0e1c26eb18c003b192
28.734375
106
0.648975
5.345506
false
false
false
false
material-components/material-components-ios
components/Cards/examples/CardsShapedEditReorderExample.swift
2
7475
// Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialCards import MaterialComponents.MaterialShapeLibrary import MaterialComponents.MaterialContainerScheme class ShapedCardCollectionCell: MDCCardCollectionCell { override init(frame: CGRect) { super.init(frame: frame) commonShapedCardCollectionCellInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonShapedCardCollectionCellInit() } func commonShapedCardCollectionCellInit() { let shapeGenerator = MDCRectangleShapeGenerator() shapeGenerator.topLeftCorner = MDCCutCornerTreatment(cut: 20) self.shapeGenerator = shapeGenerator self.isAccessibilityElement = true self.accessibilityTraits = .button self.accessibilityLabel = "Shaped collection cell" } } class CardsShapedEditReorderExampleViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @objc var containerScheme: MDCContainerScheming override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { containerScheme = MDCContainerScheme() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } enum ToggleMode: Int { case edit = 1 case reorder } let collectionView = UICollectionView( frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) var dataSource = [(Int, Bool)]() var longPressGesture: UILongPressGestureRecognizer! var toggle = ToggleMode.reorder var toggleButton: UIButton! override func viewDidLoad() { super.viewDidLoad() collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = UIColor(white: 0.9, alpha: 1) collectionView.alwaysBounceVertical = true collectionView.register(ShapedCardCollectionCell.self, forCellWithReuseIdentifier: "Cell") collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = true view.addSubview(collectionView) navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Reorder", style: .plain, target: self, action: #selector(toggleModes)) longPressGesture = UILongPressGestureRecognizer( target: self, action: #selector(handleReordering(gesture:))) longPressGesture.cancelsTouchesInView = false collectionView.addGestureRecognizer(longPressGesture) for i in 0..<20 { dataSource.append((i, false)) } let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor), collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), ]) collectionView.contentInsetAdjustmentBehavior = .always } func preiOS11Constraints() { self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) } @objc func toggleModes() { if toggle == .edit { toggle = .reorder navigationItem.rightBarButtonItem?.title = "Reorder" } else if toggle == .reorder { toggle = .edit navigationItem.rightBarButtonItem?.title = "Edit" } collectionView.reloadData() } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: "Cell", for: indexPath) as! MDCCardCollectionCell cell.applyTheme(withScheme: containerScheme) cell.backgroundColor = .white cell.isSelectable = (toggle == .edit) return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if toggle == .edit { dataSource[indexPath.item].1 = !dataSource[indexPath.item].1 } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return dataSource.count } func collectionView( _ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath ) { } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let cardSize = (collectionView.bounds.size.width / 3) - 12 return CGSize(width: cardSize, height: cardSize) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int ) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath ) -> Bool { return toggle == .reorder } @objc func handleReordering(gesture: UILongPressGestureRecognizer) { if toggle == .reorder { switch gesture.state { case .began: guard let selectedIndexPath = collectionView.indexPathForItem( at: gesture.location(in: collectionView)) else { break } collectionView.beginInteractiveMovementForItem(at: selectedIndexPath) case .changed: collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view)) case .ended: collectionView.endInteractiveMovement() default: collectionView.cancelInteractiveMovement() } } } } extension CardsShapedEditReorderExampleViewController { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Cards", "Shaped Edit/Reorder"], "primaryDemo": false, "presentable": false, ] } }
apache-2.0
b908a5f6dfee5c8b29dfe4623ab9d1be
29.141129
98
0.718395
5.227273
false
false
false
false
debugsquad/nubecero
nubecero/Controller/Photos/CPhotos.swift
1
2552
import UIKit class CPhotos:CController { private weak var viewPhotos:VPhotos! deinit { NotificationCenter.default.removeObserver(self) MPhotos.sharedInstance.cleanResources() } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver( self, selector:#selector(notifiedPhotosLoaded(sender:)), name:Notification.photosLoaded, object:nil) MPhotos.sharedInstance.loadPhotos() } override func loadView() { let viewPhotos:VPhotos = VPhotos(controller:self) self.viewPhotos = viewPhotos view = viewPhotos } //MARK: notified func notifiedPhotosLoaded(sender notification:Notification) { DispatchQueue.main.async { [weak self] in self?.viewPhotos.photosLoaded() } } //MARK: private private func asyncNewAlbum(name:String) { guard let userId:MSession.UserId = MSession.sharedInstance.user.userId else { return } let parentUser:String = FDatabase.Parent.user.rawValue let propertyAlbums:String = FDatabaseModelUser.Property.albums.rawValue let albumsPath:String = "\(parentUser)/\(userId)/\(propertyAlbums)" let modelAlbum:FDatabaseModelAlbum = FDatabaseModelAlbum(name:name) let jsonAlbum:Any = modelAlbum.modelJson() let _:MPhotos.AlbumId = FMain.sharedInstance.database.createChild( path:albumsPath, json:jsonAlbum) MPhotos.sharedInstance.loadPhotos() } //MARK: public func selected(item:MPhotosItem) { let albumController:CPhotosAlbum = CPhotosAlbum(model:item) parentController.scrollRight( controller:albumController, underBar:false, pop:false) } func newAlbum(name:String) { viewPhotos.startLoading() DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncNewAlbum(name:name) } } func storeAd() { let modelAd:MStoreAdAlbum = MStoreAdAlbum() let adController:CStoreAd = CStoreAd(model:modelAd) parentController.over( controller:adController, pop:false, animate:true) } }
mit
2edaae351eb4185ffe9654c5129f3af3
24.019608
79
0.58268
4.945736
false
false
false
false
rodrigosoldi/XCTestsExample
XCTestsExampleTests/SearchSongsViewControllerTests.swift
1
3579
// // SearchSongViewControllerTests.swift // XCTestsExample // // Created by Emannuel Fernandes de Oliveira Carvalho on 9/7/16. // Copyright © 2016 Rodrigo Soldi Lopes. All rights reserved. // import XCTest @testable import XCTestsExample class MockViewControllerOutput: SearchSongViewControllerOutput { var searchSongCalled = false var parameter: String? func searchSong(request: SearchSong.Request) { searchSongCalled = true parameter = request.search } } class MockTableView: UITableView { var reloadDataCalled = false override func reloadData() { reloadDataCalled = true } } class SearchSongsViewControllerTests: XCTestCase { func testLoading() { guard let vc = getViewController(true) else { fail() ; return } XCTAssert(vc.searchBar != nil, "It should have set the outlets") XCTAssert(vc.tableView != nil, "It should have set the outlets") } func testTableViewDataSource() { guard let vc = getViewController(true) else { fail() ; return } let sections = vc.numberOfSectionsInTableView(vc.tableView) XCTAssert(sections == 1, "It should be 1") //////// let songs = [("", ""), ("", ""), ("", "")] vc.songs = songs // <---- muito exposto, não? let rows = vc.tableView(vc.tableView, numberOfRowsInSection: 0) XCTAssert(rows == 3, "It should be equal to `songs.count`") ////////// // o cellForRow é complicado.. fica pra outro dia (2h50 já!) hahaha } func testSearchSong() { guard let vc = getViewController(true) else { fail() ; return } let output = MockViewControllerOutput() vc.output = output vc.searchSong("My string") XCTAssert(output.searchSongCalled, "It should have called searchSong()") XCTAssert(output.parameter == "My string", "It should have passed the string") } func testReloadingData() { guard let vc = getViewController(true) else { fail() ; return } let output = MockViewControllerOutput() let tableView = MockTableView() vc.output = output vc.tableView = tableView let songs = [ ("1", "um"), ("2", "dois") ] let viewModel = SearchSong.ViewModel(songs: songs) vc.displaySearchedSongs(viewModel) XCTAssert(tableView.reloadDataCalled, "It should have called reloadData()") XCTAssert(vc.songs[0].0 == "1" && vc.songs[0].1 == "um" && vc.songs[1].0 == "2" && vc.songs[1].1 == "dois", "It should have set the songs") } // MARK: - helper methods func getViewController(loading: Bool) -> SearchSongViewController? { guard let vc = UIStoryboard(name: "Main", bundle: nil) .instantiateViewControllerWithIdentifier("SongsVC") as? SearchSongViewController else { return nil } if loading { let _ = vc.view // so it will call viewDidLoad() 😉 } return vc } } extension XCTestCase { func fail() { XCTAssert(false, "It shall not pass ✋🏻😎") } }
mit
8b984447255b6267071c37225dcb2758
26.415385
75
0.539562
4.809717
false
true
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/AviasalesSource/PriceCalendar/PriceCalendarChart/PriceCalendarPriceLevelView.swift
1
981
// // PriceCalendarPriceLevelView.swift // Aviasales iOS Apps // // Created by Dmitry Ryumin on 19/06/15. // Copyright (c) 2015 aviasales. All rights reserved. // import UIKit class PriceCalendarPriceLevelView: UIView { private let lineLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(lineLayer) lineLayer.strokeColor = JRColorScheme.priceCalendarMinPriceLevelColor().cgColor lineLayer.fillColor = nil lineLayer.lineWidth = JRPixel() isUserInteractionEnabled = false } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 0)) path.addLine(to: CGPoint(x: frame.width, y: 0)) lineLayer.path = path.cgPath lineLayer.frame = bounds } }
mit
57db59faefe63e700dc0037e19bd409d
23.525
87
0.655454
4.2103
false
false
false
false
brokenhandsio/SteamPress
Tests/SteamPressTests/Helpers/TestWorld+Responses.swift
1
2912
import Vapor @testable import SteamPress extension TestWorld { func getResponse<T>(to path: String, method: HTTPMethod = .GET, headers: HTTPHeaders = .init(), decodeTo type: T.Type) throws -> T where T: Content { let response = try getResponse(to: path, method: method, headers: headers) return try response.content.decode(type).wait() } func getResponseString(to path: String, headers: HTTPHeaders = .init()) throws -> String { let data = try getResponse(to: path, headers: headers).http.body.convertToHTTPBody().data return String(data: data!, encoding: .utf8)! } func getResponse<T: Content>(to path: String, method: HTTPMethod = .POST, body: T, loggedInUser: BlogUser? = nil, passwordToLoginWith: String? = nil, headers: HTTPHeaders = .init()) throws -> Response { let request = try setupRequest(to: path, method: method, loggedInUser: loggedInUser, passwordToLoginWith: passwordToLoginWith, headers: headers) try request.content.encode(body) return try getResponse(to: request) } func getResponse(to path: String, method: HTTPMethod = .GET, headers: HTTPHeaders = .init(), loggedInUser: BlogUser? = nil) throws -> Response { let request = try setupRequest(to: path, method: method, loggedInUser: loggedInUser, passwordToLoginWith: nil, headers: headers) return try getResponse(to: request) } func setupRequest(to path: String, method: HTTPMethod = .POST, loggedInUser: BlogUser? = nil, passwordToLoginWith: String? = nil, headers: HTTPHeaders = .init()) throws -> Request { var request = HTTPRequest(method: method, url: URL(string: path)!, headers: headers) request.cookies["steampress-session"] = try setLoginCookie(for: loggedInUser, password: passwordToLoginWith) guard let app = context.app else { fatalError("App has already been deinitiliased") } return Request(http: request, using: app) } func setLoginCookie(for user: BlogUser?, password: String? = nil) throws -> HTTPCookieValue? { if let user = user { let loginData = LoginData(username: user.username, password: password ?? user.password) var loginPath = "/admin/login" if let path = context.path { loginPath = "/\(path)\(loginPath)" } let loginResponse = try getResponse(to: loginPath, method: .POST, body: loginData) let sessionCookie = loginResponse.http.cookies["steampress-session"] return sessionCookie } else { return nil } } func getResponse(to request: Request) throws -> Response { guard let app = context.app else { fatalError("App has already been deinitiliased") } let responder = try app.make(Responder.self) return try responder.respond(to: request).wait() } }
mit
73cd02bfa4d62f6836e4325a00e896c7
49.206897
206
0.658997
4.314074
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Me/MyThreads/MyThreadsBaseTableViewController.swift
1
3745
// // MyThreadsBaseTableViewController.swift // HiPDA // // Created by leizh007 on 2017/7/9. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation class MyThreadsBaseTableViewController: BaseViewController { var tableView: BaseTableView! fileprivate var isDataLoaded = false var viewModel: MyThreadsBaseTableViewModel! override func viewDidLoad() { super.viewDidLoad() skinViewModel() skinTableView() } func skinViewModel() { fatalError("Must be overrided!") } func skinTableView() { let frame = CGRect(x: 0, y: 0, width: C.UI.screenWidth, height: C.UI.screenHeight - 64) tableView = BaseTableView(frame: frame, style: .grouped) view.addSubview(tableView) tableView.hasRefreshHeader = true tableView.hasLoadMoreFooter = true tableView.delegate = self tableView.dataSource = self tableView.dataLoadDelegate = self tableView.status = .normal } func loadData() { guard !isDataLoaded else { return } isDataLoaded = true tableView.status = .loading loadNewData() } func tabBarItemDidSelectRepeatedly() { guard tableView.status != .noResult && tableView.status != .loading && tableView.status != .tapToLoad else { return } if tableView.contentOffset.y > 0 { tableView.setContentOffset(.zero, animated: true) } else { tableView.refreshing() } } } // MARK: - UITableViewDelegate extension MyThreadsBaseTableViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return .leastNormalMagnitude } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return .leastNormalMagnitude } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) URLDispatchManager.shared.linkActived(viewModel.jumpURL(at: indexPath.row)) } } // MARK: - UITableViewDataSource extension MyThreadsBaseTableViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.numberOfItems() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return UITableViewCell(style: .default, reuseIdentifier: "cell") } } // MARK: - DataLoadDelegate extension MyThreadsBaseTableViewController: DataLoadDelegate { func loadNewData() { viewModel.loadFirstPage { [weak self] result in self?.handleDataLoadResult(result) } } func loadMoreData() { viewModel.loadNextPage { [weak self] result in self?.handleDataLoadResult(result) } } fileprivate func handleDataLoadResult(_ result: HiPDA.Result<Void, NSError>) { switch result { case .success(_): tableView.status = viewModel.hasData ? .normal : .noResult case .failure(let error): showPromptInformation(of: .failure(error.localizedDescription)) tableView.status = tableView.status == .loading ? .tapToLoad : .normal } tableView.reloadData() tableView.endRefreshing() if viewModel.hasMoreData { tableView.endLoadMore() tableView.resetNoMoreData() } else { tableView.endLoadMoreWithNoMoreData() } } }
mit
263b939805b995bf0493c1d86c3475fd
29.92562
125
0.650187
5.070461
false
false
false
false
brentdax/swift
test/RemoteAST/existentials.swift
6
1402
// UNSUPPORTED: linux // <rdar://problem/42793848> // RUN: %target-swift-remoteast-test %s | %FileCheck %s // REQUIRES: swift-remoteast-test @_silgen_name("printDynamicTypeAndAddressForExistential") func printDynamicTypeAndAddressForExistential<T>(_: T) struct MyStruct<T, U, V> { let x: T let y: U let z: V } // Case one, small opaque (fits into the inline buffer). // CHECK: MyStruct<Int, Int, Int> let smallStruct = MyStruct(x : 1, y: 2, z: 3) printDynamicTypeAndAddressForExistential(smallStruct as Any) // Case two, large opaque (boxed representation). // CHECK-NEXT: MyStruct<(Int, Int, Int), (Int, Int, Int), (Int, Int, Int)> let largeStruct = MyStruct(x: (1,1,1), y: (2,2,2), z: (3,3,3)) printDynamicTypeAndAddressForExistential(largeStruct as Any) class MyClass<T, U> { let x: T let y: (T, U) init(x: T, y: (T, U)) { self.x = x self.y = y } } // Case three, class existential (adheres to AnyObject protocol).a // CHECK-NEXT: MyClass<Int, Int> let mc = MyClass(x : 23, y : (42, 44)) as AnyObject printDynamicTypeAndAddressForExistential(mc) enum MyError : Error { case a case b } // Case four: error existential. // CHECK-NEXT: MyError let q : Error = MyError.a printDynamicTypeAndAddressForExistential(q) // Case five: existential metatypes. // CHECK-NEXT: Any.Type let metatype : Any.Type = Any.self printDynamicTypeAndAddressForExistential(metatype)
apache-2.0
eb715c2d6b9fba8f1e12a2807e06e49b
25.45283
74
0.698288
3.10177
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/binary-search.swift
2
528
/** * https://leetcode.com/problems/binary-search/ * * */ // Date: Thu Oct 8 08:54:13 PDT 2020 class Solution { func search(_ nums: [Int], _ target: Int) -> Int { var left = 0 var right = nums.count - 1 while left <= right { let mid = left + (right - left) / 2 if nums[mid] == target { return mid } if nums[mid] > target { right = mid - 1 } else { left = mid + 1 } } return -1 } }
mit
f8cc5427e0caae01b0535f1c3d07fb98
23.045455
54
0.433712
3.771429
false
false
false
false
zwaldowski/ParksAndRecreation
Latest/HTMLDocument.playground/Pages/Unit Tests.xcplaygroundpage/Contents.swift
1
5317
import XCTest class HTMLDocumentTests: XCTestCase { private static var html: HTMLDocument.Node! override class func setUp() { super.setUp() let bundle = Bundle(for: HTMLDocumentTests.self) guard let url = bundle.url(forResource: "xml", withExtension: "html"), let htmlString = try? String(contentsOf: url) else { XCTFail("Unable to find test HTML document") return } html = HTMLDocument.parse(htmlString) XCTAssertNotNil(html) } override class func tearDown() { html = nil super.tearDown() } private var html: HTMLDocument.Node { return HTMLDocumentTests.html } func testDoesNotParseEmptyString() { let empty = HTMLDocument.parse("") XCTAssertNil(empty) } func testParsesTextFragment() { let fragment = HTMLDocument.parse("Lorem ipsum dolor amet") XCTAssertNotNil(fragment) } func testParsesEscapedFragmentWithOneNode() { let fragment = HTMLDocument.parseFragment("&lt;p&gt;Less than character: 4 &lt; 5, 5 &gt; 3&lt;/p&gt;") XCTAssertEqual(fragment?.name, "p") XCTAssertEqual(fragment?.kind, .element) XCTAssertEqual(fragment?.content, "Less than character: 4 < 5, 5 > 3") } func testParsesEscapedFragmentWithMultipleNodes() { let fragment = HTMLDocument.parseFragment("&lt;p&gt;Less than character: 4 &lt; 5, 5 &gt; 3&lt;/p&gt;&lt;p&gt;And another paragraph.&lt;/p&gt;") XCTAssertEqual(fragment?.kind, .documentFragment) let paragraph1 = fragment?.first XCTAssertNotNil(paragraph1) XCTAssertEqual(paragraph1?.name, "p") XCTAssertEqual(paragraph1?.kind, .element) XCTAssertEqual(paragraph1?.content, "Less than character: 4 < 5, 5 > 3") let paragraph2 = fragment?.dropFirst().first XCTAssertNotNil(paragraph2) XCTAssertEqual(paragraph2?.name, "p") XCTAssertEqual(paragraph2?.kind, .element) XCTAssertEqual(paragraph2?.content, "And another paragraph.") XCTAssertNil(fragment?.dropFirst(2).first) } func testName() { XCTAssertEqual(html.name, "html") } func testKind() { XCTAssertEqual(html.kind, .element) } func testCollectionIsEmpty() { XCTAssertFalse(html.isEmpty) XCTAssertEqual(html.first?.isEmpty, false) XCTAssertEqual(HTMLDocument.parse("<html />")?.isEmpty, true) } func testCollectionCount() { XCTAssertEqual(html.count, 2) XCTAssertEqual(html.first?.count, 26) XCTAssertEqual(HTMLDocument.parse("<html />")?.count, 0) } func testCollectionFirst() { let head = html.first XCTAssertNotNil(head) XCTAssertEqual(head?.name, "head") XCTAssertEqual(head?.kind, .element) let title = head?.dropFirst().first XCTAssertEqual(title?.name, "title") XCTAssertEqual(title?.kind, .element) XCTAssertEqual(title?.content, "XML - Wikipedia") XCTAssertNil(head?.first?.first) let body = html.dropFirst().first XCTAssertNotNil(body) XCTAssertEqual(body?.name, "body") XCTAssertEqual(body?.kind, .element) let scriptContents = body?.dropFirst(11).first?.first XCTAssertEqual(scriptContents?.name, "") XCTAssertEqual(scriptContents?.kind, .characterDataSection) XCTAssertEqual(scriptContents?.content.isEmpty, false) let footer = body?.dropFirst(9).first XCTAssertEqual(footer?.name, "div") XCTAssertEqual(footer?.kind, .element) XCTAssertEqual(footer?.content.isEmpty, false) XCTAssertEqual(footer?["id"], "footer") XCTAssertNil(footer?.dropFirst(5).first?.first) } func testAttributes() { XCTAssertEqual(html["class"], "client-nojs") XCTAssertEqual(html["lang"], "en") XCTAssertEqual(html["dir"], "ltr") XCTAssertNil(html[""]) XCTAssertNil(html["data:does-not-exist"]) } func testContentForEmptyElement() { let fragment = HTMLDocument.parse("<img />") XCTAssertNotNil(fragment) XCTAssertEqual(fragment?.content.isEmpty, true) } func testDebugDescription() { let description = String(reflecting: html) XCTAssert(description.hasPrefix("<html")) XCTAssert(description.hasSuffix("</html>")) let fragment = HTMLDocument.parse("Lorem ipsum dolor amet") let fragmentDescription = fragment.map(String.init(reflecting:)) ?? "" XCTAssertNotNil(fragment) XCTAssert(fragmentDescription.hasPrefix("<p")) XCTAssert(fragmentDescription.hasSuffix("</p>")) } func testReflection() { let magicMirror = Mirror(reflecting: html) XCTAssertEqual(magicMirror.displayStyle, .struct) XCTAssertNil(magicMirror.superclassMirror) XCTAssertNil(magicMirror.descendant(0, 0, 2, 0)) } func testDocumentReflection() { let magicMirror = Mirror(reflecting: html.document) XCTAssertEqual(magicMirror.displayStyle, .class) XCTAssertNil(magicMirror.superclassMirror) XCTAssertNil(magicMirror.descendant(0, 0, 2, 0)) } } HTMLDocumentTests.defaultTestSuite.run()
mit
edc4f0059bc9e3ccb90cbadf1e823412
31.619632
152
0.644536
4.696996
false
true
false
false
TriangleLeft/Flashcards
ios/Flashcards/UI/Common/PersistentStorage.swift
1
1336
// // PersistentStorage.swift // Flashcards // // Created by Aleksey Kurnosenko on 15.08.16. // Copyright © 2016 TriangleLeft. All rights reserved. // import Foundation import FlashcardsCore class IOSPersistentStorage : NSObject,PersistentStorage { let gson:ComGoogleGsonGson; let userDefaults = NSUserDefaults.standardUserDefaults(); init(_ gson: ComGoogleGsonGson) { self.gson = gson; } func putWithNSString(key: String!, withId value: AnyObject?) { var json:String? = nil; if (value != nil) { json = gson.toJsonWithId(value); } userDefaults.setObject(json, forKey: key); } func getWithNSString(key: String!, withIOSClass clazz: IOSClass!) -> AnyObject? { let json:String? = userDefaults.stringForKey(key); if (json != nil) { return gson.fromJsonWithNSString(json, withIOSClass: clazz); } else { return nil; } } func getWithNSString(key: String!, withIOSClass clazz: IOSClass!, withId defaultValue: AnyObject?) -> AnyObject? { let json:String? = userDefaults.stringForKey(key); if (json != nil) { return gson.fromJsonWithNSString(json, withIOSClass: clazz); } else { return defaultValue; } } }
apache-2.0
0ca591dea7aedb4f47cb12c39c873f99
27.425532
118
0.616479
4.133127
false
false
false
false
pawel-sp/PSZCircularProgressBar
iOS-Example/ViewController.swift
1
1720
// // ViewController.swift // iOS-Example // // Created by Paweł Sporysz on 04.11.2014. // Copyright (c) 2014 Paweł Sporysz. All rights reserved. // import UIKit import PSZCircularProgressBar class ViewController: UIViewController,CircularProgressViewDelegate { // MARK: - Outlets @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var setProgressLabel: UILabel! @IBOutlet weak var slider: UISlider! @IBOutlet weak var circularProgressView: CircularProgressView! @IBOutlet weak var animationSwitch: UISwitch! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() progressLabel.text = "\(50.0)" circularProgressView.delegate = self circularProgressView.addProgressBarColor(UIColor.orangeColor(), aboveProgress:0.25) circularProgressView.addProgressBarColor(UIColor.brownColor(), aboveProgress:0.75) circularProgressView.addProgressBarColor(UIColor.redColor(), aboveProgress:0.50) progressLabel.text = "\(circularProgressView.progress/100)" } // MARK: - Actions @IBAction func sliderValueChangedAction(sender: UISlider) { setProgressLabel.text = "\(sender.value)" } @IBAction func updateProgressBarAction(sender: UIButton) { circularProgressView.setProgress((CGFloat(slider.value)), withAnimation: animationSwitch.on) circularProgressView.setProgress(CGFloat(slider.value), withAnimation: animationSwitch.on) } // MARK: - PSZCircularProgressViewDelegate func circularProgressView(circularProgressView:CircularProgressView, didUpdateProgress progress:CGFloat) { progressLabel.text = "\(progress)" } }
mit
f8ca75128c5948be59ab940182be8888
32.686275
110
0.717695
4.908571
false
false
false
false
MaxKramer/Timber
Timber/Classes/Logger+LogLevels.swift
2
3160
// // Logger+LogLevels.swift // Logger // // Created by Max Kramer on 09/06/2016. // Copyright © 2016 Max Kramer. All rights reserved. // import Foundation extension Logger { /** See [https://logging.apache.org/log4j/2.0/manual/architecture.html](Apache Log4j architecture) for more info - ALL: All levels including custom levels. - DEBUG: Designates fine-grained informational events that are most useful to debug an application. - ERROR: Designates error events that might still allow the application to continue running. - FATAL: Designates very severe error events that will presumably lead the application to abort. - INFO: Designates informational messages that highlight the progress of the application at coarse-grained level. - OFF: The highest possible rank and is intended to turn off logging. - TRACE: Designates finer-grained informational events than the DEBUG. - WARN: Designates potentially harmful situations. ALL < DEBUG < TRACE < INFO < WARN < ERROR < FATAL < OFF. A log request of level p in a logger with level q is enabled if p >= q */ public enum LogLevel: Int, CustomStringConvertible { case All = 0 case Debug case Trace case Info case Warn case Error case Fatal case Off /** Converts the LogLevel into a string - Returns: The name of the log level as a string */ public var description: String { switch self { case .All: return "All" case .Debug: return "Debug" case .Trace: return "Trace" case .Info: return "Info" case .Warn: return "Warn" case .Error: return "Error" case .Fatal: return "Fatal" case .Off: return "Off" } } } } extension Logger.LogLevel: Comparable {} /** Compares the left hand side to the right hand side - Returns: TRUE if equal, FALSE if not */ public func ==(lhs: Logger.LogLevel, rhs: Logger.LogLevel) -> Bool { return lhs.rawValue == rhs.rawValue } /** Compares the left hand side to the right hand side - Returns: TRUE if lhs < rhs, FALSE if not */ public func <(lhs: Logger.LogLevel, rhs: Logger.LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue } /** Compares the left hand side to the right hand side - Returns: TRUE if lhs > rhs, FALSE if not */ public func >(lhs: Logger.LogLevel, rhs: Logger.LogLevel) -> Bool { return lhs.rawValue > rhs.rawValue } /** Compares the left hand side to the right hand side - Returns: TRUE if lhs >= rhs, FALSE if not */ public func >=(lhs: Logger.LogLevel, rhs: Logger.LogLevel) -> Bool { return lhs.rawValue >= rhs.rawValue } /** Compares the left hand side to the right hand side - Returns: TRUE if lhs <= rhs, FALSE if not */ public func <=(lhs: Logger.LogLevel, rhs: Logger.LogLevel) -> Bool { return lhs.rawValue <= rhs.rawValue }
mit
7fd50d6f3c94d7c5959a04603bc88a92
27.205357
118
0.613485
4.339286
false
false
false
false
jianghongbing/APIReferenceDemo
UIKit/UIMenuController/UIMenuController/ViewController.swift
1
4012
// // ViewController.swift // UIMenuController // // Created by jianghongbing on 2017/5/29. // Copyright © 2017年 jianghongbing. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var button: UIButton! lazy var menuController: UIMenuController = { //UIMenuController是一个单例 let menuController = UIMenuController.shared //UIMenuItem不需要指定target,它会依据响应者链去查找该方法,如果都没有实现,会抛出doesNotResonpedSelector的异常 let copyItem = UIMenuItem(title: "复制", action: #selector(copyItemClicked(_:))) let pasteItem = UIMenuItem(title: "粘贴", action: #selector(pasteItemClicked(_:))) let moreItem = UIMenuItem(title: "...", action: #selector(moreItemClicked(_:))) menuController.menuItems = [copyItem, pasteItem, moreItem] // menuController.setTargetRect(self.button.frame, in: self.view) //在self.view的target rect上下左右的地方显示UIMenuController menuController.setTargetRect(CGRect(x: 100, y: 100, width: 200, height: 100), in: self.view) return menuController }() override func viewDidLoad() { super.viewDidLoad() registerMenuControllerNotification() } deinit { unregisterMenuControllerNotification() } //必须实现下面的方法,UIMenuController才能显示出来 override var canBecomeFirstResponder: Bool { return true } //显示指定的实现的action item,如果不override该方法,不是显示系统一些默认MenuItem override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { return self.responds(to: action) && sender is UIMenuController } @IBAction func shorOrHideMenuController(_ sender: Any) { print(menuController.isMenuVisible) if menuController.isMenuVisible { menuController.setMenuVisible(false, animated: true) }else { menuController.arrowDirection = randomMenuControllerArrowDirection() menuController.setMenuVisible(true, animated: true) } } //MARK: private func randomMenuControllerArrowDirection() -> UIMenuControllerArrowDirection { return UIMenuControllerArrowDirection(rawValue: Int(arc4random() % 5))! } // MARK: menuItem Action func copyItemClicked(_ item: UIMenuItem) { print("item:\(item),func:\(#function)") } func pasteItemClicked(_ item: UIMenuItem) { print("item:\(item),func:\(#function)") } func moreItemClicked(_ item: UIMenuItem) { print("item:\(item),func:\(#function)") } override func copy(_ sender: Any?) { print("copy item clicked:"); } // MARK:UIMenuController notification private func registerMenuControllerNotification() { NotificationCenter.default.addObserver(self, selector: #selector(menuControllerWillShow(_:)), name: Notification.Name.UIMenuControllerWillShowMenu, object: nil) //与UIMenuController相关的通知名称 // public static let UIMenuControllerWillShowMenu: NSNotification.Name,将要显示的时候会向target发送该消息 // // public static let UIMenuControllerDidShowMenu: NSNotification.Name,已经显示了,会向target发送该消息 // // public static let UIMenuControllerWillHideMenu: NSNotification.Name 将要隐藏的时候,会向target发送该消息 // // public static let UIMenuControllerDidHideMenu: NSNotification.Name 已经隐藏了,会向target发送该消息 // // public static let UIMenuControllerMenuFrameDidChange: NSNotification.Name frame改变的时候,会向target发送该消息 } func menuControllerWillShow(_ notification: Notification) { print("menuControllerWillShow") } private func unregisterMenuControllerNotification() { NotificationCenter.default.removeObserver(self) } }
mit
0b446993aa700f18a78d2e720e698501
30.211864
168
0.6959
4.740026
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Components/FadeScrollView.swift
2
2156
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation // A scroll view that adds a fade at top or bottom when it scroll // to indicate more content is available to user class FadeScrollView: UIScrollView, UIScrollViewDelegate { private let fadePercentage: Double = 0.1 private let gradientLayer = CAGradientLayer() private let transparentColor = UIColor.clear.cgColor private let opaqueColor = UIColor.black.cgColor private var needsToScroll: Bool { return frame.size.height >= contentSize.height } private var isAtBottom: Bool { return contentOffset.y + frame.size.height >= contentSize.height } private var isAtTop: Bool { return contentOffset.y <= 0 } private var topOpacity: CGColor { let alpha: CGFloat = (needsToScroll || isAtTop) ? 1 : 0 return UIColor(white: 0, alpha: alpha).cgColor } private var bottomOpacity: CGColor { let alpha: CGFloat = (needsToScroll || isAtBottom) ? 1 : 0 return UIColor(white: 0, alpha: alpha).cgColor } override func layoutSubviews() { super.layoutSubviews() self.delegate = self let maskLayer = CALayer() maskLayer.frame = bounds gradientLayer.frame = CGRect(x: bounds.origin.x, y: 0, width: bounds.size.width, height: bounds.size.height) gradientLayer.colors = [topOpacity, opaqueColor, opaqueColor, bottomOpacity] gradientLayer.locations = [0, NSNumber(value: fadePercentage), NSNumber(value: 1 - fadePercentage), 1] maskLayer.addSublayer(gradientLayer) layer.mask = maskLayer } func scrollViewDidScroll(_ scrollView: UIScrollView) { gradientLayer.colors = [topOpacity, opaqueColor, opaqueColor, bottomOpacity] } }
mpl-2.0
5eb4cb3a5b4a18aeb2ef4ccd256c74b5
33.774194
84
0.615955
4.9
false
false
false
false
satyamexilant/TimeApp
KeychainSwift.swift
1
7775
// // KeychainSwift.swift // TimeLoginWindow // // Created by medidi vv satyanarayana murty on 29/02/16. // Copyright © 2016 Medidi vv satyanarayana murty. All rights reserved. // import Security import Foundation /** A collection of helper functions for saving text and data in the keychain. */ public class KeychainSwift { var lastQueryParameters: [String: NSObject]? // Used by the unit tests /// Contains result code from the last operation. Value is noErr (0) for a successful result. public var lastResultCode: OSStatus = noErr var keyPrefix = "" // Can be useful in test. /** Specify an access group that will be used to access keychain items. Access groups can be used to share keychain items between applications. When access group value is nil all application access groups are being accessed. Access group name is used by all functions: set, get, delete and clear. */ public var accessGroup: String? /// Instantiate a KeychainSwift object public init() { } /** - parameter keyPrefix: a prefix that is added before the key in get/set methods. Note that `clear` method still clears everything from the Keychain. */ public init(keyPrefix: String) { self.keyPrefix = keyPrefix } /** Stores the text value in the keychain item under the given key. - parameter key: Key under which the text value is stored in the keychain. - parameter value: Text string to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the text was successfully written to the keychain. */ public func set(value: String, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { if let value = value.dataUsingEncoding(NSUTF8StringEncoding) { return set(value, forKey: key, withAccess: access) } return false } /** Stores the data in the keychain item under the given key. - parameter key: Key under which the data is stored in the keychain. - parameter value: Data to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the text in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the text was successfully written to the keychain. */ public func set(value: NSData, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { delete(key) // Delete any existing key before saving it let accessible = access?.value ?? KeychainSwiftAccessOptions.defaultOption.value let prefixedKey = keyWithPrefix(key) var query = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey, KeychainSwiftConstants.valueData : value, KeychainSwiftConstants.accessible : accessible ] query = addAccessGroupWhenPresent(query) lastQueryParameters = query lastResultCode = SecItemAdd(query as CFDictionaryRef, nil) return lastResultCode == noErr } /** Stores the boolean value in the keychain item under the given key. - parameter key: Key under which the value is stored in the keychain. - parameter value: Boolean to be written to the keychain. - parameter withAccess: Value that indicates when your app needs access to the value in the keychain item. By default the .AccessibleWhenUnlocked option is used that permits the data to be accessed only while the device is unlocked by the user. - returns: True if the value was successfully written to the keychain. */ public func set(value: Bool, forKey key: String, withAccess access: KeychainSwiftAccessOptions? = nil) -> Bool { var localValue = value let data = NSData(bytes: &localValue, length: sizeof(Bool)) return set(data, forKey: key, withAccess: access) } /** Retrieves the text value from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - returns: The text value from the keychain. Returns nil if unable to read the item. */ public func get(key: String) -> String? { if let data = getData(key) { if let currentString = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { return currentString } lastResultCode = -67853 // errSecInvalidEncoding } return nil } /** Retrieves the data from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - returns: The text value from the keychain. Returns nil if unable to read the item. */ public func getData(key: String) -> NSData? { let prefixedKey = keyWithPrefix(key) var query: [String: NSObject] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey, KeychainSwiftConstants.returnData : kCFBooleanTrue, KeychainSwiftConstants.matchLimit : kSecMatchLimitOne ] query = addAccessGroupWhenPresent(query) lastQueryParameters = query var result: AnyObject? lastResultCode = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } if lastResultCode == noErr { return result as? NSData } return nil } /** Retrieves the boolean value from the keychain that corresponds to the given key. - parameter key: The key that is used to read the keychain item. - returns: The boolean value from the keychain. Returns nil if unable to read the item. */ public func getBool(key: String) -> Bool? { guard let data = getData(key) else { return nil } var boolValue = false data.getBytes(&boolValue, length: sizeof(Bool)) return boolValue } /** Deletes the single keychain item specified by the key. - parameter key: The key that is used to delete the keychain item. - returns: True if the item was successfully deleted. */ public func delete(key: String) -> Bool { let prefixedKey = keyWithPrefix(key) var query: [String: NSObject] = [ KeychainSwiftConstants.klass : kSecClassGenericPassword, KeychainSwiftConstants.attrAccount : prefixedKey ] query = addAccessGroupWhenPresent(query) lastQueryParameters = query lastResultCode = SecItemDelete(query as CFDictionaryRef) return lastResultCode == noErr } /** Deletes all Keychain items used by the app. Note that this method deletes all items regardless of the prefix settings used for initializing the class. - returns: True if the keychain items were successfully deleted. */ public func clear() -> Bool { var query: [String: NSObject] = [ kSecClass as String : kSecClassGenericPassword ] query = addAccessGroupWhenPresent(query) lastQueryParameters = query lastResultCode = SecItemDelete(query as CFDictionaryRef) return lastResultCode == noErr } /// Returns the key with currently set prefix. func keyWithPrefix(key: String) -> String { return "\(keyPrefix)\(key)" } func addAccessGroupWhenPresent(items: [String: NSObject]) -> [String: NSObject] { guard let accessGroup = accessGroup else { return items } var result: [String: NSObject] = items result[KeychainSwiftConstants.accessGroup] = accessGroup return result } }
mit
4140111b906f33d3d75686cc2236105c
30.864754
294
0.707615
4.98973
false
false
false
false
tarrgor/LctvSwift
Sources/LctvScope.swift
1
519
// // LctvScope.swift // Pods // // // import Foundation public enum LctvScope : String { case Read = "read" case ReadViewer = "read:viewer" case ReadUser = "read:user" case ReadChannel = "read:channel" case Chat = "chat" static func toScopeString(scope: [LctvScope]) -> String { var result = "" var first: Bool = true for currentScope in scope { if !first { result += " " } first = false result += "\(currentScope.rawValue)" } return result } }
mit
8c188bed9a968945dbf59aff68d0fbc3
16.333333
59
0.585742
3.483221
false
false
false
false
cmoulton/grokHTMLAndDownloads
grokHTMLAndDownloads/MasterViewController.swift
1
2687
// // MasterViewController.swift // grokHTMLAndDownloads // // Created by Christina Moulton on 2015-10-12. // Copyright © 2015 Teak Mobile Inc. All rights reserved. // import UIKit class MasterViewController: UITableViewController, UIDocumentInteractionControllerDelegate { var dataController = DataController() var docController: UIDocumentInteractionController? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dataController.fetchCharts { _ in // TODO: handle errors self.tableView.reloadData() } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataController.charts?.count ?? 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) if let chart = dataController.charts?[indexPath.row] { cell.textLabel!.text = "\(chart.number): \(chart.title)" } else { cell.textLabel!.text = "" } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if let chart = dataController.charts?[indexPath.row] { dataController.downloadChart(chart) { progress, error in // TODO: handle error print(progress) print(error) if (progress == 1.0) { if let filename = chart.filename { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docs = paths[0] let pathURL = NSURL(fileURLWithPath: docs, isDirectory: true) let fileURL = NSURL(fileURLWithPath: filename, isDirectory: false, relativeToURL: pathURL) self.docController = UIDocumentInteractionController(URL: fileURL) self.docController?.delegate = self if let cell = self.tableView.cellForRowAtIndexPath(indexPath) { self.docController?.presentOptionsMenuFromRect(cell.frame, inView: self.tableView, animated: true) } } } } } } // MARK: - UIDocumentInteractionControllerDelegate func documentInteractionController(controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) { self.docController = nil if let indexPath = tableView.indexPathForSelectedRow { tableView.deselectRowAtIndexPath(indexPath, animated:true) } } }
mit
6f7109cb4ad87f9762eb00fa2bae4171
33
132
0.693224
5.277014
false
false
false
false
dclelland/Ursus
Ursus/Models/Responses/SubscribeResponse.swift
1
1035
// // SubscribeResponse.swift // Ursus // // Created by Daniel Clelland on 7/06/20. // import Foundation internal struct SubscribeResponse: Decodable { enum Result { case okay case error(String) } var id: Int var result: Result enum CodingKeys: String, CodingKey { case id case okay = "ok" case error = "err" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.id = try container.decode(Int.self, forKey: .id) switch Set(container.allKeys) { case [.id, .okay]: self.result = .okay case [.id, .error]: self.result = .error(try container.decode(String.self, forKey: .error)) default: throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Failed to decode \(type(of: self)); available keys: \(container.allKeys)")) } } }
mit
beca237096b9b00e0bdd6251e4705f13
24.243902
194
0.592271
4.259259
false
false
false
false
asm-products/line-ninja-ios
proof_of_concept/LineNinja/ResponsiveTextFieldViewController.swift
1
4480
// // ResponsiveTextFieldViewController.swift // Swift version of: VBResponsiveTextFieldViewController // Original code: https://github.com/ttippin84/VBResponsiveTextFieldViewController // // Created by David Sandor on 9/27/14. // Copyright (c) 2014 David Sandor. All rights reserved. // import Foundation import UIKit class ResponsiveTextFieldViewController : UIViewController { var kPreferredTextFieldToKeyboardOffset: CGFloat = 20.0 var keyboardFrame: CGRect = CGRect.nullRect var keyboardIsShowing: Bool = false weak var activeTextField: UITextField? override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) self.findAndWatchAllTextFields(self.view) } func findAndWatchAllTextFields(view: UIView) { if (view.isKindOfClass(UITextField)) { var textField = view as UITextField self.watchTextField(textField) } for subview in view.subviews { self.findAndWatchAllTextFields(subview as UIView) } } func watchTextField(textField:UITextField) { textField.addTarget(self, action: "textFieldDidReturn:", forControlEvents: UIControlEvents.EditingDidEndOnExit) textField.addTarget(self, action: "textFieldDidBeginEditing:", forControlEvents: UIControlEvents.EditingDidBegin) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) } func keyboardWillShow(notification: NSNotification) { self.keyboardIsShowing = true if let info = notification.userInfo { self.keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as NSValue).CGRectValue() self.arrangeViewOffsetFromKeyboard() } } func keyboardWillHide(notification: NSNotification) { self.keyboardIsShowing = false self.returnViewToInitialFrame() } func arrangeViewOffsetFromKeyboard() { if (self.activeTextField == nil) { return } var theApp: UIApplication = UIApplication.sharedApplication() var windowView: UIView? = theApp.delegate!.window! var textFieldLowerPoint: CGPoint = CGPointMake(self.activeTextField!.frame.origin.x, self.activeTextField!.frame.origin.y + self.activeTextField!.frame.size.height) var convertedTextFieldLowerPoint: CGPoint = self.view.convertPoint(textFieldLowerPoint, toView: windowView) var targetTextFieldLowerPoint: CGPoint = CGPointMake(self.activeTextField!.frame.origin.x, self.keyboardFrame.origin.y - kPreferredTextFieldToKeyboardOffset) var targetPointOffset: CGFloat = targetTextFieldLowerPoint.y - convertedTextFieldLowerPoint.y var adjustedViewFrameCenter: CGPoint = CGPointMake(self.view.center.x, self.view.center.y + targetPointOffset) UIView.animateWithDuration(0.2, animations: { self.view.center = adjustedViewFrameCenter }) } func returnViewToInitialFrame() { var initialViewRect: CGRect = CGRectMake(0.0, 0.0, self.view.frame.size.width, self.view.frame.size.height) if (!CGRectEqualToRect(initialViewRect, self.view.frame)) { UIView.animateWithDuration(0.2, animations: { self.view.frame = initialViewRect }); } } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if (self.activeTextField != nil) { self.activeTextField?.resignFirstResponder() self.activeTextField = nil } } @IBAction func textFieldDidReturn(textField: UITextField!) { textField.resignFirstResponder() self.activeTextField = nil } func textFieldDidBeginEditing(textField: UITextField) { self.activeTextField = textField if(self.keyboardIsShowing) { self.arrangeViewOffsetFromKeyboard() } } }
agpl-3.0
7adcee20c806ed45b36a46820a40150f
31.948529
172
0.663616
5.221445
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/06002-no-stacktrace.swift
11
2057
// 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 A { typealias f = c protocol c : a { 0.C func b protocol c : b { func b<T : A { let t: b { enum B : c : e : e) protocol P { class A { protocol c { enum B : A { } extension NSData { protocol e { } func a } protocol c : c { class A { func a<T : A.a class A { protocol A { protocol A {} typealias e : a { } func a func c func b func b struct B, leng protocol P { protocol c : a {} extension NSData { typealias e { func a class A { func b<H : A { protocol A { st func b } protocol P { protocol c : c { let start = B<d {} if true {} protocol c : b { <d { typealias f = B<H : f.a st func b } protocol A { enum b { func a") enum B : f.a" typealias e : e) if true { class A { <T : a(" protocol P { func a func c func a" enum b { } class A { func c protocol e : c { <H : a { protocol A { protocol P { enum B : e = b<H : a { protocol B : a { } let t: e) let start = b<H : e : a func a [] func a protocol e = B<H : f.c : b { func a" [] } func b if true { enum B : e) func b typealias e : f.C <d { protocol e { protocol e : f.a protocol B : f.C 0.a<d { let t: e : a(") <T : a { } enum b { func b } return " protocol A { func a<d { let t: a func a [] class A { func c class A { 0.C typealias e { 0.C enum b { } [] st <T : a {} enum B : A.c { typealias e : a { func b<H : a { protocol B : a { typealias e {} enum b { typealias e : e = b protocol c { protocol c { func a") typealias e : A { func c <T : f.C 0.C var _ = F>(") func b } func b typealias e = b 0.c { protocol P { class A { protocol P { func c extension NSData { func b st st } 0.a func b class A { <H : e = F>(")) } func c protocol A { } func a<H : a<H : a {} } func b func b protocol A { } func c class A {} enum B : b { func c protocol A { func a let start = B<d { <H : f.a } protocol A {} extension NSData { let t: a { enum b { func c let start = c 0.c : A.C } enum b { func b func a" protocol B : c : a func b<d { typealias f = c
mit
41d2c7929fd8b0fd0280b0e234b49886
10.364641
87
0.593583
2.425708
false
false
false
false
soflare/XWebShell
XWebShell/PluginInventory.swift
1
4858
/* Copyright 2015 XWebView Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation public class PluginInventory { private enum Provider { case Class(AnyClass?) case RealID(String) } private var plugins = [String: Provider]() public init() { } public init(bundle: NSBundle) { scanInBundle(bundle) } public func scanInBundle(bundle: NSBundle) { if let xwvplugins = bundle.objectForInfoDictionaryKey("XWVPlugins") as? NSDictionary { let e = xwvplugins.keyEnumerator() while let name = e.nextObject() as? String { let id = PluginInventory.identiferForClassName(name, bundle: bundle) plugins[id] = .Class(nil) // lazy load if let alias = xwvplugins[name] as? String where !alias.isEmpty { let aid = PluginInventory.identiferForClassName(alias, bundle: bundle) plugins[aid] = .RealID(id) } } } } class public func identifierForClass(cls: AnyClass) -> String { return identiferForClassName(NSStringFromClass(cls), bundle: NSBundle(forClass: cls)) } class private func identiferForClassName(name: String, bundle: NSBundle) -> String { var id = name if let dot = find(id, ".") { id = id.substringFromIndex(dot.successor()) } if bundle != NSBundle.mainBundle() { precondition(bundle.bundleIdentifier != nil, "Bundle '\(bundle.bundlePath)' has no identifier") id += "@" + ".".join(reverse(split(bundle.bundleIdentifier!) { $0 == "." })) } return id } public func registerClass(cls: AnyClass) -> AnyClass! { return registerClass(cls, forIdentifier: PluginInventory.identifierForClass(cls)) } public func registerClass(cls: AnyClass!, forIdentifier id: String) -> AnyClass! { let old: AnyClass? = classForIdentifier(id) plugins[id] = .Class(cls) return old } public func unregisterIdentifier(id: String) { plugins.removeValueForKey(id) } public func classForIdentifier(id: String) -> AnyClass? { if let provider = plugins[id] { switch provider { case .Class(let cls): return cls ?? resolveIdentifier(id) case .RealID(let rid): return classForIdentifier(rid) } } return nil } private func resolveIdentifier(id: String) -> AnyClass? { let className: String let bundle: NSBundle! if let at = find(id, "@") { className = id[id.startIndex..<at] let domain = id[at.successor()..<id.endIndex] let bundleId = ".".join(reverse(split(domain) { $0 == "." })) bundle = NSBundle(identifier: bundleId) if bundle == nil { println("ERROR: Unknown bundle '\(bundleId)'") return nil } else if !bundle.loaded { if !bundle.loadAndReturnError(nil) { println("ERROR: Load bundle '\(bundle.bundlePath)' failed") return nil } } } else { className = id bundle = NSBundle.mainBundle() } func classForName(name: String, bundle: NSBundle) -> AnyClass? { #if TARGET_IPHONE_SIMULATOR return NSClassFromString(name) #else return bundle.classNamed(name) #endif } var cls: AnyClass? = classForName(className, bundle) if cls == nil { // Is it a Swift class? let className = bundle.executablePath!.lastPathComponent + "." + className cls = classForName(className, bundle) if cls == nil { println("ERROR: Plugin class '\(className)' not found in bundle '\(bundle.bundlePath)'") } } return cls } } extension PluginInventory { public subscript(id: String) -> AnyClass? { get { return classForIdentifier(id) } set { if newValue != nil { registerClass(newValue!, forIdentifier: id) } else { unregisterIdentifier(id) } } } }
apache-2.0
e89ed1526f346b1054e0346dcb51a861
33.7
107
0.574722
4.819444
false
false
false
false
corujautx/Announce
Sources/Core/Views/MessageWithImage.swift
1
7681
// // MessageWithImage.swift // Announce // // Created by Vitor Travain on 5/22/17. // Copyright © 2017 Vitor Travain. All rights reserved. // import Foundation import UIKit public final class MessageWithImage: UIView, TappableAnnouncement { public let message: String public let title: String public let image: UIImage? public let appearance: MessageWithImageAppearance public init(title: String, message: String, image: UIImage? = nil, appearance: MessageWithImageAppearance? = nil, tapHandler: ((MessageWithImage) -> Void)? = nil) { self.message = message self.title = title self.image = image self.appearance = appearance ?? MessageWithImageAppearance.defaultAppearance() self.tapHandler = tapHandler super.init(frame: .zero) self.layout() self.bindValues() self.addGestureRecognizers() } public convenience init(title: String, message: String, image: UIImage? = nil, theme: Theme, tapHandler: ((MessageWithImage) -> Void)? = nil) { self.init(title: title, message: message, image: image, appearance: theme.appearanceForMessageWithImage(), tapHandler: tapHandler) } public required init?(coder aDecoder: NSCoder) { fatalError("Not supported") } // MARK: - Gesture Recognizers private lazy var tapGestureRecognizer: UITapGestureRecognizer = { return UITapGestureRecognizer(target: self, action: #selector(handleTap)) }() public var tapHandler: ((MessageWithImage) -> Void)? @objc private func handleTap() { tapHandler?(self) } private func addGestureRecognizers() { addGestureRecognizer(tapGestureRecognizer) } // MARK: - Layout lazy var titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 1 label.lineBreakMode = .byTruncatingTail label.textAlignment = .left label.font = self.appearance.titleFont label.textColor = self.appearance.foregroundColor label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var messageLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textAlignment = .left label.font = self.appearance.messageFont label.textColor = self.appearance.foregroundColor label.translatesAutoresizingMaskIntoConstraints = false return label }() public private (set) lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = self.appearance.imageContentMode imageView.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) imageView.layer.masksToBounds = true imageView.layer.cornerRadius = self.appearance.imageCornerRadius imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() private func layout() { self.backgroundColor = appearance.backgroundColor addSubview(titleLabel) addSubview(messageLabel) addSubview(imageView) setContentHuggingPriority(.defaultHigh, for: .vertical) layoutImage() layoutTitle() layoutMessage() } private func layoutImage() { let leadingConstraint = NSLayoutConstraint( item: imageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 8.0 ) let topConstraint = NSLayoutConstraint( item: imageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0 ) let bottomConstraint = NSLayoutConstraint( item: imageView, attribute: .bottom, relatedBy: .greaterThanOrEqual, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0 ) let widthConstraint = NSLayoutConstraint( item: imageView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: self.appearance.imageSize.width ) let heightConstraint = NSLayoutConstraint( item: imageView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: self.appearance.imageSize.height ) leadingConstraint.isActive = true topConstraint.isActive = true bottomConstraint.isActive = true widthConstraint.isActive = true heightConstraint.isActive = true } private func layoutTitle() { let topConstraint = NSLayoutConstraint( item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 8.0 ) let leadingConstraint = NSLayoutConstraint( item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: imageView, attribute: .trailing, multiplier: 1.0, constant: 8.0 ) let trailingConstraint = NSLayoutConstraint( item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: -8.0 ) topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true } private func layoutMessage() { let topConstraint = NSLayoutConstraint( item: messageLabel, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: 8.0 ) let leadingConstraint = NSLayoutConstraint( item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: titleLabel, attribute: .leading, multiplier: 1.0, constant: 0.0 ) let trailingConstraint = NSLayoutConstraint( item: messageLabel, attribute: .trailing, relatedBy: .equal, toItem: titleLabel, attribute: .trailing, multiplier: 1.0, constant: 0.0 ) let bottomConstraint = NSLayoutConstraint( item: messageLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: -8.0 ) bottomConstraint.priority = .defaultLow topConstraint.isActive = true leadingConstraint.isActive = true trailingConstraint.isActive = true bottomConstraint.isActive = true } // MARK: - Value binding private func bindValues() { titleLabel.text = title messageLabel.text = message imageView.image = image } }
mit
123fe0da69533e15240f07cce2964340
27.131868
89
0.566146
5.58952
false
false
false
false
snazzware/Mergel
HexMatch/Scenes/SplashScene.swift
2
1994
// // SplashScene.swift // Mergel // // Created by Josh McKee on 9/12/16. // Copyright © 2016 Josh McKee. All rights reserved. // import SpriteKit import SNZSpriteKitUI class SplashScene: SNZScene { var checkboxMobilePieces: SNZCheckButtonWidget? var checkboxEnemyPieces: SNZCheckButtonWidget? var checkboxSoundEffects: SNZCheckButtonWidget? override func didMove(to view: SKView) { super.didMove(to: view) self.updateGui() } func updateGui() { self.removeAllChildren() self.widgets.removeAll() // Set background self.backgroundColor = UIColor(red: 0x69/255, green: 0x65/255, blue: 0x6f/255, alpha: 1.0) // Get an enemy sprite let enemyPiece = EnemyHexPiece() let enemySprite = enemyPiece.createSprite() enemySprite.position.x += 90 enemySprite.position.y += 8 enemySprite.zRotation = 0.4 enemySprite.zPosition = 999 // Mergel node let mergelNode = SKSpriteNode(texture: SKTexture(imageNamed: "Mergel")) mergelNode.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2) mergelNode.setScale(0) mergelNode.addChild(enemySprite) self.addChild(mergelNode) // Scale/bounce and transition to game scene mergelNode.run(SKAction.sequence([ SKAction.scale(to: 1.2, duration: 0.5), SKAction.scale(to: 0.8, duration: 0.2), SKAction.scale(to: 1.1, duration: 0.2), SKAction.scale(to: 0.9, duration: 0.2), SKAction.scale(to: 1.0, duration: 0.2), SKAction.wait(forDuration: 1.0), SKAction.run({ // Switch to game scene self.view?.presentScene(SceneHelper.instance.gameScene, transition: SKTransition.moveIn(with: SKTransitionDirection.down, duration: 0.4)) }) ])) } }
mit
84654d63d25ced35d05eea81c8d6e887
30.634921
153
0.6001
4.002008
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/scratchy/ShadowView.swift
1
2135
// // ShadowView.swift // scratchy // // Created by Don Mag on 3/13/17. // Copyright © 2017 DonMag. All rights reserved. // import UIKit class ShadowView: UIView { /// The corner radius of the `ShadowView`, inspectable in Interface Builder @IBInspectable var cornerRadius: CGFloat = 5.0 { didSet { self.updateProperties() } } /// The shadow color of the `ShadowView`, inspectable in Interface Builder @IBInspectable var shadowColor: UIColor = UIColor.black { didSet { self.updateProperties() } } /// The shadow offset of the `ShadowView`, inspectable in Interface Builder @IBInspectable var shadowOffset: CGSize = CGSize(width: 0.0, height: 2) { didSet { self.updateProperties() } } /// The shadow radius of the `ShadowView`, inspectable in Interface Builder @IBInspectable var shadowRadius: CGFloat = 4.0 { didSet { self.updateProperties() } } /// The shadow opacity of the `ShadowView`, inspectable in Interface Builder @IBInspectable var shadowOpacity: Float = 0.5 { didSet { self.updateProperties() } } /** Masks the layer to it's bounds and updates the layer properties and shadow path. */ override func awakeFromNib() { super.awakeFromNib() self.layer.masksToBounds = false self.updateProperties() self.updateShadowPath() } /** Updates all layer properties according to the public properties of the `ShadowView`. */ fileprivate func updateProperties() { self.layer.cornerRadius = self.cornerRadius self.layer.shadowColor = self.shadowColor.cgColor self.layer.shadowOffset = self.shadowOffset self.layer.shadowRadius = self.shadowRadius self.layer.shadowOpacity = self.shadowOpacity } /** Updates the bezier path of the shadow to be the same as the layer's bounds, taking the layer's corner radius into account. */ fileprivate func updateShadowPath() { self.layer.shadowPath = UIBezierPath(roundedRect: layer.bounds, cornerRadius: layer.cornerRadius).cgPath } /** Updates the shadow path everytime the views frame changes. */ override func layoutSubviews() { super.layoutSubviews() self.updateShadowPath() } }
mit
f4d2db6e6b240cba75b3bef8e192835c
24.710843
123
0.723524
3.838129
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/3rdParty/RecordVoice/JCRecordingView.swift
1
7465
// // JCRecordingView.swift // JChatSwift // // Created by oshumini on 16/2/19. // Copyright © 2016年 HXHG. All rights reserved. // import UIKit internal let voiceRecordResaueString = "松开手指,取消发送" internal let voiceRecordPauseString = "手指上滑,取消发送" class JCRecordingView: UIView { var remiadeLable: UILabel! var cancelRecordImageView: UIImageView! var recordingHUDImageView: UIImageView! var errorTipsView: UIImageView! var timeLable: UILabel! var tipsLable: UILabel! var peakPower:Float! var isRecording = false func dismissCompled(_ completed: (_ finish:Bool) -> Void) { } override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func _init() { backgroundColor = UIColor.black.withAlphaComponent(0.5) layer.masksToBounds = true layer.cornerRadius = 5 remiadeLable = UILabel() remiadeLable.textColor = UIColor.white remiadeLable.layer.cornerRadius = 2.5 remiadeLable.layer.masksToBounds = true remiadeLable.font = UIFont.systemFont(ofSize: 12) remiadeLable.text = voiceRecordPauseString remiadeLable.textAlignment = .center addSubview(remiadeLable) timeLable = UILabel() timeLable.textColor = UIColor(netHex: 0x2DD0CF) timeLable.font = UIFont.systemFont(ofSize: 12) timeLable.text = "······ 0.00 ······" timeLable.textAlignment = .center addSubview(timeLable) tipsLable = UILabel() tipsLable.textColor = UIColor(netHex: 0x2DD0CF) tipsLable.font = UIFont.systemFont(ofSize: 62) tipsLable.textAlignment = .center tipsLable.isHidden = true addSubview(tipsLable) recordingHUDImageView = UIImageView() recordingHUDImageView.image = UIImage.loadImage("com_icon_record") addSubview(recordingHUDImageView) errorTipsView = UIImageView() errorTipsView.image = UIImage.loadImage("com_icon_record_error") errorTipsView.isHidden = true addSubview(errorTipsView) cancelRecordImageView = UIImageView() cancelRecordImageView.image = UIImage.loadImage("com_icon_record_cancel") cancelRecordImageView.contentMode = .scaleToFill addSubview(cancelRecordImageView) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .top, .equal, self, .top, 21.5)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .width, .equal, nil, .notAnAttribute, 43)) addConstraint(_JCLayoutConstraintMake(recordingHUDImageView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .top, .equal, self, .top, 27.5)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .width, .equal, nil, .notAnAttribute, 5)) addConstraint(_JCLayoutConstraintMake(errorTipsView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .centerX, .equal, self, .centerX)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .top, .equal, self, .top, 21.5)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .width, .equal, nil, .notAnAttribute, 43)) addConstraint(_JCLayoutConstraintMake(cancelRecordImageView, .height, .equal, nil, .notAnAttribute, 60)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .height, .equal, nil, .notAnAttribute, 19)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .top, .equal, recordingHUDImageView, .bottom, 25.5)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .right, .equal, self, .right, -10)) addConstraint(_JCLayoutConstraintMake(remiadeLable, .left, .equal, self, .left, 10)) addConstraint(_JCLayoutConstraintMake(timeLable, .height, .equal, nil, .notAnAttribute, 16.5)) addConstraint(_JCLayoutConstraintMake(timeLable, .top, .equal, recordingHUDImageView, .bottom, 5)) addConstraint(_JCLayoutConstraintMake(timeLable, .right, .equal, self, .right)) addConstraint(_JCLayoutConstraintMake(timeLable, .left, .equal, self, .left)) addConstraint(_JCLayoutConstraintMake(tipsLable, .height, .equal, nil, .notAnAttribute, 86.5)) addConstraint(_JCLayoutConstraintMake(tipsLable, .top, .equal, self, .top, 9.5)) addConstraint(_JCLayoutConstraintMake(tipsLable, .right, .equal, self, .right)) addConstraint(_JCLayoutConstraintMake(tipsLable, .left, .equal, self, .left)) } func startRecordingHUDAtView(_ view:UIView) { view.addSubview(self) self.center = view.center configRecoding(true) } func pauseRecord() { configRecoding(true) remiadeLable.backgroundColor = UIColor.clear remiadeLable.text = voiceRecordPauseString } func resaueRecord() { configRecoding(false) remiadeLable.backgroundColor = UIColor(netHex: 0x7E1D22) remiadeLable.text = voiceRecordResaueString } func stopRecordCompleted(_ completed: (_ finish:Bool) -> Void) { dismissCompled(completed) } func cancelRecordCompleted(_ completed: (_ finish:Bool) -> Void) { dismissCompled(completed) } func dismissCompleted(_ completed:@escaping (_ finish:Bool) -> Void) { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { () -> Void in self.alpha = 0.0 }) { (finished:Bool) -> Void in super.removeFromSuperview() completed(finished) } } func configRecoding(_ recording: Bool) { isRecording = recording recordingHUDImageView.isHidden = !recording cancelRecordImageView.isHidden = recording } func setTime(_ time: TimeInterval) { let t = Int(time) if t > 49 { tipsLable.isHidden = false timeLable.isHidden = true cancelRecordImageView.isHidden = true recordingHUDImageView.isHidden = true tipsLable.text = "\(60 - t)" } else { tipsLable.isHidden = true timeLable.isHidden = false if isRecording { recordingHUDImageView.isHidden = false } else { cancelRecordImageView.isHidden = false } } if t >= 60 { timeLable.text = "······ 1.00 ······" } else if t > 9 { timeLable.text = "······ 0.\(t) ······" } else { timeLable.text = "······ 0.0\(t) ······" } } func setPeakPower(_ peakPower: Float) { self.peakPower = peakPower } func showErrorTips() { recordingHUDImageView.isHidden = true errorTipsView.isHidden = false timeLable.isHidden = true remiadeLable.text = "说话时间太短" } }
mit
fc4a4aaaebe7e630e6276cca8d06d49e
37.768421
112
0.64051
4.282558
false
false
false
false
manderson-productions/RompAround
RompAround/Player.swift
1
2970
// // PlayerEntity.swift // RompAround // // Created by Mark Anderson on 10/11/15. // Copyright © 2015 manderson-productions. All rights reserved. // import GameplayKit import GameController class Player: GKEntity { struct Constants { static let healthDefault = 3 static let attackDefault = 1 static let defenseDefault = 1 } // MARK: Properties var hero: PlayerSprite! let diceHud = DiceHUD() var gold = 0 var health: Int = Constants.healthDefault // These are not based on dice var attack: Int = Constants.attackDefault var defense: Int = Constants.defenseDefault func hasMoves() -> Bool { return diceHud.dice.moves > 0 } func hasAttacks() -> Bool { return diceHud.dice.attack > 0 } func hasMagicAttacks() -> Bool { return diceHud.dice.magic > 0 } func hasMovesOrAttacks() -> Bool { return hasMoves() && (hasAttacks() || hasMagicAttacks()) } func moveOrAttack(direction: Direction, inLevel: LevelScene) { let (shouldMove, enemy, loot) = hero.canMove(direction, inLevel: inLevel) if shouldMove { if let enemy = enemy { if diceHud.attackEnabled { if !hasAttacks() { return } diceHud.dice.attack-- } else { if !hasMagicAttacks() { return } diceHud.dice.magic-- } // is the enemy dead? if enemy.wasAttacked(hero, amount: attack, inLevel: inLevel) { inLevel.replaceEnemyTileWithLootAtPosition(enemy.position.gridPoint(inLevel.levelData.squareSize.int32)) } } else { if !hasMoves() { return } diceHud.dice.moves-- if let loot = loot, lootToCalculate = loot.getLoot() { if lootToCalculate is Gold { gold += (lootToCalculate as! Gold).amount print("Found gold") } else if lootToCalculate is Card { let card = lootToCalculate as! Card attack += card.attack defense += card.defense health += card.health print("Found Card") } else { fatalError("No Loot was matched to calculate!") } } } hero.move(direction, enemy: enemy, loot: loot, inLevel: inLevel) } print("Moves Left: \(diceHud.dice.moves)---Attack Left: \(diceHud.dice.attack)---Magic Left: \(diceHud.dice.magic)") diceHud.setLabelData(gold, attack: attack, defense: defense, health: health) } var heroFaceLocation: CGPoint? var controller: GCController? }
apache-2.0
59eb53d38d8a03cd2fa1a5a30321e393
30.924731
124
0.524756
4.58179
false
false
false
false