repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
NeoTeo/SwiftIpfsApi
refs/heads/master
SwiftIpfsApi/Multipart.swift
mit
2
// // Multipart.swift // SwiftIpfsApi // // Created by Matteo Sartori on 20/10/15. // Copyright © 2015 Teo Sartori. All rights reserved. // // Licensed under MIT See LICENCE file in the root of this project for details. import Foundation public enum MultipartError : Error { case failedURLCreation case invalidEncoding } public struct Multipart { static let lineFeed:String = "\r\n" let boundary: String let encoding: String.Encoding let charset: String var body = NSMutableData() let request: NSMutableURLRequest init(targetUrl: String, encoding: String.Encoding) throws { // Eg. UTF8 self.encoding = encoding guard let charset = Multipart.charsetString(from: encoding) else { throw MultipartError.invalidEncoding } self.charset = charset boundary = Multipart.createBoundary() guard let url = URL(string: targetUrl) else { throw MultipartError.failedURLCreation } request = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary="+boundary, forHTTPHeaderField: "content-type") request.setValue("Swift IPFS Client", forHTTPHeaderField: "user-agent") } } extension Multipart { static func charsetString(from encoding: String.Encoding) -> String? { switch encoding { case String.Encoding.utf8: return "UTF8" case String.Encoding.ascii: return "ASCII" default: return nil } } /// Generate a string of 32 random alphanumeric characters. static func createBoundary() -> String { let allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let maxCount = allowed.count let count = 32 var output = "" for _ in 0 ..< count { let r = Int(arc4random_uniform(UInt32(maxCount))) let randomIndex = allowed.index(allowed.startIndex, offsetBy: r) output += String(allowed[randomIndex]) } return output } static func addFormField(oldMultipart: Multipart, name: String, value: String) throws -> Multipart { let encoding = oldMultipart.encoding var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-disposition: form-data; name=\"" + name + "\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-type: text/plain; charset=\"" + oldMultipart.charset + "\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) oldMultipart.body.append(value.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) return oldMultipart } static func addDirectoryPart(oldMultipart: Multipart, path: String) throws -> Multipart { let encoding = oldMultipart.encoding var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-disposition: file; filename=\"\(path)\"" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-type: application/x-directory" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) outString = "content-transfer-encoding: binary" + lineFeed oldMultipart.body.append(outString.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) oldMultipart.body.append(lineFeed.data(using: encoding)!) return oldMultipart } public static func addFilePart(_ oldMultipart: Multipart, fileName: String?, fileData: Data) throws -> Multipart { var outString = "--" + oldMultipart.boundary + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) if fileName != nil { outString = "content-disposition: file; filename=\"\(fileName!)\";" + lineFeed } else { outString = "content-disposition: file; name=\"file\";" + lineFeed } oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) outString = "content-type: application/octet-stream" + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) outString = "content-transfer-encoding: binary" + lineFeed + lineFeed oldMultipart.body.append(outString.data(using: String.Encoding.utf8)!) /// Add the actual data for this file. oldMultipart.body.append(fileData) oldMultipart.body.append(lineFeed.data(using: String.Encoding.utf8)!) return oldMultipart } public static func finishMultipart(_ multipart: Multipart, completionHandler: @escaping (Data) -> Void) { let outString = "--" + multipart.boundary + "--" + lineFeed multipart.body.append(outString.data(using: String.Encoding.utf8)!) multipart.request.setValue(String(multipart.body.length), forHTTPHeaderField: "content-length") multipart.request.httpBody = multipart.body as Data /// Send off the request let task = URLSession.shared.dataTask(with: (multipart.request as URLRequest)) { (data: Data?, response: URLResponse?, error: Error?) -> Void in // FIXME: use Swift 5 Result type rather than passing nil data. if error != nil || data == nil { print("Error in dataTaskWithRequest: \(String(describing: error))") let emptyData = Data() completionHandler(emptyData) return } completionHandler(data!) } task.resume() } }
7e87901db67be48748021ebeb89e45b9
35.128655
118
0.623665
false
false
false
false
appsquickly/Typhoon-Swift-Example
refs/heads/master
PocketForecast/Client/WeatherClientBasicImpl.swift
apache-2.0
1
//////////////////////////////////////////////////////////////////////////////// // // TYPHOON FRAMEWORK // Copyright 2013, Typhoon Framework Contributors // All Rights Reserved. // // NOTICE: The authors permit you to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. // //////////////////////////////////////////////////////////////////////////////// import Foundation public class WeatherClientBasicImpl: NSObject, WeatherClient { var weatherReportDao: WeatherReportDao? var serviceUrl: NSURL? var daysToRetrieve: NSNumber? var apiKey: String? { willSet(newValue) { assert(newValue != "$$YOUR_API_KEY_HERE$$", "Please get an API key (v2) from: http://free.worldweatheronline.com, and then " + "edit 'Configuration.plist'") } } public func loadWeatherReportFor(city: String!, onSuccess successBlock: @escaping ((WeatherReport) -> Void), onError errorBlock: @escaping ((String) -> Void)) { DispatchQueue.global(priority: .high).async() { let url = self.queryURL(city: city) let data : Data! = try! Data(contentsOf: url) let dictionary = (try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary if let error = dictionary.parseError() { DispatchQueue.main.async() { errorBlock(error.rootCause()) return } } else { let weatherReport: WeatherReport = dictionary.toWeatherReport() self.weatherReportDao!.saveReport(weatherReport: weatherReport) DispatchQueue.main.async() { successBlock(weatherReport) return } } } } private func queryURL(city: String) -> URL { let serviceUrl: NSURL = self.serviceUrl! return serviceUrl.uq_URL(byAppendingQueryDictionary: [ "q": city, "format": "json", "num_of_days": daysToRetrieve!.stringValue, "key": apiKey! ]) } }
7a3a995890f6bd63d060f796da8eece6
33.323077
164
0.550874
false
false
false
false
eonil/toolbox.swift
refs/heads/master
EonilToolbox/DisplayLinkUtility-iOS.swift
mit
1
// // DisplayLinkUtility-iOS.swift // EonilToolbox // // Created by Hoon H. on 2016/06/05. // Copyright © 2016 Eonil. All rights reserved. // #if os(iOS) import Foundation import UIKit import CoreGraphics import CoreVideo public enum DisplayLinkError: Error { case cannotCreateLink } public struct DisplayLinkUtility { fileprivate typealias Error = DisplayLinkError fileprivate static var link: CADisplayLink? fileprivate static let proxy = TargetProxy() fileprivate static var handlers = Dictionary<ObjectIdentifier, ()->()>() public static func installMainScreenHandler(_ id: ObjectIdentifier, f: @escaping ()->()) throws { assertMainThread() assert(handlers[id] == nil) if handlers.count == 0 { // `CADisplayLink` retains `target`. // So we need a proxy to break retain cycle. link = CADisplayLink(target: proxy, selector: #selector(TargetProxy.TOOLBOX_onTick(_:))) guard let link = link else { throw Error.cannotCreateLink } link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) link.add(to: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode) } handlers[id] = f } public static func deinstallMainScreenHandler(_ id: ObjectIdentifier) { assertMainThread() assert(handlers[id] != nil) handlers[id] = nil if handlers.count == 0 { assert(link != nil) var moved: CADisplayLink? swap(&moved, &link) guard let link = moved else { fatalError("Display-link is missing...") } link.remove(from: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode) link.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) } } fileprivate static func callback() { for (_, h) in handlers { h() } } } @objc private final class TargetProxy: NSObject { @objc func TOOLBOX_onTick(_: AnyObject?) { DisplayLinkUtility.callback() } } #endif
a347e467f7603d2de4a74bdc9b24c58a
31.464789
105
0.569631
false
false
false
false
dmorrow/UTSwiftUtils
refs/heads/master
Classes/Base/NSObject+UT.swift
mit
1
// // NSObject+UT.swift // // Created by Daniel Morrow on 10/25/16. // Copyright © 2016 unitytheory. All rights reserved. // import Foundation extension NSObject { public typealias cancellable_closure = (() -> ())? @discardableResult public func delay(_ delay:TimeInterval, closure:@escaping ()->()) -> cancellable_closure{ var cancelled = false let cancel_closure: cancellable_closure = { cancelled = true } DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + delay, execute: { if !cancelled { closure() } } ) return cancel_closure } public func cancel_delay(_ cancel_closure: cancellable_closure?) { if let closure = cancel_closure { closure?() } } }
27f9198c185b56d855e80485df8d6789
22.736842
93
0.532151
false
false
false
false
alvarozizou/Noticias-Leganes-iOS
refs/heads/develop
NoticiasLeganes/Position/PositionAPIService.swift
mit
1
// // PositionAPIService.swift // NoticiasLeganes // // Created by Alvaro Blazquez Montero on 17/9/17. // Copyright © 2017 Alvaro Blazquez Montero. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class PositionAPIService: DataManager { func getData(completionHandler: @escaping completion) { let headers: HTTPHeaders = [ "X-Auth-Token": K.Key ] Alamofire.request(K.PositionURL, method: .get, headers: headers).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) let positions = self.getList(json: json) completionHandler(positions, nil) case .failure(let error): completionHandler(nil, error) } } } private func getList(json: JSON) -> [Position] { guard let standings = json[PositionKey.standing.rawValue] .arrayValue .first(where: { $0[PositionKey.type.rawValue].stringValue == PositionKey.total.rawValue } ) else { return [Position]() } return standings[PositionKey.table.rawValue].arrayValue.map { Position(json: $0) } } }
e04257129b6e691107852a64ba8b7dc2
31.97619
111
0.553791
false
false
false
false
dzenbot/XCSwiftr
refs/heads/master
XCSwiftr/Classes/ViewControllers/XCSConverterWindowController.swift
mit
1
// // XCSConverterWindowController.swift // XCSwiftr // // Created by Ignacio Romero on 4/3/16. // Copyright © 2016 DZN Labs. All rights reserved. // import Cocoa private let XCSwifterDomain = "com.dzn.XCSwiftr" extension Bool { init<T: Integer>(_ integer: T) { self.init(integer != 0) } } class XCSConverterWindowController: NSWindowController, NSTextViewDelegate { let commandController = XCSCommandController() let snippetManager = XCSSnippetManager(domain: XCSwifterDomain) var initialText: String? var inPlugin: Bool = false var autoConvert: Bool = false #if PLUGIN @IBOutlet var primaryTextView: DVTSourceTextView! @IBOutlet var secondaryTextView: DVTSourceTextView! #else @IBOutlet var primaryTextView: NSTextView! @IBOutlet var secondaryTextView: NSTextView! #endif @IBOutlet var autoCheckBox: NSButton! @IBOutlet var cancelButton: NSButton! @IBOutlet var acceptButton: NSButton! @IBOutlet var progressIndicator: NSProgressIndicator! var loading: Bool = false { didSet { if loading { self.progressIndicator.startAnimation(self) self.acceptButton.title = "" } else { self.progressIndicator.stopAnimation(self) self.acceptButton.title = "Convert" } } } // MARK: View lifecycle override func windowDidLoad() { super.windowDidLoad() primaryTextView.delegate = self primaryTextView.string = "" secondaryTextView.string = "" if let string = initialText { primaryTextView.string = string convertToSwift(objcString: string) updateAcceptButton() } if inPlugin == true { cancelButton.isHidden = false } } // MARK: Actions func convertToSwift(objcString: String?) { guard let objcString = objcString else { return } loading = true snippetManager.cacheTemporary(snippet: objcString) { (filePath) in if let path = filePath { self.commandController.objc2Swift(path) { (result) in self.loading = false self.secondaryTextView.string = result } } } } func updateAcceptButton() { acceptButton.isEnabled = ((primaryTextView.string?.characters.count)! > 0) } // MARK: IBActions @IBAction func convertAction(sender: AnyObject) { convertToSwift(objcString: primaryTextView.string) } @IBAction func dismissAction(sender: AnyObject) { guard let window = window, let sheetParent = window.sheetParent else { return } sheetParent.endSheet(window, returnCode: NSModalResponseCancel) } @IBAction func autoConvert(sender: AnyObject) { autoConvert = Bool(autoCheckBox.state) } // MARK: NSTextViewDelegate func textDidChange(_ notification: Notification) { updateAcceptButton() } }
127f00a04b843f79f91ec79b25975fc9
23.496
87
0.629001
false
false
false
false
AkshayNG/iSwift
refs/heads/master
iSwift/UI Components/UIView/UICounterControl.swift
mit
1
// // UICounterController.swift // iSwift // // Created by Akshay Gajarlawar on 09/05/17. // Copyright © 2017 yantrana. All rights reserved. // import UIKit class UICounterControl: UIView { var minValue:NSInteger = 0 var maxValue:NSInteger = 0 var controlColor:UIColor = UIColor.gray var controlTextColor:UIColor = UIColor.white var counterColor:UIColor = UIColor.lightGray var counterTextColor:UIColor = UIColor.black var minusImage:UIImage? var plusImage:UIImage? override init(frame: CGRect) { super.init(frame: frame) if(frame.size.height < frame.size.width/3) { fatalError("init(frame:) INVALID : Frame width (\(frame.size.width)) must be at least thrice the frame height(\(frame.size.height)) . e.g frame must have width >= (height * 3)") } self.clipsToBounds = true self.backgroundColor = UIColor.yellow self.layer.cornerRadius = 5.0 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { /*** Left Contol ***/ let minusBtn = UIButton.init(type: .custom) minusBtn.backgroundColor = controlColor minusBtn.frame = CGRect(x:1, y:1, width:rect.size.height - 2, height:rect.size.height - 2) if(minusImage != nil) { minusBtn .setImage(minusImage, for: .normal) } else { minusBtn.setTitle("-", for: .normal) minusBtn.setTitleColor(controlTextColor, for: .normal) minusBtn.titleLabel?.font = UIFont.systemFont(ofSize: minusBtn.frame.size.height/2) } /*** Right Contol ***/ let plusBtn = UIButton.init(type: .custom) plusBtn.backgroundColor = controlColor let plusX = rect.size.width - (minusBtn.frame.size.width + 1) plusBtn.frame = CGRect(x:plusX, y:minusBtn.frame.origin.y, width:minusBtn.frame.size.width, height:minusBtn.frame.size.height) if(plusImage != nil) { plusBtn .setImage(plusImage, for: .normal) } else { plusBtn.setTitle("+", for: .normal) plusBtn.setTitleColor(controlTextColor, for: .normal) plusBtn.titleLabel?.font = UIFont.systemFont(ofSize: plusBtn.frame.size.height/2) } /*** COUNTER ***/ let counterLbl = UILabel.init() let counterX = minusBtn.frame.size.width + 2 let counterWidth = rect.size.width - ( minusBtn.frame.size.width*2 + 4) counterLbl.frame = CGRect(x:counterX, y:minusBtn.frame.origin.y, width:counterWidth, height:minusBtn.frame.size.height) counterLbl.backgroundColor = counterColor counterLbl.textColor = counterTextColor /*** Add ***/ self.addSubview(minusBtn) self.addSubview(plusBtn) self.addSubview(counterLbl) } }
a41515827b6daa77517489efcc3da977
32.19
189
0.554083
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePaymentSheet/StripePaymentSheet/Helpers/STPStringUtils.swift
mit
1
// // STPStringUtils.swift // StripePaymentSheet // // Created by Brian Dorfman on 9/7/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripePaymentsUI typealias STPTaggedSubstringCompletionBlock = (String?, NSRange) -> Void typealias STPTaggedSubstringsCompletionBlock = (String, [String: NSValue]) -> Void extension STPStringUtils { /// Takes a string with the named html-style tags, removes the tags, /// and then calls the completion block with the modified string and the range /// in it that the tag would have enclosed. /// E.g. Passing in @"Test <b>string</b>" with tag @"b" would call completion /// with @"Test string" and NSMakeRange(5,6). /// Completion is always called, location of range is NSNotFound with the unmodified /// string if a match could not be found. /// - Parameters: /// - string: The string with tagged substrings. /// - tag: The tag to search for. /// - completion: The string with the named tag removed and the range of the /// substring it covered. @objc(parseRangeFromString:withTag:completion:) class func parseRange( from string: String, withTag tag: String, completion: STPTaggedSubstringCompletionBlock ) { let startingTag = "<\(tag)>" let startingTagRange = (string as NSString?)?.range(of: startingTag) if startingTagRange?.location == NSNotFound { completion(string, startingTagRange!) return } var finalString: String? if let startingTagRange = startingTagRange { finalString = (string as NSString?)?.replacingCharacters(in: startingTagRange, with: "") } let endingTag = "</\(tag)>" let endingTagRange = (finalString as NSString?)?.range(of: endingTag) if endingTagRange?.location == NSNotFound { completion(string, endingTagRange!) return } if let endingTagRange = endingTagRange { finalString = (finalString as NSString?)?.replacingCharacters( in: endingTagRange, with: "") } let finalTagRange = NSRange( location: startingTagRange?.location ?? 0, length: (endingTagRange?.location ?? 0) - (startingTagRange?.location ?? 0)) completion(finalString, finalTagRange) } /// Like `parseRangeFromString:withTag:completion:` but you can pass in a set /// of unique tags to get the ranges for and it will return you the mapping. /// E.g. Passing @"<a>Test</a> <b>string</b>" with the tag set [a, b] /// will get you a completion block dictionary that looks like /// @{ @"a" : NSMakeRange(0,4), /// @"b" : NSMakeRange(5,6) } /// - Parameters: /// - string: The string with tagged substrings. /// - tags: The tags to search for. /// - completion: The string with the named tags removed and the ranges of the /// substrings they covered (wrapped in NSValue) /// @warning Doesn't currently support overlapping tag ranges because that's /// complicated and we don't need it at the moment. @objc(parseRangesFromString:withTags:completion:) class func parseRanges( from string: String, withTags tags: Set<String>, completion: STPTaggedSubstringsCompletionBlock ) { var interiorRangesToTags: [NSValue: String] = [:] var tagsToRange: [String: NSValue] = [:] for tag in tags { self.parseRange( from: string, withTag: tag ) { _, tagRange in if tagRange.location == NSNotFound { tagsToRange[tag] = NSValue(range: tagRange) } else { let interiorRange = NSRange( location: tagRange.location + tag.count + 2, length: tagRange.length) interiorRangesToTags[NSValue(range: interiorRange)] = tag } } } let sortedRanges = interiorRangesToTags.keys.sorted { (obj1, obj2) -> Bool in let range1 = obj1.rangeValue let range2 = obj2.rangeValue return range1.location < range2.location } var modifiedString = string var deletedCharacters = 0 for rangeValue in sortedRanges { let tag = interiorRangesToTags[rangeValue] var interiorTagRange = rangeValue.rangeValue if interiorTagRange.location != NSNotFound { interiorTagRange.location -= deletedCharacters let beginningTagLength = (tag?.count ?? 0) + 2 let beginningTagRange = NSRange( location: interiorTagRange.location - beginningTagLength, length: beginningTagLength) if let subRange = Range<String.Index>(beginningTagRange, in: modifiedString) { modifiedString.removeSubrange(subRange) } interiorTagRange.location -= beginningTagLength deletedCharacters += beginningTagLength let endingTagLength = beginningTagLength + 1 let endingTagRange = NSRange( location: interiorTagRange.location + interiorTagRange.length, length: endingTagLength) if let subRange = Range<String.Index>(endingTagRange, in: modifiedString) { modifiedString.removeSubrange(subRange) } deletedCharacters += endingTagLength tagsToRange[tag!] = NSValue(range: interiorTagRange) } } completion(modifiedString, tagsToRange) } }
716e8b5e700791050bae5d5443599151
40.640288
100
0.605045
false
false
false
false
silence0201/Swift-Study
refs/heads/master
AdvancedSwift/可选值/A Tour of Optional Techniques - switch-case Matching for Optionals:.playgroundpage/Contents.swift
mit
1
/*: ### `switch`-`case` Matching for Optionals: Another consequence of optionals not being `Equatable` is that you can't check them in a `case` statement. `case` matching is controlled in Swift by the `~=` operator, and the relevant definition looks a lot like the one that wasn't working for arrays: ``` swift-example func ~=<T: Equatable>(a: T, b: T) -> Bool ``` But it's simple to produce a matching version for optionals that just calls `==`: */ //#-editable-code func ~=<T: Equatable>(pattern: T?, value: T?) -> Bool { return pattern == value } //#-end-editable-code /*: It's also nice to implement a range match at the same time: */ //#-editable-code func ~=<Bound>(pattern: Range<Bound>, value: Bound?) -> Bool { return value.map { pattern.contains($0) } ?? false } //#-end-editable-code /*: Here, we use `map` to check if a non-`nil` value is inside the interval. Because we want `nil` not to match any interval, we return `false` in case of `nil`. Given this, we can now match optional values with `switch`: */ //#-editable-code for i in ["2", "foo", "42", "100"] { switch Int(i) { case 42: print("The meaning of life") case 0..<10: print("A single digit") case nil: print("Not a number") default: print("A mystery number") } } //#-end-editable-code
5270dfa161f5918fcedb7eb37b32d809
22.839286
80
0.641948
false
false
false
false
qrpc/orbits
refs/heads/master
orbits/GameScene.swift
gpl-3.0
1
// // GameScene.swift // orbits // // Created by Robert Altenburg on 5/13/15. // Copyright (c) 2015 Robert Altenburg. All rights reserved. // import SpriteKit enum BodyType:UInt32 { case star = 1 case ship = 2 case weapon = 4 } class GameScene: SKScene, SKPhysicsContactDelegate { let star = SKSpriteNode(imageNamed:"Sun") let ship = [Ship(imageNamed: "Spaceship", name: "Player One", controlLeft: 123, controlRight: 124, controlThrust: 126, controlFire: 125), Ship(imageNamed: "Ship2", name: "Player Two", controlLeft: 0, controlRight: 2, controlThrust: 13, controlFire: 1)] var missle = [Missle]() override func didMove(to view: SKView) { //set up physics physicsWorld.contactDelegate = self let gravField = SKFieldNode.radialGravityField(); // Create grav field gravField.position = CGPoint(x: size.width/2.0, y: size.height/2) addChild(gravField); // Add to world // setting graphics self.backgroundColor = NSColor.black // set up star field with stars of different sizes for _ in 1...100 { let c = SKShapeNode(circleOfRadius: (CGFloat(arc4random_uniform(10)) / 70.0)) c.strokeColor = SKColor.white c.position = CGPoint(x: CGFloat(arc4random_uniform(UInt32(self.size.width))), y: CGFloat(arc4random_uniform(UInt32(self.size.height)))) self.addChild(c) } // set up star in center star.position = gravField.position star.setScale(0.08) star.name = "Star" star.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "Sun"), size: star.size) if let physics = star.physicsBody { physics.isDynamic = false physics.categoryBitMask = BodyType.star.rawValue } self.addChild(star) // place the ships ship[0].position = CGPoint(x: size.width * 0.25, y:size.height * 0.5) ship[0].physicsBody?.velocity = CGVector(dx: 0, dy: 100) self.addChild(ship[0]) ship[1].position = CGPoint(x: size.width * 0.75, y:size.height * 0.5) ship[1].physicsBody?.velocity = CGVector(dx: 0, dy: -100) self.addChild(ship[1]) } func endGame() { self.run(SKAction.wait(forDuration: 4), completion: { let scene = EndScene(size: self.size) self.view?.presentScene(scene, transition: SKTransition.crossFade(withDuration: 2)) }) } func didBegin(_ contact: SKPhysicsContact) { let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask var actionBody:SKPhysicsBody var otherBody:SKPhysicsBody switch(contactMask) { // contactMask 3 = ship hit the star case BodyType.ship.rawValue | BodyType.star.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Star" { actionBody = contact.bodyB } else { actionBody = contact.bodyA } explosion(actionBody.node!.position) actionBody.node!.removeFromParent() endGame() // contactMask = 5: weapon hit star case BodyType.weapon.rawValue | BodyType.star.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Star" { actionBody = contact.bodyB } else { actionBody = contact.bodyA } actionBody.node!.removeFromParent() // contactMask = 5: weapon hit ship case BodyType.weapon.rawValue | BodyType.ship.rawValue: // make sure action takes place on the ship if contact.bodyA.node!.name == "Missle" { actionBody = contact.bodyB otherBody = contact.bodyA } else { actionBody = contact.bodyA otherBody = contact.bodyB } explosion(actionBody.node!.position) actionBody.node!.removeFromParent() otherBody.node!.removeFromParent() endGame() default: print("Uncaught contact made: \(contactMask)") return } } func explosion(_ pos: CGPoint) { let emitterNode = SKEmitterNode(fileNamed: "explosion.sks") emitterNode!.particlePosition = pos self.addChild(emitterNode!) // Don't forget to remove the emitter node after the explosion self.run(SKAction.wait(forDuration: 2), completion: { emitterNode!.removeFromParent() }) } override func keyDown(with theEvent: NSEvent) { //println(theEvent.keyCode) // respond to ship events for s in ship { if theEvent.keyCode == s.controlThrust { s.thrust() } else if theEvent.keyCode == s.controlLeft { s.left() } else if theEvent.keyCode == s.controlRight { s.right() } else if theEvent.keyCode == s.controlFire { s.fire(self, missle: &missle) } /*else { println("Key: \(theEvent.keyCode)") }*/ } print("Key: \(theEvent.keyCode)") } func screenWrap(_ node:SKSpriteNode)->Void { // wrap if object exits screen if node.position.x < 0 { node.position.x = size.width } else if node.position.x > size.width { node.position.x = 0 } if node.position.y < 0 { node.position.y = size.height } else if node.position.y > size.height { node.position.y = 0 } } override func update(_ currentTime: TimeInterval) { /* Called before each frame is rendered */ for s in ship { screenWrap(s) } for m in missle { //Turn the missles into the direction of travel m.zRotation = CGFloat(M_2_PI - M_PI/4) - atan2(m.physicsBody!.velocity.dx , m.physicsBody!.velocity.dy) //Don't wrap missles unless they have a lifespan screenWrap(m) //TODO: remove missle from the array when they leave screen } } }
b0856605cd98a28b5b1204dfe3d06c1e
30.764423
141
0.548963
false
false
false
false
manavgabhawala/CocoaMultipeer
refs/heads/master
MultipeerCocoaiOS/MGBrowserTableViewController.swift
apache-2.0
1
// // MGBrowserViewController.swift // CocoaMultipeer // // Created by Manav Gabhawala on 05/07/15. // // import UIKit protocol MGBrowserTableViewControllerDelegate : NSObjectProtocol { var minimumPeers: Int { get } var maximumPeers: Int { get } } @objc internal class MGBrowserTableViewController: UITableViewController { /// The browser passed to the initializer for which this class is presenting a UI for. (read-only) internal let browser: MGNearbyServiceBrowser /// The session passed to the initializer for which this class is presenting a UI for. (read-only) internal let session: MGSession internal weak var delegate: MGBrowserTableViewControllerDelegate! private var availablePeers = [MGPeerID]() /// Initializes a browser view controller with the provided browser and session. /// - Parameter browser: An object that the browser view controller uses for browsing. This is usually an instance of MGNearbyServiceBrowser. However, if your app is using a custom discovery scheme, you can instead pass any custom subclass that calls the methods defined in the MCNearbyServiceBrowserDelegate protocol on its delegate when peers are found and lost. /// - Parameter session: The multipeer session into which the invited peers are connected. /// - Returns: An initialized browser. /// - Warning: If you want the browser view controller to manage the browsing process, the browser object must not be actively browsing, and its delegate must be nil. internal init(browser: MGNearbyServiceBrowser, session: MGSession, delegate: MGBrowserTableViewControllerDelegate) { self.browser = browser self.session = session self.delegate = delegate super.init(style: .Grouped) self.browser.delegate = self } required internal init?(coder aDecoder: NSCoder) { let peer = MGPeerID() self.browser = MGNearbyServiceBrowser(peer: peer, serviceType: "custom-server") self.session = MGSession(peer: peer) super.init(coder: aDecoder) self.browser.delegate = self } internal override func viewDidLoad() { navigationItem.title = "" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "donePressed:") navigationItem.rightBarButtonItem?.enabled = false navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "cancelPressed:") } internal override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) browser.startBrowsingForPeers() NSNotificationCenter.defaultCenter().addObserver(self, selector: "sessionUpdated:", name: MGSession.sessionPeerStateUpdatedNotification, object: session) tableView.reloadData() } internal override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self, name: MGSession.sessionPeerStateUpdatedNotification, object: session) browser.stopBrowsingForPeers() } internal func sessionUpdated(notification: NSNotification) { guard notification.name == MGSession.sessionPeerStateUpdatedNotification else { return } dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(indexesInRange: NSRange(location: 0, length: 2)), withRowAnimation: .Automatic) }) if self.session.connectedPeers.count >= self.delegate.minimumPeers { self.navigationItem.rightBarButtonItem?.enabled = true } else { self.navigationItem.rightBarButtonItem?.enabled = false } } // MARK: - Actions internal func donePressed(sender: UIBarButtonItem) { guard session.connectedPeers.count >= delegate.minimumPeers && session.connectedPeers.count <= delegate.maximumPeers else { sender.enabled = false return } dismissViewControllerAnimated(true, completion: nil) } internal func cancelPressed(sender: UIBarButtonItem) { session.disconnect() dismissViewControllerAnimated(true, completion: nil) } } // MARK: - TableViewStuff extension MGBrowserTableViewController { internal override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } internal override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? session.peers.count : availablePeers.count } internal override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell if indexPath.section == 0 { cell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "connected") cell.textLabel!.text = session.peers[indexPath.row].peer.displayName cell.detailTextLabel!.text = session.peers[indexPath.row].state.description cell.selectionStyle = .None } else { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "available") if availablePeers.count > indexPath.row { cell.textLabel!.text = availablePeers[indexPath.row].displayName } cell.selectionStyle = .Default } return cell } internal override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.cellForRowAtIndexPath(indexPath)!.setHighlighted(false, animated: true) guard indexPath.section == 1 && delegate.maximumPeers > session.peers.count else { return } dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { do { try self.browser.invitePeer(self.availablePeers[indexPath.row], toSession: self.session) } catch { MGLog("Couldn't find peer. Refreshing.") MGDebugLog("Attemtpting to connect to an unknown service. Removing the listing and refreshing the view to recover. \(error)") self.availablePeers.removeAtIndex(indexPath.row) // Couldn't find the peer so let's reload the table. dispatch_async(dispatch_get_main_queue(), self.tableView.reloadData) } }) } internal override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Connected Peers" : "Available Peers" } internal override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { return section == 0 ? nil : "This device will appear as \(browser.myPeerID.displayName). You must connect to at least \(delegate.minimumPeers.peerText) and no more than \(delegate.maximumPeers.peerText)." } } // MARK: - Browser stuff extension MGBrowserTableViewController : MGNearbyServiceBrowserDelegate { internal func browserDidStartSuccessfully(browser: MGNearbyServiceBrowser) { tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) } internal func browser(browser: MGNearbyServiceBrowser, didNotStartBrowsingForPeers error: [String : NSNumber]) { // TODO: Handle the error. } internal func browser(browser: MGNearbyServiceBrowser, foundPeer peerID: MGPeerID, withDiscoveryInfo info: [String : String]?) { assert(browser === self.browser) guard peerID != session.myPeerID && peerID != browser.myPeerID else { return } // This should never happen but its better to check availablePeers.append(peerID) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) }) } internal func browser(browser: MGNearbyServiceBrowser, lostPeer peerID: MGPeerID) { assert(browser === self.browser) guard peerID != session.myPeerID && peerID != browser.myPeerID else { // FIXME: Fail silently fatalError("We lost the browser to our own peer. Something went wrong in the browser.") } availablePeers.removeElement(peerID) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic) }) } internal func browser(browser: MGNearbyServiceBrowser, didReceiveInvitationFromPeer peerID: MGPeerID, invitationHandler: (Bool, MGSession) -> Void) { guard session.connectedPeers.count == 0 else { // We are already connected to some peers so we can't accept any other connections. invitationHandler(false, session) return } let alertController = UIAlertController(title: "\(peerID.displayName) wants to connect?", message: nil, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "Decline", style: .Destructive, handler: { action in invitationHandler(false, self.session) })) alertController.addAction(UIAlertAction(title: "Accept", style: UIAlertActionStyle.Default, handler: {action in invitationHandler(true, self.session) // Remove self since we accepted the connection. self.dismissViewControllerAnimated(true, completion: nil) })) presentViewController(alertController, animated: true, completion: nil) } internal func browserStoppedSearching(browser: MGNearbyServiceBrowser) { // availablePeers.removeAll() } }
280e23f869ab787974ff06e839f67add
37.465217
365
0.765544
false
false
false
false
rwyland/MMDB
refs/heads/master
MMDB Swift/MovieDBService.swift
apache-2.0
1
// // MovieDBService.swift // MMDB Swift // // Created by Rob W on 12/11/15. // Copyright © 2015 Org Inc. All rights reserved. // import UIKit protocol MovieLookupDelegate { /** A Delegate to receive responses for async network calls. */ func receivedMovies(movies: Array<Movie>, forPage page: Int) /** A movie returned for a specific lookup on id. This will cache movies for quicker responsiveness. */ func receivedMovieDetails(movie: Movie) /** Some sort of failure from the network call. */ func requestFailedWithError(error: NSError) } class MovieDBService { /** A queue to support network calls on a background thread */ let queue: NSOperationQueue = NSOperationQueue() /** * A simple cache by movie id. * All of the contents of a movie are historical, however the user rating and voting can change, so ideally we would support updating the cache. * We could accomplish this by immediately returning the cache value, and then applying an update to the View if the cache was found to be stale. */ var movieCache: Dictionary<Int, Movie> = [:] /** * This is loaded from a local plist called "apiKey.plist" with a single string entry: * { @"kAPI_KEY" : @"Your API key" } */ var apiKey: String? var delegate: protocol<MovieLookupDelegate>? // MARK: - Init init() { // Find out the path of the local api key properties list let path = NSBundle.mainBundle().pathForResource("apiKey", ofType: "plist") if let dict = NSDictionary(contentsOfFile: path!) { self.apiKey = dict["kAPI_KEY"] as? String } } func requestPopularMoviesWithPage(page: Int) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if page > 1000 { // The API doesn't support anything over 1000 self.delegate?.requestFailedWithError(NSError(domain: "Invalid page number", code: 400, userInfo: nil)) return } let urlString = "http://api.themoviedb.org/3/movie/popular?api_key=\(self.apiKey!)&page=\(page)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let page = parsed["page"]! as! Int // These can be useful for displaying in the View //let totalPages = parsed["total_pages"] as! Int //let totalResults = parsed["total_results"] as! Int var movies: Array<Movie> = [] let results = parsed["results"] as! Array<AnyObject> for value in results { let movie = self.parseMovieFromDictionary(value as! Dictionary<String, AnyObject>) movies.append(movie) } self.delegate?.receivedMovies(movies, forPage: page) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } func searchMoviesWithQuery(query: String, andPage page: Int) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if page > 1000 { // The API doesn't support anything over 1000 self.delegate?.requestFailedWithError(NSError(domain: "Invalid page number", code: 400, userInfo: nil)) return } let encoded = self.urlEncodeQuery(query) let urlString = "http://api.themoviedb.org/3/search/movie?api_key=\(self.apiKey!)&query=\(encoded)&page=\(page)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let page = parsed["page"]! as! Int // These can be useful for displaying in the View //let totalPages = parsed["total_pages"] as! Int //let totalResults = parsed["total_results"] as! Int var movies: Array<Movie> = [] let results = parsed["results"] as! Array<AnyObject> for value in results { let movie = self.parseMovieFromDictionary(value as! Dictionary<String, AnyObject>) movies.append(movie) } self.delegate?.receivedMovies(movies, forPage: page) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } func lookupMovieWithId(movieId: Int ) { assert(self.apiKey != nil, "An API_KEY is required to use the movie DB. Please register a key as described") if let movie = self.movieCache[movieId] { // lookup in the cache and return self.delegate?.receivedMovieDetails( movie ) return } let urlString = "http://api.themoviedb.org/3/movie/\(movieId)?api_key=\(self.apiKey!)" let url = NSURL(string: urlString)! let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in if let error = error where data == nil { self.delegate?.requestFailedWithError(error) return } // Parse the raw JSON into Objects do { let parsed = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) as! Dictionary<String, AnyObject> let movie = self.parseMovieFromDictionary(parsed) // Add the movie to the cache to avoid excessive network requests self.movieCache[movie.id] = movie self.delegate?.receivedMovieDetails(movie) } catch { self.delegate?.requestFailedWithError(NSError(domain: "JSON Parse Error", code: 400, userInfo: nil)) return } }) task.resume() } // MARK: - Private Helpers /** Using Key Value Coding (KVC), iterate the JSON response object and construct a Movie using the applicable values */ private func parseMovieFromDictionary(dict: Dictionary<String, AnyObject>) -> Movie { let movie = Movie() for (key, value) in dict { if value !== NSNull() && movie.respondsToSelector(Selector(key)) { movie.setValue(value, forKey: key) } } return movie } /** Need to make sure we are properly encoding the query for the API */ func urlEncodeQuery(query: String) -> String { return query.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet() )! } }
90c9658f6eb03505b7d18a17eda23974
37.668508
148
0.661189
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/TableOfContentsCell.swift
mit
1
import UIKit // MARK: - Cell class TableOfContentsCell: UITableViewCell { @IBOutlet var titleLabel: UILabel! @IBOutlet var selectedSectionIndicator: UIView! @IBOutlet var indentationConstraint: NSLayoutConstraint! @IBOutlet weak var titleLabelTopConstraint: NSLayoutConstraint! var titleIndentationLevel: Int = 0 { didSet { titleLabelTopConstraint.constant = titleIndentationLevel == 0 ? 19 : 11 indentationConstraint.constant = indentationWidth * CGFloat(1 + titleIndentationLevel) if titleIndentationLevel == 0 { accessibilityTraits = .header } else { accessibilityValue = String.localizedStringWithFormat(WMFLocalizedString("table-of-contents-subheading-label", value:"Subheading %1$d", comment:"VoiceOver label to indicate level of subheading in table of contents. %1$d is replaced by the level of subheading."), titleIndentationLevel) } } } private var titleHTML: String = "" private var titleTextStyle: DynamicTextStyle = .georgiaTitle3 private var isTitleLabelHighlighted: Bool = false func setTitleHTML(_ html: String, with textStyle: DynamicTextStyle, highlighted: Bool, color: UIColor, selectionColor: UIColor) { isTitleLabelHighlighted = highlighted titleHTML = html titleTextStyle = textStyle titleColor = color titleSelectionColor = selectionColor updateTitle() } func updateTitle() { let color = isTitleLabelHighlighted ? titleSelectionColor : titleColor titleLabel.attributedText = titleHTML.byAttributingHTML(with: titleTextStyle, matching: traitCollection, color: color, handlingLinks: false) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) updateTitle() } private var titleColor: UIColor = Theme.standard.colors.primaryText { didSet { titleLabel.textColor = titleColor } } private var titleSelectionColor: UIColor = Theme.standard.colors.link // MARK: - Init public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) indentationWidth = 10 } // MARK: - UIView override func awakeFromNib() { super.awakeFromNib() selectedSectionIndicator.alpha = 0.0 selectionStyle = .none } // MARK: - Accessors func setSectionSelected(_ selected: Bool, animated: Bool) { if selected { setSelectionIndicatorVisible(titleIndentationLevel == 0) } else { setSelectionIndicatorVisible(false) } } // MARK: - UITableVIewCell class func reuseIdentifier() -> String { return wmf_nibName() } override func prepareForReuse() { super.prepareForReuse() indentationLevel = 1 setSectionSelected(false, animated: false) isTitleLabelHighlighted = false accessibilityTraits = [] accessibilityValue = nil } func setSelectionIndicatorVisible(_ visible: Bool) { if visible { selectedSectionIndicator.backgroundColor = titleSelectionColor selectedSectionIndicator.alpha = 1.0 } else { selectedSectionIndicator.alpha = 0.0 } } }
b58a49b460521ab8205be9cfa81d74f7
32.326923
301
0.655511
false
false
false
false
DanielMandea/coredatahelper
refs/heads/master
Example/CoreDataStackHelper/User+CoreDataClass.swift
mit
1
// // User+CoreDataClass.swift // // // Created by DanielMandea on 3/16/17. // // import Foundation import CoreData import CoreDataStackHelper final class User: NSManagedObject, AddManagedObject, SaveManagedObject, Fetch { } // MARK: - UpdateManangedObject extension User: UpdateManangedObject { public func update(with data: Any) { // Checkout data guard let data = data as? Dictionary<String, Any> else { return } // Update managed object let updatedName = data["name"] as? String if name != updatedName { name = updatedName } let updatedUniqueID = data["uniqueID"] as? String if uniqueID != updatedUniqueID { uniqueID = updatedUniqueID } let updatedAge = data["age"] as? NSNumber if age != updatedAge { age = updatedAge } } } // MARK: - CreateOrUpdateManagedObject extension User: CreateOrUpdateManagedObject { static func createOrUpdate(with data: Any, context: NSManagedObjectContext) -> User? { guard let dataDict = data as? Dictionary<String, Any>, let uniqueID = dataDict["uniqueID"] as? String else { return nil } var user:User? let predicate = NSPredicate(format: "uniqueID = %@", uniqueID) do { user = try User.fetch(with: predicate, in: context)?.first } catch { print(error) } if user == nil { user = User.add(data: data, context: context) } else { user?.update(with: data) } return user } static func createOrUpdateMultiple(with data: Array<Any>, context: NSManagedObjectContext) -> Array<User>? { var users = [User]() for dataEntry in data { if let user = createOrUpdate(with: dataEntry, context: context) { users.append(user) } } return users } }
7cc2eec970e82da71cfb9383d5610aa6
22.539474
110
0.642817
false
false
false
false
tunespeak/AlamoRecord
refs/heads/master
Example/AlamoRecord/CommentCell.swift
mit
1
// // CommentCell.swift // AlamoRecord // // Created by Dalton Hinterscher on 7/8/17. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit class CommentCell: BaseTableViewCell { private var nameLabel: UILabel! private var emailLabel: UILabel! private var bodyLabel: UILabel! required init() { super.init() selectionStyle = .none nameLabel = UILabel() nameLabel.numberOfLines = 0 nameLabel.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize * 1.25) resizableView.addSubview(nameLabel) bodyLabel = UILabel() bodyLabel.numberOfLines = 0 bodyLabel.font = UIFont.systemFont(ofSize: UIFont.systemFontSize) resizableView.addSubview(bodyLabel) emailLabel = UILabel() emailLabel.numberOfLines = 0 emailLabel.font = UIFont.boldSystemFont(ofSize: UIFont.smallSystemFontSize) emailLabel.textColor = .lightGray resizableView.addSubview(emailLabel) nameLabel.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(10) make.left.equalToSuperview().offset(10) make.right.equalToSuperview().offset(-10) } bodyLabel.snp.makeConstraints { (make) in make.top.equalTo(nameLabel.snp.bottom).offset(5) make.left.equalTo(nameLabel) make.right.equalTo(nameLabel) } emailLabel.snp.makeConstraints { (make) in make.top.equalTo(bodyLabel.snp.bottom).offset(5) make.left.equalTo(nameLabel) make.right.equalTo(nameLabel) } autoResize(under: emailLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func bind(comment: Comment) { nameLabel.text = comment.name bodyLabel.text = comment.body emailLabel.text = comment.email } }
156b5ad07d1c8a696a4b5cc0ec3c39c4
28.705882
84
0.619307
false
false
false
false
eugenehp/Swift3SSHDemo
refs/heads/master
SSHDemo/ViewController.swift
mit
1
import UIKit import Foundation import NMSSH import CFNetwork class ViewController: UIViewController, NMSSHChannelDelegate { override func viewDidLoad() { super.viewDidLoad() // let host = "10.0.1.15:22" let host = "45.51.135.163:22" let username = "admin" let password = "123" let session = NMSSHSession(host: host, andUsername: username) print("Trying to connect now..") session?.connect() if session?.isConnected == true { print("Session connected") session?.channel.delegate = self session?.channel.ptyTerminalType = .vanilla session?.channel.requestPty = true session?.authenticate(byPassword:password) do{ try session?.channel.startShell() let a = try session?.channel.write("sleep\n") print(a) print(session?.channel.lastResponse ?? "no respone of last command") }catch{ print("Error ocurred!!") } //For other types //session.authenticateByPassword(password) } //session?.disconnect() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func channel(_ channel: NMSSHChannel!, didReadRawData data: Data!) { let str = String(data: data, encoding: .isoLatin1)! print("hello") print(str) } }
af627eae8a2be4b9a6fde6d7a9d8b8a9
28.259259
84
0.561392
false
false
false
false
gssdromen/KcptunMac
refs/heads/master
KcptunMac/Command.swift
gpl-3.0
1
// // Command.swift // KcptunMac // // Created by Cedric Wu on 8/27/16. // Copyright © 2016 Cedric Wu. All rights reserved. // import Foundation import ServiceManagement import Cocoa import AEXML class Command { static let kPidPath = "/var/run/com.cedric.KcptunMac.pid" class func runKCPTUN(_ configurationErrorBlock: @escaping (() -> Void)) { DispatchQueue.global().asyncAfter(deadline: DispatchTime.now()) { let pipe = Pipe() let file = pipe.fileHandleForReading let task = Process() let model = PreferenceModel.sharedInstance task.launchPath = model.clientPath if model.localPort.isEmpty || model.remoteAddress.isEmpty { configurationErrorBlock() } else { var args = model.combine() args.append("&") task.arguments = args task.standardOutput = pipe task.launch() Command.writePidToFilePath(path: Command.kPidPath, pid: String(task.processIdentifier)) let data = file.readDataToEndOfFile() file.closeFile() let grepOutput = String(data: data, encoding: String.Encoding.utf8) if grepOutput != nil { print(grepOutput!) } } } } class func stopKCPTUN() { DispatchQueue.global().async { let task = Process() if let pid = Command.readPidToFilePath(path: Command.kPidPath) { task.launchPath = "/bin/kill" task.arguments = ["-9", pid] task.launch() } } } class func genLaunchAgentsPlist(kcptunPath: String, params: [String]) -> AEXMLDocument { let xml = AEXMLDocument() let plist = AEXMLElement(name: "plist", value: nil, attributes: ["version": "1.0"]) let dict = AEXMLElement(name: "dict") plist.addChild(dict) dict.addChild(name: "key", value: "Label", attributes: [:]) dict.addChild(name: "string", value: "com.cedric.KcptunMac", attributes: [:]) dict.addChild(name: "key", value: "ProgramArguments", attributes: [:]) let arrayElement = AEXMLElement(name: "array") arrayElement.addChild(name: "string", value: kcptunPath, attributes: [:]) for param in params { arrayElement.addChild(name: "string", value: param, attributes: [:]) } dict.addChild(arrayElement) dict.addChild(name: "key", value: "KeepAlive", attributes: [:]) dict.addChild(name: "true", value: nil, attributes: [:]) xml.addChild(plist) return xml } // 保存kcptun的运行pid class func writePidToFilePath(path: String, pid: String) { do { try pid.write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch let e { print(e.localizedDescription) } } // 读取kcptun的运行pid class func readPidToFilePath(path: String) -> String? { guard FileManager.default.fileExists(atPath: path) else { return nil } if let data = FileManager.default.contents(atPath: path) { let pid = String(data: data, encoding: String.Encoding.utf8) return pid } return nil } // 写开机自启动的plist class func writeStringToFilePath(path: String, xmlString: String) { do { try xmlString.write(toFile: path, atomically: true, encoding: String.Encoding.utf8) } catch let e { print(e.localizedDescription) } } // 此方法需要签名才能用 class func triggerRunAtLogin(startup: Bool) { // 这里请填写你自己的Heler BundleID let launcherAppIdentifier = "com.cedric.KcptunMac.KcptunMacLauncher" // 开始注册/取消启动项 let flag = SMLoginItemSetEnabled(launcherAppIdentifier as CFString, startup) // if flag { // let userDefaults = UserDefaults.standard // userDefaults.set(startup, forKey: "LaunchAtLogin") // userDefaults.synchronize() // } // // var startedAtLogin = false // // for app in NSWorkspace.shared().runningApplications { // if let id = app.bundleIdentifier { // if id == launcherAppIdentifier { // startedAtLogin = true // } // } // // } // // if startedAtLogin { // DistributedNotificationCenter.default().post(name: NSNotification.Name(rawValue: "killhelper"), object: Bundle.main.bundleIdentifier!) // } } }
5de1ea949570709880195005d79e8596
31.048276
148
0.576071
false
false
false
false
pdx-ios/tvOS-workshop
refs/heads/master
RoShamBo/RoShamBo/ViewController.swift
mit
1
// // ViewController.swift // RoShamBo // // Created by Ryan Arana on 10/6/15. // Copyright © 2015 PDX-iOS. All rights reserved. // import UIKit class ViewController: UIViewController { var selectedButton: UIButton? { didSet { oldValue?.highlighted = false selectedButton?.highlighted = true } } @IBOutlet weak var inputsView: UIView! @IBOutlet weak var resultsView: UIView! @IBOutlet weak var winnerImage: UIImageView! @IBOutlet weak var actionLabel: UILabel! @IBOutlet weak var loserImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() resultsView.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func buttonClicked(sender: UIButton) { selectedButton = sender let playerChoice = Choice(rawValue: sender.tag)! let result = Game.play(playerChoice) resultsView.hidden = false if playerChoice == result.winner { winnerImage.image = UIImage(named: "\(result.winner.name)-highlighted") } else { winnerImage.image = UIImage(named: result.winner.name) } if playerChoice == result.loser { loserImage.image = UIImage(named: "\(result.loser.name)-highlighted") } else { loserImage.image = UIImage(named: result.loser.name) } actionLabel.text = result.summary } }
62c780f9b1c2ed752270c5391d0eab51
24.883333
83
0.629749
false
false
false
false
zwaldowski/URLGrey
refs/heads/swift-2_0
URLGrey/Data+CollectionType.swift
mit
1
// // Data+CollectionType.swift // URLGrey // // Created by Zachary Waldowski on 2/7/15. // Copyright © 2014-2015. Some rights reserved. // import Dispatch /// The deallocation routine to use for custom-backed `Data` instances. public enum UnsafeBufferOwnership<T> { /// Copy the buffer passed in; the runtime will manage deallocation. case Copy /// Dealloc data created by `malloc` or equivalent. case Free /// Free data created by `mmap` or equivalent. case Unmap /// Provide some other deallocation routine. case Custom(UnsafeBufferPointer<T> -> ()) } public extension Data { private init(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t, destructor: dispatch_block_t?) { let baseAddress = UnsafePointer<Void>(buffer.baseAddress) let bytes = buffer.count * sizeof(T) self.init(unsafe: dispatch_data_create(baseAddress, bytes, queue, destructor)) } private init<Owner: CollectionType>(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), owner: Owner) { self.init(unsafeWithBuffer: buffer, queue: queue, destructor: { _ = owner }) } /// Create `Data` backed by any arbitrary storage. /// /// For the `behavior` parameter, pass: /// - `.Copy` to copy the buffer passed in. /// - `.Free` to dealloc data created by `malloc` or equivalent. /// - `.Unmap` to free data created by `mmap` or equivalent. /// - `.Custom` for some custom deallocation. public init(unsafeWithBuffer buffer: UnsafeBufferPointer<T>, queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), behavior: UnsafeBufferOwnership<T>) { let destructor: dispatch_block_t? switch behavior { case .Copy: destructor = nil case .Free: destructor = _dispatch_data_destructor_free case .Unmap: destructor = _dispatch_data_destructor_munmap case .Custom(let fn): destructor = { fn(buffer) } } self.init(unsafeWithBuffer: buffer, queue: queue, destructor: destructor) } /// Create `Data` backed by the contiguous contents of an array. /// If the array itself is represented discontiguously, the initializer /// must first create the storage. public init(array: [T]) { let buffer = array.withUnsafeBufferPointer { $0 } self.init(unsafeWithBuffer: buffer, owner: array) } /// Create `Data` backed by a contiguous array. public init(array: ContiguousArray<T>) { let buffer = array.withUnsafeBufferPointer { $0 } self.init(unsafeWithBuffer: buffer, owner: array) } }
c0a552c2f118fa9a95df1e533c5a3294
37.492958
163
0.654226
false
false
false
false
congncif/IDMCore
refs/heads/master
IDMCore/Classes/SynchronizedArray.swift
mit
1
// // SynchronizedArray.swift // IDMCore // // Created by FOLY on 12/10/18. // Thanks to Basem Emara import Foundation /// A thread-safe array. public final class SynchronizedArray<Element> { fileprivate var queue: DispatchQueue fileprivate var array = [Element]() public init(queue: DispatchQueue = DispatchQueue.concurrent, elements: [Element] = []) { self.queue = queue self.array = elements } } // MARK: - Properties public extension SynchronizedArray { /// The first element of the collection. var first: Element? { var result: Element? queue.sync { result = self.array.first } return result } /// The last element of the collection. var last: Element? { var result: Element? queue.sync { result = self.array.last } return result } /// The number of elements in the array. var count: Int { var result = 0 queue.sync { result = self.array.count } return result } /// A Boolean value indicating whether the collection is empty. var isEmpty: Bool { var result = false queue.sync { result = self.array.isEmpty } return result } /// A textual representation of the array and its elements. var description: String { var result = "" queue.sync { result = self.array.description } return result } } // MARK: - Immutable public extension SynchronizedArray { /// Returns the first element of the sequence that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Returns: The first element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate. func first(where predicate: (Element) -> Bool) -> Element? { var result: Element? queue.sync { result = self.array.first(where: predicate) } return result } /// Returns the last element of the sequence that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - Returns: The last element of the sequence that satisfies predicate, or nil if there is no element that satisfies predicate. func last(where predicate: (Element) -> Bool) -> Element? { var result: Element? queue.sync { result = self.array.last(where: predicate) } return result } /// Returns an array containing, in order, the elements of the sequence that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element should be included in the returned array. /// - Returns: An array of the elements that includeElement allowed. func filter(_ isIncluded: @escaping (Element) -> Bool) -> SynchronizedArray { var result: SynchronizedArray? queue.sync { result = SynchronizedArray(queue: self.queue, elements: self.array.filter(isIncluded)) } return result ?? self } /// Returns the first index in which an element of the collection satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: The index of the first element for which predicate returns true. If no elements in the collection satisfy the given predicate, returns nil. func firstIndex(where predicate: (Element) -> Bool) -> Int? { var result: Int? queue.sync { result = self.array.firstIndex(where: predicate) } return result } /// Returns the elements of the collection, sorted using the given predicate as the comparison between elements. /// /// - Parameter areInIncreasingOrder: A predicate that returns true if its first argument should be ordered before its second argument; otherwise, false. /// - Returns: A sorted array of the collection’s elements. func sorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> SynchronizedArray { var result: SynchronizedArray? queue.sync { result = SynchronizedArray(queue: self.queue, elements: self.array.sorted(by: areInIncreasingOrder)) } return result ?? self } /// Returns an array containing the results of mapping the given closure over the sequence’s elements. /// /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence. func map<ElementOfResult>(_ transform: @escaping (Element) -> ElementOfResult) -> [ElementOfResult] { var result = [ElementOfResult]() queue.sync { result = self.array.map(transform) } return result } /// Returns an array containing the non-nil results of calling the given transformation with each element of this sequence. /// /// - Parameter transform: A closure that accepts an element of this sequence as its argument and returns an optional value. /// - Returns: An array of the non-nil results of calling transform with each element of the sequence. func compactMap<ElementOfResult>(_ transform: (Element) -> ElementOfResult?) -> [ElementOfResult] { var result = [ElementOfResult]() queue.sync { result = self.array.compactMap(transform) } return result } /// Returns the result of combining the elements of the sequence using the given closure. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. initialResult is passed to nextPartialResult the first time the closure is executed. /// - nextPartialResult: A closure that combines an accumulating value and an element of the sequence into a new accumulating value, to be used in the next call of the nextPartialResult closure or returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult. func reduce<ElementOfResult>(_ initialResult: ElementOfResult, _ nextPartialResult: @escaping (ElementOfResult, Element) -> ElementOfResult) -> ElementOfResult { var result: ElementOfResult? queue.sync { result = self.array.reduce(initialResult, nextPartialResult) } return result ?? initialResult } /// Returns the result of combining the elements of the sequence using the given closure. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// - updateAccumulatingResult: A closure that updates the accumulating value with an element of the sequence. /// - Returns: The final accumulated value. If the sequence has no elements, the result is initialResult. func reduce<ElementOfResult>(into initialResult: ElementOfResult, _ updateAccumulatingResult: @escaping (inout ElementOfResult, Element) -> Void) -> ElementOfResult { var result: ElementOfResult? queue.sync { result = self.array.reduce(into: initialResult, updateAccumulatingResult) } return result ?? initialResult } /// Calls the given closure on each element in the sequence in the same order as a for-in loop. /// /// - Parameter body: A closure that takes an element of the sequence as a parameter. func forEach(_ body: (Element) -> Void) { queue.sync { self.array.forEach(body) } } /// Returns a Boolean value indicating whether the sequence contains an element that satisfies the given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element represents a match. /// - Returns: true if the sequence contains an element that satisfies predicate; otherwise, false. func contains(where predicate: (Element) -> Bool) -> Bool { var result = false queue.sync { result = self.array.contains(where: predicate) } return result } /// Returns a Boolean value indicating whether every element of a sequence satisfies a given predicate. /// /// - Parameter predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition. /// - Returns: true if the sequence contains only elements that satisfy predicate; otherwise, false. func allSatisfy(_ predicate: (Element) -> Bool) -> Bool { var result = false queue.sync { result = self.array.allSatisfy(predicate) } return result } } // MARK: - Mutable public extension SynchronizedArray { /// Adds a new element at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The element to append to the array. /// - completion: The block to execute when completed. func append(_ element: Element, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.append(element) DispatchQueue.main.async { completion?() } } } /// Adds new elements at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The elements to append to the array. /// - completion: The block to execute when completed. func append(_ elements: [Element], completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array += elements DispatchQueue.main.async { completion?() } } } /// Inserts a new element at the specified position. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - element: The new element to insert into the array. /// - index: The position at which to insert the new element. /// - completion: The block to execute when completed. func insert(_ element: Element, at index: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.insert(element, at: index) DispatchQueue.main.async { completion?() } } } /// Removes and returns the first element of the collection. /// /// The collection must not be empty. /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed element. func removeFirst(completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.removeFirst() DispatchQueue.main.async { completion?(element) } } } /// Removes the specified number of elements from the beginning of the collection. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - k: The number of elements to remove from the collection. /// - completion: The block to execute when remove completed. func removeFirst(_ k: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { defer { DispatchQueue.main.async { completion?() } } guard 0...self.array.count ~= k else { return } self.array.removeFirst(k) } } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed element. func removeLast(completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.removeLast() DispatchQueue.main.async { completion?(element) } } } /// Removes the specified number of elements from the end of the collection. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - k: The number of elements to remove from the collection. /// - completion: The block to execute when remove completed. func removeLast(_ k: Int, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { defer { DispatchQueue.main.async { completion?() } } guard 0...self.array.count ~= k else { return } self.array.removeLast(k) } } /// Removes and returns the element at the specified position. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - index: The position of the element to remove. /// - completion: The handler with the removed element. func remove(at index: Int, completion: ((Element) -> Void)? = nil) { queue.async(flags: .barrier) { let element = self.array.remove(at: index) DispatchQueue.main.async { completion?(element) } } } /// Removes and returns the elements that meet the criteria. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value indicating whether the element is a match. /// - completion: The handler with the removed elements. func remove(where predicate: @escaping (Element) -> Bool, completion: (([Element]) -> Void)? = nil) { queue.async(flags: .barrier) { var elements = [Element]() while let index = self.array.firstIndex(where: predicate) { elements.append(self.array.remove(at: index)) } DispatchQueue.main.async { completion?(elements) } } } /// Removes all elements from the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter completion: The handler with the removed elements. func removeAll(completion: (([Element]) -> Void)? = nil) { queue.async(flags: .barrier) { let elements = self.array self.array.removeAll() DispatchQueue.main.async { completion?(elements) } } } } public extension SynchronizedArray { /// Accesses the element at the specified position if it exists. /// /// - Parameter index: The position of the element to access. /// - Returns: optional element if it exists. subscript(index: Int) -> Element? { get { var result: Element? queue.sync { result = self.array[safe: index] } return result } set { guard let newValue = newValue else { return } queue.async(flags: .barrier) { self.array[index] = newValue } } } } // MARK: - Equatable public extension SynchronizedArray where Element: Equatable { /// Returns a Boolean value indicating whether the sequence contains the given element. /// /// - Parameter element: The element to find in the sequence. /// - Returns: true if the element was found in the sequence; otherwise, false. func contains(_ element: Element) -> Bool { var result = false queue.sync { result = self.array.contains(element) } return result } /// Removes the specified element. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameter element: An element to search for in the collection. func remove(_ element: Element, completion: (() -> Void)? = nil) { queue.async(flags: .barrier) { self.array.remove(element) DispatchQueue.main.async { completion?() } } } /// Removes the specified element. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to remove from. /// - right: An element to search for in the collection. static func -= (left: inout SynchronizedArray, right: Element) { left.remove(right) } } // MARK: - Infix operators public extension SynchronizedArray { /// Adds a new element at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to append to. /// - right: The element to append to the array. static func += (left: inout SynchronizedArray, right: Element) { left.append(right) } /// Adds new elements at the end of the array. /// /// The task is performed asynchronously due to thread-locking management. /// /// - Parameters: /// - left: The collection to append to. /// - right: The elements to append to the array. static func += (left: inout SynchronizedArray, right: [Element]) { left.append(right) } } private extension SynchronizedArray { // swiftlint:disable file_length } extension Array where Element: Equatable { mutating func remove(_ element: Element) { guard let index = firstIndex(of: element) else { return } remove(at: index) } } extension Collection { subscript(safe index: Index) -> Element? { // http://www.vadimbulavin.com/handling-out-of-bounds-exception/ return indices.contains(index) ? self[index] : nil } }
a9fa4ad1c66ec535a290a45ff888a018
40.006818
226
0.64773
false
false
false
false
smoope/ios-sdk
refs/heads/master
Pod/Classes/TraversonOAuthAuthenticator.swift
apache-2.0
1
/* * Copyright 2016 smoope GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation import SwiftyTraverson import Alamofire public class TraversonOAuthAuthenticator: TraversonAuthenticator { var clientId: String var secret: String var url: String public var retries = 2 public init(url: String, clientId: String, secret: String) { self.url = url self.clientId = clientId self.secret = secret } public func authenticate(result: TraversonAuthenticatorResult) { Alamofire.request(.POST, url, parameters: ["grant_type": "client_credentials"], encoding: .URL) .authenticate(user: clientId, password: secret) .responseJSON { response in switch response.result { case .Success(let json): let response = json as! NSDictionary result(authorizationHeader: response.objectForKey("access_token") as? String) break default: result(authorizationHeader: nil) } } } }
6147c5b7a48df5df31a6d17c37878e48
28.192308
99
0.698287
false
false
false
false
csound/csound
refs/heads/develop
iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/CsoundVirtualKeyboard.swift
lgpl-2.1
3
/* CsoundVirtualKeyboard.swift Nikhil Singh, Dr. Richard Boulanger Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini This file is part of Csound iOS SwiftExamples. The Csound for iOS Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import UIKit class CsoundVirtualKeyboard: UIView { // Variable declarations private var keyDown = [Bool].init(repeating: false, count: 25) private var currentTouches = NSMutableSet() private var keyRects = [CGRect](repeatElement(CGRect(), count: 25)) private var lastWidth: CGFloat = 0.0 private let keysNum = 25 @IBOutlet var keyboardDelegate: AnyObject? // keyboardDelegate object will handle key presses and releases override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isMultipleTouchEnabled = true // Enable multiple touch so we can press multiple keys } // Check if a key is a white key or a black key depending on its index func isWhiteKey(_ key: Int) -> Bool { switch (key % 12) { case 0, 2, 4, 5, 7, 9, 11: return true default: return false } } // MARK: Update key statuses private func updateKeyRects() { if lastWidth == bounds.size.width { return } lastWidth = bounds.size.width let whiteKeyHeight: CGFloat = bounds.size.height let blackKeyHeight: CGFloat = whiteKeyHeight * 0.625 let whiteKeyWidth: CGFloat = bounds.size.width/15.0 let blackKeyWidth: CGFloat = whiteKeyWidth * 0.833333 let leftKeyBound: CGFloat = whiteKeyWidth - (blackKeyWidth / 2.0) var lastWhiteKey: CGFloat = 0 keyRects[0] = CGRect(x: 0, y: 0, width: whiteKeyWidth, height: whiteKeyHeight) for i in 1 ..< keysNum { if !(isWhiteKey(i)) { keyRects[i] = CGRect(x: (lastWhiteKey * whiteKeyWidth) + leftKeyBound, y: 0, width: blackKeyWidth, height: blackKeyHeight) } else { lastWhiteKey += 1 keyRects[i] = CGRect(x: lastWhiteKey * whiteKeyWidth, y: 0, width: whiteKeyWidth, height: whiteKeyHeight) } } } private func getKeyboardKey(_ point: CGPoint) -> Int { var keyNum = -1 for i in 0 ..< keysNum { if keyRects[i].contains(point) { keyNum = i if !(isWhiteKey(i)) { break } } } return keyNum } private func updateKeyStates() { updateKeyRects() var count = 0 let touches = currentTouches.allObjects count = touches.count var currentKeyState = [Bool](repeatElement(true, count: keysNum)) for i in 0 ..< keysNum { currentKeyState[i] = false } for i in 0 ..< count { let touch = touches[i] as! UITouch let point = touch.location(in: self) let index = getKeyboardKey(point) if index != -1 { currentKeyState[index] = true } } var keysUpdated = false for i in 0 ..< keysNum { if keyDown[i] != currentKeyState[i] { keysUpdated = true let keyDownState = currentKeyState[i] keyDown[i] = keyDownState if keyboardDelegate != nil { if keyDownState { keyboardDelegate?.keyDown(self, keyNum: i) } else { keyboardDelegate?.keyUp(self, keyNum: i) } } } } if keysUpdated { DispatchQueue.main.async { [unowned self] in self.setNeedsDisplay() } } } // MARK: Touch Handling Code override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.add(touch) } updateKeyStates() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { updateKeyStates() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.remove(touch) } updateKeyStates() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.remove(touch) } updateKeyStates() } // MARK: Drawing Code override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let whiteKeyHeight = rect.size.height let blackKeyHeight = round(rect.size.height * 0.625) let whiteKeyWidth = rect.size.width/15.0 let blackKeyWidth = whiteKeyWidth * 0.8333333 let blackKeyOffset = blackKeyWidth/2.0 var runningX: CGFloat = 0 let yval = 0 context?.setFillColor(UIColor.white.cgColor) context?.fill(bounds) context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(bounds) let lineHeight = whiteKeyHeight - 1 var newX = 0 for i in 0 ..< keysNum { if isWhiteKey(i) { newX = Int(round(runningX + 0.5)) if keyDown[i] { let newW = Int(round(runningX + whiteKeyWidth + 0.5) - CGFloat(newX)) context?.setFillColor(UIColor.blue.cgColor) context?.fill(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newW), height: whiteKeyHeight - 1)) } runningX += whiteKeyWidth context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newX), height: lineHeight)) } } runningX = 0 for i in 0 ..< keysNum { if isWhiteKey(i) { runningX += whiteKeyWidth } else { if keyDown[i] { context?.setFillColor(UIColor.blue.cgColor) } else { context?.setFillColor(UIColor.black.cgColor) } context?.fill(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight)) context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight)) } } } } // Protocol for delegate to conform to @objc protocol CsoundVirtualKeyboardDelegate { func keyUp(_ keybd:CsoundVirtualKeyboard, keyNum:Int) func keyDown(_ keybd:CsoundVirtualKeyboard, keyNum:Int) }
972dcf42d82ba932e1ff69219bc6af4f
32.121849
138
0.562603
false
false
false
false
crescentflare/UniLayout
refs/heads/master
UniLayoutIOS/Example/Tests/Utility/LayoutAnalyzer.swift
mit
1
// // LayoutAnalyzer.swift // Contains a trace of layout events for analysis // import UIKit @testable import UniLayout // -- // MARK: Layout analyzer // -- class LayoutAnalyzer { static var shared = LayoutAnalyzer() var items = [LayoutAnalyzerItem]() func clear() { items = [] } func add(_ item: LayoutAnalyzerItem) { items.append(item) } func printEvents() { var previousItem: LayoutAnalyzerItem? for item in items { item.printInfo(previousItem: previousItem) previousItem = item } } } // -- // MARK: Layout analyzer item // -- class LayoutAnalyzerItem { let view: UIView let type: LayoutAnalyzerType let value: Any? init(view: UIView, type: LayoutAnalyzerType, value: Any? = nil) { self.view = view self.type = type self.value = value } func printInfo(previousItem: LayoutAnalyzerItem?) { let viewLabel = view.accessibilityIdentifier ?? "unknown" var operationInfo = "" switch type { case .changeText: let stringValue = value as? String ?? "" operationInfo = type.rawValue + " to '\(stringValue)'" case .changeBounds: let rectValue = value as? CGRect ?? CGRect.zero operationInfo = type.rawValue + " to \(rectValue)" default: operationInfo = type.rawValue } print("View '\(viewLabel)' had operation: \(operationInfo)") } } // -- // MARK: Layout analyzer event type enum // -- enum LayoutAnalyzerType: String { case layoutSubviews = "layout subviews" case changeBounds = "change bounds" case changeText = "change text" }
9fb69e77272f1e1fe71547980ab25468
20.621951
69
0.583756
false
false
false
false
ontouchstart/swift3-playground
refs/heads/playgroundbook
Graphing.playgroundbook/Contents/Sources/PlaygroundInternal/LinePlotDrawable.swift
mit
1
// // LineChartLayer.swift // Charts // // Copyright © 2016 Apple Inc. All rights reserved. // import UIKit private let FunctionSampleInternalInPoints = 1.0 internal class LinePlotDrawable: ChartDrawable { var dataProvider: LineData? var color = Color.blue var symbol: Symbol? = Symbol() var lineStyle = LineStyle.none var lineWidth: CGFloat = 2.0 var label: String? func draw(onChartView chartView: ChartView, context: CGContext) { guard let dataProvider = dataProvider else { return } let modelPoints = dataProvider.data(forBounds: chartView.axisBounds, chartView: chartView) let screenPoints = modelPoints.map { modelPoint -> CGPoint in return chartView.convertPointToScreen(modelPoint: CGPoint(x: modelPoint.0, y: modelPoint.1)) } if lineStyle != .none { let linePath = pathFromPoints(points: screenPoints) linePath.lineWidth = lineWidth switch lineStyle { case .dashed: linePath.setLineDash([6,10], count: 2, phase: 0) case .dotted: linePath.setLineDash([1,5], count: 2, phase: 0) default: break } context.setStrokeColor(color.cgColor) linePath.lineJoinStyle = .round linePath.stroke() } drawSymbolsAtPoints(points: modelPoints, inChartView: chartView, inContext: context) } private func pathFromPoints(points: [CGPoint]) -> UIBezierPath { let path = UIBezierPath() for (index, point) in points.enumerated() { if (index == 0) { path.move(to: point) } else { path.addLine(to: point) } } return path } private func drawSymbolsAtPoints(points: [(Double, Double)], inChartView chartView: ChartView, inContext context: CGContext) { guard let symbol = symbol else { return } for point in points { let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: point.0, y: point.1)) symbol.draw(atCenterPoint: CGPoint(x: screenPoint.x, y: screenPoint.y), fillColor: color.uiColor, usingContext: context) } } func boundsOfData(inChartView chartView: ChartView) -> Bounds { guard let dataProvider = dataProvider else { return Bounds.infinite } return dataProvider.boundsOfData(chartView: chartView) } func values(inScreenRect rect: CGRect, inChartView chartView: ChartView) -> [ChartValue] { guard let dataProvider = dataProvider else { return [] } let minPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.minX, y: rect.maxY)) let maxPoint = chartView.convertPointFromScreen(screenPoint: CGPoint(x: rect.maxX, y: rect.minY)) let bounds = Bounds(minX: Double(minPoint.x), maxX: Double(maxPoint.x), minY: Double(minPoint.y), maxY: Double(maxPoint.y)) return dataProvider.data(withinBounds: bounds, chartView: chartView).map { data in let screenPoint = chartView.convertPointToScreen(modelPoint: CGPoint(x: data.1.0, y: data.1.1)) return ChartValue(label: label, index: data.0, value: data.1, color: color, screenPoint: screenPoint) } } } internal protocol LineData: CustomPlaygroundQuickLookable { func boundsOfData(chartView: ChartView) -> Bounds func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))] } internal class DiscreteLineData: LineData { private let xyData: XYData init(xyData: XYData) { self.xyData = xyData } func boundsOfData(chartView: ChartView) -> Bounds { guard xyData.count > 0 else { return Bounds.infinite } let xData = xyData.xData let yData = xyData.yData return Bounds(minX: xData.min()!, maxX: xData.max()!, minY: yData.min()!, maxY: yData.max()!) } func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] { // NOTE we may need to hand back data that appears outside the provided bounds otherwise data points/connections may be elided in the drawing. return xyData.xyData } func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))] { var dataWithinBounds = [(Int?, (Double, Double))]() for (index, data) in xyData.xyData.enumerated() { if bounds.contains(data: data) { dataWithinBounds.append((index, data)) } } return dataWithinBounds } } extension DiscreteLineData: CustomPlaygroundQuickLookable { internal var customPlaygroundQuickLook: PlaygroundQuickLook { get { let numPoints = xyData.count let suffix = numPoints == 1 ? "point" : "points" return .text("\(numPoints) \(suffix)") } } } internal class FunctionLineData: LineData { private let function: (Double) -> Double init(function: (Double) -> Double) { self.function = function } /// For function data, we use the current chart's x bounds and then sample the data to determine the y bounds. func boundsOfData(chartView: ChartView) -> Bounds { // grab the data for the current chart bounds. var bounds = chartView.axisBounds let boundedData = data(forBounds: bounds, chartView: chartView) guard boundedData.count > 0 else { return Bounds.infinite } // grab the y points for the data. let yData = boundedData.map { $0.1 } // update the x bounds to indicate that the data is unbounded. bounds.minX = .infinity bounds.maxX = .infinity // udpate the bounds match the y data min and max values. bounds.minY = yData.min()! bounds.maxY = yData.max()! return bounds } func data(forBounds bounds: Bounds, chartView: ChartView) -> [(Double, Double)] { let axisBounds = chartView.axisBounds let screenZeroAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint.zero).x let screenStrideOffsetAsModel = chartView.convertPointFromScreen(screenPoint: CGPoint(x: FunctionSampleInternalInPoints, y: 0.0)).x let modelStride = Double(screenStrideOffsetAsModel - screenZeroAsModel) var data = [(Double, Double)]() for x in stride(from: axisBounds.minX, through: axisBounds.maxX, by: modelStride) { data.append((x, function(x))) } // make sure we always go to the end. data.append(axisBounds.maxX, function(axisBounds.maxX)) return data } func data(withinBounds bounds: Bounds, chartView: ChartView) -> [(Int?, (Double, Double))] { let data = (bounds.midX, function(bounds.midX)) if bounds.contains(data: data) { return [(nil, data)] // Function data won't ever have an index. } return [] } } extension FunctionLineData: CustomPlaygroundQuickLookable { internal var customPlaygroundQuickLook: PlaygroundQuickLook { get { return .text(String(function)) } } }
0186ca86c80199111a390a623ac990d2
34.632075
150
0.616495
false
false
false
false
trill-lang/LLVMSwift
refs/heads/master
Sources/LLVM/OpCode.swift
mit
1
#if SWIFT_PACKAGE import cllvm #endif /// Enumerates the opcodes of instructions available in the LLVM IR language. public enum OpCode: CaseIterable { // MARK: Terminator Instructions /// The opcode for the `ret` instruction. case ret /// The opcode for the `br` instruction. case br /// The opcode for the `switch` instruction. case `switch` /// The opcode for the `indirectBr` instruction. case indirectBr /// The opcode for the `invoke` instruction. case invoke /// The opcode for the `unreachable` instruction. case unreachable // MARK: Standard Binary Operators /// The opcode for the `add` instruction. case add /// The opcode for the `fadd` instruction. case fadd /// The opcode for the `sub` instruction. case sub /// The opcode for the `fsub` instruction. case fsub /// The opcode for the `mul` instruction. case mul /// The opcode for the `fmul` instruction. case fmul /// The opcode for the `udiv` instruction. case udiv /// The opcode for the `sdiv` instruction. case sdiv /// The opcode for the `fdiv` instruction. case fdiv /// The opcode for the `urem` instruction. case urem /// The opcode for the `srem` instruction. case srem /// The opcode for the `frem` instruction. case frem // MARK: Logical Operators /// The opcode for the `shl` instruction. case shl /// The opcode for the `lshr` instruction. case lshr /// The opcode for the `ashr` instruction. case ashr /// The opcode for the `and` instruction. case and /// The opcode for the `or` instruction. case or /// The opcode for the `xor` instruction. case xor // MARK: Memory Operators /// The opcode for the `alloca` instruction. case alloca /// The opcode for the `load` instruction. case load /// The opcode for the `store` instruction. case store /// The opcode for the `getElementPtr` instruction. case getElementPtr // MARK: Cast Operators /// The opcode for the `trunc` instruction. case trunc /// The opcode for the `zext` instruction. case zext /// The opcode for the `sext` instruction. case sext /// The opcode for the `fpToUI` instruction. case fpToUI /// The opcode for the `fpToSI` instruction. case fpToSI /// The opcode for the `uiToFP` instruction. case uiToFP /// The opcode for the `siToFP` instruction. case siToFP /// The opcode for the `fpTrunc` instruction. case fpTrunc /// The opcode for the `fpExt` instruction. case fpExt /// The opcode for the `ptrToInt` instruction. case ptrToInt /// The opcode for the `intToPtr` instruction. case intToPtr /// The opcode for the `bitCast` instruction. case bitCast /// The opcode for the `addrSpaceCast` instruction. case addrSpaceCast // MARK: Other Operators /// The opcode for the `icmp` instruction. case icmp /// The opcode for the `fcmp` instruction. case fcmp /// The opcode for the `PHI` instruction. case phi /// The opcode for the `call` instruction. case call /// The opcode for the `select` instruction. case select /// The opcode for the `userOp1` instruction. case userOp1 /// The opcode for the `userOp2` instruction. case userOp2 /// The opcode for the `vaArg` instruction. case vaArg /// The opcode for the `extractElement` instruction. case extractElement /// The opcode for the `insertElement` instruction. case insertElement /// The opcode for the `shuffleVector` instruction. case shuffleVector /// The opcode for the `extractValue` instruction. case extractValue /// The opcode for the `insertValue` instruction. case insertValue // MARK: Atomic operators /// The opcode for the `fence` instruction. case fence /// The opcode for the `atomicCmpXchg` instruction. case atomicCmpXchg /// The opcode for the `atomicRMW` instruction. case atomicRMW // MARK: Exception Handling Operators /// The opcode for the `resume` instruction. case resume /// The opcode for the `landingPad` instruction. case landingPad /// The opcode for the `cleanupRet` instruction. case cleanupRet /// The opcode for the `catchRet` instruction. case catchRet /// The opcode for the `catchPad` instruction. case catchPad /// The opcode for the `cleanupPad` instruction. case cleanupPad /// The opcode for the `catchSwitch` instruction. case catchSwitch /// Creates an `OpCode` from an `LLVMOpcode` init(rawValue: LLVMOpcode) { switch rawValue { case LLVMRet: self = .ret case LLVMBr: self = .br case LLVMSwitch: self = .switch case LLVMIndirectBr: self = .indirectBr case LLVMInvoke: self = .invoke case LLVMUnreachable: self = .unreachable case LLVMAdd: self = .add case LLVMFAdd: self = .fadd case LLVMSub: self = .sub case LLVMFSub: self = .fsub case LLVMMul: self = .mul case LLVMFMul: self = .fmul case LLVMUDiv: self = .udiv case LLVMSDiv: self = .sdiv case LLVMFDiv: self = .fdiv case LLVMURem: self = .urem case LLVMSRem: self = .srem case LLVMFRem: self = .frem case LLVMShl: self = .shl case LLVMLShr: self = .lshr case LLVMAShr: self = .ashr case LLVMAnd: self = .and case LLVMOr: self = .or case LLVMXor: self = .xor case LLVMAlloca: self = .alloca case LLVMLoad: self = .load case LLVMStore: self = .store case LLVMGetElementPtr: self = .getElementPtr case LLVMTrunc: self = .trunc case LLVMZExt: self = .zext case LLVMSExt: self = .sext case LLVMFPToUI: self = .fpToUI case LLVMFPToSI: self = .fpToSI case LLVMUIToFP: self = .uiToFP case LLVMSIToFP: self = .siToFP case LLVMFPTrunc: self = .fpTrunc case LLVMFPExt: self = .fpExt case LLVMPtrToInt: self = .ptrToInt case LLVMIntToPtr: self = .intToPtr case LLVMBitCast: self = .bitCast case LLVMAddrSpaceCast: self = .addrSpaceCast case LLVMICmp: self = .icmp case LLVMFCmp: self = .fcmp case LLVMPHI: self = .phi case LLVMCall: self = .call case LLVMSelect: self = .select case LLVMUserOp1: self = .userOp1 case LLVMUserOp2: self = .userOp2 case LLVMVAArg: self = .vaArg case LLVMExtractElement: self = .extractElement case LLVMInsertElement: self = .insertElement case LLVMShuffleVector: self = .shuffleVector case LLVMExtractValue: self = .extractValue case LLVMInsertValue: self = .insertValue case LLVMFence: self = .fence case LLVMAtomicCmpXchg: self = .atomicCmpXchg case LLVMAtomicRMW: self = .atomicRMW case LLVMResume: self = .resume case LLVMLandingPad: self = .landingPad case LLVMCleanupRet: self = .cleanupRet case LLVMCatchRet: self = .catchRet case LLVMCatchPad: self = .catchPad case LLVMCleanupPad: self = .cleanupPad case LLVMCatchSwitch: self = .catchSwitch default: fatalError("invalid LLVMOpcode \(rawValue)") } } } extension OpCode { /// `BinaryOperation` enumerates the subset of opcodes that are binary operations. public enum Binary: CaseIterable { /// The `add` instruction. case add /// The `fadd` instruction. case fadd /// The `sub` instruction. case sub /// The `fsub` instruction. case fsub /// The `mul` instruction. case mul /// The `fmul` instruction. case fmul /// The `udiv` instruction. case udiv /// The `sdiv` instruction. case sdiv /// The `fdiv` instruction. case fdiv /// The `urem` instruction. case urem /// The `srem` instruction. case srem /// The `frem` instruction. case frem /// The `shl` instruction. case shl /// The `lshr` instruction. case lshr /// The `ashr` instruction. case ashr /// The `and` instruction. case and /// The `or` instruction. case or /// The `xor` instruction. case xor static let binaryOperationMap: [Binary: LLVMOpcode] = [ .add: LLVMAdd, .fadd: LLVMFAdd, .sub: LLVMSub, .fsub: LLVMFSub, .mul: LLVMMul, .fmul: LLVMFMul, .udiv: LLVMUDiv, .sdiv: LLVMSDiv, .fdiv: LLVMFDiv, .urem: LLVMURem, .srem: LLVMSRem, .frem: LLVMFRem, .shl: LLVMShl, .lshr: LLVMLShr, .ashr: LLVMAShr, .and: LLVMAnd, .or: LLVMOr, .xor: LLVMXor, ] /// Retrieves the corresponding `LLVMOpcode`. public var llvm: LLVMOpcode { return Binary.binaryOperationMap[self]! } /// Retrieves the corresponding opcode for this binary operation. public var opCode: OpCode { return OpCode(rawValue: self.llvm) } } /// `CastOperation` enumerates the subset of opcodes that are cast operations. public enum Cast: CaseIterable { /// The `trunc` instruction. case trunc /// The `zext` instruction. case zext /// The `sext` instruction. case sext /// The `fpToUI` instruction. case fpToUI /// The `fpToSI` instruction. case fpToSI /// The `uiToFP` instruction. case uiToFP /// The `siToFP` instruction. case siToFP /// The `fpTrunc` instruction. case fpTrunc /// The `fpext` instruction. case fpext /// The `ptrToInt` instruction. case ptrToInt /// The `intToPtr` instruction. case intToPtr /// The `bitCast` instruction. case bitCast /// The `addrSpaceCast` instruction. case addrSpaceCast static let castOperationMap: [Cast: LLVMOpcode] = [ .trunc: LLVMTrunc, .zext: LLVMZExt, .sext: LLVMSExt, .fpToUI: LLVMFPToUI, .fpToSI: LLVMFPToSI, .uiToFP: LLVMUIToFP, .siToFP: LLVMSIToFP, .fpTrunc: LLVMFPTrunc, .fpext: LLVMFPExt, .ptrToInt: LLVMPtrToInt, .intToPtr: LLVMIntToPtr, .bitCast: LLVMBitCast, .addrSpaceCast: LLVMAddrSpaceCast, ] /// Retrieves the corresponding `LLVMOpcode`. public var llvm: LLVMOpcode { return Cast.castOperationMap[self]! } /// Retrieves the corresponding opcode for this cast operation. public var opCode: OpCode { return OpCode(rawValue: self.llvm) } } }
a98f220255f57bd9ca91e1242f7ccc80
27.979769
84
0.664606
false
false
false
false
Qmerce/ios-sdk
refs/heads/master
Sources/EmbededUnit/AdProvider/PubMatic/APEPubMaticViewProvider.swift
mit
1
// // APEPubMaticViewProvider.swift // ApesterKit // // Created by Hasan Sawaed Tabash on 06/10/2021. // Copyright © 2021 Apester. All rights reserved. // import Foundation extension APEUnitView { struct PubMaticViewProvider { var view: POBBannerView? var delegate: PubMaticViewDelegate? } } extension APEUnitView.PubMaticViewProvider { struct Params: Hashable { enum AdType: String { case bottom case inUnit var size: CGSize { switch self { case .bottom: return .init(width: 320, height: 50) case .inUnit: return .init(width: 300, height: 250) } } } let adUnitId: String let profileId: Int let publisherId: String let appStoreUrl: String let isCompanionVariant: Bool let adType: AdType let appDomain: String let testMode: Bool let debugLogs: Bool let bidSummaryLogs: Bool let timeInView: Int? init?(from dictionary: [String: Any]) { guard let provider = dictionary[Constants.Monetization.adProvider] as? String, provider == Constants.Monetization.pubMatic, let appStoreUrl = dictionary[Constants.Monetization.appStoreUrl] as? String, let profileIdStr = dictionary[Constants.Monetization.profileId] as? String, let profileId = Int(profileIdStr), let isCompanionVariant = dictionary[Constants.Monetization.isCompanionVariant] as? Bool, let publisherId = dictionary[Constants.Monetization.publisherId] as? String, let adUnitId = dictionary[Constants.Monetization.pubMaticUnitId] as? String, let adTypeStr = dictionary[Constants.Monetization.adType] as? String, let adType = AdType(rawValue: adTypeStr) else { return nil } self.adUnitId = adUnitId self.profileId = profileId self.publisherId = publisherId self.appStoreUrl = appStoreUrl self.isCompanionVariant = isCompanionVariant self.adType = adType self.appDomain = dictionary[Constants.Monetization.appDomain] as? String ?? "" self.testMode = dictionary[Constants.Monetization.testMode] as? Bool ?? false self.debugLogs = dictionary[Constants.Monetization.debugLogs] as? Bool ?? false self.bidSummaryLogs = dictionary[Constants.Monetization.bidSummaryLogs] as? Bool ?? false self.timeInView = dictionary[Constants.Monetization.timeInView] as? Int } } } // MARK:- PubMatic ADs extension APEUnitView { private func makePubMaticViewDelegate(adType: PubMaticViewProvider.Params.AdType) -> PubMaticViewDelegate { PubMaticViewDelegate(adType: adType, containerViewController: containerViewController, receiveAdSuccessCompletion: { [weak self] adType in guard let self = self else { return } if case .inUnit = adType { self.pubMaticViewCloseButton.isHidden = false } self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonImpression) }, receiveAdErrorCompletion: { [weak self] adType, error in guard let self = self else { return } self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonLoadingImpressionFailed) print(error?.localizedDescription ?? "") if case .inUnit = adType { self.pubMaticViewCloseButton.isHidden = false } self.hidePubMaticView() }) } func setupPubMaticView(params: PubMaticViewProvider.Params) { defer { showPubMaticViews() } var pubMaticView = self.pubMaticViewProviders[params.adType]?.view guard pubMaticView == nil else { pubMaticView?.forceRefresh() return } let appInfo = POBApplicationInfo() appInfo.domain = params.appDomain appInfo.storeURL = URL(string: params.appStoreUrl)! OpenWrapSDK.setApplicationInfo(appInfo) self.messageDispatcher.sendNativeAdEvent(to: self.unitWebView, Constants.Monetization.playerMonLoadingPass) let adSizes = [POBAdSizeMake(params.adType.size.width, params.adType.size.height)].compactMap({ $0 }) pubMaticView = POBBannerView(publisherId: params.publisherId, profileId: .init(value: params.profileId), adUnitId: params.adUnitId, adSizes: adSizes) pubMaticView?.request.testModeEnabled = params.testMode pubMaticView?.request.debug = params.debugLogs pubMaticView?.request.bidSummaryEnabled = params.bidSummaryLogs let delegate = pubMaticViewProviders[params.adType]?.delegate ?? makePubMaticViewDelegate(adType: params.adType) pubMaticView?.delegate = delegate pubMaticView?.loadAd() self.pubMaticViewProviders[params.adType] = PubMaticViewProvider(view: pubMaticView, delegate: delegate) guard let timeInView = params.timeInView, pubMaticViewTimer == nil else { return } pubMaticViewTimer = Timer.scheduledTimer(withTimeInterval: Double(timeInView), repeats: false) { _ in self.hidePubMaticView() } } func removePubMaticView(of adType: PubMaticViewProvider.Params.AdType) { pubMaticViewProviders[adType]?.view?.removeFromSuperview() pubMaticViewProviders[adType] = nil guard pubMaticViewTimer != nil else { return } pubMaticViewCloseButton.removeFromSuperview() pubMaticViewTimer?.invalidate() pubMaticViewTimer = nil } @objc func hidePubMaticView() { removePubMaticView(of: .inUnit) } func showPubMaticViews() { self.pubMaticViewProviders .forEach({ type, provider in guard let containerView = unitWebView, let pubMaticView = provider.view else { return } containerView.addSubview(pubMaticView) containerView.bringSubviewToFront(pubMaticView) if case .inUnit = type { if let bottomView = self.pubMaticViewProviders[.bottom]?.view { containerView.bringSubviewToFront(bottomView) } self.pubMaticViewCloseButton.isHidden = true containerView.addSubview(self.pubMaticViewCloseButton) containerView.bringSubviewToFront(self.pubMaticViewCloseButton) } pubMaticView.translatesAutoresizingMaskIntoConstraints = false pubMaticView.removeConstraints(pubMaticView.constraints) NSLayoutConstraint.activate(pubMaticViewLayoutConstraints(pubMaticView, containerView: containerView, type: type)) }) } private func pubMaticViewLayoutConstraints(_ pubMaticView: POBBannerView, containerView: UIView, type: PubMaticViewProvider.Params.AdType) -> [NSLayoutConstraint] { var constraints = [pubMaticView.centerXAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0), pubMaticView.widthAnchor.constraint(equalToConstant: type.size.width), pubMaticView.heightAnchor.constraint(equalToConstant: type.size.height)] switch type { case .bottom: constraints += [pubMaticView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0)] case .inUnit: constraints += [pubMaticView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0), pubMaticViewCloseButton.centerXAnchor.constraint(equalTo: containerView.centerXAnchor, constant: type.size.width/2 + 7), pubMaticViewCloseButton.centerYAnchor.constraint(equalTo: containerView.centerYAnchor, constant: -type.size.height/2 - 7) ] } return constraints } }
3acaabac327565435b11ff7b9a6e5a2d
46.910526
168
0.583983
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/BlockchainComponentLibrary/Sources/Examples/RootView.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import SwiftUI @MainActor public struct RootView: View { @State var colorScheme: ColorScheme @State var layoutDirection: LayoutDirection private static let data: NavigationLinkProviderList = [ "1 - Base": [ NavigationLinkProvider(view: ColorsExamplesView(), title: "🌈 Colors"), NavigationLinkProvider(view: TypographyExamplesView(), title: "🔠 Typography"), NavigationLinkProvider(view: SpacingExamplesView(), title: "🔳 Spacing Rules"), NavigationLinkProvider(view: IconsExamplesView(), title: "🖼 Icons") ], "2 - Primitives": [ NavigationLinkProvider(view: TabBarExamplesView(), title: "🎼 TabBar"), NavigationLinkProvider(view: ButtonExamplesView(), title: "🕹 Buttons"), NavigationLinkProvider(view: PrimaryDividerExamples(), title: "🗂 Dividers"), NavigationLinkProvider(view: SVGExamples(), title: "✍️ SVG"), NavigationLinkProvider(view: GIFExamples(), title: "🌠 GIF"), NavigationLinkProvider(view: ProgressViewExamples(), title: "🌀 ProgressView"), NavigationLinkProvider(view: PrimarySwitchExamples(), title: "🔌 PrimarySwitch"), NavigationLinkProvider(view: TagViewExamples(), title: "🏷 Tag"), NavigationLinkProvider(view: CheckboxExamples(), title: "✅ Checkbox"), NavigationLinkProvider(view: RichTextExamples(), title: "🤑 Rich Text"), NavigationLinkProvider(view: SegmentedControlExamples(), title: "🚥 SegmentedControl"), NavigationLinkProvider(view: InputExamples(), title: "⌨️ Input"), NavigationLinkProvider(view: PrimaryPickerExamples(), title: "⛏ Picker"), NavigationLinkProvider(view: AlertExamples(), title: "⚠️ Alert"), NavigationLinkProvider(view: AlertToastExamples(), title: "🚨 AlertToast"), NavigationLinkProvider(view: PageControlExamples(), title: "📑 PageControl"), NavigationLinkProvider(view: PrimarySliderExamples(), title: "🎚 Slider"), NavigationLinkProvider(view: RadioExamples(), title: "🔘 Radio"), NavigationLinkProvider(view: ChartBalanceExamples(), title: "⚖️ Chart Balance"), NavigationLinkProvider(view: LineGraphExamples(), title: "📈 Line Graph"), NavigationLinkProvider(view: FilterExamples(), title: "🗳 Filter") ], "3 - Compositions": [ NavigationLinkProvider(view: PrimaryNavigationExamples(), title: "✈️ Navigation"), NavigationLinkProvider(view: CalloutCardExamples(), title: "💬 CalloutCard"), NavigationLinkProvider(view: SectionHeadersExamples(), title: "🪖 SectionHeaders"), NavigationLinkProvider(view: RowExamplesView(), title: "🚣‍♀️ Rows"), NavigationLinkProvider(view: BottomSheetExamples(), title: "📄 BottomSheet"), NavigationLinkProvider(view: SearchBarExamples(), title: "🔎 SearchBar"), NavigationLinkProvider(view: AlertCardExamples(), title: "🌋 AlertCard"), NavigationLinkProvider(view: PromoCardExamples(), title: "🛎 PromoCard"), NavigationLinkProvider(view: AnnouncementCardExamples(), title: "🎙 AnnouncementCard"), NavigationLinkProvider(view: LargeAnnouncementCardExamples(), title: "📡 LargeAnnouncementCard") ] ] public init(colorScheme: ColorScheme = .light, layoutDirection: LayoutDirection = .leftToRight) { _colorScheme = State(initialValue: colorScheme) _layoutDirection = State(initialValue: layoutDirection) } public static var content: some View { NavigationLinkProviderView(data: data) } public var body: some View { PrimaryNavigationView { NavigationLinkProviderView(data: RootView.data) .primaryNavigation(title: "📚 Component Library") { Button(colorScheme == .light ? "🌗" : "🌓") { colorScheme = colorScheme == .light ? .dark : .light } Button(layoutDirection == .leftToRight ? "➡️" : "⬅️") { layoutDirection = layoutDirection == .leftToRight ? .rightToLeft : .leftToRight } } } .colorScheme(colorScheme) .environment(\.layoutDirection, layoutDirection) } } struct RootView_Previews: PreviewProvider { static var previews: some View { ForEach( ColorScheme.allCases, id: \.self ) { colorScheme in RootView(colorScheme: colorScheme) } } }
3dbfe1a99321fb60ef44c26a233c1402
50.173913
107
0.6387
false
false
false
false
XcqRomance/BookRoom-complete-
refs/heads/master
BookRoom/BookCell.swift
mit
1
// // BookCell.swift // BookRoom // // Created by romance on 2017/5/4. // Copyright © 2017年 romance. All rights reserved. // import UIKit import SDWebImage final class BookCell: UICollectionViewCell { @IBOutlet weak var bookCover: UIImageView! @IBOutlet weak var coverName: UILabel! @IBOutlet weak var isReadImageView: UIImageView! @IBOutlet weak var bookWidth: NSLayoutConstraint! @IBOutlet weak var bookHeight: NSLayoutConstraint! @IBOutlet weak var gradientView: UIView! var book: Book? { didSet { bookCover.sd_setImage(with: URL(string: (book?.pic.aliyunThumb())!), placeholderImage: UIImage(named: "bookDefault"), options: .retryFailed) { (_, _, _, _) in self.coverName.isHidden = true } coverName.text = book?.bookName // title.text = book?.bookName if (book?.isRead)! { // 是否阅读过该书籍 isReadImageView.isHidden = false } else { isReadImageView.isHidden = true } if book?.orientation == 1 { // 竖版书籍 bookWidth.constant = 67 bookHeight.constant = 88 } else { bookWidth.constant = 96 bookHeight.constant = 67 } layoutIfNeeded() } } override func awakeFromNib() { super.awakeFromNib() bookCover.layer.cornerRadius = 10 let gradLayer = CAGradientLayer() gradLayer.colors = [UIColor.hexColor(0x045b94).cgColor, UIColor.hexColor(0x176da6).cgColor] gradLayer.startPoint = CGPoint(x: 0, y: 0) gradLayer.endPoint = CGPoint(x: 0, y: 1) gradLayer.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width / 3, height: 25) gradientView.layer.addSublayer(gradLayer) } }
e78f8be8eb781fec57b0403b4d557af0
27.474576
164
0.65119
false
false
false
false
derekcdaley/anipalooza
refs/heads/master
AnimalController.swift
gpl-3.0
1
// // AnimalController.swift // Guess It // // Created by Derek Daley on 3/15/17. // Copyright © 2017 DSkwared. All rights reserved. // import SpriteKit class AnimalController: SKSpriteNode { private var animateAnimalAction = SKAction(); private var animals = [SKNode](); func shuffle( animalssArray: [SKNode]) -> [SKNode] { var animalssArray = animalssArray; for i in ((0 + 1)...animalssArray.count - 1).reversed() { let j = Int(arc4random_uniform(UInt32(i-1))); swap(&animalssArray[i], &animalssArray[j]); } return animalssArray; } func arrangeAnimalsInScene(scene: SKScene){ let animal = Animal(); animals = animal.createAnimals(); animals = shuffle(animalssArray: animals); if scene.name == "Level1Scene" { for i in 0...3 { var x = 0; var y = 0; switch(i){ case 0: x = -150; y = -50; case 1: x = 150; y = -50; case 2: x = 0; y = -210; default: x = 0; y = 110; } animals[i].position = CGPoint(x: x, y: y); scene.addChild(animals[i]); } }else if scene.name == "Level2Scene" { for i in 0...3 { var x = 0; var y = 0; switch(i){ case 0: x = -150; y = -130; case 1: x = 150; y = -130; case 2: x = -150; y = -330; default: x = 150; y = -330; } animals[i].position = CGPoint(x: x, y: y); scene.addChild(animals[i]); } } } }
6a40615bdf763b54a539bff282dbdd1e
25.82716
65
0.364013
false
false
false
false
ikemai/ColorAdjuster
refs/heads/master
Example/ColorAdjuster/AdjustmentRbgView.swift
mit
1
// // AdjustmentRbgView.swift // ColorAdjuster // // Created by Mai Ikeda on 2015/10/10. // Copyright © 2015年 CocoaPods. All rights reserved. // import UIKit class AdjustmentRbgView: UIView { @IBOutlet weak var baseView: UIView! @IBOutlet weak var targetView: UIView! @IBOutlet weak var rgbLabel: UILabel! @IBOutlet weak var rSlider: UISlider! @IBOutlet weak var gSlider: UISlider! @IBOutlet weak var bSlider: UISlider! private var rValue: CGFloat { return CGFloat(rSlider.value) * 2 } private var gValue: CGFloat { return CGFloat(gSlider.value) * 2 } private var bValue: CGFloat { return CGFloat(bSlider.value) * 2 } override func awakeFromNib() { super.awakeFromNib() rSlider.value = 0.5 gSlider.value = 0.5 bSlider.value = 0.5 updateBaseColor(UIColor(hex: 0xB7EAE7)) } func updateBaseColor(color: UIColor) { baseView.backgroundColor = color updateRGBColor() } func updateRGBColor() { guard let color = baseView.backgroundColor else { return } let adjustmentColor = color.colorWithRGBComponent(red: rValue, green: gValue, blue: bValue) targetView.backgroundColor = adjustmentColor if let rbg = adjustmentColor?.colorRGB() { let r = Double(Int(rbg.red * 100)) / 100 let g = Double(Int(rbg.green * 100)) / 100 let b = Double(Int(rbg.blue * 100)) / 100 rgbLabel.text = "R = \(r) : G = \(g) : B = \(b)" } } }
10ab8cec81cbb12c949346f9dbddb2b8
28.867925
99
0.607707
false
false
false
false
jpush/jchat-swift
refs/heads/master
JChat/Src/UserModule/ViewController/JCUpdatePassworkViewController.swift
mit
1
// // JCUpdatePassworkViewController.swift // JChat // // Created by JIGUANG on 2017/3/16. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit import JMessage class JCUpdatePassworkViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() _init() } private lazy var oldPasswordTextField: UITextField = { var textField = UITextField() textField.placeholder = "请输入原始密码" textField.isSecureTextEntry = true textField.font = UIFont.systemFont(ofSize: 16) return textField }() private lazy var newPasswordTextField: UITextField = { var textField = UITextField() textField.placeholder = "请设置登录密码" textField.isSecureTextEntry = true textField.font = UIFont.systemFont(ofSize: 16) return textField }() private lazy var checkPasswordTextField: UITextField = { var textField = UITextField() textField.placeholder = "请再次输入" textField.isSecureTextEntry = true textField.font = UIFont.systemFont(ofSize: 16) return textField }() private lazy var updateButton: UIButton = { var updateButton = UIButton() updateButton.setTitle("确认", for: .normal) updateButton.layer.cornerRadius = 3.0 updateButton.layer.masksToBounds = true updateButton.addTarget(self, action: #selector(_updatePasswork), for: .touchUpInside) return updateButton }() private lazy var oldPasswordLabel: UILabel = { var label = UILabel() label.text = "原始密码" label.font = UIFont.systemFont(ofSize: 16) return label }() private lazy var newPasswordLabel: UILabel = { var label = UILabel() label.text = "新密码" label.font = UIFont.systemFont(ofSize: 16) return label }() private lazy var checkPasswordLabel: UILabel = { var label = UILabel() label.text = "确认密码" label.font = UIFont.systemFont(ofSize: 16) return label }() private lazy var line1: UILabel = { var label = UILabel() label.backgroundColor = UIColor(netHex: 0xd9d9d9) return label }() private lazy var line2: UILabel = { var label = UILabel() label.backgroundColor = UIColor(netHex: 0xd9d9d9) return label }() private lazy var bgView: UIView = UIView() //MARK: - private func private func _init() { self.title = "修改密码" view.backgroundColor = UIColor(netHex: 0xe8edf3) updateButton.setBackgroundImage(UIImage.createImage(color: UIColor(netHex: 0x2dd0cf), size: CGSize(width: view.width - 30, height: 40)), for: .normal) bgView.backgroundColor = .white view.addSubview(bgView) bgView.addSubview(oldPasswordLabel) bgView.addSubview(newPasswordLabel) bgView.addSubview(checkPasswordLabel) bgView.addSubview(oldPasswordTextField) bgView.addSubview(newPasswordTextField) bgView.addSubview(checkPasswordTextField) bgView.addSubview(line1) bgView.addSubview(line2) view.addSubview(updateButton) view.addConstraint(_JCLayoutConstraintMake(bgView, .left, .equal, view, .left)) view.addConstraint(_JCLayoutConstraintMake(bgView, .right, .equal, view, .right)) if isIPhoneX { view.addConstraint(_JCLayoutConstraintMake(bgView, .top, .equal, view, .top, 88)) } else { view.addConstraint(_JCLayoutConstraintMake(bgView, .top, .equal, view, .top, 64)) } view.addConstraint(_JCLayoutConstraintMake(bgView, .height, .equal, nil, .notAnAttribute, 135)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .left, .equal, bgView, .left, 15)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .top, .equal, bgView, .top, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .width, .equal, nil, .notAnAttribute, 75)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5)) bgView.addConstraint(_JCLayoutConstraintMake(line1, .left, .equal, oldPasswordLabel, .left)) bgView.addConstraint(_JCLayoutConstraintMake(line1, .top, .equal, bgView, .top, 44.5)) bgView.addConstraint(_JCLayoutConstraintMake(line1, .right, .equal, bgView, .right, -15)) bgView.addConstraint(_JCLayoutConstraintMake(line1, .height, .equal, nil, .notAnAttribute, 0.5)) bgView.addConstraint(_JCLayoutConstraintMake(line2, .left, .equal, line1, .left)) bgView.addConstraint(_JCLayoutConstraintMake(line2, .top, .equal, line1, .top, 45)) bgView.addConstraint(_JCLayoutConstraintMake(line2, .right, .equal, line1, .right)) bgView.addConstraint(_JCLayoutConstraintMake(line2, .height, .equal, nil, .notAnAttribute, 0.5)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .left, .equal, oldPasswordLabel, .left)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .top, .equal, line1, .bottom, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .width, .equal, nil, .notAnAttribute, 75)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .left, .equal, oldPasswordLabel, .left)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .top, .equal, line2, .bottom, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .width, .equal, nil, .notAnAttribute, 75)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordLabel, .height, .equal, nil, .notAnAttribute, 22.5)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .left, .equal, oldPasswordLabel, .right, 20)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .top, .equal, bgView, .top, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .right, .equal, bgView, .right, -15)) bgView.addConstraint(_JCLayoutConstraintMake(oldPasswordTextField, .height, .equal, nil, .notAnAttribute, 22.5)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .left, .equal, oldPasswordTextField, .left)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .top, .equal, line1, .bottom, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .right, .equal, oldPasswordTextField, .right)) bgView.addConstraint(_JCLayoutConstraintMake(newPasswordTextField, .height, .equal, oldPasswordTextField, .height)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .left, .equal, oldPasswordTextField, .left)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .top, .equal, line2, .bottom, 11.5)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .right, .equal, oldPasswordTextField, .right)) bgView.addConstraint(_JCLayoutConstraintMake(checkPasswordTextField, .height, .equal, oldPasswordTextField, .height)) view.addConstraint(_JCLayoutConstraintMake(updateButton, .left, .equal, view, .left, 15)) view.addConstraint(_JCLayoutConstraintMake(updateButton, .right, .equal, view, .right, -15)) view.addConstraint(_JCLayoutConstraintMake(updateButton, .top, .equal, bgView, .bottom, 15)) view.addConstraint(_JCLayoutConstraintMake(updateButton, .height, .equal, nil, .notAnAttribute, 40)) } //MARK: - click event @objc func _updatePasswork() { view.endEditing(true) let oldPassword = oldPasswordTextField.text! let newPassword = newPasswordTextField.text! let checkPassword = checkPasswordTextField.text! if oldPassword.isEmpty || newPassword.isEmpty || checkPassword.isEmpty { MBProgressHUD_JChat.show(text: "所有信息不能为空", view: view) return } if newPassword != checkPassword { MBProgressHUD_JChat.show(text: "新密码和确认密码不一致", view: view) return } MBProgressHUD_JChat.showMessage(message: "修改中", toView: view) JMSGUser.updateMyPassword(withNewPassword: newPassword, oldPassword: oldPassword) { (result, error) in MBProgressHUD_JChat.hide(forView: self.view, animated: true) if error == nil { self.navigationController?.popViewController(animated: true) } else { MBProgressHUD_JChat.show(text: "更新失败", view: self.view) } } } }
d181a23a723b43775cbc45521733d932
48.227778
158
0.678592
false
false
false
false
sovereignshare/fly-smuthe
refs/heads/master
Fly Smuthe/Fly Smuthe/DataCollectionManager.swift
gpl-3.0
1
// // DataCollectionManager.swift // Fly Smuthe // // Created by Adam M Rivera on 8/27/15. // Copyright (c) 2015 Adam M Rivera. All rights reserved. // import Foundation import UIKit import CoreLocation import CoreMotion class DataCollectionManager : NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager(); let motionManager = CMMotionManager(); var latestTurbulenceDataState: TurbulenceStatisticModel!; var delegate: DataCollectionManagerDelegate!; class var sharedInstance: DataCollectionManager { struct Singleton { static let instance = DataCollectionManager() } return Singleton.instance; } func startCollection(delegate: DataCollectionManagerDelegate){ self.delegate = delegate; locationManager.delegate = self; motionManager.startAccelerometerUpdates(); evaluateAccess(); } func evaluateAccess() { switch CLLocationManager.authorizationStatus() { case CLAuthorizationStatus.AuthorizedAlways: locationManager.startUpdatingLocation(); case CLAuthorizationStatus.NotDetermined: locationManager.requestAlwaysAuthorization() case CLAuthorizationStatus.AuthorizedWhenInUse, CLAuthorizationStatus.Restricted, CLAuthorizationStatus.Denied: let alertController = UIAlertController( title: "Background Location Access Disabled", message: "In order to provide anonymous, automatic turbulence 'PIREPs', please open this app's settings and set location access to 'Always'.", preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let openAction = UIAlertAction(title: "Open Settings", style: .Default) { (action) in if let url = NSURL(string:UIApplicationOpenSettingsURLString) { UIApplication.sharedApplication().openURL(url) } } alertController.addAction(openAction) self.delegate.requestAccess(alertController); if(CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse){ locationManager.startUpdatingLocation(); } } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if (status == CLAuthorizationStatus.AuthorizedAlways || status == CLAuthorizationStatus.AuthorizedWhenInUse){ locationManager.startUpdatingLocation(); } else { evaluateAccess(); } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { var xAccel: Double!; var yAccel: Double!; var zAccel: Double!; var altitude: Int!; var latitude: Double!; var longitude: Double!; var weakLocation: CLLocation!; var weakAccelData: CMAccelerometerData!; var hasLocationData = false; var hasAccelData = false; if let location = locations.last { altitude = Int(location.altitude); latitude = location.coordinate.latitude; longitude = location.coordinate.longitude; weakLocation = location; hasLocationData = true; } if let currentAccelValues = motionManager.accelerometerData{ weakAccelData = currentAccelValues; xAccel = currentAccelValues.acceleration.x; yAccel = currentAccelValues.acceleration.y; zAccel = currentAccelValues.acceleration.z; hasAccelData = true; } if let strongDelegate = self.delegate{ strongDelegate.receivedUpdate(weakLocation, accelerometerData: weakAccelData); } let newTurbulenceDataState = TurbulenceStatisticModel(xAccel: xAccel, yAccel: yAccel, zAccel: zAccel, altitude: altitude, latitude: latitude, longitude: longitude); if((latestTurbulenceDataState == nil && hasLocationData && hasAccelData) || (latestTurbulenceDataState != nil && latestTurbulenceDataState.hasNotableChange(newTurbulenceDataState))){ latestTurbulenceDataState = newTurbulenceDataState; TurbulenceStatisticRepository.sharedInstance.save(latestTurbulenceDataState); } SyncManager.sharedInstance.startBackgroundSync(); } } protocol DataCollectionManagerDelegate { func requestAccess(controller: UIAlertController); func receivedUpdate(lastLocation: CLLocation!, accelerometerData: CMAccelerometerData!); }
a3561733db932258a47c27f6431f6183
37.338583
190
0.655711
false
false
false
false
cafbuddy/cafbuddy-iOS
refs/heads/master
Caf Buddy/MealListingHeader.swift
mit
1
// // collectionViewHeader.swift // Caf Buddy // // Created by Jacob Forster on 3/1/15. // Copyright (c) 2015 St. Olaf Acm. All rights reserved. // import Foundation class MealListingHeader : UICollectionReusableView { var headerTitle = UILabel() var rightLine = UIView() var leftLine = UIView() func setTitle(title: String, sectionIndex : Int) { headerTitle.text = title headerTitle.font = UIFont.boldSystemFontOfSize(22) headerTitle.textColor = colorWithHexString(COLOR_DARKER_BLUE) headerTitle.textAlignment = NSTextAlignment.Center var offset : Int = 0 if (sectionIndex == 0) { offset = 5 } headerTitle.frame = CGRectMake(0, CGFloat(offset), self.frame.size.width, 40) offset = 0 if (sectionIndex == 1) { offset = 5 } rightLine.frame = CGRectMake(10, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2) rightLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE) leftLine.frame = CGRectMake(self.frame.size.width - (self.frame.size.width / 2) + 60, 25 - CGFloat(offset), (self.frame.size.width / 2) - 70, 2) leftLine.backgroundColor = colorWithHexString(COLOR_DARKER_BLUE) self.addSubview(rightLine) self.addSubview(leftLine) self.addSubview(headerTitle) } }
7097dacde2cfd6bf15dbc06cbc0d0971
28.9375
152
0.616992
false
false
false
false
Eonil/EditorLegacy
refs/heads/master
Modules/SQLite3/Sources/Value.swift
mit
2
// // Value.swift // EonilSQLite3 // // Created by Hoon H. on 9/15/14. // // import Foundation public typealias Binary = Blob /// We don't use Swift `nil` to represent SQLite3 `NULL` because it /// makes program more complex. /// /// https://www.sqlite.org/datatype3.html public enum Value : Equatable, Hashable, Printable, NilLiteralConvertible, IntegerLiteralConvertible, FloatLiteralConvertible, StringLiteralConvertible { case Null case Integer(Int64) case Float(Double) case Text(String) case Blob(Binary) } public extension Value { } public extension Value { public var hashValue:Int { get { switch self { case Null: return 0 case let Integer(s): return s.hashValue case let Float(s): return s.hashValue case let Text(s): return s.hashValue case let Blob(s): return s.hashValue } } } } public extension Value { public init(nilLiteral: ()) { self = Value.Null } public init(integerLiteral value: Int64) { self = Integer(value) } // public init(integerLiteral value: Int) { // precondition(IntMax(value) <= IntMax(Int64.max)) // self = Integer(Int64(value)) // } public init(floatLiteral value: Double) { self = Float(value) } public init(stringLiteral value: String) { self = Text(value) } public init(extendedGraphemeClusterLiteral value: String) { self = Text(value) } public init(unicodeScalarLiteral value: String) { self = Text(value) } } public extension Value { public var description:String { get { switch self { case let Null(s): return "NULL" case let Integer(s): return "INTEGER(\(s))" case let Float(s): return "FLOAT(\(s))" case let Text(s): return "TEXT(\(s))" case let Blob(s): return "BLOB(~~~~)" // default: fatalError("Unsupported value case.") } } } } public func == (l:Value, r:Value) -> Bool { switch (l,r) { case let (Value.Null, Value.Null): return true case let (Value.Integer(a), Value.Integer(b)): return a == b case let (Value.Float(a), Value.Float(b)): return a == b case let (Value.Text(a), Value.Text(b)): return a == b case let (Value.Blob(a), Value.Blob(b)): return a == b default: return false } } //public func == (l:Value, r:()?) -> Bool { // return l == Value.Null && r == nil //} // //public func == (l:Value, r:Int) -> Bool { // return l == Int64(r) //} //public func == (l:Value, r:Int64) -> Bool { // if let v2 = l.integer { return v2 == r } // return false //} //public func == (l:Value, r:Double) -> Bool { // if let v2 = l.float { return v2 == r } // return false //} //public func == (l:Value, r:String) -> Bool { // if let v2 = l.text { return v2 == r } // return false //} //public func == (l:Value, r:Binary) -> Bool { // if let v2 = l.blob { return v2 == r } // return false //} public extension Value { // init(){ // self = Value.Null // } public init(_ v:Int64?) { self = v == nil ? Null : Integer(v!) } public init(_ v:Double?) { self = v == nil ? Null : Float(v!) } public init(_ v:String?) { self = v == nil ? Null : Text(v!) } public init(_ v:Binary?) { self = v == nil ? Null : Blob(v!) } public var null:Bool { get { return self == Value.Null // switch self { // case let Null: return true // default: return false // } } } public var integer:Int64? { get { switch self { case let Integer(s): return s default: return nil } } } public var float:Double? { get { switch self { case let Float(s): return s default: return nil } } } public var text:String? { get { switch self { case let Text(s): return s default: return nil } } } public var blob:Binary? { get { switch self { case let Blob(s): return s default: return nil } } } } // //public typealias Value = AnyObject ///< Don't use `Any`. Currently, it causes many subtle unknown problems. // // // // //// ////public typealias FieldList = [Value] ///< The value can be one of these types; `Int`, `Double`, `String`, `Blob`. A field with NULL will not be stored. ////public typealias Record = [String:Value] //// ////struct RowList ////{ //// let columns:[String] //// let items:[FieldList] ////} // // // // // ////typealias Integer = Int64 // ///// 64-bit signed integer class type. ///// Defined to provide conversion to AnyObject. ///// (Swift included in Xcode 6.0.1 does not support this conversion...) //public class Integer : Printable//, SignedIntegerType, SignedNumberType //{ // public init(_ number:Int64) // { // self.number = number // } // // // public var description:String // { // get // { // return number.description // } // } // //// public var hashValue:Int //// { //// get //// { //// return number.hashValue //// } //// } //// //// public var arrayBoundValue:Int64.ArrayBound //// { //// get //// { //// return number.arrayBoundValue //// } //// } //// public func toIntMax() -> IntMax //// { //// return number.toIntMax() //// } //// //// public class func from(x: IntMax) -> Integer //// { //// return Integer(Int64.from(x)) //// } // // let number:Int64 //} // //extension Int64 //{ // init(_ integer:Integer) // { // self.init(integer.number) // } //} /// Represents BLOB. public class Blob: Hashable { init(address:UnsafePointer<()>, length:Int) { precondition(address != nil) precondition(length >= 0) value = NSData(bytes: address, length: length) } public var hashValue:Int { get { return value.hashValue } } var length:Int { get { return value.length } } var address:UnsafePointer<()> { get { return value.bytes } } private init(value:NSData) { self.value = value } private let value:NSData } public func == (l:Blob, r:Blob) -> Bool { return l.value == r.value }
612f8502a6988461f753625f2b2a25f3
16.011696
158
0.601066
false
false
false
false
cwwise/CWWeChat
refs/heads/master
CWWeChat/MainClass/Contacts/ContactSetting/CWContactSettingController.swift
mit
2
// // CWContactSettingController.swift // CWWeChat // // Created by wei chen on 2017/9/5. // Copyright © 2017年 cwwise. All rights reserved. // import UIKit class CWContactSettingController: CWBaseTableViewController { lazy var tableViewManager: CWTableViewManager = { let tableViewManager = CWTableViewManager(tableView: self.tableView) tableViewManager.delegate = self tableViewManager.dataSource = self return tableViewManager }() override func viewDidLoad() { super.viewDidLoad() self.title = "资料设置" setupData() } func setupData() { let item1 = CWTableViewItem(title: "设置备注及标签") tableViewManager.addSection(itemsOf: [item1]) let item2 = CWTableViewItem(title: "把她推荐给朋友") tableViewManager.addSection(itemsOf: [item2]) let item3 = CWBoolItem(title: "设置为星标用户", value: true) tableViewManager.addSection(itemsOf: [item3]) let item4 = CWBoolItem(title: "不让她看我的朋友圈", value: true) let item5 = CWBoolItem(title: "不看她的朋友圈 ", value: true) tableViewManager.addSection(itemsOf: [item4, item5]) let item6 = CWBoolItem(title: "加入黑名单", value: true) let item7 = CWTableViewItem(title: "投诉") tableViewManager.addSection(itemsOf: [item6, item7]) let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 80) let footerView = UIView(frame: frame) self.tableView.tableFooterView = footerView } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension CWContactSettingController: CWTableViewManagerDelegate, CWTableViewManagerDataSource { }
9dd5616bb1e65820959daa70a2128187
27.873016
96
0.647609
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/Utility/Blogging Reminders/BloggingRemindersScheduleFormatter.swift
gpl-2.0
2
import Foundation struct BloggingRemindersScheduleFormatter { private let calendar: Calendar init(calendar: Calendar? = nil) { self.calendar = calendar ?? { var calendar = Calendar.current calendar.locale = Locale.autoupdatingCurrent return calendar }() } /// Attributed short description string of the current schedule for the specified blog. /// func shortScheduleDescription(for schedule: BloggingRemindersScheduler.Schedule, time: String? = nil) -> NSAttributedString { switch schedule { case .none: return Self.stringToAttributedString(TextContent.shortNoRemindersDescription) case .weekdays(let days): guard days.count > 0 else { return shortScheduleDescription(for: .none, time: time) } return Self.shortScheduleDescription(for: days.count, time: time) } } /// Attributed long description string of the current schedule for the specified blog. /// func longScheduleDescription(for schedule: BloggingRemindersScheduler.Schedule, time: String) -> NSAttributedString { switch schedule { case .none: return NSAttributedString(string: TextContent.longNoRemindersDescription) case .weekdays(let days): guard days.count > 0 else { return longScheduleDescription(for: .none, time: time) } // We want the days sorted by their localized index because under some locale configurations // Sunday is the first day of the week, whereas in some other localizations Monday comes first. let sortedDays = days.sorted { (first, second) -> Bool in let firstIndex = self.calendar.localizedWeekdayIndex(unlocalizedWeekdayIndex: first.rawValue) let secondIndex = self.calendar.localizedWeekdayIndex(unlocalizedWeekdayIndex: second.rawValue) return firstIndex < secondIndex } let markedUpDays: [String] = sortedDays.compactMap({ day in return "<strong>\(self.calendar.weekdaySymbols[day.rawValue])</strong>" }) let text: String if days.count == 1 { text = String(format: TextContent.oneReminderLongDescriptionWithTime, markedUpDays.first ?? "", "<strong>\(time)</strong>") } else { let formatter = ListFormatter() let formattedDays = formatter.string(from: markedUpDays) ?? "" text = String(format: TextContent.manyRemindersLongDescriptionWithTime, "<strong>\(days.count)</strong>", formattedDays, "<strong>\(time)</strong>") } return Self.stringToAttributedString(text) } } } // MARK: - Private type methods and properties private extension BloggingRemindersScheduleFormatter { static func shortScheduleDescription(for days: Int, time: String?) -> NSAttributedString { guard let time = time else { return shortScheduleDescription(for: days) } return shortScheduleDescriptionWithTime(for: days, time: time) } static func shortScheduleDescriptionWithTime(for days: Int, time: String) -> NSAttributedString { let text: String = { switch days { case 1: return String(format: TextContent.oneReminderShortDescriptionWithTime, time) case 2: return String(format: TextContent.twoRemindersShortDescriptionWithTime, time) case 7: return "<strong>" + String(format: TextContent.everydayRemindersShortDescriptionWithTime, time) + "</strong>" default: return String(format: TextContent.manyRemindersShortDescriptionWithTime, days, time) } }() return Self.stringToAttributedString(text) } static func shortScheduleDescription(for days: Int) -> NSAttributedString { let text: String = { switch days { case 1: return TextContent.oneReminderShortDescription case 2: return TextContent.twoRemindersShortDescription case 7: return "<strong>" + TextContent.everydayRemindersShortDescription + "</strong>" default: return String(format: TextContent.manyRemindersShortDescription, days) } }() return Self.stringToAttributedString(text) } static func stringToAttributedString(_ string: String) -> NSAttributedString { let htmlData = NSString(string: string).data(using: String.Encoding.unicode.rawValue) ?? Data() let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html] let attributedString = (try? NSMutableAttributedString(data: htmlData, options: options, documentAttributes: nil)) ?? NSMutableAttributedString() // This loop applies the default font to the whole text, while keeping any symbolic attributes the previous font may // have had (such as bold style). attributedString.enumerateAttribute(.font, in: NSRange(location: 0, length: attributedString.length)) { (value, range, stop) in guard let oldFont = value as? UIFont, let newDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: .body) .withSymbolicTraits(oldFont.fontDescriptor.symbolicTraits) else { return } let newFont = UIFont(descriptor: newDescriptor, size: 0) attributedString.addAttributes([.font: newFont], range: range) } return attributedString } enum TextContent { static let shortNoRemindersDescription = NSLocalizedString("None set", comment: "Title shown on table row where no blogging reminders have been set up yet") static let longNoRemindersDescription = NSLocalizedString("You have no reminders set.", comment: "Text shown to the user when setting up blogging reminders, if they complete the flow and have chosen not to add any reminders.") // Ideally we should use stringsdict to translate plurals, but GlotPress currently doesn't support this. static let oneReminderLongDescriptionWithTime = NSLocalizedString("You'll get a reminder to blog <strong>once</strong> a week on %@ at %@.", comment: "Blogging Reminders description confirming a user's choices. The placeholder will be replaced at runtime with a day of the week. The HTML markup is used to bold the word 'once'.") static let manyRemindersLongDescriptionWithTime = NSLocalizedString("You'll get reminders to blog %@ times a week on %@.", comment: "Blogging Reminders description confirming a user's choices. The first placeholder will be populated with a count of the number of times a week they'll be reminded. The second will be a formatted list of days. For example: 'You'll get reminders to blog 2 times a week on Monday and Tuesday.") static let oneReminderShortDescriptionWithTime = NSLocalizedString("<strong>Once</strong> a week at %@", comment: "Short title telling the user they will receive a blogging reminder once per week. The word for 'once' should be surrounded by <strong> HTML tags.") static let twoRemindersShortDescriptionWithTime = NSLocalizedString("<strong>Twice</strong> a week at %@", comment: "Short title telling the user they will receive a blogging reminder two times a week. The word for 'twice' should be surrounded by <strong> HTML tags.") static let manyRemindersShortDescriptionWithTime = NSLocalizedString("<strong>%d</strong> times a week at %@", comment: "A short description of how many times a week the user will receive a blogging reminder. The '%d' placeholder will be populated with a count of the number of times a week they'll be reminded, and should be surrounded by <strong> HTML tags.") static let everydayRemindersShortDescriptionWithTime = NSLocalizedString("Every day at %@", comment: "Short title telling the user they will receive a blogging reminder every day of the week.") static let oneReminderShortDescription = NSLocalizedString("<strong>Once</strong> a week", comment: "Short title telling the user they will receive a blogging reminder once per week. The word for 'once' should be surrounded by <strong> HTML tags.") static let twoRemindersShortDescription = NSLocalizedString("<strong>Twice</strong> a week", comment: "Short title telling the user they will receive a blogging reminder two times a week. The word for 'twice' should be surrounded by <strong> HTML tags.") static let manyRemindersShortDescription = NSLocalizedString("<strong>%d</strong> times a week", comment: "A short description of how many times a week the user will receive a blogging reminder. The '%d' placeholder will be populated with a count of the number of times a week they'll be reminded, and should be surrounded by <strong> HTML tags.") static let everydayRemindersShortDescription = NSLocalizedString("Every day", comment: "Short title telling the user they will receive a blogging reminder every day of the week.") } }
c1c8a8b89b528591d180dd831a926dfe
56.095506
363
0.62885
false
false
false
false
FandyLiu/FDDemoCollection
refs/heads/master
Swift/WidgetDemo/WidgetDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // WidgetDemo // // Created by QianTuFD on 2017/6/23. // Copyright © 2017年 fandy. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return true } func application(_ application: UIApplication, handleOpen url: URL) -> Bool { return true } // iOS (9.0 and later), tvOS (9.0 and later) func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { return true } func abc(url: URL) { let prefix = "fandyTest://action=" let urlStr = url.absoluteString if urlStr.hasPrefix(prefix) { // let action = urlStr.replacingOccurrences(of: prefix, with: "") let index = prefix.characters.index(prefix.startIndex, offsetBy: prefix.characters.count) let action = urlStr.substring(from: index) if action == "richScan" { } } } 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:. } }
1e054051c65a57149c15ee1f0162525a
40.653333
285
0.696863
false
false
false
false
esttorhe/SlackTeamExplorer
refs/heads/master
SlackTeamExplorer/SlackTeamExplorer/ViewControllers/ViewController.swift
mit
1
// // ViewController.swift // SlackTeamExplorer // // Created by Esteban Torres on 29/6/15. // Copyright (c) 2015 Esteban Torres. All rights reserved. // // Native Frameworks import UIKit // Shared import SlackTeamCoreDataProxy // Misc. import HexColors // Network import SDWebImage class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var loadingActivityIndicator: UIActivityIndicatorView! // ViewModels let membersViewModel = MembersViewModel() override func viewDidLoad() { super.viewDidLoad() // Configure transparent nav bar self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.tintColor = UIColor.blackColor() // Configure the view models membersViewModel.beginLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in self.loadingActivityIndicator.startAnimating() } membersViewModel.endLoadingSignal.deliverOnMainThread().subscribeNext { [unowned self] _ in self.loadingActivityIndicator.stopAnimating() } membersViewModel.updateContentSignal.deliverOnMainThread().subscribeNext({ [unowned self] members in self.collectionView.reloadData() }, error: { [unowned self] error in let alertController = UIAlertController(title: "Unable to fetch members", message: error?.description, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in alertController.dismissViewControllerAnimated(true, completion: nil) }) alertController.addAction(ok) self.presentViewController(alertController, animated: true, completion: nil) println("• Unable to load members: \(error)") }) // Trigger first load membersViewModel.active = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.collectionView.collectionViewLayout.invalidateLayout() } // MARK: Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let detailVC = segue.destinationViewController as? DetailViewController, cell = sender as? MemberCell, indexPath = collectionView.indexPathForCell(cell) { let member = membersViewModel.memberAtIndexPath(indexPath) detailVC.memberViewModel = MemberViewModel(memberID: member.objectID) } } // MARK: - Collection View func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.membersViewModel.numberOfItemsInSection(section) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemberCell", forIndexPath: indexPath) as! MemberCell cell.avatarImageView.image = nil cell.avatarImageView.backgroundColor = UIColor.slackPurpleColor() cell.usernameLabel.text = nil cell.titleLabel.text = nil let member = membersViewModel.memberAtIndexPath(indexPath) cell.usernameLabel.text = "@\(member.name)" if let profile = member.profile { if let imageURL = profile.image192 { cell.avatarImageView.sd_setImageWithURL(NSURL(string: imageURL), placeholderImage: nil) { (image, error, cacheType, url) in if let img = image { cell.avatarImageView.image = img } else if let fburl = profile.fallBackImageURL { cell.avatarImageView.sd_setImageWithURL(fburl) } } } if let title = profile.title { cell.titleLabel.text = title } } if let strColor = member.color, color = UIColor(hexString: strColor) { cell.avatarImageView.layer.borderWidth = 4.0 cell.avatarImageView.layer.borderColor = color.CGColor cell.layer.cornerRadius = 10.0 } return cell } override func didRotateFromInterfaceOrientation(_: UIInterfaceOrientation) { collectionView.collectionViewLayout.invalidateLayout() } // MARK: - Collection View Flow Layout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { collectionView.layoutIfNeeded() return CGSizeMake(CGRectGetWidth(collectionView.bounds) - 30.0, 81.0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 10.0 } }
1e9e92345e4ebccc251a74b5aa56ecbf
39.492857
178
0.663197
false
false
false
false
wang-chuanhui/CHSDK
refs/heads/master
Source/Transformation/OptionalTransformational.swift
mit
1
// // OptionalTransformational.swift // CHSDK // // Created by 王传辉 on 2017/8/4. // Copyright © 2017年 王传辉. All rights reserved. // import Foundation extension Optional: OptionalTransformational { public static func _transform(from value: Any) -> Optional { if let wrapped = value as? Wrapped { return Optional.some(wrapped) }else if let wrapped = (Wrapped.self as? Transformational.Type)?.___transform(from: value) as? Wrapped { return Optional.some(wrapped) } return Optional.none } func getWrappedValue() -> Any? { return self.map( { (wrapped) -> Any in return wrapped as Any }) } public func _toJSONValue() -> Any? { if let value = getWrappedValue() { if let transform = value as? Transformational { return transform } } return nil } } extension ImplicitlyUnwrappedOptional: OptionalTransformational { public static func _transform(from value: Any) -> ImplicitlyUnwrappedOptional { if let wrapped = value as? Wrapped { return ImplicitlyUnwrappedOptional.some(wrapped) }else if let wrapped = (Wrapped.self as? Transformational.Type)?.___transform(from: value) as? Wrapped { return ImplicitlyUnwrappedOptional.some(wrapped) } return ImplicitlyUnwrappedOptional.none } func getWrappedValue() -> Any? { return self == nil ? nil : self! } public func _toJSONValue() -> Any? { if let value = getWrappedValue() { if let transform = value as? Transformational { return transform } } return nil } }
05957091cabc8cf0fab65b0549861219
25.969231
112
0.592128
false
false
false
false
Kiandr/CrackingCodingInterview
refs/heads/master
Swift/Ch 8. Recursion and Dynamic Programming/Ch 8. Recursion and Dynamic Programming.playground/Pages/8.1 Triple Step.xcplaygroundpage/Contents.swift
mit
1
import Foundation /*: 8.1 A child is running up a staircase with n steps and can hop either 1, 2, or 3 steps at a time. Count the number of ways the child can run up the stairs. */ func countWays(steps: Int) -> Int { let results = Array<Int?>(repeating: nil, count: steps + 1) let result = countWays(steps: steps, results: results) return result } private func countWays(steps: Int, results: [Int?]) -> Int { guard steps > 0 else { return steps < 0 ? 0 : 1 } if let result = results[steps] { return result } var results = results let n1 = countWays(steps: steps - 1, results: results) let n2 = countWays(steps: steps - 2, results: results) let n3 = countWays(steps: steps - 3, results: results) results[steps] = n1 + n2 + n3 return results[steps]! } assert(countWays(steps: 5) == 13)
2935aa78e3f858edf98e3498b33c5e24
27.5
99
0.642105
false
false
false
false
mthistle/HockeyTweetSwift
refs/heads/master
HockeyTweetSwift/Models/Teams.swift
mit
1
// // Teams.swift // HockeyTweetSwift // // Created by Mark Thistle on 2014-07-13. // Copyright (c) 2014 Test. All rights reserved. // import Foundation class Teams: NSObject { var teamTLA = [ "NJD", "NYI", "NYR", "PHI", "PIT", "BOS", "BUF", "MTL", "OTT", "TOR", "ATL", "CAR", "FLA", "TBL", "WSH", "CHI", "CBJ", "DET", "NSH", "STL", "CGY", "COL", "EDM", "MIN", "VAN", "ANA", "DAL", "LAK", "PHX", "SJS"] var teamNames = [ "New Jersey Devils", "New York Islanders", "New York Rangers", "Philadelphia Flyers", "Pittsburgh Penguins", "Boston Bruins", "Buffalo Sabres", "Montreal Canadiens", "Ottawa Senators", "Toronto Maple Leafs", "Atlanta Thrashers", "Carolina Hurricanes", "Florida Panthers", "Tampa Bay Lightning", "Washington Capitals", "Chicago Blackhawks", "Columbus Blue Jackets", "Detroit Red Wings", "Nashville Predators", "St Louis Blues", "Calgary Flames", "Colorado Avalanche", "Edmonton Oilers", "Minnesota Wild", "Vancouver Canucks", "Anaheim Ducks", "Dallas Stars", "Los Angeles Kings", "Phoenix Coyotes", "San Jose Sharks"] // Initialize an empty dictionary so we have a starting point from which to // add values in the init call. var rosters = [String: Array<String>]() override init() { teamNames = sorted(teamNames, { s1, s2 in return s1 < s2 }) teamTLA = sorted(teamTLA, { s1, s2 in return s1 < s2 }) // TODO: Ok, need to convert from NS to Swift here // var rostersLoaded = true // if let path: String = NSBundle.mainBundle().pathForResource("players", ofType: "plist") { // let teams = NSDictionary(contentsOfFile: path) // //rosters = rostersFromTeams(teams["players"] as NSDictionary) // } else { // rostersLoaded = false // } // if !rostersLoaded { for team in teamTLA { rosters[team] = ["--"] } //} super.init() } func playersOnTeam(team: String) -> Array<String>! { //if let players: NSDictionary = rosters["players"] as? NSDictionary { // let ns_team: NSString = NSString(string: team) //for teamPlayers in players.objectForKey(ns_team) { //} //return nil //} return nil } func rostersFromTeams(teams: NSDictionary) -> Dictionary<String, Array<String>>! { var tmprosters: Dictionary<String, Array<String>> for team in teamTLA { } return nil } }
5bc8b8da1970ec0387c1f386ca8c1b0b
24.771186
107
0.488816
false
false
false
false
WebAPIKit/WebAPIKit
refs/heads/master
Sources/WebAPIKit/Stub/StubRequestMatcher.swift
mit
1
/** * WebAPIKit * * Copyright (c) 2017 Evan Liu. Licensed under the MIT license, as follows: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import Foundation public struct StubRequestMatcher { public let request: URLRequest public let provider: WebAPIProvider? } extension StubHTTPClient { @discardableResult public func stub(match: @escaping (StubRequestMatcher) -> Bool) -> StubResponder { return stub(responder: StubResponder { match(StubRequestMatcher(request: $0, provider: self.provider)) }) } } // MARK: Method extension StubRequestMatcher { public func methodEqualTo(_ method: HTTPMethod) -> Bool { return request.httpMethod == method.rawValue } } // MARK: Path extension StubRequestMatcher { public var requestPath: String? { guard let path = request.url?.path else { return nil } guard let basePath = provider?.baseURL.path, !basePath.isEmpty, basePath != "/" else { return path } return path.substring(from: basePath.endIndex) } public func pathEqualTo(_ path: String) -> Bool { return requestPath == path } public func pathHasPrefix(_ path: String) -> Bool { return requestPath?.hasPrefix(path) == true } public func pathHasSuffix(_ path: String) -> Bool { return requestPath?.hasSuffix(path) == true } public func pathContains(_ path: String) -> Bool { return requestPath?.contains(path) == true } } extension StubHTTPClient { public enum PathMatchMode { case equalTo, prefix, suffix, contains } @discardableResult public func stub(path: String, mode: PathMatchMode = .equalTo, method: HTTPMethod? = nil) -> StubResponder { return stub { if let method = method, !$0.methodEqualTo(method) { return false } switch mode { case .equalTo: return $0.pathEqualTo(path) case .prefix: return $0.pathHasPrefix(path) case .suffix: return $0.pathHasSuffix(path) case .contains: return $0.pathContains(path) } } } }
ee8af091730ca34c4e5014813553d66c
29.613208
112
0.663174
false
false
false
false
vonholst/deeplearning_example_kog
refs/heads/master
HotdogOrNohotdog/HotdogOrNohotdog/ViewController.swift
mit
1
// // ViewController.swift // HotdogOrNohotdog // // Created by Michael Jasinski on 2017-10-25. // Copyright © 2017 HiQ. All rights reserved. // import UIKit import CoreML import Vision import AVFoundation class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { // Connect UI to code @IBOutlet weak var classificationText: UILabel! @IBOutlet weak var cameraView: UIView! private var requests = [VNRequest]() private lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession) private lazy var captureSession: AVCaptureSession = { let session = AVCaptureSession() session.sessionPreset = AVCaptureSession.Preset.photo guard let backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back), let input = try? AVCaptureDeviceInput(device: backCamera) else { return session } session.addInput(input) return session }() var player: AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() self.cameraView?.layer.addSublayer(self.cameraLayer) let videoOutput = AVCaptureVideoDataOutput() videoOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "MyQueue")) self.captureSession.addOutput(videoOutput) self.captureSession.startRunning() setupVision() self.classificationText.text = "" cameraView.bringSubview(toFront: self.classificationText) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.cameraLayer.frame = self.cameraView?.bounds ?? .zero } func setupVision() { guard let visionModel = try? VNCoreMLModel(for: hotdog_classifier().model) else { fatalError("Can't load VisionML model") } let classificationRequest = VNCoreMLRequest(model: visionModel, completionHandler: handleClassifications) classificationRequest.imageCropAndScaleOption = VNImageCropAndScaleOption.centerCrop self.requests = [classificationRequest] } func handleClassifications(request: VNRequest, error: Error?) { guard let observations = request.results as? [VNClassificationObservation] else { print("no results: \(error!)"); return } guard let best = observations.first else { fatalError("can't get best result") } print("\(best.identifier), \(best.confidence)") // latch to hotdog / no-hotdog if best.confidence > 0.9 && best.identifier == "hotdog" { DispatchQueue.main.async { if self.classificationText.text == "" { self.playSound() } self.classificationText.text = "🌭" } } else if best.confidence > 0.6 && best.identifier == "non_hotdog" { DispatchQueue.main.async { self.classificationText.text = "" } } } func playSound() { guard let url = Bundle.main.url(forResource: "hotdog", withExtension: "wav") else { return } do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) try AVAudioSession.sharedInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue) guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } } func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) { guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return } var requestOptions:[VNImageOption : Any] = [:] if let cameraIntrinsicData = CMGetAttachment(sampleBuffer, kCMSampleBufferAttachmentKey_CameraIntrinsicMatrix, nil) { requestOptions = [.cameraIntrinsics:cameraIntrinsicData] } let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: CGImagePropertyOrientation(rawValue: 1)!, options: requestOptions) do { try imageRequestHandler.perform(self.requests) } catch { print(error) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
bcab1642484bd3a4a00d6dd71b399ae8
37.720339
163
0.650252
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
enums/XGPokeSpots.swift
gpl-2.0
1
// // XGPokeSpots.swift // XG Tool // // Created by StarsMmd on 08/06/2015. // Copyright (c) 2015 StarsMmd. All rights reserved. // import Foundation enum XGPokeSpots : Int, Codable, CaseIterable { case rock = 0x00 case oasis = 0x01 case cave = 0x02 case all = 0x03 var string : String { get { switch self { case .rock : return "Rock" case .oasis : return "Oasis" case .cave : return "Cave" case .all : return "All" } } } var numberOfEntries : Int { let rel = XGFiles.common_rel.data! return rel.get4BytesAtOffset(self.commonRelEntriesIndex.startOffset) } var entries: [XGPokeSpotPokemon] { return (0 ..< numberOfEntries).map { (index) -> XGPokeSpotPokemon in return XGPokeSpotPokemon(index: index, pokespot: self) } } func setEntries(entries: Int) { if let rel = XGFiles.common_rel.data { rel.replace4BytesAtOffset(self.commonRelEntriesIndex.startOffset, withBytes: entries) rel.save() } } var commonRelIndex : CommonIndexes { get { switch self { case .rock: return .PokespotRock case .oasis: return .PokespotOasis case .cave: return .PokespotCave case .all: return .PokespotAll } } } var commonRelEntriesIndex : CommonIndexes { get { switch self { case .rock: return .PokespotRockEntries case .oasis: return .PokespotOasisEntries case .cave: return .PokespotCaveEntries case .all: return .PokespotAllEntries } } } func relocatePokespotData(toOffset offset: Int) { common.replacePointer(index: self.commonRelIndex.rawValue, newAbsoluteOffset: offset) } } extension XGPokeSpots: XGEnumerable { var enumerableName: String { return string } var enumerableValue: String? { return rawValue.string } static var className: String { return "Pokespots" } static var allValues: [XGPokeSpots] { return allCases } } extension XGPokeSpots: XGDocumentable { var documentableName: String { return string } static var DocumentableKeys: [String] { return ["Encounters"] } func documentableValue(for key: String) -> String { switch key { case "Encounters": var text = "" for i in 0 ..< self.numberOfEntries { let encounter = XGPokeSpotPokemon(index: i, pokespot: self) text += "\n" + encounter.pokemon.name.string.spaceToLength(20) text += " Lv. " + encounter.minLevel.string + " - " + encounter.maxLevel.string } return text default: return "" } } }
adc033b2a9ae51d7e79f03470166fb23
16.248276
88
0.668533
false
false
false
false
codingforentrepreneurs/Django-to-iOS
refs/heads/master
Source/ios/srvup/CommentTableViewController.swift
apache-2.0
1
// // CommentTableViewController.swift // srvup // // Created by Justin Mitchel on 6/23/15. // Copyright (c) 2015 Coding for Entrepreneurs. All rights reserved. // import UIKit class CommentTableViewController: UITableViewController, UITextViewDelegate { var lecture: Lecture? var webView = UIWebView() var message = UITextView() let textArea = UITextView() let textAreaPlaceholder = "Your comment here..." let aRefeshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() let btn = UINavButton(title: "Back", direction: .Right, parentView: self.view) btn.addTarget(self, action: "popView:", forControlEvents: UIControlEvents.TouchUpInside) btn.frame.origin.y = btn.frame.origin.y - 10 self.view.addSubview(btn) let newCommentBtn = UINavButton(title: "New", direction: .Left, parentView: self.view) newCommentBtn.addTarget(self, action: "scrollToFooter:", forControlEvents: UIControlEvents.TouchUpInside) newCommentBtn.frame.origin.y = btn.frame.origin.y self.view.addSubview(newCommentBtn) let headerView = UIView() headerView.frame = CGRectMake(0, 0, self.view.frame.width, 395) headerView.backgroundColor = .whiteColor() let headerTextView = UITextView() headerTextView.frame = CGRectMake(0, btn.frame.origin.y, self.view.frame.width, btn.frame.height) headerTextView.text = "\(self.lecture!.title)" headerTextView.textColor = .blackColor() headerTextView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) headerTextView.textAlignment = .Center headerTextView.font = UIFont.boldSystemFontOfSize(26) headerTextView.editable = false headerTextView.scrollEnabled = false headerView.addSubview(headerTextView) self.tableView.tableHeaderView = headerView self.tableView.tableFooterView = self.addContactForm() self.aRefeshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.aRefeshControl.addTarget(self, action: "updateItems:", forControlEvents: UIControlEvents.ValueChanged) self.view.addSubview(self.aRefeshControl) let webViewWidth = self.view.frame.width - 20 let webViewVideoHeight = 275 let embedCode = lecture!.embedCode let cssCode = "<style>body{padding:0px;margin:0px;}iframe{width:\(webViewWidth);height:\(webViewVideoHeight);}</style>" let htmlCode = "<html>\(cssCode)<body>\(embedCode)</body></html>" self.webView.frame = CGRectMake(10, 75, webViewWidth, 275) let url = NSURL(string: "http://codingforentrepreneurs.com") self.webView.loadHTMLString(htmlCode, baseURL: url) self.webView.scrollView.bounces = false self.webView.backgroundColor = .whiteColor() let commentLabel = UILabel() commentLabel.frame = CGRectMake(self.webView.frame.origin.x, self.webView.frame.origin.y + self.webView.frame.height + 10, self.webView.frame.width, 50) commentLabel.text = "Comments" commentLabel.font = UIFont.boldSystemFontOfSize(16) headerView.addSubview(commentLabel) headerView.addSubview(self.webView) } func updateItems(sender:AnyObject) { self.lecture?.updateLectureComments({ (success) -> Void in if success { println("grabbed comment successfully") self.aRefeshControl.endRefreshing() self.tableView.reloadData() } else { Notification().notify("Error updated data", delay: 2.0, inSpeed: 0.7, outSpeed: 2.5) self.aRefeshControl.endRefreshing() } }) } func addContactForm() -> UIView { let commentView = UITextView() commentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) commentView.backgroundColor = .blackColor() commentView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height) commentView.text = "Add New Comment" commentView.textColor = .blackColor() commentView.backgroundColor = .redColor() commentView.textAlignment = .Center commentView.font = UIFont.boldSystemFontOfSize(24) let topOffset = CGFloat(25) let xOffset = CGFloat(10) let spacingE = CGFloat(10) // response message self.message.editable = false self.message.frame = CGRectMake(xOffset, topOffset, commentView.frame.width - (2 * xOffset), 30) self.message.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0) self.message.textColor = .redColor() // title let label = UILabel() label.text = "Add new Comment" label.frame = CGRectMake(xOffset, self.message.frame.origin.y + self.message.frame.height + spacingE, self.message.frame.width, 30) label.textColor = .whiteColor() // text area field self.textArea.editable = true self.textArea.text = self.textAreaPlaceholder self.textArea.delegate = self self.textArea.frame = CGRectMake(xOffset, label.frame.origin.y + label.frame.height + spacingE, label.frame.width, 250) // submit button let submitBtn = UIButton() submitBtn.frame = CGRectMake(xOffset, self.textArea.frame.origin.y + self.textArea.frame.height + spacingE, self.textArea.frame.width, 30) submitBtn.setTitle("Submit", forState: UIControlState.Normal) submitBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside) submitBtn.tag = 1 // cancel button let cancelBtn = UIButton() cancelBtn.frame = CGRectMake(xOffset, submitBtn.frame.origin.y + submitBtn.frame.height + spacingE, submitBtn.frame.width, 30) cancelBtn.setTitle("Cancel", forState: UIControlState.Normal) cancelBtn.addTarget(self, action: "commentFormAction:", forControlEvents: UIControlEvents.TouchUpInside) cancelBtn.tag = 2 commentView.addSubview(label) commentView.addSubview(self.message) commentView.addSubview(self.textArea) commentView.addSubview(submitBtn) commentView.addSubview(cancelBtn) return commentView } func textViewDidBeginEditing(textView: UITextView) { self.message.text = "" if textView.text == self.textAreaPlaceholder { textView.text = "" } } func commentFormAction(sender: AnyObject) { let tag = sender.tag switch tag { case 1: if self.textArea.text != "" && self.textArea.text != self.textAreaPlaceholder { self.textArea.endEditing(true) self.lecture!.addComment(self.textArea.text, completion: addCommentCompletionHandler) self.textArea.text = self.textAreaPlaceholder } else { self.message.text = "A comment is required." } default: // println("cancelled") // self.commentView.removeFromSuperview() self.backToTop(self) } } func addCommentCompletionHandler(success:Bool) -> Void { if !success { self.scrollToFooter(self) Notification().notify("Failed to add", delay: 2.5, inSpeed: 0.7, outSpeed: 1.2) } else { Notification().notify("Message Added", delay: 1.5, inSpeed: 0.5, outSpeed: 1.0) self.backToTop(self) } } func backToTop(sender:AnyObject) { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Bottom, animated: true) } func scrollToFooter(sender:AnyObject) { let lastRowItem = self.lecture!.commentSet.count - 1 let section = 0 self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: lastRowItem, inSection: section), atScrollPosition: UITableViewScrollPosition.Top, animated: true) } func popView(sender:AnyObject) { self.navigationController?.popViewControllerAnimated(true) // self.dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.lecture!.commentSet.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... let text = self.lecture!.commentSet[indexPath.row]["text"].string! let user = self.lecture!.commentSet[indexPath.row]["user"].string let children = self.lecture!.commentSet[indexPath.row]["children"].array var responses = 0 if children != nil { responses = children!.count } var newText = "" if user != nil { newText = "\(text) \n\n via \(user!) - \(responses) Responses" } else { newText = "\(text)" } cell.textLabel?.text = newText cell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping cell.textLabel?.numberOfLines = 0 return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let text = self.lecture!.commentSet[indexPath.row]["text"].string! let user = self.lecture!.commentSet[indexPath.row]["user"].string let children = self.lecture!.commentSet[indexPath.row]["children"].array var responses = 0 if children != nil { responses = children!.count } var newText = "" if user != nil { newText = "\(text) \n\n via \(user!) - \(responses) Responses" } else { newText = "\(text)" } let cellFont = UIFont.boldSystemFontOfSize(14) let attrString = NSAttributedString(string: newText, attributes: [NSFontAttributeName : cellFont]) let constraintSize = CGSizeMake(self.tableView.bounds.size.width, CGFloat(MAXFLOAT)) let rect = attrString.boundingRectWithSize(constraintSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil) return rect.size.height + 50 } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
b24f21c6d7410f37f93d10f938c76c85
38.807927
162
0.642797
false
false
false
false
adamdahan/Thnx
refs/heads/master
Thnx/Thnx/Thnx.swift
bsd-3-clause
1
/* * Copyright (C) 2016, Adam Dahan. <http://thnx.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation /** :name: Strings - Strings used in the framework */ public struct Strings { static let license = "LICENSE" static let regex = "(https:\\/\\/github.com\\/)(\\w)*\\/(\\w)*\\/(\\w)*\\/(\\w)*\\/(LICENSE)*(.md)?" static let githubURL = "https://github.com" static let githubRawURL = "https://raw.githubusercontent.com" } /** :name: Strings - Regular expression matching - used for grabbing URLs from HTML. - Parameter regex: Regular expression as a string - Parameter text: Text to match against the regular expression */ private func matches(for regex: String, in text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex) let nsString = text as NSString let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error { print("invalid regex: \(error.localizedDescription)") return [] } } /** Main object */ public class Thnx { /** :name: licenses - Strings used in the framework - Parameter urls: Urls to github repositories you want to get licenses from as an array of strings */ public func licenses(urls: [String]) -> Dictionary <String, String> { var d = Dictionary <String, String>() for url in urls { do { let urlPath = URL(string: url) let html = try String(contentsOf: urlPath!) let results = matches(for: Strings.regex, in: html) for r in results { if r.contains(Strings.license) { let comps = r.components(separatedBy: "/") let replaced = url.replacingOccurrences(of: Strings.githubURL, with: Strings.githubRawURL) let url = URL(string: "\(replaced)/\(comps[comps.count - 2])/\(comps.last!)")! do { let text = try String(contentsOf: url, encoding: .ascii) d[url.absoluteString.components(separatedBy: "/")[4]] = text } catch _ {} } } } catch _ {} } return d } }
8cf1810a226fc96308d8bc6da50bf3d2
40.580645
114
0.644169
false
false
false
false
lexicalparadox/Chirppy
refs/heads/master
Chirppy/Tweet.swift
apache-2.0
1
// // Tweet.swift // Chirppy // // Created by Alexander Doan on 9/26/17. // Copyright © 2017 Alexander Doan. All rights reserved. // import UIKit import SwiftDate class Tweet: NSObject { let dateFormatter = DateFormatter() let user: User? //user var retweetedByUser: User? // To signify the user who retweeted this tweet var id: Int64? // id var text: String? // text var createdAt: String? // created_at var createdAtDate: Date? // internal use - still setting up var favoritesCount: Int? // favorite_count var retweetCount: Int? // retweet_count var favorited: Bool? // favorited var retweeted: Bool? // retweeted -- to signify that the logged in user retweeted this tweet var wasRetweeted: Bool // to signify whether this tweet is a retweet of another tweet init(_ dict : NSDictionary) { let retweetDict = dict["retweeted_status"] as? NSDictionary if let retweetDict = retweetDict { self.wasRetweeted = true let retweetedByUser = dict["user"] as? NSDictionary if let retweetedByUser = retweetedByUser { self.retweetedByUser = User(retweetedByUser) } let userDict = retweetDict["user"] as? NSDictionary self.user = User(userDict ?? NSDictionary()) self.id = retweetDict["id"] as! Int64 self.text = retweetDict["text"] as! String self.createdAt = retweetDict["created_at"] as! String if let createdAt = self.createdAt { let date = try! DateInRegion(string: createdAt, format: .custom("EE MMM dd HH:mm:ss Z yyyy"), fromRegion: Region.Local()) self.createdAtDate = date?.absoluteDate // DateFormatter.dateFormat(fromTemplate: "EE MMM dd HH:mm:ss Z yyyy", options: 0, locale: Locale.current) // self.createdAtDate = dateFormatter.date(from: createdAt) } self.retweetCount = retweetDict["retweet_count"] as! Int self.favoritesCount = retweetDict["favorite_count"] as! Int self.favorited = retweetDict["favorited"] as! Bool self.retweeted = retweetDict["retweeted"] as! Bool } else { let userDict = dict["user"] as? NSDictionary self.user = User(userDict ?? NSDictionary()) self.id = dict["id"] as! Int64 self.text = dict["text"] as! String self.createdAt = dict["created_at"] as! String if let createdAt = self.createdAt { let date = try! DateInRegion(string: createdAt, format: .custom("EE MMM dd HH:mm:ss Z yyyy"), fromRegion: Region.Local()) self.createdAtDate = date?.absoluteDate // DateFormatter.dateFormat(fromTemplate: "EE MMM dd HH:mm:ss Z yyyy", options: 0, locale: Locale.current) // self.createdAtDate = dateFormatter.date(from: createdAt) } self.retweetCount = dict["retweet_count"] as! Int self.favoritesCount = dict["favorite_count"] as! Int self.favorited = dict["favorited"] as! Bool self.retweeted = dict["retweeted"] as! Bool self.wasRetweeted = false } } static func tweetsWithArray(_ list: [NSDictionary]) -> [Tweet] { var tweets = [Tweet]() for dictionary in list { let tweet = Tweet(dictionary) tweets.append(tweet) } return tweets } }
fa00ce73c88fe7dd53e425bc2bf8bcb4
40.298851
137
0.589758
false
false
false
false
Danappelxx/SwiftMongoDB
refs/heads/linux
Sources/Database.swift
mit
1
// // Database.swift // SwiftMongoDB // // Created by Dan Appel on 11/23/15. // Copyright © 2015 Dan Appel. All rights reserved. // import CMongoC import BinaryJSON public final class Database { let pointer: _mongoc_database /// Databases are automatically created on the MongoDB server upon insertion of the first document into a collection. There is no need to create a database manually. public init(client: Client, name: String) { self.pointer = mongoc_client_get_database(client.pointer, name) } deinit { mongoc_database_destroy(pointer) } public var name: String { let nameRaw = mongoc_database_get_name(pointer) return String(cString:nameRaw) } public var collectionNames: [String]? { var error = bson_error_t() var buffer = mongoc_database_get_collection_names(self.pointer, &error) if error.error.isError { return nil } var names = [String]() while buffer.pointee != nil { let name = String(cString:buffer.pointee) names.append(name) buffer = buffer.successor() } return names } public func removeUser(username: String) throws -> Bool { var error = bson_error_t() let successful = mongoc_database_remove_user(pointer, username, &error) try error.throwIfError() return successful } public func removeAllUsers() throws -> Bool { var error = bson_error_t() let successful = mongoc_database_remove_all_users(pointer, &error) try error.throwIfError() return successful } // public func addUser(username username: String, password: String, roles: [String], customData: BSON.Document) throws -> Bool { // // guard let rolesJSON = roles.toJSON()?.toString() else { throw MongoError.InvalidData } // // var error = bson_error_t() // // var rolesRaw = try MongoBSON(json: rolesJSON).bson // var customDataRaw = try MongoBSON(data: customData).bson // // let successful = mongoc_database_add_user(pointer, username, password, &rolesRaw, &customDataRaw, &error) // // try error.throwIfError() // // return successful // } // public func command(command: BSON.Document, flags: QueryFlags = .None, skip: Int = 0, limit: Int = 0, batchSize: Int = 0, fields: [String] = []) throws -> Cursor { // // guard let fieldsJSON = fields.toJSON()?.toString() else { throw MongoError.InvalidData } // // var commandRaw = try MongoBSON(data: command).bson // var fieldsRaw = try MongoBSON(json: fieldsJSON).bson // // let cursorRaw = mongoc_database_command(pointer, flags.rawFlag, skip.UInt32Value, limit.UInt32Value, batchSize.UInt32Value, &commandRaw, &fieldsRaw, nil) // // let cursor = Cursor(cursor: cursorRaw) // // return cursor // } public func drop() throws -> Bool { var error = bson_error_t() let successful = mongoc_database_drop(pointer, &error) try error.throwIfError() return successful } public func hasCollection(name name: String) throws -> Bool { var error = bson_error_t() let successful = mongoc_database_has_collection(pointer, name, &error) try error.throwIfError() return successful } public func createCollection(name name: String, options: BSON.Document) throws -> Collection { let options = try BSON.AutoReleasingCarrier(document: options) var error = bson_error_t() mongoc_database_create_collection(pointer, name, options.pointer, &error) try error.throwIfError() let collection = Collection(database: self, name: name) return collection } public func findCollections(filter filter: BSON.Document) throws -> Cursor { let filter = try BSON.AutoReleasingCarrier(document: filter) var error = bson_error_t() let cursorPointer = mongoc_database_find_collections(pointer, filter.pointer, &error) try error.throwIfError() let cursor = Cursor(pointer: cursorPointer) return cursor } public func basicCommand(command command: BSON.Document) throws -> BSON.Document { let command = try BSON.AutoReleasingCarrier(document: command) var reply = bson_t() var error = bson_error_t() mongoc_database_command_simple(self.pointer, command.pointer, nil, &reply, &error) try error.throwIfError() guard let res = BSON.documentFromUnsafePointer(&reply) else { throw MongoError.CorruptDocument } return res } }
8a9fbba36d006ee229b57898008e8109
27.143713
169
0.639149
false
false
false
false
honghaoz/CrackingTheCodingInterview
refs/heads/master
Swift/LeetCode/Array/345_Reverse Vowels of a String.swift
mit
1
// // 345. Reverse Vowels of a String.swift // https://leetcode.com/problems/reverse-vowels-of-a-string/ // // Created by Honghao Zhang on 2016-11-02. // Copyright © 2016 Honghaoz. All rights reserved. // //Write a function that takes a string as input and reverse only the vowels of a string. // //Example 1: // //Input: "hello" //Output: "holle" //Example 2: // //Input: "leetcode" //Output: "leotcede" //Note: //The vowels does not include the letter "y". import Foundation class Num345_ReverseVowels: Solution { func reverseVowels(_ s: String) -> String { var s = [Character](s) var vowelsIndices: [Int] = [] for (index, char) in s.enumerated() { if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "A" || char == "E" || char == "I" || char == "O" || char == "U" { vowelsIndices.append(index) } } for i in 0..<vowelsIndices.count / 2 { let left = vowelsIndices[i] let right = vowelsIndices[vowelsIndices.count - 1 - i] (s[left], s[right]) = (s[right], s[left]) } return String(s) } func test() { } }
668f1092036e6f034169ecf610d0e3ef
22.583333
88
0.581272
false
false
false
false
PJayRushton/stats
refs/heads/master
Stats/ShadowableCell.swift
mit
1
// // /||\ // / || \ // / )( \ // /__/ \__\ // import Foundation import UIKit protocol ShadowableCell: class {} extension ShadowableCell where Self: UICollectionViewCell { func addShadowToTop() { let path = UIBezierPath(rect: CGRect(x: 0, y: 0, width: bounds.width, height: 1)).cgPath addShadow(with: path) } func addShadowToBottom() { let path = UIBezierPath(rect: CGRect(x: 0, y: bounds.height, width: bounds.width, height: 1)).cgPath addShadow(with: path) } func removeShadow() { layer.shadowPath = UIBezierPath(rect: .zero).cgPath } } private extension ShadowableCell where Self: UICollectionViewCell { func addShadow(with path: CGPath) { layer.masksToBounds = false layer.shadowOpacity = 0.25 layer.shadowRadius = 2.0 layer.shadowOffset = .zero layer.shadowColor = UIColor.black.cgColor layer.shadowPath = path clipsToBounds = false } }
36aa427dc8824527e0cf1a86a88a2143
21.644444
108
0.60157
false
false
false
false
jegumhon/URWeatherView
refs/heads/master
URWeatherView/Effect/UREffectLightningLineNode.swift
mit
1
// // UREffectLightningLineNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 5. 26.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit /// draw the lightning line class UREffectLightningLineNode: SKNode { static let textureLightningHalfCircle: SKTexture = SKTexture(image: UIImage(named: "lightning_half_circle", in: Bundle(for: UREffectLigthningNode.self), compatibleWith: nil)!) static let textureLightningSegment: SKTexture = SKTexture(image: UIImage(named: "lightning_segment", in: Bundle(for: UREffectLigthningNode.self), compatibleWith: nil)!) var startPoint: CGPoint = .zero var endPoint: CGPoint = .zero var lineThickness = 1.3 init(start startPoint: CGPoint, end endPoint: CGPoint, thickness: Double = 1.3) { super.init() self.startPoint = startPoint self.endPoint = endPoint self.lineThickness = thickness } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func draw() { let imageThickness = 2.0 let ratioThickness = CGFloat(self.lineThickness / imageThickness) let startPointInNode = self.convert(self.startPoint, from: self.parent!) let endPointInNode = self.convert(self.endPoint, from: self.parent!) let angle = atan2(endPointInNode.y - startPointInNode.y, endPointInNode.x - startPointInNode.x) let length = hypot(abs(endPointInNode.x - startPointInNode.x), abs(endPointInNode.y - startPointInNode.y)) let halfCircleFront = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningHalfCircle) halfCircleFront.anchorPoint = CGPoint(x: 1.0, y: 0.5) halfCircleFront.yScale = ratioThickness halfCircleFront.zRotation = angle halfCircleFront.blendMode = .alpha halfCircleFront.position = startPointInNode let halfCircleBack = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningHalfCircle) halfCircleBack.anchorPoint = CGPoint(x: 1.0, y: 0.5) halfCircleBack.xScale = -1.0 halfCircleBack.yScale = ratioThickness halfCircleBack.zRotation = angle halfCircleBack.blendMode = .alpha halfCircleBack.position = endPointInNode let lightningSegment = SKSpriteNode(texture: UREffectLightningLineNode.textureLightningSegment) lightningSegment.xScale = length * 2.0 lightningSegment.yScale = ratioThickness lightningSegment.zRotation = angle lightningSegment.position = CGPoint(x: (startPointInNode.x + endPointInNode.x) * 0.5, y: (startPointInNode.y + endPointInNode.y) * 0.5) self.addChild(halfCircleFront) self.addChild(halfCircleBack) self.addChild(lightningSegment) } }
317aed142f8e7dad3d1d7fcc72ced1da
39.735294
179
0.710108
false
false
false
false
guoc/spi
refs/heads/master
SPi/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // SPi // // Created by GuoChen on 2/12/2014. // Copyright (c) 2014 guoc. All rights reserved. // import UIKit class ViewController: UINavigationController, IASKSettingsDelegate { var appSettingsViewController: IASKAppSettingsViewController! init() { let appSettingsViewController = IASKAppSettingsViewController() super.init(rootViewController: appSettingsViewController) appSettingsViewController.delegate = self appSettingsViewController.showCreditsFooter = false appSettingsViewController.showDoneButton = false appSettingsViewController.title = "SPi 双拼输入法" self.appSettingsViewController = appSettingsViewController } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } func settingsViewControllerDidEnd(_ sender: IASKAppSettingsViewController!) { } func settingsViewController(_ settingsViewController: IASKViewController!, tableView: UITableView!, heightForHeaderForSection section: Int) -> CGFloat { if let key = settingsViewController.settingsReader.key(forSection: section) { if key == "kScreenshotTapKeyboardSettingsIcon" { return UIImage(named: "Screenshot tap keyboard settings icon")!.size.height } } return 0 } func settingsViewController(_ settingsViewController: IASKViewController!, tableView: UITableView!, viewForHeaderForSection section: Int) -> UIView! { if let key = settingsViewController.settingsReader.key(forSection: section) { if key == "kScreenshotTapKeyboardSettingsIcon" { let imageView = UIImageView(image: UIImage(named: "Screenshot tap keyboard settings icon")) imageView.contentMode = .scaleAspectFit return imageView } } return nil } func settingsViewController(_ sender: IASKAppSettingsViewController!, buttonTappedFor specifier: IASKSpecifier!) { if specifier.key() == "kFeedback" { UserVoice.presentInterface(forParentViewController: self) } } func pushToTutorialIfNecessary() { if isCustomKeyboardEnabled() == false { self.appSettingsViewController.tableView(self.appSettingsViewController.tableView, didSelectRowAt: IndexPath(item: 0, section: 0)) } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func isCustomKeyboardEnabled() -> Bool { let bundleID = "name.guoc.SPi.SPiKeyboard" if let keyboards: [String] = UserDefaults.standard.dictionaryRepresentation()["AppleKeyboards"] as? [String] { // Array of all active keyboards for keyboard in keyboards { if keyboard == bundleID { return true } } } return false } }
35ff2b4d42babed1f20a592b4fb0b360
34.774194
156
0.662158
false
false
false
false
darwin/textyourmom
refs/heads/master
TextYourMom/Globals.swift
mit
1
import UIKit var model = Model() var masterController = MasterController() var sharedLogsModel = LogsModel() var mainWindow : UIWindow? var disableScreenSwitching = false var presentViewControllerQueue = dispatch_queue_create("presentViewControllerQueue", DISPATCH_QUEUE_SERIAL) var lastError : String? var mapController : MapController? var lastLatitude : Double = 0 var lastLongitude : Double = 0 var useSignificantLocationChanges = true var supressNextStateChangeReport = true var overrideLocation = 0 // 0 means no override
9b702db5926c34c90398da90544fd832
32.125
107
0.810964
false
false
false
false
twlkyao/Swift
refs/heads/master
var_let/var_let/main.swift
gpl-2.0
1
// // main.swift // var_let // // Created by Jack on 6/8/14. // Copyright (c) 2014 Jack. All rights reserved. // import Foundation let product_constant = "iPhone6" var product_var = "iPad5" var id = 50 println(id) var x1 = 30, x2 = "abc" var value:Int = 33 var 齐士垚 = "Shiyao Qi" println(齐士垚) println("x1=\(x1),齐士垚=\(齐士垚)")
5572473a04e97c4d5e551e9d1143029a
11.923077
49
0.626866
false
false
false
false
dim0v/DOCheckboxControl
refs/heads/master
Example/DOCheckboxControl/MainTableViewController.swift
mit
1
// // MainTableViewController.swift // DOCheckboxControl // // Created by Dmytro Ovcharenko on 22.07.15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import UIKit import DOCheckboxControl class MainTableViewController: UITableViewController { @IBOutlet weak var programmaticalySwitchableCheckbox: CheckboxControl! @IBOutlet weak var switchInstantlyBtn: UIButton! @IBOutlet weak var switchAnimatedBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() programmaticalySwitchableCheckbox.isEnabled = false switchInstantlyBtn.titleLabel?.numberOfLines = 0; switchAnimatedBtn.titleLabel?.numberOfLines = 0; switchInstantlyBtn.titleLabel?.textAlignment = NSTextAlignment.center; switchAnimatedBtn.titleLabel?.textAlignment = NSTextAlignment.center; } @IBAction func switchAnimated() { programmaticalySwitchableCheckbox.setSelected(!programmaticalySwitchableCheckbox.isSelected, animated: true) } @IBAction func switchNotAnimated() { programmaticalySwitchableCheckbox.setSelected(!programmaticalySwitchableCheckbox.isSelected, animated: false) } }
17be1a6be901878d13ac44251232ab37
33.114286
117
0.746231
false
false
false
false
aryehToDog/DYZB
refs/heads/master
DYZB/DYZB/Class/Home/Controller/WKAmuseViewController.swift
apache-2.0
1
// // WKAmuseViewController.swift // DYZB // // Created by 阿拉斯加的狗 on 2017/9/3. // Copyright © 2017年 阿拉斯加的🐶. All rights reserved. // import UIKit fileprivate let amuseMenuViewH: CGFloat = 200 class WKAmuseViewController: WKBaseAnchorViewController { let amuseViewModel: WKAmuseViewModel = WKAmuseViewModel() //懒加载 fileprivate lazy var amuseMenuView: WKAmuseMenuView = { let amuseMenuView = WKAmuseMenuView.amuseMenuView() amuseMenuView.frame = CGRect(x: 0, y: -amuseMenuViewH, width: WKWidth, height: amuseMenuViewH) return amuseMenuView }() } extension WKAmuseViewController { override func setupUI() { super.setupUI() collectionView.addSubview(amuseMenuView) collectionView.contentInset = UIEdgeInsets(top: amuseMenuViewH, left: 0, bottom: 0, right: 0) } } extension WKAmuseViewController { override func reloadData() { baseViewModel = amuseViewModel amuseViewModel.loadAmuseData { var tempGroupModel = self.amuseViewModel.modelArray tempGroupModel.remove(at: 0) self.amuseMenuView.anchorGroupModel = tempGroupModel self.collectionView.reloadData() self.finishedCallBackEndAnimatin() } } }
634977c2d4a3517ca7a75b3f654d7c61
21.428571
102
0.61925
false
false
false
false
Aaron-zheng/yugioh
refs/heads/master
yugioh/CardViewWithStarController.swift
agpl-3.0
1
// // CardViewWithStarController.swift // yugioh // // Created by Aaron on 30/1/2017. // Copyright © 2017 sightcorner. All rights reserved. // import Foundation import UIKit import Kingfisher class CardViewWithStarController: CardViewBaseController { @IBOutlet weak var iTableView: UITableView! private var cardService = CardService() override func viewDidLoad() { self.tableView = iTableView self.setupTableView() self.afterDeselect = starAfterDeselect } func starAfterDeselect() { self.tableView.reloadData() } public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let ids = cardService.list() self.cardEntitys = [] for index in 0..<ids.count { cardEntitys.append(getCardEntity(id: ids[index])) } return self.cardEntitys.count } }
f6422cd1afd582a062bdd471dd92389a
20.319149
105
0.607784
false
false
false
false
blstream/mEatUp
refs/heads/master
mEatUp/mEatUp/InvitationViewController.swift
apache-2.0
1
// // InvitationViewController.swift // mEatUp // // Created by Krzysztof Przybysz on 27/04/16. // Copyright © 2016 BLStream. All rights reserved. // import UIKit import CloudKit class InvitationViewController: UIViewController { @IBOutlet weak var tableView: UITableView! let cloudKitHelper = CloudKitHelper() var users = [User]() var currentUserList: [User] { get { return loadCurrentUserList(filter) } } var completionHandler: ((User) -> Void)? = nil var filter: ((User) -> Bool)? = nil var checked = [User]() var room: Room? @IBOutlet weak var searchBar: UISearchBar! override func viewDidLoad() { super.viewDidLoad() guard let roomRecordID = self.room?.recordID else { return } cloudKitHelper.loadUserRecords({ [unowned self] users in for user in users { guard let userRecordID = user.recordID else { return } self.cloudKitHelper.checkIfUserInRoom(roomRecordID, userRecordID: userRecordID, completionHandler: { [unowned self] userInRoom in if userInRoom == nil { self.users.append(user) self.tableView.reloadData() } }, errorHandler: nil) } }, errorHandler: nil) } @IBAction func cancelButtonTapped(sender: UIBarButtonItem) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func inviteButtonTapped(sender: UIBarButtonItem) { sender.enabled = false guard let roomRecordID = room?.recordID else { return } for user in checked { guard let userRecordID = user.recordID else { return } completionHandler?(user) let userInRoom = UserInRoom(userRecordID: userRecordID, roomRecordID: roomRecordID, confirmationStatus: .Invited) cloudKitHelper.saveUserInRoomRecord(userInRoom, completionHandler: { self.dismissViewControllerAnimated(true, completion: nil) }, errorHandler: nil) } } func loadCurrentUserList(filter: ((User) -> Bool)?) -> [User] { guard let filter = filter else { return users } return users.filter({filter($0)}) } } extension InvitationViewController: UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentUserList.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UserCell", forIndexPath: indexPath) if let cell = cell as? UserTableViewCell { let user = currentUserList[indexPath.row] let accessoryType: UITableViewCellAccessoryType = checked.contains(user) ? .Checkmark : .None cell.configureWithUser(currentUserList[indexPath.row], accessoryType: accessoryType) return cell } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.cellForRowAtIndexPath(indexPath) let user = currentUserList[indexPath.row] if checked.contains(user) { if let index = checked.indexOf(user) { checked.removeAtIndex(index) cell?.accessoryType = .None } } else { checked.append(user) cell?.accessoryType = .Checkmark } } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { filter = nil } else { filter = { user in guard let name = user.name, let surname = user.surname else { return false } let userName = "\(name) \(surname)" return userName.lowercaseString.containsString(searchText.lowercaseString) } } tableView.reloadData() } func searchBarCancelButtonClicked(searchBar: UISearchBar) { searchBar.text = "" filter = nil searchBar.endEditing(true) tableView.reloadData() } }
fcc7019804485a4216e954733f9010f1
32.328467
145
0.601621
false
false
false
false
yramanchuk/gitTest
refs/heads/master
SmartFeed/DB/DataModels/XML/Atom/SFArticleAtom.swift
mit
1
// // SFArticleAtom.swift // SmartFeed // // Created by Yury Ramanchuk on 3/30/16. // Copyright © 2016 Yury Ramanchuk. All rights reserved. // import UIKit class SFArticleAtom: SFArticle { var link:[NSDictionary] = [NSDictionary]() override var linkURL: String? { get { for val in link { let relVal: String = val.objectForKey("_rel") as! String if relVal == "alternate" { return val.objectForKey("_href") as? String!; } } return "" } set {} } // override func propertyConverters() -> [(String?, ((Any?)->())?, (() -> Any?)? )] { // return [ // ( // "link", { // let arr: Array<NSDictionary> = ($0 as? Array<NSDictionary>)! // for val in arr { // let relVal: String = val.objectForKey("_rel") as! String // if relVal == "alternate" { // self.link = val.objectForKey("_href") as? String; // } // } // }, { // return self.link // } // ) // ] // } }
b9e631212dcd2742f9d2cb6f38f5e5d3
26.891304
88
0.4053
false
false
false
false
jhurray/Beginning-iOS-in-Swift-Workshop
refs/heads/master
Beginning iOS in Swift/PostComposeViewController.swift
mit
1
// // PostComposeViewController.swift // Beginning iOS in Swift // // Created by Jeff Hurray on 10/26/15. // Copyright © 2015 jhurray. All rights reserved. // import Parse import UIKit class PostComposeViewController: UIViewController { // UI Elements let titleTextField = UITextField() let messageTextField = UITextField() // MARK: Apple's API functions // This function is called by the ViewController after the view loads. // This is where you should set up any UI elements override func viewDidLoad() { super.viewDidLoad() // 1) Set title and background color for the view of the viewController // 2) Call all the setup functions you implemented // 3) Add your UI Elements to the view } // MARK: Helper functions private func setupNameTextView() { // 1) Set the delegate for the textfield // 2) Set the placeholder for the text field // 3) Set the backgroundColor for the text field // 4) Set the frame for the text field } private func setupMessageTextField() { // Setup using the same steps as above } private func setupNavigationBar() { // 1) Create cancel and post buttons (UIBarButtonItem) // let composeBarButton = ... // 2) Add buttons to navigationItem // self.navigationItem.leftBarButtonItem = ... } // This is a check to see if our post is valid // We want the body and title to have at least 1 character and for the body to be no longer than 140 chars private func inputForPostIsValid() -> Bool { return self.messageTextField.text?.characters.count > 0 && self.titleTextField.text?.characters.count > 0 && self.messageTextField.text?.characters.count <= 140 } internal func createPost() { // This is a check to see if our post is valid // the 'guard' statement means make sure that this is true, and if its not do something that raises an error or exits the function guard self.inputForPostIsValid() else { print("Invalid input!!!! Please try again") return } // 1) Create new Post PFObject // let post = PFObject(...) // 2) Set fields for object // 'Body' and 'Title' // 3) Make Parse request to save the post and deal with the success or faliure of the save request // ~~> if succeess: dismiss the view controller | if faliure : print the error } internal func cancel() { // 1) Dismiss the view controller when cancel is pressed // self.navigationController?.dismissViewControllerAnimated(...) } // MARK: UITextFieldDelegate functions func textFieldShouldReturn(textField: UITextField) -> Bool { // dismisses keyboard when return is hit textField.resignFirstResponder() return true } }
3bdc593cd9cf6fb10d766e5885a370f6
22.970803
138
0.572168
false
false
false
false
chatwyn/WBStatusBarHUD
refs/heads/master
Demo/Demo/WBStatusBarHUD/WBStatusBarHUD.swift
mit
2
// // WBStatusBarHUD.swift // WBStatusBarHUD // // Created by caowenbo on 16/1/28. // Copyright © 2016年 曹文博. All rights reserved. // import UIKit /// window背景 private var window:UIWindow? /// 渐变色layer private var gradientLayer = CAGradientLayer.init() /// 字迹动画的时间 private let textAnimationTime:NSTimeInterval = 2 /// 字迹图层 private let pathLayer = CAShapeLayer.init() /// 背景颜色 private var windowBgColor = UIColor.blackColor() /// window弹出时间 private let windowTime:NSTimeInterval = 0.25 // 定时器 private var timer:NSTimer? public class WBStatusBarHUD { /** 在statusBar显示一段提示 - parameter message: 提示的文字 - parameter image: 文字前边的小图 */ public class func show(message:String,image:UIImage?=nil) { // 显示window showWindow() // 添加渐变色layer以及动画 addGradientLayer() // 添加文字动画 addPathLayer(message) //添加gradientLayer的遮罩 gradientLayer.mask = pathLayer if let image = image { let imageView = UIImageView.init(image: image) imageView.frame = CGRect(x: CGRectGetMinX(pathLayer.frame) - 5 - imageView.image!.size.width, y: 0, width: imageView.image!.size.width, height: imageView.image!.size.height) imageView.center.y = window!.center.y window?.addSubview(imageView) } } /** 隐藏 */ public class func hide() { timer?.invalidate() timer = nil if window != nil { UIView.animateWithDuration(windowTime, animations: { () -> Void in window?.center.y -= 20 }, completion: { (bool:Bool) -> Void in window = nil pathLayer.removeAllAnimations() gradientLayer.removeAllAnimations() }) } } /** showErrorWithText - parameter msg: default is download fail */ public class func showError(msg:String?=nil) { let image = UIImage.init(named:"WBStatusBarHUD.bundle/error") show((msg ?? "download fail"),image: image) } /** showLoadingWithText - parameter msg: default is loading…… */ public class func showLoading(msg:String?=nil) { show(msg ?? "loading……", image: nil) timer?.invalidate() let activityIndicatorView = UIActivityIndicatorView.init(activityIndicatorStyle: .White) activityIndicatorView.startAnimating() activityIndicatorView.frame = CGRect(x: CGRectGetMinX(pathLayer.frame) - 5 - activityIndicatorView.frame.size.width, y: 0, width: activityIndicatorView.frame.size.width, height: activityIndicatorView.frame.size.height) window?.addSubview(activityIndicatorView) } /** showSuccessWithText - parameter msg: default is download complete */ public class func showSuccess(msg:String?=nil) { let image = UIImage.init(named:"WBStatusBarHUD.bundle/success") show(msg ?? "download successful", image: image) } /** setWindowBackGroundColor - parameter color: default is black color */ public class func setWindow(color:UIColor) { windowBgColor = color window?.backgroundColor = color } // MARK: - private method /** 显示窗口 */ private class func showWindow() { timer?.invalidate() timer = nil window = UIWindow.init() pathLayer.removeAllAnimations() window!.windowLevel = UIWindowLevelAlert window!.backgroundColor = windowBgColor window!.frame = CGRectMake(0, -20,UIScreen.mainScreen().bounds.size.width, 20) window!.hidden = false UIView.animateWithDuration(windowTime) { () -> Void in window!.center.y += 20 } //这样写是不对的 不知为何 OC中没事 // timer = NSTimer.scheduledTimerWithTimeInterval(textAnimationTime, target:self, selector: "hide", userInfo: nil, repeats: false) timer = NSTimer.scheduledTimerWithTimeInterval(textAnimationTime + 1, target:window!, selector: "hide", userInfo: nil, repeats: false) } /** 添加渐变色的layer 和动画 */ private class func addGradientLayer() { // 渐变色的颜色数 let count = 10 var colors:[CGColorRef] = [] for var i = 0; i < count; i++ { let color = UIColor.init(red: CGFloat(arc4random() % 256) / 255, green: CGFloat(arc4random() % 256) / 255, blue: CGFloat(arc4random() % 256) / 255, alpha: 1.0) colors.append(color.CGColor) } // 渐变色的方向 gradientLayer.startPoint = CGPoint(x: 0, y: 0.5) gradientLayer.endPoint = CGPoint(x: 1, y: 0.5) gradientLayer.colors = colors gradientLayer.frame = window!.bounds gradientLayer.type = kCAGradientLayerAxial window!.layer.addSublayer(gradientLayer) // 渐变色的动画 let animation = CABasicAnimation.init(keyPath: "colors") animation.duration = 0.5 animation.repeatCount = MAXFLOAT var toColors:[CGColorRef] = [] for var i = 0; i < count; i++ { let color = UIColor.init(red: CGFloat(arc4random() % 256) / 255, green: CGFloat(arc4random() % 256) / 255, blue: CGFloat(arc4random() % 256) / 255, alpha: 1.0) toColors.append(color.CGColor) } animation.autoreverses = true animation.toValue = toColors gradientLayer.addAnimation(animation, forKey: "gradientLayer") } /** 添加笔迹的动画 - parameter message: 显示的文字 */ private class func addPathLayer(message:String) { let textPath = bezierPathFrom(message) pathLayer.bounds = CGPathGetBoundingBox(textPath.CGPath) pathLayer.position = window!.center pathLayer.geometryFlipped = true pathLayer.path = textPath.CGPath pathLayer.fillColor = nil pathLayer.lineWidth = 1 pathLayer.strokeColor = UIColor.whiteColor().CGColor // 笔迹的动画 let textAnimation = CABasicAnimation.init(keyPath: "strokeEnd") textAnimation.duration = textAnimationTime textAnimation.fromValue = 0 textAnimation.toValue = 1 textAnimation.delegate = window pathLayer.addAnimation(textAnimation, forKey: "strokeEnd") } /** 将字符串转变成贝塞尔曲线 */ class func bezierPathFrom(string:String) -> UIBezierPath{ let paths = CGPathCreateMutable() let fontName = __CFStringMakeConstantString("SnellRoundhand") let fontRef:AnyObject = CTFontCreateWithName(fontName, 18, nil) let attrString = NSAttributedString(string: string, attributes: [kCTFontAttributeName as String : fontRef]) let line = CTLineCreateWithAttributedString(attrString as CFAttributedString) let runA = CTLineGetGlyphRuns(line) for (var runIndex = 0; runIndex < CFArrayGetCount(runA); runIndex++){ let run = CFArrayGetValueAtIndex(runA, runIndex); let runb = unsafeBitCast(run, CTRun.self) let CTFontName = unsafeBitCast(kCTFontAttributeName, UnsafePointer<Void>.self) let runFontC = CFDictionaryGetValue(CTRunGetAttributes(runb),CTFontName) let runFontS = unsafeBitCast(runFontC, CTFont.self) let width = UIScreen.mainScreen().bounds.width var temp = 0 var offset:CGFloat = 0.0 for(var i = 0; i < CTRunGetGlyphCount(runb); i++){ let range = CFRangeMake(i, 1) let glyph:UnsafeMutablePointer<CGGlyph> = UnsafeMutablePointer<CGGlyph>.alloc(1) glyph.initialize(0) let position:UnsafeMutablePointer<CGPoint> = UnsafeMutablePointer<CGPoint>.alloc(1) position.initialize(CGPointZero) CTRunGetGlyphs(runb, range, glyph) CTRunGetPositions(runb, range, position); let temp3 = CGFloat(position.memory.x) let temp2 = (Int) (temp3 / width) let temp1 = 0 if(temp2 > temp1){ temp = temp2 offset = position.memory.x - (CGFloat(temp) * width) } let path = CTFontCreatePathForGlyph(runFontS,glyph.memory,nil) let x = position.memory.x - (CGFloat(temp) * width) - offset let y = position.memory.y - (CGFloat(temp) * 80) var transform = CGAffineTransformMakeTranslation(x, y) CGPathAddPath(paths, &transform, path) glyph.destroy() glyph.dealloc(1) position.destroy() position.dealloc(1) } } let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPointZero) bezierPath.appendPath(UIBezierPath(CGPath: paths)) return bezierPath } } extension UIWindow{ func hide() { WBStatusBarHUD.hide() } }
bb63b5ae0ebf1e2e3578a0ca06e2382c
31.037415
226
0.580059
false
false
false
false
suragch/Chimee-iOS
refs/heads/master
Chimee/UIMongolTableView.swift
mit
1
import UIKit @IBDesignable class UIMongolTableView: UIView { // MARK:- Unique to TableView // ********* Unique to TableView ********* fileprivate var view = UITableView() fileprivate let rotationView = UIView() fileprivate var userInteractionEnabledForSubviews = true // read only refernce to the underlying tableview var tableView: UITableView { get { return view } } var tableFooterView: UIView? { get { return view.tableFooterView } set { view.tableFooterView = newValue } } func setup() { // do any setup necessary self.addSubview(rotationView) rotationView.addSubview(view) view.backgroundColor = self.backgroundColor view.layoutMargins = UIEdgeInsets.zero view.separatorInset = UIEdgeInsets.zero } // FIXME: @IBOutlet still can't be set in IB @IBOutlet weak var delegate: UITableViewDelegate? { get { return view.delegate } set { view.delegate = newValue } } // FIXME: @IBOutlet still can't be set in IB @IBOutlet weak var dataSource: UITableViewDataSource? { get { return view.dataSource } set { view.dataSource = newValue } } @IBInspectable var scrollEnabled: Bool { get { return view.isScrollEnabled } set { view.isScrollEnabled = newValue } } func scrollToRowAtIndexPath(_ indexPath: IndexPath, atScrollPosition: UITableViewScrollPosition, animated: Bool) { view.scrollToRow(at: indexPath, at: atScrollPosition, animated: animated) } func registerClass(_ cellClass: AnyClass?, forCellReuseIdentifier identifier: String) { view.register(cellClass, forCellReuseIdentifier: identifier) } func dequeueReusableCellWithIdentifier(_ identifier: String) -> UITableViewCell? { return view.dequeueReusableCell(withIdentifier: identifier) } func reloadData() { view.reloadData() } func insertRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) { view.insertRows(at: indexPaths, with: animation) } func deleteRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) { view.deleteRows(at: indexPaths, with: animation) } // MARK:- General code for Mongol views // ******************************************* // ****** General code for Mongol views ****** // ******************************************* // This method gets called if you create the view in the Interface Builder required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // This method gets called if you create the view in code override init(frame: CGRect){ super.init(frame: frame) self.setup() } override func awakeFromNib() { super.awakeFromNib() self.setup() } override func layoutSubviews() { super.layoutSubviews() rotationView.transform = CGAffineTransform.identity rotationView.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: self.bounds.height, height: self.bounds.width)) rotationView.transform = translateRotateFlip() view.frame = rotationView.bounds } func translateRotateFlip() -> CGAffineTransform { var transform = CGAffineTransform.identity // translate to new center transform = transform.translatedBy(x: (self.bounds.width / 2)-(self.bounds.height / 2), y: (self.bounds.height / 2)-(self.bounds.width / 2)) // rotate counterclockwise around center transform = transform.rotated(by: CGFloat(-M_PI_2)) // flip vertically transform = transform.scaledBy(x: -1, y: 1) return transform } }
dee9eb6e56c717535e39ba6e88bbb91d
27.241611
148
0.584601
false
false
false
false
arinjoy/Landmark-Remark
refs/heads/master
LandmarkRemark/LoginSignUpViewModel.swift
mit
1
// // LoginSignUpViewModel.swift // LandmarkRemark // // Created by Arinjoy Biswas on 6/06/2016. // Copyright © 2016 Arinjoy Biswas. All rights reserved. // import Parse /// The protocol for LoginSignupViewModel delegate, implemented by the LoginSignup view-controller public protocol LoginSignUpViewModelDelegate: class { func showInvalidUserName() func showInvalidPassword() func loginSuccessWithUser(user: PFUser) func signupSuccess() func operationFailureWithErrorMessage(title: String, message: String) } /// The view-model for the LoginSignup view-controller public class LoginSignUpViewModel { // public properties of the view-model exposed to its view-controller public var userName: String = "" public var password: String = "" // The delgate of the view-model to call back / pass back information to the view-controller public weak var delegate: LoginSignUpViewModelDelegate? // reference to the Authentication service private let authenticationService: UserAuthenticationService // new initializer public init(delegate: LoginSignUpViewModelDelegate) { self.delegate = delegate authenticationService = UserAuthenticationService() } //------------------------------------------------------------------------------------------------ // MARK: - Core methods of the view-model, called by the view-controller based on the user actions //------------------------------------------------------------------------------------------------ /** The login mehtod */ public func login() { // checking for valid username and password string, and inform the view-controller if !isValidUserName() { delegate?.showInvalidUserName() } else if !isValidPassword() { delegate?.showInvalidPassword() } else { // call to service layer // passing weak deleagte to break te retain cycle if any (for safety) // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html authenticationService.loginUser(userName, password: password, completionHandler: { [weak delegate = self.delegate!] (user, error) in if user != nil { // communicate with the view-controller and send the new logged-in user object delegate?.loginSuccessWithUser(user!) } else { // determine the error message and came from the backend side and send a user-friendly message back to the UI side var title = "Error Occurred" var message = "Some unknown error occurred. Please try again." if error != nil { if error?.code == 100 { title = "No Internet Connection" message = "Internet connection appears to be offine. Could not login." } if error?.code == 101 { title = "Login Failed" message = "You have entered invalid credentials. Please try again." } if error?.code == 401 { title = "Login Failed" message = "Could not succeed because access was denied." } } // pass back the error information delegate?.operationFailureWithErrorMessage(title, message: message) } }) } } /** The signup method */ public func signup() { // checking for valid username and password string, and inform the view-controller if !isValidUserName() { delegate?.showInvalidUserName() } else if !isValidPassword() { delegate?.showInvalidPassword() } else { // call the service layer authenticationService.signupUser(userName, password: password, completionHandler: { [weak delegate = self.delegate!] (success, error) in if error == nil { delegate?.signupSuccess() } else { // determine the error message and came from the backend side and send a user-friendly message back to the UI side var title = "Error Occurred" var message = "Some unknown error occurred. Please try again." if error?.code == 100 { title = "No Internet Connection" message = "Internet connection appears to be offine. Could not signup." } if error?.code == 202 || error?.code == 203 { title = "Signup Failed" message = "The username you have chosen has already been taken up by another user. Please choose a different one. " } // pass back the error information delegate?.operationFailureWithErrorMessage(title, message: message) } }) } } //------------------------------------------------------------------------------------------------ // MARK: - private helper methods //------------------------------------------------------------------------------------------------ /** To check for an acceptable username */ private func isValidUserName() -> Bool { do { let regex = try NSRegularExpression(pattern: "^[A-Za-z]+([A-Za-z0-9-_.]){2,15}$", options: .CaseInsensitive) return regex.firstMatchInString(userName, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, userName.characters.count)) != nil } catch { return false } } /** To check for an acceptable password */ private func isValidPassword() -> Bool { do { let regex = try NSRegularExpression(pattern: "^[A-Za-z0-9.!#$%&'*+/=?^_~-]{3,25}$", options: .CaseInsensitive) return regex.firstMatchInString(password, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, password.characters.count)) != nil } catch { return false } } }
1f81ddd4b45bbef155b79d69ed3970da
37.916168
151
0.534852
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKit/InsulinKit/ManualBolusRecommendation.swift
mit
1
// // ManualBolusRecommendation.swift // LoopKit // // Created by Pete Schwamb on 1/2/17. // Copyright © 2017 LoopKit Authors. All rights reserved. // import Foundation import HealthKit public enum BolusRecommendationNotice { case glucoseBelowSuspendThreshold(minGlucose: GlucoseValue) case currentGlucoseBelowTarget(glucose: GlucoseValue) case predictedGlucoseBelowTarget(minGlucose: GlucoseValue) case predictedGlucoseInRange case allGlucoseBelowTarget(minGlucose: GlucoseValue) } extension BolusRecommendationNotice: Codable { public init(from decoder: Decoder) throws { if let string = try? decoder.singleValueContainer().decode(String.self) { switch string { case CodableKeys.predictedGlucoseInRange.rawValue: self = .predictedGlucoseInRange default: throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration")) } } else { let container = try decoder.container(keyedBy: CodableKeys.self) if let glucoseBelowSuspendThreshold = try container.decodeIfPresent(GlucoseBelowSuspendThreshold.self, forKey: .glucoseBelowSuspendThreshold) { self = .glucoseBelowSuspendThreshold(minGlucose: glucoseBelowSuspendThreshold.minGlucose) } else if let currentGlucoseBelowTarget = try container.decodeIfPresent(CurrentGlucoseBelowTarget.self, forKey: .currentGlucoseBelowTarget) { self = .currentGlucoseBelowTarget(glucose: currentGlucoseBelowTarget.glucose) } else if let predictedGlucoseBelowTarget = try container.decodeIfPresent(PredictedGlucoseBelowTarget.self, forKey: .predictedGlucoseBelowTarget) { self = .predictedGlucoseBelowTarget(minGlucose: predictedGlucoseBelowTarget.minGlucose) } else if let allGlucoseBelowTarget = try container.decodeIfPresent(AllGlucoseBelowTarget.self, forKey: .allGlucoseBelowTarget) { self = .allGlucoseBelowTarget(minGlucose: allGlucoseBelowTarget.minGlucose) } else { throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "invalid enumeration")) } } } public func encode(to encoder: Encoder) throws { switch self { case .glucoseBelowSuspendThreshold(let minGlucose): var container = encoder.container(keyedBy: CodableKeys.self) try container.encode(GlucoseBelowSuspendThreshold(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .glucoseBelowSuspendThreshold) case .currentGlucoseBelowTarget(let glucose): var container = encoder.container(keyedBy: CodableKeys.self) try container.encode(CurrentGlucoseBelowTarget(glucose: SimpleGlucoseValue(glucose)), forKey: .currentGlucoseBelowTarget) case .predictedGlucoseBelowTarget(let minGlucose): var container = encoder.container(keyedBy: CodableKeys.self) try container.encode(PredictedGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .predictedGlucoseBelowTarget) case .predictedGlucoseInRange: var container = encoder.singleValueContainer() try container.encode(CodableKeys.predictedGlucoseInRange.rawValue) case .allGlucoseBelowTarget(minGlucose: let minGlucose): var container = encoder.container(keyedBy: CodableKeys.self) try container.encode(AllGlucoseBelowTarget(minGlucose: SimpleGlucoseValue(minGlucose)), forKey: .allGlucoseBelowTarget) } } private struct GlucoseBelowSuspendThreshold: Codable { let minGlucose: SimpleGlucoseValue } private struct CurrentGlucoseBelowTarget: Codable { let glucose: SimpleGlucoseValue } private struct PredictedGlucoseBelowTarget: Codable { let minGlucose: SimpleGlucoseValue } private struct AllGlucoseBelowTarget: Codable { let minGlucose: SimpleGlucoseValue } private enum CodableKeys: String, CodingKey { case glucoseBelowSuspendThreshold case currentGlucoseBelowTarget case predictedGlucoseBelowTarget case predictedGlucoseInRange case allGlucoseBelowTarget } } public struct ManualBolusRecommendation { public let amount: Double public let pendingInsulin: Double public var notice: BolusRecommendationNotice? public init(amount: Double, pendingInsulin: Double, notice: BolusRecommendationNotice? = nil) { self.amount = amount self.pendingInsulin = pendingInsulin self.notice = notice } } extension ManualBolusRecommendation: Codable {}
2a5a65370d8d53f76ec121a5a6d2b828
45.647059
159
0.729508
false
false
false
false
FengDeng/RXGitHub
refs/heads/master
Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift
apache-2.0
35
// // VirtualTimeConverterType.swift // Rx // // Created by Krunoslav Zaher on 12/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Parametrization for virtual time used by `VirtualTimeScheduler`s. */ public protocol VirtualTimeConverterType { /** Virtual time unit used that represents ticks of virtual clock. */ typealias VirtualTimeUnit /** Virtual time unit used to represent differences of virtual times. */ typealias VirtualTimeIntervalUnit /** Converts virtual time to real time. - parameter virtualTime: Virtual time to convert to `NSDate`. - returns: `NSDate` corresponding to virtual time. */ func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime /** Converts real time to virtual time. - parameter time: `NSDate` to convert to virtual time. - returns: Virtual time corresponding to `NSDate`. */ func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit /** Converts from virtual time interval to `NSTimeInterval`. - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. - returns: `NSTimeInterval` corresponding to virtual time interval. */ func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval /** Converts from virtual time interval to `NSTimeInterval`. - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. - returns: Virtual time interval corresponding to time interval. */ func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit /** Offsets virtual time by virtual time interval. - parameter time: Virtual time. - parameter offset: Virtual time interval. - returns: Time corresponding to time offsetted by virtual time interval. */ func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit /** This is aditional abstraction because `NSDate` is unfortunately not comparable. Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. */ func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison } /** Virtual time comparison result. This is aditional abstraction because `NSDate` is unfortunately not comparable. Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. */ public enum VirtualTimeComparison { /** lhs < rhs. */ case LessThan /** lhs == rhs. */ case Equal /** lhs > rhs. */ case GreaterThan } extension VirtualTimeComparison { /** lhs < rhs. */ var lessThen: Bool { if case .LessThan = self { return true } return false } /** lhs > rhs */ var greaterThan: Bool { if case .GreaterThan = self { return true } return false } /** lhs == rhs */ var equal: Bool { if case .Equal = self { return true } return false } }
6f3e9db68b9e6c0333e36b7bb21803e4
24.913386
113
0.662109
false
false
false
false
castial/Quick-Start-iOS
refs/heads/master
Quick-Start-iOS/Controllers/Location/Protocol/EmptyPresenter.swift
mit
1
// // EmptyPresenter.swift // Quick-Start-iOS // // Created by work on 2016/12/10. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit struct EmptyOptions { let message: String let messageFont: UIFont let messageColor: UIColor let backgroundColor: UIColor init(message: String = "暂无数据", messageFont: UIFont = UIFont.systemFont(ofSize: 16), messageColor: UIColor = UIColor.black, backgroundColor: UIColor = UIColor.white) { self.message = message self.messageFont = messageFont self.messageColor = messageColor self.backgroundColor = backgroundColor } } protocol EmptyPresenter { func presentEmpty(emptyOptions: EmptyOptions) } extension EmptyPresenter where Self: UIView { func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) { let emptyView = defaultEmptyView(emptyOptions: emptyOptions) self.addSubview(emptyView) } } extension EmptyPresenter where Self: UIViewController { func presentEmpty(emptyOptions: EmptyOptions = EmptyOptions()) { let emptyView = defaultEmptyView(emptyOptions: emptyOptions) self.view.addSubview(emptyView) } } extension EmptyPresenter { // default empty view fileprivate func defaultEmptyView(emptyOptions: EmptyOptions) -> UIView { let emptyView = UIView (frame: CGRect (x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) emptyView.backgroundColor = emptyOptions.backgroundColor // add a message label let messageLabel = UILabel() messageLabel.text = emptyOptions.message messageLabel.font = emptyOptions.messageFont messageLabel.textColor = emptyOptions.messageColor messageLabel.textAlignment = .center messageLabel.sizeToFit() messageLabel.center = emptyView.center emptyView.addSubview(messageLabel) return emptyView } }
44905fdce059992566e6fe41d1347514
31.569231
170
0.651393
false
false
false
false
lingoslinger/SwiftLibraries
refs/heads/master
SwiftLibraries/View Controllers/LibraryTableViewController.swift
mit
1
// // LibraryTableViewController.swift // SwiftLibraries // // Created by Allan Evans on 7/21/16. // Copyright © 2016 - 2021 Allan Evans. All rights reserved. Seriously. // import UIKit import Foundation typealias SessionCompletionHandler = (_ data : Data?, _ response : URLResponse?, _ error : Error?) -> Void class LibraryTableViewController: UITableViewController { var libraryArray = [Library]() var sectionDictionary = Dictionary<String, [Library]>() var sectionTitles = [String]() // MARK: - view lifecycle override func viewDidLoad() { super.viewDidLoad() let libraryURLSession = LibraryURLSession(); let completionHander : SessionCompletionHandler = {(data : Data?, response : URLResponse?, error : Error?) -> Void in if (error == nil) { let decoder = JSONDecoder() guard let libraryArray = try? decoder.decode([Library].self, from: data!) else { fatalError("Unable to decode JSON library data") } self.libraryArray = libraryArray DispatchQueue.main.async(execute: { self.setupSectionsWithLibraryArray() self.tableView.reloadData() }) } else { DispatchQueue.main.async { self.showErrorDialogWithMessage(message: error?.localizedDescription ?? "Unknown network error") } } } libraryURLSession.sendRequest(completionHander) } // MARK: - UITableViewDataSource and UITableViewDelegate methods override func numberOfSections(in tableView: UITableView) -> Int { return sectionTitles.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionTitle = self.sectionTitles[section] let sectionArray = self.sectionDictionary[sectionTitle] return sectionArray?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "LibraryTableViewCell") let sectionTitle = self.sectionTitles[indexPath.section] let sectionArray = self.sectionDictionary[sectionTitle] let library = sectionArray?[indexPath.row] cell?.textLabel?.text = library?.name return cell! } override func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int { return index } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sectionTitles[section] } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return self.sectionTitles } // MARK: - navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "LibraryDetailViewController" { guard let indexPath = self.tableView.indexPathForSelectedRow else { return } let detailViewController = segue.destination as! LibraryDetailViewController let sectionTitle = self.sectionTitles[indexPath.section] let sectionArray = self.sectionDictionary[sectionTitle] detailViewController.detailLibrary = sectionArray?[indexPath.row] } } // MARK: - private methods func setupSectionsWithLibraryArray() { for library in libraryArray { let firstLetterOfName = String.init(library.name?.first ?? Character.init("")) if (sectionDictionary[firstLetterOfName] == nil) { let sectionArray = [Library]() sectionDictionary[firstLetterOfName] = sectionArray } sectionDictionary[firstLetterOfName]?.append(library) } let unsortedLetters = self.sectionDictionary.keys sectionTitles = unsortedLetters.sorted() } }
96375ef7270cb70fb848cdad8e067086
39.68
125
0.646755
false
false
false
false
jcbages/seneca
refs/heads/master
seneca/AboutWindow.swift
mit
1
import Cocoa let APP_VERSION = "1.0.0" let NAME_LABEL_TEXT = "seneca" let CONTACT_EMAIL = "[email protected]" let SUPPORT_MESSAGE = "Si tienes algúna duda, escríbenos a alguno de estos correos" let SUPPORT_EMAIL = "[email protected]" let REPOSITORY_MESSAGE = "Si nos quieres apoyar, entra a" let REPOSITORY_LINK = "https://github.com/jcbages/seneca" let MAIN_FONT = "Helvetica Neue Light" class AboutWindow: NSWindowController { /* * The UI components related to this particular view, specified * to handle them in this controller */ @IBOutlet weak var logoIcon: NSImageView! @IBOutlet weak var nameLabel: NSTextField! @IBOutlet weak var versionLabel: NSTextField! @IBOutlet weak var contactEmailLabel: NSTextField! @IBOutlet weak var emailLabel: NSTextField! @IBOutlet weak var supportEmailLabel: NSTextField! @IBOutlet weak var supportRepositoryLabel: NSTextField! @IBOutlet weak var repositoryLabel: NSTextField! override var windowNibName : String! { return "AboutWindow" } override func windowDidLoad() { super.windowDidLoad() self.window?.center() self.window?.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) // Handling the logo image self.logoIcon.image = NSImage(named: "logo") // Handling the project name label self.nameLabel.font = NSFont(name: MAIN_FONT, size: 16) // Handling the project version label self.versionLabel.stringValue = "Versión \(APP_VERSION)" self.versionLabel.font = NSFont(name: MAIN_FONT, size: 10) self.contactEmailLabel.stringValue = SUPPORT_MESSAGE self.contactEmailLabel.font = NSFont(name: MAIN_FONT, size: 12) self.emailLabel.stringValue = CONTACT_EMAIL self.emailLabel.font = NSFont(name: MAIN_FONT, size: 12) self.supportEmailLabel.stringValue = SUPPORT_EMAIL self.supportEmailLabel.font = NSFont(name: MAIN_FONT, size: 12) self.supportRepositoryLabel.stringValue = REPOSITORY_MESSAGE self.supportRepositoryLabel.font = NSFont(name: MAIN_FONT, size: 12) self.repositoryLabel.stringValue = REPOSITORY_LINK self.repositoryLabel.font = NSFont(name: MAIN_FONT, size: 12) } }
9dd4e51891177b9751e41b5923fdbb59
29.525
83
0.662981
false
false
false
false
CodaFi/swift
refs/heads/main
test/Sema/diag_mismatched_magic_literals.swift
apache-2.0
19
// RUN: %target-typecheck-verify-swift // RUN: %target-typecheck-verify-swift -enable-experimental-concise-pound-file // The test cases in this file work the same in both Swift 5 and "Swift 6" mode. // See the _swift5 and _swift6 files for version-specific test cases. func callee(file: String = #file) {} // expected-note {{'file' declared here}} func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} func callee(fileID: String = #fileID) {} // expected-note {{'fileID' declared here}} func callee(filePath: String = #filePath) {} // expected-note {{'filePath' declared here}} func callee(arbitrary: String) {} class SomeClass { static func callee(file: String = #file) {} // expected-note 2{{'file' declared here}} static func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} static func callee(arbitrary: String) {} func callee(file: String = #file) {} // expected-note 2{{'file' declared here}} func callee(optFile: String? = #file) {} // expected-note {{'optFile' declared here}} func callee(arbitrary: String) {} } // // Basic functionality // // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func bad(function: String = #function) { // expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{29-38=#file}} // expected-note@-2 {{did you mean for parameter 'function' to default to '#fileID'?}} {{29-38=#fileID}} // expected-note@-3 {{did you mean for parameter 'function' to default to '#filePath'?}} {{29-38=#filePath}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{16-16=(}} {{24-24=)}} SomeClass.callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{26-26=(}} {{34-34=)}} SomeClass().callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{28-28=(}} {{36-36=)}} callee(fileID: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'fileID', whose default argument is '#fileID'}} // expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}} callee(filePath: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'filePath', whose default argument is '#filePath'}} // expected-note@-2 {{add parentheses to silence this warning}} {{20-20=(}} {{28-28=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func good(file: String = #file, fileID: String = #fileID, filePath: String = #filePath) { callee(file: file) SomeClass.callee(file: file) SomeClass().callee(file: file) callee(fileID: fileID) callee(filePath: filePath) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func disabled(function: String = #function) { callee(file: (function)) SomeClass.callee(file: (function)) SomeClass().callee(file: (function)) callee(fileID: (function)) callee(filePath: (function)) } // // With implicit instance `self` // extension SomeClass { // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func bad(function: String = #function) { // expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{31-40=#file}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func good(file: String = #file) { callee(file: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func disabled(function: String = #function) { callee(file: (function)) } } // // With implicit type `self` // extension SomeClass { // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. static func bad(function: String = #function) { // expected-note@-1 1{{did you mean for parameter 'function' to default to '#file'?}} {{38-47=#file}} callee(file: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'file', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{18-18=(}} {{26-26=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. static func good(file: String = #file) { callee(file: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. static func disabled(function: String = #function) { callee(file: (function)) } } // // Looking through implicit conversions // // Same as above, but these lift the argument from `String` to `String?`, so // the compiler has to look through the implicit conversion. // // We should warn when we we pass a `#function`-defaulted argument to a // `#file`-defaulted argument. func optionalBad(function: String = #function) { // expected-note@-1 3{{did you mean for parameter 'function' to default to '#file'?}} {{37-46=#file}} callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{19-19=(}} {{27-27=)}} SomeClass.callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{29-29=(}} {{37-37=)}} SomeClass().callee(optFile: function) // expected-warning@-1 {{parameter 'function' with default argument '#function' passed to parameter 'optFile', whose default argument is '#file'}} // expected-note@-2 {{add parentheses to silence this warning}} {{31-31=(}} {{39-39=)}} } // We should not warn when we pass a `#file`-defaulted argument to a // `#file`-defaulted argument. func optionalGood(file: String = #file) { callee(optFile: file) SomeClass.callee(optFile: file) SomeClass().callee(optFile: file) } // We should not warn when we surround the `#function`-defaulted argument // with parentheses, which explicitly silences the warning. func optionalDisabled(function: String = #function) { callee(optFile: (function)) SomeClass.callee(optFile: (function)) SomeClass().callee(optFile: (function)) } // // More negative cases // // We should not warn if the caller's parameter has no default. func explicit(arbitrary: String) { callee(file: arbitrary) SomeClass.callee(file: arbitrary) SomeClass().callee(file: arbitrary) } // We should not warn if the caller's parameter has a non-magic-identifier // default. func empty(arbitrary: String = "") { callee(file: arbitrary) SomeClass.callee(file: arbitrary) SomeClass().callee(file: arbitrary) } // We should not warn if the callee's parameter has no default. func ineligible(function: String = #function) { callee(arbitrary: function) SomeClass.callee(arbitrary: function) SomeClass().callee(arbitrary: function) }
45eefac9f20359d56e8cb249dc2c68bb
37.49763
153
0.693463
false
false
false
false
gavinpardoe/OfficeUpdateHelper
refs/heads/master
officeUpdateHelper/AppDelegate.swift
mit
1
/* AppDelegate.swift officeUpdateHelper Created by Gavin Pardoe on 03/03/2016. Updated 15/03/2016. Designed for Use with JAMF Casper Suite. The MIT License (MIT) Copyright (c) 2016 Gavin Pardoe 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 Cocoa import WebKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var webView: WebView! @IBOutlet weak var activityWheel: NSProgressIndicator! @IBOutlet weak var label: NSTextField! @IBOutlet weak var deferButtonDisable: NSButton! @IBOutlet weak var installButtonDisable: NSButton! var appCheckTimer = NSTimer() func applicationDidFinishLaunching(aNotification: NSNotification) { let htmlPage = NSBundle.mainBundle().URLForResource("index", withExtension: "html") webView.mainFrame.loadRequest(NSURLRequest(URL: htmlPage!)) activityWheel.displayedWhenStopped = false self.window.makeKeyAndOrderFront(nil) self.window.level = Int(CGWindowLevelForKey(.FloatingWindowLevelKey)) self.window.level = Int(CGWindowLevelForKey(.MaximumWindowLevelKey)) label.allowsEditingTextAttributes = true label.stringValue = "Checking for Running Office Apps" installButtonDisable.enabled = false NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self appCheck() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool { return true } func appCheck() { appCheckTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(AppDelegate.officeAppsRunning), userInfo: nil, repeats: true) } func officeAppsRunning() { for runningApps in NSWorkspace.sharedWorkspace().runningApplications { if let _ = runningApps.localizedName { } } let appName = NSWorkspace.sharedWorkspace().runningApplications.flatMap { $0.localizedName } if appName.contains("Microsoft Word") { label.textColor = NSColor.redColor() label.stringValue = "Please Quit All Office Apps to Continue!" } else if appName.contains("Microsoft Excel") { label.textColor = NSColor.redColor() label.stringValue = "Please Quit All Office Apps to Continue!" } else if appName.contains("Microsoft PowerPoint") { label.textColor = NSColor.redColor() label.stringValue = "Please Quit All Office Apps to Continue!" } else if appName.contains("Microsoft Outlook") { label.textColor = NSColor.redColor() label.stringValue = "Please Quit All Office Apps to Continue!" } else if appName.contains("Microsoft OneNote") { label.textColor = NSColor.redColor() label.stringValue = "Please Quit All Office Apps to Continue!" } else { installUpdates() } } func installUpdates() { appCheckTimer.invalidate() label.textColor = NSColor.blackColor() label.stringValue = "Click Install to Begin Updating Office" installButtonDisable.enabled = true } @IBAction func installButton(sender: AnyObject) { installButtonDisable.enabled = false deferButtonDisable.enabled = false self.activityWheel.startAnimation(self) let notification = NSUserNotification() notification.title = "Office Updater" notification.informativeText = "Installing Updates..." notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) label.stringValue = "Installing Updates, Window will Close Once Completed" NSAppleScript(source: "do shell script \"/usr/local/jamf/bin/jamf policy -event officeUpdate\" with administrator " + "privileges")!.executeAndReturnError(nil) // For Testing //let alert = NSAlert() //alert.messageText = "Testing Completed..!" //alert.addButtonWithTitle("OK") //alert.runModal() } @IBAction func deferButton(sender: AnyObject) { let notification = NSUserNotification() notification.title = "Office Updater" notification.informativeText = "Installation has Been Defered..." notification.soundName = NSUserNotificationDefaultSoundName NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) NSApplication.sharedApplication().terminate(self) } }
641b94ed571a36646e97af682caa4d83
36.047904
170
0.674317
false
false
false
false
SirapatBoonyasiwapong/grader
refs/heads/master
Sources/App/Admin/Commands/RedisWorker.swift
mit
2
import VaporRedisClient import Redis import RedisClient import Reswifq import Console class RedisWorker { let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } func run() { console.print("Preparing redis client pool...") let client = RedisClientPool(maxElementCount: 10) { () -> RedisClient in self.console.print("Create client") return VaporRedisClient(try! TCPClient(hostname: "redis", port: 6379)) } let queue = Reswifq(client: client) queue.jobMap[String(describing: DemoJob.self)] = DemoJob.self queue.jobMap[String(describing: SubmissionJob.self)] = SubmissionJob.self console.print("Starting worker...") let worker = Worker(queue: queue, maxConcurrentJobs: 4, averagePollingInterval: 0) worker.run() console.print("Finished") } }
7bae119dbd80bfe85b76cd094fd7577e
26.628571
90
0.625646
false
false
false
false
alex-alex/S2Geometry
refs/heads/master
Sources/S1Interval.swift
mit
1
// // S1Interval.swift // S2Geometry // // Created by Alex Studnicka on 7/1/16. // Copyright © 2016 Alex Studnicka. MIT License. // #if os(Linux) import Glibc #else import Darwin.C #endif /** An S1Interval represents a closed interval on a unit circle (also known as a 1-dimensional sphere). It is capable of representing the empty interval (containing no points), the full interval (containing all points), and zero-length intervals (containing a single point). Points are represented by the angle they make with the positive x-axis in the range [-Pi, Pi]. An interval is represented by its lower and upper bounds (both inclusive, since the interval is closed). The lower bound may be greater than the upper bound, in which case the interval is "inverted" (i.e. it passes through the point (-1, 0)). Note that the point (-1, 0) has two valid representations, Pi and -Pi. The normalized representation of this point internally is Pi, so that endpoints of normal intervals are in the range (-Pi, Pi]. However, we take advantage of the point -Pi to construct two special intervals: the Full() interval is [-Pi, Pi], and the Empty() interval is [Pi, -Pi]. */ public struct S1Interval: Equatable { public let lo: Double public let hi: Double /** Both endpoints must be in the range -Pi to Pi inclusive. The value -Pi is converted internally to Pi except for the Full() and Empty() intervals. */ public init(lo: Double, hi: Double) { self.init(lo: lo, hi: hi, checked: false) } /** Internal constructor that assumes that both arguments are in the correct range, i.e. normalization from -Pi to Pi is already done. */ private init(lo: Double, hi: Double, checked: Bool) { var newLo = lo var newHi = hi if !checked { if lo == -M_PI && hi != M_PI { newLo = M_PI } if hi == -M_PI && lo != M_PI { newHi = M_PI } } self.lo = newLo self.hi = newHi } public static let empty = S1Interval(lo: M_PI, hi: -M_PI, checked: true) public static let full = S1Interval(lo: -M_PI, hi: M_PI, checked: true) /// Convenience method to construct an interval containing a single point. public init(point p: Double) { var p = p if p == -M_PI { p = M_PI } self.init(lo: p, hi: p) } /** Convenience method to construct the minimal interval containing the two given points. This is equivalent to starting with an empty interval and calling AddPoint() twice, but it is more efficient. */ public init(p1: Double, p2: Double) { var p1 = p1, p2 = p2 if p1 == -M_PI { p1 = M_PI } if p2 == -M_PI { p2 = M_PI } if S1Interval.positiveDistance(p1, p2) <= M_PI { self.init(lo: p1, hi: p2, checked: true) } else { self.init(lo: p2, hi: p1, checked: true) } } /** An interval is valid if neither bound exceeds Pi in absolute value, and the value -Pi appears only in the empty and full intervals. */ public var isValid: Bool { return (abs(lo) <= M_PI && abs(hi) <= M_PI && !(lo == -M_PI && hi != M_PI) && !(hi == -M_PI && lo != M_PI)) } /// Return true if the interval contains all points on the unit circle. public var isFull: Bool { return hi - lo == 2 * M_PI } /// Return true if the interval is empty, i.e. it contains no points. public var isEmpty: Bool { return lo - hi == 2 * M_PI } /// Return true if lo() > hi(). (This is true for empty intervals.) public var isInverted: Bool { return lo > hi } /// Return the midpoint of the interval. For full and empty intervals, the result is arbitrary. public var center: Double { let center = 0.5 * (lo + hi) if !isInverted { return center } // Return the center in the range (-Pi, Pi]. return (center <= 0) ? (center + M_PI) : (center - M_PI) } /// Return the length of the interval. The length of an empty interval is negative. public var length: Double { var length = hi - lo if length >= 0 { return length } length += 2 * M_PI // Empty intervals have a negative length. return (length > 0) ? length : -1 } /** Return the complement of the interior of the interval. An interval and its complement have the same boundary but do not share any interior values. The complement operator is not a bijection, since the complement of a singleton interval (containing a single value) is the same as the complement of an empty interval. */ public var complement: S1Interval { if lo == hi { return S1Interval.full // Singleton. } else { return S1Interval(lo: hi, hi: lo, checked: true) // Handles empty and full. } } /// Return true if the interval (which is closed) contains the point 'p'. public func contains(point p: Double) -> Bool { // Works for empty, full, and singleton intervals. // assert (Math.abs(p) <= S2.M_PI); var p = p if (p == -M_PI) { p = M_PI } return fastContains(point: p) } /** Return true if the interval (which is closed) contains the point 'p'. Skips the normalization of 'p' from -Pi to Pi. */ public func fastContains(point p: Double) -> Bool { if isInverted { return (p >= lo || p <= hi) && !isEmpty } else { return p >= lo && p <= hi } } /// Return true if the interval contains the given interval 'y'. Works for empty, full, and singleton intervals. public func contains(interval y: S1Interval) -> Bool { // It might be helpful to compare the structure of these tests to // the simpler Contains(double) method above. if isInverted { if y.isInverted { return y.lo >= lo && y.hi <= hi } return (y.lo >= lo || y.hi <= hi) && !isEmpty } else { if y.isInverted { return isFull || y.isEmpty } return y.lo >= lo && y.hi <= hi } } /** Returns true if the interior of this interval contains the entire interval 'y'. Note that x.InteriorContains(x) is true only when x is the empty or full interval, and x.InteriorContains(S1Interval(p,p)) is equivalent to x.InteriorContains(p). */ public func interiorContains(interval y: S1Interval) -> Bool { if isInverted { if !y.isInverted { return y.lo > lo || y.hi < hi } return (y.lo > lo && y.hi < hi) || y.isEmpty } else { if y.isInverted { return isFull || y.isEmpty } return (y.lo > lo && y.hi < hi) || isFull } } /// Return true if the interior of the interval contains the point 'p'. public func interiorContains(point p: Double) -> Bool { // Works for empty, full, and singleton intervals. // assert (Math.abs(p) <= S2.M_PI); var p = p if (p == -M_PI) { p = M_PI } if isInverted { return p > lo || p < hi } else { return (p > lo && p < hi) || isFull } } /** Return true if the two intervals contain any points in common. Note that the point +/-Pi has two representations, so the intervals [-Pi,-3] and [2,Pi] intersect, for example. */ public func intersects(with y: S1Interval) -> Bool { if isEmpty || y.isEmpty { return false } if isInverted { // Every non-empty inverted interval contains Pi. return y.isInverted || y.lo <= hi || y.hi >= lo } else { if y.isInverted { return y.lo <= hi || y.hi >= lo } return y.lo <= hi && y.hi >= lo } } /** Return true if the interior of this interval contains any point of the interval 'y' (including its boundary). Works for empty, full, and singleton intervals. */ public func interiorIntersects(with y: S1Interval) -> Bool { if isEmpty || y.isEmpty || lo == hi { return false } if isInverted { return y.isInverted || y.lo < hi || y.hi > lo } else { if y.isInverted { return y.lo < hi || y.hi > lo } return (y.lo < hi && y.hi > lo) || isFull } } /** Expand the interval by the minimum amount necessary so that it contains the given point "p" (an angle in the range [-Pi, Pi]). */ public func add(point p: Double) -> S1Interval { // assert (Math.abs(p) <= S2.M_PI); var p = p if p == -M_PI { p = M_PI } if fastContains(point: p) { return self } if isEmpty { return S1Interval(point: p) } else { // Compute distance from p to each endpoint. let dlo = S1Interval.positiveDistance(p, lo) let dhi = S1Interval.positiveDistance(hi, p) if dlo < dhi { return S1Interval(lo: p, hi: hi) } else { return S1Interval(lo: lo, hi: p) } // Adding a point can never turn a non-full interval into a full one. } } /** Return an interval that contains all points within a distance "radius" of a point in this interval. Note that the expansion of an empty interval is always empty. The radius must be non-negative. */ public func expanded(radius: Double) -> S1Interval { // assert (radius >= 0) guard !isEmpty else { return self } // Check whether this interval will be full after expansion, allowing // for a 1-bit rounding error when computing each endpoint. if length + 2 * radius >= 2 * M_PI - 1e-15 { return .full } // NOTE(dbeaumont): Should this remainder be 2 * M_PI or just M_PI ?? var lo = remainder(self.lo - radius, 2 * M_PI) let hi = remainder(self.hi + radius, 2 * M_PI) if lo == -M_PI { lo = M_PI } return S1Interval(lo: lo, hi: hi) } /// Return the smallest interval that contains this interval and the given interval "y". public func union(with y: S1Interval) -> S1Interval { // The y.is_full() case is handled correctly in all cases by the code // below, but can follow three separate code paths depending on whether // this interval is inverted, is non-inverted but contains Pi, or neither. if y.isEmpty { return self } if fastContains(point: y.lo) { if fastContains(point: y.hi) { // Either this interval contains y, or the union of the two // intervals is the Full() interval. if contains(interval: y) { return self // is_full() code path } return .full } return S1Interval(lo: lo, hi: y.hi, checked: true) } if (fastContains(point: y.hi)) { return S1Interval(lo: y.lo, hi: hi, checked: true) } // This interval contains neither endpoint of y. This means that either y // contains all of this interval, or the two intervals are disjoint. if isEmpty || y.fastContains(point: lo) { return y } // Check which pair of endpoints are closer together. let dlo = S1Interval.positiveDistance(y.hi, lo) let dhi = S1Interval.positiveDistance(hi, y.lo) if dlo < dhi { return S1Interval(lo: y.lo, hi: hi, checked: true) } else { return S1Interval(lo: lo, hi: y.hi, checked: true) } } /** Compute the distance from "a" to "b" in the range [0, 2*Pi). This is equivalent to (drem(b - a - S2.M_PI, 2 * S2.M_PI) + S2.M_PI), except that it is more numerically stable (it does not lose precision for very small positive distances). */ public static func positiveDistance(_ a: Double, _ b: Double) -> Double { let d = b - a if d >= 0 { return d } // We want to ensure that if b == Pi and a == (-Pi + eps), // the return result is approximately 2*Pi and not zero. return (b + M_PI) - (a - M_PI) } } public func ==(lhs: S1Interval, rhs: S1Interval ) -> Bool { return (lhs.lo == rhs.lo && lhs.hi == rhs.hi) || (lhs.isEmpty && rhs.isEmpty) }
4d4570a06674050f4cd62a854a2c6477
29
113
0.645642
false
false
false
false
NoryCao/zhuishushenqi
refs/heads/master
zhuishushenqi/RightSide/Search/QSSearchAutoCompleteTable.swift
mit
1
// // QSSearchAutoCompleteTable.swift // zhuishushenqi // // Created by Nory Cao on 2017/4/13. // Copyright © 2017年 QS. All rights reserved. // import UIKit class ZSSearchAutoCompleteController: ZSBaseTableViewController ,UISearchResultsUpdating{ var books:[String] = [] { didSet{ self.tableView.reloadData() } } var selectRow:DidSelectRow? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(red: 1.0, green: 0.98, blue: 0.82, alpha: 1.0) tableView.qs_registerCellClass(UITableViewCell.self) // automaticallyAdjustsScrollViewInsets = false if #available(iOS 11.0, *) { self.tableView.contentInsetAdjustmentBehavior = .automatic } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tableView.frame = CGRect(x: 0, y: kNavgationBarHeight, width: ScreenWidth, height: ScreenHeight - kNavgationBarHeight) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return books.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell? = tableView.qs_dequeueReusableCell(UITableViewCell.self) cell?.backgroundColor = UIColor.white cell?.selectionStyle = .none cell?.textLabel?.text = self.books.count > indexPath.row ? books[indexPath.row]:"" return cell! } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.0001 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return UIView() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let select = selectRow { select(indexPath) } } //MARK: - UISearchBarDelegate func updateSearchResults(for searchController: UISearchController) { } } class QSSearchAutoCompleteTable: UIView,UITableViewDataSource,UITableViewDelegate { var books:[String]? { didSet{ self.tableView.reloadData() } } var selectRow:DidSelectRow? lazy var tableView:UITableView = { let tableView = UITableView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: self.bounds.height), style: .grouped) tableView.dataSource = self tableView.delegate = self tableView.sectionHeaderHeight = CGFloat.leastNonzeroMagnitude tableView.rowHeight = 44 tableView.qs_registerCellClass(UITableViewCell.self) return tableView }() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor(red: 1.0, green: 0.98, blue: 0.82, alpha: 1.0) self.addSubview(self.tableView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return books?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell? = tableView.qs_dequeueReusableCell(UITableViewCell.self) cell?.backgroundColor = UIColor.white cell?.selectionStyle = .none cell?.textLabel?.text = self.books?.count ?? 0 > indexPath.row ? books?[indexPath.row]:"" return cell! } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 0.0001 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let select = selectRow { select(indexPath) } } }
c1eef906120edd3f08094ab6b5aecb4c
33.068966
131
0.657136
false
false
false
false
shu223/watchOS-2-Sampler
refs/heads/master
watchOS2Sampler WatchKit Extension/AudioRecAndPlayInterfaceController.swift
mit
1
// // AudioRecAndPlayInterfaceController.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/10. // Copyright © 2015 Shuichi Tsutsumi. All rights reserved. // import WatchKit import Foundation class AudioRecAndPlayInterfaceController: WKInterfaceController { @IBOutlet weak var recLabel: WKInterfaceLabel! @IBOutlet weak var playLabel: WKInterfaceLabel! override func awake(withContext context: Any?) { super.awake(withContext: context) } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } // ========================================================================= // MARK: - Private func recFileURL() -> URL? { // Must use a shared container let fileManager = FileManager.default let container = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.shu223.watchos2sampler") // replace with your own identifier!!!! if let container = container { return container.appendingPathComponent("rec.mp4") } else { return nil } } // ========================================================================= // MARK: - Actions @IBAction func recBtnTapped() { if let recFileUrl = recFileURL() { presentAudioRecorderController( withOutputURL: recFileUrl, preset: WKAudioRecorderPreset.highQualityAudio, options: nil, completion: { (didSave, error) -> Void in print("error:\(String(describing: error))\n") self.recLabel.setText("didSave:\(didSave), error:\(String(describing: error))") }) } } @IBAction func playBtnTapped() { if let recFileUrl = recFileURL() { presentMediaPlayerController( with: recFileUrl, options: nil) { (didPlayToEnd, endTime, error) -> Void in self.playLabel.setText("didPlayToEnd:\(didPlayToEnd), endTime:\(endTime), error:\(String(describing: error))") } } } }
63005f43cebffd77d42901a00c36695c
27.641975
163
0.536207
false
false
false
false
segabor/OSCCore
refs/heads/master
Source/OSCCore/conversion/MIDI+OSCMessageArgument.swift
mit
1
// // MIDI+OSCType.swift // OSCCore // // Created by Sebestyén Gábor on 2017. 12. 30.. // extension MIDI: OSCMessageArgument { public init?(data: ArraySlice<Byte>) { let binary: [Byte] = [Byte](data) guard let flatValue = UInt32(data: binary) else { return nil } let portId = UInt8(flatValue >> 24) let status = UInt8( (flatValue >> 16) & 0xFF) let data1 = UInt8( (flatValue >> 8) & 0xFF) let data2 = UInt8(flatValue & 0xFF) self.init(portId: portId, status: status, data1: data1, data2: data2) } public var oscType: TypeTagValues { .MIDI_MESSAGE_TYPE_TAG } public var oscValue: [Byte]? { let portId: UInt32 = UInt32(self.portId) let statusByte: UInt32 = UInt32(self.status) let data1: UInt32 = UInt32(self.data1) let data2: UInt32 = UInt32(self.data2) let flatValue: UInt32 = portId << 24 | statusByte << 16 | data1 << 8 | data2 return flatValue.oscValue } public var packetSize: Int { MemoryLayout<UInt32>.size } }
21e97b3816c4342ae8b618dc68aa0087
28.081081
84
0.60316
false
false
false
false
zmeyc/GRDB.swift
refs/heads/master
Tests/GRDBTests/FetchedRecordsControllerTests.swift
mit
1
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif private class ChangesRecorder<Record: RowConvertible> { var changes: [(record: Record, change: FetchedRecordChange)] = [] var recordsBeforeChanges: [Record]! var recordsAfterChanges: [Record]! var countBeforeChanges: Int? var countAfterChanges: Int? var recordsOnFirstEvent: [Record]! var transactionExpectation: XCTestExpectation? { didSet { changes = [] recordsBeforeChanges = nil recordsAfterChanges = nil countBeforeChanges = nil countAfterChanges = nil recordsOnFirstEvent = nil } } func controllerWillChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) { recordsBeforeChanges = controller.fetchedRecords countBeforeChanges = count } /// The default implementation does nothing. func controller(_ controller: FetchedRecordsController<Record>, didChangeRecord record: Record, with change: FetchedRecordChange) { if recordsOnFirstEvent == nil { recordsOnFirstEvent = controller.fetchedRecords } changes.append((record: record, change: change)) } /// The default implementation does nothing. func controllerDidChange(_ controller: FetchedRecordsController<Record>, count: Int? = nil) { recordsAfterChanges = controller.fetchedRecords countAfterChanges = count if let transactionExpectation = transactionExpectation { transactionExpectation.fulfill() } } } private class Person : Record { var id: Int64? let name: String let email: String? let bookCount: Int? init(id: Int64? = nil, name: String, email: String? = nil) { self.id = id self.name = name self.email = email self.bookCount = nil super.init() } required init(row: Row) { id = row.value(named: "id") name = row.value(named: "name") email = row.value(named: "email") bookCount = row.value(named: "bookCount") super.init(row: row) } override class var databaseTableName: String { return "persons" } override var persistentDictionary: [String : DatabaseValueConvertible?] { return ["id": id, "name": name, "email": email] } override func didInsert(with rowID: Int64, for column: String?) { id = rowID } } private struct Book : RowConvertible { var id: Int64 var authorID: Int64 var title: String init(row: Row) { id = row.value(named: "id") authorID = row.value(named: "authorID") title = row.value(named: "title") } } class FetchedRecordsControllerTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "persons") { t in t.column("id", .integer).primaryKey() t.column("name", .text) t.column("email", .text) } try db.create(table: "books") { t in t.column("id", .integer).primaryKey() t.column("authorId", .integer).notNull().references("persons", onDelete: .cascade, onUpdate: .cascade) t.column("title", .text) } try db.create(table: "flowers") { t in t.column("id", .integer).primaryKey() t.column("name", .text) } } } func testControllerFromSQL() throws { let dbQueue = try makeDatabaseQueue() let authorId: Int64 = try dbQueue.inDatabase { db in let plato = Person(name: "Plato") try plato.insert(db) try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"]) let cervantes = Person(name: "Cervantes") try cervantes.insert(db) try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"]) return cervantes.id! } let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT * FROM books WHERE authorID = ?", arguments: [authorId]) try controller.performFetch() XCTAssertEqual(controller.fetchedRecords.count, 1) XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote") } func testControllerFromSQLWithAdapter() throws { let dbQueue = try makeDatabaseQueue() let authorId: Int64 = try dbQueue.inDatabase { db in let plato = Person(name: "Plato") try plato.insert(db) try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [plato.id, "Symposium"]) let cervantes = Person(name: "Cervantes") try cervantes.insert(db) try db.execute("INSERT INTO books (authorID, title) VALUES (?, ?)", arguments: [cervantes.id, "Don Quixote"]) return cervantes.id! } let adapter = ColumnMapping(["id": "_id", "authorId": "_authorId", "title": "_title"]) let controller = try FetchedRecordsController<Book>(dbQueue, sql: "SELECT id AS _id, authorId AS _authorId, title AS _title FROM books WHERE authorID = ?", arguments: [authorId], adapter: adapter) try controller.performFetch() XCTAssertEqual(controller.fetchedRecords.count, 1) XCTAssertEqual(controller.fetchedRecords[0].title, "Don Quixote") } func testControllerFromRequest() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try Person(name: "Plato").insert(db) try Person(name: "Cervantes").insert(db) } let request = Person.order(Column("name")) let controller = try FetchedRecordsController(dbQueue, request: request) try controller.performFetch() XCTAssertEqual(controller.fetchedRecords.count, 2) XCTAssertEqual(controller.fetchedRecords[0].name, "Cervantes") XCTAssertEqual(controller.fetchedRecords[1].name, "Plato") } func testSections() throws { let dbQueue = try makeDatabaseQueue() let arthur = Person(name: "Arthur") try dbQueue.inDatabase { db in try arthur.insert(db) } let request = Person.all() let controller = try FetchedRecordsController(dbQueue, request: request) try controller.performFetch() XCTAssertEqual(controller.sections.count, 1) XCTAssertEqual(controller.sections[0].numberOfRecords, 1) XCTAssertEqual(controller.sections[0].records.count, 1) XCTAssertEqual(controller.sections[0].records[0].name, "Arthur") XCTAssertEqual(controller.fetchedRecords.count, 1) XCTAssertEqual(controller.fetchedRecords[0].name, "Arthur") XCTAssertEqual(controller.record(at: IndexPath(indexes: [0, 0])).name, "Arthur") XCTAssertEqual(controller.indexPath(for: arthur), IndexPath(indexes: [0, 0])) } func testEmptyRequestGivesOneSection() throws { let dbQueue = try makeDatabaseQueue() let request = Person.all() let controller = try FetchedRecordsController(dbQueue, request: request) try controller.performFetch() XCTAssertEqual(controller.fetchedRecords.count, 0) // Just like NSFetchedResultsController XCTAssertEqual(controller.sections.count, 1) } func testDatabaseChangesAreNotReReflectedUntilPerformFetchAndDelegateIsSet() { // TODO: test that controller.fetchedRecords does not eventually change // after a database change. The difficulty of this test lies in the // "eventually" word. } func testSimpleInsert() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // First insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Arthur") switch recorder.changes[0].change { case .insertion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) default: XCTFail() } // Second insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 2) XCTAssertEqual(recorder.changes[0].record.name, "Barbara") switch recorder.changes[0].change { case .insertion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) default: XCTFail() } } func testSimpleUpdate() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // Insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) // First update recorder.transactionExpectation = expectation(description: "expectation") // No change should be recorded try dbQueue.inTransaction { db in try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Arthur", 1]) return .commit } // One change should be recorded try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Craig"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Barbara"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Craig") switch recorder.changes[0].change { case .update(let indexPath, let changes): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) default: XCTFail() } // Second update recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Craig"), Person(id: 2, name: "Danielle")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig", "Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Danielle"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 2) XCTAssertEqual(recorder.changes[0].record.name, "Danielle") switch recorder.changes[0].change { case .update(let indexPath, let changes): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) XCTAssertEqual(changes, ["name": "Barbara".databaseValue]) default: XCTFail() } } func testSimpleDelete() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // Insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) // First delete recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Arthur") switch recorder.changes[0].change { case .deletion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) default: XCTFail() } // Second delete recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, []) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 0) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 2) XCTAssertEqual(recorder.changes[0].record.name, "Barbara") switch recorder.changes[0].change { case .deletion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) default: XCTFail() } } func testSimpleMove() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // Insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) // Move recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Craig"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Craig"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Craig") switch recorder.changes[0].change { case .move(let indexPath, let newIndexPath, let changes): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 1])) XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) default: XCTFail() } } func testSideTableChange() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController<Person>( dbQueue, sql: ("SELECT persons.*, COUNT(books.id) AS bookCount " + "FROM persons " + "LEFT JOIN books ON books.authorId = persons.id " + "GROUP BY persons.id " + "ORDER BY persons.name")) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // Insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"]) try db.execute("INSERT INTO books (authorId, title) VALUES (?, ?)", arguments: [1, "Moby Dick"]) return .commit } waitForExpectations(timeout: 1, handler: nil) // Change books recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try db.execute("DELETE FROM books") return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.bookCount! }, [1]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.bookCount! }, [0]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Arthur") XCTAssertEqual(recorder.changes[0].record.bookCount, 0) switch recorder.changes[0].change { case .update(let indexPath, let changes): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) XCTAssertEqual(changes, ["bookCount": 1.databaseValue]) default: XCTFail() } } func testComplexChanges() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() enum EventTest { case I(String, Int) // insert string at index case M(String, Int, Int, String) // move string from index to index with changed string case D(String, Int) // delete string at index case U(String, Int, String) // update string at index with changed string func match(name: String, event: FetchedRecordChange) -> Bool { switch self { case .I(let s, let i): switch event { case .insertion(let indexPath): return s == name && i == indexPath[1] default: return false } case .M(let s, let i, let j, let c): switch event { case .move(let indexPath, let newIndexPath, let changes): return s == name && i == indexPath[1] && j == newIndexPath[1] && c == String.fromDatabaseValue(changes["name"]!)! default: return false } case .D(let s, let i): switch event { case .deletion(let indexPath): return s == name && i == indexPath[1] default: return false } case .U(let s, let i, let c): switch event { case .update(let indexPath, let changes): return s == name && i == indexPath[1] && c == String.fromDatabaseValue(changes["name"]!)! default: return false } } } } // A list of random updates. We hope to cover most cases if not all cases here. let steps: [(word: String, events: [EventTest])] = [ (word: "B", events: [.I("B",0)]), (word: "BA", events: [.I("A",0)]), (word: "ABF", events: [.M("B",0,1,"A"), .M("A",1,0,"B"), .I("F",2)]), (word: "AB", events: [.D("F",2)]), (word: "A", events: [.D("B",1)]), (word: "C", events: [.U("C",0,"A")]), (word: "", events: [.D("C",0)]), (word: "C", events: [.I("C",0)]), (word: "CD", events: [.I("D",1)]), (word: "B", events: [.D("D",1), .U("B",0,"C")]), (word: "BCAEFD", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), (word: "CADBE", events: [.M("A",2,0,"C"), .D("D",3), .M("C",1,2,"B"), .M("B",4,1,"E"), .M("D",0,3,"A"), .M("E",5,4,"F")]), (word: "EB", events: [.D("B",1), .D("D",3), .D("E",4), .M("E",2,1,"C"), .U("B",0,"A")]), (word: "BEC", events: [.I("C",1), .M("B",1,0,"E"), .M("E",0,2,"B")]), (word: "AB", events: [.D("C",1), .M("B",2,1,"E"), .U("A",0,"B")]), (word: "ADEFCB", events: [.I("B",1), .I("C",2), .I("E",4), .M("D",1,3,"B"), .I("F",5)]), (word: "DA", events: [.D("B",1), .D("C",2), .D("E",4), .M("A",3,0,"D"), .D("F",5), .M("D",0,1,"A")]), (word: "BACEF", events: [.I("C",2), .I("E",3), .I("F",4), .U("B",1,"D")]), (word: "BACD", events: [.D("F",4), .U("D",3,"E")]), (word: "EABDFC", events: [.M("B",2,1,"C"), .I("C",2), .M("E",1,4,"B"), .I("F",5)]), (word: "CAB", events: [.D("C",2), .D("D",3), .D("F",5), .M("C",4,2,"E")]), (word: "CBAD", events: [.M("A",1,0,"B"), .M("B",0,1,"A"), .I("D",3)]), (word: "BAC", events: [.M("A",1,0,"B"), .M("B",2,1,"C"), .D("D",3), .M("C",0,2,"A")]), (word: "CBEADF", events: [.I("A",0), .M("B",0,1,"A"), .I("D",3), .M("C",1,2,"B"), .M("E",2,4,"C"), .I("F",5)]), (word: "CBA", events: [.D("A",0), .D("D",3), .M("A",4,0,"E"), .D("F",5)]), (word: "CBDAF", events: [.I("A",0), .M("D",0,3,"A"), .I("F",4)]), (word: "B", events: [.D("A",0), .D("B",1), .D("D",3), .D("F",4), .M("B",2,0,"C")]), (word: "BDECAF", events: [.I("A",0), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), (word: "ABCDEF", events: [.M("A",1,0,"B"), .M("B",3,1,"D"), .M("D",2,3,"C"), .M("C",4,2,"E"), .M("E",0,4,"A")]), (word: "ADBCF", events: [.M("B",2,1,"C"), .M("C",3,2,"D"), .M("D",1,3,"B"), .D("F",5), .U("F",4,"E")]), (word: "A", events: [.D("B",1), .D("C",2), .D("D",3), .D("F",4)]), (word: "AEBDCF", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4), .I("F",5)]), (word: "B", events: [.D("B",1), .D("C",2), .D("D",3), .D("E",4), .D("F",5), .U("B",0,"A")]), (word: "ABCDF", events: [.I("B",1), .I("C",2), .I("D",3), .I("F",4), .U("A",0,"B")]), (word: "CAB", events: [.M("A",1,0,"B"), .D("D",3), .M("B",2,1,"C"), .D("F",4), .M("C",0,2,"A")]), (word: "AC", events: [.D("B",1), .M("A",2,0,"C"), .M("C",0,1,"A")]), (word: "DABC", events: [.I("B",1), .I("C",2), .M("A",1,0,"C"), .M("D",0,3,"A")]), (word: "BACD", events: [.M("C",1,2,"B"), .M("B",3,1,"D"), .M("D",2,3,"C")]), (word: "D", events: [.D("A",0), .D("C",2), .D("D",3), .M("D",1,0,"B")]), (word: "CABDFE", events: [.I("A",0), .I("B",1), .I("D",3), .I("E",4), .M("C",0,2,"D"), .I("F",5)]), (word: "BACDEF", events: [.M("B",2,1,"C"), .M("C",1,2,"B"), .M("E",5,4,"F"), .M("F",4,5,"E")]), (word: "AB", events: [.D("C",2), .D("D",3), .D("E",4), .M("A",1,0,"B"), .D("F",5), .M("B",0,1,"A")]), (word: "BACDE", events: [.I("C",2), .M("B",0,1,"A"), .I("D",3), .M("A",1,0,"B"), .I("E",4)]), (word: "E", events: [.D("A",0), .D("C",2), .D("D",3), .D("E",4), .M("E",1,0,"B")]), (word: "A", events: [.U("A",0,"E")]), (word: "ABCDE", events: [.I("B",1), .I("C",2), .I("D",3), .I("E",4)]), (word: "BA", events: [.D("C",2), .D("D",3), .M("A",1,0,"B"), .D("E",4), .M("B",0,1,"A")]), (word: "A", events: [.D("A",0), .M("A",1,0,"B")]), (word: "CAB", events: [.I("A",0), .I("B",1), .M("C",0,2,"A")]), (word: "EA", events: [.D("B",1), .M("E",2,1,"C")]), (word: "B", events: [.D("A",0), .M("B",1,0,"E")]), ] for step in steps { recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, step.word.characters.enumerated().map { Person(id: Int64($0), name: String($1)) }) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.changes.count, step.events.count) for (change, event) in zip(recorder.changes, step.events) { XCTAssertTrue(event.match(name: change.record.name, event: change.change)) } } } func testExternalTableChange() { // TODO: test that delegate is not notified after a database change in a // table not involved in the fetch request. The difficulty of this test // lies in the "not" word. } func testCustomRecordIdentity() { // TODO: test record comparison not based on primary key but based on // custom function } func testRequestChange() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) try controller.performFetch() // Insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) // Change request with Request recorder.transactionExpectation = expectation(description: "expectation") try controller.setRequest(Person.order(Column("name").desc)) waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Arthur"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 2) XCTAssertEqual(recorder.changes[0].record.name, "Barbara") switch recorder.changes[0].change { case .move(let indexPath, let newIndexPath, let changes): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0])) XCTAssertTrue(changes.isEmpty) default: XCTFail() } // Change request with SQL and arguments recorder.transactionExpectation = expectation(description: "expectation") try controller.setRequest(sql: "SELECT ? AS id, ? AS name", arguments: [1, "Craig"]) waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara", "Arthur"]) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig"]) XCTAssertEqual(recorder.changes.count, 2) XCTAssertEqual(recorder.changes[0].record.id, 2) XCTAssertEqual(recorder.changes[0].record.name, "Barbara") XCTAssertEqual(recorder.changes[1].record.id, 1) XCTAssertEqual(recorder.changes[1].record.name, "Craig") switch recorder.changes[0].change { case .deletion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) default: XCTFail() } switch recorder.changes[1].change { case .move(let indexPath, let newIndexPath, let changes): // TODO: is it really what we should expect? Wouldn't an update fit better? // What does UITableView think? XCTAssertEqual(indexPath, IndexPath(indexes: [0, 1])) XCTAssertEqual(newIndexPath, IndexPath(indexes: [0, 0])) XCTAssertEqual(changes, ["name": "Arthur".databaseValue]) default: XCTFail() } // Change request with a different set of tracked columns recorder.transactionExpectation = expectation(description: "expectation") try controller.setRequest(Person.select(Column("id"), Column("name"), Column("email")).order(Column("name"))) waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig"]) XCTAssertEqual(recorder.recordsAfterChanges.count, 2) XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"]) recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try db.execute("UPDATE persons SET email = ? WHERE name = ?", arguments: ["[email protected]", "Arthur"]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsAfterChanges.count, 2) XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"]) recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try db.execute("UPDATE PERSONS SET EMAIL = ? WHERE NAME = ?", arguments: ["[email protected]", "Barbara"]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 2) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.recordsAfterChanges.count, 2) XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"]) } func testSetCallbacksAfterUpdate() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) let recorder = ChangesRecorder<Person>() try controller.performFetch() // Insert try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur")]) return .commit } // Set callbacks recorder.transactionExpectation = expectation(description: "expectation") controller.trackChanges( willChange: { recorder.controllerWillChange($0) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { recorder.controllerDidChange($0) }) waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1) XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.changes.count, 1) XCTAssertEqual(recorder.changes[0].record.id, 1) XCTAssertEqual(recorder.changes[0].record.name, "Arthur") switch recorder.changes[0].change { case .insertion(let indexPath): XCTAssertEqual(indexPath, IndexPath(indexes: [0, 0])) default: XCTFail() } } func testTrailingClosureCallback() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("name"))) var persons: [Person] = [] try controller.performFetch() let expectation = self.expectation(description: "expectation") controller.trackChanges { persons = $0.fetchedRecords expectation.fulfill() } try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(persons.map { $0.name }, ["Arthur"]) } func testFetchAlongside() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.order(Column("id"))) let recorder = ChangesRecorder<Person>() controller.trackChanges( fetchAlongside: { db in try Person.fetchCount(db) }, willChange: { (controller, count) in recorder.controllerWillChange(controller, count: count) }, onChange: { (controller, record, change) in recorder.controller(controller, didChangeRecord: record, with: change) }, didChange: { (controller, count) in recorder.controllerDidChange(controller, count: count) }) try controller.performFetch() // First insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 0) XCTAssertEqual(recorder.recordsAfterChanges.count, 1) XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.countBeforeChanges!, 1) XCTAssertEqual(recorder.countAfterChanges!, 1) // Second insert recorder.transactionExpectation = expectation(description: "expectation") try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur"), Person(id: 2, name: "Barbara")]) return .commit } waitForExpectations(timeout: 1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 1) XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"]) XCTAssertEqual(recorder.recordsAfterChanges.count, 2) XCTAssertEqual(recorder.recordsAfterChanges.map { $0.name }, ["Arthur", "Barbara"]) XCTAssertEqual(recorder.countBeforeChanges!, 2) XCTAssertEqual(recorder.countAfterChanges!, 2) } func testFetchErrors() throws { let dbQueue = try makeDatabaseQueue() let controller = try FetchedRecordsController(dbQueue, request: Person.all()) let expectation = self.expectation(description: "expectation") var error: Error? controller.trackErrors { error = $1 expectation.fulfill() } controller.trackChanges { _ in } try controller.performFetch() try dbQueue.inTransaction { db in try synchronizePersons(db, [ Person(id: 1, name: "Arthur")]) try db.drop(table: "persons") return .commit } waitForExpectations(timeout: 1, handler: nil) if let error = error as? DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, "no such table: persons") XCTAssertEqual(error.sql!, "SELECT * FROM \"persons\"") XCTAssertEqual(error.description, "SQLite error 1 with statement `SELECT * FROM \"persons\"`: no such table: persons") } else { XCTFail("Expected DatabaseError") } } } // Synchronizes the persons table with a JSON payload private func synchronizePersons(_ db: Database, _ newPersons: [Person]) throws { // Sort new persons and database persons by id: let newPersons = newPersons.sorted { $0.id! < $1.id! } let databasePersons = try Person.fetchAll(db, "SELECT * FROM persons ORDER BY id") // Now that both lists are sorted by id, we can compare them with // the sortedMerge() function. // // We'll delete, insert or update persons, depending on their presence // in either lists. for mergeStep in sortedMerge( left: databasePersons, right: newPersons, leftKey: { $0.id! }, rightKey: { $0.id! }) { switch mergeStep { case .left(let databasePerson): try databasePerson.delete(db) case .right(let newPerson): try newPerson.insert(db) case .common(_, let newPerson): try newPerson.update(db) } } } /// Given two sorted sequences (left and right), this function emits "merge steps" /// which tell whether elements are only found on the left, on the right, or on /// both sides. /// /// Both sequences do not have to share the same element type. Yet elements must /// share a common comparable *key*. /// /// Both sequences must be sorted by this key. /// /// Keys must be unique in both sequences. /// /// The example below compare two sequences sorted by integer representation, /// and prints: /// /// - Left: 1 /// - Common: 2, 2 /// - Common: 3, 3 /// - Right: 4 /// /// for mergeStep in sortedMerge( /// left: [1,2,3], /// right: ["2", "3", "4"], /// leftKey: { $0 }, /// rightKey: { Int($0)! }) /// { /// switch mergeStep { /// case .left(let left): /// print("- Left: \(left)") /// case .right(let right): /// print("- Right: \(right)") /// case .common(let left, let right): /// print("- Common: \(left), \(right)") /// } /// } /// /// - parameters: /// - left: The left sequence. /// - right: The right sequence. /// - leftKey: A function that returns the key of a left element. /// - rightKey: A function that returns the key of a right element. /// - returns: A sequence of MergeStep private func sortedMerge<LeftSequence: Sequence, RightSequence: Sequence, Key: Comparable>( left lSeq: LeftSequence, right rSeq: RightSequence, leftKey: @escaping (LeftSequence.Iterator.Element) -> Key, rightKey: @escaping (RightSequence.Iterator.Element) -> Key) -> AnySequence<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> { return AnySequence { () -> AnyIterator<MergeStep<LeftSequence.Iterator.Element, RightSequence.Iterator.Element>> in var (lGen, rGen) = (lSeq.makeIterator(), rSeq.makeIterator()) var (lOpt, rOpt) = (lGen.next(), rGen.next()) return AnyIterator { switch (lOpt, rOpt) { case (let lElem?, let rElem?): let (lKey, rKey) = (leftKey(lElem), rightKey(rElem)) if lKey > rKey { rOpt = rGen.next() return .right(rElem) } else if lKey == rKey { (lOpt, rOpt) = (lGen.next(), rGen.next()) return .common(lElem, rElem) } else { lOpt = lGen.next() return .left(lElem) } case (nil, let rElem?): rOpt = rGen.next() return .right(rElem) case (let lElem?, nil): lOpt = lGen.next() return .left(lElem) case (nil, nil): return nil } } } } /** Support for sortedMerge() */ private enum MergeStep<LeftElement, RightElement> { /// An element only found in the left sequence: case left(LeftElement) /// An element only found in the right sequence: case right(RightElement) /// Left and right elements share a common key: case common(LeftElement, RightElement) }
03a07ba56c46aae3a491b4ee91866ddc
44.269697
204
0.581766
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Characteristics/Characteristic.AdministratorOnlyAccess.swift
mit
1
import Foundation public extension AnyCharacteristic { static func administratorOnlyAccess( _ value: Bool = false, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Administrator Only Access", format: CharacteristicFormat? = .bool, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.administratorOnlyAccess( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func administratorOnlyAccess( _ value: Bool = false, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Administrator Only Access", format: CharacteristicFormat? = .bool, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Bool> { GenericCharacteristic<Bool>( type: .administratorOnlyAccess, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
2ce9a86ce3d92c82535f5895c96a3af4
33.737705
75
0.588957
false
false
false
false
vulgur/WeeklyFoodPlan
refs/heads/master
WeeklyFoodPlan/WeeklyFoodPlan/Models/Managers/DailyPlanManager.swift
mit
1
// // DailyPlanManager.swift // WeeklyFoodPlan // // Created by vulgur on 2017/3/3. // Copyright © 2017年 MAD. All rights reserved. // import Foundation import RealmSwift class DailyPlanManager { static let shared = DailyPlanManager() let realm = try! Realm() func fakePlan() -> DailyPlan { let breakfastObject = realm.objects(WhenObject.self).first { (when) -> Bool in when.value == Food.When.breakfast.rawValue } let lunchObject = realm.objects(WhenObject.self).first { (when) -> Bool in when.value == Food.When.lunch.rawValue } let dinnerObject = realm.objects(WhenObject.self).first { (when) -> Bool in when.value == Food.When.dinner.rawValue } let breakfastResults = realm.objects(Food.self).filter("%@ IN whenObjects", breakfastObject!) let lunchResults = realm.objects(Food.self).filter("%@ IN whenObjects", lunchObject!) let dinnerResults = realm.objects(Food.self).filter("%@ IN whenObjects", dinnerObject!) let plan = DailyPlan() plan.date = Date() let breakfastMeal = Meal() breakfastMeal.name = Food.When.breakfast.rawValue let randomBreakfastList = breakfastResults.shuffled() for i in 0..<2 { let food = randomBreakfastList[i] let breakfast = MealFood(food: food) BaseManager.shared.transaction { food.addNeedIngredientCount() } breakfastMeal.mealFoods.append(breakfast) } let lunchMeal = Meal() lunchMeal.name = Food.When.lunch.rawValue let randomLunchList = lunchResults.shuffled() for i in 0..<2 { let food = randomLunchList[i] let lunch = MealFood(food: food) BaseManager.shared.transaction { food.addNeedIngredientCount() } lunchMeal.mealFoods.append(lunch) } let dinnerMeal = Meal() dinnerMeal.name = Food.When.dinner.rawValue let randomDinnerList = dinnerResults.shuffled() for i in 0..<2 { let food = randomDinnerList[i] let dinner = MealFood(food: food) BaseManager.shared.transaction { food.addNeedIngredientCount() } dinnerMeal.mealFoods.append(dinner) } plan.meals.append(breakfastMeal) plan.meals.append(lunchMeal) plan.meals.append(dinnerMeal) return plan } }
f55b16fa9a10c61ea7c077d8697973e5
32.584416
101
0.588167
false
false
false
false
freak4pc/netfox
refs/heads/master
netfox/Core/NFXHTTPModelManager.swift
mit
1
// // NFXHTTPModelManager.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // import Foundation private let _sharedInstance = NFXHTTPModelManager() final class NFXHTTPModelManager: NSObject { static let sharedInstance = NFXHTTPModelManager() fileprivate var models = [NFXHTTPModel]() private let syncQueue = DispatchQueue(label: "NFXSyncQueue") func add(_ obj: NFXHTTPModel) { syncQueue.async { self.models.insert(obj, at: 0) NotificationCenter.default.post(name: NSNotification.Name.NFXAddedModel, object: obj) } } func clear() { syncQueue.async { self.models.removeAll() NotificationCenter.default.post(name: NSNotification.Name.NFXClearedModels, object: nil) } } func getModels() -> [NFXHTTPModel] { var predicates = [NSPredicate]() let filterValues = NFX.sharedInstance().getCachedFilters() let filterNames = HTTPModelShortType.allValues var index = 0 for filterValue in filterValues { if filterValue { let filterName = filterNames[index].rawValue let predicate = NSPredicate(format: "shortType == '\(filterName)'") predicates.append(predicate) } index += 1 } let searchPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: predicates) let array = (self.models as NSArray).filtered(using: searchPredicate) return array as! [NFXHTTPModel] } }
3f952326f099b81fc4290698e067bedc
27
100
0.611453
false
false
false
false
AdaptiveMe/adaptive-arp-api-lib-darwin
refs/heads/master
Pod/Classes/Sources.Api/RotationEvent.swift
apache-2.0
1
/** --| 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.2.15 -------------------------------------------| aut inveniam viam aut faciam |-------------------------------------------- */ import Foundation /** Object for reporting orientation change events for device and display. @author Carlos Lozano Diez @since v2.0.5 @version 1.0 */ public class RotationEvent : APIBean { /** The orientation we're rotating to. This is the future orientation when the state of the event is WillStartRotation. This will be the current orientation when the rotation is finished with the state DidFinishRotation. */ var destination : ICapabilitiesOrientation? /** The orientation we're rotating from. This is the current orientation when the state of the event is WillStartRotation. This will be the previous orientation when the rotation is finished with the state DidFinishRotation. */ var origin : ICapabilitiesOrientation? /** The state of the event to indicate the start of the rotation and the end of the rotation event. This allows for functions to be pre-emptively performed (veto change, re-layout, etc.) before rotation is effected and concluded. */ var state : RotationEventState? /** The timestamps in milliseconds when the event was fired. */ var timestamp : Int64? /** Default constructor. @since v2.0.5 */ public override init() { super.init() } /** Convenience constructor. @param origin Source orientation when the event was fired. @param destination Destination orientation when the event was fired. @param state State of the event (WillBegin, DidFinish). @param timestamp Timestamp in milliseconds when the event was fired. @since v2.0.5 */ public init(origin: ICapabilitiesOrientation, destination: ICapabilitiesOrientation, state: RotationEventState, timestamp: Int64) { super.init() self.origin = origin self.destination = destination self.state = state self.timestamp = timestamp } /** Gets the destination orientation of the event. @return Destination orientation. @since v2.0.5 */ public func getDestination() -> ICapabilitiesOrientation? { return self.destination } /** Sets the destination orientation of the event. @param destination Destination orientation. @since v2.0.5 */ public func setDestination(destination: ICapabilitiesOrientation) { self.destination = destination } /** Get the origin orientation of the event. @return Origin orientation. @since v2.0.5 */ public func getOrigin() -> ICapabilitiesOrientation? { return self.origin } /** Set the origin orientation of the event. @param origin Origin orientation @since v2.0.5 */ public func setOrigin(origin: ICapabilitiesOrientation) { self.origin = origin } /** Gets the current state of the event. @return State of the event. @since v2.0.5 */ public func getState() -> RotationEventState? { return self.state } /** Sets the current state of the event. @param state The state of the event. @since v2.0.5 */ public func setState(state: RotationEventState) { self.state = state } /** Gets the timestamp in milliseconds of the event. @return Timestamp of the event. @since v2.0.5 */ public func getTimestamp() -> Int64? { return self.timestamp } /** Sets the timestamp in milliseconds of the event. @param timestamp Timestamp of the event. @since v2.0.5 */ public func setTimestamp(timestamp: Int64) { self.timestamp = timestamp } /** JSON Serialization and deserialization support. */ public struct Serializer { public static func fromJSON(json : String) -> RotationEvent { let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)! let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary return fromDictionary(dict!) } static func fromDictionary(dict : NSDictionary) -> RotationEvent { let resultObject : RotationEvent = RotationEvent() if let value : AnyObject = dict.objectForKey("destination") { if "\(value)" as NSString != "<null>" { resultObject.destination = ICapabilitiesOrientation.toEnum(((value as! NSDictionary)["value"]) as? String) } } if let value : AnyObject = dict.objectForKey("origin") { if "\(value)" as NSString != "<null>" { resultObject.origin = ICapabilitiesOrientation.toEnum(((value as! NSDictionary)["value"]) as? String) } } if let value : AnyObject = dict.objectForKey("state") { if "\(value)" as NSString != "<null>" { resultObject.state = RotationEventState.toEnum(((value as! NSDictionary)["value"]) as? String) } } if let value : AnyObject = dict.objectForKey("timestamp") { if "\(value)" as NSString != "<null>" { let numValue = value as? NSNumber resultObject.timestamp = numValue?.longLongValue } } return resultObject } public static func toJSON(object: RotationEvent) -> String { let jsonString : NSMutableString = NSMutableString() // Start Object to JSON jsonString.appendString("{ ") // Fields. object.destination != nil ? jsonString.appendString("\"destination\": { \"value\": \"\(object.destination!.toString())\"}, ") : jsonString.appendString("\"destination\": null, ") object.origin != nil ? jsonString.appendString("\"origin\": { \"value\": \"\(object.origin!.toString())\"}, ") : jsonString.appendString("\"origin\": null, ") object.state != nil ? jsonString.appendString("\"state\": { \"value\": \"\(object.state!.toString())\"}, ") : jsonString.appendString("\"state\": null, ") object.timestamp != nil ? jsonString.appendString("\"timestamp\": \(object.timestamp!)") : jsonString.appendString("\"timestamp\": null") // End Object to JSON jsonString.appendString(" }") return jsonString as String } } } /** ------------------------------------| Engineered with ♥ in Barcelona, Catalonia |-------------------------------------- */
3cbf8226eb50453b48f4c1242a5b61bd
32.552743
190
0.603873
false
false
false
false
silt-lang/silt
refs/heads/master
Sources/Lithosphere/DiagnosticConsumer.swift
mit
1
//===---------- DiagnosticConsumer.swift - Diagnostic Consumer ------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 // //===----------------------------------------------------------------------===// // This file provides the DiagnosticConsumer protocol. //===----------------------------------------------------------------------===// // // This file contains modifications from the Silt Langauge project. These // modifications are released under the MIT license, a copy of which is // available in the repository. // //===----------------------------------------------------------------------===// /// An object that intends to receive notifications when diagnostics are /// emitted. public protocol DiagnosticConsumer { /// Handle the provided diagnostic which has just been registered with the /// DiagnosticEngine. func handle(_ diagnostic: Diagnostic) /// Finalize the consumption of diagnostics, flushing to disk if necessary. func finalize() }
ee74b6b8bc83c0e719baf4d76274035c
41.8
80
0.598131
false
false
false
false
mzyy94/TesSoMe
refs/heads/master
TesSoMe/SearchViewController.swift
gpl-3.0
1
// // SearchViewController.swift // TesSoMe // // Created by Yuki Mizuno on 2014/10/03. // Copyright (c) 2014年 Yuki Mizuno. All rights reserved. // import UIKit class SearchValue: NSObject { enum SearchTarget { case User, Post, Reply, Hashtag } let formatString: [SearchTarget: String] = [ .User: NSLocalizedString("Go to user \"%@\"", comment: "Search user format"), .Post: NSLocalizedString("Post by \"%@\"", comment: "Search post format"), .Reply: NSLocalizedString("Reply to @%@", comment: "Search reply format"), .Hashtag: NSLocalizedString("Hashtag #%@", comment: "Search hashtag format") ] var target: SearchTarget var words: [String] = [] var formatedString: String init(target t: SearchTarget, words w: String) { target = t words.append(w) formatedString = NSString(format: formatString[t]!, w) } class func matchUsernameFormat(string: String) -> Bool { return string.rangeOfString("^@?[0-9a-z]{1,16}$", options: .RegularExpressionSearch) != nil } class func matchHashtagFormat(string: String) -> Bool { return string.rangeOfString("^#?[0-9a-zA-Z]{1,1023}$", options: .RegularExpressionSearch) != nil } func setSearchValue(inout resultView: SearchResultViewController, withType type: TesSoMeSearchType) { switch target { case .Post: resultView.username = words.first case .Reply: resultView.tag = "at_\(words.first!)" case .Hashtag: resultView.tag = "hash_\(words.first!)" default: return } resultView.type = type } } class SearchViewController: UITableViewController, UISearchBarDelegate { var searchBookmark: [String] = [] var searchWords: [SearchValue] = [] @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var searchTypeSegmentedControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() self.searchBar.delegate = self self.navigationItem.rightBarButtonItem = self.editButtonItem() let inputAccessoryView = UIToolbar() inputAccessoryView.barStyle = .Default inputAccessoryView.sizeToFit() let spacer = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) let doneBtn = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: Selector("closeKeyboard")) let toolBarItems:[UIBarButtonItem] = [spacer, doneBtn] inputAccessoryView.setItems(toolBarItems, animated: true) self.searchBar.inputAccessoryView = inputAccessoryView } func closeKeyboard() { self.searchBar.endEditing(true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { let searchWords = searchText.componentsSeparatedByString(" ") switch searchWords.count { case 0: self.searchWords.removeAll(keepCapacity: true) case 1: self.searchWords.removeAll(keepCapacity: true) if let searchWord = searchWords.first { if SearchValue.matchUsernameFormat(searchWord) { self.searchWords.append(SearchValue(target: .User, words: searchWord)) self.searchWords.append(SearchValue(target: .Post, words: searchWord)) self.searchWords.append(SearchValue(target: .Reply, words: searchWord)) } if SearchValue.matchHashtagFormat(searchWord) { self.searchWords.append(SearchValue(target: .Hashtag, words: searchWord)) } } default: return } self.tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: .None) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. switch section { case 0: return searchWords.count default: return searchBookmark.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SearchBtnCell", forIndexPath: indexPath) as UITableViewCell switch indexPath.section { case 0: let searchValue = searchWords[indexPath.row] cell.textLabel?.text = searchValue.formatedString return cell default: return cell } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return indexPath.section == 1 } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return nil } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0.0 } return 44.0 } override func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 1 { return NSLocalizedString("Bookmark", comment: "Bookmark") } return nil } /* // Override to support editing the table view. override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) { } */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if searchWords[indexPath.row].target == .User { let storyboard = UIStoryboard(name: "Main", bundle: nil) let userViewController = storyboard.instantiateViewControllerWithIdentifier("UserView") as UserViewController userViewController.username = searchWords[indexPath.row].words.first! self.navigationController?.pushViewController(userViewController, animated: true) closeKeyboard() } } override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool { let indexPath = tableView.indexPathForCell(sender as UITableViewCell)! if searchWords[indexPath.row].target == .User { return false } return true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let indexPath = tableView.indexPathForCell(sender as UITableViewCell)! if indexPath.section == 0 { let searchValue = searchWords[indexPath.row] let type = TesSoMeSearchType(rawValue: self.searchTypeSegmentedControl.selectedSegmentIndex - 1)! var resultView = segue.destinationViewController as SearchResultViewController searchValue.setSearchValue(&resultView, withType: type) } closeKeyboard() } }
75abca7dab2a8f7f521e6e6d43f79be1
32.278261
159
0.7208
false
false
false
false
lukesutton/olpej
refs/heads/master
Olpej/Olpej/Property.swift
mit
1
import Foundation public protocol PropertyType: Hashable { var hashValue: Int { get } } public enum PropertyAction { case remove case update } public struct Property<View: UIView>: PropertyType, Equatable, Hashable { public let tag: String public let hashValue: Int public let update: (ComponentIdentifier<View>, PropertyAction, View) -> Void public init(_ tag: String, _ hashValue: Int, update: (ComponentIdentifier<View>, PropertyAction, View) -> Void) { self.tag = tag self.hashValue = hashValue self.update = update } } public func ==<A, B>(lhs: Property<A>, rhs: Property<B>) -> Bool { return false } public func ==<A>(lhs: Property<A>, rhs: Property<A>) -> Bool { return lhs.tag == rhs.tag && lhs.hashValue == rhs.hashValue }
2d73f8f03b62e869744005db8fa7379f
25.866667
117
0.66005
false
false
false
false
mokriya/tvos-sample-mokriyans
refs/heads/master
TVSample/App/TVSample/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // TVSample // // Created by Diogo Brito on 01/10/15. // Copyright © 2015 Mokriya. All rights reserved. // import UIKit import TVMLKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate { var window: UIWindow? var appController: TVApplicationController? static let BaseURL = "http://localhost:1906/" static let BootURL = "\(BaseURL)js/application.js" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) // Create Controller Context let appControllerContext = TVApplicationControllerContext() //Create the NSURL for the landing javascript path guard let javaScriptURL = NSURL(string: AppDelegate.BootURL) else { fatalError("unable to create NSURL") } //Set the javascript path and base url appControllerContext.javaScriptApplicationURL = javaScriptURL appControllerContext.launchOptions["BASEURL"] = AppDelegate.BaseURL //Create the controller appController = TVApplicationController(context: appControllerContext, window: window, delegate: self) return true } }
b879edaa639f89dd4353d1c2c858ebae
30.204545
127
0.685361
false
false
false
false
haranicle/MemoryLeaks
refs/heads/master
MemoryLeaks/SwiftObject.swift
apache-2.0
1
// // SwiftObject.swift // MemoryLeaks // // Created by kazushi.hara on 2015/11/11. // Copyright © 2015年 haranicle. All rights reserved. // import UIKit class SwiftObject: NSObject { var title = "Swift Object" var completion:(()->())? override init() { super.init() } // リークしない func doSomethingAsync() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in print(self.title) } } // selfがリークする func doSomething() { completion = { () in print(self.title) } completion?() // completion = nil // これがあるとちゃんとreleaseされていることになる } // リークしない func doSomethingWithWeakSelf() { weak var weakSelf = self completion = {() in print(weakSelf!.title) } completion?() } // リークしない func doSomethingWithCaptureList() { completion = {[weak self] () in print(self!.title) } completion?() } }
f29b0562efed1dd6fcb34d5d43316f79
19.480769
101
0.533333
false
false
false
false
lyft/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Rules/ColonRule.swift
mit
1
import Foundation import SourceKittenFramework private enum ColonKind { case type case dictionary case functionCall } public struct ColonRule: CorrectableRule, ConfigurationProviderRule { public var configuration = ColonConfiguration() public init() {} public static let description = RuleDescription( identifier: "colon", name: "Colon", description: "Colons should be next to the identifier when specifying a type " + "and next to the key in dictionary literals.", kind: .style, nonTriggeringExamples: [ "let abc: Void\n", "let abc: [Void: Void]\n", "let abc: (Void, Void)\n", "let abc: ([Void], String, Int)\n", "let abc: [([Void], String, Int)]\n", "let abc: String=\"def\"\n", "let abc: Int=0\n", "let abc: Enum=Enum.Value\n", "func abc(def: Void) {}\n", "func abc(def: Void, ghi: Void) {}\n", "// 周斌佳年周斌佳\nlet abc: String = \"abc:\"", "let abc = [Void: Void]()\n", "let abc = [1: [3: 2], 3: 4]\n", "let abc = [\"string\": \"string\"]\n", "let abc = [\"string:string\": \"string\"]\n", "let abc: [String: Int]\n", "func foo(bar: [String: Int]) {}\n", "func foo() -> [String: Int] { return [:] }\n", "let abc: Any\n", "let abc: [Any: Int]\n", "let abc: [String: Any]\n", "class Foo: Bar {}\n", "class Foo<T: Equatable> {}\n", "switch foo {\n" + "case .bar:\n" + " _ = something()\n" + "}\n", "object.method(x: 5, y: \"string\")\n", "object.method(x: 5, y:\n" + " \"string\")", "object.method(5, y: \"string\")\n", "func abc() { def(ghi: jkl) }", "func abc(def: Void) { ghi(jkl: mno) }", "class ABC { let def = ghi(jkl: mno) } }", "func foo() { let dict = [1: 1] }" ], triggeringExamples: [ "let ↓abc:Void\n", "let ↓abc: Void\n", "let ↓abc :Void\n", "let ↓abc : Void\n", "let ↓abc : [Void: Void]\n", "let ↓abc : (Void, String, Int)\n", "let ↓abc : ([Void], String, Int)\n", "let ↓abc : [([Void], String, Int)]\n", "let ↓abc: (Void, String, Int)\n", "let ↓abc: ([Void], String, Int)\n", "let ↓abc: [([Void], String, Int)]\n", "let ↓abc :String=\"def\"\n", "let ↓abc :Int=0\n", "let ↓abc :Int = 0\n", "let ↓abc:Int=0\n", "let ↓abc:Int = 0\n", "let ↓abc:Enum=Enum.Value\n", "func abc(↓def:Void) {}\n", "func abc(↓def: Void) {}\n", "func abc(↓def :Void) {}\n", "func abc(↓def : Void) {}\n", "func abc(def: Void, ↓ghi :Void) {}\n", "let abc = [Void↓:Void]()\n", "let abc = [Void↓ : Void]()\n", "let abc = [Void↓: Void]()\n", "let abc = [Void↓ : Void]()\n", "let abc = [1: [3↓ : 2], 3: 4]\n", "let abc = [1: [3↓ : 2], 3↓: 4]\n", "let abc: [↓String : Int]\n", "let abc: [↓String:Int]\n", "func foo(bar: [↓String : Int]) {}\n", "func foo(bar: [↓String:Int]) {}\n", "func foo() -> [↓String : Int] { return [:] }\n", "func foo() -> [↓String:Int] { return [:] }\n", "let ↓abc : Any\n", "let abc: [↓Any : Int]\n", "let abc: [↓String : Any]\n", "class ↓Foo : Bar {}\n", "class ↓Foo:Bar {}\n", "class Foo<↓T:Equatable> {}\n", "class Foo<↓T : Equatable> {}\n", "object.method(x: 5, y↓ : \"string\")\n", "object.method(x↓:5, y: \"string\")\n", "object.method(x↓: 5, y: \"string\")\n", "func abc() { def(ghi↓:jkl) }", "func abc(def: Void) { ghi(jkl↓:mno) }", "class ABC { let def = ghi(jkl↓:mno) } }", "func foo() { let dict = [1↓ : 1] }" ], corrections: [ "let ↓abc:Void\n": "let abc: Void\n", "let ↓abc: Void\n": "let abc: Void\n", "let ↓abc :Void\n": "let abc: Void\n", "let ↓abc : Void\n": "let abc: Void\n", "let ↓abc : [Void: Void]\n": "let abc: [Void: Void]\n", "let ↓abc : (Void, String, Int)\n": "let abc: (Void, String, Int)\n", "let ↓abc : ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n", "let ↓abc : [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n", "let ↓abc: (Void, String, Int)\n": "let abc: (Void, String, Int)\n", "let ↓abc: ([Void], String, Int)\n": "let abc: ([Void], String, Int)\n", "let ↓abc: [([Void], String, Int)]\n": "let abc: [([Void], String, Int)]\n", "let ↓abc :String=\"def\"\n": "let abc: String=\"def\"\n", "let ↓abc :Int=0\n": "let abc: Int=0\n", "let ↓abc :Int = 0\n": "let abc: Int = 0\n", "let ↓abc:Int=0\n": "let abc: Int=0\n", "let ↓abc:Int = 0\n": "let abc: Int = 0\n", "let ↓abc:Enum=Enum.Value\n": "let abc: Enum=Enum.Value\n", "func abc(↓def:Void) {}\n": "func abc(def: Void) {}\n", "func abc(↓def: Void) {}\n": "func abc(def: Void) {}\n", "func abc(↓def :Void) {}\n": "func abc(def: Void) {}\n", "func abc(↓def : Void) {}\n": "func abc(def: Void) {}\n", "func abc(def: Void, ↓ghi :Void) {}\n": "func abc(def: Void, ghi: Void) {}\n", "let abc = [Void↓:Void]()\n": "let abc = [Void: Void]()\n", "let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n", "let abc = [Void↓: Void]()\n": "let abc = [Void: Void]()\n", "let abc = [Void↓ : Void]()\n": "let abc = [Void: Void]()\n", "let abc = [1: [3↓ : 2], 3: 4]\n": "let abc = [1: [3: 2], 3: 4]\n", "let abc = [1: [3↓ : 2], 3↓: 4]\n": "let abc = [1: [3: 2], 3: 4]\n", "let abc: [↓String : Int]\n": "let abc: [String: Int]\n", "let abc: [↓String:Int]\n": "let abc: [String: Int]\n", "func foo(bar: [↓String : Int]) {}\n": "func foo(bar: [String: Int]) {}\n", "func foo(bar: [↓String:Int]) {}\n": "func foo(bar: [String: Int]) {}\n", "func foo() -> [↓String : Int] { return [:] }\n": "func foo() -> [String: Int] { return [:] }\n", "func foo() -> [↓String:Int] { return [:] }\n": "func foo() -> [String: Int] { return [:] }\n", "let ↓abc : Any\n": "let abc: Any\n", "let abc: [↓Any : Int]\n": "let abc: [Any: Int]\n", "let abc: [↓String : Any]\n": "let abc: [String: Any]\n", "class ↓Foo : Bar {}\n": "class Foo: Bar {}\n", "class ↓Foo:Bar {}\n": "class Foo: Bar {}\n", "class Foo<↓T:Equatable> {}\n": "class Foo<T: Equatable> {}\n", "class Foo<↓T : Equatable> {}\n": "class Foo<T: Equatable> {}\n", "object.method(x: 5, y↓ : \"string\")\n": "object.method(x: 5, y: \"string\")\n", "object.method(x↓:5, y: \"string\")\n": "object.method(x: 5, y: \"string\")\n", "object.method(x↓: 5, y: \"string\")\n": "object.method(x: 5, y: \"string\")\n", "func abc() { def(ghi↓:jkl) }": "func abc() { def(ghi: jkl) }", "func abc(def: Void) { ghi(jkl↓:mno) }": "func abc(def: Void) { ghi(jkl: mno) }", "class ABC { let def = ghi(jkl↓:mno) } }": "class ABC { let def = ghi(jkl: mno) } }", "func foo() { let dict = [1↓ : 1] }": "func foo() { let dict = [1: 1] }", "class Foo {\n #if false\n #else\n let bar = [\"key\"↓ : \"value\"]\n #endif\n}": "class Foo {\n #if false\n #else\n let bar = [\"key\": \"value\"]\n #endif\n}" ] ) public func validate(file: File) -> [StyleViolation] { let violations = typeColonViolationRanges(in: file, matching: pattern).compactMap { range in return StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severityConfiguration.severity, location: Location(file: file, characterOffset: range.location)) } let dictionaryViolations: [StyleViolation] if configuration.applyToDictionaries { dictionaryViolations = validate(file: file, dictionary: file.structure.dictionary) } else { dictionaryViolations = [] } return (violations + dictionaryViolations).sorted { $0.location < $1.location } } public func correct(file: File) -> [Correction] { let violations = correctionRanges(in: file) let matches = violations.filter { !file.ruleEnabled(violatingRanges: [$0.range], for: self).isEmpty } guard !matches.isEmpty else { return [] } let regularExpression = regex(pattern) let description = type(of: self).description var corrections = [Correction]() var contents = file.contents for (range, kind) in matches.reversed() { switch kind { case .type: contents = regularExpression.stringByReplacingMatches(in: contents, options: [], range: range, withTemplate: "$1: $2") case .dictionary, .functionCall: contents = contents.bridge().replacingCharacters(in: range, with: ": ") } let location = Location(file: file, characterOffset: range.location) corrections.append(Correction(ruleDescription: description, location: location)) } file.write(contents) return corrections } private typealias RangeWithKind = (range: NSRange, kind: ColonKind) private func correctionRanges(in file: File) -> [RangeWithKind] { let violations: [RangeWithKind] = typeColonViolationRanges(in: file, matching: pattern).map { (range: $0, kind: ColonKind.type) } let dictionary = file.structure.dictionary let contents = file.contents.bridge() let dictViolations: [RangeWithKind] = dictionaryColonViolationRanges(in: file, dictionary: dictionary).compactMap { guard let range = contents.byteRangeToNSRange(start: $0.location, length: $0.length) else { return nil } return (range: range, kind: .dictionary) } let functionViolations: [RangeWithKind] = functionCallColonViolationRanges(in: file, dictionary: dictionary).compactMap { guard let range = contents.byteRangeToNSRange(start: $0.location, length: $0.length) else { return nil } return (range: range, kind: .functionCall) } return (violations + dictViolations + functionViolations).sorted { $0.range.location < $1.range.location } } } extension ColonRule: ASTRule { /// Only returns dictionary and function calls colon violations public func validate(file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { let ranges = dictionaryColonViolationRanges(in: file, kind: kind, dictionary: dictionary) + functionCallColonViolationRanges(in: file, kind: kind, dictionary: dictionary) return ranges.map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severityConfiguration.severity, location: Location(file: file, byteOffset: $0.location)) } } }
70b43a6df2d5968e33a629225ed28232
47.523622
119
0.474158
false
false
false
false
mansoor92/MaksabComponents
refs/heads/master
MaksabComponents/Classes/Payment/PaymentCardView.swift
mit
1
// // AddPaymentMethodView.swift // Pods // // Created by Incubasys on 15/08/2017. // // import UIKit import StylingBoilerPlate public struct PaymentCardInfo{ public var title: String public var cardNo: String public var expiryDate: String public var cvv: String public var cardHolderName: String public var expiryYear: Int = 0 public var expiryMonth: Int = 0 public init(title: String, cardNo: String, expiryDate: String, cvv: String, cardHolderName: String) { self.title = title self.cardNo = cardNo self.expiryDate = expiryDate self.cvv = cvv self.cardHolderName = cardHolderName } public func encodeToJSON() -> [String:Any] { var dictionary = [String:Any]() dictionary["name"] = cardHolderName dictionary["number"] = cardNo dictionary["exp_month"] = expiryMonth dictionary["exp_year"] = expiryYear dictionary["cvc"] = cvv return dictionary } } public class PaymentCardView: UIView, CustomView, NibLoadableView, UITextFieldDelegate { @IBOutlet weak public var staticLabelCardNo: UILabel! @IBOutlet weak public var staticLabelExpiryDate: UILabel! @IBOutlet weak public var staticLabelCvv: UILabel! @IBOutlet weak public var staticLabelCardHolderName: UILabel! @IBOutlet weak var cardImg: UIImageView! @IBOutlet weak public var fieldTitle: UITextField! @IBOutlet weak public var fieldCardNo: UITextField! @IBOutlet weak public var fieldExpiryDate: UITextField! @IBOutlet weak public var fieldCvv: UITextField! @IBOutlet weak public var fieldCardHolderName: UITextField! let bundle = Bundle(for: PaymentCardView.classForCoder()) var view: UIView! public static let height: CGFloat = 277 // 188+16 public var errors = [String]() public var errorTitle = String() static public func createInstance(x: CGFloat, y: CGFloat = 0, width: CGFloat) -> PaymentCardView{ let inst = PaymentCardView(frame: CGRect(x: x, y: y, width: width, height: PaymentCardView.height)) return inst } override required public init(frame: CGRect) { super.init(frame: frame) let bundle = Bundle(for: type(of: self)) view = self.commonInit(bundle: bundle) configView() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let bundle = Bundle(for: type(of: self)) view = self.commonInit(bundle: bundle) configView() } func configView() { backgroundColor = UIColor.appColor(color: .Light) let color = UIColor(netHex: 0x777777) staticLabelCardNo.textColor = color staticLabelExpiryDate.textColor = color staticLabelCvv.textColor = color staticLabelCardHolderName.textColor = color fieldTitle.font = UIFont.appFont(font: .RubikMedium, pontSize: 17) fieldCardNo.delegate = self fieldExpiryDate.delegate = self fieldCvv.delegate = self fieldCardHolderName.delegate = self staticLabelCardNo.text = Bundle.localizedStringFor(key: "payment-add-card-no") staticLabelExpiryDate.text = Bundle.localizedStringFor(key: "payment-add-expiry-date") staticLabelCvv.text = Bundle.localizedStringFor(key: "payment-add-cvv") staticLabelCardHolderName.text = Bundle.localizedStringFor(key: "payment-add-carholder-name") fieldTitle.attributedPlaceholder = NSAttributedString(string: Bundle.localizedStringFor(key: "constant-title"), attributes: [NSFontAttributeName: UIFont.appFont(font: .RubikMedium, pontSize: 17)]) fieldTitle.font = UIFont.appFont(font: .RubikMedium, pontSize: 17) fieldCardNo.placeholder = Bundle.localizedStringFor(key: "payment-add-cardno-placeholder") fieldExpiryDate.placeholder = Bundle.localizedStringFor(key: "payment-add-date-placeholder") fieldCvv.placeholder = Bundle.localizedStringFor(key: "payment-add-fieldcvv-placeholder") fieldCardHolderName.placeholder = Bundle.localizedStringFor(key: "payment-add-field-cardno-placeholder") errorTitle = Bundle.localizedStringFor(key: "payment-add-error-invalid-input") errors = [String]() errors.append(Bundle.localizedStringFor(key: "payment-add-eror-title-req")) errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-card-no")) errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-expiry-date")) errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-cvv")) errors.append(Bundle.localizedStringFor(key: "payment-add-eror-invalid-cardholder-name")) } public func getCardInfo(completion:@escaping((_ err:ResponseError?,_ cardInfo: PaymentCardInfo?)->Void)){ let err = ResponseError() err.errorTitle = errorTitle err.reason = "" // if deliveryItems.count == 1 && deliveryItems[0].itemName.isEmpty && deliveryItems[0].quantity < 0{ // err.reason = "Please enter valid name and quantity." // // } if fieldTitle.text!.isEmpty{ err.reason = errors[0] }else if fieldCardNo.text!.count != 19{ err.reason = errors[1] }else if fieldExpiryDate.text!.count != 5{ err.reason = errors[2] }else if fieldCvv.text!.count < 3 { err.reason = errors[3] }else if fieldCardHolderName.text!.isEmpty{ err.reason = errors[4] } var cardInfo = PaymentCardInfo(title: fieldTitle.text!, cardNo: fieldCardNo.text!, expiryDate: fieldExpiryDate.text!, cvv: fieldCvv.text!, cardHolderName: fieldCardHolderName.text!) guard !fieldExpiryDate.text!.isEmpty else { err.errorTitle = errorTitle err.reason = errors[2] completion(err, nil) return } let expDate = fieldExpiryDate.text! let yearStr = expDate.substring(from: expDate.index(expDate.startIndex, offsetBy: 3)) let monthStr = expDate.substring(to: expDate.index(expDate.startIndex, offsetBy: 2)) if let year = Int("20\(yearStr)"){ cardInfo.expiryYear = year }else{ err.reason = errors[0] } if let month = Int(monthStr),month <= 12, month >= 1 { cardInfo.expiryMonth = month }else{ err.reason = errors[0] } if err.reason.isEmpty{ cardInfo.cardNo = cardInfo.cardNo.replacingOccurrences(of: " ", with: "") completion(nil, cardInfo) }else{ completion(err, nil) } } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if textField == fieldCardNo{ return handleCardInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string) }else if textField == fieldExpiryDate{ return handleDateInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string) }else if textField == fieldCvv{ return handleCvvInput(textField: textField, shouldChangeCharactersInRange: range, replacementString: string) }else { return !(textField.text!.count > 128 && (string.count) > range.length) } } func handleCardInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // check the chars length dd -->2 at the same time calculate the dd-MM --> 5 let replaced = (textField.text! as NSString).replacingCharacters(in: range, with: string) setCardImage(string: replaced) if (textField.text!.count == 4) || (textField.text!.count == 9 ) || (textField.text!.count == 14) { //Handle backspace being pressed if !(string == "") { // append the text textField.text = textField.text! + " " } } return !(textField.text!.count > 18 && (string.count ) > range.length) } func setCardImage(string: String) { guard string.count <= 2 , let digit = Int(string) else { return } if digit == 4 || (digit >= 40 && digit <= 49){ //first digit 4 visa cardImg.setImg(named: "visacard") }else if digit >= 51 && digit <= 55{ //first two digits 5x x can be 1-5 matercard cardImg.setImg(named: "mastercard") }else if digit == 34 || digit == 37{ //first two digits 34 or 37 american express cardImg.setImg(named: "americanexpersscard") }else{ cardImg.image = nil } } func handleDateInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // check the chars length dd -->2 at the same time calculate the dd-MM --> 5 // || (textField.text!.characters.count == 5) if (textField.text!.count == 2) { //Handle backspace being pressed if !(string == "") { // append the text textField.text = textField.text! + "/" } } // check the condition not exceed 9 chars return !(textField.text!.count > 4 && (string.count ) > range.length) } func handleCvvInput(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let newLength = textField.text!.count + string.count - range.length // let newString = NSString(string: textField.text!).replacingCharacters(in: range, with: string) // if newString.characters.count == 5 { // textField.rightView = UIImageView(image: #imageLiteral(resourceName: "smallGreenTick")) // }else{ // textField.rightView = UIImageView(image: nil) // } return newLength <= 4 } }
aa8c97d6b75ff94c4cc0f7b654b21b29
40.918367
204
0.631451
false
false
false
false
jerrypupu111/LearnDrawingToolSet
refs/heads/good
SwiftGL-Demo/Source/Common/ImageFile.swift
mit
1
// // ImageFile.swift // SwiftGL // // Created by jerry on 2015/10/28. // Copyright © 2015年 Jerry Chan. All rights reserved. // import Foundation import SwiftHttp public class ImageFile: File { public override init() { } public func loadImg(_ filename:String)->UIImage! { if let img = UIImage(contentsOfFile: File.dirpath+"/"+NSString(string: filename).deletingPathExtension+".png") { return img } return nil } public func loadImgWithExtension(_ filename:String,ext:String)->UIImage! { if let img = UIImage(contentsOfFile: File.dirpath+"/"+NSString(string: filename).deletingPathExtension+ext) { return img } return nil } public func loadImg(_ filename:String, attribute:String = "original")->UIImage! { switch attribute { case "original": return loadImgWithExtension(filename, ext: ".png") case "thumb": return loadImgWithExtension(filename, ext: "thumb.png") case "gif": return loadImgWithExtension(filename, ext: ".gif") default: return loadImgWithExtension(filename, ext: ".png") } } public func saveImg(_ img:UIImage,filename:String) { let imageData:Data = UIImagePNGRepresentation(img)!; let filePath = File.dirpath+"/"+filename+".png" try? imageData.write(to: URL(fileURLWithPath: filePath), options: [.atomic]) } override public func delete(_ filename: String) { super.delete(filename+".png") } }
a7212620ebea12347ef7d1399b2534bc
26.5
118
0.590909
false
false
false
false
Alarson93/mmprogressswift
refs/heads/master
Pod/Classes/MMProgressConfiguration.swift
mit
1
// // MMProgressConfiguration.swift // Pods // // Created by Alexander Larson on 3/21/16. // // import Foundation import UIKit public enum MMProgressBackgroundType: NSInteger { case MMProgressBackgroundTypeBlurred = 0, MMProgressBackgroundTypeSolid } public class MMProgressConfiguration: NSObject { //Background public var backgroundColor: UIColor? public var backgroundType: MMProgressBackgroundType? public var backgroundEffect: UIVisualEffect? public var fullScreen: Bool? //Edges public var shadowEnabled: Bool? public var shadowOpacity: CGFloat? public var shadowColor: UIColor? public var borderEnabled: Bool? public var borderWidth: CGFloat? public var borderColor: UIColor? //Custom Animation public var loadingIndicator: UIView? //Presentation public var presentAnimated: Bool? //Status public var statusColor: UIColor? public var statusFont: UIFont? //Interaction public var tapBlock: Bool? override init() { //Background backgroundColor = UIColor.clearColor() backgroundType = MMProgressBackgroundType.MMProgressBackgroundTypeBlurred backgroundEffect = UIBlurEffect(style: UIBlurEffectStyle.Light) fullScreen = false //Edges shadowEnabled = true shadowOpacity = 1 shadowColor = UIColor.blackColor() borderEnabled = false borderWidth = 1 borderColor = UIColor.blackColor() //Default Animation //loading //Presentation presentAnimated = true //Status statusColor = UIColor.darkGrayColor() statusFont = UIFont.systemFontOfSize(17) //Interaction tapBlock = true } }
efcedb9e849887da8d477080c2613cdf
22.922078
81
0.649294
false
false
false
false
trujillo138/MyExpenses
refs/heads/master
MyExpenses/MyExpenses/Model/ExpensePeriod.swift
apache-2.0
1
// // ExpensePeriod.swift // MyExpenses // // Created by Tomas Trujillo on 5/22/17. // Copyright © 2017 TOMApps. All rights reserved. // import Foundation enum ExpensePeriodSortOption: Int { case amount = 0 case type = 1 case date = 2 case name = 3 static let numberOfOptions = 4 var name: String { switch self { case .amount: return LStrings.ExpensePeriod.SortOptionExpenseAmount case .date: return LStrings.ExpensePeriod.SortOptionExpenseDate case .name: return LStrings.ExpensePeriod.SortOptionExpenseName case .type: return LStrings.ExpensePeriod.SortOptionExpenseType } } } enum ExpensePeriodFilterOption: Int { case type = 0 case date = 1 case amount = 2 static let numberOfOptions = 3 var name: String { switch self { case .amount: return LStrings.ExpensePeriod.FilterOptionExpenseAmount case .date: return LStrings.ExpensePeriod.FilterOptionExpenseDate case .type: return LStrings.ExpensePeriod.FilterOptionExpenseType } } } struct ExpensePeriod { //MARK: Properties var expenses: [Expense] var budget: Double var goal: Double var date: Date var currency: Currency var month: Int var year: Int var amountSaved: Double { return fmax(self.budget - self.amountSpent, 0.0) } var amountSpent: Double { return expenses.reduce(0, { x, y in x + y.amount }) } var formattedAmountSpent: String { return amountSpent.currencyFormat } var formattedAmountSpentWithCurrency: String { return currency.rawValue + " " + amountSpent.currencyFormat } var formattedAmountSaved: String { return amountSaved.currencyFormat } var formattedAmountSavedWithCurrency: String { return currency.rawValue + " " + amountSaved.currencyFormat } var formattedGoal: String { return goal.currencyFormat } var formattedGoalWithCurrency: String { return currency.rawValue + " " + goal.currencyFormat } var formattedIncome: String { return budget.currencyFormat } var formattedIncomeWithCurrency: String { return currency.rawValue + " " + budget.currencyFormat } var name: String { let formatter = DateFormatter() formatter.dateFormat = "MMM yyyy" return formatter.string(from: self.date).capitalized } var maxExpenseDateForPeriod: Date? { if expenses.count == 0 { return nil } else { let descendingExpenseList = expenses.sorted { return $0.date >= $1.date } return descendingExpenseList[0].date } } var minExpenseDateForPeriod: Date? { if expenses.count == 0 { return nil } else { let ascendingExpenseList = expenses.sorted { return $1.date >= $0.date } return ascendingExpenseList[0].date } } var idExpensePeriod: String //MARK: Initializer init(budget: Double, date: Date, currency: Currency, goal: Double) { self.budget = budget self.goal = goal self.date = date self.expenses = [Expense]() self.currency = currency self.month = date.month() self.year = date.year() let currentDate = Date() self.idExpensePeriod = "\(self.date.year())-\(self.date.month())\(currentDate.year())\(currentDate.month())\(currentDate.day())\(currentDate.hour())\(currentDate.minute())\(currentDate.second())" } //MARK: Update func add(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.expenses.insert(expense, at: 0) return copyPeriod } func update(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) for (index, exp) in copyPeriod.expenses.enumerated() { guard exp.idExpense == expense.idExpense else { continue } copyPeriod.expenses[index] = expense } return copyPeriod } func delete(expense: Expense) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) for (index, exp) in copyPeriod.expenses.enumerated() { guard exp.idExpense == expense.idExpense else { continue } copyPeriod.expenses.remove(at: index) } return copyPeriod } func updateInfo(monthlyIncome: Double, monthlyGoal: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.budget = monthlyIncome copyPeriod.goal = monthlyGoal return copyPeriod } func updateInfo(monthlyIncome: Double, monthlyGoal: Double, currency: String, currencyTransformRate: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.budget = monthlyIncome copyPeriod.goal = monthlyGoal guard let newCurrency = Currency(rawValue: currency) else { return copyPeriod } return copyPeriod.transformExpenseTo(currency: newCurrency, withRate: currencyTransformRate) } //MARK: Periods func isPeriodIn(date: Date) -> Bool { return date.year() == year && date.month() == month } static func createPeriodsUpUntil(date: Date, fromPeriod: ExpensePeriod, withBudget budget: Double, currency: Currency, goal: Double) -> [ExpensePeriod] { var periods = [ExpensePeriod]() var period = fromPeriod var periodDate = fromPeriod.date var arrivedToCurrentPeriod = period.isPeriodIn(date: date) while !arrivedToCurrentPeriod { periodDate = periodDate.dateByAdding(years: 0, months: 1, days: 0) period = ExpensePeriod(budget: budget, date: periodDate.dateForFirstDayOfMonth(), currency: currency, goal: goal) periods.insert(period, at: 0) arrivedToCurrentPeriod = period.isPeriodIn(date: date) } return periods } //MARK: Sorting func sortExpensesBy(option: ExpensePeriodSortOption, ascending: Bool) -> [Expense] { return sortExpenseListBy(option: option, ascending: ascending, expenseList: expenses) } private func sortExpenseListBy(option: ExpensePeriodSortOption, ascending: Bool, expenseList: [Expense]) -> [Expense] { switch option { case .amount: return ascending ? expenseList.sorted { return $0.amount < $1.amount } : expenseList.sorted { return $0.amount >= $1.amount } case .date: return ascending ? expenseList.sorted { return $0.date < $1.date } : expenseList.sorted { return $0.date >= $1.date } case .name: return ascending ? expenseList.sorted { return $0.name < $1.name } : expenseList.sorted { return $0.name >= $1.name } case .type: return ascending ? expenseList.sorted { return $0.expenseType.displayName < $1.expenseType.displayName } : expenseList.sorted { return $0.expenseType.displayName >= $1.expenseType.displayName } } } //MARK: Filtering func filterExpensesBy(filter: ExpensePeriodFilterOption, fromValue: Any?, toValue: Any?) -> [Expense] { switch filter { case .amount: if let frmValue = fromValue as? Double { return filterExpensesBy(amount: frmValue, greaterThan: true) } else { return filterExpensesBy(amount: toValue as! Double, greaterThan: false) } case .type: return filterExpensesBy(type: ExpenseType(rawValue: fromValue as! String)!) case .date: return filterExpensesFrom(date: fromValue as! Date?, to: toValue as! Date?) } } private func filterExpensesBy(amount: Double, greaterThan: Bool) -> [Expense] { return expenses.filter { return greaterThan ? $0.amount >= amount : $0.amount <= amount } } private func filterExpensesFrom(date: Date?, to: Date?) -> [Expense] { var filteredExpenses = [Expense]() if let fromDate = date, let toDate = to { filteredExpenses = expenses.filter { return $0.date >= fromDate && $0.date <= toDate } } else if let fromDate = date { filteredExpenses = expenses.filter { return $0.date >= fromDate } } else if let toDate = to { filteredExpenses = expenses.filter { return $0.date <= toDate } } return filteredExpenses } private func filterExpensesBy(type: ExpenseType) -> [Expense] { return expenses.filter { return $0.expenseType == type } } //MARK: Sort & Filter func filterAndSortExpensesBy(filter: ExpensePeriodFilterOption, fromValue: Any?, toValue: Any?, option: ExpensePeriodSortOption, ascending: Bool) -> [Expense] { let filteredExpenses = filterExpensesBy(filter: filter, fromValue: fromValue, toValue: toValue) return sortExpenseListBy(option: option, ascending: ascending, expenseList: filteredExpenses) } //MARK: Classify func getCategoriesWithExpenses() -> [ExpenseCategory] { var categories = [ExpenseCategory]() var listOfCats = [ExpenseType: Double]() for expense in expenses { if let amount = listOfCats[expense.expenseType] { listOfCats[expense.expenseType] = amount + expense.amount } else { listOfCats[expense.expenseType] = expense.amount } } for entry in listOfCats { let category = ExpenseCategory(type: entry.key, value: entry.value) categories.append(category) } return categories.sorted { return $0.value > $1.value } } //MARK: Transform func transformExpenseTo(currency: Currency, withRate rate: Double) -> ExpensePeriod { var copyPeriod = ExpensePeriod(plist: self.plistRepresentation) copyPeriod.expenses = expenses.map { var newExp = $0 newExp.amount *= rate newExp.currency = currency return newExp } copyPeriod.currency = currency return copyPeriod } } //MARK: Coding Initializers extension ExpensePeriod { private struct CodingKeys { static let ExpensesKey = "expenses" static let BudgetKey = "budget" static let DateKey = "date" static let IdExpensePeriodKey = "id expense period" static let CurrencyKey = "currency" static let GoalKey = "goal" static let MonthKey = "key" static let YearKey = "year" } var plistRepresentation: [String: AnyObject] { return [CodingKeys.BudgetKey: budget as AnyObject, CodingKeys.DateKey: date as AnyObject, CodingKeys.IdExpensePeriodKey: idExpensePeriod as AnyObject, CodingKeys.ExpensesKey: expenses.map { $0.plistRepresentation } as AnyObject, CodingKeys.CurrencyKey: currency.rawValue as AnyObject, CodingKeys.GoalKey: goal as AnyObject, CodingKeys.YearKey: year as AnyObject, CodingKeys.MonthKey: month as AnyObject] } init(plist: [String: AnyObject]) { let periodDate = plist[CodingKeys.DateKey] as! Date budget = plist[CodingKeys.BudgetKey] as! Double date = periodDate idExpensePeriod = plist[CodingKeys.IdExpensePeriodKey] as! String expenses = (plist[CodingKeys.ExpensesKey] as! [[String: AnyObject]]).map(Expense.init(plist:)) currency = Currency(rawValue: plist[CodingKeys.CurrencyKey] as! String)! goal = plist[CodingKeys.GoalKey] as! Double year = plist[CodingKeys.YearKey] as? Int ?? periodDate.year() month = plist[CodingKeys.MonthKey] as? Int ?? periodDate.month() } } //MARK: Statistics extension ExpensePeriod { func calculateExpensePerExpenseType() -> [(ExpenseType, Double)] { var totals = [(ty: ExpenseType, ex: Double)]() let orderedExpenses = expenses.sorted { return $0.expenseType.rawValue.localizedCompare($1.expenseType.rawValue) == .orderedAscending ? true : false } var expenseType: ExpenseType? for expense in orderedExpenses { if expense.expenseType == expenseType { guard let total = totals.last else { continue } totals[totals.count - 1] = (ty: expense.expenseType, ex: total.ex + expense.amount) } else { let newTotal = (ty:expense.expenseType, ex: expense.amount) expenseType = expense.expenseType totals.append(newTotal) } } return totals.sorted(by: { return $0.ex > $1.ex }) } }
294f7aaedc4d08e3fa7a24ed02121d37
34.281501
203
0.622188
false
false
false
false
midoks/Swift-Learning
refs/heads/master
GitHubStar/GitHubStar/GitHubStar/Controllers/me/user/GsLoginViewController.swift
apache-2.0
1
// // LoginViewContoller.swift // GitHubStar // // Created by midoks on 15/12/19. // Copyright © 2015年 midoks. All rights reserved. // import UIKit import SwiftyJSON class GsLoginViewController: GsWebViewController { override func viewDidLoad() { super.viewDidLoad() self.title = sysLang(key: "Login") let rightButton = UIBarButtonItem(title: "刷新", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.reloadRequestUrl)) self.navigationItem.rightBarButtonItem = rightButton let leftButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.close)) self.navigationItem.leftBarButtonItem = leftButton self.loadRequestUrl() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //关闭 func close(){ self.pop() self.dismiss(animated: true) { () -> Void in self.clearCookie() } } //加载url请求 func loadRequestUrl(){ let urlString = GitHubApi.instance.authUrl() let url = (NSURLComponents(string: urlString)?.url)! self.loadUrl(url: url as NSURL) } //重新加载 func reloadRequestUrl(){ self.reload() } //Mark: - webView delegate - override func webViewDidFinishLoad(_ webView: UIWebView) { super.webViewDidFinishLoad(webView) let code = webView.stringByEvaluatingJavaScript(from: "code") if code != "" { //print(code) GitHubApi.instance.getToken(code: code!, callback: { (data, response, error) -> Void in //print(error) //print(response) if (response != nil) { let data = String(data: data! as Data, encoding: String.Encoding.utf8)! let userInfoData = JSON.parse(data) let token = userInfoData["access_token"].stringValue GitHubApi.instance.setToken(token: token) GitHubApi.instance.user(callback: { (data, response, error) -> Void in let userData = String(data: data! as Data, encoding: String.Encoding.utf8)! let userJsonData = JSON.parse(userData) let name = userJsonData["login"].stringValue let userInfo = UserModelList.instance().selectUser(userName: name) if (userInfo as! NSNumber != false && userInfo.count > 0) { let id = userInfo["id"] as! Int _ = UserModelList.instance().updateMainUserById(id: id) _ = UserModelList.instance().updateInfoById(info: userData, id: id) } else { _ = UserModelList.instance().addUser(userName: name, token: token) _ = UserModelList.instance().updateInfo(info: userData, token: token) } self.close() }) } else { print("error") } }) } } }
e2e39aa0e3b8045b7437c2aa3981688f
34.163265
145
0.511898
false
false
false
false
tsolomko/SWCompression
refs/heads/develop
Sources/Common/Extensions.swift
mit
1
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation extension UnsignedInteger { @inlinable @inline(__always) func toInt() -> Int { return Int(truncatingIfNeeded: self) } } extension Int { @inlinable @inline(__always) func toUInt8() -> UInt8 { return UInt8(truncatingIfNeeded: UInt(self)) } @inlinable @inline(__always) func roundTo512() -> Int { if self >= Int.max - 510 { return Int.max } else { return (self + 511) & (~511) } } /// Returns an integer with reversed order of bits. func reversed(bits count: Int) -> Int { var a = 1 << 0 var b = 1 << (count - 1) var z = 0 for i in Swift.stride(from: count - 1, to: -1, by: -2) { z |= (self >> i) & a z |= (self << i) & b a <<= 1 b >>= 1 } return z } } extension Date { private static let ntfsReferenceDate = DateComponents(calendar: Calendar(identifier: .iso8601), timeZone: TimeZone(abbreviation: "UTC"), year: 1601, month: 1, day: 1, hour: 0, minute: 0, second: 0).date! init(_ ntfsTime: UInt64) { self.init(timeInterval: TimeInterval(ntfsTime) / 10_000_000, since: .ntfsReferenceDate) } }
119ae7cd82106ff4db3371c5fdbb9f6d
24.55
99
0.493151
false
false
false
false
ejeinc/MetalScope
refs/heads/master
Sources/ViewerParameters.swift
mit
1
// // ViewerParameters.swift // MetalScope // // Created by Jun Tanaka on 2017/01/23. // Copyright © 2017 eje Inc. All rights reserved. // public protocol ViewerParametersProtocol { var lenses: Lenses { get } var distortion: Distortion { get } var maximumFieldOfView: FieldOfView { get } } public struct ViewerParameters: ViewerParametersProtocol { public var lenses: Lenses public var distortion: Distortion public var maximumFieldOfView: FieldOfView public init(lenses: Lenses, distortion: Distortion, maximumFieldOfView: FieldOfView) { self.lenses = lenses self.distortion = distortion self.maximumFieldOfView = maximumFieldOfView } public init(_ parameters: ViewerParametersProtocol) { self.lenses = parameters.lenses self.distortion = parameters.distortion self.maximumFieldOfView = parameters.maximumFieldOfView } } public struct Lenses { public enum Alignment: Int { case top = -1 case center = 0 case bottom = 1 } public let separation: Float public let offset: Float public let alignment: Alignment public let screenDistance: Float public init(separation: Float, offset: Float, alignment: Alignment, screenDistance: Float) { self.separation = separation self.offset = offset self.alignment = alignment self.screenDistance = screenDistance } } public struct FieldOfView { public let outer: Float // in degrees public let inner: Float // in degrees public let upper: Float // in degrees public let lower: Float // in degrees public init(outer: Float, inner: Float, upper: Float, lower: Float) { self.outer = outer self.inner = inner self.upper = upper self.lower = lower } public init(values: [Float]) { guard values.count == 4 else { fatalError("The values must contain 4 elements") } outer = values[0] inner = values[1] upper = values[2] lower = values[3] } } public struct Distortion { public var k1: Float public var k2: Float public init(k1: Float, k2: Float) { self.k1 = k1 self.k2 = k2 } public init(values: [Float]) { guard values.count == 2 else { fatalError("The values must contain 2 elements") } k1 = values[0] k2 = values[1] } public func distort(_ r: Float) -> Float { let r2 = r * r return ((k2 * r2 + k1) * r2 + 1) * r } public func distortInv(_ r: Float) -> Float { var r0: Float = 0 var r1: Float = 1 var dr0 = r - distort(r0) while abs(r1 - r0) > Float(0.0001) { let dr1 = r - distort(r1) let r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0)) r0 = r1 r1 = r2 dr0 = dr1 } return r1 } }
77ce2acf829c9032cafa66bb8c14aa4d
25.303571
96
0.596062
false
false
false
false
wwq0327/iOS9Example
refs/heads/master
Pinterest/Pinterest/PhotoStreamViewController.swift
apache-2.0
1
// // PhotoStreamViewController.swift // RWDevCon // // Created by Mic Pringle on 26/02/2015. // Copyright (c) 2015 Ray Wenderlich. All rights reserved. // import UIKit import AVFoundation class PhotoStreamViewController: UICollectionViewController { var photos = Photo.allPhotos() override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } override func viewDidLoad() { super.viewDidLoad() if let patternImage = UIImage(named: "Pattern") { view.backgroundColor = UIColor(patternImage: patternImage) } collectionView!.backgroundColor = UIColor.clearColor() collectionView!.contentInset = UIEdgeInsets(top: 23, left: 5, bottom: 10, right: 5) } } extension PhotoStreamViewController { override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("AnnotatedPhotoCell", forIndexPath: indexPath) as! AnnotatedPhotoCell cell.photo = photos[indexPath.item] return cell } }
ff720c83dd0f789cd337d44fec44f3db
26.869565
138
0.74337
false
false
false
false
justindaigle/grogapp-ios
refs/heads/master
GroGApp/GroGApp/GroupMembershipTableViewController.swift
mit
1
// // GroupMembershipTableViewController.swift // GroGApp // // Created by Justin Daigle on 3/27/15. // Copyright (c) 2015 Justin Daigle (.com). All rights reserved. // import UIKit class GroupMembershipTableViewController: UITableViewController { var users:JSON = [] var id = -1 @IBAction func addMember() { var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var prompt = UIAlertController(title: "Add User", message: "Enter the name of the user to add.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addTextFieldWithConfigurationHandler({(textField:UITextField!) in textField.placeholder = "Username" textField.secureTextEntry = false}) prompt.addAction((UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))) prompt.addAction(UIAlertAction(title: "Add", style: UIAlertActionStyle.Default, handler: {(alertAction: UIAlertAction!) in let text = prompt.textFields![0] as! UITextField var success = DataMethods.AddUserToGroup(username, password, self.id, text.text) if (success) { var newPrompt = UIAlertController(title: "Success", message: "User added.", preferredStyle: UIAlertControllerStyle.Alert) newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))) self.presentViewController(newPrompt, animated: true, completion: {self.reloadGroup(true)}) } else { var newPrompt = UIAlertController(title: "Failure", message: "Failed to add user to group.", preferredStyle: UIAlertControllerStyle.Alert) newPrompt.addAction((UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))) self.presentViewController(newPrompt, animated: true, completion: nil) } })) self.presentViewController(prompt, animated: true, completion: nil) } func reloadGroup(reloadTable:Bool) { var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var groups = DataMethods.GetGroups(username, password) var groupSet = groups["groups"] for (index: String, subJson: JSON) in groupSet { if (subJson["id"].intValue == id) { users = subJson["users"] } } if (reloadTable) { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return users.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! GroupsTableViewCell // Configure the cell... cell.groupName.text = users[indexPath.row].stringValue return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source var defaults = NSUserDefaults.standardUserDefaults() var username = defaults.valueForKey("username") as! String var password = defaults.valueForKey("password") as! String var result = DataMethods.DeleteUserFromGroup(username, password, id, users[indexPath.row].stringValue) reloadGroup(false) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) if (result) { var prompt = UIAlertController(title: "Success", message: "Group member removed.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(prompt, animated: true, completion: nil) } else { var prompt = UIAlertController(title: "Failure", message: "Group member not removed.", preferredStyle: UIAlertControllerStyle.Alert) prompt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(prompt, animated: true, completion: nil) } // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
97225297d8295a3f03f5d85b814376d8
42.375
157
0.665418
false
false
false
false
HotWordland/wlblog_server
refs/heads/master
Sources/App/Controllers/LoginController.swift
mit
1
import Vapor import HTTP import VaporJWT import Foundation import VaporPostgreSQL final class LoginController { func login(_ req: Request) throws -> ResponseRepresentable { guard let param_name = req.textplain_json?.node["name"]?.string,let param_pwd = req.textplain_json?.node["pwd"]?.string else{ return try responseWithError(msg: "有未提交的参数") } guard let user = try User.query().filter("name",param_name).all().first else{ return try responseWithError(msg: "用户不存在") } if user.password != param_pwd { return try responseWithError(msg: "密码有误") } let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + (60*60))), signer: HS256(key: "secret")) // let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + 60)), // signer: HS256(key: "secret")) // let jwt = try JWT(payload: Node(ExpirationTimeClaim(Date() + 60)), signer: ES256(encodedKey: "AL3BRa7llckPgUw3Si2KCy1kRUZJ/pxJ29nlr86xlm0=")) let token = try jwt.createToken() return try responseWithSuccess(data: ["token":Node(token)]) } func saveDefaultUser(_ req: Request) throws -> ResponseRepresentable { if try User.query().filter("name","admin2").all().count != 0 { return try responseWithError(msg: "admin2 aleady exsit") } var user = User(name: "admin2", password: "123456") try user.save() return try JSON(node:User.all().makeNode()) } func uploadFile(_ request: Request) throws -> ResponseRepresentable{ guard let file = request.multipart?["file"]?.file,let fileName = file.name else { throw Abort.custom(status: .notFound, message: "文件未找到") } // let dateFormatter = DateFormatter() // dateFormatter.dateFormat = "yyyyMMddHH:mm:ss" let date = Int(Date().timeIntervalSince1970) // var date_string = dateFormatter.string(from: date) var file_save_name = "\(date)" let separates = fileName.components(separatedBy: ".") if separates.count>1 { if let extension_name = separates.last { file_save_name = "\(file_save_name).\(extension_name)" } } let imagePath = "upload_images/\(file_save_name)" let savePath = drop.workDir + "Public/" + imagePath // try Data(file.data).write(to: URL(fileURLWithPath: "/Users/wulong/Desktop/\(date_string)")) let flag = FileManager.default.createFile(atPath: savePath, contents: Data(bytes: file.data), attributes: nil) if flag { return try responseWithSuccess(data: ["path":Node(imagePath)]) }else{ throw Abort.custom(status: .notFound, message: "保存失败") } } }
e0c202f903983d128f3303b233818c8f
41.924242
151
0.608189
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/Room/ReactionHistory/ReactionHistoryCoordinator.swift
apache-2.0
2
// File created from ScreenTemplate // $ createScreen.sh ReactionHistory ReactionHistory /* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit final class ReactionHistoryCoordinator: ReactionHistoryCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private let roomId: String private let eventId: String private let router: NavigationRouter // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: ReactionHistoryCoordinatorDelegate? // MARK: - Setup init(session: MXSession, roomId: String, eventId: String) { self.session = session self.roomId = roomId self.eventId = eventId self.router = NavigationRouter(navigationController: RiotNavigationController()) } // MARK: - Public methods func start() { let reactionHistoryViewModel = ReactionHistoryViewModel(session: session, roomId: roomId, eventId: eventId) let reactionHistoryViewController = ReactionHistoryViewController.instantiate(with: reactionHistoryViewModel) reactionHistoryViewModel.coordinatorDelegate = self self.router.setRootModule(reactionHistoryViewController) } func toPresentable() -> UIViewController { return self.router.toPresentable() } } // MARK: - ReactionHistoryViewModelCoordinatorDelegate extension ReactionHistoryCoordinator: ReactionHistoryViewModelCoordinatorDelegate { func reactionHistoryViewModelDidClose(_ viewModel: ReactionHistoryViewModelType) { self.delegate?.reactionHistoryCoordinatorDidClose(self) } }
ed108fdab56404133d8f198b43da882f
32.029412
117
0.735085
false
false
false
false
hassanabidpk/umapit_ios
refs/heads/master
uMAPit/models/Location.swift
mit
1
// // Location.swift // uMAPit // // Created by Hassan Abid on 16/02/2017. // Copyright © 2017 uMAPit. All rights reserved. // import Foundation import RealmSwift class Location: Object { dynamic var title = "" dynamic var latitude: Double = 0.0 dynamic var longitude: Double = 0.0 dynamic var address = "" dynamic var updated_at: Date? = nil dynamic var created_at: Date? = nil dynamic var id = 0 }
7c63396e9d91da017f2993624bf3269d
18
49
0.652174
false
false
false
false
KlubJagiellonski/pola-ios
refs/heads/master
BuyPolish/Pola/UI/ProductSearch/ScanCode/ProductCard/CompanyContent/CompanyContentView.swift
gpl-2.0
1
import UIKit final class CompanyContentView: UIView { let capitalTitleLabel = UILabel() let capitalProgressView = SecondaryProgressView() let notGlobalCheckRow = CheckRow() let registeredCheckRow = CheckRow() let rndCheckRow = CheckRow() let workersCheckRow = CheckRow() let friendButton = UIButton() let descriptionLabel = UILabel() private let stackView = UIStackView() private let padding = CGFloat(14) override init(frame: CGRect) { super.init(frame: frame) translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = padding stackView.distribution = .fillProportionally stackView.alignment = .fill stackView.translatesAutoresizingMaskIntoConstraints = false addSubview(stackView) let localizable = R.string.localizable.self capitalTitleLabel.font = Theme.normalFont capitalTitleLabel.textColor = Theme.defaultTextColor capitalTitleLabel.text = localizable.percentOfPolishHolders() capitalTitleLabel.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(capitalTitleLabel) capitalProgressView.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(capitalProgressView) notGlobalCheckRow.text = localizable.notPartOfGlobalCompany() notGlobalCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(notGlobalCheckRow) registeredCheckRow.text = localizable.isRegisteredInPoland() registeredCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(registeredCheckRow) rndCheckRow.text = localizable.createdRichSalaryWorkPlaces() rndCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(rndCheckRow) workersCheckRow.text = localizable.producingInPL() workersCheckRow.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(workersCheckRow) friendButton.setImage(R.image.heartFilled(), for: .normal) friendButton.tintColor = Theme.actionColor friendButton.setTitle(localizable.thisIsPolaSFriend(), for: .normal) friendButton.setTitleColor(Theme.actionColor, for: .normal) friendButton.titleLabel?.font = Theme.normalFont let buttontitleHorizontalMargin = CGFloat(7) friendButton.titleEdgeInsets = UIEdgeInsets(top: 0, left: buttontitleHorizontalMargin, bottom: 0, right: 0) friendButton.contentHorizontalAlignment = .left friendButton.adjustsImageWhenHighlighted = false friendButton.isHidden = true friendButton.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(friendButton) descriptionLabel.font = Theme.normalFont descriptionLabel.textColor = Theme.defaultTextColor descriptionLabel.numberOfLines = 0 descriptionLabel.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubview(descriptionLabel) createConstraints() } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } private func createConstraints() { addConstraints([ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.bottomAnchor.constraint(greaterThanOrEqualTo: bottomAnchor), ]) } }
df0696b82051522a4a55ff7e39ca147b
41.213483
88
0.727974
false
false
false
false
giftbott/HandyExtensions
refs/heads/master
Sources/UIViewExtensions.swift
mit
1
// // UIViewExtensions.swift // HandyExtensions // // Created by giftbot on 2017. 4. 29.. // Copyright © 2017년 giftbot. All rights reserved. // // MARK: - Initializer extension UIView { /// let view = UIView(x: 0, y: 20, w: 200, h: 200) public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) } public convenience init(origin: CGPoint, size: CGSize) { self.init(frame: CGRect(origin: origin, size: size)) } } // MARK: - Computed Property extension UIView { /// Call view's parent UIViewController responder. /// view.viewController public var viewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } /// var view = UIView(x: 0, y: 0, width: 100, height: 100) /// /// view.x = 50 /// view.y = 50 /// view.width = 50 /// view.height = 50 public var x: CGFloat { get { return frame.origin.x } set { self.frame.origin.x = newValue } } public var y: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } public var width: CGFloat { get { return frame.width } set { frame.size.width = newValue } } public var height: CGFloat { get { return frame.height } set { frame.size.height = newValue } } public var maxX: CGFloat { get { return x + width } set { x = newValue - width } } public var maxY: CGFloat { get { return y + height } set { y = newValue - height } } public var midX: CGFloat { get { return x + (width / 2) } set { x = newValue - (width / 2) } } public var midY: CGFloat { get { return y + (height / 2) } set { y = newValue - (height / 2) } } public var size: CGSize { get { return frame.size } set { frame.size = newValue } } @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } } // MARK: - Method extension UIView { /// view.addSubviews([aLabel, bButton]) public func addSubviews(_ views: [UIView]) { for view in views { self.addSubview(view) } } /// view.removeAllsubviews() public func removeAllSubviews() { for subview in self.subviews { subview.removeFromSuperview() } } /// Rotate view using CoreAnimation. Rotating 360 degree in a second is a default public func rotate( from: CGFloat = 0, to: CGFloat = 2 * .pi, beginTime: CFTimeInterval = 0.0, duration: CFTimeInterval = 1.0, forKey key: String? = nil, _ delegateObject: AnyObject? = nil ) { let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation") rotateAnimation.beginTime = CACurrentMediaTime() + beginTime rotateAnimation.fromValue = from.degreesToRadians rotateAnimation.toValue = to.degreesToRadians rotateAnimation.duration = duration weak var delegate = delegateObject if delegate != nil { rotateAnimation.delegate = delegate as? CAAnimationDelegate } DispatchQueue.main.async { [weak self] in self?.layer.add(rotateAnimation, forKey: key) } } } // MARK: - LayoutAnchor Helper extension UIView { public func topAnchor(to anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self { topAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func leadingAnchor(to anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self { leadingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func bottomAnchor(to anchor: NSLayoutYAxisAnchor, constant: CGFloat = 0) -> Self { bottomAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func trailingAnchor(to anchor: NSLayoutXAxisAnchor, constant: CGFloat = 0) -> Self { trailingAnchor.constraint(equalTo: anchor, constant: constant).isActive = true return self } public func widthAnchor(constant: CGFloat) -> Self { widthAnchor.constraint(equalToConstant: constant).isActive = true return self } public func heightAnchor(constant: CGFloat) -> Self { heightAnchor.constraint(equalToConstant: constant).isActive = true return self } public func sizeAnchor(width widthConstant: CGFloat, height heightConstant: CGFloat) -> Self { widthAnchor.constraint(equalToConstant: widthConstant).isActive = true heightAnchor.constraint(equalToConstant: heightConstant).isActive = true return self } public func sizeAnchor(size: CGSize) -> Self { widthAnchor.constraint(equalToConstant: size.width).isActive = true heightAnchor.constraint(equalToConstant: size.height).isActive = true return self } public func centerYAnchor(to anchor: NSLayoutYAxisAnchor) -> Self { centerYAnchor.constraint(equalTo: anchor).isActive = true return self } public func centerXAnchor(to anchor: NSLayoutXAxisAnchor) -> Self { centerXAnchor.constraint(equalTo: anchor).isActive = true return self } public func activateAnchors() { translatesAutoresizingMaskIntoConstraints = false } }
59a6ac592fcf3fa12cdee82854dd226b
25.935644
96
0.663481
false
false
false
false