repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
larryhou/swift
TexasHoldem/TexasHoldem/PlayerTableViewController.swift
1
1795
// // PlayerTableViewController.swift // TexasHoldem // // Created by larryhou on 12/3/2016. // Copyright © 2016 larryhou. All rights reserved. // import Foundation import UIKit class PlayerTableViewController: UITableViewController { var model: ViewModel! // MARK: segue override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "pattern" { let dst = segue.destinationViewController as! PatternTableViewController dst.model = model let indexPath = tableView.indexPathForSelectedRow! dst.id = indexPath.row tableView.deselectRow(at: indexPath, animated: true) } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 75 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return model == nil ? 0 : model.stats.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell")! cell.textLabel?.text = String(format: "PLAYER #%02d", (indexPath as NSIndexPath).row + 1) return cell } override func tableView(_ tableView: UITableView, accessoryButtonTappedForRowWith indexPath: IndexPath) { let alert = PatternStatsPrompt(title: "牌型分布#\((indexPath as NSIndexPath).row + 1)", message: nil, preferredStyle: .actionSheet) alert.setPromptSheet(model.stats[(indexPath as NSIndexPath).row]!) present(alert, animated: true, completion: nil) } }
mit
3174e3c37655de9613888f95c7284c21
34.72
135
0.684211
4.92011
false
false
false
false
bourdakos1/Visual-Recognition-Tool
iOS/Visual Recognition/PendingClassifier+CoreDataClass.swift
1
3711
// // PendingClassifier+CoreDataClass.swift // Visual Recognition // // Created by Nicholas Bourdakos on 5/9/17. // Copyright © 2017 Nicholas Bourdakos. All rights reserved. // import Foundation import CoreData import Zip import Alamofire public class PendingClassifier: NSManagedObject { func train(completion: @escaping (_ results: Any) -> Void) { print("train") do { let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(id!) var paths = [URL]() for result in relationship?.allObjects as! [PendingClass] { let destination = documentsUrl.appendingPathComponent(result.name!).appendingPathExtension("zip") paths.append(destination) if FileManager.default.fileExists(atPath: destination.path) { print("Exists, deleting") // Exist so delete first and then try. do { try FileManager.default.removeItem(at: destination) } catch { print("Error: \(error.localizedDescription)") if FileManager.default.fileExists(atPath: destination.path) { print("still exists") } } } // Make sure it's actually gone... if !FileManager.default.fileExists(atPath: destination.path) { try Zip.zipFiles(paths: [documentsUrl.appendingPathComponent(result.name!)], zipFilePath: destination, password: nil, progress: { progress in print("Zipping: \(progress)") }) } } let url = URL(string: "https://gateway-a.watsonplatform.net/visual-recognition/api/v3/classifiers")! let urlRequest = URLRequest(url: url) let parameters: Parameters = [ "api_key": UserDefaults.standard.string(forKey: "api_key")!, "version": "2016-05-20", ] let encodedURLRequest = try URLEncoding.queryString.encode(urlRequest, with: parameters) Alamofire.upload( multipartFormData: { multipartFormData in for path in paths { multipartFormData.append( path, withName: "\((path.pathComponents.last! as NSString).deletingPathExtension)_positive_examples" ) } multipartFormData.append(self.name!.data(using: .utf8, allowLossyConversion: false)!, withName :"name") }, to: encodedURLRequest.url!, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in completion(response) debugPrint(response) } upload.uploadProgress(closure: { //Get Progress progress in print(progress.fractionCompleted) }) case .failure(let encodingError): print(encodingError) } }) } catch { print(error) completion("FAILUREEEEE") } } }
mit
b5d33c57aed3f4d6b54b68a20d218818
39.769231
161
0.495418
6.062092
false
false
false
false
szk-atmosphere/SAHistoryNavigationViewController
SAHistoryNavigationViewController/SAHistoryNavigationViewController.swift
2
9668
// // SAHistoryNavigationViewController.swift // SAHistoryNavigationViewController // // Created by 鈴木大貴 on 2015/03/26. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit @objc public protocol SAHistoryNavigationViewControllerDelegate: NSObjectProtocol { @objc optional func historyControllerDidShowHistory(_ controller: SAHistoryNavigationViewController, viewController: UIViewController) } open class SAHistoryNavigationViewController: UINavigationController { //MARK: - Static constants fileprivate struct Const { static let imageScale: CGFloat = 1.0 } //MARK: - Properties open var thirdDimensionalTouchThreshold: CGFloat = 0.5 fileprivate var interactiveTransition: UIPercentDrivenInteractiveTransition? fileprivate var screenshots = [UIImage]() fileprivate var historyViewController: SAHistoryViewController? fileprivate let historyContentView = UIView() public weak var historyDelegate: SAHistoryNavigationViewControllerDelegate? public var historyBackgroundColor: UIColor? { get { return historyContentView.backgroundColor } set { historyContentView.backgroundColor = newValue } } public var contentView: UIView? { return historyContentView } //MARK: - Initializers required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override public init(navigationBarClass: AnyClass!, toolbarClass: AnyClass!) { super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass) } override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override public init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) } //MARK: Life cycle override open func viewDidLoad() { super.viewDidLoad() if historyContentView.backgroundColor == nil { historyContentView.backgroundColor = .gray } let gestureRecognizer: UIGestureRecognizer if #available(iOS 9, *) { if traitCollection.forceTouchCapability == .available { interactiveTransition = UIPercentDrivenInteractiveTransition() gestureRecognizer = SAThirdDimensionalTouchRecognizer(target: self, action: #selector(SAHistoryNavigationViewController.handleThirdDimensionalTouch(_:)), threshold: thirdDimensionalTouchThreshold) (gestureRecognizer as? SAThirdDimensionalTouchRecognizer)?.minimumPressDuration = 0.2 } else { gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(SAHistoryNavigationViewController.detectLongTap(_:))) } } else { gestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(SAHistoryNavigationViewController.detectLongTap(_:))) } gestureRecognizer.delegate = self navigationBar.addGestureRecognizer(gestureRecognizer) } override open func pushViewController(_ viewController: UIViewController, animated: Bool) { if let image = visibleViewController?.sah.screenshotFromWindow(Const.imageScale) { screenshots += [image] } super.pushViewController(viewController, animated: animated) } open override func popToRootViewController(animated: Bool) -> [UIViewController]? { screenshots.removeAll(keepingCapacity: false) return super.popToRootViewController(animated: animated) } open override func popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? { let vcs = super.popToViewController(viewController, animated: animated) if let index = viewControllers.index(of: viewController) { screenshots.removeSubrange(index..<screenshots.count) } return vcs } open override func setViewControllers(_ viewControllers: [UIViewController], animated: Bool) { super.setViewControllers(viewControllers, animated: animated) for (currentIndex, viewController) in viewControllers.enumerated() { if currentIndex == viewControllers.endIndex { break } guard let image = viewController.sah.screenshotFromWindow(Const.imageScale) else { continue } screenshots += [image] } } @available(iOS 9, *) func handleThirdDimensionalTouch(_ gesture: SAThirdDimensionalTouchRecognizer) { switch gesture.state { case .began: guard let image = visibleViewController?.sah.screenshotFromWindow(Const.imageScale) else { return } screenshots += [image] let historyViewController = createHistoryViewController() self.historyViewController = historyViewController present(historyViewController, animated: true, completion: nil) case .changed: interactiveTransition?.update(min(gesture.threshold, max(0, gesture.percentage))) case .ended: screenshots.removeLast() if gesture.percentage >= gesture.threshold { interactiveTransition?.finish() guard let visibleViewController = self.visibleViewController else { return } historyDelegate?.historyControllerDidShowHistory?(self, viewController: visibleViewController) } else { interactiveTransition?.cancel() } case .cancelled, .failed, .possible: screenshots.removeLast() } } func detectLongTap(_ gesture: UILongPressGestureRecognizer) { if gesture.state == .began { showHistory() } } fileprivate func createHistoryViewController() -> SAHistoryViewController { let historyViewController = SAHistoryViewController() historyViewController.delegate = self historyViewController.contentView = historyContentView historyViewController.images = screenshots historyViewController.currentIndex = viewControllers.count - 1 historyViewController.transitioningDelegate = self return historyViewController } public func showHistory() { guard let image = visibleViewController?.sah.screenshotFromWindow(Const.imageScale) else { return } screenshots += [image] let historyViewController = createHistoryViewController() self.historyViewController = historyViewController setNavigationBarHidden(true, animated: false) present(historyViewController, animated: true) { guard let visibleViewController = self.visibleViewController else { return } self.historyDelegate?.historyControllerDidShowHistory?(self, viewController: visibleViewController) } } } //MARK: - UINavigationBarDelegate extension SAHistoryNavigationViewController: UINavigationBarDelegate { public func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) { guard let items = navigationBar.items else { return } screenshots.removeSubrange(items.count..<screenshots.count) } } //MARK: - UIViewControllerTransitioningDelegate extension SAHistoryNavigationViewController : UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SAHistoryViewAnimatedTransitioning(isPresenting: true) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SAHistoryViewAnimatedTransitioning(isPresenting: false) } public func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition } } //MARK: - SAHistoryViewControllerDelegate extension SAHistoryNavigationViewController: SAHistoryViewControllerDelegate { func historyViewController(_ viewController: SAHistoryViewController, didSelectIndex index: Int) { if viewControllers.count - 1 < index { return } viewController.dismiss(animated: true) { _ in _ = self.popToViewController(self.viewControllers[index], animated: false) self.historyViewController = nil self.setNavigationBarHidden(false, animated: false) } } } //MRAK: - UIGestureRecognizerDelegate extension SAHistoryNavigationViewController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let _ = visibleViewController?.navigationController?.navigationBar.backItem, let view = gestureRecognizer.view as? UINavigationBar { let height = visibleViewController?.navigationController?.isNavigationBarHidden == true ? 44.0 : 64.0 let backButtonFrame = CGRect(x: 0.0, y :0.0, width: 100.0, height: height) let touchPoint = gestureRecognizer.location(in: view) if backButtonFrame.contains(touchPoint) { return true } } if let gestureRecognizer = gestureRecognizer as? UIScreenEdgePanGestureRecognizer , view == gestureRecognizer.view { return true } return false } }
mit
bf3b2743df6ef848fc18ace373387697
42.863636
212
0.701969
6.154337
false
false
false
false
ocrickard/Theodolite
Example/TheodoliteFeed/TheodoliteFeed/AppDelegate.swift
1
2506
// // AppDelegate.swift // TheodoliteFeed // // Created by Oliver Rickard on 10/28/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) let navigationCoordinator = NavigationCoordinator() let firstViewController = ViewController(navigationCoordinator: navigationCoordinator) let navigationController = UINavigationController(rootViewController: firstViewController) navigationCoordinator.navigationController = navigationController window!.rootViewController = navigationController window!.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
db3c55cffc8abba58b8c4b345110dbaa
48.117647
281
0.784431
5.719178
false
false
false
false
dduan/swift
test/expr/unary/selector/fixits.swift
1
7179
// REQUIRES: objc_interop // RUN: rm -rf %t // RUN: mkdir -p %t // RUN: rm -rf %t.overlays // RUN: mkdir -p %t.overlays // FIXME: BEGIN -enable-source-import hackaround // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t.overlays %clang-importer-sdk-path/swift-modules/Foundation.swift // FIXME: END -enable-source-import hackaround // Make sure we get the right diagnostics. // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %s -verify // Copy the source, apply the Fix-Its, and compile it again, making // sure that we've cleaned up all of the deprecation warnings. // RUN: mkdir -p %t.sources // RUN: mkdir -p %t.remapping // RUN: cp %s %t.sources/fixits.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %t.sources/fixits.swift -fixit-all -emit-fixits-path %t.remapping/fixits.remap // RUN: %S/../../../../utils/apply-fixit-edits.py %t.remapping // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t.overlays) -parse %t.sources/fixits.swift 2> %t.result // RUN: FileCheck %s < %t.result // RUN: grep -c "warning:" %t.result | grep 3 // CHECK: warning: no method declared with Objective-C selector 'unknownMethodWithValue:label:' // CHECK: warning: string literal is not a valid Objective-C selector // CHECK: warning: string literal is not a valid Objective-C selector import Foundation class Bar : Foo { @objc(method2WithValue:) override func method2(value: Int) { } @objc(overloadedWithInt:) func overloaded(x: Int) { } @objc(overloadedWithString:) func overloaded(x: String) { } @objc(staticOverloadedWithInt:) static func staticOverloaded(x: Int) { } @objc(staticOverloadedWithString:) static func staticOverloaded(x: String) { } @objc(staticOrNonStatic:) func staticOrNonStatic(x: Int) { } @objc(staticOrNonStatic:) static func staticOrNonStatic(x: Int) { } @objc(theInstanceOne:) func staticOrNonStatic2(x: Int) { } @objc(theStaticOne:) static func staticOrNonStatic2(x: Int) { } } class Foo { @objc(methodWithValue:label:) func method(value: Int, label: String) { } @objc(method2WithValue:) func method2(value: Int) { } @objc func method3() { } @objc var property: String = "" } func testDeprecatedStringLiteralSelector() { let sel1: Selector = "methodWithValue:label:" // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{24-48=#selector(Foo.method(_:label:))}} _ = sel1 _ = "methodWithValue:label:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-43=#selector(Foo.method(_:label:))}} _ = "property" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' or explicitly construct a 'Selector'}}{{7-7=Selector(}}{{17-29=)}} _ = "setProperty:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' or explicitly construct a 'Selector'}}{{7-7=Selector(}}{{21-33=)}} _ = "unknownMethodWithValue:label:" as Selector // expected-warning{{no method declared with Objective-C selector 'unknownMethodWithValue:label:'}}{{7-7=Selector(}}{{38-50=)}} _ = "badSelector:label" as Selector // expected-warning{{string literal is not a valid Objective-C selector}} _ = "method2WithValue:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-38=#selector(Foo.method2(_:))}} _ = "method3" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-28=#selector(Foo.method3)}} // Overloaded cases _ = "overloadedWithInt:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-39=#selector(Bar.overloaded(_:) as (Bar) -> (Int) -> ())}} _ = "overloadedWithString:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-42=#selector(Bar.overloaded(_:) as (Bar) -> (String) -> ())}} _ = "staticOverloadedWithInt:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-45=#selector(Bar.staticOverloaded(_:) as (Int) -> ())}} _ = "staticOverloadedWithString:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-48=#selector(Bar.staticOverloaded(_:) as (String) -> ())}} // We don't need coercion here because we get the right selector // from the static method. _ = "staticOrNonStatic:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-39=#selector(Bar.staticOrNonStatic(_:))}} // We need coercion here because we asked for a selector from an // instance method with the same name as (but a different selector // from) a static method. _ = "theInstanceOne:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-36=#selector(Bar.staticOrNonStatic2(_:) as (Bar) -> (Int) -> ())}} // Note: from Foundation _ = "initWithArray:" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-35=#selector(NSSet.init(array:))}} // Note: from Foundation overlay _ = "methodIntroducedInOverlay" as Selector // expected-warning{{use of string literal for Objective-C selectors is deprecated; use '#selector' instead}}{{7-46=#selector(NSArray.introducedInOverlay)}} } func testSelectorConstruction() { _ = Selector("methodWithValue:label:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-41=#selector(Foo.method(_:label:))}} _ = Selector("unknownMethodWithValue:label:") // expected-warning{{no method declared with Objective-C selector 'unknownMethodWithValue:label:'}} // expected-note@-1{{wrap the selector name in parentheses to suppress this warning}}{{16-16=(}}{{47-47=)}} _ = Selector(("unknownMethodWithValue:label:")) _ = Selector("badSelector:label") // expected-warning{{string literal is not a valid Objective-C selector}} _ = Selector("method2WithValue:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-36=#selector(Foo.method2(_:))}} _ = Selector("method3") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-26=#selector(Foo.method3)}} // Note: from Foundation _ = Selector("initWithArray:") // expected-warning{{use '#selector' instead of explicitly constructing a 'Selector'}}{{7-33=#selector(NSSet.init(array:))}} }
apache-2.0
991d385155fb0307b8924eb33ed31adc
65.472222
219
0.718206
3.758639
false
false
false
false
xsunsmile/zentivity
zentivity/ParseClient.swift
1
2122
// // ParseClient.swift // zentivity // // Created by Eric Huang on 3/6/15. // Copyright (c) 2015 Zendesk. All rights reserved. // import UIKit class ParseClient: NSObject { // Users // Give list of usernames to get users // Used for relations class func usersWithCompletion(usernames: [String], completion: (users: [PFUser], error: NSError?) -> ()) { var query = PFQuery(className:"_User") query.whereKey("username", containedIn: usernames) query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil { completion(users: objects as! [PFUser], error: nil) } else { completion(users: [], error: error) } } } class func setUpUserWithCompletion(user: User, completion: (user: User?, error: NSError?) -> ()) { // if user.contactNumber == nil { user.contactNumber = self.randomPhoneNumber() // } user.signUpInBackgroundWithBlock { (succeeded: Bool, error: NSError?) -> Void in if error == nil { println("Signed up user with username") completion(user: user as User, error: nil) } else { User.logInWithUsernameInBackground(user.username!, password: user.password!, block: { (user, error) -> Void in if error == nil { println("Logged in user with username") completion(user: user as? User, error: nil) } else { completion(user: nil, error: error) } }) } } } class func randomPhoneNumber() -> String { var randomNumber = "(415) " for i in 0...7 { if i == 3 { randomNumber += "-" } else { let randomDigit = arc4random_uniform(10) randomNumber += String(randomDigit) } } return randomNumber } }
apache-2.0
8bc506e4a29e716869f97073c2c99788
31.661538
126
0.509425
4.878161
false
false
false
false
rcgilbert/Kava
Kava/Kava/Source/PageObjects/Infrastructure/Elements/Tappable.swift
1
2878
// // Tappable.swift // Kava // // Created by John Hammerlund on 3/8/16. // Copyright © 2016 MINDBODY, Inc. All rights reserved. // import Foundation import XCTest /** A tappable element. The provided generic argument allows us to infer the proceeding block, defaulted to scope of the application */ open class Tappable<TResultBlock: Block> : Element { public typealias TResultBlockBuilder = (() -> TResultBlock)? public required init(parentBlock: Block, backingElement: XCUIElement) { super.init(parentBlock: parentBlock, backingElement: backingElement) } open func tap(constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock { return self.tap(TResultBlock.self, constructingBlock: builder) } open func tap<TCustomResultBlock : Block>(_ result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock { self.backingElement.tap() return self.parentBlock.scopeTo(TCustomResultBlock.self, builder: builder) } open func doubleTap(constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock { return self.doubleTap(TResultBlock.self, constructingBlock: builder) } open func doubleTap<TCustomResultBlock : Block>(_ result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock { self.backingElement.doubleTap() return self.parentBlock.scopeTo(TCustomResultBlock.self, builder: builder) } open func tapWithNumberOfTaps(_ numberOfTaps: UInt, numberOfTouches: UInt, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock { return self.tapWithNumberOfTaps(numberOfTaps, numberOfTouches: numberOfTouches, result: TResultBlock.self, constructingBlock: builder) } open func tapWithNumberOfTaps<TCustomResultBlock : Block>(_ numberOfTaps: UInt, numberOfTouches: UInt, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock { self.backingElement.tap(withNumberOfTaps: numberOfTaps, numberOfTouches: numberOfTouches) return self.parentBlock.scopeTo(TCustomResultBlock.self, builder: builder) } open func pressForDuration(_ duration: TimeInterval, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock { return self.pressForDuration(duration, result: TResultBlock.self, constructingBlock: builder) } open func pressForDuration<TCustomResultBlock : Block>(_ duration: TimeInterval, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock { self.backingElement.press(forDuration: duration); return self.parentBlock.scopeTo(TCustomResultBlock.self, builder: builder) } }
apache-2.0
796644bae1d8740593008b63f3d55f7e
47.762712
225
0.735836
5.146691
false
false
false
false
rogertjr/chatty
Chatty/Chatty/Controller/NavVC.swift
1
12381
// // NavVC.swift // Chatty // // Created by Roger on 01/09/17. // Copyright © 2017 Decodely. All rights reserved. // import UIKit import MapKit import Firebase class NavVC: UINavigationController { //MARK: - Properties @IBOutlet var contactsView: UIView! @IBOutlet var profileView: UIView! @IBOutlet var previewView: UIView! @IBOutlet var mapPreviewView: UIView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var previewImageView: UIImageView! @IBOutlet weak var previewScrollView: UIScrollView! @IBOutlet weak var profileImageView: RoundedImageView! @IBOutlet weak var profileNameLbl: UILabel! @IBOutlet weak var profileEmailLbl: UILabel! @IBOutlet weak var contactsCollectionView: UICollectionView! var topAnchorContraint: NSLayoutConstraint! let darkView = UIView.init() var items = [User]() //MARK: ViewController lifeCycle override func viewDidLoad() { super.viewDidLoad() setupViews() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { self.view.transform = CGAffineTransform.identity } // MARK: - View Customization func setupViews(){ // Custom Dark View self.view.addSubview(self.darkView) self.darkView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) self.darkView.alpha = 0 self.darkView.translatesAutoresizingMaskIntoConstraints = false self.darkView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true self.darkView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.darkView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true self.darkView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true // Container View let extraViewContainer = UIView.init() extraViewContainer.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(extraViewContainer) self.topAnchorContraint = NSLayoutConstraint.init(item: extraViewContainer, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 1000) self.topAnchorContraint.isActive = true extraViewContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true extraViewContainer.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true extraViewContainer.heightAnchor.constraint(equalTo: self.view.heightAnchor, multiplier: 1).isActive = true extraViewContainer.backgroundColor = UIColor.clear // Contacts View self.contactsCollectionView.delegate = self self.contactsCollectionView.dataSource = self extraViewContainer.addSubview(self.contactsView) self.contactsView.translatesAutoresizingMaskIntoConstraints = false self.contactsView.topAnchor.constraint(equalTo: extraViewContainer.topAnchor).isActive = true self.contactsView.leadingAnchor.constraint(equalTo: extraViewContainer.leadingAnchor).isActive = true self.contactsView.trailingAnchor.constraint(equalTo: extraViewContainer.trailingAnchor).isActive = true self.contactsView.bottomAnchor.constraint(equalTo: extraViewContainer.bottomAnchor).isActive = true self.contactsView.isHidden = true self.contactsCollectionView?.contentInset = UIEdgeInsetsMake(10, 0, 0, 0) self.contactsView.backgroundColor = UIColor.clear // Profile View extraViewContainer.addSubview(self.profileView) self.profileView.translatesAutoresizingMaskIntoConstraints = false self.profileView.heightAnchor.constraint(equalToConstant: (UIScreen.main.bounds.width * 0.9)).isActive = true let profileViewAspectRatio = NSLayoutConstraint.init(item: self.profileView, attribute: .width, relatedBy: .equal, toItem: self.profileView, attribute: .height, multiplier: 0.8125, constant: 0) profileViewAspectRatio.isActive = true self.profileView.centerXAnchor.constraint(equalTo: extraViewContainer.centerXAnchor).isActive = true self.profileView.centerYAnchor.constraint(equalTo: extraViewContainer.centerYAnchor).isActive = true self.profileView.layer.cornerRadius = 5 self.profileView.clipsToBounds = true self.profileView.isHidden = true self.profileImageView.layer.borderColor = GlobalVariables.green.cgColor self.profileImageView.layer.borderWidth = 3 self.view.layoutIfNeeded() // Preview View extraViewContainer.addSubview(self.previewView) self.previewView.isHidden = true self.previewView.translatesAutoresizingMaskIntoConstraints = false self.previewView.leadingAnchor.constraint(equalTo: extraViewContainer.leadingAnchor).isActive = true self.previewView.topAnchor.constraint(equalTo: extraViewContainer.topAnchor).isActive = true self.previewView.trailingAnchor.constraint(equalTo: extraViewContainer.trailingAnchor).isActive = true self.previewView.bottomAnchor.constraint(equalTo: extraViewContainer.bottomAnchor).isActive = true self.previewScrollView.minimumZoomScale = 1.0 self.previewScrollView.maximumZoomScale = 3.0 // Map extraViewContainer extraViewContainer.addSubview(self.mapPreviewView) self.mapPreviewView.isHidden = true self.mapPreviewView.translatesAutoresizingMaskIntoConstraints = false self.mapPreviewView.leadingAnchor.constraint(equalTo: extraViewContainer.leadingAnchor).isActive = true self.mapPreviewView.topAnchor.constraint(equalTo: extraViewContainer.topAnchor).isActive = true self.mapPreviewView.trailingAnchor.constraint(equalTo: extraViewContainer.trailingAnchor).isActive = true self.mapPreviewView.bottomAnchor.constraint(equalTo: extraViewContainer.bottomAnchor).isActive = true // NotificationCenter for showing extra views NotificationCenter.default.addObserver(self, selector: #selector(self.showExtraViews(notification:)), name: NSNotification.Name(rawValue: "showExtraView"), object: nil) // Loading Data self.fetchUsers() self.fetchUserInfo() } // MARK: - User(s) fetching // Retrieve all user from DataService func fetchUsers(){ if let userID = Auth.auth().currentUser?.uid { DataService.instance.getUsers(exceptUserID: userID, handler: { (returnedUsersArray) in DispatchQueue.main.async { self.items = returnedUsersArray for user in self.items { print(user.email) } self.contactsCollectionView.reloadData() } }) } } // Retrieve all user info from DataService func fetchUserInfo(){ if let userID = Auth.auth().currentUser?.uid { // chamar user info DataService.instance.REF_USERS.observe(.value, with: { (snapshot) in DataService.instance.getUserInfo(forID: userID, handler: { (returnedUserInfo) in DispatchQueue.main.async { self.profileNameLbl.text = returnedUserInfo.name self.profileEmailLbl.text = returnedUserInfo.email self.profileImageView.image = returnedUserInfo.profileImage } }) }) } } // MARK: - Views Handlers @objc func showExtraViews(notification: NSNotification){ let transform = CGAffineTransform.init(scaleX: 0.94, y: 0.94) self.topAnchorContraint.constant = 0 self.darkView.isHidden = false if let type = notification.userInfo?["viewType"] as? ShowExtraView { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.view.layoutIfNeeded() self.darkView.alpha = 0.8 if (type == .contacts || type == .profile) { self.view.transform = transform } }) switch type { case .contacts: self.contactsView.isHidden = false if self.items.count == 0 { } case .profile: self.profileView.isHidden = false case .preview: self.previewView.isHidden = false self.previewImageView.image = notification.userInfo?["profileImage"] as? UIImage self.previewScrollView.contentSize = self.previewImageView.frame.size case .map: self.mapPreviewView.isHidden = false let coordinate = notification.userInfo?["location"] as? CLLocationCoordinate2D let annotation = MKPointAnnotation.init() annotation.coordinate = coordinate! self.mapView.addAnnotation(annotation) self.mapView.showAnnotations(self.mapView.annotations, animated: false) } } } //Hide Extra views func dismissExtraViews() { self.topAnchorContraint.constant = 1000 UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.view.layoutIfNeeded() self.darkView.alpha = 0 self.view.transform = CGAffineTransform.identity }, completion: { (true) in self.darkView.isHidden = true self.profileView.isHidden = true self.contactsView.isHidden = true self.previewView.isHidden = true self.mapPreviewView.isHidden = true self.mapView.removeAnnotations(self.mapView.annotations) let vc = self.viewControllers.last vc?.inputAccessoryView?.isHidden = false }) } // MARK: - Preview Methods // Preview view scrollview zooming func viewForZooming(in scrollView: UIScrollView) -> UIView? { return self.previewImageView } // Preview view scrollview's zoom calculation func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect { var zoomRect = CGRect.zero zoomRect.size.height = self.previewImageView.frame.size.height / scale zoomRect.size.width = self.previewImageView.frame.size.width / scale let newCenter = self.previewImageView.convert(center, from: self.previewScrollView) zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0) zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0) return zoomRect } // MARK: - Buttons Actions // Generic function for all close buttons @IBAction func closeView(_ sender: UIButton) { self.dismissExtraViews() } @IBAction func logOutUser(_ sender: UIButton) { AuthService.instance.signOut { (status) in if status == true { self.dismiss(animated: true, completion: nil) } } } //Extra gesture to allow user double tap for zooming of preview view scrollview @IBAction func doubleTapGesture(_ sender: UITapGestureRecognizer) { if self.previewScrollView.zoomScale == 1 { self.previewScrollView.zoom(to: zoomRectForScale(scale: self.previewScrollView.maximumZoomScale, center: sender.location(in: sender.view)), animated: true) } else { self.previewScrollView.setZoomScale(1, animated: true) } } } extension NavVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.items.count == 0 { return 1 } else { return self.items.count } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if self.items.count == 0 { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "emptyCell", for: indexPath) return cell } else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "contactsCell", for: indexPath) as! ContactsCell cell.configureCell(forUser: self.items[indexPath.row]) return cell } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if self.items.count > 0 { self.dismissExtraViews() let userInfo = ["user": self.items[indexPath.row]] NotificationCenter.default.post(name: NSNotification.Name.init("showUserMessages"), object: nil, userInfo: userInfo) } } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if self.items.count == 0 { return self.contactsCollectionView.bounds.size } else { if UIScreen.main.bounds.width > UIScreen.main.bounds.height { let width = (0.3 * UIScreen.main.bounds.height) let height = width + 30 return CGSize.init(width: width, height: height) } else { let width = (0.3 * UIScreen.main.bounds.width) let height = width + 30 return CGSize.init(width: width, height: height) } } } } extension NavVC: UIScrollViewDelegate {}
gpl-3.0
f242ffdc40aa183a306b159e844af2a2
37.808777
195
0.768498
4.151576
false
false
false
false
festrs/Tubulus
Tubulus/BarCodeCalc.swift
1
7251
// // BarCodeCalc.swift // IBoleto-Project // // Created by Felipe Dias Pereira on 2016-02-28. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import Foundation public struct StructBarCode { var barCode: String var barCodeLine: String var bank: String? var value: Float? var expDate: NSDate? init(barCode: String, barCodeLine: String,bank:String?, value: Float?, expDate: NSDate?){ self.barCode = barCode self.barCodeLine = barCodeLine self.value = value self.expDate = expDate self.bank = bank } func toStringJSON()->String{ let formatter = NSNumberFormatter() formatter.minimumIntegerDigits = 2 if (expDate != nil) { return "{\"id\":\"\(barCode)\",\"bar_code_line\":\"\(barCodeLine)\",\"value\":\(value!),\"mes\":\"\(formatter.stringFromNumber((expDate?.getComponent(.Month))!)!)/\((expDate?.getComponent(.Year))!)\",\"bank\":\"\(bank!)\",\"exp_date\":\(expDate!.timeIntervalSince1970),\"created_at\":\"\((NSDate().timeIntervalSince1970))\"}" }else{ return "{\"id\":\"\(barCode)\",\"bar_code_line\":\"\(barCodeLine)\",\"value\":\(value!),\"mes\":\"nil\",\"bank\":\"\(bank!)\",\"exp_date\":\"nil\",\"created_at\":\"\((NSDate().timeIntervalSince1970))\"}" } } } enum BarCodeCalcError: ErrorType, Equatable { case ToManyCharacters (message: String) } func ==(lhs: BarCodeCalcError, rhs: BarCodeCalcError) -> Bool { switch (lhs, rhs) { case (.ToManyCharacters(let leftMessage), .ToManyCharacters(let rightMessage)): return leftMessage == rightMessage } } class BarCodeCalc{ func extractDataFromBarCode(barCode: String) throws -> StructBarCode { let barCodeLine = try calcStringFromBarCode(barCode) let valueString = barCode.substringWithRange(5, end: 15) let index = valueString.characters.count-2 let value = valueString.insert(".", ind: index) var valueF = Float(value) var expDate:NSDate? var bank = "" if !verifyModulo11(barCode) { if Int(barCode.substringWithRange(5, end: 9)) == 0{ valueF = 0.0 }else{ let valueString = barCode.substringWithRange(9, end: 19) let index = valueString.characters.count-2 let value = valueString.insert(".", ind: index) valueF = Float(value) } let days:Int = Int(barCode.substringWithRange(5, end: 9))! if days != 0{ // date started 7/10/1997 let formatter = NSDateFormatter() formatter.dateFormat = "yyyy/MM/dd" let someDateTime = formatter.dateFromString("1997/10/8") expDate = (someDateTime?.dateByAddingTimeInterval(Double(60*60*24*days)))! } let bankID = Int(barCode.substringWithRange(0, end: 3)) bank = banks[bankID!]! } return StructBarCode(barCode: barCode, barCodeLine: barCodeLine, bank: bank, value: valueF, expDate: expDate) } // Posição 01-03 = Identificação do banco (exemplo: 001 = Banco do Brasil) // Posição 04-04 = Código de moeda (exemplo: 9 = Real) // Posição 05-09 = 5 primeiras posições do campo livre (posições 20 a 24 do código de barras) // Posição 10-10 = Dígito verificador do primeiro campo // Posição 11-20 = 6ª a 15ª posições do campo livre (posições 25 a 34 do código de barras) // Posição 21-21 = Dígito verificador do segundo campo // Posição 22-31 = 16ª a 25ª posições do campo livre (posições 35 a 44 do código de barras) // Posição 32-32 = Dígito verificador do terceiro campo // Posição 33-33 = Dígito verificador geral (posição 5 do código de barras) // Posição 34-37 = Fator de vencimento (posições 6 a 9 do código de barras) // Posição 38-47 = Valor nominal do título (posições 10 a 19 do código de barras) func calcStringFromBarCode(barCode: String) throws -> String{ guard barCode.characters.count <= 46 else { throw BarCodeCalcError.ToManyCharacters(message: "Not 44 Characters") } let campo1 = barCode.substringWithRange(0, end: 4) + barCode.substringWithRange(19, end: 20) + barCode.substringWithRange(20, end: 24) let campo2 = barCode.substringWithRange(24, end: 29) + barCode.substringWithRange(29, end: 34) let campo3 = barCode.substringWithRange(34, end: 39) + barCode.substringWithRange(39, end: 44) let campo4 = barCode.substringWithRange(4, end: 5) let campo5 = barCode.substringWithRange(5, end: 19) // verificador de conta consumo if verifyModulo11(barCode) { let field1 = barCode.substringWithRange(0, end: 11) + modulo10(barCode.substringWithRange(0, end: 11)).description let field2 = barCode.substringWithRange(11, end: 22) + modulo10(barCode.substringWithRange(11, end: 22)).description let field3 = barCode.substringWithRange(22, end: 33) + modulo10(barCode.substringWithRange(22, end: 33)).description let field4 = barCode.substringWithRange(33, end: 44) + modulo10(barCode.substringWithRange(33, end: 44)).description return field1+field2+field3+field4 }else{ return campo1+self.modulo10(campo1).description+campo2+self.modulo10(campo2).description+campo3+self.modulo10(campo3).description+campo4+campo5 } } // verificador de conta consumo func verifyModulo11(barCode: String) ->Bool{ let modulo11Calc = modulo11(barCode.substringWithRange(0, end: 4) + barCode.substringWithRange(5, end: barCode.characters.count)) return modulo11Calc != Int(barCode.substringWithRange(4, end: 5)) } func modulo10(numero: String) -> Int{ var soma = 0 var peso = 2 var contador = (numero.characters.count - 1) while (contador >= 0) { var multiplicacao = Int(numero.substringWithRange(contador, end: contador+1))! * peso if (multiplicacao >= 10) {multiplicacao = 1 + (multiplicacao-10);} soma = soma + multiplicacao; if (peso == 2) { peso = 1; } else { peso = 2; } contador -= 1; } var digito = 10 - (soma % 10); if (digito == 10) { digito = 0; } return digito; } func modulo11(numero: String) -> Int{ var soma = 0 var peso = 2 let base = 9 var contador = (numero.characters.count - 1) while (contador >= 0){ soma = soma + Int(numero.substringWithRange(contador, end: contador+1))! * peso if peso < base { peso += 1 }else{ peso = 2 } contador -= 1; } var digito = 11 - (soma % 11) if digito > 9{ digito = 0 } if digito == 0{ digito = 1 } return digito } }
mit
4f1ae0144e185105f4533b66bd032f47
40.578035
337
0.592325
3.839829
false
false
false
false
jfosterdavis/Charles
Charles/CustomStoreCollectionViewCell.swift
1
10195
// // CustomStoreCollectionViewCell.swift // Charles // // Created by Jacob Foster Davis on 5/11/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit class CustomStoreCollectionViewCell: CommonStoreCollectionViewCell { //label @IBOutlet weak var characterNameLabel: UILabel! @IBOutlet weak var priceLabel: UILabel! @IBOutlet weak var stackView: UIStackView! @IBOutlet weak var buyButton: UIButton! //status @IBOutlet weak var statusShade: UIView! @IBOutlet weak var statusLabel: UILabel! @IBOutlet weak var pieLockImageView: UIImageView! @IBOutlet weak var characterOutfitBlocker: UIView! var canShowInfo = true //expiration timer @IBOutlet weak var expirationStatusView: UIView! var characterClue: Character? = nil /******************************************************/ /*******************///MARK: Appearance /******************************************************/ // func roundCorners() { // // self.layer.masksToBounds = true // var maskLayer = CAShapeLayer() // // //top left // // maskLayer.path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: [.allCorners], cornerRadii: CGSize(width: 10, height: 10)).cgPath // self.layer.mask = maskLayer // // } /// Adds buttons from the given phrase to the stackview func loadAppearance(from phrase: Phrase) { guard let slots = phrase.slots else { //TODO: handle phrase with nil slots return } //empty all buttons for subView in stackView.subviews { stackView.removeArrangedSubview(subView) //remove button from heirarchy subView.removeFromSuperview() } //buttonStackView.translatesAutoresizingMaskIntoConstraints = false var counter = 0 //step through each slot and createa button for it for slot in slots { //create a button let slotButton = createButton(from: slot) //add the button to the array of buttons //currentButtons.append(slotButton) //add the button to the stackview stackView.addArrangedSubview(slotButton) //create layout constraints for the button let widthConstraint = NSLayoutConstraint(item: slotButton, attribute: .width, relatedBy: .equal, toItem: stackView, attribute: .width, multiplier: 1, constant: 0) widthConstraint.isActive = true stackView.addConstraint(widthConstraint) counter += 1 } roundCorners() characterOutfitBlocker.isHidden = true self.backgroundColor = UIColor(red: 249/255, green: 234/255, blue: 188/255, alpha: 1) self.canUserHighlight = true self.isUserInteractionEnabled = true self.canShowInfo = true } /// creates a new button with the color indicated by the given Slot func createButton(from slot: Slot) -> UIButton { let newButton = UIButton(type: .system) newButton.backgroundColor = slot.color newButton.setTitle("", for: .normal) //disable buttons in this interface newButton.isEnabled = false return newButton } /******************************************************/ /*******************///MARK: Status /******************************************************/ ///sets the status to unlocked func setStatusAffordable() { //rotate and set text of the label statusLabel.transform = CGAffineTransform.identity //resets to normal statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees statusLabel.text = "For Hirė" statusShade.alpha = 0.05 statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1) setStatusVisibility(label: true, shade: true) priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1) priceLabel.font = UIFont(name:"GurmukhiMN", size: 15.0) self.canUserHighlight = true self.isUserInteractionEnabled = true self.canShowInfo = true } func setStatusVisibility(label: Bool, shade: Bool){ statusLabel.isHidden = !label statusShade.isHidden = !shade } ///sets the visual status to affordable and ready for purchase func setStatusUnlocked() { setStatusVisibility(label: false, shade: false) priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1) priceLabel.font = UIFont(name:"GurmukhiMN", size: 15.0) priceLabel.text = "Employėd" self.canUserHighlight = true self.isUserInteractionEnabled = true self.canShowInfo = true } func setStatusUnaffordable() { //rotate and set text of the label statusLabel.transform = CGAffineTransform.identity //resets to normal statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees statusLabel.text = "For Hirė" priceLabel.layer.zPosition = 1 self.setNeedsDisplay() statusShade.alpha = 0.45 statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1) setStatusVisibility(label: true, shade: true) priceLabel.textColor = .red priceLabel.font = UIFont(name:"GurmukhiMN-Bold", size: 15.0) self.canUserHighlight = true self.isUserInteractionEnabled = true self.canShowInfo = true } func setStatusLevelRequirementNotMet(levelRequired: Int) { //rotate and set text of the label statusLabel.transform = CGAffineTransform.identity //resets to normal //statusLabel.transform = CGAffineTransform(rotationAngle: -CGFloat.pi / 5) //rotates <45 degrees statusLabel.text = "Level \(levelRequired)" statusShade.alpha = 0.80 characterOutfitBlocker.isHidden = false //hide the outfit self.backgroundColor = .white //put the card to white statusShade.backgroundColor = UIColor(red: 102/255, green: 102/255, blue: 102/255, alpha: 1) setStatusVisibility(label: false, shade: true) priceLabel.text = "" priceLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1) priceLabel.font = UIFont(name:"GurmukhiMN-Bold", size: 15.0) self.canUserHighlight = false self.isUserInteractionEnabled = false self.canShowInfo = false } override func showInfo() { //launch the clue if it exists print("character clue button pressed") if let character = self.characterClue, canShowInfo { //create an image from the CharacterView to display //define the frame (size) for the view let screen = self.superview!.bounds let width = screen.width / 2 //make image 1/3 size of CV let height = width let frame = CGRect(x: 0, y: 0, width: width, height: height) let x = (screen.size.width - frame.size.width) * 0.5 let y = (screen.size.height - frame.size.height) * 0.5 let mainFrame = CGRect(x: x, y: y, width: frame.size.width, height: frame.size.height) //setup the paramaters for it to draw let characterView = CharacterView() characterView.frame = mainFrame characterView.phrase = character.phrases![0] characterView.setNeedsDisplay() let characterViewImage = characterView.asImage() //check how long the description is and split in two //let wordCount = Utilities.wordCount(character.gameDescription) let part1 = character.gameDescription var usableDurationString = "" let durationString = Utilities.getEasyDurationString(from: (character.hoursUnlocked * 60)) usableDurationString = String(describing: "Employs for \(durationString).") if character.name == "Dan" { usableDurationString = "Dan is forever in your employ." } // if wordCount.count > 30 { // let twoHalves = Utilities.getTwoStringsFromOne(character.gameDescription) // part1 = twoHalves.0 // part2 = twoHalves.1 // } else { // // } //create a clue based on the perk that was pressed let characterClue = Clue(clueTitle: character.name, part1: nil, part1Image: characterViewImage, part2: part1, part3: usableDurationString ) if let storyboard = self.storyboard { let topVC = topMostController() let clueVC = storyboard.instantiateViewController(withIdentifier: "BasicClueViewController") as! BasicClueViewController clueVC.clue = characterClue clueVC.delayDismissButton = false //set the background to paper color clueVC.view.backgroundColor = UIColor(red: 249/255, green: 234/255, blue: 188/255, alpha: 1) //paper color clueVC.overrideTextColor = .black clueVC.overrideGoldenRatio = true clueVC.overrideStackViewDistribution = .fillEqually topVC.present(clueVC, animated: true, completion: nil) } } } }
apache-2.0
b0c12ec6e8bf0aeb5c211f8a11fb695e
37.456604
174
0.576293
5.070149
false
false
false
false
davidlivadaru/DLAngle
Tests/DLAngleTests/Validation/TrigonometricArgumentsCheckerTests.swift
1
7713
// // TrigonometricArgumentsCheckerTests.swift // DLAngle // // Created by David Livadaru on 3/11/17. // import XCTest @testable import DLAngle class TrigonometricArgumentsCheckerTests: XCTestCase { static var allTests = [ ("testAsinCheck", testAsinCheck), ("testAsinCheck2", testAsinCheck2), ("testAcosCheck", testAcosCheck), ("testAcosCheck2", testAcosCheck2), ("testTanCheck", testTanCheck), ("testTanCheck2", testTanCheck2), ("testTanCheck3", testTanCheck3), ("testCotCheck", testCotCheck), ("testCotCheck2", testCotCheck2), ("testCotCheck3", testCotCheck3), ("testSecCheck", testSecCheck), ("testSecCheck2", testSecCheck2), ("testSecCheck3", testSecCheck3), ("testCscCheck", testCscCheck), ("testCscCheck2", testCscCheck2), ("testCscCheck3", testCscCheck3) ] func testAsinCheck() { do { let checker = try TrigonometricArgumentsChecker(value: -2.0, function: .asin) try checker.check() XCTFail(throwFailedMessage(for: .asin)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .asin)) } catch { } } func testAsinCheck2() { do { let checker = try TrigonometricArgumentsChecker(value: -0.456587, function: .asin) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .asin)) } catch { XCTFail(failMessage(forCatched: error, testing: .asin)) } } func testAcosCheck() { do { let checker = try TrigonometricArgumentsChecker(value: -7.0, function: .acos) try checker.check() XCTFail(throwFailedMessage(for: .acos)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .acos)) } catch { } } func testAcosCheck2() { do { let checker = try TrigonometricArgumentsChecker(value: 0.909087, function: .acos) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .acos)) } catch { XCTFail(failMessage(forCatched: error, testing: .acos)) } } func testTanCheck() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi / 2), function: .tan) try checker.check() XCTFail(throwFailedMessage(for: .tan)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .tan)) } catch { } } func testTanCheck2() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: 3 * Double.pi / 2), function: .tan) try checker.check() XCTFail(throwFailedMessage(for: .asin)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .tan)) } catch { } } func testTanCheck3() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi), function: .tan) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .tan)) } catch { XCTFail(failMessage(forCatched: error, testing: .tan)) } } func testCotCheck() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: 0.0), function: .cot) try checker.check() XCTFail(throwFailedMessage(for: .cot)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .cot)) } catch { } } func testCotCheck2() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi), function: .cot) try checker.check() XCTFail(throwFailedMessage(for: .cot)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .cot)) } catch { } } func testCotCheck3() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi / 2), function: .cot) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .cot)) } catch { XCTFail(failMessage(forCatched: error, testing: .cot)) } } func testSecCheck() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi / 2), function: .sec) try checker.check() XCTFail(throwFailedMessage(for: .sec)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .sec)) } catch { } } func testSecCheck2() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: 3 * Double.pi / 2), function: .sec) try checker.check() XCTFail(throwFailedMessage(for: .sec)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .sec)) } catch { } } func testSecCheck3() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi), function: .sec) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .sec)) } catch { XCTFail(failMessage(forCatched: error, testing: .sec)) } } func testCscCheck() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi / 2), function: .csc) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .csc)) } catch { XCTFail(failMessage(forCatched: error, testing: .csc)) } } func testCscCheck2() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi), function: .csc) try checker.check() XCTFail(throwFailedMessage(for: .csc)) } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .csc)) } catch { } } func testCscCheck3() { do { let checker = try TrigonometricArgumentsChecker(angle: Radian(rawValue: Double.pi / 2), function: .csc) try checker.check() } catch let error as TrigonometricError where error == .undefinedFunction { XCTFail(failMessage(forCatched: error, testing: .csc)) } catch { XCTFail(failMessage(forCatched: error, testing: .csc)) } } }
mit
ff49e5be2ce5250cb6b12e88f14cce19
36.441748
119
0.604434
4.296936
false
true
false
false
tdjackey/TipCalculator
TipCalculator/ViewController.swift
1
2136
// // ViewController.swift // TipCalculator // // Created by Main Account on 12/18/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import UIKit class UIViewController { } class ViewController: UIKit.UIViewController, UITableViewDataSource { @IBOutlet var totalTextField : UITextField! @IBOutlet var taxPctSlider : UISlider! @IBOutlet var taxPctLabel : UILabel! @IBOutlet var resultsTextView : UITextView! let tipCalc = TipCalculatorModel(total: 33.25, taxPct: 0.06) @IBOutlet weak var tableView: UITableView! var possibleTips = Dictionary<Int, (tipAmt:Double, total:Double)>() var sortedKeys:[Int] = [] func refreshUI() { totalTextField.text = String(format: "%0.2f", tipCalc.total) taxPctSlider.value = Float(tipCalc.taxPct) * 100.0 taxPctLabel.text = "Tax Percentage (\(Int(taxPctSlider.value))%)" } override func viewDidLoad() { super.viewDidLoad() refreshUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func calculateTapped(sender : AnyObject) { tipCalc.total = Double((totalTextField.text as NSString).doubleValue) possibleTips = tipCalc.returnPossibleTips() sortedKeys = sorted(Array(possibleTips.keys)) tableView.reloadData() } @IBAction func taxPercentageChanged(sender : AnyObject) { tipCalc.taxPct = Double(taxPctSlider.value) / 100.0 refreshUI() } @IBAction func viewTapped(sender : AnyObject) { totalTextField.resignFirstResponder() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sortedKeys.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Value2, reuseIdentifier: nil) let tipPct = sortedKeys[indexPath.row] let tipAmt = possibleTips[tipPct]!.tipAmt let total = possibleTips[tipPct]!.total cell.textLabel?.text = "\(tipPct)%:" cell.detailTextLabel?.text = String(format:"Tip: $%0.2f, Total: $%0.2f", tipAmt, total) return cell } }
mit
a16afe69e93e7b070b5d8584296f3bf9
28.260274
107
0.714419
4.297787
false
false
false
false
carabina/DDMathParser
MathParser/TokenGenerator.swift
2
2042
// // TokenGenerator.swift // DDMathParser // // Created by Dave DeLong on 8/6/15. // // import Foundation internal class TokenGenerator: GeneratorType { typealias Element = Either<RawToken, TokenizerError> private let buffer: TokenCharacterBuffer private let extractors: Array<TokenExtractor> internal let operatorSet: OperatorSet init(string: String, operatorSet: OperatorSet, locale: NSLocale?) { self.operatorSet = operatorSet let operatorTokens = operatorSet.operatorTokenSet buffer = TokenCharacterBuffer(string: string) let numberExtractor: TokenExtractor if let locale = locale { numberExtractor = LocalizedNumberExtractor(locale: locale) } else { numberExtractor = NumberExtractor() } extractors = [ HexNumberExtractor(), numberExtractor, SpecialNumberExtractor(), ExponentExtractor(), VariableExtractor(operatorTokens: operatorTokens), QuotedVariableExtractor(), OperatorExtractor(operatorTokens: operatorTokens), IdentifierExtractor(operatorTokens: operatorTokens) ] } func next() -> Element? { while buffer.peekNext()?.isWhitespaceOrNewline == true { buffer.consume() } guard buffer.isAtEnd == false else { return nil } let start = buffer.currentIndex var errors = Array<Element>() for extractor in extractors { guard extractor.matchesPreconditions(buffer) else { continue } buffer.resetTo(start) let result = extractor.extract(buffer) switch result { case .Value(_): return result case .Error(_): errors.append(result) } } return errors.first } }
mit
eaba2f592190179688df892b234d677d
26.594595
74
0.566601
5.65651
false
false
false
false
meninsilicium/apple-swifty
Trilean.swift
1
4076
// // author: fabrice truillot de chambrier // created: 09.04.2015 // // license: see license.txt // // © 2015-2015, men in silicium sàrl // public enum Trilean { case False case True case WTF } extension Trilean { public init() { self = .False } public init( _ value: Trilean ) { self = value } public init( _ value: Boolean ) { switch value { case .True: self = .True case .False: self = .False } } public init( _ value: Bool ) { self = value ? .True : .False } public init( _ value: BooleanType ) { self = value ? .True : .False } } extension Trilean : BooleanLiteralConvertible { public init( booleanLiteral value: BooleanLiteralType ) { self = value ? .True : .False } } // Equatable extension Trilean : Equatable {} public func ==( lhs: Trilean, rhs: Trilean ) -> Bool { switch (lhs, rhs) { case (.False, .False), (.True, .True), (.WTF, .WTF): return true default: return false } } public func ==( lhs: Trilean, rhs: Trilean ) -> Boolean { switch (lhs, rhs) { case (.False, .False), (.True, .True), (.WTF, .WTF): return .True default: return .False } } // Comparable // .False < .WTF < .True extension Trilean : Comparable {} public func <( lhs: Trilean, rhs: Trilean ) -> Bool { switch (lhs, rhs) { case (.False, .True), (.False, .WTF), (.WTF, .True): return true default: return false } } public func <( lhs: Trilean, rhs: Trilean ) -> Boolean { switch (lhs, rhs) { case (.False, .True), (.False, .WTF), (.WTF, .True): return .True default: return .False } } public prefix func !( value: Trilean ) -> Trilean { switch value { case .False: return .True case .True: return .False case .WTF: return .WTF } } public prefix func ~( value: Trilean ) -> Trilean { return !value } public func &( lhs: Trilean, rhs: Trilean ) -> Trilean { return lhs && rhs } public func &&( lhs: Trilean, rhs: Trilean ) -> Trilean { switch (lhs, rhs) { case (.False, _): return .False case (.True, _): return rhs case (.WTF, .False): return .False case (.WTF, _): return .WTF } } public func &&( lhs: Trilean, rhs: Bool ) -> Trilean { return lhs && Trilean( rhs ) } public func &&( lhs: Bool, rhs: Trilean ) -> Trilean { return rhs && lhs } public func !&&( lhs: Trilean, rhs: Trilean ) -> Trilean { return !(lhs && rhs) } public func |( lhs: Trilean, rhs: Trilean ) -> Trilean { return lhs || rhs } public func ||( lhs: Trilean, rhs: Trilean ) -> Trilean { switch (lhs, rhs) { case (.False, _): return rhs case (.True, _): return .True case (.WTF, .True): return .True case (.WTF, _): return .WTF } } public func !||( lhs: Trilean, rhs: Trilean ) -> Trilean { return !(lhs || rhs) } public func ^( lhs: Trilean, rhs: Trilean ) -> Trilean { return lhs ^^ rhs } public func ^^( lhs: Trilean, rhs: Trilean ) -> Trilean { switch (lhs, rhs) { case (.False, .False), (.True, .True), (.WTF, .WTF): return .False case (.False, .True), (.True, .False): return .True default: return .WTF } } public func !^^( lhs: Trilean, rhs: Trilean ) -> Trilean { return !(lhs ^^ rhs) } // Printable extension Trilean : Printable { public var description: String { switch self { case .False: return "false" case .True: return "true" case .WTF: return "Schrödinger" } } } // MARK: chaining extension Trilean { public func onTrue( @noescape function: () -> Void ) -> Trilean { switch self { case .False: break case .True: function() case .WTF: break } return self } public func onFalse( @noescape function: () -> Void ) -> Trilean { switch self { case .False: function() case .True: break case .WTF: break } return self } public func onWTF( @noescape function: () -> Void ) -> Trilean { switch self { case .False: break case .True: break case .WTF: function() } return self } }
mpl-2.0
95085d2353801886873cf2a99293186e
17.856481
68
0.575988
2.957879
false
false
false
false
ryanbooker/SwiftCheck
Tutorial.playground/Contents.swift
1
30608
//: Playground - noun: a place where people can play import SwiftCheck //: # Prerequisites //: This tutorial assumes that you have a fairly good grasp of Swift, its syntax, and terms like //: //: * [(Data) Type](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html) //: * [Protocol-Oriented Programming](https://developer.apple.com/videos/wwdc/2015/?id=408) //: * [Test-Driven Development](https://en.wikipedia.org/wiki/Test-driven_development) //: * [Polymorphism](https://en.wikipedia.org/wiki/Polymorphism) //: * [Map/Filter/Reduce](https://medium.com/@ivicamil/higher-order-functions-in-swift-part-1-d8e75f963d13) //: //: What this tutorial does *not* require is that you know about //: //: * [Abstract Nonsense](https://en.wikipedia.org/wiki/Abstract_nonsense) //: * Functional Programming //: * What that dumb ['M' word](https://wiki.haskell.org/Monad) is/does/means //: # Introduction //: SwiftCheck is a testing library that augments libraries like `XCTest` and `Quick` by giving //: them the ability to automatically test program properties. A property is a particular facet of //: an algorithm, method, data structure, or program that must *hold* (that is, remain valid) even //: when fed random or pseudo-random data. If that all seems complicated, it may be simpler to //: think of Property Testing like Fuzz Testing, but with the outcome being to satisfy requirements //: rather than break the program. Throughout this tutorial, simplifications like the above will be //: made to aid your understanding. Towards the end of it, we will begin to remove many of these //: "training wheels" and reveal the real concepts and types of the operations in the library, which //: are often much more powerful and generic than previously presented. //: //: Unlike Unit Testing, Property Testing is antithetical to the use of state and global variables. Property //: Tests are local, atomic entities that ideally only use the data given to them to match a //: user-defined specification for the behavior of a program or algorithm. While this may //: seem draconian, the upshot of following these [unwritten] rules is that the produced tests become //: "law-like", as in a [Mathematical or Scientific Law](https://en.wikipedia.org/wiki/Laws_of_science). //: //: When you approach your tests with a clear goal in mind, SwiftCheck allows you to turn //: that goal into many smaller parts that are each much easier to reason about than //: the whole problem at once. //: //: With that, let's begin. //: # `Gen`erators //: In Swift, when one thinks of a Generator, they usually think of the `GeneratorType` protocol or //: the many many individual structures the Swift Standard Library exposes to allow loops to work //: with data structures like `[T]` and `Set<T>`. In Swift, we also have Generators, but we spell //: them `Gen`erators, as in the universal Generator type `Gen`. //: //: `Gen` is a struct defined generically over any kind of type that looks like this: // // /// We're not defining this here; We'll be using SwiftCheck's `Gen` from here on out. // struct Gen<Wrapped> { } // //: `Gen`, unlike `GeneratorType`, is not backed by a concrete data structure like an `Array` or //: `Dictionary`, but is instead constructed by invoking methods that refine the kind of data that //: gets generated. Below are some examples of `Gen`erators that generate random instances of //: simple data types. // `Gen.pure` constructs a generator that *only* produces the given value. let onlyFive = Gen.pure(5) onlyFive.generate onlyFive.generate onlyFive.generate onlyFive.generate onlyFive.generate // `Gen.fromElementsIn` constructs a generator that pulls values from inside the bounds of the // given Range. Because generation is random, some values may be repeated. let fromOnetoFive = Gen<Int>.fromElementsIn(1...5) fromOnetoFive.generate fromOnetoFive.generate fromOnetoFive.generate fromOnetoFive.generate fromOnetoFive.generate let lowerCaseLetters : Gen<Character> = Gen<Character>.fromElementsIn("a"..."z") lowerCaseLetters.generate lowerCaseLetters.generate lowerCaseLetters.generate let upperCaseLetters : Gen<Character> = Gen<Character>.fromElementsIn("A"..."Z") upperCaseLetters.generate upperCaseLetters.generate upperCaseLetters.generate // `Gen.fromElementsOf` works like `Gen.fromElementsIn` but over an Array, not just a Range. // // mnemonic: Use `fromElementsIn` with an INdex. let specialCharacters = Gen<Character>.fromElementsOf([ "!", "@", "#", "$", "%", "^", "&", "*", "(", ")" ]) specialCharacters.generate specialCharacters.generate specialCharacters.generate specialCharacters.generate //: But SwiftCheck `Gen`erators aren't just flat types, they stack and compose and fit together in //: amazing ways. // `Gen.oneOf` randomly picks one of the generators from the given list and draws element from it. let uppersAndLowers = Gen<Character>.oneOf([ lowerCaseLetters, upperCaseLetters, ]) uppersAndLowers.generate uppersAndLowers.generate uppersAndLowers.generate uppersAndLowers.generate uppersAndLowers.generate // `Gen.zip` works like `zip` in Swift but with `Gen`erators. let pairsOfNumbers = Gen<(Int, Int)>.zip(fromOnetoFive, fromOnetoFive) pairsOfNumbers.generate pairsOfNumbers.generate pairsOfNumbers.generate //: `Gen`erators don't have to always generate their elements with equal frequency. SwiftCheck //: includes a number of functions for creating `Gen`erators with "weights" attached to their //: elements. // This generator ideally generates nil 1/4 (1 / (1 + 3)) of the time and `.Some(5)` 3/4 of the time. let weightedGen = Gen<Int?>.weighted([ (1, nil), (3, .Some(5)), ]) weightedGen.generate weightedGen.generate weightedGen.generate weightedGen.generate // `Gen.frequency` works like `Gen.weighted` and `Gen.oneOf` put together. let biasedUppersAndLowers = Gen<Character>.frequency([ (1, uppersAndLowers), (3, lowerCaseLetters), ]) //: `Gen`erators can even filter, modify, or combine the elements they create to produce. // `suchThat` takes a predicate function that filters generated elements. let oneToFiveEven = fromOnetoFive.suchThat { $0 % 2 == 0 } oneToFiveEven.generate oneToFiveEven.generate oneToFiveEven.generate // `proliferate` turns a generator of single elements into a generator of arrays of those elements. let characterArray = uppersAndLowers.proliferate characterArray.generate characterArray.generate characterArray.generate /// `proliferateNonEmpty` works like `proliferate` but guarantees the generated array is never empty. let oddLengthArrays = fromOnetoFive.proliferateNonEmpty.suchThat { $0.count % 2 == 1 } oddLengthArrays.generate.count oddLengthArrays.generate.count oddLengthArrays.generate.count //: Generators also admit functional methods like `map` and `flatMap`, but with different names than //: you might be used to. // `Gen.map` works exactly like Array's `map` method; it applies the function to any // values it generates. let fromTwoToSix = fromOnetoFive.map { $0 + 1 } fromTwoToSix.generate fromTwoToSix.generate fromTwoToSix.generate fromTwoToSix.generate fromTwoToSix.generate // `Gen.flatMap` works exactly like `Array`'s `flatMap`, but instead of concatenating the generated // arrays it produces a new generator that picks values from among the newly created generators // produced by the function. // // While that definition may *technically* be what occurs, it is better to think of `flatMap` as a // way of making a generator depend on another. For example, you can use a generator of sizes to // limit the length of generators of arrays: let generatorBoundedSizeArrays = fromOnetoFive.flatMap { len in return characterArray.suchThat { xs in xs.count <= len } } generatorBoundedSizeArrays.generate generatorBoundedSizeArrays.generate generatorBoundedSizeArrays.generate generatorBoundedSizeArrays.generate generatorBoundedSizeArrays.generate //: Because SwiftCheck is based on the functional concepts in our other library //: [Swiftz](https://github.com/typelift/Swiftz), each of these functions has an operator alias: //: //: * `<^>` is an alias for `map` //: * `<*>` is an alias for `ap` //: * `>>-` is an alias for `flatMap` let fromTwoToSix_ = { $0 + 1 } <^> fromOnetoFive fromTwoToSix_.generate fromTwoToSix_.generate fromTwoToSix_.generate let generatorBoundedSizeArrays_ = fromOnetoFive >>- { len in return characterArray.suchThat { xs in xs.count <= len } } generatorBoundedSizeArrays_.generate generatorBoundedSizeArrays_.generate generatorBoundedSizeArrays_.generate //: For our purposes, we will say that an email address consists of 3 parts: A local part, a //: hostname, and a Top-Level Domain each separated by an `@`, and a `.` respectively. //: //: According to RFC 2822, the local part can consist of uppercase characters, lowercase letters, //: numbers, and certain kinds of special characters. We already have generators for upper and //: lower cased letters, so all we need are special characters and a more complete number generator: let numeric : Gen<Character> = Gen<Character>.fromElementsIn("0"..."9") let special : Gen<Character> = Gen<Character>.fromElementsOf(["!", "#", "$", "%", "&", "'", "*", "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~", "."]) //: Now for the actual generator let allowedLocalCharacters : Gen<Character> = Gen<Character>.oneOf([ upperCaseLetters, lowerCaseLetters, numeric, special, ]) //: Now we need a `String` made of these characters. so we'll just `proliferate` an array of characters and `fmap` //: to get a `String` back. let localEmail = allowedLocalCharacters .proliferateNonEmpty // Make a non-empty array of characters .suchThat({ $0[$0.endIndex.predecessor()] != "." }) // Such that the last character isn't a dot. .map(String.init) // Then make a string. //: The RFC says that the host name can only consist of lowercase letters, numbers, and dashes. We'll skip some //: steps here and combine both steps into one big generator. let hostname = Gen<Character>.oneOf([ lowerCaseLetters, numeric, Gen.pure("-"), ]).proliferateNonEmpty.map(String.init) //: Finally, the RFC says the TLD for the address can only consist of lowercase letters with a length larger than 1. let tld = lowerCaseLetters .proliferateNonEmpty .suchThat({ $0.count > 1 }) .map(String.init) //: So now we've got all the pieces together, so how do we put them together to make the final generator? Well, how //: about some glue? // Concatenates an array of `String` `Gen`erators together in order. func glue(parts : [Gen<String>]) -> Gen<String> { return sequence(parts).map { $0.reduce("", combine: +) } } let emailGen = glue([localEmail, Gen.pure("@"), hostname, Gen.pure("."), tld]) //: And we're done! // Yes, these are in fact, all valid email addresses. emailGen.generate emailGen.generate emailGen.generate //: By now you may be asking "why do we need all of this in the first place? Can't we just apply //: the parts to the function to get back a result?" Well, we do it because we aren't working with //: `Character`s or `String`s or `Array`s, we're working with `Gen<String>`. And we can't apply //: `Gen<String>` to a function that expects `String`, that wouldn't make any sense - and it would //: never compile! Instead we use these operators to "lift" our function over `String`s to //: functions over `Gen<String>`s. //: //: Complex cases like the above are rare in practice. Most of the time you won't even need to use //: generators at all! This brings us to one of the most important parts of SwiftCheck: //: # Arbitrary //: Here at TypeLift, we believe that Types are the most useful part of a program. So when we were //: writing SwiftCheck, we thought about just using `Gen` everywhere and making instance methods on //: values that would ask them to generate a "next" value. But that would have been incredibly //: boring! Instead, we wrote a protocol called `Arbitrary` and let Types, not values, do all the //: work. //: //: The `Arbitrary` protocol looks like this: // // public protocol Arbitrary { // /// The generator for this particular type. // /// // /// This function should call out to any sources of randomness or state necessary to generate // /// values. It should not, however, be written as a deterministic function. If such a // /// generator is needed, combinators are provided in `Gen.swift`. // static var arbitrary : Gen<Self> { get } // } // //: There's our old friend, `Gen`! So, an `Arbitrary` type is a type that can give us a generator //: to create `Arbitrary` values. SwiftCheck defines `Arbitrary` instances for the majority of //: types in the Swift Standard Library in the ways you might expect e.g. The `Arbitrary` instance //: for `Int` calls `arc4random_uniform`. //: //: We'll take this opportunity here to show you how to use Arbitrary for any types you might happen //: to write yourself. But before that, let's try to write an `Arbitrary` instance for `NSDate`. import class Foundation.NSDate //: Here's the obvious way to do it // // extension NSDate : Arbitrary { // public static var arbitrary : Gen<NSDate> { // return Gen.oneOf([ // Gen.pure(NSDate()), // Gen.pure(NSDate.distantFuture()), // Gen.pure(NSDate.distantPast()), // NSDate.init <^> NSTimeInterval.arbitrary, // ]) // } // } // //: But this doesn't work! Swift won't let us extend `NSDate` directly because we use `Gen<Self>` //: in the wrong position. What to do? //: //: Let's write a wrapper! struct ArbitraryDate : Arbitrary { let getDate : NSDate init(date : NSDate) { self.getDate = date } static var arbitrary : Gen<ArbitraryDate> { return Gen.oneOf([ Gen.pure(NSDate()), Gen.pure(NSDate.distantFuture()), Gen.pure(NSDate.distantPast()), NSDate.init <^> NSTimeInterval.arbitrary, ]).map(ArbitraryDate.init) } } ArbitraryDate.arbitrary.generate.getDate ArbitraryDate.arbitrary.generate.getDate //: What we've just written is called a `Modifier Type`; a wrapper around one type that we can't //: generate with another that we can. //: //: SwiftCheck uses this strategy for a few of the more "difficult" types in the Swift STL, but //: we also use them in more benign ways too. For example, we can write a modifier type that only //: generates positive numbers: public struct ArbitraryPositive<A : protocol<Arbitrary, SignedNumberType>> : Arbitrary { public let getPositive : A public init(_ pos : A) { self.getPositive = pos } public static var arbitrary : Gen<ArbitraryPositive<A>> { return A.arbitrary.map { ArbitraryPositive.init(abs($0)) } } } ArbitraryPositive<Int>.arbitrary.generate.getPositive ArbitraryPositive<Int>.arbitrary.generate.getPositive ArbitraryPositive<Int>.arbitrary.generate.getPositive //: # Quantifiers //: What we've seen so far are the building blocks we need to introduce the final part of the //: library: The actual testing interface. The last concept we'll introduce is *Quantifiers*. //: //: A Quantifier is a contract that serves as a guarantee that a property holds when the given //: testing block returns `true` or truthy values, and fails when the testing block returns `false` //: or falsy values. The testing block is usually used with Swift's abbreviated block syntax and //: requires type annotations for all value positions being requested. There is only one quantifier //: in SwiftCheck, `forAll`. As its name implies, `forAll` will produce random data and your spec //: must pass "for all" of the values. Here's what it looks like: // // func forAll<A : Arbitrary>(_ : (A... -> Bool)) -> Property // //: The actual type of `forAll` is much more general and expressive than this, but for now this will do. //: //: Here is an example of a simple property // + This is "Property Notation". It allows you to give your properties a name and instructs SwiftCheck to test it. // | + This backwards arrow binds a property name and a property to each other. // | | // v v property("The reverse of the reverse of an array is that array") <- forAll { (xs : [Int]) in return xs.reverse().reverse() == xs } // From now on, all of our examples will take the form above. //: Because `forAll` is variadic it works for a large number and variety of types too: // +--- This Modifier Type produces Arrays of Integers. // | +--- This Modifier Type generates functions. That's right, SwiftCheck // | | can generate *functions*!! // v v property("filter behaves") <- forAll { (xs : ArrayOf<Int>, pred : ArrowOf<Int, Bool>) in let f = pred.getArrow return xs.getArray.filter(f).reduce(true, combine: { $0.0 && f($0.1) }) // ^ This property says that if we filter an array then apply the predicate // to all its elements, then they should all respond with `true`. } // How about a little Boolean Algebra too? property("DeMorgan's Law") <- forAll { (x : Bool, y : Bool) in let l = !(x && y) == (!x || !y) let r = !(x || y) == (!x && !y) return l && r } //: The thing to notice about all of these examples is that there isn't a `Gen`erator in sight. Not //: once did we have to invoke `.generate` or have to construct a generator. We simply told the //: `forAll` block how many variables we wanted and of what type and SwiftCheck automagically went //: out and was able to produce random values. //: //: Our not-so-magic trick is enabled behind the scenes by the judicious combination of `Arbitrary` //: to construct default generators for each type and a testing mechanism that invokes the testing //: block for the proper number of tests. For some real magic, let's see what happens when we fail //: a test: // `reportProperty` is a variation of `property` that doesn't assert on failure. It does, however, // still print all failures to the console. We use it here because XCTest does not like it when you // assert outside of a test case. reportProperty("Obviously wrong") <- forAll({ (x : Int) in return x != x }).whenFail { // `whenFail` attaches a callback to the test when we fail. print("Oh noes!") } //: If you open the console for the playground, you'll see output very similar to the following: //: //: *** Failed! Proposition: Obviously wrong //: Falsifiable (after 1 test): //: Oh noes! //: 0 //: //: The first line tells you what failed, the next how long it took to fail, the next our message //: from the callback, and the last the value of `x` the property failed with. If you keep running //: the test over and over again you'll notice that the test keeps failing on the number 0 despite //: the integer supposedly being random. What's going on here? //: //: To find out, let's see the full definition of the `Arbitrary` protocol: // // public protocol Arbitrary { // /// The generator for this particular type. // /// // /// This function should call out to any sources of randomness or state necessary to generate // /// values. It should not, however, be written as a deterministic function. If such a // /// generator is needed, combinators are provided in `Gen.swift`. // static var arbitrary : Gen<Self> { get } // // /// An optional shrinking function. If this function goes unimplemented, it is the same as // /// returning the empty list. // /// // /// Shrunken values must be less than or equal to the "size" of the original type but never the // /// same as the value provided to this function (or a loop will form in the shrinker). It is // /// recommended that they be presented smallest to largest to speed up the overall shrinking // /// process. // static func shrink(_ : Self) -> [Self] // } // //: Here's where we one-up Fuzz Testing and show the real power of Property Testing. A "shrink" is //: a strategy for reducing randomly generated values. To shrink a value, all you need to do is //: return an array of "smaller values", whether in magnitude or value. For example, the shrinker //: for `Array` returns Arrays that have a size less than or equal to that of the input array. Array<Int>.shrink([1, 2, 3]) //: So herein lies the genius: Whenever SwiftCheck encounters a failing property, it simply invokes //: the shrinker, tries the property again on the values of the array until it finds another failing //: case, then repeats the process until it runs out of cases to try. In other words, it *shrinks* //: the value down to the least possible size then reports that to you as the failing test case //: rather than the randomly generated value which could be unnecessarily large or complex. //: Before we move on, let's write a Modifier Type with a custom shrinker for the email generator we defined a little while ago: // SwiftCheck defines default shrinkers for most of the types it gives Arbitrary instances. There // will often be times when those default shrinkers don't cut it, or you need more control over // what happens when you generate or shrink values. Modifier Types to the rescue! struct ArbitraryEmail : Arbitrary { let getEmail : String init(email : String) { self.getEmail = email } static var arbitrary : Gen<ArbitraryEmail> { return emailGen.map(ArbitraryEmail.init) } } // Let's be wrong for the sake of example property("email addresses don't come with a TLD") <- forAll { (email : ArbitraryEmail) in return !email.getEmail.containsString(".") }.expectFailure // It turns out true things aren't the only thing we can test. We can `expectFailure` // to make SwiftCheck, well, expect failure. Beware, however, that if you don't fail // and live up to your expectations, SwiftCheck treats that as a failure of the test case. //: # All Together Now! //: Let's put all of our newfound understanding of this framework to use by writing a property that //: tests an implementation of the Sieve of Eratosthenes: // The Sieve of Eratosthenes: // // To find all the prime numbers less than or equal to a given integer n: // - let l = [2...n] // - let p = 2 // - for i in [(2 * p) through n by p] { // mark l[i] // } // - Remaining indices of unmarked numbers are primes func sieve(n : Int) -> [Int] { if n <= 1 { return [] } var marked : [Bool] = (0...n).map { _ in false } marked[0] = true marked[1] = true for p in 2..<n { for i in (2 * p).stride(to: n, by: p) { marked[i] = true } } var primes : [Int] = [] for (t, i) in zip(marked, 0...n) { if !t { primes.append(i) } } return primes } // Trial Division // // Short and sweet check if a number is prime by enumerating from 2...⌈√(x)⌉ and checking // for a nonzero modulus. func isPrime(n : Int) -> Bool { if n == 0 || n == 1 { return false } else if n == 2 { return true } let max = Int(ceil(sqrt(Double(n)))) for i in 2...max { if n % i == 0 { return false } } return true } //: We would like to test whether our sieve works properly, so we run it through SwiftCheck with the //: following property: reportProperty("All Prime") <- forAll { (n : Positive<Int>) in let primes = sieve(n.getPositive) return primes.count > 1 ==> { let primeNumberGen = Gen<Int>.fromElementsOf(primes) return forAll(primeNumberGen) { (p : Int) in return isPrime(p) } } } //: This test introduces several new concepts that we'll go through 1-by-1: //: //: * `Positive<Wrapped>`: This is a Modifier Type defined by SwiftCheck that only produces //: integers larger than zero - positive integers. SwiftCheck also has //: modifiers for `NonZero` (all integers that aren't 0) and `NonNegative` //: (all positive integers including 0). //: //: * `==>`: This operator is called "Implication". It is used to introduce tests that need to //: reject certain kinds of data that gets generated. Here, because our prime number //: generator can return empty lists (which throws an error when used with `Gen.fromElementsOf`) //: we put a condition on the left-hand side that requires arrays have a size larger than 1. //: //: * `forAll` in `forAll`: The *actual* type that `forAll` expects is not `Bool`. It's a protocol //: called `Testable`, `Bool` just happens to conform to it. It turns out that //: `Property`, the thing `forAll` returns, does too. So you can nest `forAll`s //: in `forAll`s to your heart's content! //: //: * `forAll` + `Gen`: The `forAll`s we've seen before have all been using `Arbitrary` to retrieve a //: default `Gen`erator for each type. But SwiftCheck also includes a variant of //: `forAll` that takes a user-supplied generator. For those times when you want //: absolute control over generated values, like we do here, use that particular //: series of overloads. //: If you check the console, you'll notice that this property doesn't hold! //: //: *** Failed! Proposition: All Prime //: Falsifiable (after 11 tests and 2 shrinks): //: Positive( 4 ) // or Positive( 9 ) //: 0 //: //: What's wrong here? //: Let's go back to the spec we had for the sieve: // // The Sieve of Eratosthenes: // // To find all the prime numbers less than or equal to a given integer n: // - let l = [2...n] // - let p = 2 // - for i in [(2 * p) **through** n by p] { // mark l[i] // } // - Remaining indices of unmarked numbers are primes // //: Looks like we used `to:` when we meant `through:`. Let's try again: func sieveProperly(n : Int) -> [Int] { if n <= 1 { return [] } var marked : [Bool] = (0...n).map { _ in false } marked[0] = true marked[1] = true for p in 2..<n { for i in (2 * p).stride(through: n, by: p) { marked[i] = true } } var primes : [Int] = [] for (t, i) in zip(marked, 0...n) { if !t { primes.append(i) } } return primes } // Fo' Real This Time. property("All Prime") <- forAll { (n : Positive<Int>) in let primes = sieveProperly(n.getPositive) return primes.count > 1 ==> { let primeNumberGen = Gen<Int>.fromElementsOf(primes) return forAll(primeNumberGen) { (p : Int) in return isPrime(p) } } } //: And that's how you test with SwiftCheck. When properties fail, it means some part of your algorithm //: isn't handling the case presented. So you search through some specification to find the mistake in //: logic and try again. Along the way, SwiftCheck will do its best help you by presenting minimal //: cases at the least, and, with more advanced uses of the framework, the names of specific sub-parts of //: cases and even percentages of failing vs. passing tests. //: Just for fun, let's try a simpler property that checks the same outcome: property("All Prime") <- forAll { (n : Positive<Int>) in // Sieving Properly then filtering for primes is the same as just Sieving, right? return sieveProperly(n.getPositive).filter(isPrime) == sieveProperly(n.getPositive) } //; # One More Thing //: When working with failing tests, it's often tough to be able to replicate the exact conditions //: that cause a failure or a bug. With SwiftCheck, that is now a thing of the past. The framework //: comes with a replay mechanism that allows the arguments that lead to a failing test to be generated //: in exactly the same order, with exactly the same values, as they did the first time. When a test //: fails, SwiftCheck will present a helpful message that looks something like this in Xcode: //: > failed - Falsifiable; Replay with 123456789 123456789 //: Or this message in your log: //: > Pass the seed values 123456789 123456789 to replay the test. //: These are called *seeds*, and they can be fed back into the property that generated them to //: activate the replay feature. For example, here's an annoying test to debug because it only fails //: every so often on one particular value: reportProperty("Screw this value in particular") <- forAll { (n : UInt) in if (n == 42) { return false } return true } //: But with a replay seed of (1391985334, 382376411) we can always reproduce the failure because //: 42 will always be generated as the first value. We've turned on verbose mode to demonstrate this. /// By passing this argument to the test, SwiftCheck will automatically use the given seed values and /// size to completely replicate a particular set of values that caused the first test to fail. let replayArgs = CheckerArguments(replay: (StdGen(1391985334, 382376411), 100)) reportProperty("Replay", arguments: replayArgs) <- forAll { (n : UInt) in if (n == 42) { return false } return true }.verbose //: # Conclusion //: If you've made it this far, congratulations! That's it. Naturally, there are other combinators //: and fancy ways of creating `Gen`erators and properties with the primitives in this framework, //: but they are all variations on the themes present in ths tutorial. With the power of SwiftCheck //: and a sufficiently expressive testing suite, we can begin to check our programs not for //: individual passing cases in a few scattershot unit tests, but declare and enforce immutable //: properties that better describe the intent and invariants of our programs. If you would like //: further reading, see the files `Arbitrary.swift`, `Test.swift`, `Modifiers.swift`, and //: `Property.swift`. Beyond that, there are a number of resources built for the original framework //: and its other derivatives whose concepts translate directly into SwiftCheck: //: //: * [FP Complete's Intro to QuickCheck](https://www.fpcomplete.com/user/pbv/an-introduction-to-quickcheck-testing) //: * [Real World Haskell on QuickCheck for QA](http://book.realworldhaskell.org/read/testing-and-quality-assurance.html) //: * [ScalaCheck](https://www.scalacheck.org) //: * [The Original (slightly outdated) QuickCheck Tutorial](http://www.cse.chalmers.se/~rjmh/QuickCheck/manual.html) //: //: Go forth and test.
mit
8e1cc6ee9b2ba2a6518cf2d2c8f2f4b2
40.806011
162
0.695608
3.837241
false
true
false
false
silence0201/Swift-Study
Learn/19.Foundation/NSSet/NSMutableSet类.playground/section-1.swift
1
566
import Foundation var weeksNames = NSMutableSet(capacity: 3) weeksNames.add("星期一") weeksNames.add("星期二") weeksNames.add("星期三") weeksNames.add("星期四") weeksNames.add("星期五") weeksNames.add("星期六") weeksNames.add("星期日") print("星期名字") print("==== ====") for day in weeksNames { print(day) } var A: NSMutableSet = ["a","b","e","d"] var B: NSMutableSet = ["d","c","e","f"] A.minus(B as Set<NSObject>) print("A与B差集 = \(A)")//[b, a] A.union(B as Set<NSObject>) print("A与B并集 = \(A)")//[ d,b,e,c,a,f]
mit
6526189557e3d60b44148da306a596dc
16.37931
42
0.619048
2.446602
false
false
false
false
ello/ello-ios
Specs/Controllers/Onboarding/OnboardingProfileScreenSpec.swift
1
4935
//// /// OnboardingProfileScreenSpec.swift // @testable import Ello import Quick import Nimble class OnboardingProfileScreenSpec: QuickSpec { class MockDelegate: OnboardingProfileDelegate { var didAssignName = false var didAssignBio = false var didAssignLinks = false var didAssignCoverImage = false var didAssignAvatar = false func present(controller: UIViewController) {} func dismissController() {} func assign(name: String?) -> ValidationState { didAssignName = true return (name?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(bio: String?) -> ValidationState { didAssignBio = true return (bio?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(links: String?) -> ValidationState { didAssignLinks = true return (links?.isEmpty == false) ? ValidationState.ok : ValidationState.none } func assign(coverImage: ImageRegionData) { didAssignCoverImage = true } func assign(avatarImage: ImageRegionData) { didAssignAvatar = true } } override func spec() { describe("OnboardingProfileScreen") { var subject: OnboardingProfileScreen! var delegate: MockDelegate! beforeEach { subject = OnboardingProfileScreen() delegate = MockDelegate() subject.delegate = delegate showView(subject) } context("snapshots") { validateAllSnapshots(named: "OnboardingProfileScreen") { return subject } } context("snapshots setting existing data") { validateAllSnapshots(named: "OnboardingProfileScreen with data") { subject.name = "name" subject.bio = "bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio bio" subject.links = "links links links links links links links links links links links links" subject.linksValid = true subject.coverImage = ImageRegionData( image: UIImage.imageWithColor( .blue, size: CGSize(width: 1000, height: 1000) )! ) subject.avatarImage = ImageRegionData(image: specImage(named: "specs-avatar")!) return subject } } context("setting text") { it("should notify delegate of name change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Name") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignName) == true } it("should notify delegate of bio change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Bio") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignBio) == true } it("should notify delegate of link change") { let textView: ClearTextView! = subject.findSubview { $0.placeholder?.contains("Links") ?? false } _ = subject.textView( textView, shouldChangeTextIn: NSRange(location: 0, length: 0), replacementText: "!" ) expect(delegate.didAssignLinks) == true } it("should notify delegate of avatar change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .avatar, updateDelegate: true) expect(delegate.didAssignAvatar) == true } it("should notify delegate of coverImage change") { let image = ImageRegionData(image: UIImage.imageWithColor(.blue)!) subject.setImage(image, target: .coverImage, updateDelegate: true) expect(delegate.didAssignCoverImage) == true } } } } }
mit
75c4e779df757704b13e4e251ba72f66
40.470588
99
0.505167
5.868014
false
false
false
false
igerry/ProjectEulerInSwift
ProjectEulerInSwift/Euler/Problem19.swift
1
2140
import Foundation /* Counting Sundays Problem 19 171 You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? */ class Problem19 { func isLeapYear(year:Int) -> Bool { let isLeap:Bool = (year % 4 == 0) && ((year % 400 == 0) || (year % 100 != 0)) return isLeap } func solution() -> Int { var daysInMonth:[Int:Int] = [ 1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31, ] var weekDay = 0 // 1:monday var specialSunndays = 0 var year = 1900 while (year < 2001) { var daysInYear = 365 if isLeapYear(year) { daysInYear = 366 daysInMonth[2] = 29 } else { daysInYear = 365 daysInMonth[2] = 28 } var month = 1 var day = 0 for _ in 0..<daysInYear { // increase day & month day += 1 if day > daysInMonth[month] { day -= daysInMonth[month]! month += 1 } weekDay = (weekDay + 1) % 7 print("\(year, month, day)=\(weekDay)") // special if (weekDay == 0 && day == 1) { if year != 1900 { specialSunndays += 1 } } } year += 1 } return specialSunndays } }
apache-2.0
c3cf79cd2a85e1d7ba158db8237653ae
24.783133
106
0.449065
4.340771
false
false
false
false
internetarchive/wayback-machine-chrome
safari/Wayback Machine Extension/SafariWebExtensionHandler.swift
1
763
// // SafariWebExtensionHandler.swift // Wayback Machine Extension // // Created by Carl on 9/4/21. // import SafariServices import os.log let SFExtensionMessageKey = "message" class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling { func beginRequest(with context: NSExtensionContext) { let item = context.inputItems[0] as! NSExtensionItem let message = item.userInfo?[SFExtensionMessageKey] os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg) let response = NSExtensionItem() response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ] context.completeRequest(returningItems: [response], completionHandler: nil) } }
agpl-3.0
1bdad7b1adc3b15843a81fbfb8f5caaa
28.346154
108
0.720839
4.310734
false
false
false
false
khanxc/KXThumbCircularProgressBar
Example/KXThumbCircular-Example/Pods/KXThumbCircularProgressBar/KXThumbCircularProgressBar/KXThumbCircularProgressView/KXThumbCircularProgressBar.swift
1
11329
// Created by khan import Foundation import UIKit @objc public protocol KXArcNotifyDelegate { @objc optional func arcAnimationDidStart() @objc optional func arcAnimationDidStop() } /// This file creates a resuable component Arc view. let π: CGFloat = CGFloat(M_PI) @IBDesignable public class KXThumbCircularProgressBar: UIView { @IBInspectable public var ringBackgroundColour: UIColor = UIColor(netHex: 0xaba8a8) @IBInspectable public var ringForegroundColour: UIColor = UIColor.green // @IBInspectable public var backgroundImage: UIImage? //commented for next release feature // @IBInspectable var lowLevelColor: UIColor = UIColor.red // @IBInspectable var midLevelColor: UIColor = UIColor.orange // @IBInspectable var highLevelColor: UIColor = UIColor.green // must be between [0,100] @IBInspectable public var animateScale: Double = 0.0 @IBInspectable public var foreGroundArcWidth: CGFloat = 20 @IBInspectable public var backGroundArcWidth: CGFloat = 8 @IBInspectable public var isthumbImageAvailable: Bool = false @IBInspectable public var thumbImage: UIImage? @IBInspectable public var arcStartAngle: CGFloat = 120 @IBInspectable public var arcEndAngle: CGFloat = 60 @IBInspectable public var arcMargin: CGFloat = 75 // Display Image or Text @IBInspectable public var showImage: Bool = false @IBInspectable public var image: UIImage? @IBInspectable public var showText: Bool = false @IBInspectable public var valueFontName: String = "HelveticaNeue" @IBInspectable public var valueFontSize: CGFloat = 25.0 @IBInspectable public var showUnit: Bool = false @IBInspectable public var UnitString: String = "%" @IBInspectable public var unitFontName: String = "HelveticaNeue" @IBInspectable public var unitFontSize: CGFloat = 15.0 @IBInspectable public var fontColor: UIColor = UIColor.black @IBInspectable public var valueMultiplier: Double = 100 let ringLayer = CAShapeLayer() let thumbLayer = CALayer() let imgView = UIImageView() var thumbImageView = UIImageView() var arcPath = UIBezierPath() // Arc animation notify Delegate public var delegate: KXArcNotifyDelegate? public override func draw(_ rect: CGRect) { backgroundArc() if showImage { drawCenterImage() } if showText { drawText(rectSize: CGSize(width: rect.width, height: rect.height)) } let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let radius: CGFloat = max(bounds.width - arcMargin, bounds.height - arcMargin) let startAngle: CGFloat = arcStartAngle.degreesToRadians let endAngle: CGFloat = arcEndAngle.degreesToRadians arcPath = UIBezierPath( arcCenter: center, radius: radius / 2 - backGroundArcWidth / 2, // changed here startAngle: startAngle, endAngle: endAngle, clockwise: true) ringLayer.path = arcPath.cgPath //make it public on next push ringLayer.strokeColor = ringForegroundColour.cgColor ringLayer.fillColor = UIColor.clear.cgColor ringLayer.lineWidth = foreGroundArcWidth ringLayer.strokeEnd = 0.0 layer.addSublayer(ringLayer) animateArc(loaderValue: CGFloat(self.animateScale)) // changed here } private func backgroundArc() { // backGroundArcWidth = 5 let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let radius: CGFloat = max(bounds.width - arcMargin, bounds.height - arcMargin) let startAngle: CGFloat = arcStartAngle.degreesToRadians let endAngle: CGFloat = arcEndAngle.degreesToRadians let path = UIBezierPath( arcCenter: center, radius: radius / 2 - backGroundArcWidth / 2, startAngle: startAngle, endAngle: endAngle, clockwise: true) path.lineWidth = backGroundArcWidth ringBackgroundColour.setStroke() path.stroke() } /** Code for animating the color on arc as well as the thumb slider - parameter loaderValue: the value passed to the animation code. Must be between 0 to 1 */ private func animateArc(loaderValue: CGFloat) { let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let radius: CGFloat = max(bounds.width - arcMargin, bounds.height - arcMargin) let rotationDiff = 360 - abs((arcStartAngle - arcEndAngle)) let startAngle: CGFloat = arcStartAngle.degreesToRadians let endAngle: CGFloat = ((((loaderValue * 100) * abs(rotationDiff)) / 100) + arcStartAngle).degreesToRadians let thumbPath = UIBezierPath( arcCenter: center, radius: radius / 2 - backGroundArcWidth / 2, // changed here startAngle: startAngle, endAngle: endAngle, clockwise: true) if isthumbImageAvailable && loaderValue != 0 { thumbImageView.image = thumbImage! thumbLayer.contents = thumbImageView.image?.cgImage thumbLayer.anchorPoint = CGPoint(x: 0.5, y: 0.5) thumbLayer.frame = CGRect(x: 0.0, y: 0.0, width: thumbImageView.image!.size.width, height: thumbImageView.image!.size.height) thumbLayer.transform = CATransform3DMakeAffineTransform(CGAffineTransform(rotationAngle: CGFloat(M_PI_2))) ringLayer.addSublayer(thumbLayer) let pathAnimation: CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") pathAnimation.duration = 2 pathAnimation.path = thumbPath.cgPath; pathAnimation.repeatCount = 0 pathAnimation.calculationMode = kCAAnimationPaced pathAnimation.rotationMode = kCAAnimationRotateAuto pathAnimation.fillMode = kCAFillModeForwards pathAnimation.isRemovedOnCompletion = false thumbLayer.add(pathAnimation, forKey: "movingMeterTip") //need to refactor } let animation = CABasicAnimation(keyPath: "strokeEnd") animation.delegate = self animation.duration = 2 animation.fromValue = 0 animation.toValue = loaderValue // changed here animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) ringLayer.strokeEnd = loaderValue ringLayer.add(animation, forKey: "animateArc") } func drawCenterImage() { let center = CGPoint(x: bounds.width / 2, y: bounds.height / 2) let radius: CGFloat = max(bounds.width - arcMargin, bounds.height - arcMargin) let imgViewWidth = image!.size.width > radius ? radius : image!.size.width let imgViewHeight = image!.size.height > radius ? radius : image!.size.height let resizedImg = resizeImage(image: image!, targetSize: CGSize(width: imgViewWidth, height: imgViewHeight)) imgView.frame = CGRect(x: 0, y: 0, width: resizedImg.size.width, height: resizedImg.size.height) imgView.center = center imgView.image = resizedImg imgView.contentMode = .scaleAspectFit self.addSubview(imgView) } func drawText(rectSize: CGSize) { let textStyle = NSMutableParagraphStyle() textStyle.alignment = .left let valueFontAttributes = [NSFontAttributeName: UIFont(name: self.valueFontName, size: self.valueFontSize == -1 ? rectSize.height/5 : self.valueFontSize)!, NSForegroundColorAttributeName: self.fontColor, NSParagraphStyleAttributeName: textStyle] as [String : Any] let text = NSMutableAttributedString() let value = self.animateScale * self.valueMultiplier if showUnit { let unitAttributes = [NSFontAttributeName: UIFont(name: self.unitFontName, size: self.unitFontSize == -1 ? rectSize.height/7 : self.unitFontSize)!, NSForegroundColorAttributeName: self.fontColor, NSParagraphStyleAttributeName: textStyle] as [String : Any] let unit = NSAttributedString(string: self.UnitString, attributes: unitAttributes) text.append(unit) } let valueSize = ("\(Int(value))" as NSString).size(attributes: valueFontAttributes) let unitSize = text.size() let centerWidth = valueSize.width let centerHeight = valueSize.height let textLabel = UILabel() textLabel.frame.size = CGSize(width: valueSize.width, height: valueSize.height) textLabel.center = CGPoint(x: (bounds.width/2) - (centerWidth / 2), y: (bounds.height/2) - (centerHeight / 2)) textLabel.font = UIFont(name: self.valueFontName, size: self.valueFontSize == -1 ? rectSize.height/5 : self.valueFontSize) textLabel.text = "\(Int(value)) " textLabel.textColor = self.fontColor self.addSubview(textLabel) let duration: Double = 2.0 //seconds DispatchQueue.global().async { for i in 0 ..< (Int(value) + 1) { let sleepTime = UInt32(duration/Double(value) * 280000.0) usleep(sleepTime) DispatchQueue.main.async { textLabel.text = "\(i)" } } } // unit string draw rect let unitRect = CGRect(x: textLabel.frame.origin.x + textLabel.frame.size.width + 5, y: textLabel.frame.origin.y + (textLabel.frame.size.height - unitSize.height - 3), width: unitSize.width, height: unitSize.height) text.draw(in: unitRect) } func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { let size = image.size let widthRatio = targetSize.width / image.size.width let heightRatio = targetSize.height / image.size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } } extension KXThumbCircularProgressBar: CAAnimationDelegate { public func animationDidStart(_ anim: CAAnimation) { self.delegate?.arcAnimationDidStart?() } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { self.delegate?.arcAnimationDidStop?() } }
mit
c7c8356fefbb2093e938fca7d206dd90
40.192727
271
0.645392
4.940253
false
false
false
false
mathcamp/swiftz
swiftz/Future.swift
2
1482
// // Future.swift // swiftz // // Created by Maxwell Swadling on 4/06/2014. // Copyright (c) 2014 Maxwell Swadling. All rights reserved. // import Foundation import swiftz_core public class Future<A> { var value: A? // The resultQueue is used to read the result. It begins suspended // and is resumed once a result exists. // FIXME: Would like to add a uniqueid to the label let resultQueue = dispatch_queue_create("swift.future", DISPATCH_QUEUE_CONCURRENT) let execCtx: ExecutionContext // for map public init(exec: ExecutionContext) { dispatch_suspend(self.resultQueue) execCtx = exec } public init(exec: ExecutionContext, _ a: () -> A) { dispatch_suspend(self.resultQueue) execCtx = exec exec.submit(self, work: a) } public init(exec: ExecutionContext, _ a: @autoclosure () -> A) { dispatch_suspend(self.resultQueue) execCtx = exec exec.submit(self, work: a) } internal func sig(x: A) { assert(self.value == nil, "Future cannot complete more than once") self.value = x dispatch_resume(self.resultQueue) } public func result() -> A { var result : A? = nil dispatch_sync(resultQueue, { result = self.value! }) return result! } public func map<B>(f: A -> B) -> Future<B> { return Future<B>(exec: execCtx, { f(self.result()) }) } public func flatMap<B>(f: A -> Future<B>) -> Future<B> { return Future<B>(exec: execCtx, { f(self.result()).result() }) } }
bsd-3-clause
1909d5d8dd68d75cdbfff236a2fc2409
24.118644
84
0.647099
3.545455
false
false
false
false
byu-oit-appdev/ios-byuSuite
byuSuite/Apps/TestingCenter/model/TestingCenterClient.swift
1
1765
// // TestingCenterClient.swift // byuSuite // // Created by Erik Brady on 7/31/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let TESTS_BASE_URL = "https://api.byu.edu/domains/testingcenter/studenttest/v1/" private let HOURS_BASE_URL = "https://api.byu.edu/domains/testingcenter/location/v1/3RcOkcOJLCUq/controlHours/Floor" class TestingCenterClient: ByuClient2 { static func findAllTestInfo(yearTerm: String?, callback: @escaping (TestingCenterStudentTestsContent?, ByuError?) -> Void) { //If they don't pass in a year term, return the default response without the year term suffix let request = ByuRequest2(url: super.url(base: TESTS_BASE_URL, queryParams: yearTerm == nil ? nil : ["yearTerm": yearTerm!])) ByuRequestManager.instance.makeRequest(request) { (response) in if response.succeeded, let responseDict = response.getDataJson() as? [String: Any], let dict = responseDict["content"] as? [String: Any] { do { callback(try TestingCenterStudentTestsContent(dict: dict), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func findHours(callback: @escaping (TestingCenterHours?, ByuError?) -> Void) { let request = ByuRequest2(url: super.url(base: HOURS_BASE_URL)) ByuRequestManager.instance.makeRequest(request) { (response) in if response.succeeded, let dict = response.getDataJson() as? [String: Any] { callback(TestingCenterHours(dict: dict), nil) } else { callback(nil, response.error) } } } }
apache-2.0
50eab5a6b6a7c451ae9a70f92aef71ae
40.023256
133
0.642857
3.911308
false
true
false
false
jamalping/XPUtil
XPUtil/Tool/KVO.swift
1
1683
// // KVO.swift // XPUtilExample // // Created by jamalping on 2018/7/24. // Copyright © 2018年 xyj. All rights reserved. // import Foundation // MARK: KVO:实现了KVO的观察者的自动释放 public class KVO: NSObject { var target: AnyObject? var selector: Selector? var observedObject: NSObject? var keyPath: String? /// 建立观察者与被观察者之间的联系 /// /// - Parameters: /// - object: 观察者 /// - keyPath: 观察目标 /// - target: 被观察对象 /// - selector: 响应 /// - Returns: <#return value description#> @discardableResult public class func observer(object: NSObject, keyPath: String, target: AnyObject, selector: Selector) -> KVO { return KVO.init(object: object, keyPath: keyPath, target: target, selector: selector) } init(object: NSObject, keyPath: String, target: AnyObject, selector: Selector) { super.init() self.target = target self.selector = selector self.observedObject = object self.keyPath = keyPath object.addObserver(self, forKeyPath: keyPath, options: .new, context: nil) } override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let ok = self.target?.responds(to: self.selector), ok == true { _ = self.target?.perform(self.selector) } } deinit { guard let keyPath = self.keyPath else { return } self.observedObject?.removeObserver(self, forKeyPath: keyPath) } }
mit
8618ceb0f951648750f135bd54635a76
28.018182
158
0.614662
4.102828
false
false
false
false
maximveksler/Developing-iOS-8-Apps-with-Swift
lesson-014/Trax MapKit/Trax/GPXViewController.swift
2
4386
// // GPXViewController.swift // Trax // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import UIKit import MapKit class GPXViewController: UIViewController, MKMapViewDelegate { // MARK: - Outlets @IBOutlet weak var mapView: MKMapView! { didSet { mapView.mapType = .Satellite mapView.delegate = self } } // MARK: - Public API var gpxURL: NSURL? { didSet { clearWaypoints() if let url = gpxURL { GPX.parse(url) { if let gpx = $0 { self.handleWaypoints(gpx.waypoints) } } } } } // MARK: - Waypoints private func clearWaypoints() { if mapView?.annotations != nil { mapView.removeAnnotations(mapView.annotations as [MKAnnotation]) } } private func handleWaypoints(waypoints: [GPX.Waypoint]) { mapView.addAnnotations(waypoints) mapView.showAnnotations(waypoints, animated: true) } // MARK: - MKMapViewDelegate func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier) if view == nil { view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier) view.canShowCallout = true } else { view.annotation = annotation } view.leftCalloutAccessoryView = nil view.rightCalloutAccessoryView = nil if let waypoint = annotation as? GPX.Waypoint { if waypoint.thumbnailURL != nil { view.leftCalloutAccessoryView = UIImageView(frame: Constants.LeftCalloutFrame) } if waypoint.imageURL != nil { view.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as UIButton } } return view } func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) { if let waypoint = view.annotation as? GPX.Waypoint { if let thumbnailImageView = view.leftCalloutAccessoryView as? UIImageView { if let imageData = NSData(contentsOfURL: waypoint.thumbnailURL!) { // blocks main thread! if let image = UIImage(data: imageData) { thumbnailImageView.image = image } } } } } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { performSegueWithIdentifier(Constants.ShowImageSegue, sender: view) } // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == Constants.ShowImageSegue { if let waypoint = (sender as? MKAnnotationView)?.annotation as? GPX.Waypoint { if let ivc = segue.destinationViewController as? ImageViewController { ivc.imageURL = waypoint.imageURL ivc.title = waypoint.name } } } } // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() // sign up to hear about GPX files arriving let center = NSNotificationCenter.defaultCenter() let queue = NSOperationQueue.mainQueue() let appDelegate = UIApplication.sharedApplication().delegate center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue) { notification in if let url = notification?.userInfo?[GPXURL.Key] as? NSURL { self.gpxURL = url } } // gpxURL = NSURL(string: "http://cs193p.stanford.edu/Vacation.gpx") // for demo/debug/testing } // MARK: - Constants private struct Constants { static let LeftCalloutFrame = CGRect(x: 0, y: 0, width: 59, height: 59) static let AnnotationViewReuseIdentifier = "waypoint" static let ShowImageSegue = "Show Image" } }
apache-2.0
624852841c2b1c60541338627ffddca8
32.227273
130
0.599407
5.530895
false
false
false
false
yangchenghu/actor-platform
actor-apps/app-ios/ActorApp/AACollectionViewController.swift
3
1503
// // AACollectionViewController.swift // ActorApp // // Created by Steve Kite on 24.09.15. // Copyright © 2015 Actor LLC. All rights reserved. // import Foundation class AACollectionViewController: AAViewController, UICollectionViewDelegate, UICollectionViewDataSource { var collectionView:UICollectionView! init(collectionLayout: UICollectionViewLayout) { super.init() collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: collectionLayout) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { super.loadView() collectionView.delegate = self collectionView.dataSource = self view.addSubview(collectionView) navigationItem.backBarButtonItem = UIBarButtonItem(title: NSLocalizedString("NavigationBack",comment:"Back button"), style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() collectionView.frame = view.bounds; } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { fatalError("Not implemented!") } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { fatalError("Not implemented!") } }
mit
1108b6cc4edf1e469c518a1616c0d0cd
30.3125
185
0.696405
5.867188
false
false
false
false
maximkhatskevich/MKHSequence
Setup.playground/Contents.swift
2
6589
import Cocoa import RepoConfig import Mustache import XCEProjectGenerator // MARK: - Global parameters let swiftVersion = "4.0" let tstSuffix = "Tst" let company = ( name: "XCEssentials", identifier: "io.XCEssentials", prefix: "XCE" ) let product = ( name: "OperationFlow", summary: "Lightweight async serial operation flow controller.", type: Template.XCE.InfoPlist.Options.TargetType.framework ) let moduleName = company.prefix + product.name let podspecPath = moduleName + ".podspec" let projectName = product.name let licenseType = "MIT" // open-source let author = ( name: "Maxim Khatskevich", email: "[email protected]" ) let depTargets = [ Template.XCE .CocoaPods .Podfile .Options .DeploymentTarget .with( name: .iOS, minimumVersion: "8.0" ), Template.XCE .CocoaPods .Podfile .Options .DeploymentTarget .with( name: .watchOS, minimumVersion: "2.0" ), Template.XCE .CocoaPods .Podfile .Options .DeploymentTarget .with( name: .tvOS, minimumVersion: "9.0" ), Template.XCE .CocoaPods .Podfile .Options .DeploymentTarget .with( name: .macOS, minimumVersion: "10.9" ) ] let targetName = ( main: product.name, tst: product.name + tstSuffix ) let targetType = ( main: product.type, tst: Template.XCE.InfoPlist.Options.TargetType.tests ) let targetInfo = ( main: "Info/" + targetName.main + ".plist", tst: "Info/" + targetName.tst + ".plist" ) let bundleId = ( main: company.identifier + "." + product.name, tst: company.identifier + "." + product.name + ".Tst" ) let sourcesPath = ( main: "Sources/" + targetName.main, tst: "Sources/" + targetName.tst ) let structConfigPath = "project.yml" let repo = ( name: product.name, location: PathPrefix .iCloudDrive .appendingPathComponent("Dev/XCEssentials") .appendingPathComponent(product.name) ) // MARK: - Actually write repo configuration files try! Template.XCE.Gitignore .prepare() .render(.cocoaFramework) .write(at: repo.location) try! Template.XCE.SwiftLint .prepare() .render(.recommended) .write(at: repo.location) try! Template.XCE.Fastlane.Fastfile .prepare() .render(.combined( .framework( projectName: projectName ), usesCocoapods: true ) ) .write(at: repo.location) try! Template.XCE.InfoPlist .prepare() .render(.with(targetType: targetType.main)) .write(to: targetInfo.main, at: repo.location) try! Template.XCE.InfoPlist .prepare() .render(.with(targetType: targetType.tst)) .write(to: targetInfo.tst, at: repo.location) try! Template.XCE.License.MIT .prepare() .render(.with(copyrightEntity: author.name)) .write(at: repo.location) try! Template.XCE.CocoaPods.Podspec .prepare() .render(.with( company: .with( name: company.name, prefix: company.prefix ), product: .with( name: product.name, summary: product.summary ), license: .with( type: licenseType ), author: .with( name: author.name, email: author.email ), deploymentTargets: Set(depTargets.map{ $0.name }), sourcesPath: sourcesPath.main, subspecs: false ) ) .write(to: podspecPath, at: repo.location) try! Template.XCE.CocoaPods.Podfile .prepare() .render(.with( workspaceName: product.name, globalEntries: [ "use_frameworks!" ], sharedEntries: [ "podspec" ], targets: [ .target( named: targetName.main, projectName: projectName, deploymentTarget: depTargets[0], entries: [] ), .target( named: targetName.tst, projectName: projectName, deploymentTarget: depTargets[0], entries: [ "pod 'XCETesting', '~> 1.2'" ] ) ] ) ) .write(at: repo.location) //=== let specFormat = Spec.Format.v2_1_0 let project = Project(projectName) { project in project.configurations.all.override( "IPHONEOS_DEPLOYMENT_TARGET" <<< depTargets[0].minimumVersion, "SWIFT_VERSION" <<< swiftVersion, "VERSIONING_SYSTEM" <<< "apple-generic" ) project.configurations.debug.override( "SWIFT_OPTIMIZATION_LEVEL" <<< "-Onone" ) //--- project.target(targetName.main, .iOS, .framework) { fwk in fwk.include(sourcesPath.main) //--- fwk.configurations.all.override( "IPHONEOS_DEPLOYMENT_TARGET" <<< depTargets[0].minimumVersion, "PRODUCT_BUNDLE_IDENTIFIER" <<< bundleId.main, "INFOPLIST_FILE" <<< targetInfo.main, //--- iOS related: "SDKROOT" <<< "iphoneos", "TARGETED_DEVICE_FAMILY" <<< DeviceFamily.iOS.universal, //--- Framework related: "PRODUCT_NAME" <<< moduleName, "DEFINES_MODULE" <<< "NO", "SKIP_INSTALL" <<< "YES" ) fwk.configurations.debug.override( "MTL_ENABLE_DEBUG_INFO" <<< true ) //--- fwk.unitTests(targetName.tst) { fwkTests in fwkTests.include(sourcesPath.tst) //--- fwkTests.configurations.all.override( // very important for unit tests, // prevents the error when unit test do not start at all "LD_RUNPATH_SEARCH_PATHS" <<< "$(inherited) @executable_path/Frameworks @loader_path/Frameworks", "IPHONEOS_DEPLOYMENT_TARGET" <<< depTargets[0].minimumVersion, "PRODUCT_BUNDLE_IDENTIFIER" <<< bundleId.tst, "INFOPLIST_FILE" <<< targetInfo.tst, "FRAMEWORK_SEARCH_PATHS" <<< "$(inherited) $(BUILT_PRODUCTS_DIR)" ) fwkTests.configurations.debug.override( "MTL_ENABLE_DEBUG_INFO" <<< true ) } } } //=== try! Manager .prepareSpec(specFormat, for: project) .write(to: structConfigPath, at: repo.location)
mit
baf869685950526c3e9b457d28ba011f
21.799308
83
0.556837
4.025046
false
false
false
false
einsteinx2/iSub
Classes/Data Model/ContentTypeRepository.swift
1
1860
// // ContentTypeRepository.swift // iSub Beta // // Created by Benjamin Baron on 11/19/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation struct ContentTypeRepository { static let si = ContentTypeRepository() func contentType(contentTypeId: Int64) -> ContentType? { var contentType: ContentType? = nil Database.si.read.inDatabase { db in let query = "SELECT * FROM contentTypes WHERE contentTypeId = ?" do { let result = try db.executeQuery(query, contentTypeId) if result.next() { contentType = ContentType(result: result) } result.close() } catch { printError(error) } } return contentType } func contentType(mimeType: String) -> ContentType? { var contentType: ContentType? = nil Database.si.read.inDatabase { db in let query = "SELECT * FROM contentTypes WHERE mimeType = ?" do { let result = try db.executeQuery(query, mimeType) if result.next() { contentType = ContentType(result: result) } result.close() } catch { printError(error) } } return contentType } } extension ContentType { convenience init(result: FMResultSet) { let contentTypeId = result.longLongInt(forColumnIndex: 0) let mimeType = result.string(forColumnIndex: 1) ?? "" let fileExtension = result.string(forColumnIndex: 2) ?? "" let basicTypeId = result.longLongInt(forColumnIndex: 3) self.init(contentTypeId: contentTypeId, mimeType: mimeType, fileExtension: fileExtension, basicTypeId: basicTypeId) } }
gpl-3.0
28c6eb75073f94eea152107f80f8c004
31.051724
123
0.572351
5.079235
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/Extensions/ObjecttoDict.swift
1
1952
// // ObjecttoDict.swift // DemoSocketIO // // Created by Loc.dx-KeizuDev on 11/16/16. // Copyright © 2016 Loc Dinh Xuan. All rights reserved. // import Foundation @objc protocol Serializable { var jsonProperties:Array<String> { get } func valueForKey(key: String!) -> AnyObject! } struct Serialize { static func toDictionary(obj:Serializable) -> NSDictionary { // make dictionary var dict = Dictionary<String, Any>() // add values for prop in obj.jsonProperties { let val:AnyObject! = obj.valueForKey(key: prop) if (val is String) { dict[prop] = val as! String } else if (val is Int) { dict[prop] = val as! Int } else if (val is Double) { dict[prop] = val as! Double } else if (val is Array<String>) { dict[prop] = val as! Array<String> } else if (val is Serializable) { dict[prop] = toJSON(obj: val as! Serializable) } else if (val is Array<Serializable>) { var arr = Array<NSDictionary>() for item in (val as! Array<Serializable>) { arr.append(toDictionary(obj: item)) } dict[prop] = arr } } // return dict return dict as NSDictionary } static func toJSON(obj:Serializable) -> String { // get dict let dict = toDictionary(obj: obj) // make JSON let data = try! JSONSerialization.data(withJSONObject: dict, options:[]) // return result return NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String } }
gpl-3.0
e0bc0dfd8a0c069ee6b4b90e97064229
25.726027
87
0.483854
4.758537
false
false
false
false
Sage-Bionetworks/BridgeAppSDK
BridgeAppSDKSample/ActivityTableViewCell.swift
1
2725
// // ActivityTableViewCell.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import BridgeAppSDK class ActivityTableViewCell: SBAActivityTableViewCell { @IBOutlet weak var uncheckedView: UIView! @IBOutlet weak var checkmarkView: UIImageView! override var complete: Bool { didSet { self.checkmarkView.isHidden = !complete self.uncheckedView.isHidden = complete } } override func layoutSubviews() { super.layoutSubviews() // hardcode the corner radius b/c for some reason the bounds // are not correct after laying out subviews self.uncheckedView.layer.borderColor = UIColor.lightGray.cgColor self.uncheckedView.layer.borderWidth = 1 self.uncheckedView.layer.cornerRadius = 14 updateTintColors() } override func tintColorDidChange() { super.tintColorDidChange() updateTintColors() } func updateTintColors() { self.timeLabel?.textColor = self.tintColor } }
bsd-3-clause
ab2295690291ff84117702c7b64e16cb
37.914286
84
0.725404
5.016575
false
false
false
false
NUKisZ/MyTools
MyTools/MyTools/Class/FirstVC/Controllers/PingViewController.swift
1
2780
// // PingViewController.swift // MyTools // // Created by gongrong on 2017/8/7. // Copyright © 2017年 zhangk. All rights reserved. // import UIKit class PingViewController: BaseViewController { var textFile:UITextField! var pingLabel:UILabel! var pingHost:UILabel! var btn:UIButton! var server:PPSPingServices! var isPing:Bool = true override func viewDidLoad() { super.viewDidLoad() textFile = UITextField(frame: CGRect(x: 20, y: 64, width: 200, height: 30)) textFile.text = "www.baidu.com" textFile.placeholder = "www.baidu.com" textFile.backgroundColor = UIColor.gray textFile.layer.cornerRadius = 5 textFile.layer.masksToBounds = true view.addSubview(textFile) btn = ZKTools.createButton(CGRect(x: 240, y: 64, w: 80, h: 30), title: "ping", imageName: nil, bgImageName: nil, target: self, action: #selector(pingClick)) view.addSubview(btn) pingLabel = UILabel(frame: CGRect(x: 20, y: 100, w: 200, h: 20)) pingLabel.backgroundColor = UIColor.cyan pingLabel.textAlignment = .center view.addSubview(pingLabel) pingHost = UILabel(frame: CGRect(x: 20, y: 130, w: 200, h: 20)) pingHost.backgroundColor = UIColor.cyan pingHost.textAlignment = .center view.addSubview(pingHost) // Do any additional setup after loading the view. } func pingClick(){ if(isPing){ isPing = false btn.setTitle("cancel", for: .normal) server = PPSPingServices.service(withAddress: textFile.text) server?.start(callbackHandler: { [weak self] (summary, dict) in if let summ = summary{ DispatchQueue.main.async { self?.pingLabel.text = "Ping:\(Int(summ.rtt))ms" if let host = summ.host{ self?.pingHost.text = "Host:\(host)" } } } }) }else{ isPing = true btn.setTitle("ping", for: .normal) server.cancel() } } 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
b05aa9ac275dde760904e26a0545bae4
31.290698
164
0.576161
4.429027
false
false
false
false
keepcalmandcodecodecode/SweetSpinners
Pod/Classes/TwoCirclesSpinner.swift
1
2467
// // TwoCirclesSpinner.swift // Pods // // Created by macmini1 on 28.01.16. // // import Foundation import UIKit class TwoCirclesSpinner:UIView,Spinner{ var smallCircle:CircleView var largeCircle:CircleView func upscaleAnimation()->CABasicAnimation{ let animation = CABasicAnimation() animation.keyPath = "transform.scale" animation.fromValue = 0 animation.toValue = 0.35 animation.duration = 1.0 animation.repeatCount = .infinity animation.removedOnCompletion = false animation.fillMode = kCAFillModeForwards animation.autoreverses = true animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) return animation } func downscaleAnimation()->CABasicAnimation{ let animation = CABasicAnimation() animation.keyPath = "transform.scale" animation.fromValue = 1.0 animation.toValue = 0.35 animation.duration = 1.0 animation.repeatCount = .infinity animation.removedOnCompletion = false animation.autoreverses = true animation.fillMode = kCAFillModeForwards animation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear) return animation } func animate(){ largeCircle.layer.addAnimation(self.downscaleAnimation(), forKey: "downscaleAnimation") smallCircle.layer.addAnimation(self.upscaleAnimation(), forKey: "upscaleAnimation") } override init(frame: CGRect) { largeCircle = CircleView().useFillColor(UIColor.grayColor()).useBackgroundColor(UIColor.clearColor()) smallCircle = CircleView().useFillColor(UIColor.lightGrayColor()).useBackgroundColor(UIColor.clearColor()) super.init(frame:frame) self.backgroundColor = UIColor.clearColor() self.addSubview(largeCircle) self.addSubview(smallCircle) } required init?(coder aDecoder: NSCoder) { largeCircle = CircleView() smallCircle = CircleView() super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() smallCircle.frame = CGRectMake(0, 0, self.width, self.height) smallCircle.center = CGPoint(x:self.width/2.0,y:self.height/2.0) largeCircle.frame = CGRectMake(0, 0, self.width, self.height) largeCircle.center = CGPoint(x:self.width/2.0,y:self.height/2.0) } }
mit
77b9850d69d5046fa36af8dc51b3fec7
36.393939
114
0.684637
4.790291
false
false
false
false
PiasMasumKhan/Swift
SocialFrameworkTwitter/SocialFrameworkTwitter/FirstViewController.swift
32
5574
// // FirstViewController.swift // // Created by Carlos Butron on 11/11/14. // Copyright (c) 2014 Carlos Butron. // // This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public // License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later // version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. // You should have received a copy of the GNU General Public License along with this program. If not, see // http:/www.gnu.org/licenses/. // import UIKit import Accounts import QuartzCore import Social import CoreGraphics import Foundation class FirstViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var imageViewPhoto: UIImageView! @IBOutlet weak var labelUserName: UITextField! @IBOutlet weak var labelFollowers: UILabel! @IBOutlet weak var labelFollowing: UILabel! @IBOutlet weak var textViewDescription: UITextView! @IBAction func update(sender: UIButton) { if(labelUserName.text != ""){ checkUser() //method implemented after } else{ println("Introduce a name!") } } @IBAction func sendTweet(sender: UIButton) { var twitterController = SLComposeViewController(forServiceType:SLServiceTypeTwitter) var imageToTweet = UIImage(named:"image1.png") twitterController.setInitialText("Test from Xcode") twitterController.addImage(imageToTweet) var completionHandler:SLComposeViewControllerCompletionHandler = {(result) in twitterController.dismissViewControllerAnimated(true, completion: nil) switch(result) { case SLComposeViewControllerResult.Cancelled: println("Canceled") case SLComposeViewControllerResult.Done: println("User tweeted") default: println("Canceled") } } twitterController.completionHandler = completionHandler self.presentViewController(twitterController, animated: true, completion: nil) } override func viewDidLoad() { super.viewDidLoad() labelUserName.delegate = self // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func textFieldShouldReturn(textField: UITextField) -> Bool // called when 'return' key pressed. return NO to ignore. { textField.resignFirstResponder() return true; } func checkUser(){ var accountStore = ACAccountStore() var accountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: {(granted, error) in if(granted == true) { var accounts = accountStore.accountsWithAccountType(accountType) if(accounts.count>0){ var twitterAccount = accounts[0] as! ACAccount var twitterInfoRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: NSURL(string: "https://api.twitter.com/1.1/users/show.json"), parameters: NSDictionary(object: self.labelUserName.text, forKey: "screen_name") as [NSObject : AnyObject]) twitterInfoRequest.account = twitterAccount twitterInfoRequest.performRequestWithHandler({(responseData,urlResponse,error) in dispatch_async(dispatch_get_main_queue(), {() in //check access if(urlResponse.statusCode == 429){ println("Rate limit reached") return } //check error if((error) != nil){ println("Error \(error.localizedDescription)") } if(responseData != nil){ //if dta received TO DO var error: NSError? var TWData = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: &error) as! NSDictionary //getting data var followers = TWData.objectForKey("followers_count")!.integerValue var following = TWData.objectForKey("friends_count")!.integerValue! var description = TWData.objectForKey("description") as! NSString self.labelFollowers.text = "\(followers)" self.labelFollowing.text = "\(following)" self.textViewDescription.text = description as String var profileImageStringURL = TWData.objectForKey("profile_image_url_https") as! NSString profileImageStringURL = profileImageStringURL.stringByReplacingOccurrencesOfString("_normal", withString: "") var url = NSURL(string: profileImageStringURL as String) var data = NSData(contentsOfURL: url!) self.imageViewPhoto.image = UIImage(data: data!) } }) }) } } else { println("No access granted") } }) } }
gpl-3.0
624be876078202fdfb41a5754fb1101f
42.209302
299
0.643703
5.464706
false
false
false
false
ravisun66/Shirtist
iPhone_app_v1/Shirtist/Shirtist/AppDelegate.swift
1
6929
// // AppDelegate.swift // Shirtist // // Created by Ravi Shankar Jha on 06/12/15. // Copyright © 2015 Ravi Shankar Jha. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // let items = {1: {name: "Formal Shirt", images: ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"], price: 50.50, size: [1,2,3,5,6,9]}} // // // let Products: [String: AnyObject] = [ // "product_id": 1, // "product_name": 1, // "product_images": ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"], // "product_sizes": ["S","L", "XXL"], // "product_quantity": 8, // "product_styles": ["abc", "xyz", "mno", "mnq"], // "custom": savedData // ] let products = ["Formal Shirt": ["1.jpeg","2.jpeg","3.jpeg","4.jpeg"], "Party Shirt": ["5.jpeg","19.png","7.jpeg","8.jpeg"], "Night Wear": ["9.jpeg","10.jpeg","11.jpeg","12.jpeg"], "Club Wear": ["13.jpeg","14.jpeg","15.jpeg","16.jpeg"], "Holiday Wear": ["17.jpeg","18.jpeg","21.jpeg","22.jpeg"]] func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "Nishayu-Labs.Shirtist" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Shirtist", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
905e7dade9e535a11851cdc8b2e67364
51.885496
291
0.690676
5.1586
false
false
false
false
TruckMuncher/TruckMuncher-iOS
TruckMuncher/MenuViewController.swift
1
7380
// // MenuViewController.swift // TruckMuncher // // Created by Josh Ault on 10/19/14. // Copyright (c) 2014 TruckMuncher. All rights reserved. // import UIKit import Alamofire import Realm class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tblMenu: UITableView! @IBOutlet weak var lblNoItems: UILabel! var selectedCells = [NSIndexPath]() var menu: RMenu var truck: RTruck let menuManager = MenuManager() var textColor = UIColor.blackColor() init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?, truck: RTruck) { self.truck = truck menu = RMenu.objectsWhere("truckId = %@", truck.id).firstObject() as? RMenu ?? RMenu() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { self.truck = aDecoder.decodeObjectForKey("mvcTruck") as! RTruck self.menu = aDecoder.decodeObjectForKey("mvcMenu") as! RMenu super.init(coder: aDecoder) } override func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(truck, forKey: "mvcTruck") aCoder.encodeObject(menu, forKey: "mvcMenu") } override func viewDidLoad() { super.viewDidLoad() if menu.categories.count > 0 { lblNoItems.removeFromSuperview() } // http://stackoverflow.com/questions/19456288/text-color-based-on-background-image let primary = UIColor(rgba: truck.primaryColor) textColor = primary.suggestedTextColor() view.backgroundColor = primary lblNoItems.textColor = textColor view.frame = UIScreen.mainScreen().bounds navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editTable") tblMenu.registerNib(UINib(nibName: "MenuItemTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MenuItemTableViewCellIdentifier") tblMenu.estimatedRowHeight = 99.0 tblMenu.rowHeight = UITableViewAutomaticDimension tblMenu.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func sendDiffs(diffs: [String: Bool]) { menuManager.modifyMenuItemAvailability(items: diffs, success: { () -> () in println("successfully updated diffs") self.menu = RMenu.objectsWhere("truckId = %@", self.truck.id).firstObject() as! RMenu }) { (error) -> () in println("error updating diffs") } } func doneEditingTable() { var diffs = [String: Bool]() let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() for indexPath in selectedCells { var category = menu.categories.objectAtIndex(UInt(indexPath.section)) as! RCategory var currentItem = category.menuItems.objectAtIndex(UInt(indexPath.row)) as! RMenuItem currentItem.isAvailable = !currentItem.isAvailable diffs[currentItem.id] = currentItem.isAvailable } realm.commitWriteTransaction() CATransaction.begin() CATransaction.setCompletionBlock { () -> Void in self.tblMenu.reloadRowsAtIndexPaths(self.selectedCells, withRowAnimation: UITableViewRowAnimation.None) self.selectedCells = [NSIndexPath]() } tblMenu.beginUpdates() sendDiffs(diffs) tblMenu.setEditing(false, animated: true) tblMenu.endUpdates() CATransaction.commit() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Edit, target: self, action: "editTable") } func editTable() { tblMenu.setEditing(true, animated: true) navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "doneEditingTable") } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Int(menu.categories.count) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("MenuItemTableViewCellIdentifier") as! MenuItemTableViewCell cell.givenTextColor = textColor var category = menu.categories.objectAtIndex(UInt(indexPath.section)) as! RCategory cell.menuItem = category.menuItems.objectAtIndex(UInt(indexPath.row)) as? RMenuItem var bgView = UIView() bgView.backgroundColor = view.backgroundColor cell.selectedBackgroundView = bgView return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Int((menu.categories.objectAtIndex(UInt(section)) as! RCategory).menuItems.count) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return (menu.categories.objectAtIndex(UInt(section)) as! RCategory).name } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return MENU_CATEGORY_HEIGHT } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var container = UIView(frame: CGRectMake(0, 0, tblMenu.frame.size.width, MENU_CATEGORY_HEIGHT)) var label = UILabel(frame: CGRectMake(0, 0, tblMenu.frame.size.width, MENU_CATEGORY_HEIGHT)) label.textAlignment = .Center label.font = UIFont.italicSystemFontOfSize(18.0) label.backgroundColor = view.backgroundColor label.textColor = textColor label.text = self.tableView(tableView, titleForHeaderInSection: section) container.addSubview(label) return container } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if !tableView.editing { tableView.deselectRowAtIndexPath(indexPath, animated: true) } else { selectedCells.append(indexPath) } } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { if tableView.editing { if let index = find(selectedCells, indexPath) { selectedCells.removeAtIndex(index) } } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return .Delete } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { selectedCells = [indexPath] doneEditingTable() } func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String! { var category = menu.categories.objectAtIndex(UInt(indexPath.section)) as! RCategory var menuItem = category.menuItems.objectAtIndex(UInt(indexPath.row)) as! RMenuItem return menuItem.isAvailable ? "Out of Stock" : "In Stock" } }
gpl-2.0
f3f0ce0fea1a170accb049d8303b2620
39.108696
158
0.675474
5.241477
false
false
false
false
benlangmuir/swift
stdlib/public/core/ObjectIdentifier.swift
9
3988
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A unique identifier for a class instance or metatype. /// /// This unique identifier is only valid for comparisons during the lifetime /// of the instance. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. @frozen // trivial-implementation public struct ObjectIdentifier: Sendable { @usableFromInline // trivial-implementation internal let _value: Builtin.RawPointer /// Creates an instance that uniquely identifies the given class instance. /// /// The following example creates an example class `IntegerRef` and compares /// instances of the class using their object identifiers and the identical-to /// operator (`===`): /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// let x = IntegerRef(10) /// let y = x /// /// print(ObjectIdentifier(x) == ObjectIdentifier(y)) /// // Prints "true" /// print(x === y) /// // Prints "true" /// /// let z = IntegerRef(10) /// print(ObjectIdentifier(x) == ObjectIdentifier(z)) /// // Prints "false" /// print(x === z) /// // Prints "false" /// /// - Parameter x: An instance of a class. @inlinable // trivial-implementation public init(_ x: AnyObject) { self._value = Builtin.bridgeToRawPointer(x) } /// Creates an instance that uniquely identifies the given metatype. /// /// - Parameter: A metatype. @inlinable // trivial-implementation public init(_ x: Any.Type) { self._value = unsafeBitCast(x, to: Builtin.RawPointer.self) } } extension ObjectIdentifier: CustomDebugStringConvertible { /// A textual representation of the identifier, suitable for debugging. public var debugDescription: String { return "ObjectIdentifier(\(_rawPointerToString(_value)))" } } extension ObjectIdentifier: Equatable { @inlinable // trivial-implementation public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value)) } } extension ObjectIdentifier: Comparable { @inlinable // trivial-implementation public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return UInt(bitPattern: lhs) < UInt(bitPattern: rhs) } } extension ObjectIdentifier: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(Int(Builtin.ptrtoint_Word(_value))) } @_alwaysEmitIntoClient // For back deployment public func _rawHashValue(seed: Int) -> Int { Int(Builtin.ptrtoint_Word(_value))._rawHashValue(seed: seed) } } extension UInt { /// Creates an integer that captures the full value of the given object /// identifier. @inlinable // trivial-implementation public init(bitPattern objectID: ObjectIdentifier) { self.init(Builtin.ptrtoint_Word(objectID._value)) } } extension Int { /// Creates an integer that captures the full value of the given object /// identifier. @inlinable // trivial-implementation public init(bitPattern objectID: ObjectIdentifier) { self.init(bitPattern: UInt(bitPattern: objectID)) } }
apache-2.0
53a349f4de9e00283fa5a2ef582ae532
31.958678
80
0.650702
4.521542
false
false
false
false
pointfreeco/swift-web
Sources/Css/Common.swift
1
1874
public protocol Other { static func other(_ other: Value) -> Self } func eq<A: Equatable>(lhsTuples xs: [(A, A)], rhsTuples ys: [(A, A)]) -> Bool { return xs.count == ys.count && zip(xs, ys).reduce(true) { accum, tuple in accum && tuple.0 == tuple.1 } } public protocol Inherit { static var inherit: Self { get } } extension Value: Inherit { public static let inherit: Value = "inherit" } public protocol None { static var none: Self { get } } extension Value: None { public static let none: Value = "none" } public protocol Normal { static var normal: Self { get } } extension Value: Normal { public static let normal: Value = "normal" } public protocol Center { static var center: Self { get } } extension Value: Center { public static let center: Value = "center" } public protocol Hidden { static var hidden: Self { get } } extension Value: Hidden { public static let hidden: Value = "hidden" } public protocol Visible { static var visible: Self { get } } extension Value: Visible { public static let visible: Value = "visible" } public protocol Baseline { static var baseline: Self { get } } extension Value: Baseline { public static let baseline: Value = "baseline" } public protocol Auto { static var auto: Self { get } } extension Value: Auto { public static let auto: Value = "auto" } public protocol All { static var all: Self { get } } extension Value: All { public static let all: Value = "all" } public protocol Initial { static var initial: Self { get } } extension Value: Initial { public static let initial: Value = "initial" } public protocol Unset { static var unset: Self { get } } extension Value: Unset { public static let unset: Value = "unset" } public let browsers = Prefixed.prefixed( [ ("-webkit-", ""), ("-moz-", ""), ("-ms-", ""), ("-o-", ""), ("", "") ] )
mit
e47cc1a08b9e57b39f4f23b7a3279c6d
18.726316
79
0.653148
3.562738
false
false
false
false
dfucci/iTunesSearch
iTunesSearch/Album.swift
1
2669
// // Album.swift // iTunesSearch // // Created by Davide Fucci on 19/10/14. // Copyright (c) 2014 Davide Fucci. All rights reserved. // import Foundation class Album { var title: String var price: String var thumbnailImageURL: String var largeImageURL: String var itemURL: String var collectionId: Int var artistURL: String init(name: String, price: String, thumbnailImageURL: String, largeImageURL: String, itemURL: String, artistURL: String, collectionId: Int) { self.title = name self.price = price self.thumbnailImageURL = thumbnailImageURL self.largeImageURL = largeImageURL self.itemURL = itemURL self.artistURL = artistURL self.collectionId = collectionId } class func albumsWithJSON(allResults: NSArray) -> [Album]{ var albums = [Album]() if allResults.count > 0 { // Sometimes iTunes returns a collection, not a track, so we check both for the 'name' for result in allResults { var name = result["trackName"] as? String if name == nil { name = result["collectionName"] as? String } // Check format of price var price = result["formattedPrice"] as? String if price == nil { price = result["collectionPrice"] as? String if price == nil { var priceFloat:Float? = result["collectionPrice"] as? Float var nf:NSNumberFormatter = NSNumberFormatter() nf.maximumFractionDigits=2 if priceFloat != nil { price = "$"+nf.stringFromNumber(priceFloat!) } } } let thumbnailURL = result["artworkUrl60"] as? String ?? "" let imageURL = result["artworkUrl100"] as? String ?? "" let artistURL = result["artistViewUrl"] as? String ?? "" var itemURL = result["collectionViewUrl"] as? String if itemURL == nil { itemURL = result["trackViewUrl"] as? String } var collectionId = result["collectionId"] as? Int var newAlbum = Album(name: name!, price: price!, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, itemURL: itemURL!, artistURL: artistURL, collectionId: collectionId!) albums.append(newAlbum) } } return albums } }
apache-2.0
941b3edc8d0219bad6207c0dc64517ec
37.695652
192
0.536531
5.2643
false
false
false
false
LGKKTeam/FlagKits
FlagKits/Classes/FKCountryPicker.swift
1
4404
// // FKCountryPicker.swift // FlagKits // // Created by Nguyen Minh on 3/29/17. // Copyright © 2017 LGKKTeam. All rights reserved. // import UIKit import libPhoneNumber_iOS protocol FKCountryPickerDelegate: class { func countryPhoneCodePicker(picker: FKFKCountryPicker, didSelectCountryCountryWithName name: String, countryCode: String, phoneCode: String) } public struct Country { var code: String? var name: String? var phoneCode: String? public init(code: String?, name: String?, phoneCode: String?) { self.code = code self.name = name self.phoneCode = phoneCode } } open class FKFKCountryPicker: UIPickerView, UIPickerViewDelegate, UIPickerViewDataSource { var countries: [Country]! weak var countryPhoneCodeDelegate: FKCountryPickerDelegate? override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { super.dataSource = self super.delegate = self countries = countryNamesByCode() } // MARK: - Country Methods open func setCountry(code: String) { var row = 0 for index in 0..<countries.count { if countries[index].code?.uppercased() == code.uppercased() { row = index break } } self.selectRow(row, inComponent: 0, animated: true) } fileprivate func countryNamesByCode() -> [Country] { var countries = [Country]() for code in NSLocale.isoCountryCodes { if let countryName = (Locale.current as NSLocale).displayName(forKey: .countryCode, value: code) { let phoneNumberUtil = NBPhoneNumberUtil.sharedInstance() if let num = phoneNumberUtil?.getCountryCode(forRegion: code) { let phoneCode: String = String(format: "+%d", num.intValue) if phoneCode != "+0" { let country = Country(code: code, name: countryName, phoneCode: phoneCode) countries.append(country) } } } } countries = countries.sorted(by: { (country1, country2) -> Bool in if let name1 = country1.name, let name2 = country2.name { return name1 < name2 } else { return false } }) return countries } // MARK: - Picker Methods public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 40 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return countries.count } public func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { var resultView: Any if view == nil { resultView = Bundle(for: FKFlagView.self).loadNibNamed("FKFlagView", owner: self)?.first as Any } else { resultView = view as Any } if let resultView = resultView as? FKFlagView { resultView.setup(country: countries[row]) return resultView } else { fatalError("FKFlagView invalid, double check pls!") } } public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let country = countries[row] if let countryPhoneCodeDelegate = countryPhoneCodeDelegate, let name = country.name, let code = country.code, let phoneCode = country.phoneCode { countryPhoneCodeDelegate.countryPhoneCodePicker( picker: self, didSelectCountryCountryWithName: name, countryCode: code, phoneCode: phoneCode ) } } }
mit
98c77f852478f90a9399308e741b34e1
30.22695
110
0.55871
5.125728
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Home/HomeViewController.swift
1
2858
// // HomeViewController.swift // LiveBroadcast // // Created by 朱双泉 on 2018/12/10. // Copyright © 2018 Castie!. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() setupUI() } } extension HomeViewController { fileprivate func setupUI() { setupNavigationBar() setupContentView() } private func setupContentView() { let homeTypes = loadTypesData() let titles = homeTypes.map({ $0.title }) var childVcs = [AnchorViewController]() for type in homeTypes { let anchorVc = AnchorViewController() anchorVc.homeType = type childVcs.append(anchorVc) } let style = TitleStyle() style.isScrollEnable = true style.isShowScrollLine = true let statusbarH = UIApplication.shared.statusBarFrame.size.height let navbarH = navigationController!.navigationBar.frame.size.height let tabbarH = tabBarController!.tabBar.frame.size.height let pageFrame = CGRect(x: 0, y: statusbarH + navbarH, width: view.bounds.width, height: view.bounds.height - statusbarH - navbarH - tabbarH) let pageView = PageView(frame: pageFrame, titles: titles, childVcs: childVcs, parentVc: self, style: style) view.addSubview(pageView) } fileprivate func loadTypesData() -> [HomeType] { let path = Bundle.main.path(forResource: "types.plist", ofType: nil)! let dataArray = NSArray(contentsOfFile: path) as! [[String : Any]] var tempArray = [HomeType]() for dict in dataArray { tempArray.append(HomeType(dict: dict)) } return tempArray } private func setupNavigationBar() { let logoImage = UIImage(named: "home-logo") navigationItem.leftBarButtonItem = UIBarButtonItem(image: logoImage, style: .plain, target: nil, action: nil) let collectImage = UIImage(named: "search_btn_follow") navigationItem.rightBarButtonItem = UIBarButtonItem(image: collectImage, style: .plain, target: self, action: #selector(collectItemClick)) let searchFrame = CGRect(x: 0, y: 0, width: 200, height: 32) let searchBar = UISearchBar(frame: searchFrame) searchBar.placeholder = "主播昵称/房间号/链接" navigationItem.titleView = searchBar searchBar.searchBarStyle = .minimal let searchFiled = searchBar.value(forKey: "_searchField") as? UITextField searchFiled?.textColor = UIColor.white navigationController?.navigationBar.barTintColor = UIColor.black } } extension HomeViewController { @objc fileprivate func collectItemClick() { print("弹出收藏控制器") } }
mit
7e59ba063962f8cfddb07159e1c1900c
33.802469
148
0.647393
4.706177
false
false
false
false
nextcloud/ios
iOSClient/Account Request/NCAccountRequest.swift
1
7818
// // NCAccountRequest.swift // Nextcloud // // Created by Marino Faggiana on 26/02/21. // Copyright © 2021 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import UIKit import NextcloudKit public protocol NCAccountRequestDelegate: AnyObject { func accountRequestAddAccount() func accountRequestChangeAccount(account: String) } // optional func public extension NCAccountRequestDelegate { func accountRequestAddAccount() {} func accountRequestChangeAccount(account: String) {} } class NCAccountRequest: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var progressView: UIProgressView! public var accounts: [tableAccount] = [] public var activeAccount: tableAccount? public let heightCell: CGFloat = 60 public var enableTimerProgress: Bool = true public var enableAddAccount: Bool = false public var dismissDidEnterBackground: Bool = false public weak var delegate: NCAccountRequestDelegate? private var timer: Timer? private var time: Float = 0 private let secondsAutoDismiss: Float = 3 // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() titleLabel.text = NSLocalizedString("_account_select_", comment: "") closeButton.setImage(NCUtility.shared.loadImage(named: "xmark", color: .label), for: .normal) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 1)) tableView.separatorStyle = UITableViewCell.SeparatorStyle.none view.backgroundColor = .secondarySystemBackground tableView.backgroundColor = .secondarySystemBackground progressView.trackTintColor = .clear progressView.progress = 1 if enableTimerProgress { progressView.isHidden = false } else { progressView.isHidden = true } NotificationCenter.default.addObserver(self, selector: #selector(startTimer), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidBecomeActive), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: NSNotification.Name(rawValue: NCGlobal.shared.notificationCenterApplicationDidEnterBackground), object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let visibleCells = tableView.visibleCells var numAccounts = accounts.count if enableAddAccount { numAccounts += 1 } if visibleCells.count == numAccounts { tableView.isScrollEnabled = false } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) timer?.invalidate() } // MARK: - Action @IBAction func actionClose(_ sender: UIButton) { dismiss(animated: true) } // MARK: - NotificationCenter @objc func applicationDidEnterBackground() { if dismissDidEnterBackground { dismiss(animated: false) } } // MARK: - Progress @objc func startTimer() { if enableTimerProgress { time = 0 timer?.invalidate() timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgress), userInfo: nil, repeats: true) progressView.isHidden = false } else { progressView.isHidden = true } } @objc func updateProgress() { time += 0.1 if time >= secondsAutoDismiss { dismiss(animated: true) } else { progressView.progress = 1 - (time / secondsAutoDismiss) } } } extension NCAccountRequest: UITableViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { timer?.invalidate() progressView.progress = 0 } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { // startTimer() } } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // startTimer() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return heightCell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == accounts.count { dismiss(animated: true) delegate?.accountRequestAddAccount() } else { let account = accounts[indexPath.row] if account.account != activeAccount?.account { dismiss(animated: true) { self.delegate?.accountRequestChangeAccount(account: account.account) } } else { dismiss(animated: true) } } } } extension NCAccountRequest: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if enableAddAccount { return accounts.count + 1 } else { return accounts.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.backgroundColor = tableView.backgroundColor let avatarImage = cell.viewWithTag(10) as? UIImageView let userLabel = cell.viewWithTag(20) as? UILabel let urlLabel = cell.viewWithTag(30) as? UILabel let activeImage = cell.viewWithTag(40) as? UIImageView userLabel?.text = "" urlLabel?.text = "" if indexPath.row == accounts.count { avatarImage?.image = NCUtility.shared.loadImage(named: "plus").image(color: .systemBlue, size: 15) avatarImage?.contentMode = .center userLabel?.text = NSLocalizedString("_add_account_", comment: "") userLabel?.textColor = .systemBlue userLabel?.font = UIFont.systemFont(ofSize: 15) } else { let account = accounts[indexPath.row] avatarImage?.image = NCUtility.shared.loadUserImage( for: account.user, displayName: account.displayName, userBaseUrl: account) if account.alias.isEmpty { userLabel?.text = account.user.uppercased() urlLabel?.text = (URL(string: account.urlBase)?.host ?? "") } else { userLabel?.text = account.alias.uppercased() } if account.active { activeImage?.image = NCUtility.shared.loadImage(named: "checkmark").image(color: .systemBlue, size: 30) } else { activeImage?.image = nil } } return cell } }
gpl-3.0
5a4b47313a514ee451faa78476a3d921
30.906122
219
0.647563
5.07268
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/ActorCoreExt.swift
1
19016
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import AVFoundation public var Actor : ACCocoaMessenger { get { return ActorSDK.sharedActor().messenger } } public extension ACCocoaMessenger { public func sendUIImage(_ image: Data, peer: ACPeer, animated:Bool) { let imageFromData = UIImage(data:image) let thumb = imageFromData!.resizeSquare(90, maxH: 90); let resized = imageFromData!.resizeOptimize(1200 * 1200); let thumbData = UIImageJPEGRepresentation(thumb, 0.55); let fastThumb = ACFastThumb(int: jint(thumb.size.width), with: jint(thumb.size.height), with: thumbData!.toJavaBytes()) let descriptor = "/tmp/"+UUID().uuidString let path = CocoaFiles.pathFromDescriptor(descriptor); animated ? ((try? image.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil) : ((try? UIImageJPEGRepresentation(resized, 0.80)!.write(to: URL(fileURLWithPath: path), options: [.atomic])) != nil) animated ? sendAnimation(with: peer, withName: "image.gif", withW: jint(resized.size.width), withH:jint(resized.size.height), with: fastThumb, withDescriptor: descriptor) : sendPhoto(with: peer, withName: "image.jpg", withW: jint(resized.size.width), withH: jint(resized.size.height), with: fastThumb, withDescriptor: descriptor) } public func sendVideo(_ url: URL, peer: ACPeer) { if let videoData = try? Data(contentsOf: url) { // if data have on this local path url go to upload let descriptor = "/tmp/"+UUID().uuidString + ".mp4" let path = CocoaFiles.pathFromDescriptor(descriptor); try? videoData.write(to: URL(fileURLWithPath: path), options: [.atomic]) // write to file // get video duration let assetforduration = AVURLAsset(url: url) let videoDuration = assetforduration.duration let videoDurationSeconds = CMTimeGetSeconds(videoDuration) // get thubnail and upload let movieAsset = AVAsset(url: url) // video asset let imageGenerator = AVAssetImageGenerator(asset: movieAsset) var thumbnailTime = movieAsset.duration thumbnailTime.value = 25 let orientation = movieAsset.videoOrientation() do { let imageRef = try imageGenerator.copyCGImage(at: thumbnailTime, actualTime: nil) let thumbnail = UIImage(cgImage: imageRef) var thumb = thumbnail.resizeSquare(90, maxH: 90); let resized = thumbnail.resizeOptimize(1200 * 1200); if (orientation.orientation.isPortrait) == true { thumb = thumb.imageRotatedByDegrees(90, flip: false) } let thumbData = UIImageJPEGRepresentation(thumb, 0.55); // thumbnail binary data let fastThumb = ACFastThumb(int: jint(resized.size.width), with: jint(resized.size.height), with: thumbData!.toJavaBytes()) print("video upload imageRef = \(imageRef)") print("video upload thumbnail = \(thumbnail)") //print("video upload thumbData = \(thumbData)") print("video upload fastThumb = \(fastThumb)") print("video upload videoDurationSeconds = \(videoDurationSeconds)") print("video upload width = \(thumbnail.size.width)") print("video upload height = \(thumbnail.size.height)") if (orientation.orientation.isPortrait == true) { self.sendVideo(with: peer, withName: "video.mp4", withW: jint(thumbnail.size.height/2), withH: jint(thumbnail.size.width/2), withDuration: jint(videoDurationSeconds), with: fastThumb, withDescriptor: descriptor) } else { self.sendVideo(with: peer, withName: "video.mp4", withW: jint(thumbnail.size.width), withH: jint(thumbnail.size.height), withDuration: jint(videoDurationSeconds), with: fastThumb, withDescriptor: descriptor) } } catch { print("can't get thumbnail image") } } } fileprivate func prepareAvatar(_ image: UIImage) -> String { let res = "/tmp/" + UUID().uuidString let avatarPath = CocoaFiles.pathFromDescriptor(res) let thumb = image.resizeSquare(800, maxH: 800); try? UIImageJPEGRepresentation(thumb, 0.8)!.write(to: URL(fileURLWithPath: avatarPath), options: [.atomic]) return res } public func changeOwnAvatar(_ image: UIImage) { changeMyAvatar(withDescriptor: prepareAvatar(image)) } public func changeGroupAvatar(_ gid: jint, image: UIImage) -> String { let fileName = prepareAvatar(image) self.changeGroupAvatar(withGid: gid, withDescriptor: fileName) return fileName } public func requestFileState(_ fileId: jlong, notDownloaded: (()->())?, onDownloading: ((_ progress: Double) -> ())?, onDownloaded: ((_ reference: String) -> ())?) { Actor.requestState(withFileId: fileId, with: AAFileCallback(notDownloaded: notDownloaded, onDownloading: onDownloading, onDownloaded: onDownloaded)) } public func requestFileState(_ fileId: jlong, onDownloaded: ((_ reference: String) -> ())?) { Actor.requestState(withFileId: fileId, with: AAFileCallback(notDownloaded: nil, onDownloading: nil, onDownloaded: onDownloaded)) } } // // Collcections // extension JavaUtilAbstractCollection : Sequence { public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } public extension JavaUtilListProtocol { public func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.size() { res.append(self.getWith(i) as! T) } return res } } public extension IOSObjectArray { public func toSwiftArray<T>() -> [T] { var res = [T]() for i in 0..<self.length() { res.append(self.object(at: UInt(i)) as! T) } return res } } public extension Data { public func toJavaBytes() -> IOSByteArray { return IOSByteArray(bytes: (self as NSData).bytes.bindMemory(to: jbyte.self, capacity: self.count), count: UInt(self.count)) } } // // Entities // public extension ACPeer { public var isGroup: Bool { get { return self.peerType.ordinal() == ACPeerType.group().ordinal() } } public var isPrivate: Bool { get { return self.peerType.ordinal() == ACPeerType.private().ordinal() } } } public extension ACMessage { public var isOut: Bool { get { return Actor.myUid() == self.senderId } } } // // Callbacks // open class AACommandCallback: NSObject, ACCommandCallback { open var resultClosure: ((_ val: Any?) -> ())?; open var errorClosure: ((_ val:JavaLangException?) -> ())?; public init<T>(result: ((_ val:T?) -> ())?, error: ((_ val:JavaLangException?) -> ())?) { super.init() self.resultClosure = { (val: Any!) -> () in (result?(val as? T))! } self.errorClosure = error } open func onResult(_ res: Any!) { resultClosure?(res) } open func onError(_ e: JavaLangException!) { errorClosure?(e) } } class AAUploadFileCallback : NSObject, ACUploadFileCallback { let notUploaded: (()->())? let onUploading: ((_ progress: Double) -> ())? let onUploadedClosure: (() -> ())? init(notUploaded: (()->())?, onUploading: ((_ progress: Double) -> ())?, onUploadedClosure: (() -> ())?) { self.onUploading = onUploading self.notUploaded = notUploaded self.onUploadedClosure = onUploadedClosure; } func onNotUploading() { self.notUploaded?() } func onUploaded() { self.onUploadedClosure?() } func onUploading(_ progress: jfloat) { self.onUploading?(Double(progress)) } } class AAFileCallback : NSObject, ACFileCallback { let notDownloaded: (()->())? let onDownloading: ((_ progress: Double) -> ())? let onDownloaded: ((_ fileName: String) -> ())? init(notDownloaded: (()->())?, onDownloading: ((_ progress: Double) -> ())?, onDownloaded: ((_ reference: String) -> ())?) { self.notDownloaded = notDownloaded; self.onDownloading = onDownloading; self.onDownloaded = onDownloaded; } init(onDownloaded: @escaping (_ reference: String) -> ()) { self.notDownloaded = nil; self.onDownloading = nil; self.onDownloaded = onDownloaded; } func onNotDownloaded() { self.notDownloaded?(); } func onDownloading(_ progress: jfloat) { self.onDownloading?(Double(progress)); } func onDownloaded(_ reference: ARFileSystemReference!) { self.onDownloaded?(reference!.getDescriptor()); } } // // Markdown // open class TextParser { open let textColor: UIColor open let linkColor: UIColor open let fontSize: CGFloat fileprivate let markdownParser = ARMarkdownParser(int: ARMarkdownParser_MODE_FULL) public init(textColor: UIColor, linkColor: UIColor, fontSize: CGFloat) { self.textColor = textColor self.linkColor = linkColor self.fontSize = fontSize } open func parse(_ text: String) -> ParsedText { let doc = markdownParser?.processDocument(with: text) if (doc?.isTrivial())! { let nAttrText = NSMutableAttributedString(string: "") for ch in text.characters { let str = String(ch) if(str.containsEmoji){ let emoji = NSMutableAttributedString(string: str) let range = NSRange(location: 0, length: emoji.length) emoji.yy_setColor(textColor, range: range) emoji.yy_setFont(UIFont.textFontOfSize(30), range: range) nAttrText.append(emoji) }else{ let noEmoji = NSMutableAttributedString(string: str) let range = NSRange(location: 0, length: noEmoji.length) noEmoji.yy_setColor(textColor, range: range) noEmoji.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) nAttrText.append(noEmoji) } } return ParsedText(attributedText: nAttrText, isTrivial: true, code: []) } var sources = [String]() let sections: [ARMDSection] = doc!.getSections().toSwiftArray() let nAttrText = NSMutableAttributedString() var isFirst = true for s in sections { if !isFirst { nAttrText.append(NSAttributedString(string: "\n")) } isFirst = false if s.getType() == ARMDSection_TYPE_CODE { let str = NSMutableAttributedString(string: AALocalized("ActionOpenCode")) let range = NSRange(location: 0, length: str.length) let highlight = YYTextHighlight() highlight.userInfo = ["url" : "source:///\(sources.count)"] str.yy_setTextHighlight(highlight, range: range) str.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) str.yy_setColor(linkColor, range: range) nAttrText.append(str) sources.append(s.getCode().getCode()) } else if s.getType() == ARMDSection_TYPE_TEXT { let child: [ARMDText] = s.getText().toSwiftArray() for c in child { nAttrText.append(buildText(c, fontSize: fontSize)) } } else { fatalError("Unsupported section type") } } return ParsedText(attributedText: nAttrText, isTrivial: false, code: sources) } fileprivate func buildText(_ text: ARMDText, fontSize: CGFloat) -> NSAttributedString { if let raw = text as? ARMDRawText { let res = NSMutableAttributedString(string: raw.getRawText()) let range = NSRange(location: 0, length: res.length) res.beginEditing() res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(textColor, range: range) res.endEditing() return res } else if let span = text as? ARMDSpan { let res = NSMutableAttributedString() res.beginEditing() // Processing child texts let child: [ARMDText] = span.getChild().toSwiftArray() for c in child { res.append(buildText(c, fontSize: fontSize)) } // Setting span elements if span.getType() == ARMDSpan_TYPE_BOLD { res.appendFont(UIFont.boldSystemFont(ofSize: fontSize)) } else if span.getType() == ARMDSpan_TYPE_ITALIC { res.appendFont(UIFont.italicSystemFont(ofSize: fontSize)) } else { fatalError("Unsupported span type") } res.endEditing() return res } else if let url = text as? ARMDUrl { // Parsing url element let nsUrl = URL(string: url.getUrl()) if nsUrl != nil { let res = NSMutableAttributedString(string: url.getTitle()) let range = NSRange(location: 0, length: res.length) let highlight = YYTextHighlight() highlight.userInfo = ["url" : url.getUrl()] res.yy_setTextHighlight(highlight, range: range) res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(linkColor, range: range) return res } else { // Unable to parse: show as text let res = NSMutableAttributedString(string: url.getTitle()) let range = NSRange(location: 0, length: res.length) res.beginEditing() res.yy_setFont(UIFont.textFontOfSize(fontSize), range: range) res.yy_setColor(textColor, range: range) res.endEditing() return res } } else { fatalError("Unsupported text type") } } } open class ParsedText { open let isTrivial: Bool open let attributedText: NSAttributedString open let code: [String] public init(attributedText: NSAttributedString, isTrivial: Bool, code: [String]) { self.attributedText = attributedText self.code = code self.isTrivial = isTrivial } } // // Promises // open class AAPromiseFunc: NSObject, ARPromiseFunc { let closure: (_ resolver: ARPromiseResolver) -> () init(closure: @escaping (_ resolver: ARPromiseResolver) -> ()){ self.closure = closure } open func exec(_ resolver: ARPromiseResolver) { closure(resolver) } } public extension ARPromise { convenience init(closure: @escaping (_ resolver: ARPromiseResolver) -> ()) { self.init(executor: AAPromiseFunc(closure: closure)) } } // // Data Binding // open class AABinder { fileprivate var bindings : [BindHolder] = [] public init() { } open func bind<T1,T2,T3>(_ valueModel1:ARValue, valueModel2:ARValue, valueModel3:ARValue, closure: @escaping (_ value1:T1?, _ value2:T2?, _ value3:T3?) -> ()) { let listener1 = BindListener { (_value1) -> () in closure(_value1 as? T1, valueModel2.get() as? T2, valueModel3.get() as? T3) }; let listener2 = BindListener { (_value2) -> () in closure(valueModel1.get() as? T1, _value2 as? T2, valueModel3.get() as? T3) }; let listener3 = BindListener { (_value3) -> () in closure(valueModel1.get() as? T1, valueModel2.get() as? T2, _value3 as? T3) }; bindings.append(BindHolder(valueModel: valueModel1, listener: listener1)) bindings.append(BindHolder(valueModel: valueModel2, listener: listener2)) bindings.append(BindHolder(valueModel: valueModel3, listener: listener3)) valueModel1.subscribe(with: listener1, notify: false) valueModel2.subscribe(with: listener2, notify: false) valueModel3.subscribe(with: listener3, notify: false) closure(valueModel1.get() as? T1, valueModel2.get() as? T2, valueModel3.get() as? T3) } open func bind<T1,T2>(_ valueModel1:ARValue, valueModel2:ARValue, closure: @escaping (_ value1:T1?, _ value2:T2?) -> ()) { let listener1 = BindListener { (_value1) -> () in closure(_value1 as? T1, valueModel2.get() as? T2) }; let listener2 = BindListener { (_value2) -> () in closure(valueModel1.get() as? T1, _value2 as? T2) }; bindings.append(BindHolder(valueModel: valueModel1, listener: listener1)) bindings.append(BindHolder(valueModel: valueModel2, listener: listener2)) valueModel1.subscribe(with: listener1, notify: false) valueModel2.subscribe(with: listener2, notify: false) closure(valueModel1.get() as? T1, valueModel2.get() as? T2) } open func bind<T>(_ value:ARValue, closure: @escaping (_ value: T?)->()) { let listener = BindListener { (value2) -> () in closure(value2 as? T) }; let holder = BindHolder(valueModel: value, listener: listener) bindings.append(holder) value.subscribe(with: listener) } open func unbindAll() { for holder in bindings { holder.valueModel.unsubscribe(with: holder.listener) } bindings.removeAll(keepingCapacity: true) } } class BindListener: NSObject, ARValueChangedListener { var closure: ((_ value: Any?)->())? init(closure: @escaping (_ value: Any?)->()) { self.closure = closure } func onChanged(_ val: Any!, withModel valueModel: ARValue!) { closure?(val) } } class BindHolder { var listener: BindListener var valueModel: ARValue init(valueModel: ARValue, listener: BindListener) { self.valueModel = valueModel self.listener = listener } }
agpl-3.0
59f265bbf7e7a71130fb7cf8e6c536b4
34.610487
337
0.579407
4.541677
false
false
false
false
jeremy-w/ImageSlicer
Image Slicer.playground/Contents.swift
1
6500
//: Playground - noun: a place where people can play //: Copyright (c) 2016 Jeremy W. Sherman. Released with NO WARRANTY. //: //: 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 Cocoa var str = "Hello, playground" enum Orientation { case Horizontally case Vertically } struct Cut { let at: CGPoint let oriented: Orientation func slice(subimage: Subimage) -> [Subimage] { let edge: CGRectEdge let amount: CGFloat switch oriented { case .Horizontally: edge = .MinYEdge amount = at.y - CGRectGetMinY(subimage.rect) case .Vertically: edge = .MinXEdge amount = at.x - CGRectGetMinX(subimage.rect) } var subrect = CGRectZero var otherSubrect = CGRectZero CGRectDivide(subimage.rect, &subrect, &otherSubrect, amount, edge) return [subrect, otherSubrect].map(Subimage.init) } } struct Subimage { let rect: CGRect func contains(point: CGPoint) -> Bool { return CGRectContainsPoint(rect, point) } } struct Mark { let around: CGPoint let name: String } struct Job { let image: NSImage var cuts: [Cut] var selections: [Mark] mutating func add(cut: Cut) { cuts.append(cut) } var subimages: [Subimage] { var subimages = [Subimage( rect: CGRect(origin: CGPointZero, size: image.size))] for cut in cuts { let at = cut.at let index = subimages.indexOf({ $0.contains(at) })! let withinSubimage = subimages[index] let children = cut.slice(withinSubimage) subimages.replaceRange(Range(start: index, end: index + 1), with: children) } return subimages } /// - returns: the file URLs created func exportSelectedSubimages(directory: NSURL, dryRun: Bool) -> [NSURL] { var created: [NSURL] = [] let subimages = self.subimages selections.forEach { selection in guard let index = subimages.indexOf({ $0.contains(selection.around) }) else { NSLog("%@", "\(#function): error: selection \(selection) not contained by any subimage!") return } let subimage = subimages[index] guard let bitmap = bitmapFor(subimage) else { return } let fileURL = directory.URLByAppendingPathComponent("\(selection.name).png", isDirectory: false) guard !dryRun else { created.append(fileURL) return } let data = bitmap.representationUsingType(.NSPNGFileType, properties: [:]) do { try data?.writeToURL(fileURL, options: .DataWritingWithoutOverwriting) created.append(fileURL) } catch { NSLog("%@", "\(#function): error: failed writing \(data?.length) bytes to file \(fileURL.absoluteURL.path): \(error)") } } NSLog("%@", "created: \(created)") return created } func bitmapFor(subregion: Subimage) -> NSBitmapImageRep? { let subregion = CGRectIntegral(subregion.rect) let size = subregion.size guard let bitmap = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(subregion.size.width), pixelsHigh: Int(subregion.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 4*Int(subregion.size.width), bitsPerPixel: 32) else { NSLog("%@", "\(#function): error: failed to create bitmap image rep") return nil } let bitmapContext = NSGraphicsContext(bitmapImageRep: bitmap) let old = NSGraphicsContext.currentContext() NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext(bitmapContext) let target = CGRect(origin: CGPointZero, size: size) image.drawInRect( target, fromRect: subregion, operation: .CompositeCopy, fraction: 1.0, respectFlipped: true, hints: nil) NSGraphicsContext.setCurrentContext(old) NSGraphicsContext.restoreGraphicsState() return bitmap } } class ImageSliceJobView: NSView { var job: Job init(job: Job) { self.job = job let frame = CGRect(origin: CGPointZero, size: job.image.size) super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(dirtyRect: NSRect) { job.image.drawInRect(self.bounds) NSColor.greenColor().set() outlineSubimages() NSColor.redColor().set() markCutPoints() labelSelections(NSColor.blueColor()) } func outlineSubimages() { for sub in job.subimages { NSFrameRect(sub.rect) } } func markCutPoints() { for cut in job.cuts { let rect = CGRect(origin: cut.at, size: CGSize(width: 2, height: 2)) NSRectFill(CGRectOffset(rect, -1, -1)) } } func labelSelections(textColor: NSColor) { let attributes = [NSForegroundColorAttributeName: textColor] for selection in job.selections { let text = selection.name text.drawAtPoint(selection.around, withAttributes: attributes) } } } //: Basic image let image = NSImage(named: "fourpart.gif")! //: Split between English and Gregg var job = Job(image: image, cuts: [], selections: []) job.add( Cut(at: CGPoint(x: 20, y: image.size.height - 18), oriented: .Horizontally)) job.add(Cut(at: CGPoint(x: 75, y: 0), oriented: .Vertically)) job.add(Cut(at: CGPoint(x: 155, y: 0), oriented: .Vertically)) job.add(Cut(at: CGPoint(x: 235, y: 0), oriented: .Vertically)) job.selections.append(Mark(around: CGPointZero, name: "deed")) job.selections.append(Mark(around: CGPoint(x: 80, y: 0), name: "dad")) var display = ImageSliceJobView(job: job) //: Dry-run of exporting should list an image per mark job.exportSelectedSubimages(NSURL(fileURLWithPath: NSHomeDirectory(), isDirectory: true), dryRun: true)
mpl-2.0
68b89eb2bf9e0581a0c0b93bf049d5e1
28.680365
134
0.607077
4.445964
false
false
false
false
csnu17/My-Swift-learning
collection-data-structures-swift/DataStructures/SetViewController.swift
1
3557
// // SetViewController.swift // DataStructures // // Created by Ellen Shapiro on 8/2/14. // Copyright (c) 2014 Ray Wenderlich Tutorial Team. All rights reserved. // import UIKit private enum SetVCRow: Int { case creation = 0, add1Object, add5Objects, add10Objects, remove1Object, remove5Objects, remove10Objects, lookup1Object, lookup10Objects } class SetViewController: DataStructuresViewController { //MARK: - Variables let setManipulator = SwiftSetManipulator() var creationTime: TimeInterval = 0 var add1ObjectTime: TimeInterval = 0 var add5ObjectsTime: TimeInterval = 0 var add10ObjectsTime: TimeInterval = 0 var remove1ObjectTime: TimeInterval = 0 var remove5ObjectsTime: TimeInterval = 0 var remove10ObjectsTime: TimeInterval = 0 var lookup1ObjectTime: TimeInterval = 0 var lookup10ObjectsTime: TimeInterval = 0 //MARK: - Methods //MARK: View lifecycle override func viewDidLoad() { super.viewDidLoad() createAndTestButton.setTitle("Create Set and Test", for: UIControlState()) } //MARK: Superclass creation/testing overrides override func create(_ size: Int) { creationTime = setManipulator.setupWithObjectCount(size) } override func test() { if (setManipulator.setHasObjects()) { add1ObjectTime = setManipulator.add1Object() add5ObjectsTime = setManipulator.add5Objects() add10ObjectsTime = setManipulator.add10Objects() remove1ObjectTime = setManipulator.remove1Object() remove5ObjectsTime = setManipulator.remove5Objects() remove10ObjectsTime = setManipulator.remove10Objects() lookup1ObjectTime = setManipulator.lookup1Object() lookup10ObjectsTime = setManipulator.lookup10Objects() } else { print("Set is not set up yet!") } } //MARK: Table View Override override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAt: indexPath) switch (indexPath as NSIndexPath).row { case SetVCRow.creation.rawValue: cell.textLabel!.text = "Set Creation:" cell.detailTextLabel!.text = formattedTime(creationTime) case SetVCRow.add1Object.rawValue: cell.textLabel!.text = "Add 1 Object:" cell.detailTextLabel!.text = formattedTime(add1ObjectTime) case SetVCRow.add5Objects.rawValue: cell.textLabel!.text = "Add 5 Objects:" cell.detailTextLabel!.text = formattedTime(add5ObjectsTime) case SetVCRow.add10Objects.rawValue: cell.textLabel!.text = "Add 10 Objects:" cell.detailTextLabel!.text = formattedTime(add10ObjectsTime) case SetVCRow.remove1Object.rawValue: cell.textLabel!.text = "Remove 1 Object:" cell.detailTextLabel!.text = formattedTime(remove1ObjectTime) case SetVCRow.remove5Objects.rawValue: cell.textLabel!.text = "Remove 5 Objects:" cell.detailTextLabel!.text = formattedTime(remove5ObjectsTime) case SetVCRow.remove10Objects.rawValue: cell.textLabel!.text = "Remove 10 Objects:" cell.detailTextLabel!.text = formattedTime(remove10ObjectsTime) case SetVCRow.lookup1Object.rawValue: cell.textLabel!.text = "Lookup 1 Object:" cell.detailTextLabel!.text = formattedTime(lookup1ObjectTime) case SetVCRow.lookup10Objects.rawValue: cell.textLabel!.text = "Lookup 10 Objects:" cell.detailTextLabel!.text = formattedTime(lookup10ObjectsTime) default: print("Unhandled row! \((indexPath as NSIndexPath).row)") } return cell } }
mit
2b6c834267c879a732ef5805ab7c0e3f
31.935185
107
0.729547
4.219454
false
false
false
false
magnetsystems/message-samples-ios
QuickStart/QuickStart/PushViewController.swift
1
3089
/* * Copyright (c) 2015 Magnet Systems, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ import UIKit import MagnetMax class PushViewController: UIViewController { // MARK: Outlets @IBOutlet weak var messageTextField: UITextField! @IBOutlet weak var shouldAddBadge: UISwitch! @IBOutlet weak var shouldAddSound: UISwitch! // MARK: public properties var bgTaskIdentifier : UIBackgroundTaskIdentifier = 0 // MARK: Actions @IBAction func sendMessage(sender: UIBarButtonItem) { let delay : NSTimeInterval = 5.0 // Start background task bgTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { [weak self] in self?.endBackgroundTask() } let alert = UIAlertController(title: "Sending push", message: "Sending push in \(delay) sec(s)\n Please put app in background.", preferredStyle: .Alert) let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(defaultAction) presentViewController(alert, animated: true, completion: nil) self.performSelector(Selector("sendMessageAfterDelay"), withObject: nil, afterDelay: delay) } // MARK: public implementations func sendMessageAfterDelay() { if let messageText = messageTextField.text { guard let currentUser = MMUser.currentUser() else { return } // Build the push message let recipients : Set <MMUser> = [currentUser] let title = "MMX Push Message" let sound : String? = shouldAddSound.on ? "default" : nil let badge : NSNumber? = shouldAddBadge.on ? 1 : nil let pushMessage : MMXPushMessage = MMXPushMessage.pushMessageWithRecipients(recipients, body: messageText, title: title, sound: sound, badge: badge, userDefinedObjects: ["SenderKey" : currentUser.userName]) pushMessage.sendPushMessage({ [weak self] in print("Push message sent successfully") self?.endBackgroundTask() }, failure: { [weak self] error in print(error) self?.endBackgroundTask() }) } } func endBackgroundTask() { print("Background task ended.") UIApplication.sharedApplication().endBackgroundTask(bgTaskIdentifier) bgTaskIdentifier = UIBackgroundTaskInvalid } }
apache-2.0
fabb018b87377609d377b21eee675397
33.707865
218
0.647782
5.226734
false
false
false
false
tcliff111/TipR
Tip Calculator/ViewController.swift
1
7535
// // ViewController.swift // Tip Calculator // // Created by Thomas Clifford on 12/5/15. // Copyright (c) 2015 Thomas Clifford. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var billField: UITextField! @IBOutlet weak var totalLabel: UILabel! @IBOutlet weak var tipLabel: UILabel! @IBOutlet weak var total2: UILabel! @IBOutlet weak var total3: UILabel! @IBOutlet weak var total4: UILabel! @IBOutlet weak var blackView: UIView! @IBOutlet weak var percentButton: UISegmentedControl! var key1 = "firstKey" var key2 = "secondKey" var key3 = "thirdKey" var closeKey = "closingKey" var percentages = [Double]() var openingTime: NSDate? = nil var closingTime: NSDate? = nil let formatter = NSNumberFormatter() var tipLabelY: CGFloat = 0.0 override func viewDidLoad() { super.viewDidLoad() tipLabelY = tipLabel.frame.origin.y tipLabel.frame.origin.y += 400; totalLabel.frame.origin.y += 400; total2.frame.origin.y += 400; total3.frame.origin.y += 400; total4.frame.origin.y += 400; blackView.frame.origin.y += 400; percentButton.frame.origin.y += 400; billField.frame.origin.y += 100; // Do any additional setup after loading the view, typically from a nib. formatter.numberStyle = .CurrencyStyle billField.textAlignment = .Right billField.attributedPlaceholder = NSAttributedString(string:formatter.currencySymbol, attributes:[NSForegroundColorAttributeName: UIColor.blackColor()]) reset() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) billField.becomeFirstResponder() let defaults = NSUserDefaults.standardUserDefaults() let first:Int? = Int(defaults.objectForKey(key1) as! String) let second:Int? = Int(defaults.objectForKey(key2) as! String) let third:Int? = Int(defaults.objectForKey(key3) as! String) if(first != nil && second != nil && third != nil) { percentages[0] = Double(first!)/100.00 percentages[1] = Double(second!)/100.00 percentages[2] = Double(third!)/100.00 percentButton.setTitle(String(first!)+"%", forSegmentAtIndex: 0) percentButton.setTitle(String(second!)+"%", forSegmentAtIndex: 1) percentButton.setTitle(String(third!)+"%", forSegmentAtIndex: 2) } else { percentages[0] = 0.15 percentages[1] = 0.18 percentages[2] = 0.2 percentButton.setTitle("15%", forSegmentAtIndex: 0) percentButton.setTitle("18%", forSegmentAtIndex: 1) percentButton.setTitle("20%", forSegmentAtIndex: 2) } let percent = percentages[percentButton.selectedSegmentIndex] if let billAmount = Double(billField.text!) { let tip = billAmount*percent let total = billAmount + tip tipLabel.text = "+ "+formatter.stringFromNumber(tip)! totalLabel.text = formatter.stringFromNumber(total) total2.text = formatter.stringFromNumber(total/2) total3.text = formatter.stringFromNumber(total/3) total4.text = formatter.stringFromNumber(total/4) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onEditingChanged(sender: AnyObject) { let percent = percentages[percentButton.selectedSegmentIndex] if let billAmount = Double(billField.text!) { let tip = billAmount*percent let total = billAmount + tip tipLabel.text = "+ "+formatter.stringFromNumber(tip)! totalLabel.text = formatter.stringFromNumber(total) total2.text = formatter.stringFromNumber(total/2) total3.text = formatter.stringFromNumber(total/3) total4.text = formatter.stringFromNumber(total/4) if(tipLabelY != tipLabel.frame.origin.y) { UIView.animateWithDuration(0.4, animations: { self.tipLabel.frame.origin.y -= 400; self.totalLabel.frame.origin.y -= 400; self.total2.frame.origin.y -= 400; self.total3.frame.origin.y -= 400; self.total4.frame.origin.y -= 400; self.blackView.frame.origin.y -= 400; self.percentButton.frame.origin.y -= 400; self.billField.frame.origin.y -= 100; }) } } else if(billField.text!.isEmpty) { if(tipLabelY == tipLabel.frame.origin.y) { UIView.animateWithDuration(0.4, animations: { self.tipLabel.frame.origin.y += 400; self.totalLabel.frame.origin.y += 400; self.total2.frame.origin.y += 400; self.total3.frame.origin.y += 400; self.total4.frame.origin.y += 400; self.blackView.frame.origin.y += 400; self.percentButton.frame.origin.y += 400; self.billField.frame.origin.y += 100; }) } tipLabel.text = "+ "+formatter.stringFromNumber(0)! totalLabel.text = formatter.stringFromNumber(0) total2.text = formatter.stringFromNumber(0) total3.text = formatter.stringFromNumber(0) total4.text = formatter.stringFromNumber(0) } } func reset() { billField.text="" tipLabel.text = "+ "+formatter.stringFromNumber(0)! totalLabel.text = formatter.stringFromNumber(0) total2.text = formatter.stringFromNumber(0) total3.text = formatter.stringFromNumber(0) total4.text = formatter.stringFromNumber(0) let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject("15", forKey: key1) defaults.setObject("18", forKey: key2) defaults.setObject("20", forKey: key3) defaults.synchronize() percentages.append(0.1) percentages.append(0.1) percentages.append(0.1) percentButton.setTitle("15%", forSegmentAtIndex: 0) percentButton.setTitle("18%", forSegmentAtIndex: 1) percentButton.setTitle("20%", forSegmentAtIndex: 2) } @IBAction func onTap(sender: AnyObject) { view.endEditing(true) } // func compareTimes(opens: NSDate?, closes: NSDate?) { // print("compare") // if(opens!.timeIntervalSinceReferenceDate-closes!.timeIntervalSinceReferenceDate>3) { // reset() // print("op") // } // } // func openApp() { // print("open") // openingTime = NSDate() // let defaults = NSUserDefaults.standardUserDefaults() // closingTime = defaults.objectForKey(closeKey) as! NSDate? // if (closingTime != nil) { // compareTimes(openingTime, closes: closingTime) // } // } // // func closeApp() { // print("close") // closingTime = NSDate() // let defaults = NSUserDefaults.standardUserDefaults() // defaults.setObject(closingTime, forKey: closeKey) // } }
apache-2.0
0773f3b14f74bc0ad4129d39c437db95
36.487562
98
0.592037
4.533694
false
false
false
false
nearspeak/iOS-SDK
NearspeakKit/NSKLinkedTag.swift
1
2185
// // NSKLinkedTag.swift // NearspeakKit // // Created by Patrick Steiner on 21.01.15. // Copyright (c) 2015 Mopius OG. All rights reserved. // import Foundation // NSCoding Keys let keyNSKLinkedTagId = "linkedTag_id" let keyNSKLinkedTagName = "linkedTag_name" let keyNSKLinkedTagIdentifier = "linkedTag_identifier" /** Linked nearspeak tags class. */ public class NSKLinkedTag: NSObject, NSCoding { /** The id of the linked Nearspeak tag. */ public var id: NSNumber = 0 /** The name of the linked Nearspeak tag. */ public var name: String? /** The identifier of the linked Nearspeak tag. */ public var identifier: String? /** Constructor where you have to set the id of the linked Nearspeak tag. - parameter id: The id of the linked Nearspeak tag. */ public init(id: NSNumber) { super.init() self.id = id } /** Constructor for the linked Nearspeak tag. - parameter id: The id of the linked Nearspeak tag. - parameter name: The name of the linked Nearspeak tag. - parameter identifier: The identifier of the linked Nearspeak tag. */ public init(id: NSNumber, name: String, identifier: String) { self.id = id self.name = name self.identifier = identifier } /** Standard constructor for the linked Nearspeak tag, with NSCoder support. - parameter aDecoder: The NScoder decoder object. */ required public init?(coder aDecoder: NSCoder) { self.id = aDecoder.decodeIntegerForKey(keyNSKLinkedTagId) self.name = aDecoder.decodeObjectForKey(keyNSKLinkedTagName) as? String self.identifier = aDecoder.decodeObjectForKey(keyNSKLinkedTagIdentifier) as? String } /** Encode the linked Nearspeak tag for NSCoder. - parameter aCoder: The NSCoder encoder object. **/ public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeInt(self.id.intValue, forKey: keyNSKLinkedTagId) aCoder.encodeObject(self.name, forKey: keyNSKLinkedTagName) aCoder.encodeObject(self.identifier, forKey: keyNSKLinkedTagIdentifier) } }
lgpl-3.0
f3a64ba28117c70459d39977549a9796
28.540541
91
0.666819
4.169847
false
false
false
false
Johennes/firefox-ios
Utils/FaviconFetcher.swift
1
10130
/* 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 Storage import Shared import Alamofire import XCGLogger import Deferred import WebImage import Fuzi private let log = Logger.browserLogger private let queue = dispatch_queue_create("FaviconFetcher", DISPATCH_QUEUE_CONCURRENT) class FaviconFetcherErrorType: MaybeErrorType { let description: String init(description: String) { self.description = description } } /* A helper class to find the favicon associated with a URL. * This will load the page and parse any icons it finds out of it. * If that fails, it will attempt to find a favicon.ico in the root host domain. */ public class FaviconFetcher: NSObject, NSXMLParserDelegate { public static var userAgent: String = "" static let ExpirationTime = NSTimeInterval(60*60*24*7) // Only check for icons once a week private static var characterToFaviconCache = [String : UIImage]() static var defaultFavicon: UIImage = { return UIImage(named: "defaultFavicon")! }() class func getForURL(url: NSURL, profile: Profile) -> Deferred<Maybe<[Favicon]>> { let f = FaviconFetcher() return f.loadFavicons(url, profile: profile) } private func loadFavicons(url: NSURL, profile: Profile, oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> { if isIgnoredURL(url) { return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons.")) } let deferred = Deferred<Maybe<[Favicon]>>() var oldIcons: [Favicon] = oldIcons dispatch_async(queue) { _ in self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in var deferreds = [Deferred<Maybe<Favicon>>]() if let icons = result.successValue { deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) } } return all(deferreds) }).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in for result in results { if let icon = result.successValue { oldIcons.append(icon) } } oldIcons = oldIcons.sort { return $0.width > $1.width } return deferMaybe(oldIcons) }).upon({ (result: Maybe<[Favicon]>) in deferred.fill(result) return }) } return deferred } lazy private var alamofire: Alamofire.Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.timeoutIntervalForRequest = 5 return Alamofire.Manager.managerWithUserAgent(userAgent, configuration: configuration) }() private func fetchDataForURL(url: NSURL) -> Deferred<Maybe<NSData>> { let deferred = Deferred<Maybe<NSData>>() alamofire.request(.GET, url).response { (request, response, data, error) in // Don't cancel requests just because our Manager is deallocated. withExtendedLifetime(self.alamofire) { if error == nil { if let data = data { deferred.fill(Maybe(success: data)) return } } let errorDescription = (error as NSError?)?.description ?? "No content." deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: errorDescription))) } } return deferred } // Loads and parses an html document and tries to find any known favicon-type tags for the page private func parseHTMLForFavicons(url: NSURL) -> Deferred<Maybe<[Favicon]>> { return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in var icons = [Favicon]() guard let data = result.successValue where result.isSuccess, let root = try? HTMLDocument(data: data) else { return deferMaybe([]) } var reloadUrl: NSURL? = nil for meta in root.xpath("//head/meta") { if let refresh = meta["http-equiv"] where refresh == "Refresh", let content = meta["content"], let index = content.rangeOfString("URL="), let url = NSURL(string: content.substringFromIndex(index.startIndex.advancedBy(4))) { reloadUrl = url } } if let url = reloadUrl { return self.parseHTMLForFavicons(url) } var bestType = IconType.NoneFound for link in root.xpath("//head//link[contains(@rel, 'icon')]") { var iconType: IconType? = nil if let rel = link["rel"] { switch (rel) { case "shortcut icon": iconType = .Icon case "icon": iconType = .Icon case "apple-touch-icon": iconType = .AppleIcon case "apple-touch-icon-precomposed": iconType = .AppleIconPrecomposed default: iconType = nil } } guard let href = link["href"] where iconType != nil else { continue //Skip the rest of the loop. But don't stop the loop } if (href.endsWith(".ico")) { iconType = .Guess } if let type = iconType where !bestType.isPreferredTo(type), let iconUrl = NSURL(string: href, relativeToURL: url), let absoluteString = iconUrl.absoluteString { let icon = Favicon(url: absoluteString, date: NSDate(), type: type) // If we already have a list of Favicons going already, then add it… if (type == bestType) { icons.append(icon) } else { // otherwise, this is the first in a new best yet type. icons = [icon] bestType = type } } // If we haven't got any options icons, then use the default at the root of the domain. if let url = NSURL(string: "/favicon.ico", relativeToURL: url) where icons.isEmpty, let absoluteString = url.absoluteString { let icon = Favicon(url: absoluteString, date: NSDate(), type: .Guess) icons = [icon] } } return deferMaybe(icons) }) } func getFavicon(siteUrl: NSURL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let url = icon.url let manager = SDWebImageManager.sharedManager() let site = Site(url: siteUrl.absoluteString!, title: "") var fav = Favicon(url: url, type: icon.type) if let url = url.asURL { var fetch: SDWebImageOperation? fetch = manager.downloadImageWithURL(url, options: SDWebImageOptions.LowPriority, progress: { (receivedSize, expectedSize) in if receivedSize > FaviconManager.maximumFaviconSize || expectedSize > FaviconManager.maximumFaviconSize { fetch?.cancel() } }, completed: { (img, err, cacheType, success, url) -> Void in fav = Favicon(url: url.absoluteString!, type: icon.type) if let img = img { fav.width = Int(img.size.width) fav.height = Int(img.size.height) profile.favicons.addFavicon(fav, forSite: site) } else { fav.width = 0 fav.height = 0 } deferred.fill(Maybe(success: fav)) }) } else { return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)")) } return deferred } // Returns the default favicon for a site based on the first letter of the site's domain class func getDefaultFavicon(url: NSURL) -> UIImage { guard let character = url.baseDomain()?.characters.first else { return defaultFavicon } let faviconLetter = String(character).uppercaseString if let cachedFavicon = characterToFaviconCache[faviconLetter] { return cachedFavicon } var faviconImage = UIImage() let faviconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: TwoLineCellUX.ImageSize, height: TwoLineCellUX.ImageSize)) faviconLabel.text = faviconLetter faviconLabel.textAlignment = .Center faviconLabel.font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium) faviconLabel.textColor = UIColor.grayColor() UIGraphicsBeginImageContextWithOptions(faviconLabel.bounds.size, false, 0.0) faviconLabel.layer.renderInContext(UIGraphicsGetCurrentContext()!) faviconImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() characterToFaviconCache[faviconLetter] = faviconImage return faviconImage } // Returns a color based on the url's hash class func getDefaultColor(url: NSURL) -> UIColor { guard let hash = url.baseDomain()?.hashValue else { return UIColor.grayColor() } let index = abs(hash) % (UIConstants.DefaultColorStrings.count - 1) let colorHex = UIConstants.DefaultColorStrings[index] return UIColor(colorString: colorHex) } }
mpl-2.0
2dc7d249f50d727469b4cf2d58417921
39.512
176
0.567141
5.247668
false
false
false
false
SECH-Tag-EEXCESS-Browser/iOSX-App
SechQueryComposer/SechQueryComposer/Connection.swift
1
944
// // Connection.swift // SechQueryComposer // // Copyright © 2015 Peter Stoehr. All rights reserved. // import Foundation class Connection { func post(params : AnyObject, url : String, postCompleted : (succeeded: Bool, data: NSData) -> ()) { let request = NSMutableURLRequest(URL: NSURL(string: url)!) request.HTTPMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [NSJSONWritingOptions()]) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in postCompleted(succeeded: error == nil, data: data!) }) task.resume() } }
mit
0dea6d1b285b179fbab368cd15911971
30.466667
113
0.639449
4.860825
false
false
false
false
wangchong321/tucao
WCWeiBo/WCWeiBo/Classes/Model/Main/VieitorView.swift
1
1666
// // VieitorView.swift // WCWeiBo // // Created by 王充 on 15/5/10. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit protocol VieitorViewDelegate : NSObjectProtocol { func visitorViewLoginViewDidSelected() func visitorViewRegiesterViewDidSelected() } class VieitorView: UIView { @IBOutlet weak var scrollImgView: UIImageView! @IBOutlet weak var smallImgView: UIImageView! @IBOutlet weak var titleLabel: UILabel! weak var delegate : VieitorViewDelegate? func setupInfo(imageName: String, message: String, isHome: Bool = false){ titleLabel.text = message } func setNoLoginImge(smallImgName: String , title: String , isHome: Bool = false) { if isHome { smallImgView.image = UIImage(named: smallImgName) }else{ bringSubviewToFront(scrollImgView) scrollImgView.image = UIImage(named: smallImgName) smallImgView.hidden = true } titleLabel.text = title isHome ? startAnimation() : endAnimation() } func startAnimation(){ let anim = CABasicAnimation() anim.keyPath = "transform.rotation" anim.toValue = 2 * M_PI anim.repeatCount = MAXFLOAT anim.duration = 20.0 scrollImgView.layer.addAnimation(anim, forKey: "zhuan") } func endAnimation(){ scrollImgView.layer.removeAnimationForKey("zhuan") } @IBAction func register() { delegate?.visitorViewRegiesterViewDidSelected() } @IBAction func login() { delegate?.visitorViewLoginViewDidSelected() } }
mit
373de748f49b860bbbbff451bc32db70
25.774194
86
0.638554
4.523161
false
false
false
false
teads/TeadsSDK-iOS
MediationAdapters/TeadsSASAdapter/TeadsSASAdapterHelper.swift
1
1955
// // TeadsSASAdapterHelper.swift // TeadsSASAdapter // // Created by Jérémy Grosjean on 06/11/2020. // import TeadsSDK import UIKit @objc public final class TeadsSASAdapterHelper: NSObject { @objc public static func teadsAdSettingsToString(adSettings: TeadsAdapterSettings) -> String? { guard let adSettingsEscapedString = adSettings.escapedString else { return nil } return "teadsAdSettingsKey=\(adSettingsEscapedString)" } @objc public static func concatAdSettingsToKeywords(keywordsStrings: String, adSettings: TeadsAdapterSettings) -> String { if let adSettingsStrings = teadsAdSettingsToString(adSettings: adSettings) { return "\(keywordsStrings);\(adSettingsStrings)" } return keywordsStrings } static func stringToAdSettings(adSettingsString: String?) -> TeadsAdapterSettings? { if let adSettingsString = adSettingsString?.removingPercentEncoding?.data(using: .utf8) { return try? JSONDecoder().decode(TeadsAdapterSettings.self, from: adSettingsString) } return nil } } extension TeadsAdapterSettings { var escapedString: String? { if let data = try? JSONEncoder().encode(self), let adSettingsString = String(data: data, encoding: .utf8) { return adSettingsString.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed) } return nil } } struct ServerParameter: Codable { var placementId: Int? var teadsAdSettingsKey: String? static func instance(from serverParameterString: String) -> Self? { guard let data = serverParameterString.data(using: .utf8) else { return nil } return try? JSONDecoder().decode(Self.self, from: data) } var adSettings: TeadsAdapterSettings { return TeadsSASAdapterHelper.stringToAdSettings(adSettingsString: teadsAdSettingsKey) ?? TeadsAdapterSettings() } }
mit
acfb48431b0ae68c340132b17bbe1943
33.263158
126
0.698413
4.227273
false
false
false
false
VeinGuo/VGPlayer
VGPlayer/Classes/VGPlayer.swift
1
16160
// // VGPlayer.swift // VGPlayer // // Created by Vein on 2017/5/30. // Copyright © 2017年 Vein. All rights reserved. // import Foundation import AVFoundation /// play state /// /// - none: none /// - playing: playing /// - paused: pause /// - playFinished: finished /// - error: play failed public enum VGPlayerState: Int { case none // default case playing case paused case playFinished case error } /// buffer state /// /// - none: none /// - readyToPlay: ready To Play /// - buffering: buffered /// - stop : buffer error stop /// - bufferFinished: finished public enum VGPlayerBufferstate: Int { case none // default case readyToPlay case buffering case stop case bufferFinished } /// play video content mode /// /// - resize: Stretch to fill layer bounds. /// - resizeAspect: Preserve aspect ratio; fit within layer bounds. /// - resizeAspectFill: Preserve aspect ratio; fill layer bounds. public enum VGVideoGravityMode: Int { case resize case resizeAspect // default case resizeAspectFill } /// play background mode /// /// - suspend: suspend /// - autoPlayAndPaused: auto play and Paused /// - proceed: continue public enum VGPlayerBackgroundMode: Int { case suspend case autoPlayAndPaused case proceed } public protocol VGPlayerDelegate: class { // play state func vgPlayer(_ player: VGPlayer, stateDidChange state: VGPlayerState) // playe Duration func vgPlayer(_ player: VGPlayer, playerDurationDidChange currentDuration: TimeInterval, totalDuration: TimeInterval) // buffer state func vgPlayer(_ player: VGPlayer, bufferStateDidChange state: VGPlayerBufferstate) // buffered Duration func vgPlayer(_ player: VGPlayer, bufferedDidChange bufferedDuration: TimeInterval, totalDuration: TimeInterval) // play error func vgPlayer(_ player: VGPlayer, playerFailed error: VGPlayerError) } // MARK: - delegate methods optional public extension VGPlayerDelegate { func vgPlayer(_ player: VGPlayer, stateDidChange state: VGPlayerState) {} func vgPlayer(_ player: VGPlayer, playerDurationDidChange currentDuration: TimeInterval, totalDuration: TimeInterval) {} func vgPlayer(_ player: VGPlayer, bufferStateDidChange state: VGPlayerBufferstate) {} func vgPlayer(_ player: VGPlayer, bufferedDidChange bufferedDuration: TimeInterval, totalDuration: TimeInterval) {} func vgPlayer(_ player: VGPlayer, playerFailed error: VGPlayerError) {} } open class VGPlayer: NSObject { open var state: VGPlayerState = .none { didSet { if state != oldValue { self.displayView.playStateDidChange(state) self.delegate?.vgPlayer(self, stateDidChange: state) } } } open var bufferState : VGPlayerBufferstate = .none { didSet { if bufferState != oldValue { self.displayView.bufferStateDidChange(bufferState) self.delegate?.vgPlayer(self, bufferStateDidChange: bufferState) } } } open var displayView : VGPlayerView open var gravityMode : VGVideoGravityMode = .resizeAspect open var backgroundMode : VGPlayerBackgroundMode = .autoPlayAndPaused open var bufferInterval : TimeInterval = 2.0 open weak var delegate : VGPlayerDelegate? open fileprivate(set) var mediaFormat : VGPlayerMediaFormat open fileprivate(set) var totalDuration : TimeInterval = 0.0 open fileprivate(set) var currentDuration : TimeInterval = 0.0 open fileprivate(set) var buffering : Bool = false open fileprivate(set) var player : AVPlayer? { willSet{ removePlayerObservers() } didSet { addPlayerObservers() } } private var timeObserver: Any? open fileprivate(set) var playerItem : AVPlayerItem? { willSet { removePlayerItemObservers() removePlayerNotifations() } didSet { addPlayerItemObservers() addPlayerNotifications() } } open fileprivate(set) var playerAsset : AVURLAsset? open fileprivate(set) var contentURL : URL? open fileprivate(set) var error : VGPlayerError fileprivate var seeking : Bool = false fileprivate var resourceLoaderManager = VGPlayerResourceLoaderManager() //MARK:- life cycle public init(URL: URL?, playerView: VGPlayerView?) { mediaFormat = VGPlayerUtils.decoderVideoFormat(URL) contentURL = URL error = VGPlayerError() if let view = playerView { displayView = view } else { displayView = VGPlayerView() } super.init() if contentURL != nil { configurationPlayer(contentURL!) } } public convenience init(URL: URL) { self.init(URL: URL, playerView: nil) } public convenience init(playerView: VGPlayerView) { self.init(URL: nil, playerView: playerView) } public override convenience init() { self.init(URL: nil, playerView: nil) } deinit { removePlayerNotifations() cleanPlayer() displayView.removeFromSuperview() NotificationCenter.default.removeObserver(self) } internal func configurationPlayer(_ URL: URL) { self.displayView.setvgPlayer(vgPlayer: self) self.playerAsset = AVURLAsset(url: URL, options: .none) if URL.absoluteString.hasPrefix("file:///") { let keys = ["tracks", "playable"]; playerItem = AVPlayerItem(asset: playerAsset!, automaticallyLoadedAssetKeys: keys) } else { // remote add cache playerItem = resourceLoaderManager.playerItem(URL) } player = AVPlayer(playerItem: playerItem) displayView.reloadPlayerView() } // time KVO internal func addPlayerObservers() { timeObserver = player?.addPeriodicTimeObserver(forInterval: .init(value: 1, timescale: 1), queue: DispatchQueue.main, using: { [weak self] time in guard let strongSelf = self else { return } if let currentTime = strongSelf.player?.currentTime().seconds, let totalDuration = strongSelf.player?.currentItem?.duration.seconds { strongSelf.currentDuration = currentTime strongSelf.delegate?.vgPlayer(strongSelf, playerDurationDidChange: currentTime, totalDuration: totalDuration) strongSelf.displayView.playerDurationDidChange(currentTime, totalDuration: totalDuration) } }) } internal func removePlayerObservers() { player?.removeTimeObserver(timeObserver!) } } //MARK: - public extension VGPlayer { open func replaceVideo(_ URL: URL) { reloadPlayer() mediaFormat = VGPlayerUtils.decoderVideoFormat(URL) contentURL = URL configurationPlayer(URL) } open func reloadPlayer() { seeking = false totalDuration = 0.0 currentDuration = 0.0 error = VGPlayerError() state = .none buffering = false bufferState = .none cleanPlayer() } open func cleanPlayer() { player?.pause() player?.cancelPendingPrerolls() player?.replaceCurrentItem(with: nil) player = nil playerAsset?.cancelLoading() playerAsset = nil playerItem?.cancelPendingSeeks() playerItem = nil } open func play() { if contentURL == nil { return } player?.play() state = .playing displayView.play() } open func pause() { guard state == .paused else { player?.pause() state = .paused displayView.pause() return } } open func seekTime(_ time: TimeInterval) { seekTime(time, completion: nil) } open func seekTime(_ time: TimeInterval, completion: ((Bool) -> Swift.Void)?) { if time.isNaN || playerItem?.status != .readyToPlay { if completion != nil { completion!(false) } return } DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.seeking = true strongSelf.startPlayerBuffering() strongSelf.playerItem?.seek(to: CMTimeMakeWithSeconds(time, preferredTimescale: Int32(NSEC_PER_SEC)), completionHandler: { (finished) in DispatchQueue.main.async { strongSelf.seeking = false strongSelf.stopPlayerBuffering() strongSelf.play() if completion != nil { completion!(finished) } } }) } } } //MARK: - private extension VGPlayer { internal func startPlayerBuffering() { pause() bufferState = .buffering buffering = true } internal func stopPlayerBuffering() { bufferState = .stop buffering = false } internal func collectPlayerErrorLogEvent() { error.playerItemErrorLogEvent = playerItem?.errorLog()?.events error.error = playerItem?.error error.extendedLogData = playerItem?.errorLog()?.extendedLogData() error.extendedLogDataStringEncoding = playerItem?.errorLog()?.extendedLogDataStringEncoding } } //MARK: - Notifation Selector & KVO private var playerItemContext = 0 extension VGPlayer { internal func addPlayerItemObservers() { let options = NSKeyValueObservingOptions([.new, .initial]) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: options, context: &playerItemContext) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: options, context: &playerItemContext) playerItem?.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty), options: options, context: &playerItemContext) } internal func addPlayerNotifications() { NotificationCenter.default.addObserver(self, selector: .playerItemDidPlayToEndTime, name: .AVPlayerItemDidPlayToEndTime, object: nil) NotificationCenter.default.addObserver(self, selector: .applicationWillEnterForeground, name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: .applicationDidEnterBackground, name: UIApplication.didEnterBackgroundNotification, object: nil) } internal func removePlayerItemObservers() { playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges)) playerItem?.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.playbackBufferEmpty)) } internal func removePlayerNotifations() { NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil) } @objc internal func playerItemDidPlayToEnd(_ notification: Notification) { if state != .playFinished { state = .playFinished } } @objc internal func applicationWillEnterForeground(_ notification: Notification) { if let playerLayer = displayView.playerLayer { playerLayer.player = player } switch self.backgroundMode { case .suspend: pause() case .autoPlayAndPaused: play() case .proceed: break } } @objc internal func applicationDidEnterBackground(_ notification: Notification) { if let playerLayer = displayView.playerLayer { playerLayer.player = nil } switch self.backgroundMode { case .suspend: pause() case .autoPlayAndPaused: pause() case .proceed: play() break } } } extension VGPlayer { open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (context == &playerItemContext) { if keyPath == #keyPath(AVPlayerItem.status) { let status: AVPlayerItem.Status if let statusNumber = change?[.newKey] as? NSNumber { status = AVPlayerItem.Status(rawValue: statusNumber.intValue)! } else { status = .unknown } switch status { case .unknown: startPlayerBuffering() case .readyToPlay: bufferState = .readyToPlay case .failed: state = .error collectPlayerErrorLogEvent() stopPlayerBuffering() delegate?.vgPlayer(self, playerFailed: error) displayView.playFailed(error) } } else if keyPath == #keyPath(AVPlayerItem.playbackBufferEmpty){ if let playbackBufferEmpty = change?[.newKey] as? Bool { if playbackBufferEmpty { startPlayerBuffering() } } } else if keyPath == #keyPath(AVPlayerItem.loadedTimeRanges) { // 计算缓冲 let loadedTimeRanges = player?.currentItem?.loadedTimeRanges if let bufferTimeRange = loadedTimeRanges?.first?.timeRangeValue { let star = bufferTimeRange.start.seconds // The start time of the time range. let duration = bufferTimeRange.duration.seconds // The duration of the time range. let bufferTime = star + duration if let itemDuration = playerItem?.duration.seconds { delegate?.vgPlayer(self, bufferedDidChange: bufferTime, totalDuration: itemDuration) displayView.bufferedDidChange(bufferTime, totalDuration: itemDuration) totalDuration = itemDuration if itemDuration == bufferTime { bufferState = .bufferFinished } } if let currentTime = playerItem?.currentTime().seconds{ if (bufferTime - currentTime) >= bufferInterval && state != .paused { play() } if (bufferTime - currentTime) < bufferInterval { bufferState = .buffering buffering = true } else { buffering = false bufferState = .readyToPlay } } } else { play() } } }else{ super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } } // MARK: - Selecter extension Selector { static let playerItemDidPlayToEndTime = #selector(VGPlayer.playerItemDidPlayToEnd(_:)) static let applicationWillEnterForeground = #selector(VGPlayer.applicationWillEnterForeground(_:)) static let applicationDidEnterBackground = #selector(VGPlayer.applicationDidEnterBackground(_:)) }
mit
5de247b816b122adf78d1b9d9eaf3cb7
33.359574
161
0.603876
5.468676
false
false
false
false
ktmswzw/FeelingClientBySwift
FeelingClient/MVC/LoginViewController.swift
1
5525
// // LoginViewController.swift // FeelingClient // // Created by vincent on 13/2/16. // Copyright © 2016 xecoder. All rights reserved. // import UIKit import IBAnimatable import SwiftyJSON import Alamofire class LoginViewController: DesignableViewController,UITextFieldDelegate { @IBOutlet var username: AnimatableTextField! @IBOutlet var password: AnimatableTextField! let jwt = JWTTools() var actionButton: ActionButton! override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "lonely-children") let blurredImage = image!.imageByApplyingBlurWithRadius(3) self.view.layer.contents = blurredImage.CGImage let register = ActionButtonItem(title: "注册帐号", image: UIImage(named: "new")!) register.action = { item in self.performSegueWithIdentifier("register", sender: self) } // let forget = ActionButtonItem(title: "忘记密码", image: UIImage(named: "new")!) // forget.action = { item in } // let wechatLogin = ActionButtonItem(title: "微信登录", image: UIImage(named: "wechat")!) // wechatLogin.action = { item in } // let qqLogin = ActionButtonItem(title: "QQ登录", image: UIImage(named: "qq")!) // qqLogin.action = { item in } // let weiboLogin = ActionButtonItem(title: "微博登录", image: UIImage(named: "weibo")!) // weiboLogin.action = { item in } // let taobaoLogin = ActionButtonItem(title: "淘宝登录", image: UIImage(named: "taobao")!) // taobaoLogin.action = { item in // } // actionButton = ActionButton(attachedToView: self.view, items: [register, forget, wechatLogin, qqLogin, weiboLogin, taobaoLogin]) actionButton = ActionButton(attachedToView: self.view, items: [register]) actionButton.action = { button in button.toggleMenu() } actionButton.setImage(UIImage(named: "new"), forState: .Normal) actionButton.backgroundColor = UIColor.lightGrayColor() username.delegate = self password.delegate = self HUD = MBProgressHUD(view: self.view) self.view.addSubview(HUD!) } override func textFieldShouldReturn(textField: UITextField) -> Bool { if (textField === username) { password.becomeFirstResponder() } else if (textField === password) { password.resignFirstResponder() self.login(self) } else { // etc } return true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func login(sender: AnyObject) { // self.performSegueWithIdentifier("login", sender: self) // return if username.text != "" && password.text != "" { if !self.password.validatePassword() { self.view.makeToast("密码必选大于6位数小于18的数字或字符", duration: 2, position: .Top) return } else{ //123456789001 //123456 let userNameText = username.text let passwordText = password.text!.md5() HUD!.showAnimated(true, whileExecutingBlock: { () -> Void in NetApi().makeCall(Alamofire.Method.POST, section: "login", headers: [:], params: ["username": userNameText!,"password":passwordText!,"device":"APP"], completionHandler: { (result:BaseApi.Result) -> Void in switch (result) { case .Success(let r): if let json = r { let myJosn = JSON(json) let code:Int = Int(myJosn["status"].stringValue)! if code != 200 { self.view.makeToast(myJosn.dictionary!["message"]!.stringValue, duration: 2, position: .Top) } else{ self.jwt.jwtTemp = myJosn.dictionary!["message"]!.stringValue self.view.makeToast("登陆成功", duration: 1, position: .Top) self.performSegueWithIdentifier("login", sender: self) } } break; case .Failure(let error): print("\(error)") break; } }) }) { () -> Void in HUD!.removeFromSuperview() } } } else { //self.alertStatusBarMsg("帐号或密码为空"); self.view.makeToast("帐号或密码为空", duration: 2, position: .Top) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if !jwt.jwtTemp.isEmpty { self.view.makeToast("登陆成功", duration: 1, position: .Top) self.performSegueWithIdentifier("login", sender: self) } } }
mit
a273db27d184c02981af70dcca5ba413
38.15942
225
0.517209
5.132004
false
false
false
false
GEOSwift/GEOSwift
Sources/GEOSwift/GEOS/WKBConvertible.swift
2
1945
import Foundation import geos public protocol WKBConvertible { func wkb() throws -> Data } protocol WKBConvertibleInternal: WKBConvertible, GEOSObjectConvertible {} extension WKBConvertibleInternal { public func wkb() throws -> Data { let context = try GEOSContext() let writer = try WKBWriter(context: context) return try writer.write(self) } } extension Point: WKBConvertible, WKBConvertibleInternal {} extension LineString: WKBConvertible, WKBConvertibleInternal {} extension Polygon.LinearRing: WKBConvertible, WKBConvertibleInternal {} extension Polygon: WKBConvertible, WKBConvertibleInternal {} extension MultiPoint: WKBConvertible, WKBConvertibleInternal {} extension MultiLineString: WKBConvertible, WKBConvertibleInternal {} extension MultiPolygon: WKBConvertible, WKBConvertibleInternal {} extension GeometryCollection: WKBConvertible, WKBConvertibleInternal {} extension Geometry: WKBConvertible, WKBConvertibleInternal {} private final class WKBWriter { private let context: GEOSContext private let writer: OpaquePointer init(context: GEOSContext) throws { guard let writer = GEOSWKBWriter_create_r(context.handle) else { throw GEOSError.libraryError(errorMessages: context.errors) } self.context = context self.writer = writer } deinit { GEOSWKBWriter_destroy_r(context.handle, writer) } func write(_ geometry: GEOSObjectConvertible) throws -> Data { let geosObject = try geometry.geosObject(with: context) var bufferCount = 0 guard let bufferPointer = GEOSWKBWriter_write_r( context.handle, writer, geosObject.pointer, &bufferCount) else { throw GEOSError.libraryError(errorMessages: context.errors) } defer { bufferPointer.deallocate() } return Data(buffer: UnsafeBufferPointer(start: bufferPointer, count: bufferCount)) } }
mit
0d6d6b9efd4924d04c8ce62efb170e74
35.018519
90
0.731105
4.686747
false
false
false
false
daxrahusen/Eindproject
Social Wall/ContentTextField.swift
1
2485
// // ContentTextField.swift // Social Wall // // Created by Dax Rahusen on 11/01/2017. // Copyright © 2017 Dax. All rights reserved. // import UIKit // Subclass of an UITextField which has the option // for letting an image to the left size of the text class ContentTextField: UITextField { // set a hardcoded left padding of 30 let padding = UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 5); // define an optional leftImage object var leftImage: UIImage? { didSet { // if the UIImage is set, // call the function updateViews updateViews() } } // function which renders the UIImage and it's color value private func updateViews() { // allways show a view to the left leftViewMode = .always // create a imageView rect with hardcoded values let imageViewRect = CGRect(x: 5, y: 0, width: 20, height: 20) // initialize an UIImageView with the defined rect let imageView = UIImageView(frame: imageViewRect) // set the contentMode so it will always fit imageView.contentMode = .scaleAspectFit // set the defined UIImage in the UIImageView with renderingmode // for changing the image color imageView.image = leftImage?.withRenderingMode(UIImageRenderingMode.alwaysTemplate) // set the tintColor of the imageview to light gray imageView.tintColor = .lightGray // make a rect with hardcoded values let viewRect = CGRect(x: 0, y: 0, width: 25, height: 20) // initialize a UIView with defined rect let view = UIView(frame: viewRect) // add the imageView to the UIView view.addSubview(imageView) // set the view in the leftView property of the UITextField leftView = view } // set the defined padding for the text rect override func textRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } // set the defined padding for the placeholder rect override func placeholderRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } // set the defined padding for the editing rect override func editingRect(forBounds bounds: CGRect) -> CGRect { return UIEdgeInsetsInsetRect(bounds, padding) } }
apache-2.0
df46726eab49418eb6358aa08e581f3a
31.25974
91
0.632045
5.090164
false
false
false
false
sendyhalim/Yomu
YomuTests/Models/ChapterSpec.swift
1
1614
// // ChapterSpec.swift // Yomu // // Created by Sendy Halim on 6/11/16. // Copyright © 2016 Sendy Halim. All rights reserved. // import Argo import Nimble import Quick @testable import Yomu class ChapterSpec: QuickSpec { override func spec() { describe("[Argo Decodable] When decoded from json") { context("and all values are not null") { let jsonString = "[700, 1415346745.0, \"Uzumaki Naruto!!\", \"545c7a3945b9ef92f1e256f7\"]" let json: AnyObject = JSONDataFromString(jsonString)! let chapter: Chapter = decode(json)! it("should decode chapter id") { expect(chapter.id) == "545c7a3945b9ef92f1e256f7" } it("should decode chapter number") { expect(chapter.number) == 700 } it("should decode chapter title") { expect(chapter.title) == "Uzumaki Naruto!!" } } context("and title is null") { let json = JSON.array([ JSON.number(800), JSON.number(1888221.3), JSON.null, JSON.string("someId") ]) var chapter: Chapter? switch Chapter.decode(json) { case .success(let _chapter): chapter = _chapter case .failure(let error): print(error) } it("should decode chapter id") { expect(chapter?.id) == "someId" } it("should decode chapter number") { expect(chapter?.number) == 800 } it("should decode chapter title to an empty string") { expect(chapter?.title) == "" } } } } }
mit
ff93fb4d1ec1bb32252f84a17d236ac4
22.720588
98
0.556727
3.934146
false
false
false
false
koutalou/iOS-CleanArchitecture
iOSCleanArchitectureTwitterSample/Domain/UseCase/TimelineUseCase.swift
1
2532
// // TimelineUseCase.swift // iOSCleanArchitectureTwitterSample // // Created by Kodama.Kotaro on 2015/12/21. // Copyright © 2015年 koutalou. All rights reserved. // import Foundation import RxSwift import Accounts // MARK: - Interface protocol TimelineUseCase { func loadTimelines() -> Observable<TimelinesModel> func loadTimelines(screenName: String) -> Observable<TimelinesModel> } // MARK: - Implementation struct TimelineUseCaseImpl: TimelineUseCase { private let loginAccountRepository: LoginAccountRepository private let socialAccountRepository: SocialAccountRepository private let timelineRepository: TimelineRepository public init(loginAccountRepository: LoginAccountRepository, socialAccountRepository: SocialAccountRepository, timelineRepository: TimelineRepository) { self.loginAccountRepository = loginAccountRepository self.socialAccountRepository = socialAccountRepository self.timelineRepository = timelineRepository } func loadTimelines() -> Observable<TimelinesModel> { let login = loginAccountRepository.getSelectedTwitterAccount() let accounts = socialAccountRepository.getTwitterAccounts() return Observable.combineLatest(login, accounts) { ($0, $1) } .flatMap { (identifier, accounts) -> Observable<TimelinesModel> in guard let identifier = identifier, let selectAccount = accounts.filter({$0.identifier.isEqual(to: identifier)}).first else { return Observable.error(AppError.notAuthorized) } return self.timelineRepository.getTwitterTimelines(selectAccount) .map(translator: TimelineTranslater()) } } func loadTimelines(screenName: String) -> Observable<TimelinesModel> { let login = loginAccountRepository.getSelectedTwitterAccount() let accounts = socialAccountRepository.getTwitterAccounts() return Observable.combineLatest(login, accounts) { ($0, $1) } .flatMap { (identifier, accounts) -> Observable<TimelinesModel> in guard let identifier = identifier, let selectAccount = accounts.filter({$0.identifier.isEqual(to: identifier)}).first else { return Observable.error(AppError.notAuthorized) } return self.timelineRepository.getTwitterUserTimelines(selectAccount, screenName: screenName) .map(translator: TimelineTranslater()) } } }
mit
16bbd64988cb5a30936f442869f0b819
42.603448
155
0.701463
5.171779
false
false
false
false
lerigos/music-service
iOS_9/Pods/ImagePicker/Source/BottomView/ImageStack.swift
1
1045
import UIKit import Photos public class ImageStack { public struct Notifications { public static let imageDidPush = "imageDidPush" public static let imageDidDrop = "imageDidDrop" public static let stackDidReload = "stackDidReload" } public var assets = [PHAsset]() private let imageKey = "image" public func pushAsset(asset: PHAsset) { assets.append(asset) NSNotificationCenter.defaultCenter().postNotificationName(Notifications.imageDidPush, object: self, userInfo: [imageKey: asset]) } public func dropAsset(asset: PHAsset) { assets = assets.filter() {$0 != asset} NSNotificationCenter.defaultCenter().postNotificationName(Notifications.imageDidDrop, object: self, userInfo: [imageKey: asset]) } public func resetAssets(assetsArray: [PHAsset]) { assets = assetsArray NSNotificationCenter.defaultCenter().postNotificationName(Notifications.stackDidReload, object: self, userInfo: nil) } public func containsAsset(asset: PHAsset) -> Bool { return assets.contains(asset) } }
apache-2.0
0efb0ec88800fbf4ad9b05f6e2fcfadf
30.666667
132
0.743541
4.50431
false
false
false
false
certainly/Caculator
Smashtag/Smashtag/SmashTweetersTableViewController.swift
1
2221
// // SmashTweetersTableViewController.swift // Smashtag // // Created by certainly on 2017/4/1. // Copyright © 2017年 certainly. All rights reserved. // import UIKit import CoreData class SmashTweetersTableViewController: FetchedResultsTableViewController { var mention: String? { didSet { updateUI() } } var container: NSPersistentContainer? = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer { didSet { updateUI() } } var fetchedResultsController: NSFetchedResultsController<TwitterUser>? private func updateUI() { if let context = container?.viewContext, mention != nil { let request: NSFetchRequest<TwitterUser> = TwitterUser.fetchRequest() request.sortDescriptors = [NSSortDescriptor(key: "handle", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))] request.predicate = NSPredicate(format: "any tweets.text contains[c] %@", mention!) fetchedResultsController = NSFetchedResultsController<TwitterUser>(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) fetchedResultsController?.delegate = self try? fetchedResultsController?.performFetch() tableView.reloadData() } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TwitterUser Cell", for: indexPath) if let twitterUser = fetchedResultsController?.object(at: indexPath) { cell.textLabel?.text = twitterUser.handle let tweetCount = tweetCountWithMentionBy(twitterUser) cell.detailTextLabel?.text = "\(tweetCount) tweet\(tweetCount == 1 ? "" : "s ")" } return cell } private func tweetCountWithMentionBy(_ twitterUser: TwitterUser) -> Int { let request: NSFetchRequest<Tweet> = Tweet.fetchRequest() request.predicate = NSPredicate(format: "text contains[c] %@ and tweeter = %@", mention!, twitterUser) return (try? twitterUser.managedObjectContext!.count(for: request)) ?? 0 } }
mit
c40e9332fd17ea301456deb90cb854ce
45.208333
173
0.690261
5.231132
false
false
false
false
AdaptiveMe/adaptive-arp-darwin
adaptive-arp-rt/Source/Sources.Impl/MessagingDelegate.swift
1
7185
/** --| ADAPTIVE RUNTIME PLATFORM |---------------------------------------------------------------------------------------- (C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. 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 appli- -cable 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. Original author: * Carlos Lozano Diez <http://github.com/carloslozano> <http://twitter.com/adaptivecoder> <mailto:[email protected]> Contributors: * Ferran Vila Conesa <http://github.com/fnva> <http://twitter.com/ferran_vila> <mailto:[email protected]> * See source code files for contributors. Release: * @version v2.0.2 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation import AdaptiveArpApi #if os(iOS) import MessageUI /** Interface for Managing the Messaging operations Auto-generated implementation of IMessaging specification. */ public class MessagingDelegate : UIViewController, /*BasePIMDelegate,*/ IMessaging, MFMessageComposeViewControllerDelegate { // TODO: Should delegate avoid extending UIViewController to prevent dupl. NSObject inheritance? /// Logger variable let logger : ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge() let loggerTag : String = "MessagingDelegate" /// Callbacks var smsCallback:IMessagingCallback! /** Group of API. */ private var apiGroup : IAdaptiveRPGroup? /** Return the API group for the given interface. */ public final func getAPIGroup() -> IAdaptiveRPGroup? { return self.apiGroup! } /** Return the API version for the given interface. */ public final func getAPIVersion() -> String? { return "v2.0.3" } /** Default Constructor. */ override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nibNameOrNil, bundle:nibBundleOrNil) self.apiGroup = IAdaptiveRPGroup.PIM } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } /** Send text SMS @param number to send @param text to send @param callback with the result @since ARP1.0 */ public func sendSMS(number : String, text : String, callback : IMessagingCallback) { // Check if the device can send SMS if !(MFMessageComposeViewController.canSendText()) { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The device cannot send SMS. Check the device") callback.onError(IMessagingCallbackError.NotSupported) return } // Open the view to compose the mail with the fields setted if let view = BaseViewController.ViewCurrent.getView() { self.smsCallback = callback // Add the MessageImplementation view controller and the subview view.addChildViewController(self) view.view.addSubview(self.view) let sms: MFMessageComposeViewController = MFMessageComposeViewController() sms.messageComposeDelegate = self sms.body = text sms.recipients = [number] self.presentViewController(sms, animated: true, completion: { self.logger.log(ILoggingLogLevel.Debug, category: self.loggerTag, message: "MFMessageComposeViewController presented") }) } else { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no a current view controller on the stack") callback.onError(IMessagingCallbackError.NotSent) } } /** This method is the metod called by the OS when the user leaves the sms screen. This method receives the result of the opertaion @param controller MFMessageComposeViewController used to fire this event @param result Send SMS result */ public func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) { switch result.rawValue { case MessageComposeResultSent.rawValue : logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Message sent") smsCallback.onResult(true) case MessageComposeResultCancelled.rawValue : logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Message cancelled by the user") smsCallback.onResult(false) case MessageComposeResultFailed.rawValue : logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Message not send due to an error") smsCallback.onError(IMessagingCallbackError.NotSent) default: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "The message delegeate received an unsuported result") } // Remove the view if (BaseViewController.ViewCurrent.getView() != nil) { // Remove the Message, Remove the view and remove the parent view controller self.dismissViewControllerAnimated(true, completion: nil) self.view.removeFromSuperview() self.removeFromParentViewController() } else { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is no a current view controller on the stack") smsCallback.onError(IMessagingCallbackError.Unknown) } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Set the background color to transparent self.view.backgroundColor = UIColor.clearColor() } } #endif #if os(OSX) /** Interface for Managing the Messaging operations Auto-generated implementation of IMessaging specification. */ public class MessagingDelegate : BasePIMDelegate, IMessaging { /** Default Constructor. */ public override init() { super.init() } /** Send text SMS @param number to send @param text to send @param callback with the result @since ARP1.0 */ public func sendSMS(number : String, text : String, callback : IMessagingCallback) { // TODO: implement this for OSX } } #endif /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
apache-2.0
de52577fc708689538f026fc77bca8e2
34.384236
221
0.630238
5.269993
false
false
false
false
owncloud/ios
Owncloud iOs Client/Tabs/SettingTab/Account/ManageAccounts.swift
1
4989
// // ManageAccounts.swift // Owncloud iOs Client // // Created by Noelia Alvarez on 13/07/2017. // // /* Copyright (C) 2017, ownCloud GmbH. This code is covered by the GNU Public License Version 3. For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/ You should have received a copy of this license along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>. */ import Foundation @objc class ManageAccounts: NSObject { /* * @param UserDto -> user to store * @param CredentialsDto -> credentials of user */ @objc func storeAccountOfUser(_ user: UserDto, withCredentials credDto: OCCredentialsDto) -> UserDto? { if let userInDB = ManageUsersDB.insertUser(user) { userInDB.credDto = credDto.copy() as! OCCredentialsDto userInDB.credDto.userId = String(userInDB.userId) //userInDB contains the userId in DB, we add the credentials and store the user in keychain OCKeychain.storeCredentials(userInDB.credDto) UtilsCookies.update(inDBOfUser: userInDB) // grant that settings of instant uploads are the same for the new account that for the currently active account ManageAppSettingsDB.updateInstantUploadAllUser(); return userInDB; } else { print("Error storing account for \(user.username)") return nil; } } @objc func updateAccountOfUser(_ user: UserDto, withCredentials credDto: OCCredentialsDto) { user.credDto = credDto.copy() as! OCCredentialsDto user.credDto.userId = String(user.userId) ManageUsersDB.updateUser(by: user) OCKeychain.updateCredentials(user.credDto) UtilsCookies.update(inDBOfUser: user) //Change the state of user uploads with credential error ManageUploadsDB.updateErrorCredentialFiles(user.userId) self.restoreDownloadAndUploadsOfUser(user) NotificationCenter.default.post(name: NSNotification.Name.RelaunchErrorCredentialFiles, object: nil) } @objc func migrateAccountOfUser(_ user: UserDto, withCredentials credDto: OCCredentialsDto) { //Update parameters after a force url and credentials have not been renewed let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) user.predefinedUrl = k_default_url_server ManageUploadsDB.overrideAllUploads(withNewURL: UtilsUrls.getFullRemoteServerPath(user)) self.updateAccountOfUser(user, withCredentials: credDto) self.updateDisplayNameOfUser(user: user) app.updateStateAndRestoreUploadsAndDownloads() let instantUploadManager: InstantUpload = InstantUpload.instantUploadManager() instantUploadManager.activate() } @objc func restoreDownloadAndUploadsOfUser(_ user : UserDto) { let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) app.cancelTheCurrentUploads(ofTheUser: user.userId) let downloadManager : ManageDownloads = app.downloadManager downloadManager.cancelAndRefreshInterface() if user.activeaccount { app.launchProcessToSyncAllFavorites() } } @objc func updateDisplayNameOfUser(user :UserDto) { guard (user.credDto) != nil else { return } DetectUserData.getUserDisplayName(ofServer: user.credDto.baseURL, credentials: user.credDto) { (serverUserID, displayName, error) in if ((serverUserID) != nil) { if (serverUserID == user.credDto.userName) { if ((displayName) != nil) { if (displayName != user.credDto.userDisplayName) { if (user.credDto.authenticationMethod == .SAML_WEB_SSO) { user.username = displayName } user.credDto.userDisplayName = displayName OCKeychain.updateCredentials(user.credDto) if (user.activeaccount) { let app: AppDelegate = (UIApplication.shared.delegate as! AppDelegate) app.activeUser.credDto = user.credDto.copy() as! OCCredentialsDto app.activeUser.username = user.credDto.userName } } } else { print("DisplayName not updated") } } } } } }
gpl-3.0
c11d44e29fbe5d9d2906549f4b381e48
35.152174
140
0.586089
4.778736
false
false
false
false
Raiden9000/Sonarus
ChatCell.swift
1
7272
// // ChatCell.swift // Sonarus // // Created by Christopher Arciniega on 5/3/17. // Copyright © 2017 HQZenithLabs. All rights reserved. // import UIKit class ChatCell: UITableViewCell { let chatCellLabel : UILabel = UILabel() var cellText : NSMutableAttributedString! //private let bubbleImageView = UIImageView() private var outgoingConstraints : [NSLayoutConstraint]! private var incomingConstraints : [NSLayoutConstraint]! var u:String = ""//user var t:String = ""//message text var i:Int = 100//index override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) chatCellLabel.translatesAutoresizingMaskIntoConstraints = false //bubbleImageView.translatesAutoresizingMaskIntoConstraints = false //contentView.addSubview(bubbleImageView) contentView.addSubview(chatCellLabel) NSLayoutConstraint.activate([ chatCellLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), chatCellLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), chatCellLabel.topAnchor.constraint(equalTo: contentView.topAnchor), chatCellLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), ]) //messageLabel.centerXAnchor.constraint(equalTo: bubbleImageView.centerXAnchor).isActive = true //messageLabel.centerYAnchor.constraint(equalTo: bubbleImageView.centerYAnchor).isActive = true //So speech bubble grows with text size //bubbleImageView.widthAnchor.constraint(equalTo: messageLabel.widthAnchor, constant: 50).isActive = true //50 accounts for tail in image //bubbleImageView.heightAnchor.constraint(equalTo: messageLabel.heightAnchor, constant:20).isActive = true//20 constant for padding text /*bubbleImageView.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true //One of the following will activate depending on message incoming/outgoing outgoingConstraint = bubbleImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor) incomingConstraint = bubbleImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor) outgoingConstraints = [ //bubbleImageView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),//flush bubble right //bubbleImageView.leadingAnchor.constraint(greaterThanOrEqualTo: contentView.centerXAnchor)//not farther than center ] incomingConstraints = [ //bubbleImageView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), //bubbleImageView.trailingAnchor.constraint(lessThanOrEqualTo: contentView.centerXAnchor) ] */ //bubbleImageView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true//constant for padding //bubbleImageView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10).isActive = true //bubbleImageView.backgroundColor = UIColor.clear self.backgroundColor = UIColor.clear chatCellLabel.textAlignment = .left chatCellLabel.numberOfLines = 0 //let image = UIImage(named:"MessageBubble")?.withRenderingMode(.alwaysTemplate) //bubbleImageView.tintColor = UIColor.blue //bubbleImageView.image = image } override func prepareForReuse() { super.prepareForReuse() print("cell Reuse - Previous text: \(t), index: \(i)") self.chatCellLabel.attributedText = nil u = "" t = "" i = 100 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //Bubble image flush left or right, depending on incoming or outgoing func setText(isIncoming:Bool, user:String, message:String){ let nameLength = user.characters.count + 1 let messageLength = message.characters.count + 1 if isIncoming{ cellText = NSMutableAttributedString(string: user + ": " + message, attributes: [NSAttributedStringKey.font:UIFont(name: "Georgia", size: 12)!]) cellText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, nameLength)) cellText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSMakeRange(nameLength, messageLength)) chatCellLabel.attributedText = cellText /*incomingConstraint.isActive = true outgoingConstraint.isActive = false*/ // NSLayoutConstraint.deactivate(outgoingConstraints) // NSLayoutConstraint.activate(incomingConstraints) //bubbleImageView.image = bubble.incoming//calls makeBubble method } else{//message isOutgoing cellText = NSMutableAttributedString(string: user + ": " + message, attributes: [NSAttributedStringKey.font:UIFont(name: "Georgia", size: 13)!]) print(cellText) print(cellText.length) cellText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSMakeRange(0, nameLength)) cellText.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.white, range: NSMakeRange(nameLength, messageLength)) chatCellLabel.attributedText = cellText /*incomingConstraint.isActive = false outgoingConstraint.isActive = true*/ // NSLayoutConstraint.deactivate(incomingConstraints) // NSLayoutConstraint.activate(outgoingConstraints) //bubbleImageView.image = bubble.outgoing//calls makeBubble method } } } //let bubble = makeBubble() /* func makeBubble() -> (incoming : UIImage, outgoing : UIImage){ let image = UIImage(named:"MessageBubble")! let insetsIncoming = UIEdgeInsets(top: 17, left: 26.5, bottom: 17.5, right: 21) let insetsOutgoing = UIEdgeInsets(top: 17, left: 21, bottom: 17.5, right: 26.5) let outgoing = coloredImage(image: image, red: 0/255, green: 122/255, blue: 255/255, alpha:1).resizableImage(withCapInsets: insetsOutgoing) let flippedImage = UIImage(cgImage: image.cgImage!, scale: image.scale, orientation: UIImageOrientation.upMirrored) let incoming = coloredImage(image: flippedImage, red: 229/255, green: 229/255, blue: 229/255, alpha:1).resizableImage(withCapInsets: insetsIncoming) return(incoming, outgoing) } func coloredImage(image: UIImage, red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat) -> UIImage{ let rect = CGRect(origin: CGPoint.zero, size: image.size) UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) let context = UIGraphicsGetCurrentContext() image.draw(in: rect) context?.setFillColor(red: red, green: green, blue: blue, alpha: alpha) context?.setBlendMode(CGBlendMode.sourceAtop) context?.fill(rect) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result! } */
mit
cffdb5c3a43b5396a2e8873960ac219f
44.72956
156
0.69564
5.171408
false
false
false
false
iXieYi/Weibo_DemoTest
Weibo_DemoTest/Weibo_DemoTest/PicturePicker/PicturePickerCollection.swift
1
8432
// // PicturePickerCollection.swift // 照片选择 // // Created by 谢毅 on 17/1/7. // Copyright © 2017年 xieyi. All rights reserved. // import UIKit //可重用cell private let PicturePickerCellId = "PicturePickerCellId" //最大选择照片数量 - 开发测试到所有边界到- 建议先将临界值设置小一些 private let PicturePickerMaxCount = 8 //照片选择控制器 class PicturePickerCollection: UICollectionViewController { //配图数组 lazy var pictures = [UIImage]() //当前用户照片选中的照片索引 private var selectIndex = 0 init(){ super.init(collectionViewLayout:PicturePickerLayout()) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //在colectionViewController中collectionView != view override func viewDidLoad() { super.viewDidLoad() //注册可重用cell self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId) collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0) } //类中类 - 照片选择器布局 private class PicturePickerLayout:UICollectionViewFlowLayout{ private override func prepareLayout() { super.prepareLayout() let count:CGFloat = 4 //在ios9之后,ipad支持分屏,不建议过分依赖布局参照 //6s- scale= 2;6s+ - scale= 3 let margin = UIScreen.mainScreen().scale * 4 let w = ((collectionView?.bounds.width)! - (count + 1) * margin) / count itemSize = CGSize(width: w, height: w) sectionInset = UIEdgeInsetsMake(margin, margin, 0, margin) minimumInteritemSpacing = margin minimumLineSpacing = margin } } } // MARK: 数据源方法 extension PicturePickerCollection{ override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 如果达到上限就不显示加号按钮 return pictures.count + (pictures.count == PicturePickerMaxCount ? 0:1) } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell //设置图像 cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] :nil //设置代理 cell.pictureDelegate = self return cell } } //MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate extension PicturePickerCollection:UIImagePickerControllerDelegate, UINavigationControllerDelegate{ /// 照片选择完成 /// /// - parameter picker: 照片选择控制器 /// - parameter info: info字典 ///一旦实现代理方法,必须自己dismiss //cocos2dx 开发一个空白模板,内存占用70m,ios,UI空白应用大概19M //一般应用程序内存控制在100M左右,都是可以接受的 func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { print(info) let image = info[UIImagePickerControllerOriginalImage] as!UIImage let scaleImage = image.scaleToWith(600) //判断当前选中的索引是否超出数组上限 if selectIndex >= pictures.count{ //将图像添加到数组 pictures.append(scaleImage) }else{ pictures[selectIndex] = scaleImage } //刷新视图 collectionView?.reloadData() dismissViewControllerAnimated(true, completion: nil) } } // MARK: - PicturePickerCellDelegate extension PicturePickerCollection:PicturePickerCellDelegate{ @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) { //判断是否允许访问相册 if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){ print("无法访问照片库") return } //记录当前用选中照片索引 selectIndex = collectionView?.indexPathForCell(cell)!.item ?? 0 //照片选择器 let picker = UIImagePickerController() //设置代理 picker.delegate = self // picker.allowsEditing = true//允许编辑 - 适合用于头像选择 presentViewController(picker, animated: true, completion: nil) /* case PhotoLibrary 相册 = 保存的照片(可以删除) + 同步的照片(不可以删除) case SavedPhotosAlbum 保存的照片、屏幕截图、拍照 */ print("添加照片") } @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) { //1.获取照片索引 let index = collectionView!.indexPathForCell(cell)! //2.判断索引是否超出上限 if index.item >= pictures.count{ return }else{ //3.删除数据 pictures.removeAtIndex(index.item) } //4.刷新视图 - 重新调用数据源方法,中的行数(内部实现要求 删除一个indexpath - //如果数据源不返回-1后的数值,就会奔溃 // collectionView?.deleteItemsAtIndexPaths([index])//动画刷新视图 collectionView?.reloadData()//这个方法单纯刷新数据,不会检测具体的数据 items数量 print("删除照片") } } /// cell的代理 //如果协议中包含optional 的函数,协议需要使用@objc的修饰, //但凡是需要遵守动态发布消息的,就需要准守@objc //备注:如果协议是私有的,在实现协议方法时,函数也是私有的,函数一旦是私有的就没有办法发送消息 @objc private protocol PicturePickerCellDelegate:NSObjectProtocol{ //添加照片 optional func picturePickerCellDidAdd(cell:PicturePickerCell) //删除照片 optional func picturePickerCellDidRemove(cell:PicturePickerCell) } /// MARK: - 自定义照片选择cell private 来修饰类,内部一切的方法和属性都是私有的, ///若要使用类里的方法必须将其以 @objc 作为修饰 private class PicturePickerCell:UICollectionViewCell { //照片选择代理 weak var pictureDelegate:PicturePickerCellDelegate? var image:UIImage?{ didSet{ addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: .Normal) //隐藏删除按钮 image == nil就是新增按钮 removeButton.hidden = (image == nil) } } //MARK: - 监听方法 @objc func addPicture(){ pictureDelegate?.picturePickerCellDidAdd?(self) } @objc func removePicture(){ pictureDelegate?.picturePickerCellDidRemove?(self) } //MARK: - 构造函数 override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //控件很少的时候,将UI界面布局写在这里 private func setupUI(){ //1.添加控件 contentView.addSubview(addButton) contentView.addSubview(removeButton) //2.设置布局 addButton.frame = bounds removeButton.snp_makeConstraints { (make) -> Void in make.top.equalTo(contentView.snp_top) make.right.equalTo(contentView.snp_right) } //3.添加监听方法 addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside) removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside) //4.设置填充模式,在imageView上设置才有效果 addButton.imageView?.contentMode = .ScaleAspectFill } //MARK: - 懒加载控件 //添加按钮 private lazy var addButton:UIButton = UIButton(imageName: "compose_pic_add", backImageName: nil) //删除按钮 private lazy var removeButton:UIButton = UIButton(imageName: "compose_photo_close", backImageName: nil) }
mit
f6829442c2d64459bc2a7ab8fdfe5b67
27.458167
140
0.666247
4.303012
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Jetpack/Jetpack Scan/JetpackScanHistoryCoordinator.swift
2
5660
import Foundation class JetpackScanHistoryCoordinator { private let service: JetpackScanService private let view: JetpackScanHistoryView private(set) var model: JetpackScanHistory? let blog: Blog // Filtering var activeFilter: Filter = .all let filterItems = [Filter.all, .fixed, .ignored] private var actionButtonState: ErrorButtonAction? private var isLoading: Bool? private var threats: [JetpackScanThreat]? { guard let threats = model?.threats else { return nil } switch activeFilter { case .all: return threats case .fixed: return threats.filter { $0.status == .fixed } case .ignored: return threats.filter { $0.status == .ignored } } } var sections: [JetpackThreatSection]? init(blog: Blog, view: JetpackScanHistoryView, service: JetpackScanService? = nil, context: NSManagedObjectContext = ContextManager.sharedInstance().mainContext) { self.service = service ?? JetpackScanService(managedObjectContext: context) self.blog = blog self.view = view } // MARK: - Public Methods public func viewDidLoad() { view.showLoading() refreshData() } public func refreshData() { isLoading = true service.getHistory(for: blog) { [weak self] scanObj in self?.refreshDidSucceed(with: scanObj) } failure: { [weak self] error in DDLogError("Error fetching scan object: \(String(describing: error.localizedDescription))") WPAnalytics.track(.jetpackScanError, properties: ["action": "fetch_scan_history", "cause": error.localizedDescription]) self?.refreshDidFail(with: error) } } public func noResultsButtonPressed() { guard let action = actionButtonState else { return } switch action { case .contactSupport: openSupport() case .tryAgain: refreshData() } } private func openSupport() { let supportVC = SupportTableViewController() supportVC.showFromTabBar() } // MARK: - Private: Handling private func refreshDidSucceed(with model: JetpackScanHistory) { isLoading = false self.model = model threatsDidChange() } private func refreshDidFail(with error: Error? = nil) { isLoading = false let appDelegate = WordPressAppDelegate.shared guard let connectionAvailable = appDelegate?.connectionAvailable, connectionAvailable == true else { view.showNoConnectionError() actionButtonState = .tryAgain return } view.showGenericError() actionButtonState = .contactSupport } private func threatsDidChange() { guard let threatCount = threats?.count, threatCount > 0 else { sections = nil switch activeFilter { case .all: view.showNoHistory() case .fixed: view.showNoFixedThreats() case .ignored: view.showNoIgnoredThreats() } return } groupThreats() view.render() } private func groupThreats() { guard let threats = self.threats, let siteRef = JetpackSiteRef(blog: self.blog) else { sections = nil return } self.sections = JetpackScanThreatSectionGrouping(threats: threats, siteRef: siteRef).sections } // MARK: - Filters func changeFilter(_ filter: Filter) { // Don't do anything if we're already on the filter guard activeFilter != filter else { return } activeFilter = filter // Don't refresh UI if we're still loading guard isLoading == false else { return } threatsDidChange() } enum Filter: Int, FilterTabBarItem { case all = 0 case fixed = 1 case ignored = 2 var title: String { switch self { case .all: return NSLocalizedString("All", comment: "Displays all of the historical threats") case .fixed: return NSLocalizedString("Fixed", comment: "Displays the fixed threats") case .ignored: return NSLocalizedString("Ignored", comment: "Displays the ignored threats") } } var accessibilityIdentifier: String { switch self { case .all: return "filter_toolbar_all" case .fixed: return "filter_toolbar_fixed" case .ignored: return "filter_toolbar_ignored" } } var eventProperty: String { switch self { case .all: return "" case .fixed: return "fixed" case .ignored: return "ignored" } } } private enum ErrorButtonAction { case contactSupport case tryAgain } } protocol JetpackScanHistoryView { func render() func showLoading() // Errors func showNoHistory() func showNoFixedThreats() func showNoIgnoredThreats() func showNoConnectionError() func showGenericError() }
gpl-2.0
5cc61ac664d31edf9d999d8c9755798e
25.698113
103
0.55265
5.192661
false
false
false
false
poolqf/FillableLoaders
Source/SpikeLoader.swift
4
1930
// // SpikeLoader.swift // PQFFillableLoaders // // Created by Pol Quintana on 2/8/15. // Copyright (c) 2015 Pol Quintana. All rights reserved. // import Foundation import UIKit open class SpikeLoader: FillableLoader { /// Height of the spike open var spikeHeight: CGFloat = 10.0 internal override func generateLoader() { extraHeight = spikeHeight layoutPath() } internal override func layoutPath() { super.layoutPath() shapeLayer.path = shapePath() } // MARK: Animate internal override func startAnimating() { guard animate else { return } if swing { startswinging() } startMoving(up: true) } //MARK: Spikes internal func shapePath() -> CGMutablePath { let width = loaderView.frame.width let height = loaderView.frame.height let path = CGMutablePath() path.move(to: CGPoint(x: 0, y: height/2)) let widthDiff = width/32 var nextX = widthDiff var nextY = height/2 + spikeHeight for i: Int in 1...32 { path.addLine(to: CGPoint(x: nextX, y: nextY)) nextX += widthDiff nextY += (i%2 == 0) ? spikeHeight : -spikeHeight } path.addLine(to: CGPoint(x: width + 100, y: height/2)) path.addLine(to: CGPoint(x: width + 100, y: height*2)) path.addLine(to: CGPoint(x: 0, y: height*2)) path.closeSubpath() return path } } extension SpikeLoader { open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard animate, let key = anim.value(forKey: "animation") as? String else { return } if key == "up" { startMoving(up: false) } else if key == "down" { startMoving(up: true) } if key == "rotation" { startswinging() } } }
mit
70cdbe3402b751a6b530d79bc622e886
25.081081
91
0.564767
4.063158
false
false
false
false
Shivam0911/IOS-Training-Projects
Delegation Sir Example/Delegation/ViewController.swift
1
3002
// // ViewController.swift // Delegation // // Created by Gurdeep on 03/02/17. // Copyright © 2017 Gurdeep. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var carsTableView: UITableView! let cars : [[String:Any]] = [ ["carName" : "BMW", "carColor" : UIColor.white], ["carName" : "Audi", "carColor" : UIColor.blue], ["carName" : "Ford", "carColor" : UIColor.black], ["carName" : "Porsche", "carColor" : UIColor.red], ["carName" : "Tata", "carColor" : UIColor.yellow] ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.carsTableView.dataSource = self self.carsTableView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print(#function) print(section) print(cars.count) return cars.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print(#function) print("indexPath.section : \(indexPath.section)") print("indexPath.row : \(indexPath.row)") guard let cell = tableView.dequeueReusableCell(withIdentifier: "CarCellID", for: indexPath) as? CarCell else { fatalError("CELL NOT FOUND") } cell.carNameLabel.text = cars[indexPath.row]["carName"] as? String ?? "" cell.carImageView.backgroundColor = cars[indexPath.row]["carColor"] as? UIColor ?? UIColor.gray return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("Row Selected : \(indexPath.row)") guard let cell = tableView.cellForRow(at: indexPath) as? CarCell else { return } cell.carImageView.backgroundColor = UIColor.brown } } class CarCell: UITableViewCell { @IBOutlet weak var carImageView: UIImageView! @IBOutlet weak var carNameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Equivalent to "viewDidLoad" for UIVIewController // Manipulate UI accordingly carImageView.layer.cornerRadius = carImageView.layer.bounds.size.width/2 } override func prepareForReuse() { super.prepareForReuse() carImageView.image = nil carImageView.backgroundColor = UIColor.white carNameLabel.text = "" } }
mit
ff62c087f49941aed5da84e42aa23baa
28.135922
118
0.610796
4.855987
false
false
false
false
Ramesh-P/on-the-spot
On the Spot/PlaceTabBarController+Helper.swift
1
1527
// // PlaceTabBarController+Helper.swift // On the Spot // // Created by Ramesh Parthasarathy on 5/16/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation import UIKit import CoreData // MARK: PlaceTabBarController+Helper extension PlaceTabBarController { // MARK: Class Functions func getFontSize() { // Get screen height let screenHeight = UIScreen.main.bounds.size.height // Get font size switch screenHeight { case Constants.ScreenHeight.phoneSE: titleFontSize = Constants.FontSize.Title.phoneSE case Constants.ScreenHeight.phone: titleFontSize = Constants.FontSize.Title.phone case Constants.ScreenHeight.phonePlus: titleFontSize = Constants.FontSize.Title.phonePlus default: break } } func displayTitle() { // Set title to selected place type self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name: "Roboto-Medium", size: titleFontSize)!] self.title = typeName } func displayError(_ message: String?) { // Display Error let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } }
mit
1bac8bbdc4f5c5fbc25d024a30da6023
29.52
145
0.657929
5.05298
false
false
false
false
curoo/ios-keychain
ConfidoIOS/KeyChainItem.swift
3
5431
// // KeyChainItem.swift // ExpendSecurity // // Created by Rudolph van Graan on 18/08/2015. // // import Foundation import Security // Update -> Add writers for functions, populate separate dictionary, something calls update /** Abstract Item that has a securityClass and attributes. Two classes derive from it. KeychainItem that represents actual objects in the IOS Keychain and KeychainProperties that describe the attributes of either a IOS Keychain search (the input dictionary) or the attributes of an object (such as a KeychainKey that could be generated or imported. */ open class AbstractItem: KeychainItemClass, KeyChainAttributeStorage { open fileprivate(set) var securityClass: SecurityClass //A dictionary of IOS Keychain attributes keyed by their kSecAttr constants and stored in the format the IOS Keychain requires them open var attributes : [String : AnyObject] = [ : ] public init(securityClass: SecurityClass) { self.securityClass = securityClass } init(securityClass: SecurityClass, byCopyingAttributes attributes: KeyChainAttributeStorage? ) { self.securityClass = securityClass self.initAttributes(attributes) } // Initialises the AbstractItem with the contents from an IOS Keychain Attribute Dictionary init(securityClass: SecurityClass, SecItemAttributes attributes: SecItemAttributes) { if let secClass: AnyObject = attributes[String(kSecClass)] { self.securityClass = SecurityClass.securityClass(secClass)! } else { self.securityClass = securityClass } self.initAttributes(attributes as NSDictionary) } func initAttributes(_ attributes: KeyChainAttributeStorage?) { if let attributes = attributes { self.attributes = attributes.attributes } } func initAttributes(_ keychainAttributes: NSDictionary) { for (key, object) in keychainAttributes { // -TODO: This method should only copy the attributes that belongs to the item and not everything as yet. Some types (KeychainIdentity is composed of KeychainCertificate and the KeychainIdentify object should not store the KeychainCertificate's properties, etc. if let key = key as? String { attributes[key] = object as AnyObject? } } } } open class KeychainItem: AbstractItem, KeychainCommonClassProperties { open class func itemFromAttributes(_ securityClass: SecurityClass, SecItemAttributes attributes: SecItemAttributes) throws -> KeychainItem { switch securityClass { case .identity: return try KeychainIdentity.identityFromAttributes(SecItemAttributes: attributes) case .key: return try KeychainKey.keychainKeyFromAttributes(SecItemAttributes: attributes) case .certificate : return try KeychainCertificate.keychainCertificateFromAttributes(SecItemAttributes: attributes) default: throw KeychainError.unimplementedSecurityClass } } public override init(securityClass: SecurityClass) { super.init(securityClass: securityClass) } override init(securityClass: SecurityClass, byCopyingAttributes attributes: KeyChainAttributeStorage? ) { super.init(securityClass: securityClass, byCopyingAttributes: attributes) } override init(securityClass: SecurityClass, SecItemAttributes attributes: SecItemAttributes) { super.init(securityClass: securityClass, SecItemAttributes: attributes) } open func specifierMatchingProperties() -> Set<String> { return kCommonMatchingProperties } } open class KeychainDescriptor : AbstractItem, KeychainMatchable { /** Initialises keychain properties from a KeychainItem :param: keychainItem :returns: a new instance of KeychainDescriptor. */ public init(keychainItem: KeychainItem) { super.init(securityClass: keychainItem.securityClass) for matchingProperty in keychainItem.specifierMatchingProperties() { if let value: AnyObject = keychainItem[matchingProperty] { attributes[matchingProperty] = value } } } public init(descriptor: KeychainDescriptor) { super.init(securityClass: descriptor.securityClass) self.attributes = descriptor.attributes } override init(securityClass: SecurityClass, byCopyingAttributes attributes: KeyChainAttributeStorage? ) { super.init(securityClass: securityClass, byCopyingAttributes: attributes) } public init(securityClass: SecurityClass, itemLabel: String? = nil) { super.init(securityClass: securityClass) if let itemLabel = itemLabel { attributes[String(kSecAttrLabel)] = itemLabel as AnyObject? } } /** Provides the dictionary of IOS Keychain attributes that will be used to match IOS Keychain Items against. This is the dictionary that is passed to SecItemCopyMatching() :returns: a dictionary of IOS Keychain Attributes. */ //TODO: Rename this to iosKeychainMatchDictionary() open func keychainMatchPropertyValues() -> [ String: AnyObject ] { var dictionary : [ String : AnyObject] = [ : ] dictionary[String(kSecClass)] = SecurityClass.kSecClass(securityClass) for (attribute, value) in attributes { dictionary[attribute] = value } return dictionary } }
mit
436de29e05951f4de542e123a7322eee
38.642336
273
0.71902
5.128423
false
false
false
false
thatseeyou/SpriteKitExamples.playground
Pages/BouncingBall.xcplaygroundpage/Contents.swift
1
3219
/*: ### Edge에 physics body를 설정할 수 있다. - Scene의 경계에 physics body를 설정 - Gravity의 영향을 받지 않게 설정 - physicsWorld.speed를 이용해서 simulation 속도를 조절 */ import UIKit import SpriteKit class GameScene: SKScene { override func didMove(to view: SKView) { // SKScene의 경계에 physicsbody 설정 self.physicsBody = SKPhysicsBody(edgeLoopFrom: self.frame) //self.physicsWorld.gravity = CGVectorMake(0, 0) self.physicsWorld.speed = 2 // Make ball let ball1 = ballWithRadius(10) do { ball1.fillColor = #colorLiteral(red: 0.7540004253387451, green: 0, blue: 0.2649998068809509, alpha: 1) ball1.position = CGPoint(x: 100,y: 10) ball1.physicsBody?.velocity = CGVector(dx: 100, dy: 0) } let ball2 = ballWithRadius(20) do { ball2.fillColor = #colorLiteral(red: 0.2818343937397003, green: 0.5693024396896362, blue: 0.1281824260950089, alpha: 1) ball2.position = CGPoint(x: 100,y: 100) ball2.physicsBody?.velocity = CGVector(dx: 0, dy: 100) } let ball3 = ballWithRadius(30) do { ball3.fillColor = #colorLiteral(red: 0.4120420813560486, green: 0.8022739887237549, blue: 0.9693969488143921, alpha: 1) ball3.position = CGPoint(x: 110,y: 400) ball3.physicsBody?.velocity = CGVector(dx: 0, dy: -100) } addChild(ball1) addChild(ball2) addChild(ball3) } func ballWithRadius(_ radius:CGFloat) -> SKShapeNode { let ballShape = SKShapeNode(circleOfRadius: radius) do { ballShape.physicsBody = SKPhysicsBody(circleOfRadius: radius) ballShape.physicsBody?.allowsRotation = true ballShape.physicsBody?.affectedByGravity = false ballShape.physicsBody?.density = 1.0 ballShape.physicsBody?.friction = 0.0 ballShape.physicsBody?.angularDamping = 0 ballShape.physicsBody?.linearDamping = 0 ballShape.physicsBody?.restitution = 1.0 ballShape.physicsBody?.velocity = CGVector(dx: 100, dy: 100) //ballShape.fillColor = [#Color(colorLiteralRed: 0.6637836694717407, green: 0.4033902585506439, blue: 0.08084951341152191, alpha: 1)#] //ballShape.position = CGPointMake(100,100) } let label = SKLabelNode(text: "\(radius)") do { label.fontSize = 10 } ballShape.addChild(label) return ballShape } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // add SKView do { let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480)) skView.showsFPS = true //skView.showsNodeCount = true skView.ignoresSiblingOrder = true let scene = GameScene(size: CGSize(width: 320, height: 480)) scene.scaleMode = .aspectFit skView.presentScene(scene) self.view.addSubview(skView) } } } PlaygroundHelper.showViewController(ViewController())
isc
2b99e27feb16440c90d742248d7c8e78
32.37234
146
0.612369
3.970886
false
false
false
false
jyunderwood/Mazing-Swift
Mazing.playground/Sources/BinaryTreeMaze.swift
1
715
// // BinaryTreeMaze.swift // Mazing // // Created by Jonathan on 7/17/15. // Copyright © 2015 Jonathan Underwood. All rights reserved. // import Foundation public class BinaryTreeMaze { public static func on(grid: Grid) { grid.eachCell { cell in var neighbors = [Cell]() if let northCell = cell.north { neighbors.append(northCell) } if let eastCell = cell.east { neighbors.append(eastCell) } if neighbors.count != 0 { let randomIndex = Int(arc4random_uniform(UInt32(neighbors.count))) let neighbor = neighbors[randomIndex] cell.link(neighbor, bidirectionally: true) } } } }
mit
6283ddc140b672d17f132289c2ac97b1
27.56
82
0.595238
4.056818
false
false
false
false
AceWangLei/BYWeiBo
BYWeiBo/AppDelegate.swift
1
4531
// // AppDelegate.swift // BYWeiBo // // Created by wanglei on 16/1/25. // Copyright © 2016年 lit. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // 1. 初始化 window window = UIWindow(frame: UIScreen.mainScreen().bounds) // 2. 设置根控制器 /** 首先判断是否登陆 - 没有登陆:直接跳转到首页 - 有登陆:做判断是否有新版本的逻辑 */ //window?.rootViewController = BYNewFeatureViewController() //window?.rootViewController = BYMainViewController() window?.rootViewController = BYUserAccountViewModel.sharedViewModel.isLogon ?defaultViewControl() : BYMainViewController() // 3. 成为主窗口并显示 window?.makeKeyAndVisible() // 4. 注册通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootVC:", name: BYSwitchRootVCNotification, object: nil) return true } // 切换根控制器的触发方法 @objc private func switchRootVC(noti: NSNotification) { if noti.object != nil { // 取到通知里面的 obj 如果不为 nil,就代表 OAuth 发的, 直接跳转欢迎界面 window?.rootViewController = BYWelcomeViewController() } else { window?.rootViewController = BYMainViewController() } } // 判断是否有新版本 func defaultViewControl() -> UIViewController { if hasNewVersion() { return BYNewFeatureViewController() } else { return BYWelcomeViewController() } } func hasNewVersion() -> Bool { let versionKey = "version" // 1. 获取当前应用版本 let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]! as! String // 2. 获取沙盒中的版本号 (如果沙盒中没有版本号的话,就代表第一次使用,直接返回 true) let sanboxVersion = NSUserDefaults.standardUserDefaults().stringForKey(versionKey) // 3. 判断两个版本号返回不同的结果 // 如果当前版本号与沙盒版本号相同,就代表不是新版本 if currentVersion == sanboxVersion { return false } // 新版本号保存到沙盒中 NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey) return true; } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
32ecb1b2b5853a2f7b2208d1e6e14a0b
36.618182
285
0.673997
5.244613
false
false
false
false
Irvel/Actionable-Screenshots
ActionableScreenshots/ActionableScreenshots/AllScreenshotsViewController.swift
1
12918
// // SecondViewController.swift // ActionableScreenshots // // Created by Jesus Galvan on 10/21/17. // Copyright © 2017 Jesus Galvan. All rights reserved. // import UIKit import Photos import RealmSwift // Collection depending on environment #if (arch(i386) || arch(x86_64)) && os(iOS) // Simulator private let collectionTitle = "Camera Roll" #else // Device private let collectionTitle = "Screenshots" #endif class AllScreenshotsViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate, UISearchDisplayDelegate, UIWithCollection { func reloadCollection() { filteredScreenshots = Array(filteredScreenshotsQuery!) collectionView.reloadData() } // MARK: Class variables private let reuseIdentifier = "Cell" private let SPACE_BETWEEN_CELLS: CGFloat = 3 var screenshotsCollection: Results<Screenshot>? var filteredScreenshotsQuery: Results<Screenshot>? var filteredScreenshots: Array<Screenshot>? var lastProcessed = Date(timeIntervalSince1970: 0) var cellSize: CGSize! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var lbNoPhotos: UILabel! // MARK: Class overrides override func viewDidLoad() { super.viewDidLoad() print(Realm.Configuration.defaultConfiguration.fileURL!) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) self.tabBarController?.tabBar.layer.shadowOpacity = 0.2 self.tabBarController?.tabBar.layer.shadowRadius = 5.0 self.searchBar.delegate = self let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = SPACE_BETWEEN_CELLS collectionView!.collectionViewLayout = layout searchBar.autocapitalizationType = .none // Register callback refresh screenshots when resuming from background NotificationCenter.default.addObserver(self, selector:#selector(refreshScreenshots), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) refreshScreenshots() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewDidAppear(_ animated: Bool) { if searchBar.text == "" { filteredScreenshotsQuery = screenshotsCollection?.sorted(byKeyPath: "creationDate", ascending: false) filteredScreenshots = Array(filteredScreenshotsQuery!) } else { let predicateQuery = NSPredicate(format: "text CONTAINS[cd] %@", searchBar.text!) let predicateTag = NSPredicate(format: "ANY tags.id CONTAINS[cd] %@", searchBar.text!) filteredScreenshotsQuery = screenshotsCollection?.filter(predicateQuery) let tagScreenshotsQuery = screenshotsCollection?.filter(predicateTag) filteredScreenshots = (Array(tagScreenshotsQuery!) + Array(filteredScreenshotsQuery!)).orderedSet } self.collectionView.reloadData() } deinit { NotificationCenter.default.removeObserver(self) } // MARK: Photo retrieval @objc func refreshScreenshots() { let realm = try! Realm() screenshotsCollection = realm.objects(Screenshot.self) filteredScreenshotsQuery = screenshotsCollection?.sorted(byKeyPath: "creationDate", ascending: false) filteredScreenshots = Array(filteredScreenshotsQuery!) lastProcessed = (screenshotsCollection?.filter(NSPredicate(format: "processed = true")).max(ofProperty: "creationDate")) ?? Date(timeIntervalSince1970: 0) initializeScreenshotResults() self.collectionView.reloadData() } func initializeScreenshotResults() { switch PHPhotoLibrary.authorizationStatus() { case .authorized: loadScreenshotAlbum() break case .denied, .restricted: alertRequestAccess() break case .notDetermined: PHPhotoLibrary.requestAuthorization({(newStatus) -> Void in if newStatus == .authorized { self.loadScreenshotAlbum() } else { self.alertRequestAccess() } }) } } func loadScreenshotAlbum() { let realm = try! Realm() let nonProcessedScreenshots = getNonProcessedScreenshots() if nonProcessedScreenshots.count > 0 { for index in 0...nonProcessedScreenshots.count - 1 { let screenshot = Screenshot() screenshot.id = nonProcessedScreenshots[index].localIdentifier screenshot.creationDate = nonProcessedScreenshots[index].creationDate! try! realm.write { realm.add(screenshot, update: true) } } DispatchQueue.global(qos: .userInitiated).async { self.processScreenshots(screenshots: nonProcessedScreenshots) } } DispatchQueue.main.async { self.filteredScreenshots = Array(self.filteredScreenshotsQuery!) self.collectionView.reloadData() } } /** Present a dialog for requesting access to Photos */ func alertRequestAccess() { let alert = UIAlertController(title: "Error", message: "This app is not authorized to access your photos, please give access to continue.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) } } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } /** Returns a list of image assets that have not been classified for information */ func getNonProcessedScreenshots() -> PHFetchResult<PHAsset> { var notProcessed: PHFetchResult<PHAsset>! let smartAlbums:PHFetchResult<PHAssetCollection> = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil) smartAlbums.enumerateObjects({(collection, index, object) in if collection.localizedTitle == collectionTitle { let fetchOptions = PHFetchOptions() fetchOptions.predicate = NSPredicate(format: "creationDate > %@", self.lastProcessed as CVarArg) fetchOptions.sortDescriptors = [NSSortDescriptor(key:"creationDate", ascending: true)] notProcessed = PHAsset.fetchAssets(in: collection, options: fetchOptions) } }) return notProcessed } // MARK: Functions for SearchBar func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText == "" { filteredScreenshotsQuery = screenshotsCollection?.sorted(byKeyPath: "creationDate", ascending: false) filteredScreenshots = Array(filteredScreenshotsQuery!) } else { let predicateQuery = NSPredicate(format: "text CONTAINS[cd] %@", searchText) let predicateTag = NSPredicate(format: "ANY tags.id CONTAINS[cd] %@", searchText) filteredScreenshotsQuery = screenshotsCollection?.filter(predicateQuery) let tagScreenshotsQuery = screenshotsCollection?.filter(predicateTag) filteredScreenshots = (Array(tagScreenshotsQuery!) + Array(filteredScreenshotsQuery!)).orderedSet } collectionView.reloadData() } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() } @objc func dismissKeyboard() { searchBar.resignFirstResponder() } // MARK: Functions for CollectionView func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // Compute the dimension of a cell for an NxN layout with space S between // cells. Take the collection view's width, subtract (N-1)*S points for // the spaces between the cells, and then divide by N to find the final // dimension for the cell's width and height. let cellsAcross: CGFloat = 3 let dim = (collectionView.bounds.width - (cellsAcross - 1) * SPACE_BETWEEN_CELLS) / cellsAcross cellSize = CGSize(width: dim, height: dim) return CGSize(width: dim, height: dim) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { lbNoPhotos.isHidden = (filteredScreenshots?.count != 0) if let filtered = filteredScreenshots { return filtered.count } return 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell let screenshot = filteredScreenshots![indexPath.row] // Configure the cell let fetchOptions = PHImageRequestOptions() fetchOptions.isSynchronous = true fetchOptions.resizeMode = .fast let currentImg = screenshot.getImage(width: cellSize.width, height: cellSize.height, contentMode: .aspectFill, fetchOptions: fetchOptions) cell.layer.shouldRasterize = true cell.layer.rasterizationScale = UIScreen.main.scale cell.imgView.image = currentImg cell.layer.cornerRadius = 3.1 if screenshot.processed { cell.activityIndicator.stopAnimating() } else { cell.activityIndicator.startAnimating() } return cell } // MARK: Navigation override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { let selectedImageIndex = (collectionView.indexPathsForSelectedItems!.first?.row)! return filteredScreenshots![selectedImageIndex].processed } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let destinationView = segue.destination as! DetailViewController let selectedImageIndex = (collectionView.indexPathsForSelectedItems!.first?.row)! destinationView.screenshot = filteredScreenshots![selectedImageIndex] destinationView.previousView = self } @IBAction func unwindDetail(segueUnwind: UIStoryboardSegue) { } // MARK: Processing /** Extracts semantic information from a set of screenshots Extracts text with OCR of those screenshots that contain text and uses the visual content of the image to identify in which category does it belong. - Parameters: - screenshots: A set of PHAsset to fetch the images from */ func processScreenshots(screenshots: PHFetchResult<PHAsset>) { let ocrProcessor = OCRProcessor() let classifier = ImageClassifier() for index in 0...screenshots.count - 1 { let extractedText = ocrProcessor.extractText(from: screenshots[index]) let mlCategories = classifier.classify(asset: screenshots[index]) let realm = try! Realm() let screenshot = realm.object(ofType: Screenshot.self, forPrimaryKey: screenshots[index].localIdentifier) ?? Screenshot() try! realm.write() { if screenshot.id == nil { screenshot.id = screenshots[index].localIdentifier realm.add(screenshot, update: true) } screenshot.text = extractedText screenshot.creationDate = screenshots[index].creationDate! screenshot.processed = true } if mlCategories.count > 0 { print("Identified the following categories: \(mlCategories)") screenshot.addTags(from: mlCategories) } DispatchQueue.main.async { self.collectionView.reloadData() } } } } extension Array where Element: Hashable { var orderedSet: Array { var set = Set<Element>() return filter { set.insert($0).inserted } } }
gpl-3.0
e846164cfc7846e9b3f48426fb6fe49e
38.142424
208
0.655957
5.565274
false
false
false
false
cohena100/Shimi
Shimi/AppDelegate.swift
1
3286
// // AppDelegate.swift // Shimi // // Created by Pango-mac on 20/05/2017. // Copyright © 2017 TsiliGiliMiliTili. All rights reserved. // import UIKit import SwiftyBeaver @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupLogging() setupModel() setupWindow() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } fileprivate func setupLogging() { let console = ConsoleDestination() let platform = SBPlatformDestination(appID: "AOBXnj", appSecret: "fnpcpq6qajfql1dUtjwgeyKxbP3bWesj", encryptionKey: "pirkf0fu7tiO5xdnlezstzotifh179s5") #if DEBUG #else platform.minLevel = .info #endif SwiftyBeaver.addDestination(console) SwiftyBeaver.addDestination(platform) } fileprivate func setupModel() { let arguments = ProcessInfo.processInfo.arguments if arguments.contains("-test") { Model.sharedInstance.proxies = ProxiesMock() } } fileprivate func setupWindow() { var vc = UIViewController() #if DEBUG if (NSClassFromString("XCTest") == nil) { vc = MainViewController() } #else vc = MainViewController() #endif window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.rootViewController = UINavigationController(rootViewController: vc) } }
mit
c4d0e3a5969a967a9e0f8be3130de605
40.0625
285
0.703196
5.230892
false
false
false
false
FabrizioBrancati/BFKit-Swift
Example/BFKitExample/AppDelegate.swift
1
4955
// // AppDelegate.swift // BFKitDemo // BFKit // // The MIT License (MIT) // // Copyright (c) 2015 - 2018 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit // MARK: - Global variables let BFKitArray = [ "BFApp", "BFBiometrics", "BFButton", "BFDataStructures", "BFLog", "BFPassword", "BFSystemSound", "BFTextField"] let UIKitArray = [ "UIButton", "UIColor", "UIDevice", "UIFont", "UIImage", "UIImageView", "UILabel", "UINavigationBar", "UIScreen", "UIScrollView", "UITableView", "UITextField", "UITextView", "UIToolbar", "UIView", "UIWindow"] let FoundationArray = [ "Array", "Collection", "Data", "Date", "FileManager", "Number", "NSObject", "Thread", "String"] let InfoViewControllerSegueID = "InfoViewControllerSegueID" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // MARK: - Variables var window: UIWindow? // MARK: - Functions func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor(red: 0.9218, green: 0.565, blue: 0.139, alpha: 1.0)] UINavigationBar.appearance().tintColor = UIColor(red: 0.9218, green: 0.565, blue: 0.139, alpha: 1.0) UITabBar.appearance().tintColor = UIColor(red: 0.9218, green: 0.565, blue: 0.139, alpha: 1.0) UIBarButtonItem.appearance().tintColor = UIColor(red: 0.9218, green: 0.565, blue: 0.139, alpha: 1.0) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
353f0749e619e2369f00f49245217c53
44.87963
285
0.636731
5.188482
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/ForumFloorData.swift
1
1556
// // ForumFloorData.swift // DingshanSwift // // Created by song jufeng on 15/9/9. // Copyright (c) 2015年 song jufeng. All rights reserved. // import Foundation class ForumFloorData : NSObject { var floorId:Int = 0 var contentText:String = "" var isLordFloor:Bool = false var rowHeight:CGFloat = 0.0 var contentAttrString:NSAttributedString? required override init() { super.init() } init( dic : [NSObject: AnyObject]){ if let s = dic["floor_id"] as? String { if let n = Int(s){ floorId = n } }else{ if let n = dic["floor_id"] as? NSNumber{ floorId = n.integerValue } } if let tmp = dic["floor_content"] as? String{ contentText = tmp } } func getCalculatedRowHeight() -> CGFloat { if (rowHeight > 0){ return rowHeight }else { return self.calculateRowHeight() } } func calculateRowHeight() -> CGFloat { // 正文与图片 let widthLimit = isLordFloor ? kForumLordFloorContentWidth : kForumFollowingFloorContentWidth let sz:CGSize = TTTAttributedLabel.sizeThatFitsAttributedString(contentAttrString, withConstraints: CGSizeMake(widthLimit, CGFloat.max), limitedToNumberOfLines: UInt.max) rowHeight = sz.height print("----------------calculateRowHeight= \(sz)") return max(rowHeight, kMinForumLordFloorContentHieght) } }
mit
b1c3d1eed13a1b74d9896341dba28238
26.105263
178
0.580311
4.475362
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/CacheDBWriting.swift
1
4940
import Foundation enum SaveResult { case success case failure(Error) } enum CacheDBWritingResultWithURLRequests { case success([URLRequest]) case failure(Error) } enum CacheDBWritingResultWithItemAndVariantKeys { case success([CacheController.ItemKeyAndVariant]) case failure(Error) } enum CacheDBWritingResult { case success case failure(Error) } enum CacheDBWritingMarkDownloadedError: Error { case cannotFindCacheGroup case cannotFindCacheItem case unableToDetermineItemKey case missingMOC } enum CacheDBWritingRemoveError: Error { case cannotFindCacheGroup case cannotFindCacheItem case missingMOC } protocol CacheDBWriting: CacheTaskTracking { var context: NSManagedObjectContext { get } typealias CacheDBWritingCompletionWithURLRequests = (CacheDBWritingResultWithURLRequests) -> Void typealias CacheDBWritingCompletionWithItemAndVariantKeys = (CacheDBWritingResultWithItemAndVariantKeys) -> Void func add(url: URL, groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithURLRequests) func add(urls: [URL], groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithURLRequests) func shouldDownloadVariant(itemKey: CacheController.ItemKey, variant: String?) -> Bool func shouldDownloadVariant(urlRequest: URLRequest) -> Bool func shouldDownloadVariantForAllVariantItems(variant: String?, _ allVariantItems: [CacheController.ItemKeyAndVariant]) -> Bool var fetcher: CacheFetching { get } // default implementations func remove(itemAndVariantKey: CacheController.ItemKeyAndVariant, completion: @escaping (CacheDBWritingResult) -> Void) func remove(groupKey: String, completion: @escaping (CacheDBWritingResult) -> Void) func fetchKeysToRemove(for groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithItemAndVariantKeys) func markDownloaded(urlRequest: URLRequest, response: HTTPURLResponse?, completion: @escaping (CacheDBWritingResult) -> Void) } extension CacheDBWriting { func fetchKeysToRemove(for groupKey: CacheController.GroupKey, completion: @escaping CacheDBWritingCompletionWithItemAndVariantKeys) { context.perform { guard let group = CacheDBWriterHelper.cacheGroup(with: groupKey, in: self.context) else { completion(.failure(CacheDBWritingMarkDownloadedError.cannotFindCacheGroup)) return } guard let cacheItems = group.cacheItems as? Set<CacheItem> else { completion(.failure(CacheDBWritingMarkDownloadedError.cannotFindCacheItem)) return } let cacheItemsToRemove = cacheItems.filter({ (cacheItem) -> Bool in return cacheItem.cacheGroups?.count == 1 }) completion(.success(cacheItemsToRemove.compactMap { CacheController.ItemKeyAndVariant(itemKey: $0.key, variant: $0.variant) })) } } func remove(itemAndVariantKey: CacheController.ItemKeyAndVariant, completion: @escaping (CacheDBWritingResult) -> Void) { context.perform { guard let cacheItem = CacheDBWriterHelper.cacheItem(with: itemAndVariantKey.itemKey, variant: itemAndVariantKey.variant, in: self.context) else { completion(.failure(CacheDBWritingRemoveError.cannotFindCacheItem)) return } self.context.delete(cacheItem) CacheDBWriterHelper.save(moc: self.context) { (result) in switch result { case .success: completion(.success) case .failure(let error): completion(.failure(error)) } } } } func remove(groupKey: CacheController.GroupKey, completion: @escaping (CacheDBWritingResult) -> Void) { context.perform { guard let cacheGroup = CacheDBWriterHelper.cacheGroup(with: groupKey, in: self.context) else { completion(.failure(CacheDBWritingRemoveError.cannotFindCacheItem)) return } self.context.delete(cacheGroup) CacheDBWriterHelper.save(moc: self.context) { (result) in switch result { case .success: completion(.success) case .failure(let error): completion(.failure(error)) } } } } func shouldDownloadVariant(urlRequest: URLRequest) -> Bool { guard let itemKey = fetcher.itemKeyForURLRequest(urlRequest) else { return false } let variant = fetcher.variantForURLRequest(urlRequest) return shouldDownloadVariant(itemKey: itemKey, variant: variant) } }
mit
3755d6c35a5ef9342deb5c260706c6dc
38.206349
157
0.673279
4.935065
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Related Missions/RelatedMissionsView.swift
1
2922
// // RelatedMissionsView.swift // MEGameTracker // // Created by Emily Ivie on 5/22/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit final public class RelatedMissionsView: SimpleArrayDataRow { lazy var dummyMissions: [Mission] = { if let mission = Mission.getDummy() { return [mission] } return [] }() public var missions: [Mission] { if UIWindow.isInterfaceBuilder { return dummyMissions } return controller?.relatedMissions ?? [] } public var controller: RelatedMissionsable? { didSet { reloadData() } } override var heading: String? { return "Related Missions" } override var cellNibs: [String] { return ["MissionRow"] } override var rowCount: Int { return missions.count } override var viewController: UIViewController? { return controller as? UIViewController } override func setupRow(cell: UITableViewCell, indexPath: IndexPath) { guard missions.indices.contains((indexPath as NSIndexPath).row) else { return } _ = (cell as? MissionRow)?.define(mission: missions[(indexPath as NSIndexPath).row], origin: viewController) } override func identifierForIndexPath(_ indexPath: IndexPath) -> String { return cellNibs[0] } override func openRow(indexPath: IndexPath, sender: UIView?) { guard missions.indices.contains((indexPath as NSIndexPath).row) else { return } let mission = missions[(indexPath as NSIndexPath).row] startParentSpinner() let bundle = Bundle(for: type(of: self)) if let flowController = UIStoryboard(name: "MissionsFlow", bundle: bundle) .instantiateViewController(withIdentifier: "Mission") as? MissionsFlowController, let missionController = flowController.includedController as? MissionController { // configure detail missionController.mission = mission self.viewController?.navigationController?.pushViewController(flowController, animated: true) } self.stopParentSpinner() } override func startListeners() { guard !UIWindow.isInterfaceBuilder else { return } Mission.onChange.cancelSubscription(for: self) _ = Mission.onChange.subscribe(with: self) { [weak self] changed in if let newRow = changed.object ?? Mission.get(id: changed.id) { DispatchQueue.main.async { if let index = self?.controller?.relatedMissions.firstIndex(where: { $0.id == newRow.id }) { self?.controller?.relatedMissions[index] = newRow let reloadRows: [IndexPath] = [IndexPath(row: index, section: 0)] self?.reloadRows(reloadRows) } // make sure controller listens here and updates its own object's decisions list } } } } override func removeListeners() { guard !UIWindow.isInterfaceBuilder else { return } Mission.onChange.cancelSubscription(for: self) } }
mit
a7891a5e804ecff6b828688ca18da730
35.061728
112
0.681274
4.327407
false
false
false
false
Srinija/SAGeometry
Example/SAGeometry/ViewController.swift
1
13925
// // ViewController.swift // SwiftGeometry // // Created by Srinija on 09/09/17. // Copyright © 2017 Srinija. All rights reserved. // import UIKit import SAGeometry class ViewController: UIViewController { let geometry = SAGeometry() @IBOutlet weak var quadStatus: UILabel! @IBOutlet weak var pointStatus: UILabel! @IBOutlet weak var lineStatus: UILabel! let quadBorder = CAShapeLayer() var quadVertices = [UIView]() var quadLabels = [UILabel]() let line1 = CAShapeLayer() var line1labels = [UILabel]() var line1Vertices = [UIView]() var line1Length :UILabel? = nil var freeVertex = UIView() var freeLabel = UILabel() var selectedIndex : Int? var shape: String? var oldPoint = CGPoint(x: 0, y: 0) var graph:Graph! override func viewWillAppear(_ animated: Bool) { graph = self.view as! Graph line1.strokeColor = UIColor.black.cgColor quadBorder.strokeColor = UIColor.black.cgColor quadBorder.fillColor = nil setUpGestureRecognizer() addElementsToGraph() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() quadBorder.frame = self.view.bounds line1.frame = self.view.bounds plot() } func addElementsToGraph(){ view.layer.addSublayer(quadBorder) view.layer.addSublayer(line1) view.addSubview(freeVertex) for i in 0...6{ let vertex = UIView() vertex.alpha = 0.65 vertex.layer.cornerRadius = 10 vertex.frame.size = CGSize(width: 20, height: 20) vertex.layer.borderWidth = 1 vertex.layer.borderColor = UIColor.white.cgColor vertex.backgroundColor = UIColor.black let label = UILabel() label.textColor = UIColor.blue label.font = label.font.withSize(10) label.sizeToFit() label.translatesAutoresizingMaskIntoConstraints = false var quadPoints = [CGPoint(x: 10, y: 140), CGPoint(x:60,y:140), CGPoint(x: 60, y: 90), CGPoint(x: 10, y: 90)] var linePoints = [CGPoint(x:20, y:30), CGPoint(x:80, y:70)] var freePoint = CGPoint(x: 50, y: 50) switch i{ case 0: freePoint = freePoint.applying(graph.chartTransform!) vertex.center = freePoint freeVertex = vertex freeLabel = label label.text = "P" case 1: linePoints[0] = linePoints[0].applying(graph.chartTransform!) vertex.center = linePoints[0] line1Vertices.append(vertex) line1labels.append(label) label.text = "L" case 2: linePoints[1] = linePoints[1].applying(graph.chartTransform!) vertex.center = linePoints[1] line1Vertices.append(vertex) line1labels.append(label) label.text = "M" case 3: quadPoints[0] = quadPoints[0].applying(graph.chartTransform!) vertex.center = quadPoints[0] quadVertices.append(vertex) quadLabels.append(label) label.text = "A" case 4: quadPoints[1] = quadPoints[1].applying(graph.chartTransform!) vertex.center = quadPoints[1] quadVertices.append(vertex) quadLabels.append(label) label.text = "B" case 5: quadPoints[2] = quadPoints[2].applying(graph.chartTransform!) vertex.center = quadPoints[2] quadVertices.append(vertex) quadLabels.append(label) label.text = "C" default: quadPoints[3] = quadPoints[3].applying(graph.chartTransform!) vertex.center = quadPoints[3] quadVertices.append(vertex) quadLabels.append(label) label.text = "D" } view.addSubview(vertex) let trans = vertex.center.applying(graph.chartTransform!.inverted()) // label.text = "(\(Int(trans.x)),\(Int(trans.y)))" label.text = "\(label.text ?? "")(\(Int(trans.x)),\(Int(trans.y)))" view.addSubview(label) let verticalSpace = NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: vertex, attribute: .bottom, multiplier: 1, constant: 5) let leading = NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: vertex, attribute: .leading, multiplier: 1, constant: 0) NSLayoutConstraint.activate([verticalSpace, leading]) } } func setUpGestureRecognizer(){ let gestureRecognizer = UIPanGestureRecognizer.init(target: self, action: #selector(ViewController.panGesture)) view.addGestureRecognizer(gestureRecognizer) } @objc func panGesture(gesture : UIPanGestureRecognizer){ let point = gesture.location(in: view) if(gesture.state == UIGestureRecognizerState.began){ selectedIndex = nil var minDistance = CGFloat.greatestFiniteMagnitude for i in 0...3{ let distance = geometry.distanceBetweenPoints(point1: point, point2: quadVertices[i].center) if(distance < minDistance){ minDistance = distance shape = "quad" selectedIndex = i } } for i in 0...1{ let distance = geometry.distanceBetweenPoints(point1: point, point2: line1Vertices[i].center) if(distance < minDistance){ minDistance = distance shape = "line1" selectedIndex = i } } let distance = geometry.distanceBetweenPoints(point1: point, point2: freeVertex.center) if(distance < minDistance){ minDistance = distance shape = "point" selectedIndex = 0 } oldPoint = point } if let selectedIndex = selectedIndex { var current = CGPoint() switch shape!{ case "quad": current = quadVertices[selectedIndex].center case "line1": current = line1Vertices[selectedIndex].center default: current = freeVertex.center } let newPoint = CGPoint(x: current.x + (point.x - oldPoint.x) , y: current.y + (point.y - oldPoint.y) ) oldPoint = point let inverted = round(newPoint.applying(graph.chartTransform!.inverted())) switch shape!{ case "quad": quadVertices[selectedIndex].center = newPoint let str = quadLabels[selectedIndex].text! let index = str.index(str.startIndex, offsetBy: 1) quadLabels[selectedIndex].text = "\(str.substring(to: index))(\(inverted.x),\(inverted.y))" plot(border: quadBorder, vertices: quadVertices) setStatusLabels() case "line1": line1Vertices[selectedIndex].center = newPoint let str = line1labels[selectedIndex].text! let index = str.index(str.startIndex, offsetBy: 1) line1labels[selectedIndex].text = "\(str.substring(to: index))(\(inverted.x),\(inverted.y))" plot(border: line1, vertices: line1Vertices) setStatusLabels() default: freeVertex.center = newPoint let str = freeLabel.text! let index = str.index(str.startIndex, offsetBy: 1) freeLabel.text = "\(str.substring(to: index))(\(inverted.x),\(inverted.y))" setPointStatus() } } //TODO: change colors while moving } func setStatusLabels(){ setQuadStatus() setLineStatus() setPointStatus() } func setQuadStatus(){ let corners = getQuadCoordinates() if(!geometry.isQuadrilateral(points: corners)){ quadStatus.text = "ABCD is not a quadrilateral!" return } if(geometry.isConcave(corners: corners)){ quadStatus.text = "ABCD is concave" return } if(!geometry.isConvex(corners: corners)){ quadStatus.text = "ABCD is complex" return } if(geometry.isQuadrilateralRhombus(corners: corners)){ if(geometry.isQuadrilateralRectangle(corners: corners)){ quadStatus.text = "ABCD is a square" }else{ quadStatus.text = "ABCD is a rhombus" } }else if(geometry.isQuadrilateralRectangle(corners: corners)){ quadStatus.text = "ABCD is a rectangle" }else{ quadStatus.text = "ABCD is convex" } } func setPointStatus(){ let point = getRoundedPoint(freeVertex.center) let quad = getQuadCoordinates() if(geometry.isPointOnPolygon(point: point, polygon: quad) == true){ pointStatus.text = "P is on ABCD" } else if(geometry.isPointInsidePolygon(point: point, polygon: quad) == true){ pointStatus.text = "P is inside ABCD" } else{ pointStatus.text = "P is outside ABCD" } let distance = geometry.shortestDistanceBetweenLineAndPoint(point: round(point), l1: getRoundedPoint(line1Vertices[0].center), l2: getRoundedPoint(line1Vertices[1].center)) if(distance > 0){ pointStatus.text = pointStatus.text! + " & \(distance.rounded(toPlaces: 2)) units from LM" }else{ pointStatus.text = pointStatus.text! + " & lies on LM" } } func setLineStatus(){ let line = [getRoundedPoint(line1Vertices[0].center), getRoundedPoint(line1Vertices[1].center)] let quad = getQuadCoordinates() var status = "" if(geometry.doLineSegmentsIntersect(l1: line[0], l2: line[1], m1: quad[0], m2: quad[1])){ status = "AB" } if(geometry.doLineSegmentsIntersect(l1: line[0], l2: line[1], m1: quad[1], m2: quad[2])){ status = status == "" ? "BC" : "\(status), BC" } if(geometry.doLineSegmentsIntersect(l1: line[0], l2: line[1], m1: quad[2], m2: quad[3])){ status = status == "" ? "CD" : "\(status), CD" } if(geometry.doLineSegmentsIntersect(l1: line[0], l2: line[1], m1: quad[3], m2: quad[0])){ status = status == "" ? "AD" : "\(status), AD" } if(status == ""){ let length = geometry.distanceBetweenPoints(point1: line[0], point2: line[1]) status = "Length of LM : \(length.rounded(toPlaces: 2))" lineStatus.text = status return } let range = status.range(of: ",", options:String.CompareOptions.backwards) if let range = range{ status = status.replacingCharacters(in: range, with: " and") } status = "LM intersects with \(status)" lineStatus.text = status } func getRoundedPoint(_ point:CGPoint) -> CGPoint { return round(point.applying(graph.chartTransform!.inverted())) } func getQuadCoordinates() -> [CGPoint]{ return [round(quadVertices[0].center.applying(graph.chartTransform!.inverted())), round(quadVertices[1].center.applying(graph.chartTransform!.inverted())), round(quadVertices[2].center.applying(graph.chartTransform!.inverted())), round(quadVertices[3].center.applying(graph.chartTransform!.inverted()))] } func round(_ point: CGPoint) -> CGPoint{ return CGPoint(x: point.x.rounded(), y: point.y.rounded()) } func plot(){ if graph.chartTransform == nil { graph.setAxisRange() } plot(border: quadBorder, vertices: quadVertices) plot(border: line1, vertices: line1Vertices) setStatusLabels() } func plot(border:CAShapeLayer?,vertices:[UIView]){ var points = [CGPoint]() for vertex in vertices { points.append(vertex.center) } if(vertices.count > 2){ points.append(vertices[0].center) } border?.path = nil let linePath = CGMutablePath() linePath.addLines(between: points) border?.path = linePath } } extension String { func size(withSystemFontSize pointSize: CGFloat) -> CGSize { return (self as NSString).size(withAttributes: [NSAttributedStringKey.font: UIFont.systemFont(ofSize: pointSize)]) } } extension CGFloat { /// Rounds the double to decimal places value func rounded(toPlaces places:Int) -> CGFloat { let divisor = CGFloat(pow(10.0, Double(places))) return (self * divisor).rounded() / divisor } } extension CGPoint { func adding(x: CGFloat) -> CGPoint { return CGPoint(x: self.x + x, y: self.y) } func adding(y: CGFloat) -> CGPoint { return CGPoint(x: self.x, y: self.y + y) } }
mit
4e113d4222c532240f7d48d1a0c9ce27
34.979328
311
0.546395
4.624377
false
false
false
false
swift102016team5/mefocus
MeFocus/MeFocus/AppDelegate.swift
1
7914
// // AppDelegate.swift // MeFocus // // Created by Enta'ard on 11/15/16. // Copyright © 2016 Group5. All rights reserved. // import UIKit import CoreData import UserNotifications let returnNotification = "returnToApp" let enterForegroundNotification = "appWillEnterForeground" let saveCurrentTimeNotification = "saveCurrentTime" let resumeTimerNotification = "resumeTimer" @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var deviceLocked = false func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let center = UNUserNotificationCenter.current() center.requestAuthorization( options: [.alert, .sound], completionHandler: { (granted, error) in } ) registerforDeviceLockNotification() // Finish old ongoing session SessionsManager.unfinished?.finish() SessionsManager.notify() // Check if any unfinished session is going let session = SessionsManager.unfinished if session != nil { App.shared.redirect( delegate: self, storyboard: "Session", controller: "SessionOngoingViewController", modifier:{(controller:UIViewController) in let ongoing = controller as! SessionOngoingViewController ongoing.session = session } ) return true } // If user havent seen onboard screen , navigate to it if !App.shared.isViewedOnboard() { App.shared.redirect( delegate: self, storyboard: "Onboard", controller: "OnboardIntroViewController", modifier:nil ) return true } // Navigate user direct to create new session App.shared.redirect( delegate: self, storyboard: "Session", controller: "SessionStartNavigationController", modifier:nil ) return true // self.window = UIWindow(frame: UIScreen.main.bounds) // let storyboard: UIStoryboard = UIStoryboard(name: "User", bundle: nil) // let controller: UserLoginViewController = storyboard.instantiateViewController(withIdentifier: "UserLoginViewController") as! UserLoginViewController // // self.window?.rootViewController = controller // // self.window?.makeKeyAndVisible() } 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) { guard deviceLocked else { NotificationCenter.default.post(name: NSNotification.Name(returnNotification), object: self) return } NotificationCenter.default.post(name: NSNotification.Name(saveCurrentTimeNotification), object: self) } func applicationWillEnterForeground(_ application: UIApplication) { guard deviceLocked else { NotificationCenter.default.post(name: NSNotification.Name(enterForegroundNotification), object: self) return } deviceLocked = false NotificationCenter.default.post(name: NSNotification.Name(resumeTimerNotification), object: self) } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. // Stop session when app is terminated SessionsManager.unfinished?.finish() 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: "MeFocus") 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 registerforDeviceLockNotification() { // Void pointer to `self`: let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque()) CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), observer, { (center, observer, name, object, userInfo) -> Void in // the "com.apple.springboard.lockcomplete" notification will always come after the "com.apple.springboard.lockstate" notification let lockState = name?.rawValue as! String if lockState == "com.apple.springboard.lockcomplete", let observer = observer { let this = Unmanaged<AppDelegate>.fromOpaque(observer).takeUnretainedValue() this.deviceLocked = true NSLog("DEVICE LOCKED") } else { NSLog("LOCK STATUS CHANGED") } }, "com.apple.springboard.lockcomplete" as CFString!, nil, CFNotificationSuspensionBehavior.deliverImmediately) } }
mit
70141f3930c4289637f83632806f4ee2
42.718232
285
0.647795
5.680546
false
false
false
false
bradhilton/Table
Table/UIWindow.swift
1
1965
// // UIWindow.swift // Table // // Created by Bradley Hilton on 7/31/18. // Copyright © 2018 Brad Hilton. All rights reserved. // extension UIWindow { public var keyboardLayoutGuide: UILayoutGuide { return storage[\.keyboardLayoutGuide, default: KeyboardLayoutGuide(self)] } } private class KeyboardLayoutGuide : UILayoutGuide { init(_ window: UIWindow) { super.init() window.addLayoutGuide(self) leftAnchor.constraint(equalTo: window.leftAnchor).isActive = true bottomAnchor.constraint(equalTo: window.bottomAnchor).isActive = true rightAnchor.constraint(equalTo: window.rightAnchor).isActive = true let heightConstraint = heightAnchor.constraint(equalToConstant: 0) heightConstraint.isActive = true NotificationCenter.default.addObserver( forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: .main ) { [weak window] notification in guard let window = window, let userInfo = notification.userInfo, let frame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let animationCurve = userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? UIView.AnimationOptions else { return } UIView.animate( withDuration: duration, delay: 0, options: animationCurve, animations: { heightConstraint.constant = window.frame.height - frame.minY window.layoutIfNeeded() }, completion: nil ) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9edab8a365c6472e185619454740ef4c
34.071429
120
0.61609
5.759531
false
false
false
false
jsclayton/swatches
Swatches WatchKit Extension/InterfaceController.swift
1
4393
// // InterfaceController.swift // Swatches WatchKit Extension // // Created by John Clayton on 11/20/14. // Copyright (c) 2014 Code Monkey Labs LLC. All rights reserved. // import WatchKit import Foundation import MultipeerConnectivity class InterfaceController: WKInterfaceController, MCNearbyServiceBrowserDelegate, MCSessionDelegate { lazy var localPeerID: MCPeerID = { return MCPeerID(displayName: "Apple Watch") }() lazy var serviceBrowser: MCNearbyServiceBrowser = { var browser = MCNearbyServiceBrowser(peer: self.localPeerID, serviceType: "swatch-remote") browser.delegate = self return browser }() var remoteSession: MCSession? var remoteSessionState = MCSessionState.NotConnected override init(context: AnyObject?) { // Initialize variables here. super.init(context: context) } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() NSLog("Started browsing for peers") serviceBrowser.startBrowsingForPeers() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() NSLog("Stopped browsing for peers") serviceBrowser.stopBrowsingForPeers() if let session = remoteSession { NSLog("Disconnecting peer session") session.disconnect() } } // No way to get the button's color so use unique actions @IBAction func didSelectRed() { NSLog("Red button selected") sendColor(UIColor.redColor()) } @IBAction func didSelectBlue() { NSLog("Blue button selected") sendColor(UIColor.blueColor()) } @IBAction func didSelectGreen() { NSLog("Green button selected") sendColor(UIColor.greenColor()) } func sendColor(color: UIColor) { if remoteSessionState == .Connected { if let session = remoteSession { let colorData = NSKeyedArchiver.archivedDataWithRootObject(color) session.sendData(colorData, toPeers: session.connectedPeers, withMode: MCSessionSendDataMode.Reliable, error: nil) } } } // MARK: MCNearbyServiceBrowserDelegate func browser(browser: MCNearbyServiceBrowser!, didNotStartBrowsingForPeers error: NSError!) { NSLog("Browser unable to start: %@", error) } func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) { NSLog("Browser found peer: %@", peerID.displayName) remoteSession = MCSession(peer: localPeerID, securityIdentity: nil, encryptionPreference: .None) remoteSession?.delegate = self browser.invitePeer(peerID, toSession: remoteSession, withContext: nil, timeout: 10) } func browser(browser: MCNearbyServiceBrowser!, lostPeer peerID: MCPeerID!) { NSLog("Browser lost peer: %@", peerID.displayName) } // MARK: MCSessionDelegate func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) { remoteSessionState = state var status: String switch state { case .NotConnected: status = "not connected" case .Connecting: status = "connecting" case .Connected: status = "connected" } NSLog("Session state did change: %@ to %@", status, peerID.displayName) } func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) { NSLog("Session did receive data") } func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) { NSLog("Session did receive stream") } func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) { NSLog("Session did start receiving resource") } func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) { NSLog("Session did finish receiving resource") } }
mit
e4bd8ca0eb222502415a103061df7fff
32.792308
176
0.672433
5.344282
false
false
false
false
liuduoios/HLDBadgeControls
HLDBadgeControls/HLDBadgeView.swift
1
1553
// // HLDBadgeView.swift // HLDBadgeControlsDemo // // Created by 刘铎 on 15/9/9. // Copyright © 2015年 Derek Liu. All rights reserved. // import UIKit public class HLDBadgeView: UILabel { struct Constants { static let frame = CGRect(x: 0, y: 0, width: 20, height: 20) static let defaultBackgroundColor = UIColor(red: 250/255.0, green: 82/255.0, blue: 82/255.0, alpha: 1.0) static let defaultFont = UIFont.systemFontOfSize(14) } var autoHideWhenZero: Bool = false { didSet { if let text = text { if let count = UInt(text) { setCount(count) } } } } init() { super.init(frame: Constants.frame) backgroundColor = Constants.defaultBackgroundColor layer.cornerRadius = CGRectGetHeight(frame) / 2.0 layer.masksToBounds = true textAlignment = .Center textColor = UIColor.whiteColor() font = Constants.defaultFont setCount(0) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func setCount(count: UInt) { switch count { case 0..<10: text = "\(count)" case 10..<100: text = "\(count)" frame.size.width = 29 default: text = "99+" frame.size.width = 38 } hidden = (autoHideWhenZero && count == 0) ? true : false } }
mit
c3e8c8b8a2264fb8d2ade5f4e46a42a8
24.766667
112
0.540103
4.282548
false
false
false
false
ilyahal/VKMusic
VkPlaylist/TableViewCellIdentifiers.swift
1
3572
// // TableViewCellIdentifiers.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // 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. // /// Идентификаторы ячеек struct TableViewCellIdentifiers { /// Ячейка с сообщением об отсутствии авторизации static let noAuthorizedCell = "NoAuthorizedCell" /// Ячейка с сообщением об ошибке при подключении к интернету static let networkErrorCell = "NetworkErrorCell" /// Ячейка с сообщением об ошибке доступа static let accessErrorCell = "AccessErrorCell" /// Ячейка с сообщением "Ничего не найдено" static let nothingFoundCell = "NothingFoundCell" /// Ячейка с сообщением о загрузке данных static let loadingCell = "LoadingCell" /// Ячейка для вывода аудиозаписи static let audioCell = "AudioCell" /// Ячейка для вывода загружаемой аудиозаписи static let activeDownloadCell = "ActiveDownloadCell" /// Ячейка для вывода оффлайн аудиозаписи static let offlineAudioCell = "OfflineAudioCell" /// Ячейка для добавления плейлиста static let addPlaylistCell = "AddPlaylistCell" /// Ячейка для вывода плейлиста static let playlistCell = "PlaylistCell" /// Ячейка для перехода к добавлению аудиозаписей в плейлист static let addAudioCell = "AddAudioCell" /// Ячейка для вывода аудиозаписи добавляемой в плейлист static let addToPlaylistCell = "AddToPlaylistCell" /// Ячейка для добавления альбома static let addAlbumCell = "AddAlbumCell" /// Ячейка для вывода альбома static let albumCell = "AlbumCell" /// Ячейка для вывода ссылки на другой экран static let moreCell = "MoreCell" /// Ячейка для вывода друга static let friendCell = "FriendCell" /// Ячейка для вывода группы static let groupCell = "GroupCell" /// Ячейка для вывода количества строк в таблице static let numberOfRowsCell = "NumberOfRowsCell" }
mit
437db0cfadfef7fbac322c1b5ccf8c9c
42.602941
82
0.734143
3.962567
false
false
false
false
OctMon/OMExtension
OMExtensionDemo/OMExtensionDemo/AppDelegate.swift
1
4073
// // AppDelegate.swift // OMExtensionDemo // // The MIT License (MIT) // // Copyright (c) 2016 OctMon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import OMExtension @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { /// 配置release #if DEBUG let isDebug = true #else let isDebug = false #endif #if APPSTORE let isAppstore = true #else let isAppstore = false #endif #if BETA let isBeta = true #else let isBeta = false #endif UIApplication.OM.release.isDebug = isDebug UIApplication.OM.release.isAppstore = isAppstore UIApplication.OM.release.isBeta = isBeta UIApplication.OM.release.configURLRelease = "https://release.example.com" UIApplication.OM.release.configURLDeveloper = "https://developer.example.com" UIApplication.OM.release.configURLTest = "https://test.example.com" // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
0434765e4a11f7b087255c64eecb5ec2
42.287234
285
0.710002
5.144121
false
false
false
false
benlangmuir/swift
test/SourceKit/Misc/Inputs/errors-a.swift
14
1945
this file has a _bunch_ of errors, but we want to generate the module anyway! public typealias InvalidAlias = undefined public class InvalidClass: undefined, InvalidProtocol { public var classMemberA: undefined public init(param1: undefined, param2: undefined) { undefined } public convenience init() { self.init(undefined, undefined) } public convenience init(param: undefined) {} } public class InvalidClassSub1: InvalidClass { public var classMemberB: undefined public override init(param1: undefined, param2: undefined) { undefined } public convenience init() {} } public class InvalidClassSub2: InvalidClass { public var classMemberC: undefined public convenience init() {} } public enum InvalidEnum { var badEnumMemberA case enumeratorA case enumeratorB, enumeratorC trailing } public struct InvalidGenericStruct<T: InvalidProtocol, U: undefined> where T.Item == U.Item, T.Item: undefined { public var genericMemberA: undefined } public protocol InvalidProtocol : undefined { associatedtype Item mutating func add(_) func get() -> Item mutating func set(item: Item) } public struct InvalidStruct : undefined, InvalidProtocol { typealias Item = undefined public let memberA: Int { willSet(newVal invalid) { print("Setting value \(newVal)") } didSet(oldVal invalid) { print("Set value \(oldVal)") } } public let memberB: undefined { willSet { print("Setting value \(newValue)") } didSet { print("Set value \(oldValue)") } } public var memberC: undefined = { return undefined }() public lazy var memberD: undefined = { return undefined }() public var memberE: undefined { get { undefined } set { undefined = "bar" } } mutating func set(item: Item) { undefined } } public extension undefined { public enum ValidEnum: String { case a case b case c } }
apache-2.0
31b0f0f7fd379d9983b150e331f44798
19.260417
68
0.687918
4.129512
false
false
false
false
bitjammer/swift
test/SILGen/witness_same_type.swift
1
1369
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s // RUN: %target-swift-frontend -emit-ir %s protocol Fooable { associatedtype Bar func foo<T: Fooable where T.Bar == Self.Bar>(x x: T) -> Self.Bar } struct X {} // Ensure that the protocol witness for requirements with same-type constraints // is set correctly. <rdar://problem/16369105> // CHECK-LABEL: sil hidden [transparent] [thunk] @_T017witness_same_type3FooVAA7FooableA2aDP3foo3BarQzqd__1x_tAaDRd__AGQyd__AHRSlFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Fooable, τ_0_0.Bar == X> (@in τ_0_0, @in_guaranteed Foo) -> @out X struct Foo: Fooable { typealias Bar = X func foo<T: Fooable where T.Bar == X>(x x: T) -> X { return X() } } // rdar://problem/19049566 // CHECK-LABEL: sil [transparent] [thunk] @_T017witness_same_type14LazySequenceOfVyxq_Gs0E0AAsAERz8Iterator_7ElementQZRs_r0_lsAEP04makeG0AFQzyFTW : $@convention(witness_method) <τ_0_0, τ_0_1 where τ_0_0 : Sequence, τ_0_1 == τ_0_0.Iterator.Element> (@in_guaranteed LazySequenceOf<τ_0_0, τ_0_1>) -> @out AnyIterator<τ_0_1> public struct LazySequenceOf<SS : Sequence, A where SS.Iterator.Element == A> : Sequence { public func makeIterator() -> AnyIterator<A> { var opt: AnyIterator<A>? return opt! } public subscript(i : Int) -> A { get { var opt: A? return opt! } } }
apache-2.0
ee4787c424fd74b6e7abad2d78a13c7d
38.911765
320
0.678703
2.89339
false
false
false
false
AppriaTT/Swift_SelfLearning
Swift/swift16 slideMenu/swift16 slideMenu/TransitionManager.swift
1
2880
// // TransitionManager.swift // swift16 slideMenu // // Created by Aaron on 16/7/18. // Copyright © 2016年 Aaron. All rights reserved. // import UIKit @objc protocol TransitionManagerDelegate { func dismiss() } class TransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { var duration = 0.5 var isPresenting = false var snapshot:UIView?{ didSet{ if let _delegate = delegate{ let tap = UITapGestureRecognizer(target: _delegate, action: "dismiss") snapshot?.addGestureRecognizer(tap) } } } var delegate:TransitionManagerDelegate? func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval{ return duration } //必须要实现的方法 func animateTransition(transitionContext: UIViewControllerContextTransitioning){ let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)! let toView = transitionContext.viewForKey(UITransitionContextToViewKey)! let container = transitionContext.containerView() let moveDown = CGAffineTransformMakeTranslation(0, container!.frame.height - 150) let moveUp = CGAffineTransformMakeTranslation(0, -50) if isPresenting {//正在展示的时候 toView.transform = moveUp snapshot = fromView.snapshotViewAfterScreenUpdates(false) //添加的顺序问题 container!.addSubview(toView) container!.addSubview(snapshot!) } UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.3, options: .CurveEaseInOut, animations: { () -> Void in if self.isPresenting { self.snapshot?.transform = moveDown toView.transform = CGAffineTransformIdentity }else{ self.snapshot?.transform = CGAffineTransformIdentity fromView.transform = moveUp } }) { (Bool) -> Void in transitionContext.completeTransition(true) if !self.isPresenting { self.snapshot?.removeFromSuperview() } } } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = false return self } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresenting = true return self } }
mit
bf4473802be6306c1ab7210041a8d915
33.54878
217
0.639605
6.497706
false
false
false
false
fakerabbit/LucasBot
LucasBot/LoginVC.swift
1
1916
// // LoginVC.swift // LucasBot // // Created by Mirko Justiniano on 1/16/17. // Copyright © 2017 LB. All rights reserved. // import Foundation import UIKit class LoginVC: BotViewController { lazy var loginView:LoginView! = { let frame = UIScreen.main.bounds let v = LoginView(frame: frame) return v }() override func loadView() { super.loadView() BotMgr.sharedInstance.currentView = self.loginView self.view = self.loginView } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Utils.printFontNamesInSystem() self.checkStore() loginView.animateSignUp() loginView.onSignUp = { [weak self] email, password in if email != nil && password != nil { BotMgr.sharedInstance.signUp(email: email!, password: password!) { [weak self] result in if result { debugPrint("sign up SUCCESS") self?.loginView.animateLogin(callback: { [weak self] finished in let vc = ViewController() self?.nav?.viewControllers = [vc] }) } else { //show error message to user debugPrint("error occurred during sign up...") } } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK:- Private private func checkStore() { if DataMgr.sharedInstance.initStore() { // sign up } } }
gpl-3.0
adfa784b70a6d3c16d7f20898d5c6756
27.58209
104
0.502872
5.471429
false
false
false
false
keith/radars
LazyCollectionEvaluatedMultipleTimes/LazyCollectionEvaluatedMultipleTimes.swift
1
527
func g(string: String) -> String { let result = string == "b" ? "hi" : "" print("Called with '\(string)' returning '\(result)'") return result } public extension CollectionType { public func find(includedElement: Generator.Element -> Bool) -> Generator.Element? { if let index = self.indexOf(includedElement) { return self[index] } return nil } } func f(fields: [String]) { _ = fields.lazy .map { g($0) } .find { !$0.isEmpty } } f(["a", "b", "c"])
mit
df1b469ab205fe4638ddeb9fe5f10bea
21.913043
88
0.552182
3.609589
false
false
false
false
ninewine/SaturnTimer
SaturnTimer/View/Home/STDialPlateSliderView.swift
1
6793
// // STDialPlateSliderView.swift // SaturnTimer // // Created by Tidy Nine on 2/22/16. // Copyright © 2016 Tidy Nine. All rights reserved. // import UIKit import QorumLogs import ReactiveCocoa import ReactiveSwift import pop class STDialPlateSliderView: UIView { var active: Bool = false var enabled: Bool = false { willSet { dazzlelightAnimation(newValue) } } let progress: MutableProperty<Double> = MutableProperty(0.0) //From 0.0 to 1.0 var ovalCenter: CGPoint? var ovalRadius: CGFloat? var zeroPointCenter = CGPoint.zero fileprivate var degree: CGFloat = 0 fileprivate let imageLayer = CALayer() fileprivate let dazzlelightLayer = CALayer() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); } init (image: UIImage) { let width: CGFloat = 40.0 let height: CGFloat = width super.init(frame: CGRect(x: 0, y: 0, width: width, height: height)) backgroundColor = UIColor.clear let size = image.size imageLayer.frame = CGRect( x: (width - size.width) * 0.5, y: (height - size.height) * 0.5, width: size.width, height: size.height ) imageLayer.contents = image.cgImage layer.addSublayer(imageLayer) let dazzlelightFrame = imageLayer.frame.insetBy(dx: -4, dy: -4) dazzlelightLayer.frame = dazzlelightFrame dazzlelightLayer.contents = UIImage(named: "pic-dazzlelight")?.cgImage layer.insertSublayer(dazzlelightLayer, below: imageLayer) NotificationCenter.default .reactive .notifications(forName: NSNotification.Name.UIApplicationWillResignActive) .take(during: reactive.lifetime) .observeValues({[weak self] (notification) in self?.dazzlelightLayer.removeAllAnimations() }) NotificationCenter.default .reactive .notifications(forName: NSNotification.Name.UIApplicationWillEnterForeground) .take(during: reactive.lifetime) .observeValues({[weak self] (notification) in guard let _self = self else {return} let enabled = _self.enabled _self.enabled = enabled }) } func dazzlelightAnimation (_ enabled: Bool) { if enabled { dazzlelightLayer.opacityAnimation(0.0, to: 1.0, duration: 1.0, completion: {[weak self] () -> Void in let scaleAnim = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) scaleAnim?.fromValue = NSValue(cgPoint:CGPoint(x: 1.0, y: 1.0)) scaleAnim?.toValue = NSValue(cgPoint:CGPoint(x: 1.2, y: 1.2)) scaleAnim?.duration = 1.5 scaleAnim?.autoreverses = true scaleAnim?.repeatForever = true self?.dazzlelightLayer.pop_add(scaleAnim, forKey: "ScaleAnimation") }) } else { dazzlelightLayer.opacityAnimation(1.0, to: 0.0, duration: 1.0, completion: {[weak self] () -> Void in self?.dazzlelightLayer.pop_removeAllAnimations() }) } } func slideWithRefrencePoint (_ point: CGPoint) { guard let center = ovalCenter, let radius = ovalRadius else { print("Slide must have a oval center and a radius") return } let transformedPoint = transformPoint(point, coordinateSystemCenter: center) let factor: CGFloat = transformedPoint.y < 0 ? -1.0 : 1.0 let (oneQuadrantRadian, fourQuadrantRadian) = calculateDeltaAngle(point) let moveToDegree = fourQuadrantRadian * 180 / CGFloat.pi let moveToProgress: Double = Double(moveToDegree) / 360.0 let targetX = sin(oneQuadrantRadian) * radius let targetY = cos(oneQuadrantRadian) * radius * factor let outputPoint = transformPoint( CGPoint(x: targetX, y: targetY), coordinateSystemCenter: CGPoint(x: -center.x, y: -center.y) ) let outputOriginPoint = CGPoint(x: outputPoint.x - bounds.width * 0.5, y: outputPoint.y - bounds.height * 0.5) frame.origin = outputOriginPoint degree = moveToDegree progress.value = moveToProgress } func slideToProgress (_ progress: Double, duration: Double) { if progress < 0.0 || progress > 1.0 { print("Progress must be a value between 0.0 and 1.0") return } guard let center = ovalCenter, let radius = ovalRadius else { print("Slide must have a oval center and a radius") return } let radian = 2 * Double.pi * progress let toDegree = CGFloat(radian * 180 / Double.pi) let clockwise = degree < toDegree degree = toDegree let x = sin(radian) * Double(radius) let y = cos(radian) * Double(radius) let toPoint = CGPoint(x: center.x + CGFloat(x), y: center.y - CGFloat(y)) slideAnimationFrom(self.center, to: toPoint, duration: duration, clockwise: clockwise) } func slideAnimationFrom(_ from: CGPoint, to: CGPoint, duration: Double, clockwise: Bool) { guard let center = ovalCenter, let radius = ovalRadius else { print("Slide must have a oval center and a radius") return } let (_, fromRadian) = calculateDeltaAngle(from) let (_, toRadian) = calculateDeltaAngle(to) let path = UIBezierPath() path.addArc(withCenter: center, radius: radius, startAngle: fromRadian - (CGFloat.pi * 0.5), endAngle: toRadian - (CGFloat.pi * 0.5), clockwise: clockwise) let pathAnim = CAKeyframeAnimation(keyPath: "position") pathAnim.path = path.cgPath pathAnim.duration = duration pathAnim.fillMode = kCAFillModeForwards pathAnim.calculationMode = kCAAnimationCubicPaced pathAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) layer.add(pathAnim, forKey: "PositionAnimation") self.center = to } func calculateDeltaAngle (_ referncePoint: CGPoint) -> (oneQuadrantRadian: CGFloat, fourQuadrantRadian : CGFloat) { guard let center = ovalCenter else { print("Slide must have a oval center and radius") return (0, 0) } let transformedPoint = transformPoint(referncePoint, coordinateSystemCenter: center) let referencePointRadius = sqrt(pow(transformedPoint.x, 2) + pow(transformedPoint.y, 2)) let oneQuadrantRadian = asin(transformedPoint.x / referencePointRadius) var fourQuadrantRadian:CGFloat = 0.0 if transformedPoint.y > 0 { fourQuadrantRadian = CGFloat.pi - oneQuadrantRadian } else if transformedPoint.x < 0 && transformedPoint.y <= 0 { fourQuadrantRadian = (CGFloat.pi * 2) + oneQuadrantRadian } else { fourQuadrantRadian = oneQuadrantRadian } return (oneQuadrantRadian, fourQuadrantRadian) } func transformPoint (_ point: CGPoint, coordinateSystemCenter center: CGPoint) -> CGPoint { return CGPoint( x: point.x - center.x, y: point.y - center.y ) } }
mit
b00115f07cbf5a5549dcda95c309d6b9
31.811594
159
0.672261
4.14399
false
false
false
false
Wolox/wolmo-core-ios
WolmoCore/Extensions/UIKit/UIView/GestureRecognizers/PanRecognizer.swift
1
2545
// // PanRecognizer.swift // WolmoCore // // Created by Gabriel Mazzei on 26/12/2018. // Copyright © 2018 Wolox. All rights reserved. // import Foundation public extension UIView { // In order to create computed properties for extensions, we need a key to // store and access the stored property fileprivate struct AssociatedObjectKeys { static var panGestureRecognizer = "MediaViewerAssociatedObjectKey_mediaViewer" } fileprivate typealias Action = ((UIPanGestureRecognizer) -> Void)? // Set our computed property type to a closure fileprivate var panGestureRecognizerAction: Action? { get { let panGestureRecognizerActionInstance = objc_getAssociatedObject(self, &AssociatedObjectKeys.panGestureRecognizer) as? Action return panGestureRecognizerActionInstance } set { if let newValue = newValue { // Computed properties get stored as associated objects objc_setAssociatedObject(self, &AssociatedObjectKeys.panGestureRecognizer, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } /** Adds a pan gesture recognizer that executes the closure when panned - Parameter minimumNumberOfTouches: The minimum number of touches required to match. Default is 1 - Parameter maximumNumberOfTouches: The maximum number of touches that can be down. Default is Int.max - Parameter action: The closure that will execute when the view is panned */ func addPanGestureRecognizer(minimumNumberOfTouches: Int = 1, maximumNumberOfTouches: Int = .max, action: ((UIPanGestureRecognizer) -> Void)?) { isUserInteractionEnabled = true panGestureRecognizerAction = action let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture)) panGestureRecognizer.minimumNumberOfTouches = minimumNumberOfTouches panGestureRecognizer.maximumNumberOfTouches = maximumNumberOfTouches addGestureRecognizer(panGestureRecognizer) } // Every time the user pans on the UIView, this function gets called, // which triggers the closure we stored @objc fileprivate func handlePanGesture(sender: UIPanGestureRecognizer) { if let action = panGestureRecognizerAction { action?(sender) } else { print("No action for the pan gesture") } } }
mit
c04bdead9c12af75232219fdfa46d8bf
40.032258
148
0.683569
5.943925
false
false
false
false
yannickl/Cocarde
Cocarde/DefaultLayer.swift
1
4058
/* * Cocarde * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import Foundation import UIKit import QuartzCore internal final class DefaultLayer: CocardeLayer { required init(segmentCount segments: UInt, segmentColors colors: [UIColor], loopDuration duration: Double) { super.init(segmentCount: segments, segmentColors: colors, loopDuration: duration) } override init(layer: AnyObject) { super.init(layer: layer) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Drawing Cocarde Activity override func drawInRect(rect: CGRect) { let center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)) let colorCount = segmentColors.count let radius = (min(CGRectGetWidth(rect), CGRectGetHeight(rect)) / 2) let startAngle = CGFloat(0) let endAngle = CGFloat(2 * M_PI) for i in 0 ..< Int(segmentCount) { let plotLayer = CAShapeLayer() insertSublayer(plotLayer, atIndex: 0) let plotPath = UIBezierPath() plotPath.addArcWithCenter(CGPointZero, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) plotLayer.path = plotPath.CGPath plotLayer.fillColor = segmentColors[Int(i) % colorCount].CGColor plotLayer.position = center let group = CAAnimationGroup() var scaleValues: [CGFloat] = [] var fadeValues: [CGFloat] = [] var zIndexValues: [CGFloat] = [] for j in 0 ..< Int(segmentCount) { if j == i { zIndexValues.append(1) scaleValues.append(0) fadeValues.append(1) zIndexValues.append(1) scaleValues.append(1) fadeValues.append(0) zIndexValues.append(1) scaleValues.append(0) fadeValues.append(0) } else { zIndexValues.append(0) scaleValues.append(0) fadeValues.append(1) } } let scaleAnim = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnim.duration = loopDuration scaleAnim.cumulative = false scaleAnim.values = scaleValues let fadeAnim = CAKeyframeAnimation(keyPath: "opacity") fadeAnim.duration = loopDuration fadeAnim.cumulative = false fadeAnim.values = fadeValues fadeAnim.fillMode = kCAFillModeForwards let zIndexAnim = CAKeyframeAnimation(keyPath: "zPosition") zIndexAnim.duration = loopDuration zIndexAnim.cumulative = false zIndexAnim.values = zIndexValues group.animations = [fadeAnim, scaleAnim, zIndexAnim] group.duration = loopDuration group.repeatCount = Float.infinity group.removedOnCompletion = false plotLayer.addAnimation(group, forKey: "circle.group") } } }
mit
1ec68081fc9dc3142c354c64357b164e
33.982759
121
0.66412
4.574972
false
false
false
false
welbesw/easypost-swift
Pod/Classes/EasyPostShipment.swift
1
5015
// // EasyPostShipment.swift // Pods // // Created by William Welbes on 10/5/15. // // import Foundation public struct EasyPostShipmentMessage { public var carrier:String = "" public var message:String = "" } open class EasyPostShipment { open var id:String? open var mode:String? open var toAddress:EasyPostAddress? open var fromAddress:EasyPostAddress? open var parcel:EasyPostParcel? open var customsInfo:EasyPostCustomsInfo? open var rates:[EasyPostRate] = [] open var postageLabel:EasyPostLabel? open var trackingCode:String? open var tracker:EasyPostTracker? open var referenceNumber:String? open var refundStatus:String? open var batchStatus:String? open var batchMessage:String? open var forms:[EasyPostForm]? open var selectedRate:EasyPostRate? open var createdAt:Date? open var updatedAt:Date? open var messages:[EasyPostShipmentMessage] = [] public init() { } public init(jsonDictionary: [String: Any]) { //Load the JSON dictionary let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" //2013-04-22T05:40:57Z if let stringValue = jsonDictionary["id"] as? String { id = stringValue } if let stringValue = jsonDictionary["mode"] as? String { mode = stringValue } if let addressDict = jsonDictionary["to_address"] as? [String: Any] { self.toAddress = EasyPostAddress(jsonDictionary: addressDict) } if let addressDict = jsonDictionary["from_address"] as? [String: Any] { self.fromAddress = EasyPostAddress(jsonDictionary: addressDict) } if let parcelDict = jsonDictionary["parcel"] as? [String: Any] { self.parcel = EasyPostParcel(jsonDictionary: parcelDict) } if let customsInfoDict = jsonDictionary["customs_info"] as? [String: Any] { self.customsInfo = EasyPostCustomsInfo(jsonDictionary: customsInfoDict) } if let ratesArray = jsonDictionary["rates"] as? NSArray { for rateElement in ratesArray { if let rateDict = rateElement as? NSDictionary { let rate = EasyPostRate(jsonDictionary: rateDict) self.rates.append(rate) } } } if let postageLabelDict = jsonDictionary["postage_label"] as? NSDictionary { postageLabel = EasyPostLabel(jsonDictionary: postageLabelDict) } if let stringValue = jsonDictionary["tracking_code"] as? String { trackingCode = stringValue } if let trackerValue = jsonDictionary["tracker"] as? Dictionary<String, Any> { tracker = EasyPostTracker(jsonDictionary: trackerValue) } if let stringValue = jsonDictionary["reference"] as? String { referenceNumber = stringValue } if let stringValue = jsonDictionary["refund_status"] as? String { refundStatus = stringValue } if let stringValue = jsonDictionary["batch_status"] as? String { batchStatus = stringValue } if let stringValue = jsonDictionary["batch_message"] as? String { batchMessage = stringValue } if let arrayValue = jsonDictionary["forms"] as? Array<Dictionary<String, Any>> { forms = [] for value in arrayValue { let form = EasyPostForm(jsonDictionary: value) forms?.append(form) } } if let rateDict = jsonDictionary["selected_rate"] as? NSDictionary { selectedRate = EasyPostRate(jsonDictionary: rateDict) } if let messagesArray = jsonDictionary["messages"] as? NSArray { for messageElement in messagesArray { if let messageDict = messageElement as? NSDictionary { var message = EasyPostShipmentMessage() if let stringValue = messageDict["carrier"] as? String { message.carrier = stringValue } if let stringValue = messageDict["message"] as? String { message.message = stringValue } self.messages.append(message) } } } if let stringValue = jsonDictionary["created_at"] as? String { createdAt = dateFormatter.date(from: stringValue) } if let stringValue = jsonDictionary["updated_at"] as? String { updatedAt = dateFormatter.date(from: stringValue) } } }
mit
d417a88bf692d371b22bcede671bdf16
31.354839
88
0.575673
5.117347
false
false
false
false
eMdOS/AirPlay
Sources/AirPlay.swift
1
7496
// // AirPlay.swift // AirPlay // // Created by eMdOS on 1/12/16. // // import Foundation import MediaPlayer import AVFoundation public extension Notification.Name { /// Notification sent everytime AirPlay availability changes. public static let airplayAvailabilityChangedNotification = Notification.Name("AirPlayAvailabilityChangedNotification") /// Notification sent everytime AirPlay connection route changes. public static let airplayRouteStatusChangedNotification = Notification.Name("AirPlayRouteChangedNotification") } final public class AirPlay: NSObject { public typealias AirPlayHandler = () -> Void // MARK: Properties fileprivate var window: UIWindow? fileprivate let volumeView: MPVolumeView fileprivate var airplayButton: UIButton? /// Returns `true` | `false` if there are or not available devices for casting via AirPlay. fileprivate var isAvailable = false /// Returns `true` | `false` if AirPlay availability is being monitored or not. fileprivate var isBeingMonitored = false /// Returns Device's name if connected, if not, it returns `nil`. fileprivate var connectedDevice: String? { didSet { postCurrentRouteChangedNotification() } } fileprivate var whenAvailable: AirPlayHandler? fileprivate var whenUnavailable: AirPlayHandler? fileprivate var whenRouteChanged: AirPlayHandler? // MARK: Singleton /// Singleton fileprivate static let shared = AirPlay() /// Private Initializer (because of Singleton pattern) fileprivate override init() { volumeView = MPVolumeView( frame: CGRect( x: -1000, y: -1000, width: 1, height: 1 ) ) volumeView.showsVolumeSlider = false volumeView.showsRouteButton = true } // MARK: Methods fileprivate func start() { guard let delegate = UIApplication.shared.delegate, let window = delegate.window else { return } self.window = window self.window?.addSubview(volumeView) for view in volumeView.subviews { if (view is UIButton) { airplayButton = view as? UIButton airplayButton?.addObserver( self, forKeyPath: AirPlayKVOButtonAlphaKey, options: [.initial, .new], context: nil ) isBeingMonitored = true } } NotificationCenter.default.addObserver( self, selector: .audioRouteHasChanged, name: .AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance() ) } fileprivate func stop() { airplayButton?.removeObserver( self, forKeyPath: AirPlayKVOButtonAlphaKey ) isBeingMonitored = false isAvailable = false NotificationCenter.default.removeObserver( self, name: .AVAudioSessionRouteChange, object: AVAudioSession.sharedInstance() ) } fileprivate func getConnectedDevice() -> String? { return AVAudioSession.sharedInstance().currentRoute.outputs.filter { $0.portType == AVAudioSessionPortAirPlay }.first?.portName } @objc fileprivate func audioRouteHasChanged(_ notification: Notification) { connectedDevice = getConnectedDevice() } } // MARK: - AirPlay KVO private let AirPlayKVOButtonAlphaKey = "alpha" extension AirPlay { final override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == AirPlayKVOButtonAlphaKey { guard let object = object, (object is UIButton) else { return } var newAvailabilityStatus: Bool if let newAvailabilityStatusAsNumber = change?[NSKeyValueChangeKey.newKey] as? NSNumber { newAvailabilityStatus = (newAvailabilityStatusAsNumber.floatValue == 1) } else { newAvailabilityStatus = false } if (isAvailable != newAvailabilityStatus) { isAvailable = newAvailabilityStatus postAvailabilityChangedNotification() } isAvailable = newAvailabilityStatus } } } // MARK: - Notifications extension AirPlay { fileprivate func postAvailabilityChangedNotification() { DispatchQueue.main.async { [weak self] () -> Void in guard let `self` = self else { return } NotificationCenter.default.post(name: .airplayAvailabilityChangedNotification, object: self) if let whenAvailable = self.whenAvailable, (self.isAvailable) { whenAvailable() } else if let whenUnavailable = self.whenUnavailable { whenUnavailable() } } } fileprivate func postCurrentRouteChangedNotification() { DispatchQueue.main.async { [unowned self] () -> Void in NotificationCenter.default.post(name: .airplayRouteStatusChangedNotification, object: self) if let whenRouteChanged = self.whenRouteChanged { whenRouteChanged() } } } } // MARK: - Availability / Connectivity extension AirPlay { /// Returns `true` or `false` if there are or not available devices for casting via AirPlay. (read-only) public static var isAvailable: Bool { return AirPlay.shared.isAvailable } /// Returns `true` or `false` if AirPlay availability is being monitored or not. (read-only) public static var isBeingMonitored: Bool { return AirPlay.shared.isBeingMonitored } /// Returns `true` or `false` if device is connected or not to a second device via AirPlay. (read-only) public static var isConnected: Bool { return AVAudioSession.sharedInstance().currentRoute.outputs.filter { $0.portType == AVAudioSessionPortAirPlay }.count >= 1 } /// Returns Device's name if connected, if not, it returns `nil`. (read-only) public static var connectedDevice: String? { return AirPlay.shared.connectedDevice } } // MARK: - Monitoring extension AirPlay { /// Starts monitoring AirPlay availability changes. public static func startMonitoring() { AirPlay.shared.start() } /// Stops monitoring AirPlay availability changes. public static func stopMonitoring() { AirPlay.shared.stop() } } // MARK: - Closures extension AirPlay { /// Closure called when is available to cast media via `AirPlay`. public static var whenAvailable: AirPlayHandler? { didSet { AirPlay.shared.whenAvailable = whenAvailable } } /// Closure called when is not available to cast media via `AirPlay`. public static var whenUnavailable: AirPlayHandler? { didSet { AirPlay.shared.whenUnavailable = whenUnavailable } } /// Closure called when route changed. public static var whenRouteChanged: AirPlayHandler? { didSet { AirPlay.shared.whenRouteChanged = whenRouteChanged } } } // MARK: - (Private) Selector fileprivate extension Selector { static let audioRouteHasChanged: Selector = #selector(AirPlay.audioRouteHasChanged(_:)) }
mit
a66e8fb1dd2d21cb33bbda6a3a35c2d4
28.864542
164
0.640875
5.068289
false
false
false
false
v2panda/DaysofSwift
swift2.3/My-SpotifyVideoBackground/My-SpotifyVideoBackground/ViewController.swift
1
939
// // ViewController.swift // My-SpotifyVideoBackground // // Created by Panda on 16/2/25. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit class ViewController: VideoSplashViewController { override func viewDidLoad() { super.viewDidLoad() setupVideoBackground() } func setupVideoBackground() { videoFrame = view.frame fillMode = .ResizeAspectFill alwaysRepeat = true sound = true startTime = 2.0 alpha = 0.8 contentURL = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("moments", ofType: "mp4")!) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
05ae18509076d4195e48fa15f3b5a7c1
21.285714
108
0.632479
5.171271
false
false
false
false
beepscore/ShuffleSwift
ShuffleSwift/Node.swift
1
2416
// // Node.swift // ShuffleSwift // // Created by Steve Baker on 12/28/15. // Copyright © 2015 Beepscore LLC. All rights reserved. // import Foundation class Node: NSObject { /** The partial shuffledString obtained by descending the node tree, * drawing the next matching available character from string0 or string1 at each step. */ var value: String = "" /** The string0 index. * For example if to reach this node we used the first 3 characters from string0 * index0 is 2 * nil if we have not used any characters from string0 */ var index0: String.Index? = nil /** The string1 index. * For example if to reach this node we used the first 7 characters from string1 * index1 is 6 * nil if we have not used any characters from string1 */ var index1: String.Index? = nil var left: Node? = nil var right: Node? = nil // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html convenience init(value: String, index0: String.Index?, index1: String.Index?, left: Node?, right: Node?) { self.init() self.value = value self.index0 = index0 self.index1 = index1 self.left = left self.right = right } override var description: String { let SEPARATOR_SPACE = ", " var index0String = "" var index1String = "" var leftString = "" var rightString = "" if (self.index0 == nil) { index0String = "nil" } else { index0String = "\(self.index0!)" } if (self.index1 == nil) { index1String = "nil" } else { index1String = "\(self.index1!)" } if (self.left == nil) { leftString = "left: nil" } else { leftString = "left.value: " + self.left!.value } if (self.right == nil) { rightString = "right: nil" } else { rightString = "right.value: " + self.right!.value } let descriptionString = value + SEPARATOR_SPACE + index0String + SEPARATOR_SPACE + index1String + SEPARATOR_SPACE + leftString + SEPARATOR_SPACE + rightString return descriptionString } }
mit
d979eddb494d82167abb18233d280472
27.411765
124
0.561077
4.185442
false
false
false
false
lacklock/ResponseMock
ResponseMock/ResponseMock/ResponseMockManager.swift
1
3596
// // MockConfig.swift // RequestDemo // // Created by 卓同学 on 2017/5/15. // Copyright © 2017年 卓同学. All rights reserved. // import Foundation public class ResponseMockManager { /// start mock service /// /// - Parameters: /// - inBackground: should load mock files asynchronous, defalut is **True** . /// - loadMockFilesEachRequest: keep mock synchronize with local config files. should load mock files before each request happen, defalut is False. public static func start(inBackground: Bool = true, loadMockFilesEachRequest: Bool = false) { self.loadMockFilesEachRequest = loadMockFilesEachRequest if inBackground { DispatchQueue.global(qos: .userInitiated).async { loadConfig() URLProtocol.registerClass(MapLocalURLProtocol.self) } }else { loadConfig() URLProtocol.registerClass(MapLocalURLProtocol.self) } } public static var loadMockFilesEachRequest = false public static var rootPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("mock", isDirectory: true) static var resoureDirectory = rootPath.appendingPathComponent("resource", isDirectory: true) static var mocks = [ResponseMock]() static func loadConfig(){ do { mocks.removeAll() let configFiles = try FileManager.default.contentsOfDirectory(at: rootPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles]) for configFile in configFiles { if #available(iOS 9.0, *) { guard configFile.hasDirectoryPath == false else { return } } else { let isDirectory = (try? configFile.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false guard isDirectory == false else { return } } guard let configData = try? Data(contentsOf: configFile) else { assertionFailure("can't read file") continue } do { let jsons = try JSONSerialization.jsonObject(with: configData, options: []) as? [[String: Any]] guard let jsonDicts = jsons else { assertionFailure("mock json should be array, [[String: Any]]") continue } for config in jsonDicts { guard checkConfigFileIsVaild(config: config) else { continue } if let mock = ResponseMock(JSON: config) { mocks.append(mock) } } } catch { print(error.localizedDescription) } } } catch { print("config folder not found") } } private static func checkConfigFileIsVaild(config: [String: Any]) -> Bool { if config["enable"] as? Bool == false { return false } guard config.keys.contains("url")else { return false } guard config.keys.contains("response")||config.keys.contains("resource") else { return false } return true } static func isMockFor(request: URLRequest) -> ResponseMock? { return mocks.first(where: { $0.isMatch(request) }) } }
mit
a37935cf6505a76cddb35c1c9e86e2c5
37.095745
156
0.550126
5.376877
false
true
false
false
grantmagdanz/SnapBoard
Keyboard/KeyboardKeyBackground.swift
2
10567
// // KeyboardKeyBackground.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/19/14. // Copyright (c) 2014 Apple. All rights reserved. // import UIKit // This class does not actually draw its contents; rather, it generates bezier curves for others to use. // (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.) class KeyboardKeyBackground: UIView, Connectable { var fillPath: UIBezierPath? var underPath: UIBezierPath? var edgePaths: [UIBezierPath]? // do not set this manually var cornerRadius: CGFloat var underOffset: CGFloat var startingPoints: [CGPoint] var segmentPoints: [(CGPoint, CGPoint)] var arcCenters: [CGPoint] var arcStartingAngles: [CGFloat] var dirty: Bool var attached: Direction? { didSet { self.dirty = true self.setNeedsLayout() } } var hideDirectionIsOpposite: Bool { didSet { self.dirty = true self.setNeedsLayout() } } init(cornerRadius: CGFloat, underOffset: CGFloat) { attached = nil hideDirectionIsOpposite = false dirty = false startingPoints = [] segmentPoints = [] arcCenters = [] arcStartingAngles = [] startingPoints.reserveCapacity(4) segmentPoints.reserveCapacity(4) arcCenters.reserveCapacity(4) arcStartingAngles.reserveCapacity(4) for _ in 0..<4 { startingPoints.append(CGPointZero) segmentPoints.append((CGPointZero, CGPointZero)) arcCenters.append(CGPointZero) arcStartingAngles.append(0) } self.cornerRadius = cornerRadius self.underOffset = underOffset super.init(frame: CGRectZero) self.userInteractionEnabled = false } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } var oldBounds: CGRect? override func layoutSubviews() { if !self.dirty { if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && CGRectEqualToRect(self.bounds, oldBounds!) { return } } oldBounds = self.bounds super.layoutSubviews() self.generatePointsForDrawing(self.bounds) self.dirty = false } let floatPi = CGFloat(M_PI) let floatPiDiv2 = CGFloat(M_PI/2.0) let floatPiDivNeg2 = -CGFloat(M_PI/2.0) func generatePointsForDrawing(bounds: CGRect) { let segmentWidth = bounds.width let segmentHeight = bounds.height - CGFloat(underOffset) // base, untranslated corner points self.startingPoints[0] = CGPointMake(0, segmentHeight) self.startingPoints[1] = CGPointMake(0, 0) self.startingPoints[2] = CGPointMake(segmentWidth, 0) self.startingPoints[3] = CGPointMake(segmentWidth, segmentHeight) self.arcStartingAngles[0] = floatPiDiv2 self.arcStartingAngles[2] = floatPiDivNeg2 self.arcStartingAngles[1] = floatPi self.arcStartingAngles[3] = 0 //// actual coordinates for each edge, including translation //self.segmentPoints.removeAll(keepCapacity: true) // //// actual coordinates for arc centers for each corner //self.arcCenters.removeAll(keepCapacity: true) // //self.arcStartingAngles.removeAll(keepCapacity: true) for i in 0 ..< self.startingPoints.count { let currentPoint = self.startingPoints[i] let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count] var floatXCorner: CGFloat = 0 var floatYCorner: CGFloat = 0 if (i == 1) { floatXCorner = cornerRadius } else if (i == 3) { floatXCorner = -cornerRadius } if (i == 0) { floatYCorner = -cornerRadius } else if (i == 2) { floatYCorner = cornerRadius } let p0 = CGPointMake( currentPoint.x + (floatXCorner), currentPoint.y + underOffset + (floatYCorner)) let p1 = CGPointMake( nextPoint.x - (floatXCorner), nextPoint.y + underOffset - (floatYCorner)) self.segmentPoints[i] = (p0, p1) let c = CGPointMake( p0.x - (floatYCorner), p0.y + (floatXCorner)) self.arcCenters[i] = c } // order of edge drawing: left edge, down edge, right edge, up edge // We need to have separate paths for all the edges so we can toggle them as needed. // Unfortunately, it doesn't seem possible to assemble the connected fill path // by simply using CGPathAddPath, since it closes all the subpaths, so we have to // duplicate the code a little bit. let fillPath = UIBezierPath() var edgePaths: [UIBezierPath] = [] var prevPoint: CGPoint? for i in 0..<4 { var edgePath: UIBezierPath? let segmentPoint = self.segmentPoints[i] if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) { // do nothing // TODO: quick hack if !self.hideDirectionIsOpposite { continue } } else { edgePath = UIBezierPath() // TODO: figure out if this is ncessary if prevPoint == nil { prevPoint = segmentPoint.0 fillPath.moveToPoint(prevPoint!) } fillPath.addLineToPoint(segmentPoint.0) fillPath.addLineToPoint(segmentPoint.1) edgePath!.moveToPoint(segmentPoint.0) edgePath!.addLineToPoint(segmentPoint.1) prevPoint = segmentPoint.1 } let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false) if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) { // do nothing } else { edgePath = (edgePath == nil ? UIBezierPath() : edgePath) if prevPoint == nil { prevPoint = segmentPoint.1 fillPath.moveToPoint(prevPoint!) } let startAngle = self.arcStartingAngles[(i + 1) % 4] let endAngle = startAngle + floatPiDiv2 let arcCenter = self.arcCenters[(i + 1) % 4] fillPath.addLineToPoint(prevPoint!) fillPath.addArcWithCenter(arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) edgePath!.moveToPoint(prevPoint!) edgePath!.addArcWithCenter(arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true) prevPoint = self.segmentPoints[(i + 1) % 4].0 } edgePath?.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset)) if edgePath != nil { edgePaths.append(edgePath!) } } fillPath.closePath() fillPath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset)) let underPath = { () -> UIBezierPath in let underPath = UIBezierPath() underPath.moveToPoint(self.segmentPoints[2].1) var startAngle = self.arcStartingAngles[3] var endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArcWithCenter(self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLineToPoint(self.segmentPoints[3].1) startAngle = self.arcStartingAngles[0] endAngle = startAngle + CGFloat(M_PI/2.0) underPath.addArcWithCenter(self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true) underPath.addLineToPoint(CGPointMake(self.segmentPoints[0].0.x, self.segmentPoints[0].0.y - self.underOffset)) startAngle = self.arcStartingAngles[1] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArcWithCenter(CGPointMake(self.arcCenters[0].x, self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.addLineToPoint(CGPointMake(self.segmentPoints[2].1.x - self.cornerRadius, self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset)) startAngle = self.arcStartingAngles[0] endAngle = startAngle - CGFloat(M_PI/2.0) underPath.addArcWithCenter(CGPointMake(self.arcCenters[3].x, self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false) underPath.closePath() return underPath }() self.fillPath = fillPath self.edgePaths = edgePaths self.underPath = underPath } func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint) { let returnValue = ( self.segmentPoints[direction.clockwise().rawValue].0, self.segmentPoints[direction.counterclockwise().rawValue].1) return returnValue } func attachmentDirection() -> Direction? { return self.attached } func attach(direction: Direction?) { self.attached = direction } }
bsd-3-clause
9890d36f3109b12f6dbacbca98bcc5b1
36.077193
212
0.566859
5.226014
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Settings/SettingsCurrencyTableViewCell.swift
1
3132
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import SwiftyArk class SettingsCurrencyTableViewCell: UITableViewCell { var titleLabel : UILabel! var currencyLabel : UILabel! init(_ currency: Currency) { super.init(style: .default, reuseIdentifier: "currency") backgroundColor = ArkPalette.backgroundColor selectionStyle = .none titleLabel = UILabel() titleLabel.text = "Reference Currency" titleLabel.textColor = ArkPalette.highlightedTextColor titleLabel.font = UIFont.systemFont(ofSize: 16.0, weight: .semibold) addSubview(titleLabel) titleLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.left.equalTo(15.0) make.width.equalTo(250.0) } let chevron = UIImageView(image: #imageLiteral(resourceName: "chevron")) addSubview(chevron) chevron.snp.makeConstraints { (make) in make.height.width.equalTo(15.0) make.centerY.equalToSuperview() make.right.equalToSuperview().offset(-15.0) } currencyLabel = UILabel() currencyLabel.textAlignment = .right currencyLabel.text = currency.rawValue currencyLabel.textColor = ArkPalette.textColor currencyLabel.font = UIFont.systemFont(ofSize: 18.0, weight: .regular) addSubview(currencyLabel) currencyLabel.snp.makeConstraints { (make) in make.top.bottom.equalToSuperview() make.width.equalTo(100.0) make.right.equalTo(chevron.snp.left).offset(-10.0) } let seperator = UIView() seperator.backgroundColor = ArkPalette.secondaryBackgroundColor addSubview(seperator) seperator.snp.makeConstraints { (make) in make.left.right.bottom.equalToSuperview() make.height.equalTo(1.0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
6287131f272e51f5e7dafbbfdb05d545
40.76
137
0.679119
4.825886
false
false
false
false
dkarsh/SwiftGoal
SwiftGoal/Helpers/Extensions.swift
2
2928
// // Extensions.swift // SwiftGoal // // Created by Martin Richter on 23/06/15. // Copyright (c) 2015 Martin Richter. All rights reserved. // import ReactiveCocoa import Result extension Array { func difference<T: Equatable>(otherArray: [T]) -> [T] { var result = [T]() for e in self { if let element = e as? T { if !otherArray.contains(element) { result.append(element) } } } return result } func intersection<T: Equatable>(otherArray: [T]) -> [T] { var result = [T]() for e in self { if let element = e as? T { if otherArray.contains(element) { result.append(element) } } } return result } } extension UIStepper { func signalProducer() -> SignalProducer<Int, NoError> { return self.rac_newValueChannelWithNilValue(0).toSignalProducer() .map { $0 as! Int } .flatMapError { _ in return SignalProducer<Int, NoError>.empty } } } extension UITextField { func signalProducer() -> SignalProducer<String, NoError> { return self.rac_textSignal().toSignalProducer() .map { $0 as! String } .flatMapError { _ in return SignalProducer<String, NoError>.empty } } } extension UIViewController { func isActive() -> SignalProducer<Bool, NoError> { // Track whether view is visible let viewWillAppear = rac_signalForSelector(#selector(viewWillAppear(_:))).toSignalProducer() let viewWillDisappear = rac_signalForSelector(#selector(viewWillDisappear(_:))).toSignalProducer() let viewIsVisible = SignalProducer<SignalProducer<Bool, NSError>, NoError>(values: [ viewWillAppear.map { _ in true }, viewWillDisappear.map { _ in false } ]).flatten(.Merge) // Track whether app is in foreground let notificationCenter = NSNotificationCenter.defaultCenter() let didBecomeActive = notificationCenter .rac_addObserverForName(UIApplicationDidBecomeActiveNotification, object: nil) .toSignalProducer() let willBecomeInactive = notificationCenter .rac_addObserverForName(UIApplicationWillResignActiveNotification, object: nil) .toSignalProducer() let appIsActive = SignalProducer<SignalProducer<Bool, NSError>, NoError>(values: [ SignalProducer(value: true), // Account for app being initially active without notification didBecomeActive.map { _ in true }, willBecomeInactive.map { _ in false } ]).flatten(.Merge) // View controller is active iff both are true: return combineLatest(viewIsVisible, appIsActive) .map { $0 && $1 } .flatMapError { _ in SignalProducer.empty } } }
mit
1023262ae7ae846e84ee8db920dab521
29.821053
106
0.605874
5.005128
false
false
false
false
krzyzanowskim/Natalie
Sources/natalie/main.swift
1
881
// // main.swift // Natalie // // Created by Marcin Krzyzanowski on 07/08/16. // Copyright © 2016 Marcin Krzyzanowski. All rights reserved. // import Foundation func printUsage() { print("Usage:") print("natalie <storyboard-path or directory>") } if CommandLine.arguments.count == 1 { printUsage() exit(1) } var filePaths: [String] = [] let storyboardSuffix = ".storyboard" for arg in CommandLine.arguments.dropFirst() { if arg == "--help" { printUsage() exit(0) } else if arg.hasSuffix(storyboardSuffix) { filePaths.append(arg) } else if let s = findStoryboards(rootPath: arg, suffix: storyboardSuffix) { filePaths.append(contentsOf: s) } } let storyboardFiles = filePaths.compactMap { try? StoryboardFile(filePath: $0) } let output = Natalie.process(storyboards: storyboardFiles) print(output) exit(0)
mit
5f684abfcea261700eea65179da38ccc
21
80
0.671591
3.666667
false
false
false
false