repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ITzTravelInTime/TINU
TINU/PackagesWrapper.swift
1
4075
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Foundation import AppKit import TINUNotifications import TINURecovery import TINUSerialization import SwiftCPUDetect import SwiftLoggedPrint public class Recovery: TINURecovery.Recovery{ public override class var simulatedStatus: Bool?{ return TINU.simulateRecovery } } public final class SIPManager: SIP, ViewID { public let id: String = "SIPManager" private static let ref = SIPManager() public override class var simulatedStatus: SIP.SIPStatus?{ guard let simulate = TINU.simulateSIPStatus else{ return nil } return simulate ? 0 : 0x7f } public class func checkStatusAndLetTheUserKnow(){ DispatchQueue.global(qos: .background).async { if !status.isOkForTINU && !CommandLine.arguments.contains("-disgnostics-mode"){ //msgBoxWithCustomIcon("TINU: Please disable SIP", "SIP (system integrity protection) is enabled and will not allow TINU to complete successfully the installer creation process, please disable it or use the diagnostics mode with administrator privileges", .warning , IconsManager.shared.stopIcon) DispatchQueue.main.async { msgboxWithManager(ref, name: "disable", parseList: nil, style: NSAlert.Style.critical, icon: nil) } } } } } public extension SIP.SIPIntegerFormat{ var isOkForTINU: Bool{ let mask = SIPManager.SIPBits.CSR_ALLOW_UNRESTRICTED_FS.rawValue return (self & mask) == mask } } internal class LogManager: SwiftLoggedPrint.LoggedPrinter{ override class var printerID: String{ super.showPrefixesIntoLoggedLines = true super.logsDebugLines = false return Bundle.main.bundleIdentifier ?? "TINU" } static func clearLog(){ super.clearLog() log(AppBanner.banner) } } public func log( _ log: String){ LogManager.print("\(log)") } public func print( _ str: Any){ LogManager.debug("\(str)") } typealias UINotification = TINUNotifications.Notification public final class Notifications: ViewID{ public let id: String = "NotificationsManager" private static let ref = Notifications() public class func make(id: String, icon: NSImage? = NSImage(named: "AppIcon")!) -> TINUNotifications.Notification{ let title = TextManager.getViewString(context: ref, stringID: id + "Title")! let description = TextManager.getViewString(context: ref, stringID: id)! return TINUNotifications.Notification(id: id, message: title, description: description, icon: icon) } public class func sendWith(id: String, icon: NSImage? = NSImage(named: "AppIcon")!) -> NSUserNotification?{ return make(id: id, icon: icon).send() } public class func justSendWith(id: String, icon: NSImage? = NSImage(named: "AppIcon")!){ Notifications.make(id: id, icon: icon).justSend() } } public typealias Alert = TINUNotifications.Alert public extension Alert{ func warningWithIcon() -> Alert{ var mycopy = warning() mycopy.icon = IconsManager.shared.warningIcon.normalImage() return mycopy } func criticalWithIcon() -> Alert{ var mycopy = critical() mycopy.icon = IconsManager.shared.stopIcon.normalImage() return mycopy } } public final class Reachability: SimpleReachability{ public override class var simulatedStatus: Bool?{ return TINU.simulateReachabilityStatus } } extension Dictionary: GenericCodable { } extension Array: GenericCodable { }
gpl-2.0
6f21fee9cef7a1a6ee39eb9f8151a9de
29.185185
300
0.758282
3.808411
false
false
false
false
soffes/X
Sources/X/CGSize.swift
1
1714
import Foundation import CoreGraphics #if os(macOS) public func NSStringFromCGSize(_ size: CGSize) -> String! { return NSStringFromSize(size) } public func CGSizeFromString(_ string: String!) -> CGSize { return NSSizeFromString(string) as CGSize } #else import UIKit #endif extension CGSize { public var stringRepresentation: String { #if os(macOS) return NSStringFromCGSize(self) #else return NSCoder.string(for: self) #endif } public init(string: String) { #if os(macOS) self = CGSizeFromString(string) #else self = NSCoder.cgSize(for: string) #endif } public var integral: CGSize { return CGSize(width: ceil(width), height: ceil(height)) } public func aspectFit(_ boundingSize: CGSize) -> CGSize { let aspectRatio = self var size = boundingSize let widthRatio = boundingSize.width / aspectRatio.width let heightRatio = boundingSize.height / aspectRatio.height if widthRatio < heightRatio { size.height = boundingSize.width / aspectRatio.width * aspectRatio.height } else if (heightRatio < widthRatio) { size.width = boundingSize.height / aspectRatio.height * aspectRatio.width } return size } public func aspectFill(_ minimumSize: CGSize) -> CGSize { let aspectRatio = self var size = minimumSize let widthRatio = minimumSize.width / aspectRatio.width let heightRatio = minimumSize.height / aspectRatio.height if widthRatio > heightRatio { size.height = minimumSize.width / aspectRatio.width * aspectRatio.height } else if heightRatio > widthRatio { size.width = minimumSize.height / aspectRatio.height * aspectRatio.width } return size } }
mit
5e1003a64ac34303639747b5a21e056d
26.206349
76
0.698366
4.110312
false
false
false
false
P0ed/FireTek
Source/SpaceEngine/SpaceEngine.swift
1
2391
import PowerCore import SpriteKit import Fx final class SpaceEngine { struct Model { unowned let scene: SpaceScene let inputController: InputController } static let timeStep = 1.0 / 60.0 as CFTimeInterval private let model: Model let world: World private var levelSystem: LevelSystem private let spriteSpawnSystem: SpriteSpawnSystem private let inputSystem: InputSystem private let physicsSystem: PhysicsSystem private let collisionsSystem: CollisionsSystem private let damageSystem: DamageSystem private let targetSystem: TargetSystem private var aiSystem: AISystem private let cameraSystem: CameraSystem private var weaponSystem: WeaponSystem private let projectileSystem: ProjectileSystem private let lifetimeSystem: LifetimeSystem private let lootSystem: LootSystem private let hudSystem: HUDSystem private let planetarySystem: PlanetarySystem init(_ model: Model) { self.model = model let world = World() self.world = world spriteSpawnSystem = SpriteSpawnSystem(scene: model.scene, store: world.sprites) physicsSystem = PhysicsSystem(world: world) collisionsSystem = CollisionsSystem(scene: model.scene) weaponSystem = WeaponSystem(world: world) damageSystem = DamageSystem(world: world) targetSystem = TargetSystem(targets: world.targets) projectileSystem = ProjectileSystem(world: world, collisionsSystem: collisionsSystem, damageSystem: damageSystem) levelSystem = LevelSystem(world: world, level: .default) inputSystem = InputSystem(world: world, player: levelSystem.state.value.player, inputController: model.inputController) aiSystem = AISystem(world: world) lifetimeSystem = LifetimeSystem(world: world) lootSystem = LootSystem(world: world, collisionsSystem: collisionsSystem) cameraSystem = CameraSystem(player: world.sprites[0].sprite, camera: model.scene.camera!) cameraSystem.update() hudSystem = HUDSystem(world: world, player: levelSystem.state.value.player, hudNode: model.scene.hud) planetarySystem = PlanetarySystem(planets: world.planets) } func simulate() { inputSystem.update() physicsSystem.update() planetarySystem.update() weaponSystem.update() targetSystem.update() projectileSystem.update() levelSystem.update() // aiSystem.update() hudSystem.update() lootSystem.update() lifetimeSystem.update() } func didFinishUpdate() { cameraSystem.update() } }
mit
50ecfd92234514820d768d8e42f2fb50
27.129412
121
0.783354
3.712733
false
false
false
false
mcjcloud/Show-And-Sell
Show And Sell/RateXIBView.swift
1
4480
// // RateXIBView.swift // Show And Sell // // Created by Brayden Cloud on 4/25/17. // Copyright © 2017 Brayden Cloud. All rights reserved. // import UIKit protocol RateXIBViewDelegate { func rateXIBView(didSubmitRating rating: Int) } class RateXIBView: UIView { // MARK: UI Properties @IBOutlet var contentView: UIView! @IBOutlet var star1: UIButton! @IBOutlet var star2: UIButton! @IBOutlet var star3: UIButton! @IBOutlet var star4: UIButton! @IBOutlet var star5: UIButton! @IBOutlet var submitButton: UIButton! // MARK: Properties var buttons: [UIButton]! var parentView: UIView? var blurEffectView: UIVisualEffectView! var rating: Int = 0 var delegate: RateXIBViewDelegate? init(parentView: UIView) { self.parentView = parentView let width = parentView.frame.width - 20 let height = width * 0.35 let frame = CGRect(x: 0, y: 0, width: width, height: height) super.init(frame: frame) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { Bundle.main.loadNibNamed("RateXIB", owner: self, options: nil) self.addSubview(self.contentView) self.contentView.frame = self.bounds buttons = [star1, star2, star3, star4, star5] for button in buttons { button.addTarget(self, action: #selector(starPressed(_:)), for: .touchUpInside) } print("submit button: \(submitButton)") submitButton.setTitleColor(UIColor.gray, for: .disabled) submitButton.addTarget(self, action: #selector(rateGroup(_:)), for: .touchUpInside) updateSubmitButton() } func show(rating: Int) { if let view = parentView { self.contentView.clipsToBounds = true self.contentView.layer.cornerRadius = 10 self.contentView.layer.zPosition = 1 self.center = view.center self.contentView.alpha = 0.0 let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) blurEffectView = UIVisualEffectView(effect: blurEffect) let touchRecognizer = UITapGestureRecognizer(target: self, action: #selector(hide)) touchRecognizer.cancelsTouchesInView = false blurEffectView.addGestureRecognizer(touchRecognizer) //always fill the view blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] blurEffectView.alpha = 0.0 view.addSubview(blurEffectView) view.addSubview(self) // fill rating stars for i in 0..<rating { buttons[i].setBackgroundImage(UIImage(named: "starfilled")!, for: .normal) } for i in rating..<buttons.count { buttons[i].setBackgroundImage(UIImage(named: "star")!, for: .normal) } UIView.animate(withDuration: 0.2) { self.contentView.alpha = 1.0 self.blurEffectView.alpha = 1.0 } } } func hide() { UIView.animate(withDuration: 0.2, animations: { self.contentView.alpha = 0.0 self.blurEffectView.alpha = 0.0 }, completion: { finished in self.blurEffectView.removeFromSuperview() self.removeFromSuperview() }) } // MARK: Button pressed func starPressed(_ button: UIButton!) { let index = Int(buttons.index(of: button)!) self.rating = index + 1 for i in 0...index { buttons[i].setBackgroundImage(UIImage(named: "starfilled")!, for: .normal) } for i in (index + 1)..<buttons.count { buttons[i].setBackgroundImage(UIImage(named: "star")!, for: .normal) } updateSubmitButton() } func rateGroup(_ button: UIButton!) { print("rating group") delegate?.rateXIBView(didSubmitRating: self.rating) hide() } // MARK: Helper func updateSubmitButton() { submitButton.isEnabled = self.rating != 0 } }
apache-2.0
3529980daa860f7a154b671e33609d71
29.263514
95
0.576245
4.714737
false
false
false
false
kay-kim/stitch-examples
todo/ios/Pods/ExtendedJson/ExtendedJson/ExtendedJson/Source/Bson/Document.swift
1
4760
// // Document.swift // ExtendedJson // import Foundation public struct Document: BSONCollection, Codable, Collection { public typealias Element = (key: String, value: ExtendedJsonRepresentable) fileprivate var storage: [String: ExtendedJsonRepresentable] = [:] internal var orderedKeys = NSMutableOrderedSet() private let writeQueue = DispatchQueue.global(qos: .utility) public init() { } public init(key: String, value: ExtendedJsonRepresentable) { self[key] = value orderedKeys.add(key) } public init(dictionary: [String: ExtendedJsonRepresentable?]) { for (key, value) in dictionary { self[key] = value ?? nil orderedKeys.add(key) } } public init(extendedJson json: [String: Any?]) throws { for (key, value) in json { self[key] = try Document.decodeXJson(value: value) orderedKeys.add(key) } } public func index(after i: Dictionary<Document.Key, Document.Value>.Index) -> Dictionary<Document.Key, Document.Value>.Index { return self.storage.index(after: i) } public subscript(position: Dictionary<String, Document.Value>.Index) -> (key: String, value: ExtendedJsonRepresentable) { return self.storage[position] } public var startIndex: Dictionary<Key, Value>.Index { return self.storage.startIndex } public var endIndex: Dictionary<Key, Value>.Index { return self.storage.endIndex } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ExtendedJsonCodingKeys.self) guard let sourceMap = try? container.decode([String: String].self, forKey: ExtendedJsonCodingKeys.info) else { throw BsonError<Document>.illegalArgument( message: "decoder of type \(decoder) did enough information to map out a new bson document") } try sourceMap.forEach { (arg) throws in let (key, value) = arg self[key] = try Document.decode(from: container, decodingTypeString: value, forKey: ExtendedJsonCodingKeys.init(stringValue: key)!) orderedKeys.add(key) } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: ExtendedJsonCodingKeys.self) var sourceMap = [String: String]() try self.forEach { (arg) in let (k, v) = arg try Document.encodeKeyedContainer(to: &container, sourceMap: &sourceMap, forKey: ExtendedJsonCodingKeys(stringValue: k)!, withValue: v) } if (encoder.userInfo[BSONEncoder.CodingKeys.shouldIncludeSourceMap] as? Bool ?? false) { try container.encode(sourceMap, forKey: ExtendedJsonCodingKeys.info) } } // MARK: - Subscript /// Accesses the value associated with the given key for reading and writing, like a `Dictionary`. /// Document keeps the order of entry while iterating over itskey-value pair. /// Writing `nil` removes the stored value from the document and takes O(n), all other read/write action take O(1). /// If you wish to set a MongoDB value to `null`, set the value to `NSNull`. public subscript(key: String) -> ExtendedJsonRepresentable? { get { return storage[key] } set { writeQueue.sync { if newValue == nil { orderedKeys.remove(key) } else if storage[key] == nil { orderedKeys.add(key) } storage[key] = newValue } } } } extension Document: ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, ExtendedJsonRepresentable)...) { for (key, value) in elements { self[key] = value self.orderedKeys.add(key) } } } extension Document: Equatable { public static func ==(lhs: Document, rhs: Document) -> Bool { let lKeySet = Set(lhs.storage.keys) let rKeySet = Set(rhs.storage.keys) if lKeySet == rKeySet { for key in lKeySet { if let lValue = lhs.storage[key], let rValue = rhs.storage[key] { if !lValue.isEqual(toOther: rValue) { return false } } } return true } return false } }
apache-2.0
41d3e21b768a9ec2607f29115c88afae
33
130
0.571429
4.774323
false
false
false
false
Zewo/Zewo
Tests/IOTests/TLSTests.swift
1
4142
import XCTest @testable import IO @testable import Core @testable import Venice public class TLSTests: XCTestCase { var testsPath: String { var components = #file.components(separatedBy: "/") components.removeLast() return components.joined(separator: "/") + "/" } func testConnectionRefused() throws { let deadline = 1.minute.fromNow() let connection = try TLSStream(host: "127.0.0.1", port: 8005, deadline: deadline) XCTAssertThrowsError(try connection.open(deadline: deadline)) } func testReadWriteClosedSocket() throws { let deadline = 5.seconds.fromNow() let port = 8006 let channel = try Channel<Void>() let buffer = UnsafeMutableRawBufferPointer.allocate( byteCount: 1, alignment: MemoryLayout<UInt8>.alignment ) defer { buffer.deallocate() } let coroutine = try Coroutine { do { let host = try TLSHost( port: port, certificatePath: self.testsPath + "cert.pem", keyPath: self.testsPath + "key.pem" ) let stream = try host.accept(deadline: deadline) try channel.receive(deadline: deadline) try stream.close(deadline: deadline) XCTAssertThrowsError(try stream.write("123", deadline: deadline)) XCTAssertThrowsError(try stream.read(buffer, deadline: deadline)) try channel.receive(deadline: deadline) } catch { print(error) XCTFail("\(error)") } } let stream = try TLSStream(host: "127.0.0.1", port: port, deadline: deadline) try stream.open(deadline: deadline) try channel.send(deadline: deadline) try stream.close(deadline: deadline) XCTAssertThrowsError(try stream.close(deadline: deadline)) XCTAssertThrowsError(try stream.write("123", deadline: deadline)) XCTAssertThrowsError(try stream.read(buffer, deadline: deadline)) try channel.send(deadline: deadline) coroutine.cancel() } func testClientServer() throws { let deadline = 1.minute.fromNow() let port = 8009 let channel = try Channel<Void>() let buffer = UnsafeMutableRawBufferPointer.allocate( byteCount: 10, alignment: MemoryLayout<UInt8>.alignment ) defer { buffer.deallocate() } let coroutine = try Coroutine { do { let host = try TLSHost( port: port, certificatePath: self.testsPath + "cert.pem", keyPath: self.testsPath + "key.pem" ) let stream = try host.accept(deadline: deadline) try stream.write("Yo client!", deadline: deadline) let read: String = try stream.read(buffer, deadline: deadline) XCTAssertEqual(read, "Yo server!") try stream.close(deadline: deadline) try channel.send(deadline: deadline) } catch { XCTFail("\(error)") } } let stream = try TLSStream(host: "127.0.0.1", port: port, deadline: deadline) try stream.open(deadline: deadline) let read: String = try stream.read(buffer, deadline: deadline) XCTAssertEqual(read, "Yo client!") try stream.write("Yo server!", deadline: deadline) try stream.close(deadline: deadline) try channel.receive(deadline: deadline) coroutine.cancel() } } extension TLSTests { public static var allTests: [(String, (TLSTests) -> () throws -> Void)] { return [ ("testConnectionRefused", testConnectionRefused), ("testReadWriteClosedSocket", testReadWriteClosedSocket), ("testClientServer", testClientServer), ] } }
mit
b875f565eff7dcd706851f5f83a25f97
34.706897
89
0.558184
5.094711
false
true
false
false
yellokrow/XMLGenerator
XMLGenerator/XMLGenerator.swift
1
2315
// // XMLGenerator.swift // XMLGenerator // // Created by iury bessa on 7/11/14. // Copyright (c) 2014 yellokrow. All rights reserved. // import Foundation class XMLGenerator { var xmlString : NSMutableString = ""; var tags:Array<String> = []; let ELEMENT = "" init() { xmlString.appendString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") } init(ver:Double,encode:NSString) { xmlString.appendString("<?xml version=\"\(ver)\" encoding=\"\(encode)\"?>") } func tag(tagName:NSString) { assert(tagName != ELEMENT, "CANNOT HAVE TAGNAME TO BE EMPTY") xmlString.appendString("<\(tagName)>") tags.append(tagName) } func tagAttributes(attributes:NSDictionary) { var tempXMLAttributes: NSMutableString = "" let keys = attributes.allKeys let lastIndex = keys.count - 1 var counter = 0 for k in keys { let value:NSString = attributes.objectForKey(k) as NSString if(counter != lastIndex) { tempXMLAttributes.appendString("\(k)=\"\(value)\" ") } else { tempXMLAttributes.appendString("\(k)=\"\(value)\"") } counter++; } let range = NSRange(location: xmlString.length - 1, length: 1) xmlString = NSMutableString(string: xmlString.stringByReplacingCharactersInRange(range, withString: " ")) xmlString.appendString("\(tempXMLAttributes)>") } func addElement(input: NSString) { xmlString.appendString("\(input)</\(tags[tags.count-1])>") tags.removeLast() } func end() { assert(tags.count > 0, "Can't remove tag when there aren't any") let range = NSRange(location: xmlString.length - 1, length: 1) xmlString = NSMutableString(string: xmlString.stringByReplacingCharactersInRange(range, withString: "/>")) tags.removeLast() } func endTag() { assert(tags.count > 0, "Can't remove tag when there aren't any") xmlString.appendString("</\(tags[tags.count-1])>") tags.removeLast() } func output() -> String { return xmlString } }
mit
5e7ad02267d530205ba8bdea623159f5
26.247059
114
0.560691
4.593254
false
false
false
false
jonbalbarin/LibGroupMe
LibGroupMe/LibGroupMe.swift
1
2844
// // LibGroupMe.swift // LibGroupMe // // Created by Jon Balbarin on 6/17/15. // Copyright (c) 2015 Jon Balbarin. All rights reserved. // import Foundation /** public interface for networking, database access */ public class GroupMe: NSObject { private(set) public var apiClient : APIClient! private(set) public var storage : Storage! /** injects independent networking, database storage layers */ required public init(apiClient: APIClient, storage:Storage) { self.apiClient = apiClient self.storage = storage super.init() } /** - parameter updated: - a block that gets called back with results(twice, once with cached data, again with fetched data, with the resultant powerups - parameter _: - the list of - parameter isFromCache: - `true` whether powerups were fetched from database, `false` if they were fetched from network */ public func powerups(updated: ((Array<Powerup>?, isFromCache:Bool) -> Void)) { self.storage.fetchPowerups({(cachedPowerups: Array<Powerup>?) in updated(cachedPowerups, isFromCache:true) }) self.apiClient.fetchPowerups({(powerupsDict: NSDictionary) in var updatedPowerups: Array = Array<Powerup>() if let powerupInfos = powerupsDict["powerups"] as? NSArray { for p in powerupInfos { updatedPowerups.append(Powerup(info: p as? NSDictionary)) } self.storage.storePowerups(updatedPowerups, completion: { () -> Void in }) updated(updatedPowerups, isFromCache:false) } }) } /** - parameter updated: - a block that gets called back with results (twice, once with cached data, again with fetched data, with the resultant groups - parameter _: - the list of fetched groups - parameter isFromCache: - `true` whether powerups were fetched from database, `false` if they were fetched from network */ public func groupsIndex(updated: ((Array<Group>?, isFromCache:Bool) -> Void)) { self.storage.fetchGroups({(cachedGroups: Array<Group>?) in updated(cachedGroups, isFromCache:true) }); self.apiClient.fetchGroups({(groupsDict: NSDictionary) in var groups: Array = Array<Group>() if let groupInfos = groupsDict["response"] as? NSArray { for info in groupInfos { groups.append(Group(info: info as! NSDictionary)) } } self.storage.storeGroups(groups, completion: { () -> Void in }) updated(groups, isFromCache:false) }) } }
mit
bc27a6761f635f9b799e0e69ec61b1fc
35.461538
156
0.592827
4.685338
false
false
false
false
janniklorenz/MyPlan
MyPlan/MPMenuViewController.swift
1
7852
// // MPMenu.swift // MyPlan // // Created by Jannik Lorenz on 07.04.15. // Copyright (c) 2015 Jannik Lorenz. All rights reserved. // import UIKit import CoreData protocol MPMenuViewControllerDelegate { func openPerson(person: Person) func openSettings() } class MPMenuViewController: UITableViewController, NSFetchedResultsControllerDelegate { let kSectionPersons = 0 let kSectionSettings = 1 var delegate: MPMenuViewControllerDelegate? var _fetchedResultsController: NSFetchedResultsController? var fetchedResultsController: NSFetchedResultsController { if self._fetchedResultsController != nil { return self._fetchedResultsController! } let managedObjectContext = NSManagedObjectContext.MR_defaultContext() let req = NSFetchRequest() req.entity = Person.MR_entityDescription() req.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] let aFetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) aFetchedResultsController.delegate = self self._fetchedResultsController = aFetchedResultsController var e: NSError? if !self._fetchedResultsController!.performFetch(&e) { println("fetch error: \(e!.localizedDescription)") abort(); } return self._fetchedResultsController! } // MARK: - Init required init() { super.init(style: UITableViewStyle.Grouped) self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.title = NSLocalizedString("Persons", comment: "") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } // MARK: - View Livestyle override func viewDidLoad() { super.viewDidLoad() // Add Person Button self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addPerson" ) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch (section) { case kSectionPersons: let info = self.fetchedResultsController.sections![kSectionPersons] as! NSFetchedResultsSectionInfo return info.numberOfObjects case kSectionSettings: return 1 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var reuseIdentifier: String switch indexPath.section { default: reuseIdentifier = "Cell" } let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! UITableViewCell cell.selectionStyle = .None switch (indexPath.section, indexPath.row) { case (kSectionPersons, 0...self.tableView(self.tableView, numberOfRowsInSection: kSectionPersons)): let person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person cell.textLabel?.text = person.title if person == (Settings.MR_findFirst() as! Settings).currentPerson { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } case (kSectionSettings, 0): cell.textLabel?.text = NSLocalizedString("Settings", comment: "") default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch (indexPath.section, indexPath.row) { case (kSectionPersons, 0...self.tableView(self.tableView, numberOfRowsInSection: kSectionPersons)): let person = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Person self.delegate?.openPerson(person) case (kSectionSettings, 0): self.delegate?.openSettings() default: break } } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { switch (indexPath.section, indexPath.row) { default: return false } } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { } 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 func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case kSectionPersons: return NSLocalizedString("Persons", comment: "") default: return nil } } /* // 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: - Add Person func addPerson() { MagicalRecord.saveWithBlockAndWait({ (localContext: NSManagedObjectContext!) -> Void in var person: Person = Person.MR_createInContext(localContext) as! Person! person.setDefaults(localContext) localContext.MR_saveToPersistentStoreAndWait() }) } // MARK: - NSFetchedResultsControllerDelegate func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject object: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Update: let cell = self.tableView.cellForRowAtIndexPath(indexPath!) self.tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Move: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) self.tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: self.tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } }
gpl-2.0
8e1a974990336a4c6893b10379d0dedb
30.534137
209
0.632323
5.989321
false
false
false
false
aniluyg/AUForms
Examples/SampleFormPage/SampleFormPage/AUForms/Validations/AUFormValidator.swift
2
2358
// // AUFormValidator.swift // Copyright (c) 2015 Anıl Uygun // // 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. class AUFormValidator{ private var validators=[AUControlValidator]() init(){} func validate() -> Bool{ var isFormValid = true for validator in validators{ if(!validator.validate()){ isFormValid = false } } return isFormValid } func addValidator(validator:AUControlValidator){ self.validators.append(validator) } func removeValidator(validator:AUControlValidator){ if let index = Swift.find(self, validator){ self.validators.removeAtIndex(index) } } } extension AUFormValidator : CollectionType{ typealias Index = Int var startIndex: Int { return 0 } var endIndex: Int { return validators.count } subscript(i: Int) -> AUControlValidator { return validators[i] } typealias Generator = GeneratorOf<AUControlValidator> func generate() -> Generator { var index = 0 return GeneratorOf { if index < self.validators.count { return self.validators[index++] } return nil } } }
mit
9c0418b3d01bb8abd26fb2fd7d0575b2
30.44
82
0.652524
4.695219
false
false
false
false
Olinguito/YoIntervengoiOS
Yo Intervengo/Helpers/TabBar/LinkComponent.swift
1
3977
// // LinkComponent.swift // Yo Intervengo // // Created by Jorge Raul Ovalle Zuleta on 2/7/15. // Copyright (c) 2015 Olinguito. All rights reserved. // import UIKit class LinkComponent: UIView { var title:UIButton! var subtitle:UILabel! var date:UILabel! var actionPanel:Panel! var iconLink:UIImageView! let paddinLeft:CGFloat = 14 override init(frame: CGRect) { super.init(frame: frame) } convenience init(type:Int, frame:CGRect) { self.init() if type == 1{ self.frame = CGRect(x: 0, y: 0, width: frame.width, height: 106) } else{ self.frame = CGRect(x: paddinLeft, y: 0, width: 292, height: 72) self.layer.cornerRadius = 5; } self.backgroundColor = UIColor.whiteColor() iconLink = UIImageView(image: UIImage(named: "Empty")) iconLink.frame.origin = CGPoint(x: paddinLeft,y: paddinLeft) self.addSubview(iconLink) date = UILabel(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: 14, width: frame.width, height: 11)) date.text = "Fecha de publicación" date.font = UIFont(name: "Roboto-Light", size: 10) date.textColor = UIColor.greyDark() addSubview(date) title = UIButton(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: date.frame.maxY + 2 , width: frame.width, height: 16)) title.setTitle("Fuente del enlace", forState: UIControlState.Normal) title.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left title.titleLabel?.font = UIFont(name: "Roboto-Regular", size: 16) title.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) addSubview(title) subtitle = UILabel(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: title.frame.maxY + 2, width: frame.width - ((paddinLeft*2)+iconLink.frame.maxX), height: 13)) subtitle.text = "Descripción del enlace" subtitle.font = UIFont(name: "Roboto-Italic", size: 12) subtitle.lineBreakMode = NSLineBreakMode.ByWordWrapping subtitle.numberOfLines = 1 subtitle.textColor = UIColor.orangeYI() addSubview(subtitle) iconLink.center.y = title.center.y if type == 1 { actionPanel = Panel(frame: CGRectZero, data: NSMutableArray()) actionPanel.center = CGPoint(x: frame.width/2, y: subtitle.frame.maxY + 20) addSubview(actionPanel) var line = UIBezierPath(rect: CGRect(x: 0, y: frame.maxY-1, width: frame.width, height: 0)) var shape = CAShapeLayer(layer: line) var staticLine = CAShapeLayer() staticLine.path = line.CGPath staticLine.strokeColor = UIColor.greyLight().CGColor self.layer.addSublayer(staticLine) } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setAsNew(){ date.textColor = UIColor.greyLight() title.setTitleColor(UIColor.greyLight(), forState: UIControlState.Normal) subtitle.textColor = UIColor.greyLight() setIcon(UIImage(named: "Empty")!) date.text = "Fecha de publicación" title.setTitle("Fuente del enlace", forState: UIControlState.Normal) subtitle.text = "Descripción del enlace" iconLink.center.y = title.center.y } func setDates(dateStr:NSString!){ date.textColor = UIColor.orangeYI() date.text = dateStr as String! } func setIcon(image:UIImage){ if iconLink.isDescendantOfView(self){ iconLink.removeFromSuperview() } iconLink = UIImageView(image: image) iconLink.frame.origin = CGPoint(x: paddinLeft,y: paddinLeft) addSubview(iconLink) } }
mit
35b2e7c95ecf65bbe261ada7e0838878
34.473214
174
0.614649
4.108583
false
false
false
false
panyam/SwiftIO
Sources/DataWriter.swift
1
2066
// // DataWriter.swift // SwiftIO // // Created by Sriram Panyam on 1/3/16. // Copyright © 2016 Sriram Panyam. All rights reserved. // import Foundation public class DataWriter { private var writer : Writer public init (_ writer : Writer) { self.writer = writer } public func writeNBytes(numBytes : Int, _ value: Int, bigEndian: Bool, _ callback : CompletionCallback?) { var numBytesLeft = numBytes while numBytesLeft > 0 { let value : UInt8 = UInt8(truncatingBitPattern: ((value >> ((numBytesLeft - 1) * 8)) & 0xff)) if numBytesLeft == 1 { writer.write(value, callback) } else { writer.write(value, nil) } numBytesLeft -= 1 } } public func writeInt8(value: Int8, callback : CompletionCallback?) { return writeNBytes(1, Int(value), bigEndian: true, callback) } public func writeInt16(value: Int16, callback : CompletionCallback?) { return writeNBytes(2, Int(value), bigEndian: true, callback) } public func writeInt32(value: Int32, callback : CompletionCallback?) { return writeNBytes(4, Int(value), bigEndian: true, callback) } public func writeInt64(value: Int64, callback : CompletionCallback?) { return writeNBytes(8, Int(value), bigEndian: true, callback) } public func writeUInt8(value: UInt8, callback : CompletionCallback?) { return writeNBytes(1, Int(value), bigEndian: true, callback) } public func writeUInt16(value: UInt16, callback : CompletionCallback?) { return writeNBytes(2, Int(value), bigEndian: true, callback) } public func writeUInt32(value: UInt32, callback : CompletionCallback?) { return writeNBytes(4, Int(value), bigEndian: true, callback) } public func writeUInt64(value: UInt64, callback : CompletionCallback?) { return writeNBytes(8, Int(value), bigEndian: true, callback) } }
apache-2.0
7b6e7a835d40e2daebacb3894a07f2c1
28.927536
108
0.615981
4.01751
false
false
false
false
mercadopago/px-ios
px-templates/VIP.xctemplate/With header/___FILEBASENAME___Factory.swift
1
751
// ___FILEHEADER___ import UIKit enum ___FILEBASENAMEASIDENTIFIER___ { static func make() -> ViewController<___VARIABLE_productName:identifier___View, ___VARIABLE_productName:identifier___InteractorProtocol> { let view = ___VARIABLE_productName:identifier___View() let presenter = ___VARIABLE_productName:identifier___Presenter() let repository = ___VARIABLE_productName:identifier___Repository() let interactor = ___VARIABLE_productName:identifier___Interactor(presenter: presenter, repository: repository) let controller = ___VARIABLE_productName:identifier___ViewController(customView: view, interactor: interactor) presenter.controller = controller return controller } }
mit
2a1cd80651de7edb3458cf975eef29bc
45.9375
142
0.697736
5.402878
false
false
false
false
lanjing99/iOSByTutorials
iOS 9 by tutorials/02-introducing-app-search/starter/Colleagues/Colleagues/EmployeeViewController.swift
1
3223
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import EmployeeKit class EmployeeViewController: UIViewController { @IBOutlet weak var pictureImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var departmentLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var skillsLabel: UILabel! @IBOutlet weak var otherEmployeesLabel: UILabel! @IBOutlet weak var sameDepartmentContainerView: UIView! var employee: Employee! override func viewDidLoad() { super.viewDidLoad() pictureImageView.image = employee.loadPicture() nameLabel.text = employee.name departmentLabel.text = employee.department titleLabel.text = employee.title phoneLabel.text = employee.phone emailLabel.text = employee.email skillsLabel.text = employee.skills.joinWithSeparator(", ") otherEmployeesLabel.text = "Other employees in \(employee.department)" let activity = employee.userActivity switch Setting.searchIndexingPreference { case .Disabled: activity.eligibleForSearch = false case .ViewedRecords: activity.eligibleForSearch = true activity.contentAttributeSet?.relatedUniqueIdentifier = nil case .AllRecords: activity.eligibleForSearch = true } userActivity = activity } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let destination = segue.destinationViewController as? EmployeeListViewController where segue.identifier == "EmployeeListEmbedSegue" { destination.filterEmployees { employee -> Bool in employee.department == self.employee.department && employee.objectId != self.employee.objectId } } } override func updateUserActivityState(activity: NSUserActivity) { activity.addUserInfoEntriesFromDictionary(employee.userActivityUserInfo) } @IBAction func call(sender: UITapGestureRecognizer) { employee.call() } @IBAction func email(sender: UITapGestureRecognizer) { employee.sendEmail() } }
mit
d11eaa7150895f6ee010b154486bbab6
34.811111
104
0.746199
4.958462
false
false
false
false
paulrehkugler/xkcd
Classes/CoreDataStack.swift
1
5338
// // CoreDataStack.swift // xkcd // // Created by Paul Rehkugler on 1/24/16. // // import CoreData /// A class that sets up the Core Data stack used in the application. final class CoreDataStack: NSObject { /// The directory where the application stores its documents. @objc var applicationsDocumentsDirectory: String /// The context where all of the Core Data objects are managed in the application. @objc var managedObjectContext: NSManagedObjectContext private var managedObjectModel: NSManagedObjectModel private var persistentStoreCoordinator: NSPersistentStoreCoordinator /// Holds the singleton returned by `sharedCoreDataStack()`. private static var sharedCoreDataStackStorage: CoreDataStack? /** A singleton Core Data stack instance that is used across the application. - note: Ideally we would use dependency injection instead of obfuscating the dependency graph like this. On the other hand, shipping is better than perfect. - returns: A fully initialized `CoreDataStack`. */ @objc class func sharedCoreDataStack() -> CoreDataStack { if let coreDataStack = CoreDataStack.sharedCoreDataStackStorage { return coreDataStack } else { let coreDataStack = CoreDataStack() CoreDataStack.sharedCoreDataStackStorage = coreDataStack return coreDataStack } } /** Initializes a `CoreDataStack`. - returns: A fully initialized `CoreDataStack`. */ override init() { let fileManager = FileManager.default guard let applicationsDocumentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, [.userDomainMask], true).first else { fatalError("Unable to get the applications documents directory.") } guard let managedObjectModel = NSManagedObjectModel.mergedModel(from: nil) else { fatalError("Unable to create a managed object model.") } // Clean up the old file from pervious versions let oldStorePath = (applicationsDocumentsDirectory as NSString).appendingPathComponent("xkcd.sqlite") if fileManager.fileExists(atPath: oldStorePath) { do { try fileManager.removeItem(atPath: oldStorePath) } catch let error as NSError { print("Error removing old SQLite file at \(oldStorePath): \(error.description)") } } let storePath = (applicationsDocumentsDirectory as NSString).appendingPathComponent("comics.sqlite") if !fileManager.fileExists(atPath: storePath) { if let bundledPath = Bundle.main.path(forResource: "comics", ofType: "sqlite") { if fileManager.fileExists(atPath: bundledPath) { do { try fileManager.copyItem(atPath: bundledPath, toPath: storePath) } catch let error as NSError { print("The SQLite database does not exist, and the sample one in the bundle is not able to be copied: \(error.description)") } } } } let storeURL = NSURL.fileURL(withPath: storePath) let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]) managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator } catch let error as NSError { fatalError("Unable to add the SQLite store to the persistent store coordinator: \(error.description)") } self.persistentStoreCoordinator = persistentStoreCoordinator self.applicationsDocumentsDirectory = applicationsDocumentsDirectory self.managedObjectModel = managedObjectModel super.init() NotificationCenter.default.addObserver(self, selector: #selector(UIApplicationDelegate.applicationWillTerminate(_:)), name: UIApplication.willTerminateNotification, object: nil) } // MARK: - Saving /** Saves the managed object context. */ @objc func save() { assert(Thread.isMainThread, "This Core Data stack only supports main thread concurrency.") if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch let error as NSError { print("Could not save CoreData changes: \(error.description)") } } } // MARK: - Notifications /** Called when the application will terminate. Do not call this directly. - parameter notification: The notification that triggered this method call. */ @objc func applicationWillTerminate(notification: NSNotification) { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch let error as NSError { print("Could not save CoreData changes: \(error.description)") exit(EXIT_FAILURE) } } } }
mit
e67b8c76844ad9bc54d2dc4903190dbb
36.858156
235
0.674223
5.808487
false
false
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/Weibo/Model/URLModel.swift
1
1436
// // URLModel.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/5/17. // Copyright © 2017年 伯驹 黄. All rights reserved. // import SwiftyJSON struct URLModel { /** 链接 */ // let result: Bool // let oriURL: String ///< 原始链接 // let urlType: Int ///< 0:一般链接 36地点 39视频/图片 // let log: String // let actionLog: [String: Any] // let storageType: String //如果是图片,则会有下面这些,可以直接点开看 // let picIds: [String] // let picInfos: [String: String] let pics: [PictureMetaModel]? let pageID: String? ///< 对应着 WBPageInfo let urlTitle: String ///< 显示文本,例如"网页链接",可能需要裁剪(24) let urlTypePic: String ///< 链接类型的图片URL let shortURL: String ///< 短域名 (原文) init(dict: [String: JSON]?) { shortURL = dict?["short_url"]?.stringValue ?? "" urlTitle = dict?["url_title"]?.stringValue ?? "" urlTypePic = dict?["url_type_pic"]?.stringValue ?? "" pageID = dict?["page_id"]?.stringValue let picInfos = dict?["pic_infos"]?.dictionaryValue let picIds: [String]? = dict?["pic_ids"]?.arrayValue.compactMap { $0.stringValue } pics = picIds?.map { return PictureMetaModel(dict: picInfos?[$0]?.dictionaryValue["large"]?.dictionaryValue) } } }
mit
508374cd718bca885c109679c875ee4c
28.790698
99
0.576893
3.471545
false
false
false
false
nickfrey/knightsapp
Newman Knights/DataSource.swift
1
9931
// // DataSource.swift // Newman Knights // // Created by Nick Frey on 12/20/15. // Copyright © 2015 Nick Frey. All rights reserved. // import Foundation class DataSource { class func fetchBookmarks(_ completionHandler: @escaping (Array<Bookmark>?, Error?) -> Void) { URLSession.shared.dataTask(with: URL(string: AppConfiguration.KnightsAPIURLString + "?action=info")!, completionHandler: { (data, response, error) -> Void in guard let data = data, error == nil else { return completionHandler(nil, error) } do { let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any> var bookmarks = Array<Bookmark>() if let links = response["links"] as? Array<Dictionary<String, AnyObject>> { for link in links { guard let title = link["title"] as? String else { continue } guard let url = link["url"] as? String else { continue } if let isDocument = link["document"] as? Bool, isDocument { bookmarks.append(Bookmark(title: title, icon: .default, URL: nil, documentID: url)) } else if let URL = URL(string: url) { bookmarks.append(Bookmark(title: title, icon: .default, URL: URL, documentID: nil)) } } } if let handbook = response["handbook"] as? Dictionary<String, AnyObject> { if let url = handbook["url"] as? String { if let isDocument = handbook["document"] as? Bool, isDocument { bookmarks.append(Bookmark(title: "Handbook", icon: .book, URL: nil, documentID: url)) } else if let URL = URL(string: url) { bookmarks.append(Bookmark(title: "Handbook", icon: .book, URL: URL, documentID: nil)) } } } completionHandler(bookmarks, nil) } catch _ { completionHandler(nil, nil) } }).resume() } class func fetchSchedules(_ completionHandler: @escaping (Array<Schedule>?, Error?) -> Void) { URLSession.shared.dataTask(with: URL(string: AppConfiguration.KnightsAPIURLString + "?action=schedules")!, completionHandler: { (data, response, error) -> Void in guard let data = data, error == nil else { return completionHandler(nil, error) } do { let response = try JSONSerialization.jsonObject(with: data, options: []) as! Dictionary<String, Any> var schedules = Array<Schedule>() if let responses = response["schedules"] as? Array<Dictionary<String, AnyObject>> { for schedule in responses { guard let title = schedule["title"] as? String else { continue } guard let url = schedule["url"] as? String else { continue } if let isDocument = schedule["document"] as? Bool, isDocument { schedules.append(Schedule(title: title, URL: nil, documentID: url)) } else if let URL = URL(string: url) { schedules.append(Schedule(title: title, URL: URL, documentID: nil)) } } } completionHandler(schedules, nil) } catch _ { let fallbackError = NSError( domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: [NSLocalizedDescriptionKey: "A bad response was received from the server."] ) completionHandler(nil, fallbackError) } }).resume() } class func fetchContacts(_ directory: Contact.Directory, completionHandler: @escaping (Array<Contact>?, Error?) -> Void) { var directoryString: String switch directory { case .administration: directoryString = "administration" case .faculty: directoryString = "faculty" case .office: directoryString = "office" } let fetchURL = URL(string: AppConfiguration.KnightsAPIURLString + "?action=contacts&directory=" + directoryString) URLSession.shared.dataTask(with: fetchURL!, completionHandler: { (data, response, error) -> Void in guard let data = data, error == nil else { return completionHandler(nil, error) } do { let response = try JSONSerialization.jsonObject(with: data, options: []) var contacts = Array<Contact>() if let response = response as? Array<Dictionary<String, AnyObject>> { for contact in response { guard let name = contact["name"] as? String else { continue } guard let title = contact["title"] as? String else { continue } guard let email = contact["email"] as? String else { continue } contacts.append(Contact(name: name, title: title, email: email)) } } completionHandler(contacts, nil) } catch _ { let fallbackError = NSError( domain: NSURLErrorDomain, code: NSURLErrorBadServerResponse, userInfo: [NSLocalizedDescriptionKey: "A bad response was received from the server."] ) completionHandler(nil, fallbackError) } }).resume() } class func fetchSocialPosts(_ count: Int?, completionHandler: @escaping (Array<SocialPost>?, Error?) -> Void) { let twitter = Swifter( consumerKey: AppConfiguration.Twitter.ConsumerKey, consumerSecret: AppConfiguration.Twitter.ConsumerSecret, appOnly: true ) twitter.authorizeAppOnly(success: { (accessToken, response) in twitter.getTimeline( for: "356522712", count: count, sinceID: nil, maxID: nil, trimUser: nil, contributorDetails: nil, includeEntities: true, success: { (jsonResponse) -> Void in guard let statuses = jsonResponse.array else { return completionHandler(nil, nil) } var tweets = Array<SocialPost>() let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.dateFormat = "EEE MMM d HH:mm:ss Z y" for status in statuses { var status = status if status["retweeted_status"].object != nil { status = status["retweeted_status"] } guard let identifier = status["id_str"].string else { continue } guard let content = status["text"].string else { continue } guard let createdAt = status["created_at"].string else { continue } guard let creationDate = dateFormatter.date(from: createdAt) else { continue } let avatarURLString = status["user"]["profile_image_url_https"].string?.replacingOccurrences(of: "_normal", with: "_bigger") var images = Array<URL>() if let mediaEntities = status["entities"]["media"].array { for mediaEntity in mediaEntities { guard let mediaType = mediaEntity["type"].string, mediaType == "photo" else { continue } guard let mediaURLString = mediaEntity["media_url_https"].string else { continue } if let URL = URL(string: mediaURLString) { images.append(URL) } } } tweets.append(SocialPost( identifier: identifier, author: SocialPost.Author( username: status["user"]["screen_name"].string, displayName: status["user"]["name"].string, avatarURL: (avatarURLString != nil ? URL(string: avatarURLString!) : nil) ), content: content, creationDate: creationDate, images: images, permalink: nil, source: .twitter, retweetCount: status["retweet_count"].integer, favoriteCount: status["favorite_count"].integer )) } completionHandler(tweets, nil) }, failure: { (error) -> Void in completionHandler(nil, error) }) }, failure: { (error) in completionHandler(nil, error) }) } }
mit
a8344ca678b5f38d159519f2c8b3cf4a
48.158416
170
0.482377
5.854953
false
false
false
false
0xfeedface1993/Xs8-Safari-Block-Extension-Mac
Sex8BlockExtension/Sex8BlockExtension/Decripter/PicsCollectionViewController.swift
1
6643
// // PicsCollectionViewController.swift // Sex8BlockExtension // // Created by virus1994 on 2017/6/25. // Copyright © 2017年 ascp. All rights reserved. // import Cocoa class PicsCollectionViewController: NSViewController, NSCollectionViewDelegate, NSCollectionViewDataSource, NSCollectionViewDelegateFlowLayout { @IBOutlet weak var collectionView: NSCollectionView! let ImageViewIdentifier = NSUserInterfaceItemIdentifier("image") var datas = [Pic]() let defaultImage = NSImage(named: "watting.jpeg") var downloadedImagesIndex = [Int]() var downloadingImagesIndex = [Int]() var downloadImages = [Int:NSImage]() var executingTask = [URLSessionDownloadTask]() override func viewDidLoad() { super.viewDidLoad() // Do view setup here. collectionView.register(ImageCollectionItem.self, forItemWithIdentifier: ImageViewIdentifier) let grid = NSCollectionViewFlowLayout() collectionView.collectionViewLayout = grid NotificationCenter.default.addObserver(self, selector: #selector(windowDidResize(notification:)), name: NSWindow.didResizeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(select), name: SelectItemName, object: nil) reloadImages() } deinit { NotificationCenter.default.removeObserver(self, name: SelectItemName, object: nil) NotificationCenter.default.removeObserver(self, name: NSWindow.didResizeNotification, object: nil) } //MARK: - NSCollectionViewDelegate func numberOfSections(in collectionView: NSCollectionView) -> Int { return datas.count } func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let item = collectionView.makeItem(withIdentifier: ImageViewIdentifier, for: indexPath) as! ImageCollectionItem item.maleImageView.image = downloadImages[indexPath.section] return item } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize { let item = downloadImages[indexPath.section] let padding : CGFloat = 20 let width : CGFloat = view.bounds.size.width - padding if let w = item?.size.width, let h = item?.size.height { let size = CGSize(width: width, height: w >= view.bounds.size.width ? (width / w * h):h) return size } return CGSize(width: width, height: width / self.defaultImage!.size.width * self.defaultImage!.size.height) } // func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, insetForSectionAt section: Int) -> EdgeInsets { // return NSEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) // } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } // // func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { // return 0 // } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> NSSize { return NSSize(width: 0, height: 0) } func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, referenceSizeForFooterInSection section: Int) -> NSSize { return NSSize(width: 0, height: 0) } // 清除缓存 func clearCacheImages() { self.executingTask.forEach({ task in if task.state == .running { task.cancel() } }) self.downloadedImagesIndex.removeAll() self.downloadImages.removeAll() self.downloadingImagesIndex.removeAll() self.executingTask.removeAll() } // 获取数据更新视图 @objc func select(notification: NSNotification) { datas = notification.object as? [Pic] ?? [] clearCacheImages() reloadImages() } // 重新获取数据 func reloadImages() { for (index, pic) in datas.enumerated() { if let imageData = pic.data, let image = NSImage(data: imageData as Data) { downloadedImagesIndex.append(index) downloadImages[index] = image } else { downloadingImagesIndex.append(index) downloadImages[index] = defaultImage DispatchQueue.global().async { if let urlString = pic.pic, let url = URL(string: urlString) { self.downloadingImagesIndex.append(index) let task = URLSession.shared.downloadTask(with: url, completionHandler: { (url, response, error) in if error == nil, let datURL = url, let img = NSImage(contentsOf: datURL) { DispatchQueue.main.async { self.downloadedImagesIndex.append(index) self.downloadImages[index] = img if let indx = self.downloadingImagesIndex.firstIndex(of: index) { self.downloadingImagesIndex.remove(at: indx) } let app = NSApplication.shared.delegate as! AppDelegate let pic = self.datas[index] pic.data = img.tiffRepresentation app.saveAction(nil) self.collectionView.reloadItems(at: [IndexPath(item: 0, section: index)]) } } }) self.executingTask.append(task) task.resume() } } } } collectionView.reloadData() } // 窗口事件 @objc func windowDidResize(notification: Notification) { collectionView.reloadData() } }
apache-2.0
c7166c6878f4159baee203f0a797ea9f
43.870748
177
0.615828
5.524288
false
false
false
false
aimobier/AVPlayExample
PlayerDemo/ViewController.swift
1
14357
// // ViewController.swift // PlayerDemo // // Created by 荆文征 on 2016/12/21. // Copyright © 2016年 aimobier. All rights reserved. // import UIKit import AVFoundation /// 模拟视频对象 class VideoModal: NSObject { var commit:Int! var title:String! var videoUrl:String! var coverUrl:String! init(commit:Int,title:String,videoUrl:String,coverUrl:String) { self.commit = commit self.title = title self.videoUrl = videoUrl self.coverUrl = coverUrl } class func DataSource() -> [VideoModal] { let video1 = "http://60.5.255.71/sohu.vodnew.lxdns.com/sohu/s26h23eab6/15/13/49aKiVoAISHXIDs7D22yEB.mp4?wshc_tag=0&wsiphost=ipdbm" let video2 = "http://101.28.249.72/sohu.vodnew.lxdns.com/sohu/s26h23eab6/193/142/tas6Zt4gReWdeh2eiBm7yD.mp4?wshc_tag=0&wsiphost=ipdbm" let v1 = VideoModal(commit: 1, title: "Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video1, coverUrl: "a") let v2 = VideoModal(commit: 2, title: "o 只需几分钟时间,若您在安装过程中遇到问题或无", videoUrl: video2, coverUrl: "b") let v3 = VideoModal(commit: 3, title: "译时可能会遇到问题,请先到 App Store 安装 Xcode", videoUrl: video2, coverUrl: "c") let v4 = VideoModal(commit: 4, title: "安装 Hexo 只需几分钟时间,若您在安装过程中遇到问题或无法找到解决方式,请提交问题,我会尽力解决您的问题。", videoUrl: video2, coverUrl: "d") let v5 = VideoModal(commit: 5, title: "Hexo单。然而在安装前,您必须检查电脑中是否已安擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video2, coverUrl: "e") let v6 = VideoModal(commit: 6, title: "Hexo 是一个快速单。然而在安装前,您必须检查电脑中是否已安丽的主题生成静态网页。", videoUrl: video2, coverUrl: "f") let v7 = VideoModal(commit: 7, title: "单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安否已安生成静态网页。", videoUrl: video2, coverUrl: "a") let v8 = VideoModal(commit: 8, title: "Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video1, coverUrl: "a") let v9 = VideoModal(commit: 9, title: "o 只需几分钟时间,若您在安装过程中遇到问题或无", videoUrl: video2, coverUrl: "b") let v10 = VideoModal(commit: 10, title: "译时可能会遇到问题,请先到 App Store 安装 Xcode", videoUrl: video2, coverUrl: "c") let v11 = VideoModal(commit: 11, title: "安装 Hexo 只需几分钟时间,若您在安装过程中遇到问题或无法找到解决方式,请提交问题,我会尽力解决您的问题。", videoUrl: video2, coverUrl: "d") let v12 = VideoModal(commit: 12, title: "Hexo单。然而在安装前,您必须检查电脑中是否已安擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video2, coverUrl: "e") let v13 = VideoModal(commit: 13, title: "Hexo 是一个快速单。然而在安装前,您必须检查电脑中是否已安丽的主题生成静态网页。", videoUrl: video2, coverUrl: "f") let v14 = VideoModal(commit: 14, title: "单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安否已安生成静态网页。", videoUrl: video2, coverUrl: "a") let v15 = VideoModal(commit: 15, title: "Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video1, coverUrl: "a") let v16 = VideoModal(commit: 16, title: "o 只需几分钟时间,若您在安装过程中遇到问题或无", videoUrl: video2, coverUrl: "b") let v17 = VideoModal(commit: 17, title: "译时可能会遇到问题,请先到 App Store 安装 Xcode", videoUrl: video2, coverUrl: "c") let v18 = VideoModal(commit: 18, title: "安装 Hexo 只需几分钟时间,若您在安装过程中遇到问题或无法找到解决方式,请提交问题,我会尽力解决您的问题。", videoUrl: video2, coverUrl: "d") let v19 = VideoModal(commit: 19, title: "Hexo单。然而在安装前,您必须检查电脑中是否已安擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video2, coverUrl: "e") let v20 = VideoModal(commit: 20, title: "Hexo 是一个快速单。然而在安装前,您必须检查电脑中是否已安丽的主题生成静态网页。", videoUrl: video2, coverUrl: "f") let v21 = VideoModal(commit: 21, title: "单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安否已安生成静态网页。", videoUrl: video2, coverUrl: "a") let v22 = VideoModal(commit: 22, title: "Hexo 是一个快速、简洁且高效的博客框架。Hexo 使用 Markdown(或其他渲染引擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video1, coverUrl: "a") let v23 = VideoModal(commit: 23, title: "o 只需几分钟时间,若您在安装过程中遇到问题或无", videoUrl: video2, coverUrl: "b") let v24 = VideoModal(commit: 24, title: "译时可能会遇到问题,请先到 App Store 安装 Xcode", videoUrl: video2, coverUrl: "c") let v25 = VideoModal(commit: 25, title: "安装 Hexo 只需几分钟时间,若您在安装过程中遇到问题或无法找到解决方式,请提交问题,我会尽力解决您的问题。", videoUrl: video2, coverUrl: "d") let v26 = VideoModal(commit: 26, title: "Hexo单。然而在安装前,您必须检查电脑中是否已安擎)解析文章,在几秒内,即可利用靓丽的主题生成静态网页。", videoUrl: video2, coverUrl: "e") let v27 = VideoModal(commit: 27, title: "Hexo 是一个快速单。然而在安装前,您必须检查电脑中是否已安丽的主题生成静态网页。", videoUrl: video2, coverUrl: "f") let v28 = VideoModal(commit: 28, title: "单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安单。然而在安装前,您必须检查电脑中是否已安否已安生成静态网页。", videoUrl: video2, coverUrl: "a") return [v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16,v17,v18,v19,v20,v21,v22,v23,v24,v25,v26,v27,v28] } } extension UINavigationController { open override var shouldAutorotate : Bool { return self.visibleViewController?.shouldAutorotate ?? false } open override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return self.visibleViewController?.supportedInterfaceOrientations ?? .portrait } open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{ return self.visibleViewController?.preferredInterfaceOrientationForPresentation ?? .portrait } } class ViewController: UIViewController { open override var shouldAutorotate: Bool{ return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait} override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } @IBOutlet var tableView:UITableView! let modals = VideoModal.DataSource() var manager:PlayerViewManager! let sView = UIView() override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorStyle = .none self.tableView.estimatedRowHeight = 100 self.tableView.rowHeight = UITableViewAutomaticDimension self.manager = PlayerViewManager( playProtocol: self) self.tableView.delegate = self.manager self.tableView.register(VideoTableVideoCell.self, forCellReuseIdentifier: "cell") } @IBAction func Click(_ sender: Any) { for (index,e) in modals.enumerated() { print(index,"-----",e.v_currentPlayer) } } } extension ViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return modals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let modal = modals[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! VideoTableVideoCell cell.finishModal(modal: modal) cell.clickBlock { self.modals.forEach{ $0.v_currentPlayer = false } modal.v_currentPlayer = true self.manager.PlayIndexPath(indexPath: indexPath, modal: modal) } return cell } } extension ViewController : PlayerTableViewControllerProtocol { var playTableView: UITableView { get { return self.tableView } } } extension VideoTableVideoCell : PlayerTableViewCellProtocol { var playContentView: UIView { get { return self.coverImageView} } } /// TablviewCell class VideoTableVideoCell: UITableViewCell { /// 标题Label let titleLabel = UILabel() /// 封面ImageView let coverImageView = UIImageView() /// 播放按钮 let playButton = UIButton() /// 放置 评论 Label 和 更多按钮 视图 let moreView = UIView() /// 评论Label let commitLabel = UILabel() /// 更多按钮 let moreButton = UIButton() /// 准备开始 播放某一个 视频 private var startPlayerVideo:(()->Void)? required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.addSubview(titleLabel) self.titleLabel.font = UIFont.systemFont(ofSize: 19) self.titleLabel.textColor = UIColor(red: 51/255, green: 51/255, blue: 51/255, alpha: 1) self.titleLabel.numberOfLines = 3 self.titleLabel.top.constraint(constant: 14) self.titleLabel.left.constraint(constant: 12) self.titleLabel.right.constraint(constant: -12) self.addSubview(coverImageView) self.coverImageView.contentMode = .scaleAspectFill coverImageView.clipsToBounds = true self.coverImageView.top.constraint( anchor: self.titleLabel.bottom, constant: 14) self.coverImageView.left.constraint(constant: 0) self.coverImageView.right.constraint(constant: 0) self.coverImageView.height.constraint(anchor: self.coverImageView.width, multiplier: 211/375) self.addSubview(playButton) self.playButton.setImage(UIImage(named: "video_play"), for: UIControlState.normal) self.playButton.centerX.constraint(anchor: self.coverImageView.centerX, constant: 0) self.playButton.centerY.constraint(anchor: self.coverImageView.centerY, constant: 0) self.addSubview(moreView) self.moreView.left.constraint() self.moreView.right.constraint() self.moreView.top.constraint( anchor: self.coverImageView.bottom) self.moreView.bottom.constraint() self.moreView.height.constraint(constant: 32) self.moreView.addSubview(moreButton) self.moreButton.setImage(UIImage(named: "video_share_black"), for: UIControlState.normal) self.moreButton.right.constraint(constant: -12) self.moreButton.centerY.constraint() self.moreView.addSubview(commitLabel) self.commitLabel.font = UIFont.systemFont(ofSize: 13) self.commitLabel.textColor = UIColor(red: 190/255, green: 190/255, blue: 190/255, alpha: 1) self.commitLabel.right.constraint( anchor: self.moreButton.left, constant: -14) self.commitLabel.centerY.constraint() self.playButton.addTarget(self, action: #selector(VideoTableVideoCell.clickPlayButton), for: UIControlEvents.touchUpInside) } /*** * 点击播放按钮 * 再点击播放按钮的时候开始初始化播放视图 ***/ internal func clickPlayButton(){ DispatchQueue.main.async { self.startPlayerVideo?() } } /*** * 填充数据 * 填充数据,并且完成视频播放的准备工作 * - parameter modal: 数据 * - parameter block: 用户点击播放按钮准备播放视频回调. ***/ func finishModal(modal m : VideoModal){ self.titleLabel.text = m.title self.commitLabel.text = "\(m.commit!)" self.coverImageView.image = UIImage(named: m.coverUrl) } /// 点击播放按钮 func clickBlock(block b :@escaping (()->Void)) { startPlayerVideo = b } }
mit
4a19b6e1fd199aa27f29dec0a2d700a0
40.736264
199
0.674214
3.264756
false
false
false
false
kfinn/puppies
Puppies/DetailCard.swift
1
1976
// // DetailCard.swift // Puppies // // Created by Kevin Finn on 11/16/14. // Copyright (c) 2014 Heptarex. All rights reserved. // import UIKit class DetailCard: UIView { private let tagsLabel : UILabel = { let tags = UILabel() tags.numberOfLines = 0 tags.setTranslatesAutoresizingMaskIntoConstraints(false) return tags }() private let gifView : GifView = { let gifView = GifView(frame: CGRectZero) gifView.setTranslatesAutoresizingMaskIntoConstraints(false) return gifView }() var gif : Gif? { didSet { gifView.gif = gif if let tags = gif?.tags.allObjects as? [String] { self.tagsLabel.text = ", ".join(tags) } } } var hasConstraints = false override init(frame: CGRect) { super.init(frame: frame) layer.cornerRadius = 10 layer.shadowOpacity = 0.5 backgroundColor = UIColor.whiteColor() setTranslatesAutoresizingMaskIntoConstraints(false) addSubview(tagsLabel) addSubview(gifView) self.setNeedsUpdateConstraints() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { if !hasConstraints { hasConstraints = true self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[gif]-|", options: .allZeros, metrics: nil, views: ["gif": gifView])) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[label]-|", options: .allZeros, metrics: nil, views: ["label": tagsLabel])) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[gif]-[label]-|", options: .allZeros, metrics: nil, views: ["gif": gifView, "label": tagsLabel])) } super.updateConstraints() } }
mit
d562838a3468f6b51d06b20f36bbe9ff
29.4
181
0.6083
5.040816
false
false
false
false
LIFX/Argo
Argo/Operators/Operators.swift
1
1748
import Runes infix operator <| { associativity left precedence 150 } infix operator <|? { associativity left precedence 150 } infix operator <|| { associativity left precedence 150 } infix operator <||? { associativity left precedence 150 } // MARK: Values // Pull value from JSON public func <|<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A> { return decodeObject(json) >>- { (A.decode <^> $0[key]) ?? .MissingKey(key) } } // Pull optional value from JSON public func <|?<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<A?> { return .optional(json <| key) } // Pull embedded value from JSON public func <|<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A> { return flatReduce(keys, json, <|) >>- A.decode } // Pull embedded optional value from JSON public func <|?<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<A?> { return .optional(json <| keys) } // MARK: Arrays // Pull array from JSON public func <||<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]> { return json <| key >>- decodeArray } // Pull optional array from JSON public func <||?<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, key: String) -> Decoded<[A]?> { return .optional(json <|| key) } // Pull embedded array from JSON public func <||<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]> { return json <| keys >>- decodeArray } // Pull embedded optional array from JSON public func <||?<A where A: JSONDecodable, A == A.DecodedType>(json: JSON, keys: [String]) -> Decoded<[A]?> { return .optional(json <|| keys) }
mit
f671052a112824eec434465ade6bedec
33.27451
109
0.665332
3.649269
false
false
false
false
shepting/AutoLayout
AutoLayoutDemo/AutoLayoutDemo/KeyboardAvoider.swift
1
2410
// // KeyboardAvoider.swift // AutoLayoutDemo // // Created by Steven Hepting on 8/22/14. // Copyright (c) 2014 Protospec. All rights reserved. // import UIKit class KeyboardAvoider: UIView { required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init () { super.init() commonInit() } weak var scrollView: UIScrollView? var heightConstraint: NSLayoutConstraint = NSLayoutConstraint() func commonInit() { setTranslatesAutoresizingMaskIntoConstraints(false) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) heightConstraint = self.constraintWithFormat("V:[self(0)]", views:["self": self]) addConstraint(heightConstraint) self.addVisualConstraints("H:[self(300@250)]", views: ["self":self]) // Low priority default width } func keyboardWillShow(notification: NSNotification) { // Save the height of keyboard and animation duration let userInfo: NSDictionary = notification.userInfo! let endFrame: NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as NSValue let keyboardRect: CGRect = endFrame.CGRectValue() let convertedRect = convertRect(keyboardRect, fromView: nil) // Convert from window coordinates let height = CGRectGetHeight(convertedRect) heightConstraint.constant = height if let scrollView = scrollView { scrollView.contentInset = UIEdgeInsetsMake(0, 0, height, 0) } animateSizeChange() } func keyboardWillHide(notification: NSNotification) { heightConstraint.constant = 0.0 animateSizeChange() } override func intrinsicContentSize() -> CGSize { return CGSizeMake(320, UIViewNoIntrinsicMetric) } func animateSizeChange() { self.setNeedsUpdateConstraints() // Animate transition UIView.animateWithDuration(0.3, animations: { self.superview!.layoutIfNeeded() }) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } }
mit
b4906bb231f8f0f1ac12d20119d4f65d
32.472222
154
0.66971
5.552995
false
false
false
false
swift-gtk/SwiftGTK
Sources/UIKit/GTypeHelper.swift
1
460
internal class GTypeHelper { private static let widgetType: GType = gtk_widget_get_type() private static let containerType = gtk_container_get_type() private static let binType = gtk_bin_get_type() class func convertToClass(_ type: GType) -> AnyObject.Type? { if type == widgetType { return Widget.self } else if type == containerType { return Container.self } else if type == binType { return Bin.self } else { return nil } } }
gpl-2.0
e0e31371c98907345c36d549c5e54b56
22
62
0.68913
3.333333
false
false
false
false
MyHZ/DouYuZB
DYZB/DYZB/Classes/Home/Controller/RecommendViewController.swift
1
5559
// // RecommendViewController.swift // DYZB // // Created by DM on 2016/11/17. // Copyright © 2016年 DM. All rights reserved. // import UIKit import SnapKit let kItemMargin : CGFloat = 10 let kItemW = (KScreenW - 3 * kItemMargin)/2 let kNormalItemH = kItemW * 3 / 4 let kPrettyItemH = kItemW * 4 / 3 let kHeadViewH:CGFloat = 50 let kNormalCellId = "kNormalCellId" let kPrettyCellId = "kPrettyCellId" let kHeaderViewID = "kHeaderViewID" let kCycleViewH = KScreenW * 3 / 8 let kGameViewH:CGFloat = 90 class RecommendViewController: UIViewController { lazy var recommendViewModel : RecommendViewModel = RecommendViewModel() lazy var collcetionView : UICollectionView = {[unowned self]in //创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: KScreenW, height: kHeadViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) //创建 UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = .white collectionView.dataSource = self collectionView.delegate = self collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellId) collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellId) collectionView.register(UINib(nibName: "CollecetionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier : kHeaderViewID) collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth] return collectionView }() lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommedCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH) , width: KScreenW, height: kCycleViewH) return cycleView }() lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: KScreenW, height: kGameViewH) return gameView }() override func viewDidLoad() { super.viewDidLoad() setupUI() // Do any additional setup after loading the view. loadData() collcetionView.addSubview(cycleView) collcetionView.addSubview(gameView) } } extension RecommendViewController{ func setupUI(){ view.addSubview(collcetionView) collcetionView.contentInset = UIEdgeInsetsMake(kCycleViewH + kGameViewH, 0, 0, 0) } } //请求数据 extension RecommendViewController{ func loadData(){ //1.请求推荐数据 recommendViewModel.requestData { self.collcetionView.reloadData() //将数据展示给collec self.gameView.groups = self.recommendViewModel.anchorGroups } //2.请求轮播数据 recommendViewModel.requestCycleData { print("数据请求完成") self.cycleView.cycleModles = self.recommendViewModel.cycleModels } } } extension RecommendViewController:UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{ func numberOfSections(in collectionView: UICollectionView) -> Int { return recommendViewModel.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let group = recommendViewModel.anchorGroups[section] return group.anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { //0.取出模型对象 let group = recommendViewModel.anchorGroups[indexPath.section] let anchor = group.anchors[indexPath.item] var cell:CollectionViewBaseCell! if indexPath.section == 1 { cell = collectionView .dequeueReusableCell(withReuseIdentifier: kPrettyCellId , for: indexPath) as! CollectionViewPrettyCell } else { cell = collectionView .dequeueReusableCell(withReuseIdentifier: kNormalCellId, for: indexPath) as! CollectionNormalCell } cell.anchor = anchor return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollecetionHeaderView headerView.group = recommendViewModel.anchorGroups[indexPath.section] return headerView } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{ let itemH = indexPath.section == 1 ? kPrettyItemH : kNormalItemH return CGSize.init(width: kItemW, height: itemH) } }
mit
e2b0429758374e61ef3e3962abd1f7e7
34.558442
188
0.679693
5.645361
false
false
false
false
simonnarang/Fandom-IOS
Fandomm/ShareCameraViewController.swift
1
1143
// // ShareCameraViewController.swift // Fandomm // // Created by Simon Narang on 12/21/15. // Copyright © 2015 Simon Narang. All rights reserved. // import UIKit import AVFoundation class ShareCameraViewController: UIViewController, /* For capturing barcodes */AVCaptureMetadataOutputObjectsDelegate { let captureSession = AVCaptureSession() var previewLayer : AVCaptureVideoPreviewLayer? var captureDevice : AVCaptureDevice? var userFandoms = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() captureSession.sessionPreset = AVCaptureSessionPresetHigh let devices = AVCaptureDevice.devices() func beginSession() { } for device in devices { if (device.hasMediaType(AVMediaTypeVideo)) { if(device.position == AVCaptureDevicePosition.Back) { captureDevice = device as? AVCaptureDevice if captureDevice != nil { print("Capture device found") beginSession() } } } } } }
unlicense
43bc230473cc9db5cb8bb4ce40b6039a
30.75
119
0.60683
5.886598
false
false
false
false
FuzzyHobbit/bitcoin-swift
BitcoinSwift/Models/IPAddress.swift
1
2873
// // IPAddress.swift // BitcoinSwift // // Created by Kevin Greene on 7/15/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public func ==(left: IPAddress, right: IPAddress) -> Bool { switch (left, right) { case (.IPV4(let leftWord), .IPV4(let rightWord)): return leftWord == rightWord case (.IPV6(let leftWord0, let leftWord1, let leftWord2, let leftWord3), .IPV6(let rightWord0, let rightWord1, let rightWord2, let rightWord3)): return leftWord0 == rightWord0 && leftWord1 == rightWord1 && leftWord2 == rightWord2 && leftWord3 == rightWord3 default: return false } } public enum IPAddress: Equatable { case IPV4(UInt32) case IPV6(UInt32, UInt32, UInt32, UInt32) } extension IPAddress: BitcoinSerializable { public var bitcoinData: NSData { var data = NSMutableData() // An IPAddress is encoded as 4 32-bit words. IPV4 addresses are encoded as IPV4-in-IPV6 // (12 bytes 00 00 00 00 00 00 00 00 00 00 FF FF, followed by the 4 bytes of the IPv4 address). // Addresses are encoded using network byte order (big endian). switch self { case .IPV4(let word): data.appendUInt32(0, endianness: .BigEndian) data.appendUInt32(0, endianness: .BigEndian) data.appendUInt32(0xffff, endianness: .BigEndian) data.appendUInt32(word, endianness: .BigEndian) case .IPV6(let word0, let word1, let word2, let word3): data.appendUInt32(word0, endianness: .BigEndian) data.appendUInt32(word1, endianness: .BigEndian) data.appendUInt32(word2, endianness: .BigEndian) data.appendUInt32(word3, endianness: .BigEndian) } return data } public static func fromBitcoinStream(stream: NSInputStream) -> IPAddress? { // An IPAddress is encoded as 4 32-bit words. IPV4 addresses are encoded as IPV4-in-IPV6 // (12 bytes 00 00 00 00 00 00 00 00 00 00 FF FF, followed by the 4 bytes of the IPv4 address). // Addresses are encoded using network byte order. let word0 = stream.readUInt32(endianness: .BigEndian) if word0 == nil { Logger.warn("Failed to parse word0 from IPAddress") return nil } let word1 = stream.readUInt32(endianness: .BigEndian) if word1 == nil { Logger.warn("Failed to parse word1 from IPAddress") return nil } let word2 = stream.readUInt32(endianness: .BigEndian) if word2 == nil { Logger.warn("Failed to parse word2 from IPAddress") return nil } let word3 = stream.readUInt32(endianness: .BigEndian) if word3 == nil { Logger.warn("Failed to parse word3 from IPAddress") return nil } if word0! == 0 && word1! == 0 && word2! == 0xffff { return IPAddress.IPV4(word3!) } return IPAddress.IPV6(word0!, word1!, word2!, word3!) } }
apache-2.0
2d1cdbab958fd51733d79477b56f3761
33.614458
99
0.660285
3.692802
false
false
false
false
pietro82/TransitApp
TransitApp/DirectionsDataManager.swift
1
6050
// // DirectionsDataManager.swift // TransitApp // // Created by Pietro Santececca on 24/01/17. // Copyright © 2017 Tecnojam. All rights reserved. // import MapKit class DirectionsDataManager { static func retreiveDirectionsOptions(originLocation: CLLocationCoordinate2D, arrivalLocation: CLLocationCoordinate2D, timeType: TimeType, time: Date) -> [DirectionsOption] { guard let result = parseJsonData() else { print("Error during JSON parsing: file is badly formatted") return [] } return result } static fileprivate func parseJsonData() -> [DirectionsOption]? { var options = [DirectionsOption]() guard let url = Bundle.main.url(forResource: "door2door", withExtension: "json") else { return nil } do { let data = try Data(contentsOf: url) if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let optionsJson = json["routes"] as? [[String: Any]] { for optionJson in optionsJson { // Directions mode guard let mode = optionJson["type"] as? String else { return nil } // Directions provider guard let provider = optionJson["provider"] as? String else { return nil } // Directions list guard let directionsJson = optionJson["segments"] as? [[String: Any]] else { return nil } // Directions price var price: Price? if let priceJson = optionJson["price"] as? [String: Any] { guard let currency = priceJson["currency"] as? String else { return nil } guard let amount = priceJson["amount"] as? Double else { return nil } price = Price(currency: currency, amount: amount) } var directions = [Direction]() for directionJson in directionsJson { // Direction name var name: String? if let nameJson = directionJson["name"] as? String { name = nameJson } // Direction num stops guard let numStops = directionJson["num_stops"] as? Int else { return nil } // Direction travel mode guard let travelMode = directionJson["travel_mode"] as? String else { return nil } // Direction description var description: String? if let descriptionJson = directionJson["description"] as? String { description = descriptionJson } // Direction color guard let color = directionJson["color"] as? String else { return nil } // Direction icon url guard let iconUrl = directionJson["icon_url"] as? String else { return nil } // Direction polyline var polyline: String? if let polylineJson = directionJson["polyline"] as? String { polyline = polylineJson } // Stops guard let stopsJson = directionJson["stops"] as? [[String: Any]] else { return nil } var stops = [Stop]() for stopJson in stopsJson { // Stop latitude guard let latitude = stopJson["lat"] as? Double else { return nil } // Stop longitude guard let longitude = stopJson["lng"] as? Double else { return nil } // Stop time guard let timeString = stopJson["datetime"] as? String, let timeDate = Utils.convertToDate(string: timeString) else { return nil } // Stop name var name: String? if let nameJson = stopJson["name"] as? String { name = nameJson } // Create a new stop let stop = Stop(name: name, latitude: latitude, longitude: longitude, time: timeDate, color: color) // Add stop to the stop list stops.append(stop) } // Create a new direction let direction = Direction(name: name, numStops: numStops, stops: stops, travelMode: travelMode, description: description, color: color, iconUrl: iconUrl, polyline: polyline) // Add direction to the directions list directions.append(direction) } // Create a new option let option = DirectionsOption(mode: mode, provider: provider, price: price, directions: directions) // Add option to the result list options.append(option) } } } catch { print("Error deserializing JSON: \(error)") } return options } }
mit
aa75737280ab5bcf8cf4cef2e14cd798
43.807407
197
0.440734
6.476445
false
false
false
false
tylow/surftranslate
surftranslate/SURF_Translate/CardTableViewController.swift
1
5643
// // CardTableViewController.swift // SURF_Translate // // Created by Legeng Liu on 6/2/16. // Copyright © 2016 SURF. All rights reserved. // import UIKit class CardTableViewController: UITableViewController, UINavigationControllerDelegate { //MARK: properties var cards = [Card]() //keeps track of all the Card objects //search let searchController = UISearchController(searchResultsController: nil) var filteredCards = [Card]() 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() /* //adding some sample Cards let card1 = Card(firstPhrase: "1", secondPhrase: "2", numTimesUsed: 0) let card2 = Card(firstPhrase: "English", secondPhrase: "Arabic", numTimesUsed: 0) let card3 = Card(firstPhrase: "I need water", secondPhrase: "أحتاج إلى الماء", numTimesUsed:0) cards += [card1, card2, card3] */ //search searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = true definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar } //how to be able to search both top and bottom string? func filterContentForSearchText(searchText:String){ filteredCards = cards.filter { card in return (card.firstPhrase.lowercaseString.containsString(searchText.lowercaseString)) || (card.secondPhrase.lowercaseString.containsString(searchText.lowercaseString)) } tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if searchController.active && searchController.searchBar.text != ""{ return filteredCards.count } else { return cards.count } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "CardTableViewCell" let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CardTableViewCell var card: Card if searchController.active && searchController.searchBar.text != "" { card = filteredCards[indexPath.row] } else { card = cards[indexPath.row] } cell.topPhrase.text = card.firstPhrase cell.bottomPhrase.text = card.secondPhrase return cell } /* // 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 false 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?) { if segue.identifier == "AddCard"{ print ("adding new card") } /* let card: Card if searchController.active && searchController.searchBar.text != ""{ card = filteredCards[indexPath.row] } else { card = cards[indexPath.row] } */ } @IBAction func unwindToCardList(sender: UIStoryboardSegue){ if let sourceViewController = sender.sourceViewController as? NewCardViewController, newCard = sourceViewController.newCard { //need to implement fav function later let newIndexPath = NSIndexPath(forRow: cards.count, inSection: 0) cards.append(newCard) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } } } extension CardTableViewController: UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) } }
agpl-3.0
0346e4c69e5c6063ce983557b5b111cc
32.307692
178
0.659442
5.562253
false
false
false
false
zixun/GodEye
GodEye/Classes/Main/Controller/TabController/FileController/FileBrowser/FileList/FileListViewController.swift
1
4743
// // FileListViewController.swift // FileBrowser // // Created by Roy Marmelstein on 12/02/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import UIKit class FileListViewController: UIViewController { // TableView @IBOutlet weak var tableView: UITableView! let collation = UILocalizedIndexedCollation.current() /// Data var didSelectFile: ((FBFile) -> ())? var didClose: (() -> ())? var files = [FBFile]() var initialPath: URL? let parser = FileParser.sharedInstance let previewManager = PreviewManager() var sections: [[FBFile]] = [] var allowEditing: Bool = false var showSize: Bool = false // Search controller var filteredFiles = [FBFile]() let searchController: UISearchController = { let searchController = UISearchController(searchResultsController: nil) searchController.searchBar.searchBarStyle = .minimal searchController.searchBar.backgroundColor = UIColor.fileBrowserBackground() searchController.dimsBackgroundDuringPresentation = false return searchController }() //MARK: Lifecycle convenience init (initialPath: URL, allowEditing: Bool = false) { self.init(initialPath: initialPath, showCancelButton: true, allowEditing: allowEditing) } convenience init (initialPath: URL, showCancelButton: Bool, allowEditing: Bool = false, showSize: Bool = false) { #if SWIFT_PACKAGE self.init(nibName: nil, bundle: .module) #else self.init(nibName: "FileListViewController", bundle: Bundle(for: FileListViewController.self)) #endif self.edgesForExtendedLayout = UIRectEdge() // Set initial path self.initialPath = initialPath self.title = initialPath.lastPathComponent self.allowEditing = allowEditing self.showSize = showSize // Set search controller delegates searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.delegate = self if showCancelButton { // Add dismiss button let dismissButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(FileListViewController.dismiss(button:))) self.navigationItem.rightBarButtonItem = dismissButton } } deinit{ if #available(iOS 9.0, *) { searchController.loadViewIfNeeded() } else { searchController.loadView() } } func prepareData() { // Prepare data if let initialPath = initialPath { files = parser.filesForDirectory(initialPath) indexFiles() } } //MARK: UIViewController override func viewDidLoad() { prepareData() // Set search bar tableView.tableHeaderView = searchController.searchBar // Register for 3D touch self.registerFor3DTouch() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Scroll to hide search bar self.tableView.contentOffset = CGPoint(x: 0, y: searchController.searchBar.frame.size.height) // Make sure navigation bar is visible self.navigationController?.isNavigationBarHidden = false } @objc func dismiss(button: UIBarButtonItem = UIBarButtonItem()) { self.dismiss(animated: true, completion: { self.didClose?() }) } //MARK: Data func indexFiles() { let selector: Selector = #selector(getter: FBFile.displayName) sections = Array(repeating: [], count: collation.sectionTitles.count) if let sortedObjects = collation.sortedArray(from: files, collationStringSelector: selector) as? [FBFile]{ for object in sortedObjects { let sectionNumber = collation.section(for: object, collationStringSelector: selector) sections[sectionNumber].append(object) } } } func fileForIndexPath(_ indexPath: IndexPath) -> FBFile { var file: FBFile if searchController.isActive { file = filteredFiles[(indexPath as NSIndexPath).row] } else { file = sections[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row] } return file } func filterContentForSearchText(_ searchText: String) { filteredFiles = files.filter({ (file: FBFile) -> Bool in return file.displayName.lowercased().contains(searchText.lowercased()) }) tableView.reloadData() } }
mit
b497022b37ddb35ae36b46427f5f828c
31.258503
151
0.635386
5.376417
false
false
false
false
269961541/weibo
xinlangweibo/Class/Other/Controller/XGWNewVersionController.swift
1
5424
// // XGWNewVersionController.swift // xinlangweibo // // Created by Mac on 15/10/30. // Copyright © 2015年 Mac. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class XGWNewVersionController: UICollectionViewController { //图片的个数 private let cont = 4 //布局属性 private var layou = UICollectionViewFlowLayout() //重写构造方法 init(){ super.init(collectionViewLayout: layou) } //写了上面的init方法会自动提示下面的方法 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //View开始启动的时候会调用 override func viewDidLoad() { super.viewDidLoad() //加载自定义cell为当前cell reuseIdentifier定义的重用标识 self.collectionView?.registerClass(XGWNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier) //调用方法准备UI prepareLayou() } //准备UI的固定方法 private func prepareLayou(){ //设置大小 layou.itemSize = UIScreen.mainScreen().bounds.size //设置间隔 layou.minimumInteritemSpacing = 0 layou.minimumLineSpacing = 0 //设置滚动方向为水平滚动 layou.scrollDirection = UICollectionViewScrollDirection.Horizontal //整页滚动 collectionView?.pagingEnabled = true // 取消弹簧效果 collectionView?.bounces = false } //返回页数 总共有多少张图片 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return cont } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! XGWNewFeatureCell //获得已经消失的图片索引 cell.imageIndex = indexPath.item return cell } // collectionView显示完毕cell // collectionView分页滚动完毕cell看不到的时候调用 override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { // 正在显示的cell的indexPath let showIndexPath = collectionView.indexPathsForVisibleItems().first! // 获取collectionView正在显示的cell let cell = collectionView.cellForItemAtIndexPath(showIndexPath) as! XGWNewFeatureCell // 最后一页动画 if showIndexPath.item == cont - 1 { // 开始按钮动画 cell.startButtonAnimation() } } } //MARK: 自定义Cell class XGWNewFeatureCell: UICollectionViewCell { //重写构造方法 override init(frame: CGRect) { super.init(frame: frame) prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } //MARK: 固定准备UI的方法 func prepareUI(){ self.addSubview(bgView) self.addSubview(startButton) //添加约束 bgView.translatesAutoresizingMaskIntoConstraints = false startButton.translatesAutoresizingMaskIntoConstraints = false //背景View的约束 // X bgView.ff_Fill(self) //开始点击按钮 startButton.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: self, size: nil, offset: CGPoint(x: 0, y: -160)) } //记录当前图片的张数 赋值属性 var imageIndex:Int = 0 { // didSet{ //根据索引获得下一张图片 bgView.image = UIImage(named: "new_feature_\(imageIndex + 1)") //隐藏开始体验按钮 startButton.hidden = true } } //MARK: 属性懒加载 //背景图片 lazy var bgView:UIImageView = UIImageView() //开始体验按钮 lazy var startButton:UIButton = { let btn = UIButton() // 设置按钮背景 btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal) btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted) btn.setTitle("开始体验", forState: UIControlState.Normal) btn.addTarget(self, action: "clickBtn", forControlEvents: UIControlEvents.TouchUpInside) return btn }() //MARK: 按钮的点击事件 func clickBtn(){ //跳转控制器 (UIApplication.sharedApplication().delegate as! AppDelegate).switchRootController(true) } // MARK: - 开始按钮动画 func startButtonAnimation() { startButton.hidden = false // 把按钮的 transform 缩放设置为0 startButton.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 5, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in self.startButton.transform = CGAffineTransformIdentity }) { (_) -> Void in } } }
apache-2.0
3336e30abdc614a787c2e5def8f58fb5
29.198758
178
0.641843
4.910101
false
false
false
false
stephentyrone/swift
test/Incremental/Dependencies/private-var-fine.swift
5
1068
// REQUIRES: shell // Also uses awk: // XFAIL OS=windows // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DOLD -emit-reference-dependencies-path %t.swiftdeps -module-name main -disable-direct-intramodule-dependencies | %FileCheck %s -check-prefix=CHECK-OLD // RUN: %S/../../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps // RUN: %target-swift-frontend -emit-silgen -primary-file %s %S/Inputs/InterestingType.swift -DNEW -emit-reference-dependencies-path %t.swiftdeps -module-name main -disable-direct-intramodule-dependencies | %FileCheck %s -check-prefix=CHECK-NEW // RUN: %FileCheck -check-prefix=CHECK-DEPS %s < %t-processed.swiftdeps private var privateVar: InterestingType { fatalError() } // CHECK-OLD: sil_global @$s4main1x{{[^ ]+}} : $Int // CHECK-NEW: sil_global @$s4main1x{{[^ ]+}} : $Double public var x = privateVar + 0 // CHECK-DEPS: topLevel interface '' InterestingType false
apache-2.0
dec2998d6f06fa7608b20d906a1cedab
52.4
244
0.735955
3.390476
false
false
false
false
zitao0322/DouyuDemo
Douyu/Douyu/Main/View/PageScrollView/PageScrollView.swift
1
2606
// // PageScrollView.swift // Douyu // // Created by venusource on 16/9/5. // Copyright © 2016年 venusource.com. All rights reserved. // import UIKit class PageScrollView: UIView { private var titlesArray: [String]! private var controllerArray: [UIViewController]! private var segmentStyle = SegmentStyle() private weak var parentController: UIViewController? deinit{ print("PageScrollView销毁") } init(frame: CGRect, segmentStyle: SegmentStyle?, titles: [String], controllers: [UIViewController], parentController: UIViewController) { self.parentController = parentController titlesArray = titles controllerArray = controllers if let style = segmentStyle{ self.segmentStyle = style } super.init(frame: frame) assert(titles.count == controllers.count, "title要和子控制器数量一致") setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("不能关联xib") } private func setupUI(){ //将控制器自动偏移关掉 guard let controller = parentController else { return } controller.automaticallyAdjustsScrollViewInsets = false addSubview(segmentView) addSubview(contentView) //实现title点击的闭包 segmentView.didClickTitle = {[unowned self] label,tag in let x = self.contentView.bounds.size.width * CGFloat(tag) self.contentView.setContentViewOffset( CGPointMake(x, 0), animated: self.segmentStyle.titleDidClickAnimated) } } //滚动view private lazy var segmentView: SegmentView = { let frame = CGRectMake(0, 0, self.bounds.width, 44) let view = SegmentView(frame: frame, segmentStyle: self.segmentStyle, titles: self.titlesArray) return view }() //内容view private lazy var contentView: ContentView = { let frame = CGRectMake(0, 44, self.bounds.width, self.bounds.height - 44) let view = ContentView(frame: frame, controllerArray: self.controllerArray, parentController: self.parentController!) view.delegate = self return view }() } extension PageScrollView: ContentViewDelegate{ var segView: SegmentView{ return segmentView } }
mit
0efcdae63d6d1f3162fca64c495e32cc
24.806122
81
0.586793
5.140244
false
false
false
false
AshuMishra/iAppStreetDemo
iAppStreet App/Third Party/PKHUD/FrameView.swift
13
1805
// // HUDView.swift // PKHUD // // Created by Philip Kluz on 6/16/14. // Copyright (c) 2014 NSExceptional. All rights reserved. // import UIKit /// Provides the general look and feel of the PKHUD, into which the eventual content is inserted. internal class FrameView: UIVisualEffectView { internal init() { super.init(effect: UIBlurEffect(style: .Light)) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { backgroundColor = UIColor(white: 0.8, alpha: 0.36) layer.cornerRadius = 9.0 layer.masksToBounds = true contentView.addSubview(self.content) let offset = 20.0 let motionEffectsX = UIInterpolatingMotionEffect(keyPath: "center.x", type: .TiltAlongHorizontalAxis) motionEffectsX.maximumRelativeValue = offset motionEffectsX.minimumRelativeValue = -offset let motionEffectsY = UIInterpolatingMotionEffect(keyPath: "center.y", type: .TiltAlongVerticalAxis) motionEffectsY.maximumRelativeValue = offset motionEffectsY.minimumRelativeValue = -offset var group = UIMotionEffectGroup() group.motionEffects = [motionEffectsX, motionEffectsY] addMotionEffect(group) } private var _content = UIView() internal var content: UIView { get { return _content } set { _content.removeFromSuperview() _content = newValue _content.alpha = 0.85 _content.clipsToBounds = true _content.contentMode = .Center frame.size = _content.bounds.size addSubview(_content) } } }
mit
b283c7fb4f50d60d6c13536175e15e25
28.590164
109
0.617175
5.013889
false
false
false
false
Palleas/memoires
MemoiresTests/OnboardingSpec.swift
1
3832
import Quick import Nimble import OHHTTPStubs import ReactiveSwift import Result @testable import Memoires class OnboardingSpec: QuickSpec { override func spec() { describe("OnboardingController") { var onboarding: OnboardingController! let factory = StaticStringTokenFactory(wrapped: "state-is-evil") beforeEach { onboarding = OnboardingController(credentials: .init(clientId: "client-id", clientSecret: "client-secret"), redirectURI: "memoires://auth", tokenFactory: factory) } afterEach { onboarding = nil OHHTTPStubs.removeAllStubs() } it("builds an URL to redirect the user to") { let url = URL(string: "https://github.com/login/oauth/authorize?client_id=client-id&redirect_uri=memoires://auth&scope=user%20repo&state=state-is-evil&allow_signup=false")! let initialState = onboarding.onboard().first()?.value expect(initialState) == OnboardingController.State.openAuthorizeURL(url) } it("handles auth redirect") { stub(condition: isHost("github.com"), response: { _ -> OHHTTPStubsResponse in let path = Bundle(for: type(of: self)).path(forResource: "access_token", ofType: "json", inDirectory: "fixtures")! return fixture(filePath: path, headers: nil) }) let redirectURL = URL(string: "memoires://auth?code=github-auth-code&state=state-is-evil")! var state: OnboardingController.State? onboarding .onboard() .flatMapError { _ in SignalProducer<OnboardingController.State, NoError>.empty } .startWithValues { state = $0 } onboarding.finalizeAuthentication(with: redirectURL) let expected = OnboardingController.State.token(Token(value: "e72e16c7e42f292c6912e7710c838347ae178b4a")) expect(state).toEventually(equal(expected)) } it("rejects invalid completion URL") { let redirectURL = URL(string: "memoires://auth?code=github-auth-code&state=this-is-not-the-right-state")! waitUntil { done in onboarding .onboard() .startWithFailed { error in expect(error) == OnboardingController.OnboardingError.internalError done() } onboarding.finalizeAuthentication(with: redirectURL) } } it("request a token") { stub(condition: isHost("github.com"), response: { _ -> OHHTTPStubsResponse in let path = Bundle(for: type(of: self)).path(forResource: "access_token", ofType: "json", inDirectory: "fixtures")! return fixture(filePath: path, headers: nil) }) let token = onboarding .requestToken(code: "some-code", state: "state") .first()? .value expect(token) == Token(value: "e72e16c7e42f292c6912e7710c838347ae178b4a") } } } } final class StaticStringTokenFactory: StateTokenFactory { let wrapped: String init(wrapped: String) { self.wrapped = wrapped } func generate() -> Token { return Token(value: wrapped) } }
mit
23ec37700f3f58c526ae1fd3f0ed2087
38.102041
188
0.522704
5.263736
false
false
false
false
to4iki/conference-app-2017-ios
conference-app-2017/domain/translater/TimetableTranslater.swift
1
1337
import OctavKit struct TimetableTranslater: Translator { static func translate(_ input: (conference: Conference, sessions: [Session])) -> [Timetable] { return input.conference.schedules.map { (schedule: Conference.Schedule) in let predicate: (Session) -> Bool = { $0.startsOn.startOfDay == schedule.open.startOfDay } let groupedByStartOfDay = input.sessions.lazy.filter(predicate).groping() let tracks = input.conference.tracks.reduce([]) { (acc: [Track], value: Conference.Track) -> [Track] in if let sessions = groupedByStartOfDay[value.roomId] { return acc + [Track(name: value.name, sessions: sessions)] } else { return acc } } return Timetable(schedule: schedule, tracks: tracks) } } } private extension Sequence where Iterator.Element == Session { func groping() -> [Id<Conference.Track.Room>: [Iterator.Element]] { var result: [Id<Conference.Track.Room>: [Iterator.Element]] = [:] for element in self { if result[element.room.id] == nil { result[element.room.id] = [element] } else { result[element.room.id]!.append(element) } } return result } }
apache-2.0
41fbe47c6ef8d761e49696448ff64959
39.515152
115
0.57816
4.398026
false
false
false
false
erikmartens/NearbyWeather
NearbyWeather/Scenes/Weather Map Scene/Map Annotations/Weather Station Information Preview Map Annotation/WeatherStationMeteorologyInformationPreviewAnnotationModel.swift
1
2367
// // WeatherMapAnnotationModel.swift // NearbyWeather // // Created by Erik Maximilian Martens on 10.01.21. // Copyright © 2021 Erik Maximilian Martens. All rights reserved. // import MapKit struct WeatherStationMeteorologyInformationPreviewAnnotationModel { let title: String? let subtitle: String? let weatherConditionSymbol: UIImage? let isDayTime: Bool? let tintColor: UIColor? let backgroundColor: UIColor? init( title: String? = nil, subtitle: String? = nil, weatherConditionSymbol: UIImage? = nil, isDayTime: Bool? = false, tintColor: UIColor? = nil, backgroundColor: UIColor? = nil ) { self.title = title self.subtitle = subtitle self.weatherConditionSymbol = weatherConditionSymbol self.isDayTime = isDayTime self.tintColor = tintColor self.backgroundColor = backgroundColor } init( weatherInformationDTO: WeatherInformationDTO, temperatureUnitOption: TemperatureUnitOption, isBookmark: Bool ) { let isDayTime = MeteorologyInformationConversionWorker.isDayTime(for: weatherInformationDTO.dayTimeInformation, coordinates: weatherInformationDTO.coordinates) ?? true var weatherConditionSymbol: UIImage? if let weatherConditionIdentifier = weatherInformationDTO.weatherCondition.first?.identifier { weatherConditionSymbol = MeteorologyInformationConversionWorker.weatherConditionSymbol( fromWeatherCode: weatherConditionIdentifier, isDayTime: isDayTime ) } var temperatureDescriptor: String? if let temperatureKelvin = weatherInformationDTO.atmosphericInformation.temperatureKelvin { temperatureDescriptor = MeteorologyInformationConversionWorker.temperatureDescriptor( forTemperatureUnit: temperatureUnitOption, fromRawTemperature: temperatureKelvin ) } let subtitle = temperatureDescriptor self.init( title: weatherInformationDTO.stationName, subtitle: subtitle, weatherConditionSymbol: weatherConditionSymbol, isDayTime: isDayTime, tintColor: Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundPrimaryTitle, backgroundColor: isDayTime ? Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundDay : Constants.Theme.Color.ViewElement.WeatherInformation.colorBackgroundNight ) } }
mit
58c3c9194442fddd24f2404b02ee08e7
33.289855
182
0.756128
5.177243
false
false
false
false
HabitRPG/habitrpg-ios
Habitica Database/Habitica Database/Models/User/RealmBuff.swift
1
1241
// // RealmBuff.swift // Habitica Database // // Created by Phillip Thelen on 13.03.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift class RealmBuff: Object, BuffProtocol { @objc dynamic var strength: Int = 0 @objc dynamic var intelligence: Int = 0 @objc dynamic var constitution: Int = 0 @objc dynamic var perception: Int = 0 @objc dynamic var shinySeed: Bool = false @objc dynamic var snowball: Bool = false @objc dynamic var seafoam: Bool = false @objc dynamic var streaks: Bool = false @objc dynamic var stealth: Int = 0 @objc dynamic var spookySparkles: Bool = false @objc dynamic var id: String? override static func primaryKey() -> String { return "id" } convenience init(id: String?, buff: BuffProtocol) { self.init() self.id = id strength = buff.strength intelligence = buff.intelligence constitution = buff.constitution perception = buff.perception shinySeed = buff.shinySeed seafoam = buff.seafoam streaks = buff.streaks stealth = buff.stealth spookySparkles = buff.spookySparkles } }
gpl-3.0
3d425f3e2747b2e5ccd026153d9eb15d
27.837209
55
0.654032
3.961661
false
false
false
false
cweatureapps/SwiftScraper
Sources/Browser.swift
1
10167
// // Browser.swift // SwiftScraper // // Created by Ken Ko on 21/04/2017. // Copyright © 2017 Ken Ko. All rights reserved. // import Foundation import WebKit // MARK: - Types /// The result of the browser navigation. typealias NavigationResult = Result<Void, SwiftScraperError> /// Invoked when the page navigation has completed or failed. typealias NavigationCallback = (_ result: NavigationResult) -> Void /// The result of some JavaScript execution. /// /// If successful, it contains the response from the JavaScript; /// If it failed, it contains the error. typealias ScriptResponseResult = Result<Any?, SwiftScraperError> /// Invoked when the asynchronous call to some JavaScript is completed, containing the response or error. typealias ScriptResponseResultCallback = (_ result: ScriptResponseResult) -> Void // MARK: - Browser /// The browser used to perform the web scraping. /// /// This class encapsulates the webview and its delegates, providing an closure based API. public class Browser: NSObject, WKNavigationDelegate, WKScriptMessageHandler { // MARK: - Constants private enum Constants { static let coreScript = "SwiftScraper" static let messageHandlerName = "swiftScraperResponseHandler" } // MARK: - Properties private let moduleName: String private (set) public var webView: WKWebView! private let userContentController = WKUserContentController() private var navigationCallback: NavigationCallback? private var asyncScriptCallback: ScriptResponseResultCallback? // MARK: - Setup /// Initialize the Browser object. /// /// - parameter moduleName: The name of the JavaScript module. By convention, the filename of the JavaScript file is the same as the module name. /// - parameter scriptBundle: The bundle from which to load the JavaScript file. Defaults to the main bundle. /// - parameter customUserAgent: The custom user agent string (only works for iOS 9+). init(moduleName: String, scriptBundle: Bundle = Bundle.main, customUserAgent: String? = nil) { self.moduleName = moduleName super.init() setupWebView(moduleName: moduleName, customUserAgent: customUserAgent, scriptBundle: scriptBundle) } private func setupWebView(moduleName: String, customUserAgent: String?, scriptBundle: Bundle) { let coreScriptURL = moduleResourceBundle().path(forResource: Constants.coreScript, ofType: "js") let coreScriptContent = try! String(contentsOfFile: coreScriptURL!) let coreScript = WKUserScript(source: coreScriptContent, injectionTime: .atDocumentEnd, forMainFrameOnly: true) userContentController.addUserScript(coreScript) let moduleScriptURL = scriptBundle.path(forResource: moduleName, ofType: "js") let moduleScriptContent = try! String(contentsOfFile: moduleScriptURL!) // TODO: prevent force try, propagate error let moduleScript = WKUserScript(source: moduleScriptContent, injectionTime: .atDocumentEnd, forMainFrameOnly: true) userContentController.addUserScript(moduleScript) userContentController.add(self, name: Constants.messageHandlerName) let config = WKWebViewConfiguration() config.userContentController = userContentController webView = WKWebView(frame: CGRect.zero, configuration: config) webView.navigationDelegate = self webView.allowsBackForwardNavigationGestures = true if #available(iOS 9.0, *) { webView.customUserAgent = customUserAgent } } /// Returns the resource bundle for this Pod where all the resources are kept, /// or defaulting to the framework module bundle (e.g. when running unit tests). private func moduleResourceBundle() -> Bundle { let moduleBundle = Bundle(for: Browser.self) guard let resourcesBundleURL = moduleBundle.url(forResource: "SwiftScraper", withExtension: ".bundle"), let resourcesBundle = Bundle(url: resourcesBundleURL) else { return moduleBundle } return resourcesBundle } // MARK: - WKNavigationDelegate public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { print("didFinishNavigation was called") callNavigationCompletion(result: .success(())) } public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { print("didFailProvisionalNavigation") let navigationError = SwiftScraperError.navigationFailed(error: error) callNavigationCompletion(result: .failure(navigationError)) } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { print("didFailNavigation was called") let nsError = error as NSError if nsError.domain == "NSURLErrorDomain" && nsError.code == NSURLErrorCancelled { return } let navigationError = SwiftScraperError.navigationFailed(error: error) callNavigationCompletion(result: .failure(navigationError)) } private func callNavigationCompletion(result: NavigationResult) { guard let navigationCompletion = self.navigationCallback else { return } // Make a local copy of closure before setting to nil, to due async nature of this, // there is a timing issue if simply setting to nil after calling the completion. // This is because the completion is the code that triggers the next step. self.navigationCallback = nil navigationCompletion(result) } // MARK: - WKScriptMessageHandler public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print("WKScriptMessage didReceiveMessage") guard message.name == Constants.messageHandlerName else { print("Ignoring message with name of \(message.name)") return } asyncScriptCallback?(.success(message.body)) } // MARK: - API /// Insert the WebView at index 0 of the given parent view, /// using AutoLayout to pin all 4 sides to the parent. func insertIntoView(parent: UIView) { parent.insertSubview(webView, at: 0) webView.translatesAutoresizingMaskIntoConstraints = false if #available(iOS 9.0, *) { webView.topAnchor.constraint(equalTo: parent.topAnchor).isActive = true webView.bottomAnchor.constraint(equalTo: parent.bottomAnchor).isActive = true webView.leadingAnchor.constraint(equalTo: parent.leadingAnchor).isActive = true webView.trailingAnchor.constraint(equalTo: parent.trailingAnchor).isActive = true } else { NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: parent, attribute: .top, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: parent, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: parent, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true NSLayoutConstraint(item: webView, attribute: .trailing, relatedBy: .equal, toItem: parent, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true } } /// Loads a page with the given path into the WebView. func load(path: String, completion: @escaping NavigationCallback) { self.navigationCallback = completion webView.load(URLRequest(url: URL(string: path)!)) } /// Run some JavaScript with error handling and logging. func runScript(functionName: String, params: [Any] = [], completion: @escaping ScriptResponseResultCallback) { guard let script = try? JavaScriptGenerator.generateScript(moduleName: moduleName, functionName: functionName, params: params) else { completion(.failure(SwiftScraperError.parameterSerialization)) return } print("script to run:", script) webView.evaluateJavaScript(script) { response, error in if let nsError = error as NSError?, nsError.domain == WKError.errorDomain, nsError.code == WKError.Code.javaScriptExceptionOccurred.rawValue { let jsErrorMessage = nsError.userInfo["WKJavaScriptExceptionMessage"] as? String ?? nsError.localizedDescription print("javaScriptExceptionOccurred error: \(jsErrorMessage)") completion(.failure(SwiftScraperError.javascriptError(errorMessage: jsErrorMessage))) } else if let error = error { print("javascript error: \(error.localizedDescription)") completion(.failure(SwiftScraperError.javascriptError(errorMessage: error.localizedDescription))) } else { print("javascript response:") print(response ?? "(no response)") completion(.success(response)) } } } /// Run some JavaScript that results in a page being loaded (i.e. navigation happens). func runPageChangeScript(functionName: String, params: [Any] = [], completion: @escaping NavigationCallback) { self.navigationCallback = completion runScript(functionName: functionName, params: params) { result in if case .failure(let error) = result { completion(.failure(error)) self.navigationCallback = nil } } } /// Run some JavaScript asynchronously, the completion being called when a script message is received from the JavaScript. func runAsyncScript(functionName: String, params: [Any] = [], completion: @escaping ScriptResponseResultCallback) { self.asyncScriptCallback = completion runScript(functionName: functionName, params: params) { result in if case .failure = result { completion(result) self.asyncScriptCallback = nil } } } }
mit
fcd582325058fa31688285480c155a2b
46.283721
170
0.69398
5.105977
false
false
false
false
skyfe79/RxPlayground
RxSectionedTableView/Pods/RxDataSources/Sources/DataSources/Changeset.swift
2
3339
// // Changeset.swift // RxDataSources // // Created by Krunoslav Zaher on 5/30/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation import CoreData #if !RX_NO_MODULE import RxSwift import RxCocoa #endif public struct Changeset<S: SectionModelType> { public typealias I = S.Item public let reloadData: Bool public let finalSections: [S] public let insertedSections: [Int] public let deletedSections: [Int] public let movedSections: [(from: Int, to: Int)] public let updatedSections: [Int] public let insertedItems: [ItemPath] public let deletedItems: [ItemPath] public let movedItems: [(from: ItemPath, to: ItemPath)] public let updatedItems: [ItemPath] init(reloadData: Bool = false, finalSections: [S] = [], insertedSections: [Int] = [], deletedSections: [Int] = [], movedSections: [(from: Int, to: Int)] = [], updatedSections: [Int] = [], insertedItems: [ItemPath] = [], deletedItems: [ItemPath] = [], movedItems: [(from: ItemPath, to: ItemPath)] = [], updatedItems: [ItemPath] = [] ) { self.reloadData = reloadData self.finalSections = finalSections self.insertedSections = insertedSections self.deletedSections = deletedSections self.movedSections = movedSections self.updatedSections = updatedSections self.insertedItems = insertedItems self.deletedItems = deletedItems self.movedItems = movedItems self.updatedItems = updatedItems } public static func initialValue(sections: [S]) -> Changeset<S> { return Changeset<S>( insertedSections: Array(0 ..< sections.count) as [Int], finalSections: sections, reloadData: true ) } } extension ItemPath : CustomDebugStringConvertible { public var debugDescription : String { get { return "(\(sectionIndex), \(itemIndex))" } } } extension Changeset : CustomDebugStringConvertible { public var debugDescription : String { get { let serializedSections = "[\n" + finalSections.map { "\($0)" }.joinWithSeparator(",\n") + "\n]\n" return " >> Final sections" + " \n\(serializedSections)" + (insertedSections.count > 0 || deletedSections.count > 0 || movedSections.count > 0 || updatedSections.count > 0 ? "\nSections:" : "") + (insertedSections.count > 0 ? "\ninsertedSections:\n\t\(insertedSections)" : "") + (deletedSections.count > 0 ? "\ndeletedSections:\n\t\(deletedSections)" : "") + (movedSections.count > 0 ? "\nmovedSections:\n\t\(movedSections)" : "") + (updatedSections.count > 0 ? "\nupdatesSections:\n\t\(updatedSections)" : "") + (insertedItems.count > 0 || deletedItems.count > 0 || movedItems.count > 0 || updatedItems.count > 0 ? "\nItems:" : "") + (insertedItems.count > 0 ? "\ninsertedItems:\n\t\(insertedItems)" : "") + (deletedItems.count > 0 ? "\ndeletedItems:\n\t\(deletedItems)" : "") + (movedItems.count > 0 ? "\nmovedItems:\n\t\(movedItems)" : "") + (updatedItems.count > 0 ? "\nupdatedItems:\n\t\(updatedItems)" : "") } } }
mit
617c503cacc196f1529c87fa1f111e87
33.061224
148
0.602756
4.421192
false
false
false
false
nathawes/swift
test/stdlib/MathConstants.swift
5
447
// RUN: %target-typecheck-verify-swift #if canImport(Darwin) import Darwin #elseif canImport(Glibc) import Glibc #elseif os(Windows) import MSVCRT #else #error("Unsupported platform") #endif _ = M_PI // expected-warning {{is deprecated}} _ = M_PI_2 // expected-warning {{is deprecated}} _ = M_PI_4 // expected-warning {{is deprecated}} _ = M_SQRT2 // expected-warning {{is deprecated}} _ = M_SQRT1_2 // expected-warning {{is deprecated}}
apache-2.0
cb310782ba53b7e0292a7d9d4d41e4be
23.833333
51
0.689038
3.23913
false
false
false
false
roambotics/swift
test/decl/func/vararg.swift
4
3438
// RUN: %target-typecheck-verify-swift var t1a: (Int...) = (1) // expected-error@-1 {{variadic expansion 'Int' must contain at least one variadic generic parameter}} var t2d: (Double = 0.0) = 1 // expected-error {{default argument not permitted in a tuple type}} {{18-23=}} func f1(_ a: Int...) { for _ in a {} } f1() f1(1) f1(1,2) func f2(_ a: Int, _ b: Int...) { for _ in b {} } f2(1) f2(1,2) f2(1,2,3) func f3(_ a: (String) -> Void) { } f3({ print($0) }) func f4(_ a: Int..., b: Int) { } // rdar://16008564 func inoutVariadic(_ i: inout Int...) { // expected-error {{'inout' must not be used on variadic parameters}} } // rdar://19722429 func invalidVariadic(_ e: NonExistentType) { // expected-error {{cannot find type 'NonExistentType' in scope}} { (e: ExtraCrispy...) in }() // expected-error {{cannot find type 'ExtraCrispy' in scope}} } func twoVariadics(_ a: Int..., b: Int...) { } func unlabeledFollowingVariadic(_ a: Int..., _ b: Int) { } // expected-error {{a parameter following a variadic parameter requires a label}} func unlabeledVariadicFollowingVariadic(_ a: Int..., _ b: Int...) { } // expected-error {{a parameter following a variadic parameter requires a label}} func unlabeledFollowingTwoVariadics(_ a: Int..., b: Int..., _ c: Int) { } // expected-error {{a parameter following a variadic parameter requires a label}} func splitVariadics(_ a: Int..., b: Int, _ c: String...) { } func splitByDefaultArgVariadics(_ a: Int..., b: Int = 0, _ c: String...) { } struct HasSubscripts { subscript(a: Int...) -> Void { () } subscript(a: Int..., b b: Int...) -> Void { () } subscript(a: Int..., b: Int...) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., b: Int) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., b b: Int..., c c: Int) -> Void { () } subscript(a: Int..., b b: Int..., c: Int) -> Void { () } // expected-error {{a parameter following a variadic parameter requires a label}} subscript(a: Int..., c c: Int = 0, b: Int...) -> Void { () } subscript(a: Int..., b: String = "hello, world!") -> Bool { false } // expected-error {{a parameter following a variadic parameter requires a label}} } struct HasInitializers { init(a: Int...) {} init(a: Int..., b: Int...) {} init(a: Int..., _ b: Int...) {} // expected-error {{a parameter following a variadic parameter requires a label}} init(a: Int..., c: Int = 0, _ b: Int...) {} } let closure = {(x: Int..., y: Int...) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure2 = {(x: Int..., y: Int) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure3 = {(x: Int..., y: Int, z: Int...) in } // expected-error {{no parameters may follow a variadic parameter in a closure}} let closure4 = {(x: Int...) in } let closure5 = {(x: Int, y: Int...) in } let closure6 = {(x: Int..., y z: Int) in } // expected-error {{closure cannot have keyword arguments}} // expected-error@-1 {{no parameters may follow a variadic parameter in a closure}} // rdar://22056861 func f5(_ list: Any..., end: String = "") {} f5(String()) // rdar://18083599 enum E1 { case On, Off } func doEV(_ state: E1...) {} doEV(.On) func hasDefaultArg(a: Int... = [5]) {} // expected-error {{variadic parameter cannot have a default value}}
apache-2.0
91dc0b5ed5c6234676f5e6dad23b6ef0
44.236842
155
0.625073
3.321739
false
false
false
false
citysite102/kapi-kaffeine
kapi-kaffeine/kapi-kaffeine/KPShopRatingCell.swift
1
9627
// // KPShopRatingCell.swift // kapi-kaffeine // // Created by YU CHONKAO on 2017/7/24. // Copyright © 2017年 kapi-kaffeine. All rights reserved. // import UIKit class KPShopRatingCell: UITableViewCell { var userPicture: UIImageView! var userNameLabel: UILabel! var timeHintLabel: UILabel! var scoreLabel: KPMainListCellScoreLabel! var separator: UIView! var rateTitles = ["WiFi穩定", "安靜程度", "價格實惠", "座位數量", "咖啡品質", "餐點美味", "環境舒適"] var rateImages = [R.image.icon_wifi(), R.image.icon_sleep(), R.image.icon_money(), R.image.icon_seat(), R.image.icon_cup(), R.image.icon_cutlery(), R.image.icon_pic()] var rateViews: [rateStatusView] = [rateStatusView]() var rateContents = [String]() var rateData: KPSimpleRateModel! { didSet { var totalRate: CGFloat = 0 var availableRateCount: CGFloat = 0 if let wifi = rateData.wifi { rateContents.append(rateData.wifi?.stringValue.count == 1 ? "\((rateData.wifi?.stringValue)!).0" : "\((rateData.wifi?.stringValue)!)") if wifi.floatValue != 0.0 { totalRate = totalRate + wifi.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let quiet = rateData.quiet { rateContents.append(rateData.quiet?.stringValue.count == 1 ? "\((rateData.quiet?.stringValue)!).0" : "\((rateData.quiet?.stringValue)!)") if quiet.floatValue != 0.0 { totalRate = totalRate + quiet.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let cheap = rateData.cheap { rateContents.append(rateData.cheap?.stringValue.count == 1 ? "\((rateData.cheap?.stringValue)!).0" : "\((rateData.cheap?.stringValue)!)") if cheap.floatValue != 0.0 { totalRate = totalRate + cheap.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let seat = rateData.seat { rateContents.append(rateData.seat?.stringValue.count == 1 ? "\((rateData.seat?.stringValue)!).0" : "\((rateData.seat?.stringValue)!)") if seat.floatValue != 0.0 { totalRate = totalRate + seat.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let tasty = rateData.tasty { rateContents.append(rateData.tasty?.stringValue.count == 1 ? "\((rateData.tasty?.stringValue)!).0" : "\((rateData.tasty?.stringValue)!)") if tasty.floatValue != 0.0 { totalRate = totalRate + tasty.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let food = rateData.food { rateContents.append(rateData.food?.stringValue.count == 1 ? "\((rateData.food?.stringValue)!).0" : "\((rateData.food?.stringValue)!)") if food.floatValue != 0.0 { totalRate = totalRate + food.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } if let music = rateData.music { rateContents.append(rateData.music?.stringValue.count == 1 ? "\((rateData.music?.stringValue)!).0" : "\((rateData.music?.stringValue)!)") if music.floatValue != 0.0 { totalRate = totalRate + music.cgFloatValue availableRateCount = availableRateCount+1 } } else { rateContents.append("0.0") } for (index, rateView) in rateViews.enumerated() { rateView.rateContentLabel.text = rateContents[index] } let averageRate = totalRate/availableRateCount scoreLabel.score = String(format: "%.1f", averageRate) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) userPicture = UIImageView(image: R.image.demo_profile()) userPicture.contentMode = .scaleAspectFit userPicture.layer.cornerRadius = 10.0 userPicture.layer.borderWidth = 1.0 userPicture.layer.borderColor = KPColorPalette.KPMainColor.grayColor_level5?.cgColor userPicture.layer.masksToBounds = true contentView.addSubview(userPicture) userPicture.addConstraints(fromStringArray: ["H:|-16-[$self(40)]", "V:|-24-[$self(40)]"]) userNameLabel = UILabel() userNameLabel.font = UIFont.systemFont(ofSize: 14.0) userNameLabel.text = "測試用名稱" userNameLabel.textColor = KPColorPalette.KPTextColor.mainColor contentView.addSubview(userNameLabel) userNameLabel.addConstraints(fromStringArray: ["H:[$view0]-16-[$self(190)]", "V:|-24-[$self]"], views:[userPicture]) timeHintLabel = UILabel() timeHintLabel.text = "一個世紀前" timeHintLabel.font = UIFont.systemFont(ofSize: 12.0) timeHintLabel.textColor = KPColorPalette.KPTextColor.grayColor_level4 contentView.addSubview(timeHintLabel) timeHintLabel.addConstraints(fromStringArray: ["[$view0]-16-[$self]"], views:[userPicture]) timeHintLabel.addConstraintForAligning(to: .bottom, of: userPicture, constant: -1) for (index, property) in rateTitles.enumerated() { let rateView = rateStatusView.init(frame:.zero, icon:rateImages[index]!, content:property, rateContent:"0.0") contentView.addSubview(rateView!) rateViews.append(rateView!) rateView!.addConstraint(forWidth: (UIScreen.main.bounds.size.width-48)/2) if index == 0 { rateView!.addConstraints(fromStringArray: ["V:[$view0]-20-[$self(24)]", "H:|-16-[$self]"], views:[userPicture]) } else if index == 4 { rateView!.addConstraints(fromStringArray: ["V:[$view0]-8-[$self(24)]-16-|", "H:|-16-[$self]"], views: [rateViews[index-1]]) } else if index == 5 { rateView!.addConstraints(fromStringArray: ["V:[$view1]-20-[$self(24)]", "H:[$view0]-16-[$self]"], views:[rateViews[0], userPicture]) } else if index == 6 || index == 7 || index == 8 { rateView!.addConstraints(fromStringArray: ["V:[$view0]-8-[$self(24)]", "H:[$view1]-16-[$self]"], views:[rateViews[index-1], rateViews[0]]) } else { rateView!.addConstraints(fromStringArray: ["V:[$view0]-8-[$self(24)]", "H:|-16-[$self]"], views: [rateViews[index-1]]) } } scoreLabel = KPMainListCellScoreLabel() scoreLabel.score = "0.0" contentView.addSubview(scoreLabel) scoreLabel.addConstraints(fromStringArray: ["H:[$self(32)]-16-|", "V:|-24-[$self(24)]"]) separator = UIView() separator.backgroundColor = KPColorPalette.KPBackgroundColor.grayColor_level6 contentView.addSubview(separator) separator.addConstraints(fromStringArray: ["V:[$self(1)]|", "H:|-16-[$self]|"]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
6126f82dc0949b750798e4a110d56c3b
40.894737
92
0.473095
5.182854
false
false
false
false
Eonil/SignalGraph.Swift
Code/Implementations/ValueStorage.swift
1
2375
// // ValueStorage.swift // SG5 // // Created by Hoon H. on 2015/07/04. // Copyright (c) 2015 Eonil. All rights reserved. // //public class ValueStorage<T>: ValueStorageType { public class ValueStorage<T> { public typealias Snapshot = T public typealias Transaction = ValueTransaction<T> public typealias OutgoingSignal = TimingSignal<Snapshot, Transaction> public typealias Signal = OutgoingSignal /// public init(_ snapshot: T) { _snapshot = snapshot } deinit { } /// public var state: T { get { return snapshot } set(v) { snapshot = v } } public var snapshot: T { get { return _snapshot } set(v) { apply(Transaction([(_snapshot, v)])) } } public func apply(transaction: Transaction) { assert(_isApplying == false, "You cannot call `apply` until application of prior transaction to be finished.") _isApplying = true _cast(HOTFIX_TimingSignalUtility.willEndStateByTransaction(_snapshot, transaction: transaction)) for m in transaction.mutations { _cast(HOTFIX_TimingSignalUtility.willEndStateByMutation(_snapshot, mutation: m)) _snapshot = m.future _cast(HOTFIX_TimingSignalUtility.didBeginStateByMutation(_snapshot, mutation: m)) } _cast(HOTFIX_TimingSignalUtility.didBeginStateByTransaction(_snapshot, transaction: transaction)) _isApplying = false } public func register(identifier: ObjectIdentifier, handler: Signal->()) { _relay.register(identifier, handler: handler) handler(HOTFIX_TimingSignalUtility.didBeginStateBySession(_snapshot)) } public func deregister(identifier: ObjectIdentifier) { _relay.handlerForIdentifier(identifier)(HOTFIX_TimingSignalUtility.willEndStateBySession(_snapshot)) _relay.deregister(identifier) } public func register<S: SensitiveStationType where S.IncomingSignal == OutgoingSignal>(s: S) { register(ObjectIdentifier(s)) { [weak s] in s!.cast($0) } } public func deregister<S: SensitiveStationType where S.IncomingSignal == OutgoingSignal>(s: S) { deregister(ObjectIdentifier(s)) } /// private typealias _Signal = Signal private let _relay = Relay<Signal>() private var _snapshot : T private var _isApplying = false private func _cast(signal: Signal) { _relay.cast(signal) } } //extension ValueStorage: SequenceType { // public func generate() -> GeneratorOfOne<T> { // return GeneratorOfOne(_snapshot) // } //}
mit
b8a1c2da7a5f9b8f0b3dffc4a0edc244
24.815217
112
0.724632
3.312413
false
false
false
false
adamhartford/MoneyTextField
MoneyTextField Example/ViewController.swift
1
1654
// // ViewController.swift // MoneyTextField Example // // Created by Adam Hartford on 5/23/15. // Copyright (c) 2015 Adam Hartford. All rights reserved. // import UIKit import MoneyTextField class ViewController: UIViewController { @IBOutlet weak var moneyField: MoneyTextField! @IBOutlet weak var moneyStepper: UIStepper! @IBOutlet weak var moneyLabel: UILabel! @IBOutlet weak var localeButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. textChanged(nil) updateLocale(NSLocale.currentLocale()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func textChanged(sender: AnyObject?) { moneyLabel.text = "Double value: \(moneyField.numberValue.doubleValue)" } @IBAction func moneyStepperChanged(sender: AnyObject?) { moneyField.negative = moneyStepper.value < 0 textChanged(nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showLocales" { let controller = segue.destinationViewController as! LocaleViewController controller.didSelectLocale = updateLocale } } func updateLocale(locale: NSLocale) { moneyField.locale = locale let name = NSLocale.currentLocale().displayNameForKey(NSLocaleIdentifier, value: locale.localeIdentifier) localeButton.setTitle(name, forState: .Normal) } }
mit
dab03e836009be56e8a1c168925c11a4
29.072727
113
0.681983
4.937313
false
false
false
false
cabarique/TheProposalGame
MyProposalGame/Scenes/Layers/TileLayer4.swift
1
21550
// // TileLayer4.swift // MyProposalGame // // Created by Luis Cabarique on 11/24/16. // Copyright © 2016 Luis Cabarique. All rights reserved. // import SpriteKit import GameplayKit class TileLayer4: TileLayer{ override var randomSceneryArt: [String] { get{ return ["Bush-1", "Bush-2", "DeadBush", "Skeleton", "TombStone-1", "TombStone-2", "Skeleton", "TombStone-1", "TombStone-2", "Tree"] } set{ } } convenience init(levelIndex: Int, typeIndex: setType) { self.init(levelIndex: levelIndex, typeIndex: typeIndex, textureName: "Tiles4" ) } override init(levelIndex: Int, typeIndex: setType, textureName: String) { super.init(levelIndex: levelIndex, typeIndex: typeIndex, textureName: textureName) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal override func createNodeOf(type type:tileType, location:CGPoint, level: Int) { //Handle each object switch type { case .tileAir: //Intentionally left blank if GameSettings.Builder.ALL_Black_Background { let node = SKSpriteNode(color: SKColor.blackColor(), size: CGSize(width: 32, height: 32)) node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) } break case .tileGroundLeft: let node = SGSpriteNode(texture: atlasTiles.textureNamed("1")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallL" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .leftOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tileGround: let node = SGInOutSpriteNode(texture: atlasTiles.textureNamed("2")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .topOutline, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileGroundRight: let node = SGSpriteNode(texture: atlasTiles.textureNamed("3")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallR" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .rightOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tileWallLeft: let node = SGSpriteNode(texture: atlasTiles.textureNamed("4")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileGroundMiddle: let node = SGSpriteNode(texture: atlasTiles.textureNamed("5")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileWallRight: let node = SGSpriteNode(texture: atlasTiles.textureNamed("6")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileGroundCornerR: let node = SGInOutSpriteNode(texture: atlasTiles.textureNamed("7")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .topOutline, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallR" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .rightOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tileGroundCornerRU: let node = SGSpriteNode(texture: atlasTiles.textureNamed("8")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileCeiling: let node = SGSpriteNode(texture: atlasTiles.textureNamed("9")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .bottomOutline, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileGroundCornerLU: let node = SGSpriteNode(texture: atlasTiles.textureNamed("10")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileGroundCornerL: let node = SGInOutSpriteNode(texture: atlasTiles.textureNamed("11")) node.tileSpriteType = type node.size = CGSize(width: 32, height: 32) node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .topOutline, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallL" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .leftOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tileCeilingLeft: let node = SGSpriteNode(texture: atlasTiles.textureNamed("12")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileCeilingRight: let node = SGSpriteNode(texture: atlasTiles.textureNamed("13")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tilePlatformLeft: let node = SGSpriteNode(texture: atlasTiles.textureNamed("14")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue | ColliderType.Enemy.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallL" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .leftOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tilePlatform: let node = SGSpriteNode(texture: atlasTiles.textureNamed("15")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue | ColliderType.Enemy.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tilePlatformRight: let node = SGSpriteNode(texture: atlasTiles.textureNamed("16")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Wall.rawValue, dynamic: false) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue | ColliderType.Enemy.rawValue) node.physicsBody = physicsComponent.physicsBody let invisibleWall = SKNode() invisibleWall.name = "invisibleWallR" invisibleWall.position = CGPointZero invisibleWall.zPosition = -1 let invisiblePhysicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .rightOutline, rotation: false) invisiblePhysicsComponent.setCategoryBitmask(ColliderType.InvisibleWall.rawValue, dynamic: false) invisiblePhysicsComponent.setPhysicsCollisions(ColliderType.Enemy.rawValue) invisibleWall.physicsBody = invisiblePhysicsComponent.physicsBody node.addChild(invisibleWall) addChild(node) break case .tileWaterSurface: let node = SGSpriteNode(texture: atlasTiles.textureNamed("17")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileWater: let node = SGSpriteNode(texture: atlasTiles.textureNamed("18")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileRandomScenery: let node = SGSpriteNode(texture: atlasTiles.textureNamed(randomSceneryArt[randomScenery.nextInt() - 1])) node.xScale = 0.5 node.yScale = 0.5 node.tileSpriteType = type node.anchorPoint = CGPoint(x: 0.5, y: 0.0) node.position = CGPoint(x: location.x, y: location.y - 16) node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileSignPost: let node = SGSpriteNode(texture: atlasTiles.textureNamed("Sign_1")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileSignArrow: let node = SGSpriteNode(texture: atlasTiles.textureNamed("Sign_2")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break case .tileCrate: let node = SGSpriteNode(texture: atlasTiles.textureNamed("Crate")) node.size = CGSize(width: 32, height: 32) node.tileSpriteType = type node.position = location node.zPosition = GameSettings.GameParams.zValues.zWorld node.name = "crateNode" let physicsComponent = PhysicsComponent(entity: GKEntity(), bodySize: node.size, bodyShape: .square, rotation: false) physicsComponent.setCategoryBitmask(ColliderType.Destroyable.rawValue, dynamic: true) physicsComponent.setPhysicsCollisions(ColliderType.Player.rawValue | ColliderType.Wall.rawValue | ColliderType.Destroyable.rawValue) node.physicsBody = physicsComponent.physicsBody addChild(node) break case .tileStartLevel: let node = SKNode() node.position = CGPoint(x: location.x, y: location.y) node.name = "placeholder_StartPoint" addChild(node) break case .tileEndLevel: let node = SKNode() node.position = location node.name = "placeholder_FinishPoint" addChild(node) break case .tileDiamond: let node = SKNode() node.position = location node.name = "placeholder_Diamond" addChild(node) case .tileCoin: let node = SKNode() node.position = location node.name = "placeholder_Coin" addChild(node) case .tileZombie: let node = SKNode() node.position = location node.name = "placeholder_Zombie1" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tileZombie2: let node = SKNode() node.position = location node.name = "placeholder_Zombie2" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tileMage1: let node = SKNode() node.position = location node.name = "placeholder_Mage1" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tileMage2: let node = SKNode() node.position = location node.name = "placeholder_Mage2" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tileBoss: let node = SKNode() node.position = location node.name = "placeholder_Boss" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tilePrincess: let node = SKNode() node.position = location node.name = "placeholder_Princess" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) case .tileEndDialog: let node = SKSpriteNode(color: SKColor.clearColor(), size: CGSize(width: 32, height: 32)) node.position = location node.name = "placeholder_EndDialog" node.zPosition = GameSettings.GameParams.zValues.zWorld addChild(node) break default: break } } }
mit
400e4b4b4f7c70b0127c426d24de0611
46.886667
144
0.627964
4.842472
false
false
false
false
silence0201/Swift-Study
Learn/10.属性和下标/计算属性概念.playground/section-1.swift
1
878
import Foundation class Employee { var no: Int = 0 var firstName: String = "Tony" var lastName: String = "Guan" var job: String? var salary: Double = 0 lazy var dept: Department = Department() var fullName: String { get { return firstName + "." + lastName } set (newFullName) { let name = newFullName.components(separatedBy: ".") firstName = name[0] lastName = name[1] } // set { // let name = newValue.components(separatedBy: ".") // firstName = name[0] // lastName = name[1] // } } } struct Department { let no: Int = 0 var name: String = "" } var emp = Employee() print(emp.fullName) emp.fullName = "Tom.Guan" print(emp.fullName)
mit
fcdc3d9392300ff323364859df1093e4
19.904762
70
0.490888
4.200957
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Controllers/ExerciseDetail/ExerciseDetailViewModel.swift
1
1356
// // ExerciseDetailViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/24/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmSwift import RealmS struct UserExerciseParams { var exerciseId: Int var duration: Int } class ExerciseDetailViewModel: NSObject { var exercise: Exercise var activity: HomeViewController.AddActivity init(exercise: Exercise, activity: HomeViewController.AddActivity) { self.exercise = exercise self.activity = activity } func save(duration: Int, completion: @escaping Completion) { if User.me == nil { let error = NSError(message: Strings.Errors.tokenError) completion(.failure(error)) return } else { let params = UserExerciseParams(exerciseId: exercise.id, duration: duration) ExerciseServices.save(params: params, completion: completion) } } func dataForHeaderView() -> MealHeaderView.Data? { return MealHeaderView.Data(title: exercise.name, detail: nil, image: activity.image) } func dataForAddUserExercise() -> AddUserExerciseCell.Data? { let `default` = exercise.duration let calories = exercise.calories return AddUserExerciseCell.Data(default: "\(`default`)", calories: "\(calories)") } }
mit
b5492c54f7b5e1362328394e3fa3c5fe
27.829787
92
0.667159
4.413681
false
false
false
false
ello/ello-ios
Sources/Networking/ElloProvider.swift
1
8275
//// /// ElloProvider.swift // import Moya import Alamofire import PromiseKit import WebLinking class ElloProvider { typealias Response = (Any, ResponseConfig) typealias RequestFuture = (target: ElloAPI, resolve: (Response) -> Void, reject: ErrorBlock) static let shared = ElloProvider() static func endpointClosure(_ target: ElloAPI) -> Endpoint { let url = target.baseURL.appendingPathComponent(target.path).absoluteString return Endpoint( url: url, sampleResponseClosure: { return target.stubbedNetworkResponse }, method: target.method, task: target.task, httpHeaderFields: target.headers ) } static func DefaultProvider() -> MoyaProvider<ElloAPI> { return MoyaProvider<ElloAPI>( endpointClosure: ElloProvider.endpointClosure, manager: ElloManager.alamofireManager ) } static var defaultProvider: MoyaProvider<ElloAPI> = ElloProvider.DefaultProvider() static var oneTimeProvider: MoyaProvider<ElloAPI>? static var moya: MoyaProvider<ElloAPI> { get { if let provider = oneTimeProvider { oneTimeProvider = nil return provider } return defaultProvider } set { defaultProvider = newValue } } func request(_ target: ElloAPI) -> Promise<Response> { let (promise, seal) = Promise<Response>.pending() sendRequest((target, resolve: seal.fulfill, reject: seal.reject)) return promise } private func sendRequest(_ request: RequestFuture) { AuthenticationManager.shared.attemptRequest( request.target, retry: { self.sendRequest(request) }, proceed: { uuid in ElloProvider.moya.request(request.target) { result in self.handleRequest(request: request, result: result, uuid: uuid) } }, cancel: { self.requestFailed(request: request) } ) } private func requestFailed(request: RequestFuture) { let elloError = NSError( domain: ElloErrorDomain, code: 401, userInfo: [NSLocalizedFailureReasonErrorKey: "Logged Out"] ) inForeground { request.reject(elloError) } } } extension ElloProvider { private func handleRequest(request: RequestFuture, result: MoyaResult, uuid: UUID) { switch result { case let .success(moyaResponse): switch moyaResponse.statusCode { case 200...299, 300...399: handleNetworkSuccess(request: request, response: moyaResponse) case 410: postOldAPINotification() case 401: AuthenticationManager.shared.attemptAuthentication( uuid: uuid, request: ( request.target, { self.sendRequest(request) }, { self.handleServerError(request: request, response: moyaResponse) } ) ) default: handleServerError(request: request, response: moyaResponse) } case .failure: handleNetworkFailure(request: request) } } private func handleNetworkSuccess(request: RequestFuture, response moyaResponse: Moya.Response) { let response = moyaResponse.response let data = moyaResponse.data let statusCode = moyaResponse.statusCode let mappedJSON = try? JSONSerialization.jsonObject(with: data) let responseConfig = parseResponseConfig(response) if let dict = mappedJSON as? [String: Any] { parseLinked(request: request, dict: dict, responseConfig: responseConfig) } else if isEmptySuccess(data, statusCode: statusCode) { request.resolve(("", responseConfig)) } else { ElloProvider.failedToMapObjects(request.reject) } } private func parseLinked( request: RequestFuture, dict: [String: Any], responseConfig: ResponseConfig ) { let completion: Block = { let elloAPI = request.target let node = dict[elloAPI.mappingType.rawValue] var newResponseConfig: ResponseConfig? if let pagingPath = elloAPI.pagingPath, let links = (node as? [String: Any])?["links"] as? [String: Any], let pagingPathNode = links[pagingPath] as? [String: Any], let pagination = pagingPathNode["pagination"] as? [String: String] { newResponseConfig = self.parsePagination(pagination) } guard elloAPI.mappingType != .noContentType else { request.resolve((Void(), newResponseConfig ?? responseConfig)) return } let mappedObjects: Any? if let node = node as? [[String: Any]] { mappedObjects = Mapper.mapToObjectArray(node, type: elloAPI.mappingType) } else if let node = node as? [String: Any] { mappedObjects = Mapper.mapToObject(node, type: elloAPI.mappingType) } else { mappedObjects = nil } if let mappedObjects = mappedObjects { request.resolve((mappedObjects, newResponseConfig ?? responseConfig)) } else { ElloProvider.failedToMapObjects(request.reject) } } if let linked = dict["linked"] as? [String: [[String: Any]]] { ElloLinkedStore.shared.parseLinked(linked, completion: completion) } else { completion() } } private func parsePagination(_ node: [String: String]) -> ResponseConfig { let config = ResponseConfig() config.totalPages = node["total_pages"] config.totalCount = node["total_count"] config.totalPagesRemaining = node["total_pages_remaining"] if let next = node["next"] { if let components = URLComponents(string: next) { config.nextQuery = components } } return config } private func parseResponseConfig(_ response: HTTPURLResponse?) -> ResponseConfig { let config = ResponseConfig() if let response = response { config.statusCode = response.statusCode config.lastModified = response.allHeaderFields["Last-Modified"] as? String config.totalPages = response.allHeaderFields["X-Total-Pages"] as? String config.totalCount = response.allHeaderFields["X-Total-Count"] as? String config.totalPagesRemaining = response.allHeaderFields["X-Total-Pages-Remaining"] as? String config.nextQuery = response.findLink(relation: "next").flatMap { URLComponents(string: $0.uri) } } return config } private func isEmptySuccess(_ data: Data, statusCode: Int?) -> Bool { guard let statusCode = statusCode else { return false } // accepted || no content if statusCode == 202 || statusCode == 204 { return true } // no content return String(data: data, encoding: .utf8) == "" && statusCode >= 200 && statusCode < 400 } private func handleServerError(request: RequestFuture, response moyaResponse: Moya.Response) { let data = moyaResponse.data let statusCode = moyaResponse.statusCode let elloError = ElloProvider.generateElloError(data, statusCode: statusCode) Tracker.shared.encounteredNetworkError( request.target.path, error: elloError, statusCode: statusCode ) request.reject(elloError) } private func handleNetworkFailure(request: RequestFuture) { delay(1) { self.sendRequest(request) } } private func postOldAPINotification() { postNotification(AuthenticationNotifications.outOfDateAPI, value: ()) } }
mit
a30de0eb23345b275128c0e3cafdec2f
33.194215
99
0.587311
5.197864
false
true
false
false
klone1127/yuan
yuan/YHomeViewController.swift
1
1602
// // YHomeViewController.swift // yuan // // Created by jgrm on 2017/5/16. // Copyright © 2017年 klone. All rights reserved. // import UIKit class YHomeViewController: YBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. // let net = YAuthorizationManager() // net.authorize() self.addLoginbutton() } func addLoginbutton() { let loginBtn = UIButton(type: .system) let H: CGFloat = 50.0 let W: CGFloat = 60.0 loginBtn.frame = CGRect(x: UIScreen.main.bounds.size.width / 2.0 - W / 2.0, y: UIScreen.main.bounds.size.height / 2.0 - H / 2.0, width: W, height: H) self.view.addSubview(loginBtn) loginBtn.setTitle("登录", for: .normal) loginBtn.addTarget(self, action: #selector(loginHandle), for: .touchUpInside) } func loginHandle() { let loginVC = YLoginViewController() self.navigationController?.pushViewController(loginVC, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
023968ca33c171a1b10efb64f27a81e2
30.27451
157
0.641379
4.322493
false
false
false
false
Shimmen/CoreDataTests
CoreDataTest-1/CoreDataTest-1/AppDelegate.swift
1
5347
// // AppDelegate.swift // CoreDataTest-1 // // Created by Simon Moos on 06/11/14. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var mainViewController: ViewController { return (self.window!.rootViewController as UINavigationController).viewControllers.first! as ViewController } // MARK: - ApplicationDelegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Fetch all local Persons into the view controller fetchLocal() return true } func applicationWillTerminate(application: UIApplication) { // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func fetchLocal() { // Request Persons let request = NSFetchRequest(entityName: "Person") // Request ALL Persons request.predicate = nil // Perform fetch var error: NSError? = NSError() let fetchResults = managedObjectContext!.executeFetchRequest(request, error: &error) if fetchResults == nil { println("Fetch error \(error)") } // Assign the fetch results to the view controllers array mainViewController.people = fetchResults as [Person] } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "io.github.shimmen.CoreDataTest_1" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("CoreDataTest_1", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("CoreDataTest_1.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
56f0b5650cef7ba421db45b07197c21f
43.190083
290
0.680943
5.768069
false
false
false
false
Fiskie/jsrl
jsrl/Media.swift
1
1186
// // Media.swift // jsrl // import Foundation class Media : Resource { /** Get the absolute URL for some media with percent encoding. - parameters: - name: The track name. - returns: An URL object representing the resource location. */ func resolveUrl(_ name: String) -> URL { let encName = name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)! return URL(string: "\(context.root)/audioplayer/audio/\(encName).mp3")! } /** Get a track and return a callback. - parameters: - name: The track name. - callback: Callback with err and data. */ func getData(_ name: String, _ callback: @escaping (Error?, Data?)->()) { var request = URLRequest(url: resolveUrl(name)) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in if (error != nil) { callback(error, nil) } if let data = data { callback(nil, data) } } task.resume() } }
gpl-3.0
2bbe243746cb047eab13a16f5b522d27
25.355556
103
0.542159
4.544061
false
false
false
false
brave/browser-ios
Client/Frontend/Home/TopSitesPanel.swift
1
21806
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared import XCGLogger import Storage import WebImage import Deferred private let log = Logger.browserLogger struct TopSitesPanelUX { static let statsHeight: CGFloat = 110.0 static let statsBottomMargin: CGFloat = 5 } class TopSitesPanel: UIViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? // MARK: - Favorites collection view properties fileprivate lazy var collection: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 6 let view = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) view.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.BackgroundColorForTopSitesPrivate : BraveUX.BackgroundColorForBookmarksHistoryAndTopSites view.delegate = self let thumbnailIdentifier = "Thumbnail" view.register(ThumbnailCell.self, forCellWithReuseIdentifier: thumbnailIdentifier) view.keyboardDismissMode = .onDrag view.alwaysBounceVertical = true view.accessibilityIdentifier = "Top Sites View" // Entire site panel, including the stats view insets view.contentInset = UIEdgeInsetsMake(TopSitesPanelUX.statsHeight, 0, 0, 0) return view }() fileprivate lazy var dataSource: FavoritesDataSource = { return FavoritesDataSource() }() // MARK: - Lazy views fileprivate lazy var privateTabMessageContainer: UIView = { let view = UIView() view.isUserInteractionEnabled = true view.isHidden = !PrivateBrowsing.singleton.isOn return view }() fileprivate lazy var privateTabGraphic: UIImageView = { return UIImageView(image: UIImage(named: "private_glasses")) }() fileprivate lazy var privateTabTitleLabel: UILabel = { let view = UILabel() view.lineBreakMode = .byWordWrapping view.textAlignment = .center view.numberOfLines = 0 view.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold) view.textColor = UIColor(white: 1, alpha: 0.6) view.text = Strings.Private_Tab_Title return view }() fileprivate lazy var privateTabInfoLabel: UILabel = { let view = UILabel() view.lineBreakMode = .byWordWrapping view.textAlignment = .center view.numberOfLines = 0 view.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium) view.textColor = UIColor(white: 1, alpha: 1.0) view.text = Strings.Private_Tab_Body return view }() fileprivate lazy var privateTabLinkButton: UIButton = { let view = UIButton() let linkButtonTitle = NSAttributedString(string: Strings.Private_Tab_Link, attributes: [NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue]) view.setAttributedTitle(linkButtonTitle, for: .normal) view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium) view.titleLabel?.textColor = UIColor(white: 1, alpha: 0.25) view.titleLabel?.textAlignment = .center view.titleLabel?.lineBreakMode = .byWordWrapping view.addTarget(self, action: #selector(showPrivateTabInfo), for: .touchUpInside) return view }() fileprivate var ddgLogo = UIImageView(image: UIImage(named: "duckduckgo")) fileprivate lazy var ddgLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.textColor = BraveUX.GreyD label.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular) label.text = Strings.DDG_promotion return label }() fileprivate lazy var ddgButton: UIControl = { let control = UIControl() control.addTarget(self, action: #selector(showDDGCallout), for: .touchUpInside) return control }() fileprivate lazy var braveShieldStatsView: BraveShieldStatsView = { let view = BraveShieldStatsView(frame: CGRect.zero) view.autoresizingMask = [.flexibleWidth] return view }() /// Called after user taps on ddg popup to set it as a default search enginge in private browsing mode. var ddgPrivateSearchCompletionBlock: (() -> ())? // MARK: - Init/lifecycle init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(existingUserTopSitesConversion), name: NotificationTopSitesConversion, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(TopSitesPanel.privateBrowsingModeChanged), name: NotificationPrivacyModeChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(TopSitesPanel.updateIphoneConstraints), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } @objc func existingUserTopSitesConversion() { dataSource.refetch() collection.reloadData() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self, name: NotificationTopSitesConversion, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationPrivacyModeChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = PrivateBrowsing.singleton.isOn ? BraveUX.BackgroundColorForTopSitesPrivate : BraveUX.BackgroundColorForBookmarksHistoryAndTopSites let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture(gesture:))) collection.addGestureRecognizer(longPressGesture) view.addSubview(collection) collection.dataSource = PrivateBrowsing.singleton.isOn ? nil : dataSource self.dataSource.collectionView = self.collection // Could setup as section header but would need to use flow layout, // Auto-layout subview within collection doesn't work properly, // Quick-and-dirty layout here. var statsViewFrame: CGRect = braveShieldStatsView.frame statsViewFrame.origin.x = 20 // Offset the stats view from the inset set above statsViewFrame.origin.y = -(TopSitesPanelUX.statsHeight + TopSitesPanelUX.statsBottomMargin) statsViewFrame.size.width = collection.frame.width - statsViewFrame.minX * 2 statsViewFrame.size.height = TopSitesPanelUX.statsHeight braveShieldStatsView.frame = statsViewFrame collection.addSubview(braveShieldStatsView) ddgButton.addSubview(ddgLogo) ddgButton.addSubview(ddgLabel) privateTabMessageContainer.addSubview(privateTabGraphic) privateTabMessageContainer.addSubview(privateTabTitleLabel) privateTabMessageContainer.addSubview(privateTabInfoLabel) privateTabMessageContainer.addSubview(privateTabLinkButton) privateTabMessageContainer.addSubview(ddgButton) collection.addSubview(privateTabMessageContainer) makeConstraints() if !getApp().browserViewController.shouldShowDDGPromo { hideDDG() } if let profile = getApp().profile, profile.searchEngines.defaultEngine(forType: .privateMode).shortName == OpenSearchEngine.EngineNames.duckDuckGo { hideDDG() } ddgPrivateSearchCompletionBlock = { [weak self] in self?.hideDDG() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // This makes collection view layout to recalculate its cell size. collection.collectionViewLayout.invalidateLayout() } func hideDDG() { ddgButton.isHidden = true } /// Handles long press gesture for UICollectionView cells reorder. @objc func handleLongGesture(gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: guard let selectedIndexPath = collection.indexPathForItem(at: gesture.location(in: collection)) else { break } dataSource.isEditing = true collection.beginInteractiveMovementForItem(at: selectedIndexPath) case .changed: collection.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!)) case .ended: // Allows user to tap anywhere to dimiss 'edit thumbnail' button. (view.window as! BraveMainWindow).addTouchFilter(self) collection.endInteractiveMovement() default: collection.cancelInteractiveMovement() } } // MARK: - Constraints setup fileprivate func makeConstraints() { collection.snp.makeConstraints { make -> Void in if #available(iOS 11.0, *) { make.edges.equalTo(self.view.safeAreaLayoutGuide.snp.edges) } else { make.edges.equalTo(self.view) } } privateTabMessageContainer.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(collection) if UIDevice.current.userInterfaceIdiom == .pad { make.centerY.equalTo(self.view) make.width.equalTo(400) } else { make.top.equalTo(self.braveShieldStatsView.snp.bottom).offset(25) make.leftMargin.equalTo(collection).offset(8) make.rightMargin.equalTo(collection).offset(-8) } make.bottom.equalTo(collection) } privateTabGraphic.snp.makeConstraints { make in make.top.equalTo(0) make.centerX.equalTo(self.privateTabMessageContainer) } if UIDevice.current.userInterfaceIdiom == .pad { privateTabTitleLabel.snp.makeConstraints { make in make.top.equalTo(self.privateTabGraphic.snp.bottom).offset(15) make.centerX.equalTo(self.privateTabMessageContainer) make.left.right.equalTo(0) } privateTabInfoLabel.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.privateTabTitleLabel.snp.bottom).offset(10) if UIDevice.current.userInterfaceIdiom == .pad { make.centerX.equalTo(collection) } make.left.equalTo(16) make.right.equalTo(-16) } privateTabLinkButton.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.privateTabInfoLabel.snp.bottom).offset(10) make.left.equalTo(0) make.right.equalTo(0) } ddgLogo.snp.makeConstraints { make in make.top.left.bottom.equalTo(0) make.size.equalTo(38) } ddgLabel.snp.makeConstraints { make in make.top.right.bottom.equalTo(0) make.left.equalTo(self.ddgLogo.snp.right).offset(5) make.width.equalTo(180) make.centerY.equalTo(self.ddgLogo) } ddgButton.snp.makeConstraints { make in make.top.equalTo(self.privateTabLinkButton.snp.bottom).offset(30) make.centerX.equalTo(self.collection) make.bottom.equalTo(-8) } } else { updateIphoneConstraints() } } override func viewSafeAreaInsetsDidChange() { // Not sure why but when a side panel is opened and you transition from portait to landscape // top site cells are misaligned, this is a workaroud for this edge case. Happens only on iPhoneX*. if #available(iOS 11.0, *) { collection.snp.remakeConstraints { make -> Void in make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top) make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom) make.leading.equalTo(self.view.safeAreaLayoutGuide.snp.leading) make.trailing.equalTo(self.view.safeAreaLayoutGuide.snp.trailing).offset(self.view.safeAreaInsets.right) } } } @objc func updateIphoneConstraints() { if UIDevice.current.userInterfaceIdiom == .pad { return } let isLandscape = UIApplication.shared.statusBarOrientation.isLandscape UIView.animate(withDuration: 0.2, animations: { self.privateTabGraphic.alpha = isLandscape ? 0 : 1 }) let offset = isLandscape ? 10 : 15 privateTabTitleLabel.snp.remakeConstraints { make in if isLandscape { make.top.equalTo(0) } else { make.top.equalTo(self.privateTabGraphic.snp.bottom).offset(offset) } make.centerX.equalTo(self.privateTabMessageContainer) make.left.right.equalTo(0) } privateTabInfoLabel.snp.remakeConstraints { make in make.top.equalTo(self.privateTabTitleLabel.snp.bottom).offset(offset) make.left.equalTo(32) make.right.equalTo(-32) } privateTabLinkButton.snp.remakeConstraints { make in make.top.equalTo(self.privateTabInfoLabel.snp.bottom).offset(offset) make.left.equalTo(32) make.right.equalTo(-32) } ddgLogo.snp.remakeConstraints { make in make.top.left.bottom.equalTo(0) make.size.equalTo(38) } ddgLabel.snp.remakeConstraints { make in make.top.right.bottom.equalTo(0) make.left.equalTo(self.ddgLogo.snp.right).offset(5) make.width.equalTo(180) make.centerY.equalTo(self.ddgLogo) } ddgButton.snp.remakeConstraints { make in make.top.equalTo(self.privateTabLinkButton.snp.bottom).offset(30) make.centerX.equalTo(self.collection) make.bottom.equalTo(-8) } self.view.setNeedsUpdateConstraints() } @objc func showDDGCallout() { getApp().browserViewController.presentDDGCallout(force: true) } func endEditing() { guard let window = view.window as? BraveMainWindow else { return } window.removeTouchFilter(self) dataSource.isEditing = false } // MARK: - Private browsing modde @objc func privateBrowsingModeChanged() { let isPrivateBrowsing = PrivateBrowsing.singleton.isOn if isPrivateBrowsing { let profile = getApp().profile let isDDGSet = profile?.searchEngines.defaultEngine(forType: .privateMode).shortName == OpenSearchEngine.EngineNames.duckDuckGo let shouldShowDDGPromo = getApp().browserViewController.shouldShowDDGPromo ddgButton.isHidden = isDDGSet || !shouldShowDDGPromo } // TODO: This entire blockshould be abstracted // to make code in this class DRY (duplicates from elsewhere) collection.backgroundColor = isPrivateBrowsing ? BraveUX.BackgroundColorForTopSitesPrivate : BraveUX.BackgroundColorForBookmarksHistoryAndTopSites privateTabMessageContainer.isHidden = !isPrivateBrowsing braveShieldStatsView.timeStatView.color = isPrivateBrowsing ? BraveUX.GreyA : BraveUX.GreyJ // Handling edge case when app starts in private only browsing mode and is switched back to normal mode. if collection.dataSource == nil && !isPrivateBrowsing { collection.dataSource = dataSource } else if isPrivateBrowsing { collection.dataSource = nil } collection.reloadData() } @objc func showPrivateTabInfo() { let url = URL(string: "https://github.com/brave/browser-laptop/wiki/What-a-Private-Tab-actually-does")! postAsyncToMain { let t = getApp().tabManager _ = t?.addTabAndSelect(URLRequest(url: url)) } } } // MARK: - Delegates extension TopSitesPanel: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let fav = dataSource.favoriteBookmark(at: indexPath) guard let urlString = fav?.url, let url = URL(string: urlString) else { return } homePanelDelegate?.homePanel(self, didSelectURL: url) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collection.frame.width let padding: CGFloat = traitCollection.horizontalSizeClass == .compact ? 6 : 20 let cellWidth = floor(width - padding) / CGFloat(columnsPerRow) // The tile's height is determined the aspect ratio of the thumbnails width. We also take into account // some padding between the title and the image. let cellHeight = floor(cellWidth / (CGFloat(ThumbnailCellUX.ImageAspectRatio) - 0.1)) return CGSize(width: cellWidth, height: cellHeight) } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let thumbnailCell = cell as? ThumbnailCell else { return } thumbnailCell.delegate = self } fileprivate var columnsPerRow: Int { let size = collection.bounds.size let traitCollection = collection.traitCollection var cols = 0 if traitCollection.horizontalSizeClass == .compact { // Landscape iPhone if traitCollection.verticalSizeClass == .compact { cols = 5 } // Split screen iPad width else if size.widthLargerOrEqualThanHalfIPad() { cols = 4 } // iPhone portrait else { cols = 3 } } else { // Portrait iPad if size.height > size.width { cols = 4; } // Landscape iPad else { cols = 5; } } return cols + 1 } } extension TopSitesPanel : WindowTouchFilter { func filterTouch(_ touch: UITouch) -> Bool { // Allows user to tap anywhere to dimiss 'edit thumbnail' button. if (touch.view as? UIButton) == nil && touch.phase == .began { self.endEditing() } return false } } extension TopSitesPanel: ThumbnailCellDelegate { func editThumbnail(_ thumbnailCell: ThumbnailCell) { guard let indexPath = collection.indexPath(for: thumbnailCell), let fav = dataSource.frc?.fetchedObjects?[indexPath.item] as? Bookmark else { return } let actionSheet = UIAlertController(title: fav.displayTitle, message: nil, preferredStyle: .actionSheet) let deleteAction = UIAlertAction(title: Strings.Remove_Favorite, style: .destructive) { _ in fav.remove(save: true) // Remove cached icon. if let urlString = fav.url, let url = URL(string: urlString) { ImageCache.shared.remove(url, type: .square) } self.dataSource.isEditing = false } let editAction = UIAlertAction(title: Strings.Edit_Favorite, style: .default) { _ in guard let title = fav.displayTitle, let urlString = fav.url else { return } let editPopup = UIAlertController.userTextInputAlert(title: Strings.Edit_Bookmark, message: urlString, startingText: title, startingText2: fav.url, placeholder2: urlString, keyboardType2: .URL) { callbackTitle, callbackUrl in if let cTitle = callbackTitle, !cTitle.isEmpty, let cUrl = callbackUrl, !cUrl.isEmpty { if URL(string: cUrl) != nil { fav.update(customTitle: cTitle, url: cUrl, save: true) } } self.dataSource.isEditing = false } self.present(editPopup, animated: true, completion: nil) } let cancelAction = UIAlertAction(title: Strings.Cancel, style: .cancel, handler: nil) actionSheet.addAction(editAction) actionSheet.addAction(deleteAction) actionSheet.addAction(cancelAction) if DeviceDetector.isIpad { actionSheet.popoverPresentationController?.permittedArrowDirections = .any actionSheet.popoverPresentationController?.sourceView = thumbnailCell actionSheet.popoverPresentationController?.sourceRect = thumbnailCell.bounds present(actionSheet, animated: true, completion: nil) } else { present(actionSheet, animated: true) { self.dataSource.isEditing = false } } } } extension CGSize { public func widthLargerOrEqualThanHalfIPad() -> Bool { let halfIPadSize: CGFloat = 507 return width >= halfIPadSize } }
mpl-2.0
bf1e3cfd000e6edfcfa7be4b484222fe
39.456401
181
0.639136
5.050023
false
false
false
false
heylau/HLPageView
HLPageView/ViewController.swift
1
2953
// // ViewController.swift // HLPageView // // Created by heylau on 2017/3/16. // Copyright © 2017年 hey lau. All rights reserved. // import UIKit private let cellID = "pageCell" class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() HLPageCollectionViewDemo() // HLPageViewDemo() } } extension ViewController :HLPageCollecitonViewDataSource{ //MARK:- 自定义表情框Demo func HLPageCollectionViewDemo() { automaticallyAdjustsScrollViewInsets = false let pageFrame = CGRect(x: 0, y: 100, width:view.bounds.width, height: 300) let titles = ["one","two","three","four"] var style = HLPageStyle() style.isShowBottomLine = true let layout = HLPageCollecitonLayout() layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10) layout.itemMargin = 10 layout.lineMargin = 30 layout.cols = 6 layout.rows = 3 let pageCollectionView = HLPageCollectionView(frame: pageFrame, titles: titles, style: style, layout: layout) pageCollectionView.dataSource = self pageCollectionView.registerCell(UICollectionViewCell.self, reusableIdentifier: cellID) view.addSubview(pageCollectionView) } func numberOfSectionInPageCollectionView(_ pageCollectionView: HLPageCollectionView) -> Int { return 4 } func pageCollectionView(_ pageCollectionView: HLPageCollectionView, numberOfSection section: Int) -> Int { return 30 } func pageCollectionView(_ pageCollectionView: HLPageCollectionView, _ collectionView: UICollectionView, cellAtIndexPath indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) cell.backgroundColor = UIColor.randomColor() return cell } } //MARK:- PageViewDemo extension ViewController { func HLPageViewDemo() { let pageviewF = CGRect(x: 0, y: 64, width: view.bounds.width, height: view.bounds.height - 64) let titles = ["首页","库存","销售","基础","首页库存","库存库存","销售库存","基础库存"] var childVcs = [UIViewController]() for _ in 0..<titles.count { let vc = UIViewController() vc.view.backgroundColor = UIColor.randomColor() childVcs.append(vc) } var style = HLPageStyle() style.isSrollEnable = true // style.titleHeight = 44 // style.isScale = fal let pageView = HLPageView(frame: pageviewF, titles: titles, style: style, childVcs: childVcs, parentVc: self) view.addSubview(pageView) } }
apache-2.0
ef8e07339a2c9b6c4b9dd302351692bd
26.52381
171
0.610381
4.991364
false
false
false
false
OliverCulleyDeLange/WeClimbRocks-IOS
wcr/TableViewController.swift
1
4224
// // TableViewController.swift // wcr // // Created by Oliver Culley De Lange on 08/09/2015. // Copyright (c) 2015 Oliver Culley De Lange. All rights reserved. // import UIKit import Alamofire import AlamofireJsonToObjects import EVReflection class People : EVObject { var entries: [Person] = [Person]() } class Person : EVObject { var name: String = "default" var address: String = "default" } class TableViewController: UITableViewController { var people: [Person] = [Person]() override func viewDidLoad() { super.viewDidLoad() getData() // 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() } @IBOutlet weak var txt: UITextView! func getData() { let url = "https://sheltered-fjord-9141.herokuapp.com/testService" Alamofire.request(.GET, url).responseObject { (response: People?, error: NSError?) in if let model:People = response { self.people = model.entries self.tableView.reloadData() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.people.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> TableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("pic") as! TableViewCell // cell.caption?.text = people[indexPath.row].name var imageName = UIImage(named: people[indexPath.row].name) if let img: UIImage = imageName { cell.img?.image = imageName } return cell } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... 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 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. } */ }
mit
f7e5216f42402b15049b98d4a71598a3
32
157
0.662879
5.234201
false
false
false
false
YauheniYarotski/APOD
APOD/String+Utils.swift
1
1288
// // String+Utils.swift // APOD // // Created by Yauheni Yarotski on 10/23/16. // Copyright © 2016 Yauheni_Yarotski. All rights reserved. // import UIKit extension String { func videoIdentifier() -> String? { let pattern = "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)" guard let regExp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive) else { return nil } let nsLink = self as NSString let options = NSRegularExpression.MatchingOptions(rawValue: 0) let range = NSRange(location: 0,length: nsLink.length) let matches = regExp.matches(in: self as String, options:options, range:range) if let firstMatch = matches.first { return nsLink.substring(with: firstMatch.range) } return nil } // func fileName() -> String { // // if let fileNameWithoutExtension = NSURL(fileURLWithPath: self).deletingPathExtension?.lastPathComponent { // return fileNameWithoutExtension // } else { // return "" // } // } func fileExtension() -> String { let fileExtension = URL(fileURLWithPath: self).pathExtension return fileExtension } }
mit
f597d500d60918a55bea994985343af0
28.930233
115
0.583528
4.165049
false
false
false
false
ContinuousLearning/PokemonKit
Carthage/Checkouts/PromiseKit/Categories/AssetsLibrary/ALAssetsLibrary+Promise.swift
1
1659
import AssetsLibrary import Foundation.NSData #if !COCOAPODS import PromiseKit #endif import UIKit.UIViewController /** To import this `UIViewController` extension: use_frameworks! pod "PromiseKit/AssetsLibrary" And then in your sources: #if !COCOAPODS import PromiseKit #endif */ extension UIViewController { /** @return A promise that presents the provided UIImagePickerController and fulfills with the user selected media’s `NSData`. */ public func promiseViewController(vc: UIImagePickerController, animated: Bool = false, completion: (() -> Void)? = nil) -> Promise<NSData> { let proxy = UIImagePickerControllerProxy() vc.delegate = proxy presentViewController(vc, animated: animated, completion: completion) return proxy.promise.then(on: zalgo) { info -> Promise<NSData> in let url = info[UIImagePickerControllerReferenceURL] as! NSURL return Promise { sealant in ALAssetsLibrary().assetForURL(url, resultBlock: { asset in let N = Int(asset.defaultRepresentation().size()) let bytes = UnsafeMutablePointer<UInt8>.alloc(N) var error: NSError? asset.defaultRepresentation().getBytes(bytes, fromOffset: 0, length: N, error: &error) sealant.resolve(NSData(bytesNoCopy: bytes, length: N), error as NSError!) }, failureBlock: sealant.resolve) } }.finally { self.dismissViewControllerAnimated(animated, completion: nil) } } }
mit
b083f294f2ceb847b15e0197ada4309d
32.816327
144
0.627037
5.29393
false
false
false
false
tardieu/swift
test/Misc/expression_too_complex.swift
5
420
// RUN: %target-typecheck-verify-swift -solver-memory-threshold 8000 var x = [1, 2, 3, 4.5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ,19] // expected-error{{expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions}} // No errors should appear below as a result of the error above. var y = 10 var z = 10 + 10 class C {} var c = C() var d = c
apache-2.0
a805051f39873ba6742e3480de5d382c
34
221
0.678571
3.111111
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Whistle/Base/MOptionWhistlesVsZombiesWhistleBaseStrategyExploded.swift
1
1062
import SpriteKit class MOptionWhistlesVsZombiesWhistleBaseStrategyExploded:MGameStrategy< MOptionWhistlesVsZombiesWhistleBase, MOptionWhistlesVsZombies> { private var startingTime:TimeInterval? private let kWait:TimeInterval = 1 override func update( elapsedTime:TimeInterval, scene:ViewGameScene<MOptionWhistlesVsZombies>) { if let startingTime:TimeInterval = self.startingTime { let deltaTime:TimeInterval = elapsedTime - startingTime if deltaTime > kWait { model.explodeFinish() } } else { startingTime = elapsedTime showExploded(scene:scene) } } //MARK: private private func showExploded(scene:ViewGameScene<MOptionWhistlesVsZombies>) { let soundExplosion:SKAction = scene.controller.model.sounds.soundExplosion scene.controller.playSound(actionSound:soundExplosion) model.viewWhistle?.explode() } }
mit
10dbef57f7a7f5ceaea6d7463c5fa22d
26.230769
82
0.636535
5.418367
false
false
false
false
jjochen/JJFloatingActionButton
Sources/UIView+JJFloatingActionButton.swift
1
3551
// // UIView+JJFloatingActionButton.swift // // Copyright (c) 2017-Present Jochen Pfeiffer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit internal extension UIView { class func animate(duration: TimeInterval, delay: TimeInterval = 0, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions = [.beginFromCurrentState], animations: @escaping () -> Void, completion: ((Bool) -> Void)? = nil, group: DispatchGroup? = nil, animated: Bool = true) { let groupedAnimations: () -> Void = { group?.enter() animations() } let groupedCompletion: (Bool) -> Void = { finished in completion?(finished) group?.leave() } if animated { UIView.animate(withDuration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: groupedAnimations, completion: groupedCompletion) } else { groupedAnimations() groupedCompletion(true) } } class func transition(with view: UIView, duration: TimeInterval, options: UIView.AnimationOptions = [.transitionCrossDissolve], animations: (() -> Swift.Void)?, completion: ((Bool) -> Swift.Void)? = nil, group: DispatchGroup? = nil, animated: Bool = true) { let groupedAnimations: () -> Void = { group?.enter() animations?() } let groupedCompletion: (Bool) -> Void = { finished in completion?(finished) group?.leave() } if animated { UIView.transition(with: view, duration: duration, options: options, animations: groupedAnimations, completion: groupedCompletion) } else { groupedAnimations() groupedCompletion(true) } } }
mit
9ed7e0cf6b1466bf1448e8477d87f872
39.352273
88
0.558153
5.636508
false
false
false
false
hooman/swift
test/AutoDiff/SILOptimizer/semantic_member_accessors_sil.swift
1
5790
// RUN: %target-swift-frontend -emit-sil -Xllvm -sil-print-after=differentiation %s -module-name null -o /dev/null -requirement-machine=off 2>&1 | %FileCheck %s // Test differentiation of semantic member accessors: // - Stored property accessors. // - Property wrapper wrapped value accessors. // TODO(TF-1254): Support forward-mode differentiation and test generated differentials. import _Differentiation @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value } struct Struct: Differentiable { @Wrapper @Wrapper var x: Float = 10 var y: Float = 10 } struct Generic<T> { @Wrapper @Wrapper var x: T var y: T } extension Generic: Differentiable where T: Differentiable {} func trigger<T: Differentiable>(_ x: T.Type) { let _: @differentiable(reverse) (Struct) -> Float = { $0.x } let _: @differentiable(reverse) (inout Struct, Float) -> Void = { $0.x = $1 } let _: @differentiable(reverse) (Generic<T>) -> T = { $0.x } let _: @differentiable(reverse) (inout Generic<T>, T) -> Void = { $0.x = $1 } } // CHECK-LABEL: // differentiability witness for Generic.x.setter // CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0 1] [results 0] <τ_0_0 where τ_0_0 : Differentiable> @$s4null7GenericV1xxvs : $@convention(method) <T> (@in T, @inout Generic<T>) -> () { // CHECK-LABEL: // differentiability witness for Generic.x.getter // CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0] [results 0] <τ_0_0 where τ_0_0 : Differentiable> @$s4null7GenericV1xxvg : $@convention(method) <T> (@in_guaranteed Generic<T>) -> @out T { // CHECK-LABEL: // differentiability witness for Struct.x.setter // CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0 1] [results 0] @$s4null6StructV1xSfvs : $@convention(method) (Float, @inout Struct) -> () { // CHECK-LABEL: // differentiability witness for Struct.x.getter // CHECK-NEXT: sil_differentiability_witness private [reverse] [parameters 0] [results 0] @$s4null6StructV1xSfvg : $@convention(method) (Struct) -> Float { // CHECK-LABEL: sil private [ossa] @$s4null7GenericV1xxvs16_Differentiation14DifferentiableRzlTJpSSpSr // CHECK: bb0([[ADJ_X_RESULT:%.*]] : $*τ_0_0.TangentVector, [[ADJ_SELF:%.*]] : $*Generic<τ_0_0>.TangentVector, {{.*}} : {{.*}}): // CHECK: [[ADJ_X_TMP:%.*]] = alloc_stack $τ_0_0.TangentVector // CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter // CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X_TMP]], {{.*}}) // CHECK: [[ADJ_X:%.*]] = struct_element_addr [[ADJ_SELF]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.x // CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic."+=" // CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X_TMP]], [[ADJ_X]], {{.*}}) // CHECK: destroy_addr [[ADJ_X]] : $*τ_0_0.TangentVector // CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter // CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_X]], {{.*}}) // CHECK: copy_addr [take] [[ADJ_X_TMP]] to [initialization] [[ADJ_X_RESULT]] : $*τ_0_0.TangentVector // CHECK: dealloc_stack [[ADJ_X_TMP]] : $*τ_0_0.TangentVector // CHECK: return {{.*}} : $() // CHECK: } // CHECK-LABEL: sil private [ossa] @$s4null7GenericV1xxvg16_Differentiation14DifferentiableRzlTJpSpSr // CHECK: bb0([[ADJ_SELF_RESULT:%.*]] : $*Generic<τ_0_0>.TangentVector, [[SEED:%.*]] : $*τ_0_0.TangentVector, {{.*}} : ${{.*}}): // CHECK: [[ADJ_SELF_TMP:%.*]] = alloc_stack $Generic<τ_0_0>.TangentVector // CHECK: [[SEED_COPY:%.*]] = alloc_stack $τ_0_0.TangentVector // CHECK: copy_addr [[SEED]] to [initialization] [[SEED_COPY]] : $*τ_0_0.TangentVector // CHECK: [[ADJ_X:%.*]] = struct_element_addr [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.x // CHECK: copy_addr [take] [[SEED_COPY]] to [initialization] [[ADJ_X]] : $*τ_0_0.TangentVector // CHECK: [[ADJ_Y:%.*]] = struct_element_addr [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector, #Generic.TangentVector.y // CHECK: [[ZERO_FN:%.*]] = witness_method $τ_0_0.TangentVector, #AdditiveArithmetic.zero!getter // CHECK: apply [[ZERO_FN]]<τ_0_0.TangentVector>([[ADJ_Y]], {{.*}}) // CHECK: copy_addr [take] [[ADJ_SELF_TMP]] to [initialization] [[ADJ_SELF_RESULT]] : $*Generic<τ_0_0>.TangentVector // CHECK: dealloc_stack [[SEED_COPY]] : $*τ_0_0.TangentVector // CHECK: dealloc_stack [[ADJ_SELF_TMP]] : $*Generic<τ_0_0>.TangentVector // CHECK: return {{.*}} : $() // CHECK: } // CHECK-LABEL: sil private [ossa] @$s4null6StructV1xSfvsTJpSSpSr // CHECK: bb0([[ADJ_SELF:%.*]] : $*Struct.TangentVector, {{.*}} : $_AD__$s4null6StructV1xSfvs_bb0__PB__src_0_wrt_0_1): // CHECK: [[ADJ_X_ADDR:%.*]] = struct_element_addr [[ADJ_SELF]] : $*Struct.TangentVector, #Struct.TangentVector.x // CHECK: [[ADJ_X:%.*]] = load [trivial] [[ADJ_X_ADDR]] : $*Float // CHECK: [[ZERO_FN:%.*]] = witness_method $Float, #AdditiveArithmetic.zero!getter // CHECK: apply [[ZERO_FN]]<Float>([[ADJ_X_ADDR]], {{.*}}) // CHECK: return [[ADJ_X]] : $Float // CHECK: } // CHECK-LABEL: sil private [ossa] @$s4null6StructV1xSfvgTJpSpSr // CHECK: bb0([[ADJ_X:%.*]] : $Float, {{.*}} : $_AD__$s4null6StructV1xSfvg_bb0__PB__src_0_wrt_0): // CHECK: [[ADJ_Y_ADDR:%.*]] = alloc_stack $Float // CHECK: [[ZERO_FN:%.*]] = witness_method $Float, #AdditiveArithmetic.zero!getter // CHECK: apply [[ZERO_FN]]<Float>([[ADJ_Y_ADDR]], {{.*}}) // CHECK: [[ADJ_Y:%.*]] = load [trivial] [[ADJ_Y_ADDR]] : $*Float // CHECK: dealloc_stack [[ADJ_Y_ADDR]] : $*Float // CHECK: [[ADJ_SELF:%.*]] = struct $Struct.TangentVector ([[ADJ_X]] : $Float, [[ADJ_Y]] : $Float) // CHECK: return [[ADJ_SELF]] : $Struct.TangentVector // CHECK: }
apache-2.0
7683cbc69b238e212de1b27d3635af37
58.381443
216
0.645486
3.116883
false
false
false
false
rondinellimorais/RMExtensionKit
RMExtensionKit/Classes/UIColor.swift
1
2084
// // UIColor.swift // ConectaCenter // // Created by Rondinelli Morais on 10/03/16. // Copyright © 2016 Rondinelli Morais. All rights reserved. // import UIKit extension UIColor { public convenience init(r: Float, g: Float, b: Float, a:Float) { assert(r >= 0.0 && r <= 255.0, "Invalid red component") assert(g >= 0.0 && g <= 255.0, "Invalid green component") assert(b >= 0.0 && b <= 255.0, "Invalid blue component") assert(a >= 0.0 && a <= 1.0, "Invalid alpha component") self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(a)) } public convenience init(r: Float, g: Float, b: Float) { self.init(r:r, g:g, b:b, a: 1.0) } public class func random(alpha:CGFloat? = nil) -> UIColor { return UIColor(red: randomCGFloat(), green: randomCGFloat(), blue: randomCGFloat(), alpha: (alpha ?? randomCGFloat()) ) } /* create color base on hexdecimal string UIColor("#00ADEE") UIColor("#8BC53F") UIColor("#AB2784") UIColor("#6F3D23") */ public convenience init?(_ hex:String) { var hexValue: UInt32 = 0 // remove # let invertedSet = CharacterSet(charactersIn: "#") let cleanerHexString = hex.components(separatedBy: invertedSet).joined(separator: "") guard Scanner(string: cleanerHexString).scanHexInt32(&hexValue) else { assertionFailure("hex decimal color \(hex) is invalid!") return nil } self.init(hex: Int(hexValue)) } // MARK: Private methods private class func randomCGFloat() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) } private convenience init(hex:Int) { self.init( red: CGFloat((hex & 0xFF0000) >> 16) / 255.0, green: CGFloat((hex & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hex & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } }
mit
b86a56d15f3489a75b1bdaf762c434b5
30.560606
128
0.56073
3.699822
false
false
false
false
PokeMapCommunity/PokeMap-iOS
Pods/Permission/Source/PermissionAlert.swift
1
5306
// // PermissionAlert.swift // // Copyright (c) 2015-2016 Damien (http://delba.io) // // 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. // public class PermissionAlert { /// The permission. private let permission: Permission /// The status of the permission. private var status: PermissionStatus { return permission.status } /// The domain of the permission. private var type: PermissionType { return permission.type } private var callbacks: Permission.Callback { return permission.callbacks } /// The title of the alert. public var title: String? /// Descriptive text that provides more details about the reason for the alert. public var message: String? /// The title of the cancel action. public var cancel: String? { get { return cancelActionTitle } set { cancelActionTitle = newValue } } /// The title of the settings action. public var settings: String? { get { return defaultActionTitle } set { defaultActionTitle = newValue } } /// The title of the confirm action. public var confirm: String? { get { return defaultActionTitle } set { defaultActionTitle = newValue } } private var cancelActionTitle: String? private var defaultActionTitle: String? var controller: UIAlertController { let controller = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: cancelActionTitle, style: .Cancel, handler: cancelHandler) controller.addAction(action) return controller } internal init(permission: Permission) { self.permission = permission } internal func present() { Queue.main { Application.presentViewController(self.controller) } } private func cancelHandler(action: UIAlertAction) { callbacks(status) } } internal class DisabledAlert: PermissionAlert { override init(permission: Permission) { super.init(permission: permission) title = "\(permission.prettyDescription) is currently disabled" message = "Please enable access to \(permission.prettyDescription) in the Settings app." cancel = "OK" } } internal class DeniedAlert: PermissionAlert { override var controller: UIAlertController { let controller = super.controller let action = UIAlertAction(title: defaultActionTitle, style: .Default, handler: settingsHandler) controller.addAction(action) return controller } override init(permission: Permission) { super.init(permission: permission) title = "Permission for \(permission.prettyDescription) was denied" message = "Please enable access to \(permission.prettyDescription) in the Settings app." cancel = "Cancel" settings = "Settings" } @objc func settingsHandler() { NotificationCenter.removeObserver(self, name: UIApplicationDidBecomeActiveNotification) callbacks(status) } private func settingsHandler(action: UIAlertAction) { NotificationCenter.addObserver(self, selector: .settingsHandler, name: UIApplicationDidBecomeActiveNotification) if let URL = NSURL(string: UIApplicationOpenSettingsURLString) { Application.openURL(URL) } } } internal class PrePermissionAlert: PermissionAlert { override var controller: UIAlertController { let controller = super.controller let action = UIAlertAction(title: defaultActionTitle, style: .Default, handler: confirmHandler) controller.addAction(action) return controller } override init(permission: Permission) { super.init(permission: permission) title = "\(Bundle.name) would like to access your \(permission.prettyDescription)" message = "Please enable access to \(permission.prettyDescription)." cancel = "Cancel" confirm = "Confirm" } private func confirmHandler(action: UIAlertAction) { permission.requestAuthorization(callbacks) } }
mit
22b009f6e7a16e40faaf6c2fea270178
33.686275
120
0.677158
5.166504
false
false
false
false
flodolo/firefox-ios
Client/Frontend/Home/HomepageContextMenuProtocol.swift
1
4114
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import UIKit import Foundation import Storage protocol HomepageContextMenuProtocol { func getContextMenuActions(for site: Site, with sourceView: UIView?, sectionType: HomepageSectionType) -> [PhotonRowActions]? func presentContextMenu(for site: Site, with sourceView: UIView?, sectionType: HomepageSectionType) func presentContextMenu(for site: Site, with sourceView: UIView?, sectionType: HomepageSectionType, completionHandler: @escaping () -> PhotonActionSheet?) func getContextMenuActions(for highlightItem: HighlightItem, with sourceView: UIView?, sectionType: HomepageSectionType) -> [PhotonRowActions]? func presentContextMenu(for highlightItem: HighlightItem, with sourceView: UIView?, sectionType: HomepageSectionType) func presentContextMenu(for highlightItem: HighlightItem, with sourceView: UIView?, sectionType: HomepageSectionType, completionHandler: @escaping () -> PhotonActionSheet?) } extension HomepageContextMenuProtocol { // MARK: Site func presentContextMenu(for site: Site, with sourceView: UIView?, sectionType: HomepageSectionType) { presentContextMenu(for: site, with: sourceView, sectionType: sectionType, completionHandler: { return self.contextMenu(for: site, with: sourceView, sectionType: sectionType) }) } func contextMenu(for site: Site, with sourceView: UIView?, sectionType: HomepageSectionType) -> PhotonActionSheet? { guard let actions = getContextMenuActions(for: site, with: sourceView, sectionType: sectionType) else { return nil } let viewModel = PhotonActionSheetViewModel(actions: [actions], site: site, modalStyle: .overFullScreen) let contextMenu = PhotonActionSheet(viewModel: viewModel) contextMenu.modalTransitionStyle = .crossDissolve let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() return contextMenu } // MARK: - Highlight Item func presentContextMenu(for highlightItem: HighlightItem, with sourceView: UIView?, sectionType: HomepageSectionType) { presentContextMenu(for: highlightItem, with: sourceView, sectionType: sectionType, completionHandler: { return self.contextMenu(for: highlightItem, with: sourceView, sectionType: sectionType) }) } func contextMenu(for highlightItem: HighlightItem, with sourceView: UIView?, sectionType: HomepageSectionType) -> PhotonActionSheet? { guard let actions = getContextMenuActions(for: highlightItem, with: sourceView, sectionType: sectionType) else { return nil } var viewModel: PhotonActionSheetViewModel switch highlightItem.type { case .item: guard let url = highlightItem.siteUrl?.absoluteString else { return nil } let site = Site(url: url, title: highlightItem.displayTitle) viewModel = PhotonActionSheetViewModel(actions: [actions], site: site, modalStyle: .overFullScreen) case .group: viewModel = PhotonActionSheetViewModel(actions: [actions], title: highlightItem.displayTitle, modalStyle: .overFullScreen) } let contextMenu = PhotonActionSheet(viewModel: viewModel) contextMenu.modalTransitionStyle = .crossDissolve let generator = UIImpactFeedbackGenerator(style: .heavy) generator.impactOccurred() return contextMenu } }
mpl-2.0
7fea805ae57c238982728d43e739d44f
49.170732
176
0.643899
6.067847
false
false
false
false
phakphumi/Chula-Expo-iOS-Application
Chula Expo 2017/Chula Expo 2017/Modal_QR/QRViewController.swift
1
7040
// // QRViewController.swift // Chula Expo 2017 // // Created by Pakpoom on 1/11/2560 BE. // Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved. // import UIKit import CoreData import FBSDKLoginKit import Answers class QRViewController: UIViewController { @IBOutlet var profileImage: UIImageView! @IBOutlet var qrCodeImage: UIImageView! @IBOutlet var name: UILabel! @IBOutlet var school: UILabel! @IBOutlet weak var scanQR: UIButton! @IBAction func cancle(_ sender: UIButton) { self.dismiss(animated: true, completion: nil) } var baseQRViewCenter = CGPoint() var managedObjectContext: NSManagedObjectContext? = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext override func viewDidLoad() { super.viewDidLoad() Answers.logContentView(withName: "QR Code", contentType: nil, contentId: nil, customAttributes: nil) //load auto layout view.setNeedsLayout() view.layoutIfNeeded() fetchUserData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) UIApplication.shared.statusBarStyle = .lightContent } override func viewWillDisappear(_ animated: Bool) { UIApplication.shared.statusBarStyle = .default } override func viewDidLayoutSubviews() { self.profileImage.layer.cornerRadius = self.profileImage.bounds.height / 2 self.profileImage.layer.borderColor = UIColor.darkGray.cgColor self.profileImage.layer.borderWidth = 3 self.profileImage.layer.masksToBounds = true self.scanQR.layer.cornerRadius = self.scanQR.frame.height / 2 self.scanQR.layer.masksToBounds = true self.scanQR.titleLabel?.adjustsFontSizeToFitWidth = true } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ private func fetchUserData() { managedObjectContext?.performAndWait { print(1) let userData = UserData.fetchUser(inManageobjectcontext: self.managedObjectContext!)! print(userData.profile!) self.setImageProfile(pictureUrl: userData.profile!) print(userData.name!) self.name.text = userData.name if userData.school != "" { self.school.text = userData.school } else { self.school.text = "ไม่พบข้อมูลสถาบันการศึกษา" } let qrImage = self.generateQRCode(from: "\(userData.id!)") self.qrCodeImage.image = qrImage } } func generateQRCode(from string: String) -> UIImage? { let data = string.data(using: String.Encoding.ascii) if let filter = CIFilter(name: "CIQRCodeGenerator") { filter.setValue(data, forKey: "inputMessage") filter.setValue("H", forKey: "inputCorrectionLevel") let transform = CGAffineTransform(scaleX: 5, y: 5) if let qrCodeImage = filter.outputImage?.applying(transform) { return UIImage(ciImage: qrCodeImage) } } return nil } func setImageProfile(pictureUrl: String) { if let facebookProfileUrl = URL(string: pictureUrl) { if let data = NSData(contentsOf: facebookProfileUrl) { self.profileImage.image = UIImage(data: data as Data) } } } func drag(gestureRecognizer: UIPanGestureRecognizer) { let xDistanceToDismiss = self.view.bounds.width * 0.3 let yDistanceToDismiss = self.view.bounds.height * 0.3 let translation = gestureRecognizer.translation(in: view) let touchedMovingView = gestureRecognizer.view! // get moving object touchedMovingView.center = CGPoint(x: baseQRViewCenter.x + translation.x, y: baseQRViewCenter.y + translation.y) if gestureRecognizer.state == UIGestureRecognizerState.ended { let xFromCenter = abs(touchedMovingView.center.x - self.view.bounds.width / 2) // check how far from center let yFromCenter = abs(touchedMovingView.center.y - self.view.bounds.height / 2) if xFromCenter > xDistanceToDismiss || yFromCenter > yDistanceToDismiss { self.dismiss(animated: true, completion: nil) } else { UIView.animate(withDuration: 0.5, animations: { touchedMovingView.center = self.baseQRViewCenter }) } } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? ScanQRCodeViewController { destination.managedObjectContext = self.managedObjectContext } } // func addDragGestureToCancel() { // // let dragGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(QRViewController.drag(gestureRecognizer:))) // qrView.addGestureRecognizer(dragGestureRecognizer) // // } // func createGradientLayer() { // // //Begin, define gradient color shade from RGB(210,116,184) to RGB(144,112,196) // let headGradientColor = UIColor(red: 0.82, green: 0.455, blue: 0.72, alpha: 1).cgColor // let tailGradientColor = UIColor(red: 0.565, green: 0.44, blue: 0.77, alpha: 1).cgColor // // // // //Begin, create gradient layer with 2 colors shade and start gradient from left to right // let gradientLayer = CAGradientLayer() // gradientLayer.frame = CGRect(x: 0, y: 0, width: gradientView.bounds.width, height: gradientView.bounds.height) // gradientLayer.colors = [headGradientColor, tailGradientColor] // gradientLayer.startPoint = CGPoint(x: 0, y: 0) // gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0) // //End // // gradientView.layer.insertSublayer(gradientLayer, at: 0) // // } }
mit
7979ec9837dfa1ce82261a03a1ca1258
31.506977
136
0.576191
5.049855
false
false
false
false
horizon-institute/babyface-ios
src/Extensions.swift
1
2074
// // Extensions.swift // babyface // // Created by Kevin Glover on 15 Mar 2016. // Copyright © 2016 Horizon. All rights reserved. // import Foundation import UIKit extension UIView { func makeCirclePath(bounds: CGRect) -> CGPathRef { return UIBezierPath(roundedRect: bounds, cornerRadius: bounds.width).CGPath } func circleReveal(speed: CFTimeInterval) { let mask = CAShapeLayer() mask.path = makeCirclePath(CGRect(x: bounds.midX, y: bounds.midY, width: 0, height: 0)) mask.fillColor = UIColor.blackColor().CGColor layer.mask = mask CATransaction.begin() let animation = CABasicAnimation(keyPath: "path") animation.duration = speed animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false let size = max(bounds.width, bounds.height) let newPath = makeCirclePath(CGRect(x: bounds.midX - (size / 2), y: bounds.midY - (size / 2), width: size, height: size)) animation.fromValue = mask.path animation.toValue = newPath CATransaction.setCompletionBlock() { self.layer.mask = nil; } mask.addAnimation(animation, forKey:"path") CATransaction.commit() hidden = false } func circleHide(speed: CFTimeInterval, altView: UIView? = nil) { let mask = CAShapeLayer() let size = max(bounds.width, bounds.height) mask.path = makeCirclePath(CGRect(x: bounds.midX - (size / 2), y: bounds.midY - (size / 2), width: size, height: size)) mask.fillColor = UIColor.blackColor().CGColor layer.mask = mask CATransaction.begin() let animation = CABasicAnimation(keyPath: "path") animation.duration = speed animation.fillMode = kCAFillModeForwards animation.removedOnCompletion = false let newPath = makeCirclePath(CGRect(x: bounds.midX, y: bounds.midY, width: 0, height: 0)) animation.fromValue = mask.path animation.toValue = newPath CATransaction.setCompletionBlock() { self.hidden = true self.layer.mask = nil if let view = altView { view.hidden = false } } mask.addAnimation(animation, forKey:"path") CATransaction.commit() } }
gpl-3.0
0993e2ac70c1f8e174540b380506196e
25.253165
123
0.706223
3.592721
false
false
false
false
apple/swift-tools-support-core
Sources/TSCLibc/libc.swift
1
3247
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ #if canImport(Glibc) @_exported import Glibc #elseif os(Windows) @_exported import CRT @_exported import WinSDK #else @_exported import Darwin.C #endif #if os(Windows) private func __randname(_ buffer: UnsafeMutablePointer<CChar>) { let alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" _ = (0 ..< 6).map { index in buffer[index] = CChar(alpha.shuffled().randomElement()!.utf8.first!) } } // char *mkdtemp(char *template); // NOTE(compnerd) this is unsafe! This assumes that the template is *ASCII*. public func mkdtemp( _ template: UnsafeMutablePointer<CChar>? ) -> UnsafeMutablePointer<CChar>? { // Although the signature of the function is `char *(*)(char *)`, the C // library treats it as `char *(*)(char * _Nonull)`. Most implementations // will simply use and trigger a segmentation fault on x86 (and similar faults // on other architectures) when the memory is accessed. This roughly emulates // that by terminating in the case even though it is possible for us to return // an error. guard let template = template else { fatalError() } let length: Int = strlen(template) // Validate the precondition: the template must terminate with 6 `X` which // will be filled in to generate a unique directory. guard length >= 6, memcmp(template + length - 6, "XXXXXX", 6) == 0 else { _set_errno(EINVAL) return nil } // Attempt to create the directory var retries: Int = 100 repeat { __randname(template + length - 6) if _mkdir(template) == 0 { return template } retries = retries - 1 } while retries > 0 return nil } // int mkstemps(char *template, int suffixlen); public func mkstemps( _ template: UnsafeMutablePointer<CChar>?, _ suffixlen: Int32 ) -> Int32 { // Although the signature of the function is `char *(*)(char *)`, the C // library treats it as `char *(*)(char * _Nonull)`. Most implementations // will simply use and trigger a segmentation fault on x86 (and similar faults // on other architectures) when the memory is accessed. This roughly emulates // that by terminating in the case even though it is possible for us to return // an error. guard let template = template else { fatalError() } let length: Int = strlen(template) // Validate the precondition: the template must terminate with 6 `X` which // will be filled in to generate a unique directory. guard length >= 6, memcmp(template + length - Int(suffixlen) - 6, "XXXXXX", 6) == 0 else { _set_errno(EINVAL) return -1 } // Attempt to create file var retries: Int = 100 repeat { __randname(template + length - Int(suffixlen) - 6) var fd: CInt = -1 if _sopen_s(&fd, template, _O_RDWR | _O_CREAT | _O_BINARY | _O_NOINHERIT, _SH_DENYNO, _S_IREAD | _S_IWRITE) == 0 { return fd } retries = retries - 1 } while retries > 0 return -1 } #endif
apache-2.0
2ea4a8e9724fad1cac17327c4d53be92
31.79798
92
0.682168
3.893285
false
false
false
false
wesj/firefox-ios-1
Storage/SQL/BrowserDB.swift
2
7065
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public enum QuerySort { case None, LastVisit, Frecency } public enum FilterType { case ExactUrl case Url case Guid case Id case None } public class QueryOptions { // A filter string to apploy to the query public var filter: AnyObject? = nil // Allows for customizing how the filter is applied (i.e. only urls or urls and titles?) public var filterType: FilterType = .None // The way to sort the query public var sort: QuerySort = .None public init(filter: AnyObject? = nil, filterType: FilterType = .None, sort: QuerySort = .None) { self.filter = filter self.filterType = filterType self.sort = sort } } let DBCouldNotOpenErrorCode = 200 /* This is a base interface into our browser db. It holds arrays of tables and handles basic creation/updating of them. */ // Version 1 - Basic history table // Version 2 - Added a visits table, refactored the history table to be a GenericTable // Version 3 - Added a favicons table // Version 4 - Added a readinglist table // Version 5 - Added the clients and the tabs tables. class BrowserDB { private let db: SwiftData // XXX: Increasing this should blow away old history, since we currently dont' support any upgrades private let Version: Int = 5 private let FileName = "browser.db" private let files: FileAccessor private let schemaTable: SchemaTable<TableInfo> private var initialized = [String]() init?(files: FileAccessor) { self.files = files db = SwiftData(filename: files.getAndEnsureDirectory()!.stringByAppendingPathComponent(FileName)) self.schemaTable = SchemaTable() self.createOrUpdate(self.schemaTable) } var filename: String { return db.filename } // Creates a table and writes its table info the the table-table database. private func createTable<T:Table>(db: SQLiteDBConnection, table: T) -> Bool { debug("Try create \(table.name) version \(table.version)") if !table.create(db, version: table.version) { // If creating failed, we'll bail without storing the table info return false } var err: NSError? = nil return schemaTable.insert(db, item: table, err: &err) > -1 } // Updates a table and writes its table into the table-table database. private func updateTable<T: Table>(db: SQLiteDBConnection, table: T) -> Bool { debug("Try update \(table.name) version \(table.version)") var from = 0 // Try to find the stored version of the table let cursor = schemaTable.query(db, options: QueryOptions(filter: table.name)) if cursor.count > 0 { if let info = cursor[0] as? TableInfoWrapper { from = info.version } } // If the versions match, no need to update if from == table.version { return true } if !table.updateTable(db, from: from, to: table.version) { // If the update failed, we'll bail without writing the change to the table-table return false } var err: NSError? = nil return schemaTable.update(db, item: table, err: &err) > 0 } // Utility for table classes. They should call then when they're initialized to force // creation of the table in the database func createOrUpdate<T: Table>(table: T) -> Bool { debug("Create or update \(table.name) version \(table.version)") var success = true db.transaction({ connection -> Bool in // If the table doesn't exist, we'll create it if !table.exists(connection) { success = self.createTable(connection, table: table) } else { // Otherwise, we'll update it success = self.updateTable(connection, table: table) if !success { println("Update failed for \(table.name). Dropping and recreating") table.drop(connection) var err: NSError? = nil self.schemaTable.delete(connection, item: table, err: &err) success = self.createTable(connection, table: table) } } // If we failed, move the file and try again. This will probably break things that are already // attached and expecting a working DB, but at least we should be able to restart if !success { println("Couldn't create or update \(table.name)") success = self.files.move(self.FileName, toRelativePath: "\(self.FileName).bak") assert(success) success = self.createTable(connection, table: table) } return success }) return success } typealias CursorCallback = (connection: SQLiteDBConnection, inout err: NSError?) -> Cursor typealias IntCallback = (connection: SQLiteDBConnection, inout err: NSError?) -> Int func insert(inout err: NSError?, callback: IntCallback) -> Int { var res = 0 db.withConnection(SwiftData.Flags.ReadWrite) { connection in var err: NSError? = nil res = callback(connection: connection, err: &err) return err } return res } func update(inout err: NSError?, callback: IntCallback) -> Int { var res = 0 db.withConnection(SwiftData.Flags.ReadWrite) { connection in var err: NSError? = nil res = callback(connection: connection, err: &err) return err } return res } func delete(inout err: NSError?, callback: IntCallback) -> Int { var res = 0 db.withConnection(SwiftData.Flags.ReadWrite) { connection in var err: NSError? = nil res = callback(connection: connection, err: &err) return err } return res } func query(inout err: NSError?, callback: CursorCallback) -> Cursor { var c: Cursor! db.withConnection(SwiftData.Flags.ReadOnly) { connection in var err: NSError? = nil c = callback(connection: connection, err: &err) return err } return c } func transaction(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) { db.transaction { connection in var err: NSError? = nil return callback(connection: connection, err: &err) } } private let debug_enabled = false private func debug(err: NSError) { debug("\(err.code): \(err.localizedDescription)") } private func debug(msg: String) { if debug_enabled { println("BrowserDB: " + msg) } } }
mpl-2.0
536f6fc38fa592d581dcf552699718d2
34.325
122
0.609908
4.602606
false
false
false
false
jumpingfrog0/JFPlayer
Source/JFPlayerItem.swift
2
1790
// JFBrightnessView.swift // JFPlayerDemo // // Created by jumpingfrog0 on 14/12/2016. // // // Copyright (c) 2016 Jumpingfrog0 LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class JFPlayerItem { var title: String var resources: [JFPlayerDefinitionProtocol] var cover: String init(title: String, resources: [JFPlayerDefinitionProtocol], cover: String = "") { self.title = title self.resources = resources self.cover = cover } } class JFPlayerDefinitionItem: JFPlayerDefinitionProtocol { var videoUrl: URL var definitionName: String init(url: URL, definitionName: String) { self.videoUrl = url self.definitionName = definitionName } }
mit
9b4b979d814d7f06c477e62754b06599
34.8
86
0.721229
4.231678
false
false
false
false
makomori/Dots
Example/Dots/UIColor+hex.swift
2
833
// // UIColor+hex.swift // Pods // // Created by 母利睦人 on 2017/05/11. // // import UIKit extension UIColor { class func hexStr ( hexStr : NSString, alpha : CGFloat) -> UIColor { var hexStr = hexStr let alpha = alpha hexStr = hexStr.replacingOccurrences(of: "#", with: "") as NSString let scanner = Scanner(string: hexStr as String) var color: UInt32 = 0 if scanner.scanHexInt32(&color) { let r = CGFloat((color & 0xFF0000) >> 16) / 255.0 let g = CGFloat((color & 0x00FF00) >> 8) / 255.0 let b = CGFloat(color & 0x0000FF) / 255.0 return UIColor(red:r,green:g,blue:b,alpha:alpha) } else { // Invalid hex string print("invalid hex string") return UIColor.white; } } }
mit
1260575db601282a44b08497db414d44
27.448276
75
0.551515
3.699552
false
false
false
false
Ramshandilya/Swift-Notes
Swift-Notes.playground/Pages/20. Nested Types.xcplaygroundpage/Contents.swift
1
3602
//: # Swift Foundation //: ---- //: ## Nested Types //: Swift enables you to define *nested types*, whereby you nest enumerations, classes and structures within the definition of the type they support. Types can be nested to as many levels as are required. struct Message { enum Status { case Sent case Received case Read } let sender: String let recepient: String let message: String init(sender: String, recepient: String, message: String) { self.sender = sender self.recepient = recepient self.message = message } var status: Status = .Sent func printStatus() -> String { switch status{ case .Sent: return "Message Sent" case .Received: return "Message Received" case .Read: return "Message Read" } } } var message = Message(sender: "Robb", recepient: "Jon Snow", message: "Bran is alive") message.status = Message.Status.Read //: ## Nesting Value and Reference Types //: There are four possible combinations when nesting value and reference types. //: ### Reference type in a reference type //: If you have a reference type which contains another reference type, anything which has a reference to either the inner or outer value can manipulate it, as usual. Everyone will see any changes made. class ClassA { var value = 0 var foo = InnerClass() class InnerClass { var innerValue = 0 } } var outer = ClassA() var outer2 = outer outer.value = 10 outer.foo.innerValue = 11 outer2.value outer2.foo.innerValue //: ### Value type in a Value type //: If you have a value type which contains a value type, this makes the outer value bigger. The inner value is part of the outer value. When you assign the outer instance to an other instance, everything get copied, including the inner value. struct StructA { var value = 0 var foo = InnerStruct() struct InnerStruct { var innerValue = 0 } } var outer3 = StructA() var outer4 = outer3 outer3.value = 20 outer3.foo.innerValue = 21 outer4.value outer4.foo.innerValue //: ### Value type in a Reference type //: If you have a reference type which contains a value type, this also makes the referenced value bigger. Anyone with a reference to the outer value can manipulate the whole thing, including the nested value. class ClassB { var value = 0 var foo = InnerStruct() struct InnerStruct { var innerValue = 0 } } var outer5 = ClassB() var outer6 = outer5 outer5.value = 30 outer5.foo.innerValue = 31 outer6.value outer6.foo.innerValue //Inner is a Value type. var outer7 = ClassB() outer6.foo = outer7.foo outer6.value outer6.foo.innerValue //: ### Reference type in a Value type //: If you have a value type which contains a reference type, things get interesting. The outer value being value type, gets copied, but the copy has a reference to the same nested type as the original. struct StructB { var value = 0 var foo = InnerClass() class InnerClass { var innerValue = 0 } } var outer8 = StructB() var outer9 = outer8 outer8.value = 40 outer9.value outer8.foo.innerValue = 41 outer9.foo.innerValue // 😰 OUCH!!! //We are effective breaking value semantics, which can do more bad than good. //: Hence always be cautious of nesting reference types in a value type. In the ablove example, it is a good indication that the outer type shouldn't be a struct, since we couldn't maintain value semantics. //: ---- //: [Next](@next)
mit
b645398d7d6991b733e14d3c0fafc8d3
24.524823
244
0.679078
4.012263
false
false
false
false
chrisamanse/Stopwatch
Stopwatch/Stopwatch.swift
1
3423
// // Stopwatch.swift // Stopwatch // // Created by Joe Amanse on 06/12/2015. // Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved. // import Foundation public class Stopwatch: NSObject { internal var timer: NSTimer? public weak var dataSource: StopwatchDataSource? { didSet { if active { createTimer() } } } public weak var delegate: StopwatchDelegate? { didSet { if active { // When delegate is set to non-nil from nil, recreate timer if oldValue == nil && delegate != nil { createTimer() } else if delegate == nil { destroyTimer() } } } } public internal(set) var startDate: NSDate? internal var timePassedOnPause: NSTimeInterval public override init() { timePassedOnPause = 0 super.init() } public var active: Bool { return startDate != nil } public internal(set) var paused: Bool = false public var stopped: Bool { return !active && timePassedOnPause == 0 } public var timePassed: NSTimeInterval { var currentTimeInterval: NSTimeInterval = 0 if let date = startDate { currentTimeInterval = NSDate().timeIntervalSinceDate(date) } return timePassedOnPause + currentTimeInterval } public func start() { startWithTimeIntervalOffset(0) } /** Start a timer with an offset. For example, if offset is 60 seconds, then the starting value of `timePassed` of the receiver is 60 seconds. - parameters: - offset: the offset for the stopwatch */ public func startWithTimeIntervalOffset(offset: NSTimeInterval) { timePassedOnPause = paused ? timePassedOnPause + offset : offset startDate = NSDate() createTimer() paused = false } public func pause() { destroyTimer() timePassedOnPause = timePassed startDate = nil paused = true } public func stop() { destroyTimer() paused = false timePassedOnPause = 0 startDate = nil } public func triggerRefresh(sender: AnyObject?) { delegate?.stopwatchDidRefresh(self) } private func createTimer() { // Always destroy old timer when creating a new one destroyTimer() // Create timer only when delegate is not empty guard delegate != nil else { return } // Get interval from data source if let interval = dataSource?.refreshIntervalForStopwatch(self) { let newTimer = NSTimer(timeInterval: interval, target: self, selector: #selector(triggerRefresh(_:)), userInfo: nil, repeats: true) timer = newTimer NSRunLoop.mainRunLoop().addTimer(newTimer, forMode: NSRunLoopCommonModes) } } private func destroyTimer() { timer?.invalidate() timer = nil } } public protocol StopwatchDataSource: class { func refreshIntervalForStopwatch(stopwatch: Stopwatch) -> NSTimeInterval } public protocol StopwatchDelegate: class { func stopwatchDidRefresh(stopwatch: Stopwatch) }
mit
45206b201349621e6505b457d1f1392b
25.952756
143
0.581531
5.338534
false
false
false
false
cristianames92/PortalView
Sources/Components/Progress.swift
2
1343
// // Progress.swift // PortalView // // Created by Cristian Ames on 4/11/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // public func progress<MessageType>( progress: ProgressCounter = ProgressCounter.initial, style: StyleSheet<ProgressStyleSheet> = ProgressStyleSheet.defaultStyleSheet, layout: Layout = layout()) -> Component<MessageType> { return .progress(progress, style, layout) } // MARK:- Style sheet public enum ProgressContentType { case color(Color) case image(Image) } public struct ProgressStyleSheet { public static let defaultStyleSheet = StyleSheet<ProgressStyleSheet>(component: ProgressStyleSheet()) public var progressStyle: ProgressContentType public var trackStyle: ProgressContentType public init( progressStyle: ProgressContentType = .color(defaultProgressColor), trackStyle: ProgressContentType = .color(defaultTrackColor)) { self.progressStyle = progressStyle self.trackStyle = trackStyle } } public func progressStyleSheet(configure: (inout BaseStyleSheet, inout ProgressStyleSheet) -> ()) -> StyleSheet<ProgressStyleSheet> { var base = BaseStyleSheet() var custom = ProgressStyleSheet() configure(&base, &custom) return StyleSheet(component: custom, base: base) }
mit
502f5f998c329111ee3ac9f3bbb7ef4f
28.173913
133
0.716841
4.59589
false
false
false
false
CoderSLZeng/SLWeiBo
SLWeiBo/SLWeiBo/Classes/Home/Popover/SLPresentationController.swift
1
1439
// // SLPresentationController.swift // SLWeiBo // // Created by Anthony on 17/3/7. // Copyright © 2017年 SLZeng. All rights reserved. // import UIKit class SLPresentationController: UIPresentationController { // MARK:- 对外提供属性 var presentedFrame : CGRect = CGRect.zero // MARK: - 懒加载属性 fileprivate lazy var coverView : UIView = UIView() // MARK: - 系统回调函数 override func containerViewWillLayoutSubviews() { super.containerViewWillLayoutSubviews() // 1.设置弹出View的尺寸 presentedView?.frame = presentedFrame // 2.添加蒙版 setupCoverView() } } // MARK: - 设置UI界面相关 extension SLPresentationController { fileprivate func setupCoverView() { // 1.添加蒙版 containerView?.insertSubview(coverView, at: 0) // 2.设置蒙版的属性 coverView.backgroundColor = UIColor(white: 0.8, alpha: 0.2) coverView.frame = containerView!.bounds // 3.添加手势 let tapGes = UITapGestureRecognizer(target: self, action: #selector(SLPresentationController.coverViewClick)) coverView.addGestureRecognizer(tapGes) } } // MARK: - 事件监听 extension SLPresentationController { @objc fileprivate func coverViewClick() { presentedViewController.dismiss(animated: true, completion: nil) } }
mit
74c25c350efb5ebf5eb584bf13efcbc5
25.078431
117
0.65188
4.784173
false
false
false
false
zhangdadi/SwiftHttp
HDNetwork/HDNetwork/Network/HDNetRequestQueue.swift
1
6095
// // HDNetRequestQueue.swift // HDNetFramework // // Created by 张达棣 on 14-7-23. // Copyright (c) 2014年 HD. All rights reserved. // // 若发现bug请致电:z_dadi@163.com,在此感谢你的支持。 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit /** * 带队列的网络请求 */ class HDNetQueuedRequest: HDNetRequest { var queue: HDNetRequestQueue? //队列 var _fProcessingQueue: HDNetRequestQueue? // 正在排队中的队列 final override var isInProgress: Bool { get { if let v = _fProcessingQueue { if v.isInQueue(request: self) { //判断请求是否在队列中 return true } } return queuedInProgress() //判断请求是否在进行中 } set { super.isInProgress = newValue } } //+__________________________________________ // 开始请求,子类应重写此方法 func queuedStart() -> Bool { return false; } // 停止请求,子类应重写此方法 func queuedStop() { } // 判断请求本身是否在进行中,子类重写此方法 func queuedInProgress() -> Bool { return false } //-__________________________________________ final override func start() -> Bool { if queue == nil { return queuedStart() } queue?.enqueueRequest(self) return true } final override func cancel() { if _fProcessingQueue != nil { if _fProcessingQueue!.removeRequest(self) { return } } if isInProgress == false { return } queuedStop() } override func requestCompleted(error: NSError?) { if _fProcessingQueue != nil { _fProcessingQueue!.notifyRequestCompleted(self) _fProcessingQueue = nil } super.requestCompleted(error) } //新加入队列 func onRequestQueueEnter(sender: HDNetRequestQueue) { _fProcessingQueue = sender } //退出队列 func onRequestQueueLeave(sender: HDNetRequestQueue) { if _fProcessingQueue == sender { _fProcessingQueue = nil } } } //_______________________________________________________________________ /** * 队列 */ class HDNetRequestQueue: NSObject { var _requestQueue = [HDNetQueuedRequest]() var _requestCount: UInt = 0 var _maxParrielRequestCount: UInt = 1 //最大的同时下载数 //+___________________________________________________ // 将请求加入队尾 func enqueueRequest(request: HDNetQueuedRequest!) { assert(request.isInProgress == false, "请求正在进行中") //从队列中删除 var exists = _internalRemoveRequest(request) //重新加入队列 _requestQueue.append(request) if exists == false { // 通知请求对象:新加入队列 request.onRequestQueueEnter(self) } // 继续请求 _continueProcessRequest() } // 移除请求 func removeRequest(request: HDNetQueuedRequest!) -> Bool { if _internalRemoveRequest(request) { // 通知请求对象:退出队列 request.onRequestQueueLeave(self) return true } return false } // 判断请求是否在队列中 func isInQueue(#request: HDNetQueuedRequest!) -> Bool { for item in _requestQueue { if item == request { return true } } return false } // 由HDNetQueuedRequest调用,通知HDNetRequestQueue下载已完成 func notifyRequestCompleted(request: HDNetQueuedRequest!) { assert(_requestCount != 0, "请求队列已为0") _requestCount-- request.onRequestQueueLeave(self) _continueProcessRequest() } //-___________________________________________________ func _continueProcessRequest() { _doProcessRequest() } func _doProcessRequest() { while _requestCount < _maxParrielRequestCount { if _requestQueue.count == 0 { //没有等待中的请求 return } //提取请求 var request = _requestQueue[0] _requestQueue.removeAtIndex(0) //开始 if request.queuedStart() { _requestCount++ } else { //请求失败 } } } func _internalRemoveRequest(request: HDNetQueuedRequest!) -> Bool { var i = 0 for item in _requestQueue { if item == request { debugPrintln("删除") _requestQueue.removeAtIndex(i) return true } ++i } return false } }
mit
ead10b1ccfba5e8eac2308e17e57783f
25.246512
81
0.541024
4.48926
false
false
false
false
cezarywojcik/Operations
Tests/Core/BlockConditionTests.swift
1
2303
// // BlockConditionTests.swift // Operations // // Created by Daniel Thorpe on 20/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import XCTest @testable import Operations class BlockConditionTests: OperationTests { func test__operation_with_successful_block_condition_finishes() { let operation = TestOperation() operation.addCondition(BlockCondition { true }) addCompletionBlockToTestOperation(operation, withExpectation: expectationWithDescription("Test: \(#function)")) runOperation(operation) waitForExpectations(timeout: 3, handler: nil) XCTAssertTrue(operation.finished) } func test__operation_with_unsuccessful_block_condition_errors() { let expectation = self.expectation(description: "Test: \(#function)") let operation = TestOperation() operation.addCondition(BlockCondition { false }) var receivedErrors = [Error]() operation.addObserver(DidFinishObserver { _, errors in receivedErrors = errors expectation.fulfill() }) runOperation(operation) waitForExpectations(timeout: 3, handler: nil) XCTAssertFalse(operation.didExecute) if let error = receivedErrors[0] as? BlockCondition.Error { XCTAssertTrue(error == BlockCondition.Error.BlockConditionFailed) } else { XCTFail("No error message was observed") } } func test__operation_with_block_which_throws_condition_errors() { let expectation = self.expectation(description: "Test: \(#function)") let operation = TestOperation() operation.addCondition(BlockCondition { throw TestOperation.Error.SimulatedError }) var receivedErrors = [Error]() operation.addObserver(DidFinishObserver { _, errors in receivedErrors = errors expectation.fulfill() }) runOperation(operation) waitForExpectations(timeout: 3, handler: nil) XCTAssertFalse(operation.didExecute) if let error = receivedErrors[0] as? TestOperation.Error { XCTAssertTrue(error == TestOperation.Error.simulatedError) } else { XCTFail("No error message was observed") } } }
mit
ceb3aa1ad6631467a1d9ea7e1d827b45
31.422535
119
0.657689
5.161435
false
true
false
false
huonw/swift
test/SILGen/synthesized_conformance_struct.swift
1
5751
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-silgen %s -swift-version 4 | %FileCheck %s struct Struct<T> { var x: T } // CHECK-LABEL: struct Struct<T> { // CHECK: @sil_stored var x: T { get set } // CHECK: init(x: T) // CHECK: enum CodingKeys : CodingKey { // CHECK: case x // CHECK: var stringValue: String { get } // CHECK: init?(stringValue: String) // CHECK: var intValue: Int? { get } // CHECK: init?(intValue: Int) // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Struct<T>.CodingKeys, _ b: Struct<T>.CodingKeys) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK: } // CHECK-LABEL: extension Struct : Equatable where T : Equatable { // CHECK: @_implements(Equatable, ==(_:_:)) static func __derived_struct_equals(_ a: Struct<T>, _ b: Struct<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Struct : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Struct : Decodable & Encodable where T : Decodable, T : Encodable { // CHECK: init(from decoder: Decoder) throws // CHECK: func encode(to encoder: Encoder) throws // CHECK: } extension Struct: Equatable where T: Equatable {} // CHECK-LABEL: // static Struct<A>.__derived_struct_equals(_:_:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAAs9EquatableRzlE010__derived_C7_equalsySbACyxG_AFtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Struct<T>, @in_guaranteed Struct<T>, @thin Struct<T>.Type) -> Bool { extension Struct: Hashable where T: Hashable {} // CHECK-LABEL: // Struct<A>.hashValue.getter // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAAs8HashableRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Struct<T>) -> Int { // CHECK-LABEL: // Struct<A>.hash(into:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAAs8HashableRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Struct<T>) -> () { extension Struct: Codable where T: Codable {} // CHECK-LABEL: // Struct<A>.init(from:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAAs9DecodableRzs9EncodableRzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable, T : Encodable> (@in Decoder, @thin Struct<T>.Type) -> (@out Struct<T>, @error Error) // CHECK-LABEL: // Struct<A>.encode(to:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAAs9DecodableRzs9EncodableRzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Decodable, T : Encodable> (@in_guaranteed Encoder, @in_guaranteed Struct<T>) -> @error Error { // Witness tables // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct { // CHECK-NEXT: method #Equatable."=="!1: <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$S30synthesized_conformance_struct6StructVyxGs9EquatableAAsAERzlsAEP2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Struct<T>: Hashable module synthesized_conformance_struct { // CHECK-NEXT: base_protocol Equatable: <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct // CHECK-NEXT: method #Hashable.hashValue!getter.1: <Self where Self : Hashable> (Self) -> () -> Int : @$S30synthesized_conformance_struct6StructVyxGs8HashableAAsAERzlsAEP9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Struct<A> // CHECK-NEXT: method #Hashable.hash!1: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$S30synthesized_conformance_struct6StructVyxGs8HashableAAsAERzlsAEP4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Struct<A> // CHECK-NEXT: method #Hashable._rawHashValue!1: <Self where Self : Hashable> (Self) -> ((UInt64, UInt64)) -> Int : @$S30synthesized_conformance_struct6StructVyxGs8HashableAAsAERzlsAEP13_rawHashValue4seedSis6UInt64V_AJt_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Hashable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Decodable module synthesized_conformance_struct { // CHECK-NEXT: method #Decodable.init!allocator.1: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$S30synthesized_conformance_struct6StructVyxGs9DecodableAAsAERzs9EncodableRzlsAEP4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Encodable module synthesized_conformance_struct { // CHECK-NEXT: method #Encodable.encode!1: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$S30synthesized_conformance_struct6StructVyxGs9EncodableAAs9DecodableRzsAERzlsAEP6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: }
apache-2.0
38fbcc2e8dd63fd54e4eb27960be2966
73.688312
309
0.725961
3.460289
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatModule/Input/InputView/Emoticon/JCEmoticonPreviewer.swift
1
2594
// // JCEmoticonPreviewer.swift // JChat // // Created by JIGUANG on 2017/3/9. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit internal class JCEmoticonPreviewer: UIView { func preview(_ emoticon: JCEmoticon?, _ itemType: JCEmoticonType, in rect: CGRect) { guard let emoticon = emoticon else { isHidden = true return } _type = itemType _popoverFrame = _popoverFrame(in: rect, and: _backgroundView.bounds(for: itemType)) _presenterFrame = _presenterFrame(in: rect, and: _popoverFrame) frame = _popoverFrame isHidden = false _contentView.frame = _backgroundView.boundsOfContent(for: itemType) _backgroundView.popoverFrame = convert(_popoverFrame, from: superview) _backgroundView.presenterFrame = convert(_presenterFrame, from: superview) _backgroundView.updateBackgroundImages(with: itemType) _backgroundView.updateBackgroundLayouts() // update emoticon.show(in: _contentView) } private func _popoverFrame(in frame: CGRect, and bounds: CGRect) -> CGRect { var nframe = bounds nframe.origin.x = frame.midX + bounds.minX - nframe.width / 2 nframe.origin.y = frame.minY + bounds.minY - nframe.height if let window = window, _type.isLarge { nframe.origin.x = max(nframe.minX, _inset.left) nframe.origin.x = min(nframe.minX, window.frame.maxX - bounds.width - _inset.right) } return nframe } private func _presenterFrame(in frame: CGRect, and bounds: CGRect) -> CGRect { return CGRect(x: frame.minX, y: frame.minY - bounds.height, width: frame.width, height: frame.height + bounds.height) } private func _init() { addSubview(_backgroundView) addSubview(_contentView) } private var _type: JCEmoticonType = .small private var _inset: UIEdgeInsets = UIEdgeInsets.init(top: 0, left: 4, bottom: 0, right: 4) private var _popoverFrame: CGRect = .zero private var _presenterFrame: CGRect = .zero private lazy var _contentView: UIView = UIView() private lazy var _backgroundView: JCEmoticonBackgroundView = JCEmoticonBackgroundView() override init(frame: CGRect) { super.init(frame: frame) _init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _init() } }
mit
aaf97041e31a5ee2c7e7b3bbb2b002b5
31.797468
95
0.609031
4.384095
false
false
false
false
btanner/Eureka
Example/Example/Controllers/MultivaluedExamples.swift
3
9504
// // MultivaluedSectionsController.swift // Example // // Created by Mathias Claassen on 3/15/18. // Copyright © 2018 Xmartlabs. All rights reserved. // import Eureka class MultivaluedSectionsController: FormViewController { override func viewDidLoad() { super.viewDidLoad() title = "Multivalued examples" form +++ Section("Multivalued examples") <<< ButtonRow(){ $0.title = "Multivalued Sections" $0.presentationMode = .segueName(segueName: "MultivaluedControllerSegue", onDismiss: nil) } <<< ButtonRow(){ $0.title = "Multivalued Only Reorder" $0.presentationMode = .segueName(segueName: "MultivaluedOnlyReorderControllerSegue", onDismiss: nil) } <<< ButtonRow(){ $0.title = "Multivalued Only Insert" $0.presentationMode = .segueName(segueName: "MultivaluedOnlyInsertControllerSegue", onDismiss: nil) } <<< ButtonRow(){ $0.title = "Multivalued Only Delete" $0.presentationMode = .segueName(segueName: "MultivaluedOnlyDeleteControllerSegue", onDismiss: nil) } } } class MultivaluedController: FormViewController { override func viewDidLoad() { super.viewDidLoad() title = "Multivalued Examples" form +++ MultivaluedSection(multivaluedOptions: [.Reorder, .Insert, .Delete], header: "Multivalued TextField", footer: ".Insert multivaluedOption adds the 'Add New Tag' button row as last cell.") { $0.tag = "textfields" $0.addButtonProvider = { section in return ButtonRow(){ $0.title = "Add New Tag" }.cellUpdate { cell, row in cell.textLabel?.textAlignment = .left } } $0.multivaluedRowToInsertAt = { index in return NameRow() { $0.placeholder = "Tag Name" } } $0 <<< NameRow() { $0.placeholder = "Tag Name" } } +++ MultivaluedSection(multivaluedOptions: [.Insert, .Delete], header: "Multivalued ActionSheet Selector example", footer: ".Insert multivaluedOption adds a 'Add' button row as last cell.") { $0.tag = "options" $0.multivaluedRowToInsertAt = { index in return ActionSheetRow<String>{ $0.title = "Tap to select.." $0.options = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] } } $0 <<< ActionSheetRow<String> { $0.title = "Tap to select.." $0.options = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] } } +++ MultivaluedSection(multivaluedOptions: [.Insert, .Delete, .Reorder], header: "Multivalued Push Selector example") { $0.tag = "push" $0.multivaluedRowToInsertAt = { index in return PushRow<String>{ $0.title = "Tap to select ;)..at \(index)" $0.options = ["Option 1", "Option 2", "Option 3"] } } $0 <<< PushRow<String> { $0.title = "Tap to select ;).." $0.options = ["Option 1", "Option 2", "Option 3"] } } } @IBAction func save(_ sender: Any) { print("\(form.values())") } } class MultivaluedOnlyReorderController: FormViewController { override func viewDidLoad() { super.viewDidLoad() let secondsPerDay = 24 * 60 * 60 let list = ["Today", "Yesterday", "Before Yesterday"] form +++ MultivaluedSection(multivaluedOptions: .Reorder, header: "Reordering Selectors") { $0 <<< PushRow<String> { $0.title = "Tap to select ;).." $0.options = ["Option 1", "Option 2", "Option 3"] } <<< PushRow<String> { $0.title = "Tap to select ;).." $0.options = ["Option 1", "Option 2", "Option 3"] } <<< PushRow<String> { $0.title = "Tap to select ;).." $0.options = ["Option 1", "Option 2", "Option 3"] } <<< PushRow<String> { $0.title = "Tap to select ;).." $0.options = ["Option 1", "Option 2", "Option 3"] } } +++ // Multivalued Section with inline rows - section set up to support only reordering MultivaluedSection(multivaluedOptions: .Reorder, header: "Reordering Inline Rows") { section in list.enumerated().forEach({ offset, string in let dateInlineRow = DateInlineRow(){ $0.value = Date(timeInterval: Double(-secondsPerDay) * Double(offset), since: Date()) $0.title = string } section <<< dateInlineRow }) } +++ MultivaluedSection(multivaluedOptions: .Reorder, header: "Reordering Field Rows") <<< NameRow { $0.value = "Martin" } <<< NameRow { $0.value = "Mathias" } <<< NameRow { $0.value = "Agustin" } <<< NameRow { $0.value = "Enrique" } } } class MultivaluedOnlyInsertController: FormViewController { override func viewDidLoad() { super.viewDidLoad() title = "Multivalued Only Insert" form +++ MultivaluedSection(multivaluedOptions: .Insert) { sec in sec.addButtonProvider = { _ in return ButtonRow { $0.title = "Add Tag" }.cellUpdate { cell, row in cell.textLabel?.textAlignment = .left } } sec.multivaluedRowToInsertAt = { index in return TextRow { $0.placeholder = "Tag Name" } } sec.showInsertIconInAddButton = false } +++ MultivaluedSection(multivaluedOptions: .Insert, header: "Insert With Inline Cells") { $0.multivaluedRowToInsertAt = { index in return DateInlineRow { $0.title = "Date" $0.value = Date() } } } } } class MultivaluedOnlyDeleteController: FormViewController { @IBOutlet weak var editButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() tableView.isEditing = false let nameList = ["family", "male", "female", "client"] let section = MultivaluedSection(multivaluedOptions: .Delete) for tag in nameList { section <<< TextRow { $0.placeholder = "Tag Name" $0.value = tag } } let section2 = MultivaluedSection(multivaluedOptions: .Delete, footer: "") for _ in 1..<4 { section2 <<< PickerInlineRow<String> { $0.title = "Tap to select" $0.value = "client" $0.options = nameList } } editButton.title = tableView.isEditing ? "Done" : "Edit" editButton.target = self editButton.action = #selector(editPressed(sender:)) form +++ section +++ section2 } @objc func editPressed(sender: UIBarButtonItem){ tableView.setEditing(!tableView.isEditing, animated: true) editButton.title = tableView.isEditing ? "Done" : "Edit" } }
mit
41e39d2386afe3f361ef024de1c561ac
36.710317
125
0.417658
5.790981
false
false
false
false
CPRTeam/CCIP-iOS
OPass/Class+addition/OPassAPI/Portal.swift
1
8501
// // Portal.swift // OPass // // Created by 腹黒い茶 on 2019/6/17. // 2019 OPass. // import Foundation import Then import SwiftyJSON import SwiftDate enum OPassKnownFeatures: String { case FastPass = "fastpass" case Schedule = "schedule" case Announcement = "announcement" case Puzzle = "puzzle" case Ticket = "ticket" case Telegram = "telegram" case IM = "im" case WiFiConnect = "wifi" case Venue = "venue" case Sponsors = "sponsors" case Partners = "partners" case Staffs = "staffs" case WebView = "webview" } struct EventDisplayName: OPassData { var _data: JSON init(_ data: JSON) { self._data = data } subscript(_ member: String) -> String { if member == "_displayData" { return "" } return self._data[member].stringValue } } struct PublishDate: OPassData { var _data: JSON var Start: Date var End: Date init(_ data: JSON) { self._data = data self.Start = Date.init() self.End = Date.init() if let start = self._data["start"].stringValue.toDate(style: .iso(.init())) { self.Start = Date.init(seconds: start.timeIntervalSince1970) } if let end = self._data["end"].stringValue.toDate(style: .iso(.init())) { self.End = Date.init(seconds: end.timeIntervalSince1970) } } } struct EventWiFi: OPassData { var _data: JSON var SSID: String var Password: String init(_ data: JSON) { self._data = data self.SSID = self._data["SSID"].stringValue self.Password = self._data["password"].stringValue } } struct EventFeatures: OPassData { var _data: JSON var Feature: String var Icon: URL? var DisplayText: EventDisplayName var WiFi: [EventWiFi] var _url: String? var Url: URL? { get { if var newUrl = _url { guard let paramsRegex = try? NSRegularExpression.init(pattern: "(\\{[^\\}]+\\})", options: .caseInsensitive) else { return nil } let matches = paramsRegex.matches(in: newUrl, options: .reportProgress, range: NSRange(location: 0, length: newUrl.count)) for m in stride(from: matches.count, to: 0, by: -1) { let range = matches[m - 1].range(at: 1) let param = newUrl[range] switch param { case "{token}": newUrl = newUrl.replacingOccurrences(of: param, with: Constants.accessToken ?? "") case "{public_token}": newUrl = newUrl.replacingOccurrences(of: param, with: Constants.accessTokenSHA1) case "{role}": newUrl = newUrl.replacingOccurrences(of: param, with: OPassAPI.userInfo?.Role ?? "") default: newUrl = newUrl.replacingOccurrences(of: param, with: "") } } return URL(string: newUrl) } else { return nil } } } var VisibleRoles: [String]? init(_ data: JSON) { self._data = data self.Feature = self._data["feature"].stringValue self.Icon = self._data["icon"].url self.DisplayText = EventDisplayName(self._data["display_text"]) self.WiFi = self._data["wifi"].arrayValue.map({ wifi -> EventWiFi in return EventWiFi(wifi) }) self._url = self._data["url"].string self.VisibleRoles = self._data["visible_roles"].arrayObject as? [String] } } extension Array where Element == EventFeatures { subscript(_ feature: OPassKnownFeatures) -> EventFeatures? { return self.first { ft -> Bool in if OPassKnownFeatures(rawValue: ft.Feature) == feature { return true } return false } } } struct EventInfo: OPassData { var _data: JSON var EventId: String var DisplayName: EventDisplayName var LogoUrl: URL var Publish: PublishDate var Features: Array<EventFeatures> init(_ data: JSON) { self._data = data self.EventId = self._data["event_id"].stringValue self.DisplayName = EventDisplayName(self._data["display_name"]) self.LogoUrl = URL.init(fileURLWithPath: "") if let logoUrl = self._data["logo_url"].url { self.LogoUrl = logoUrl } self.Publish = PublishDate(self._data["publish"]) self.Features = self._data["features"].arrayValue.map { ft -> EventFeatures in return EventFeatures(ft) } } } struct EventShortInfo: Codable { var _data: JSON var EventId: String var DisplayName: EventDisplayName var LogoUrl: URL init(_ data: JSON) { self._data = data self.EventId = self._data["event_id"].stringValue self.DisplayName = EventDisplayName(self._data["display_name"]) self.LogoUrl = URL.init(fileURLWithPath: "") if let logoUrl = self._data["logo_url"].url { self.LogoUrl = logoUrl } } } extension OPassAPI { static func GetEvents(_ onceErrorCallback: OPassErrorCallback) -> Promise<Array<EventShortInfo>> { return OPassAPI.InitializeRequest("https://\(OPassAPI.PORTAL_DOMAIN)/events/", onceErrorCallback) .then({ (infoObj: Any) -> Array<EventShortInfo> in return JSON(infoObj).arrayValue.map { info -> EventShortInfo in return EventShortInfo(info) } }) } static func SetEvent(_ eventId: String, _ onceErrorCallback: OPassErrorCallback) -> Promise<EventInfo> { return OPassAPI.InitializeRequest("https://\(OPassAPI.PORTAL_DOMAIN)/events/\(eventId)/", onceErrorCallback) .then { (infoObj: Any) -> EventInfo in OPassAPI.eventInfo = EventInfo(JSON(infoObj)) OPassAPI.currentEvent = "" OPassAPI.lastEventId = "" if let eventJson = JSONSerialization.stringify(infoObj as Any) { OPassAPI.currentEvent = eventJson } if let eventInfo = OPassAPI.eventInfo { OPassAPI.lastEventId = eventInfo.EventId return eventInfo } return EventInfo(JSON(parseJSON: "{}")) } } static func CleanupEvents() { OPassAPI.currentEvent = "" OPassAPI.eventInfo = nil OPassAPI.userInfo = nil OPassAPI.scenarios = [] OPassAPI.isLoginSession = false AppDelegate.delegateInstance.checkinView = nil } static func DoLogin(_ eventId: String, _ token: String, _ completion: OPassCompletionCallback) { async { while true { var vc: UIViewController? = nil DispatchQueue.main.sync { if let topMost = UIApplication.getMostTopPresentedViewController() { vc = topMost } } guard let vcName = vc?.className else { return } var done = false try? await(Promise{ resolve, _ in switch vcName { case OPassEventsController.className: DispatchQueue.main.sync { OPassAPI.isLoginSession = false OPassAPI.userInfo = nil Constants.accessToken = "" } done = true resolve() break default: DispatchQueue.main.async { if let vc = vc { vc.dismiss(animated: true, completion: { resolve() }) } } } }) if done { break } } DispatchQueue.main.sync { if let opec = UIApplication.getMostTopPresentedViewController() as? OPassEventsController { opec.LoadEvent(eventId).then { _ in OPassAPI.RedeemCode(eventId, token, completion) } } } } } }
gpl-3.0
f3d026c3058a7652c6fcb7469937e437
33.245968
144
0.531968
4.697456
false
false
false
false
optimizely/objective-c-sdk
Pods/Mixpanel-swift/Mixpanel/JSONHandler.swift
1
3034
// // JSONHandler.swift // Mixpanel // // Created by Yarden Eitan on 6/3/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation class JSONHandler { typealias MPObjectToParse = Any class func encodeAPIData(_ obj: MPObjectToParse) -> String? { let data: Data? = serializeJSONObject(obj) guard let d = data else { Logger.warn(message: "couldn't serialize object") return nil } let base64Encoded = d.base64EncodedString(options: .lineLength64Characters) guard let b64 = base64Encoded .addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { Logger.warn(message: "couldn't replace characters to allowed URL character set") return nil } return b64 } class func serializeJSONObject(_ obj: MPObjectToParse) -> Data? { let serializableJSONObject = makeObjectSerializable(obj) guard JSONSerialization.isValidJSONObject(serializableJSONObject) else { Logger.warn(message: "object isn't valid and can't be serialzed to JSON") return nil } var serializedObject: Data? = nil do { serializedObject = try JSONSerialization .data(withJSONObject: serializableJSONObject, options: []) } catch { Logger.warn(message: "exception encoding api data") } return serializedObject } private class func makeObjectSerializable(_ obj: MPObjectToParse) -> MPObjectToParse { switch obj { case let obj as NSNumber: if isBoolNumber(obj) { return obj.boolValue } else { return obj } case let obj as Double where obj.isFinite: return obj case is String, is Int, is UInt, is UInt64, is Float, is Bool: return obj case let obj as Array<Any>: return obj.map() { makeObjectSerializable($0) } case let obj as InternalProperties: var serializedDict = InternalProperties() _ = obj.map() { e in serializedDict[e.key] = makeObjectSerializable(e.value) } return serializedDict case let obj as Date: let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" dateFormatter.timeZone = TimeZone(abbreviation: "UTC") dateFormatter.locale = Locale(identifier: "en_US_POSIX") return dateFormatter.string(from: obj) case let obj as URL: return obj.absoluteString default: Logger.info(message: "enforcing string on object") return String(describing: obj) } } private class func isBoolNumber(_ num: NSNumber) -> Bool { let boolID = CFBooleanGetTypeID() let numID = CFGetTypeID(num) return numID == boolID } }
apache-2.0
8a3d5d1576241e7f5638f1d1e1708643
29.636364
94
0.596769
4.868379
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/GraphSwitch.swift
1
2175
// // GraphSwitch.swift // denm_view // // Created by James Bean on 10/12/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class GraphSwitch: Graph { // if 1: states are Off, On; if 2: states are Off, 1, 2 public var amountThrows: Int = 1 public override init(id: String) { super.init(id: id) } public override init() { super.init() } public override init(layer: AnyObject) { super.init(layer: layer) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func addSwitchEventAtX(x: CGFloat, withValue value: Int, andStemDirection stemDirection: StemDirection ) { let switchEvent = GraphEventSwitch(x: x, value: value, stemDirection: stemDirection) events.append(switchEvent) } public override func build() { commitLines() setFrame() let shape = CAShapeLayer() let path = UIBezierPath() for (e, event) in (events as! [GraphEventSwitch]).enumerate() { let newY: CGFloat = height - height * CGFloat(event.value) // later height * amountThrows / value if e == 0 { path.moveToPoint(CGPointMake(event.x, newY)) } else { let lastEvent = events[e-1] as! GraphEventSwitch let oldY: CGFloat = height - height * CGFloat(lastEvent.value) path.addLineToPoint(CGPointMake(event.x, oldY)) path.addLineToPoint(CGPointMake(event.x, newY)) } } // last point at some x, at height // hack x -- make frame.width, but currently that isn't being set nicely! path.addLineToPoint(CGPointMake(250, height)) path.addLineToPoint(CGPointMake((events.first as! GraphEventSwitch).x, height)) path.closePath() //path.closePath() shape.path = path.CGPath shape.fillColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor shape.strokeColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor shape.lineWidth = 2 addSublayer(shape) } }
gpl-2.0
e22a4c344bbc4b96155804a63ad6ca57
33.507937
109
0.620515
4.296443
false
false
false
false
hishida/media-storage-swift
Sample/Source/ViewController.swift
2
2820
// // Copyright (c) 2016 Ricoh Company, Ltd. All Rights Reserved. // See LICENSE for more information // import UIKit import RicohAPIMStorage import RicohAPIAuth class ViewController: UIViewController { var authClient = AuthClient( clientId: "### enter your client ID ###", clientSecret: "### enter your client secret ###" ) var mstorage: MediaStorage? @IBAction func tapHandler(sender: AnyObject) { authClient.setResourceOwnerCreds( userId: "### enter your user id ###", userPass: "### enter your user password ###" ) mstorage = MediaStorage(authClient: authClient) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { self.mstorage!.connect(){result, error in if error.isEmpty() { dispatch_async(dispatch_get_main_queue(), { self.resultTextField.text = "connect!" }) } else { dispatch_async(dispatch_get_main_queue(), { self.resultTextField.text = "ERROR: \(error)" }) } } }) } @IBOutlet weak var resultTextField: UITextField! @IBAction func getMediaIdButtonHandler(sender: AnyObject) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { if self.mstorage == nil { print("ERROR: push connect button.") return } self.mstorage!.list(){result, error in if error.isEmpty() { var idArray = [String]() let mediaList: Array = result.mediaList for media in mediaList { idArray.append(media.id) } dispatch_async(dispatch_get_main_queue(), { self.mediaIdListTextView.text = idArray.joinWithSeparator("\n") self.getMediaIdListResultTextField.text = "finished" }) } else { dispatch_async(dispatch_get_main_queue(), { self.getMediaIdListResultTextField.text = "ERROR: \(error)" }) } } }) } @IBOutlet weak var mediaIdListTextView: UITextView! @IBOutlet weak var getMediaIdListResultTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
578839d9cd307fe09bb9a13e09b2f7e3
33.814815
87
0.535461
5.053763
false
false
false
false
mikekavouras/Glowb-iOS
Glowb/Wizard/ViewControllers/ConnectingProgressViewController.swift
1
5564
// // ConnectingProgressViewController.swift // ParticleConnect // // Created by Michael Kavouras on 9/5/16. // Copyright © 2016 Mike Kavouras. All rights reserved. // import UIKit extension Notification.Name { static let ReachabilityChanged = Notification.Name("kNetworkReachabilityChangedNotification") } enum ProgressState { case configureCredentials case connectToWifi case waitForCloudConnection case checkInternetConnectivity case verifyDeviceOwnership case last } class ConnectingProgressViewController: BaseViewController { var network: Network! var deviceId: String! fileprivate var state: ProgressState = .configureCredentials fileprivate var communicationManager: DeviceCommunicationManager? = DeviceCommunicationManager() fileprivate var needsToClaimDevice = false fileprivate var isAPIReachable = false fileprivate var isHostReachable = false fileprivate var hostReachability = Reachability(hostName: "https://api.particle.io") // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() state = .configureCredentials NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(notification:)), name: Notification.Name.ReachabilityChanged, object: nil) hostReachability?.startNotifier() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationItem.hidesBackButton = true let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge) view.addSubview(activityIndicator) activityIndicator.startAnimating() activityIndicator.snp.makeConstraints { $0.center.equalToSuperview() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) configureDeviceNetworkCredentials { self.connectDeviceToNetwork { self.waitForCloudConnection { self.checkForInternetConnectivity() } } } } // MARK: Connecting private func configureDeviceNetworkCredentials(completion: @escaping () -> Void) { communicationManager = DeviceCommunicationManager() communicationManager?.configureAP(network: network) { [unowned self] result in self.communicationManager = nil completion() } } private func connectDeviceToNetwork(completion: @escaping () -> Void) { communicationManager = DeviceCommunicationManager() communicationManager?.connectAP { [unowned self] result in self.communicationManager = nil var retries = 0 func connect() { if Wifi.isDeviceConnected(.photon) == true && retries < 10 { DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { retries += 1 connect() } } else { // TODO: Handle error case (never connected) completion() } } connect() } } private func waitForCloudConnection(completion: @escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { completion() } } private func checkForInternetConnectivity() { var retries = 0 func connect() { if !isHostReachable && retries < 5 { DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { retries += 1 connect() } } else { if isHostReachable { displayNameInputUI() { name in let userInfo: [AnyHashable: Any] = [ "device_id" : self.deviceId, "device_name" : name ] NotificationCenter.default.post(name: .particleDeviceConnected, object: nil, userInfo: userInfo) } } else { print("failed") } } } connect() } // MARK: - @objc private func reachabilityChanged(notification: NSNotification) { guard let reachability = notification.object as? Reachability else { return } let status = reachability.currentReachabilityStatus() isHostReachable = status.rawValue == 1 || status.rawValue == 2 } // MARK: - private func displayNameInputUI(completion: @escaping (String) -> Void) { let alertController = UIAlertController(title: "Connected!", message: "Name your device", preferredStyle: .alert) let nameTextField = { (textField: UITextField) -> Void in textField.placeholder = "Name (e.g. living room)" } let submitAction = UIAlertAction(title: "Finish", style: .default) { action in if let textFields = alertController.textFields, let nameField = textFields.last, let name = nameField.text { completion(name) } } alertController.addTextField(configurationHandler: nameTextField) alertController.addAction(submitAction) present(alertController, animated: true, completion: nil) } }
mit
ec6f1366c8b6fe0853898e80f06f2e5a
31.723529
167
0.592666
5.729145
false
false
false
false
diwip/inspector-ios
Inspector/ViewControllers/Properties/PropertiesViewModel.swift
1
2113
// // PropertiesViewModel.swift // Inspector // // Created by Kevin Hury on 11/2/15. // Copyright © 2015 diwip. All rights reserved. // import Foundation import RxSwift import RxCocoa class PropertiesViewModel { var disposeBag = DisposeBag() var properties = Variable<[TNodeProperty]>([]) init() { NSNotificationCenter.defaultCenter() .rx_notification("ConnectionLost", object: nil) .subscribeCompleted { self.properties.value = [] } .addDisposableTo(disposeBag) } func getValuesForProperty(type: String, value: String) -> [String] { switch type { case "Point", "Size": return [NSPointFromString(value).x.description, NSPointFromString(value).y.description] case "Vector3": return value.componentsSeparatedByString(",") default: return [value] } } func setValueForProperty(property: TNodeProperty, values: [String]) { switch property.propType { case "Point": let x = values.first?.toCGFloat() let y = values.last?.toCGFloat() property.propValue = NSStringFromPoint(NSPoint(x: x!, y: y!)) case "Size": let width = values.first?.toCGFloat() let height = values.last?.toCGFloat() property.propValue = NSStringFromSize(NSSize(width: width!, height: height!)) case "Vector3": let red = values.first! let green = values[1] let blue = values.last! property.propValue = red + "," + green + "," + blue default: property.propValue = values.first } } func viewIdentifierForPropertyType(propertyType: String) -> String { switch propertyType { case "Point", "Size", "Vector3": return "Vector3" case "Bool": return "Checkbox" case "Int", "Float", "String": return "Text" case "Action": return "Vector3" default: return "Vector3" } } }
mit
daa056795842a6a8572b868b7a4eaa13
28.760563
99
0.566288
4.641758
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Blog/SharingButtonsViewController.swift
1
35841
import UIKit import CocoaLumberjack import WordPressShared /// Manages which sharing button are displayed, their order, and other settings /// related to sharing. /// @objc class SharingButtonsViewController: UITableViewController { typealias SharingButtonsRowAction = () -> Void typealias SharingButtonsCellConfig = (UITableViewCell) -> Void let buttonSectionIndex = 0 let moreSectionIndex = 1 let blog: Blog private var buttons = [SharingButton]() private var sections = [SharingButtonsSection]() private var buttonsSection: SharingButtonsSection { return sections[buttonSectionIndex] } private var moreSection: SharingButtonsSection { return sections[moreSectionIndex] } private var twitterSection: SharingButtonsSection { return sections.last! } private var didMakeChanges: Bool = false let buttonStyles = [ "icon-text": NSLocalizedString("Icon & Text", comment: "Title of a button style"), "icon": NSLocalizedString("Icon Only", comment: "Title of a button style"), "text": NSLocalizedString("Text Only", comment: "Title of a button style"), "official": NSLocalizedString("Official Buttons", comment: "Title of a button style") ] let buttonStyleTitle = NSLocalizedString("Button Style", comment: "Title for a list of different button styles.") let labelTitle = NSLocalizedString("Label", comment: "Noun. Title for the setting to edit the sharing label text.") let twitterUsernameTitle = NSLocalizedString("Twitter Username", comment: "Title for the setting to edit the twitter username used when sharing to twitter.") let twitterServiceID = "twitter" /// Core Data Context /// var viewContext: NSManagedObjectContext { ContextManager.sharedInstance().mainContext } struct SharingCellIdentifiers { static let SettingsCellIdentifier = "SettingsTableViewCellIdentifier" static let SortableSwitchCellIdentifier = "SortableSwitchTableViewCellIdentifier" static let SwitchCellIdentifier = "SwitchTableViewCellIdentifier" } // MARK: - LifeCycle Methods @objc init(blog: Blog) { self.blog = blog super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("Manage", comment: "Verb. Title of the screen for managing sharing buttons and settings related to sharing.") let service = SharingService(managedObjectContext: viewContext) buttons = service.allSharingButtonsForBlog(self.blog) configureTableView() setupSections() syncSharingButtons() syncSharingSettings() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if didMakeChanges { self.saveButtonChanges(true) } } // MARK: - Sections Setup and Config /// Configures the table view. The table view is set to edit mode to allow /// rows in the buttons and more sections to be reordered. /// private func configureTableView() { tableView.register(SettingTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SettingsCellIdentifier) tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SortableSwitchCellIdentifier) tableView.register(SwitchTableViewCell.self, forCellReuseIdentifier: SharingCellIdentifiers.SwitchCellIdentifier) WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.setEditing(true, animated: false) tableView.allowsSelectionDuringEditing = true } /// Sets up the sections for the table view and configures their starting state. /// private func setupSections() { sections.append(setupButtonSection()) // buttons section should be section idx 0 sections.append(setupMoreSection()) // more section should be section idx 1 sections.append(setupShareLabelSection()) sections.append(setupButtonStyleSection()) if blog.isHostedAtWPcom { sections.append(setupReblogAndLikeSection()) sections.append(setupCommentLikeSection()) } sections.append(setupTwitterNameSection()) configureTwitterNameSection() configureButtonRows() configureMoreRows() } /// Sets up the buttons section. This section is sortable. /// private func setupButtonSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.canSort = true section.headerText = NSLocalizedString("Sharing Buttons", comment: "Title of a list of buttons used for sharing content to other services.") return section } /// Sets up the more section. This section is sortable. /// private func setupMoreSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.canSort = true section.headerText = NSLocalizedString("\"More\" Button", comment: "Title of a list of buttons used for sharing content to other services. These buttons appear when the user taps a `More` button.") section.footerText = NSLocalizedString("A \"more\" button contains a dropdown which displays sharing buttons", comment: "A short description of what the 'More' button is and how it works.") return section } /// Sets up the label section. /// private func setupShareLabelSection() -> SharingButtonsSection { let section = SharingButtonsSection() let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditLabel() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .disclosureIndicator cell.textLabel?.text = self.labelTitle cell.detailTextLabel!.text = self.blog.settings!.sharingLabel } section.rows = [row] return section } /// Sets up the button style section /// private func setupButtonStyleSection() -> SharingButtonsSection { let section = SharingButtonsSection() let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditButtonStyle() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .disclosureIndicator cell.textLabel?.text = self.buttonStyleTitle cell.detailTextLabel!.text = self.buttonStyles[self.blog.settings!.sharingButtonStyle] } section.rows = [row] return section } /// Sets up the reblog and the likes section /// private func setupReblogAndLikeSection() -> SharingButtonsSection { var rows = [SharingButtonsRow]() let section = SharingButtonsSection() section.headerText = NSLocalizedString("Reblog & Like", comment: "Title for a list of ssettings for editing a blog's Reblog and Like settings.") // Reblog button row var row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Show Reblog button", comment: "Title for the `show reblog button` setting") switchCell.on = !self.blog.settings!.sharingDisabledReblogs switchCell.onChange = { newValue in self.blog.settings!.sharingDisabledReblogs = !newValue self.didMakeChanges = true self.saveBlogSettingsChanges(false) let properties = [ "checked": NSNumber(value: newValue) ] WPAppAnalytics.track(.sharingButtonShowReblogChanged, withProperties: properties, with: self.blog) } } } rows.append(row) // Like button row row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Show Like button", comment: "Title for the `show like button` setting") switchCell.on = !self.blog.settings!.sharingDisabledLikes switchCell.onChange = { newValue in self.blog.settings!.sharingDisabledLikes = !newValue self.didMakeChanges = true self.saveBlogSettingsChanges(false) } } } rows.append(row) section.rows = rows return section } /// Sets up the section for comment likes /// private func setupCommentLikeSection() -> SharingButtonsSection { let section = SharingButtonsSection() section.footerText = NSLocalizedString("Allow all comments to be Liked by you and your readers", comment: "A short description of the comment like sharing setting.") let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType if let switchCell = cell as? SwitchTableViewCell { switchCell.textLabel?.text = NSLocalizedString("Comment Likes", comment: "Title for the `comment likes` setting") switchCell.on = self.blog.settings!.sharingCommentLikesEnabled switchCell.onChange = { newValue in self.blog.settings!.sharingCommentLikesEnabled = newValue self.didMakeChanges = true self.saveBlogSettingsChanges(false) } } } section.rows = [row] return section } /// Sets up the twitter names section. The contents of the section are displayed /// or not displayed depending on if the Twitter button is enabled. /// private func setupTwitterNameSection() -> SharingButtonsSection { return SharingButtonsSection() } /// Configures the twiter name section. When the twitter button is disabled, /// the section header is empty, and there are no rows. When the twitter button /// is enabled. the section header and the row is shown. /// private func configureTwitterNameSection() { if !shouldShowTwitterSection() { twitterSection.footerText = " " twitterSection.rows.removeAll() return } twitterSection.footerText = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment: "A description of the twitter sharing setting.") let row = SharingSettingRow() row.action = { [unowned self] in self.handleEditTwitterName() } row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.editingAccessoryType = .disclosureIndicator cell.textLabel?.text = self.twitterUsernameTitle var name = self.blog.settings!.sharingTwitterName if name.count > 0 { name = "@\(name)" } cell.detailTextLabel?.text = name } twitterSection.rows = [row] } /// Creates a sortable row for the specified button. /// /// - Parameter button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// private func sortableRowForButton(_ button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in cell.imageView?.image = self.iconForSharingButton(button) cell.imageView?.tintColor = .listIcon cell.editingAccessoryView = nil cell.editingAccessoryType = .none cell.textLabel?.text = button.name } return row } /// Creates a switch row for the specified button in the sharing buttons section. /// /// - Parameter button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// private func switchRowForButtonSectionButton(_ button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { self.configureSortableSwitchCellAppearance(switchCell, button: button) switchCell.on = button.enabled && button.visible switchCell.onChange = { newValue in button.enabled = newValue if button.enabled { button.visibility = button.enabled ? SharingButton.visible : nil } self.didMakeChanges = true self.refreshMoreSection() } } } return row } /// Creates a switch row for the specified button in the more buttons section. /// /// - Parameter button: The sharing button that the row will represent. /// /// - Returns: A SortableSharingSwitchRow. /// private func switchRowForMoreSectionButton(_ button: SharingButton) -> SortableSharingSwitchRow { let row = SortableSharingSwitchRow(buttonID: button.buttonID) row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { self.configureSortableSwitchCellAppearance(switchCell, button: button) switchCell.on = button.enabled && !button.visible switchCell.onChange = { newValue in button.enabled = newValue if button.enabled { button.visibility = button.enabled ? SharingButton.hidden : nil } self.didMakeChanges = true self.refreshButtonsSection() } } } return row } /// Configures common appearance properties for the button switch cells. /// /// - Parameters: /// - cell: The SwitchTableViewCell cell to configure /// - button: The sharing button that the row will represent. /// private func configureSortableSwitchCellAppearance(_ cell: SwitchTableViewCell, button: SharingButton) { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType cell.imageView?.image = self.iconForSharingButton(button) cell.imageView?.tintColor = .listIcon cell.textLabel?.text = button.name } /// Configures the rows for the button section. When the section is editing, /// all buttons are shown with switch cells. When the section is not editing, /// only enabled and visible buttons are shown and the rows are sortable. /// private func configureButtonRows() { var rows = [SharingButtonsRow]() let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType switchCell.textLabel?.text = NSLocalizedString("Edit sharing buttons", comment: "Title for the edit sharing buttons section") switchCell.on = self.buttonsSection.editing switchCell.onChange = { newValue in self.buttonsSection.editing = !self.buttonsSection.editing self.updateButtonOrderAfterEditing() self.reloadButtons() } } } rows.append(row) if !buttonsSection.editing { let buttonsToShow = buttons.filter { (button) -> Bool in return button.enabled && button.visible } for button in buttonsToShow { rows.append(sortableRowForButton(button)) } } else { for button in buttons { rows.append(switchRowForButtonSectionButton(button)) } } buttonsSection.rows = rows } /// Configures the rows for the more section. When the section is editing, /// all buttons are shown with switch cells. When the section is not editing, /// only enabled and hidden buttons are shown and the rows are sortable. /// private func configureMoreRows() { var rows = [SharingButtonsRow]() let row = SharingSwitchRow() row.configureCell = {[unowned self] (cell: UITableViewCell) in if let switchCell = cell as? SwitchTableViewCell { cell.editingAccessoryView = cell.accessoryView cell.editingAccessoryType = cell.accessoryType switchCell.textLabel?.text = NSLocalizedString("Edit \"More\" button", comment: "Title for the edit more button section") switchCell.on = self.moreSection.editing switchCell.onChange = { newValue in self.updateButtonOrderAfterEditing() self.moreSection.editing = !self.moreSection.editing self.reloadButtons() } } } rows.append(row) if !moreSection.editing { let buttonsToShow = buttons.filter { (button) -> Bool in return button.enabled && !button.visible } for button in buttonsToShow { rows.append(sortableRowForButton(button)) } } else { for button in buttons { rows.append(switchRowForMoreSectionButton(button)) } } moreSection.rows = rows } /// Refreshes the rows for but button section (also the twitter section if /// needed) and reloads the section. /// private func refreshButtonsSection() { configureButtonRows() configureTwitterNameSection() let indexes: IndexSet = [buttonSectionIndex, sections.count - 1] tableView.reloadSections(indexes, with: .automatic) } /// Refreshes the rows for but more section (also the twitter section if /// needed) and reloads the section. /// private func refreshMoreSection() { configureMoreRows() configureTwitterNameSection() let indexes: IndexSet = [moreSectionIndex, sections.count - 1] tableView.reloadSections(indexes, with: .automatic) } /// Provides the icon that represents the sharing button's service. /// /// - Parameter button: The sharing button for the icon. /// /// - Returns: The UIImage for the icon /// private func iconForSharingButton(_ button: SharingButton) -> UIImage { return WPStyleGuide.iconForService(button.buttonID as NSString) } // MARK: - Instance Methods /// Whether the twitter section should be present or not. /// /// - Returns: true if the twitter section should be shown. False otherwise. /// private func shouldShowTwitterSection() -> Bool { for button in buttons { if button.buttonID == twitterServiceID { return button.enabled } } return false } /// Saves changes to blog settings back to the blog and optionally refreshes /// the tableview. /// /// - Parameter refresh: True if the tableview should be reloaded. /// private func saveBlogSettingsChanges(_ refresh: Bool) { if refresh { tableView.reloadData() } let context = ContextManager.sharedInstance().mainContext let service = BlogService(managedObjectContext: context) let dotComID = blog.dotComID service.updateSettings( for: self.blog, success: { WPAppAnalytics.track(.sharingButtonSettingsChanged, withBlogID: dotComID) }, failure: { [weak self] (error: Error) in let error = error as NSError DDLogError(error.description) self?.showErrorSyncingMessage(error) }) } /// Syncs sharing buttons from the user's blog and reloads the button sections /// when finished. Fails silently if there is an error. /// private func syncSharingButtons() { let service = SharingService(managedObjectContext: viewContext) service.syncSharingButtonsForBlog(self.blog, success: { [weak self] in self?.reloadButtons() }, failure: { (error: NSError?) in DDLogError((error?.description)!) }) } /// Sync sharing settings from the user's blog and reloads the setting sections /// when finished. Fails silently if there is an error. /// private func syncSharingSettings() { let service = BlogService(managedObjectContext: viewContext) service.syncSettings(for: blog, success: { [weak self] in self?.reloadSettingsSections() }, failure: { (error: Error) in let error = error as NSError DDLogError(error.description) }) } /// Reloads the sections for different button settings. /// private func reloadSettingsSections() { let settingsSections = NSMutableIndexSet() for i in 0..<sections.count { if i <= buttonSectionIndex { continue } settingsSections.add(i) } tableView.reloadSections(settingsSections as IndexSet, with: .automatic) } // MARK: - Update And Save Buttons /// Updates rows after editing. /// private func updateButtonOrderAfterEditing() { let buttonsForButtonSection = buttons.filter { (btn) -> Bool in return btn.enabled && btn.visible } let buttonsForMoreSection = buttons.filter { (btn) -> Bool in return btn.enabled && !btn.visible } let remainingButtons = buttons.filter { (btn) -> Bool in return !btn.enabled } var order = 0 for button in buttonsForButtonSection { button.order = NSNumber(value: order) order += 1 } for button in buttonsForMoreSection { button.order = NSNumber(value: order) order += 1 } for button in remainingButtons { // we'll update the order for the remaining buttons but this is not // respected by the REST API and changes after syncing. button.order = NSNumber(value: order) order += 1 } } /// Saves changes to sharing buttons to core data, reloads the buttons, then /// pushes the changes up to the blog, optionally refreshing when done. /// /// - Parameter refreshAfterSync: If true buttons are reloaded when the sync completes. /// private func saveButtonChanges(_ refreshAfterSync: Bool) { let context = ContextManager.sharedInstance().mainContext ContextManager.sharedInstance().save(context) { [weak self] in self?.reloadButtons() self?.syncButtonChangesToBlog(refreshAfterSync) } } /// Retrives a fresh copy of the SharingButtons from core data, updating the /// `buttons` property and refreshes the button section and the more section. /// private func reloadButtons() { let service = SharingService(managedObjectContext: viewContext) buttons = service.allSharingButtonsForBlog(blog) refreshButtonsSection() refreshMoreSection() } /// Saves changes to the sharing buttons back to the blog. /// /// - Parameter refresh: True if the tableview sections should be reloaded. /// private func syncButtonChangesToBlog(_ refresh: Bool) { let service = SharingService(managedObjectContext: viewContext) service.updateSharingButtonsForBlog(blog, sharingButtons: buttons, success: {[weak self] in if refresh { self?.reloadButtons() } }, failure: { [weak self] (error: NSError?) in DDLogError((error?.description)!) self?.showErrorSyncingMessage(error) }) } /// Shows an alert. The localized description of the specified NSError is /// included in the alert. /// /// - Parameter error: An NSError object. /// private func showErrorSyncingMessage(_ error: NSError?) { let title = NSLocalizedString("Could Not Save Changes", comment: "Title of an prompt letting the user know there was a problem saving.") var message = NSLocalizedString("There was a problem saving changes to sharing management.", comment: "A short error message shown in a prompt.") if let error = error { message.append(error.localizedDescription) } let controller = UIAlertController(title: title, message: message, preferredStyle: .alert) controller.addCancelActionWithTitle(NSLocalizedString("OK", comment: "A button title."), handler: nil) controller.presentFromRootViewController() } // MARK: - Actions /// Called when the user taps the label row. Shows a controller to change the /// edit label text. /// private func handleEditLabel() { let text = blog.settings!.sharingLabel let placeholder = NSLocalizedString("Type a label", comment: "A placeholder for the sharing label.") let hint = NSLocalizedString("Change the text of the sharing buttons' label. This text won't appear until you add at least one sharing button.", comment: "Instructions for editing the sharing label.") let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint) controller.title = labelTitle controller.onValueChanged = {[unowned self] (value) in guard value != self.blog.settings!.sharingLabel else { return } self.blog.settings!.sharingLabel = value self.saveBlogSettingsChanges(true) } navigationController?.pushViewController(controller, animated: true) } /// Called when the user taps the button style row. Shows a controller to /// choose from available button styles. /// private func handleEditButtonStyle() { var titles = [String]() var values = [String]() _ = buttonStyles.map({ (k: String, v: String) in titles.append(v) values.append(k) }) let currentValue = blog.settings!.sharingButtonStyle let dict: [String: AnyObject] = [ SettingsSelectionDefaultValueKey: values[0] as AnyObject, SettingsSelectionTitleKey: buttonStyleTitle as AnyObject, SettingsSelectionTitlesKey: titles as AnyObject, SettingsSelectionValuesKey: values as AnyObject, SettingsSelectionCurrentValueKey: currentValue as AnyObject ] let controller = SettingsSelectionViewController(dictionary: dict) controller?.onItemSelected = { [unowned self] (selected) in if let str = selected as? String { if self.blog.settings!.sharingButtonStyle == str { return } self.blog.settings!.sharingButtonStyle = str self.saveBlogSettingsChanges(true) } } navigationController?.pushViewController(controller!, animated: true) } /// Called when the user taps the twitter name row. Shows a controller to change /// the twitter name text. /// private func handleEditTwitterName() { let text = blog.settings!.sharingTwitterName let placeholder = NSLocalizedString("Username", comment: "A placeholder for the twitter username") let hint = NSLocalizedString("This will be included in tweets when people share using the Twitter button.", comment: "Information about the twitter sharing feature.") let controller = SettingsTextViewController(text: text, placeholder: placeholder, hint: hint) controller.title = twitterUsernameTitle controller.onValueChanged = {[unowned self] (value) in if value == self.blog.settings!.sharingTwitterName { return } // Remove the @ sign if it was entered. var str = NSString(string: value) str = str.replacingOccurrences(of: "@", with: "") as NSString self.blog.settings!.sharingTwitterName = str as String self.saveBlogSettingsChanges(true) } navigationController?.pushViewController(controller, animated: true) } /// Represents a section in the sharinging management table view. /// class SharingButtonsSection { var rows: [SharingButtonsRow] = [SharingButtonsRow]() var headerText: String? var footerText: String? var editing = false var canSort = false } /// Represents a row in the sharing management table view. /// class SharingButtonsRow { var cellIdentifier = "" var action: SharingButtonsRowAction? var configureCell: SharingButtonsCellConfig? } /// A sortable switch row. By convention this is only used for sortable button rows /// class SortableSharingSwitchRow: SharingButtonsRow { var buttonID: String init(buttonID: String) { self.buttonID = buttonID super.init() cellIdentifier = SharingCellIdentifiers.SortableSwitchCellIdentifier } } /// An unsortable switch row. /// class SharingSwitchRow: SharingButtonsRow { override init() { super.init() cellIdentifier = SharingCellIdentifiers.SwitchCellIdentifier } } /// A row for sharing settings that do not need a switch control in its cell. /// class SharingSettingRow: SharingButtonsRow { override init() { super.init() cellIdentifier = SharingCellIdentifiers.SettingsCellIdentifier } } } // MARK: - TableView Delegate Methods extension SharingButtonsViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].rows.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = sections[indexPath.section].rows[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: row.cellIdentifier)! row.configureCell?(cell) return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section].headerText } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { } override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return sections[section].footerText } override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { WPStyleGuide.configureTableViewSectionFooter(view) } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let row = sections[indexPath.section].rows[indexPath.row] if row.cellIdentifier != SharingCellIdentifiers.SettingsCellIdentifier { tableView.deselectRow(at: indexPath, animated: true) } row.action?() } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Since we want to be able to order particular rows, let's only allow editing for those specific rows. // Note: We have to allow editing because UITableView will only give us the ordering accessory while editing is toggled. let section = sections[indexPath.section] return section.canSort && !section.editing && indexPath.row > 0 } override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { let section = sections[indexPath.section] return section.canSort && !section.editing && indexPath.row > 0 } // The table view is in editing mode, but no cells should show the delete button, // only the move icon. override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return .none } override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } // The first row in the section is static containing the on/off toggle. override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath { let row = proposedDestinationIndexPath.row > 0 ? proposedDestinationIndexPath.row : 1 return IndexPath(row: row, section: sourceIndexPath.section) } // Updates the order of the moved button. override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { let sourceSection = sections[sourceIndexPath.section] let diff = destinationIndexPath.row - sourceIndexPath.row let movedRow = sourceSection.rows[sourceIndexPath.row] as! SortableSharingSwitchRow let movedButton = buttons.filter { (button) -> Bool in return button.buttonID == movedRow.buttonID } let theButton = movedButton.first! let oldIndex = buttons.firstIndex(of: theButton)! let newIndex = oldIndex + diff let buttonsArr = NSMutableArray(array: buttons) buttonsArr.removeObject(at: oldIndex) buttonsArr.insert(theButton, at: newIndex) // Update the order for all buttons for (index, button) in buttonsArr.enumerated() { let sharingButton = button as! SharingButton sharingButton.order = NSNumber(value: index) } self.didMakeChanges = true WPAppAnalytics.track(.sharingButtonOrderChanged, with: blog) } }
gpl-2.0
efd6c0cf5ec4ac23368d231b573db56b
38.256298
208
0.636561
5.356598
false
false
false
false
gradyzhuo/GZImageLayoutView
GZImageLayoutView/GZPositionView.swift
1
7799
// // GZPositionView.swift // Flingy // // Created by Grady Zhuo on 6/17/15. // Copyright (c) 2015 Skytiger Studio. All rights reserved. // import Foundation import UIKit //MARK: - public class GZPositionView: UIView { var position:GZPosition! = GZPosition.fullPosition(){ didSet{ if position == nil { self.layer.mask = nil self.frame = CGRect() } } } public var identifier:String { return self.position.identifier } public var maskBezierPath:UIBezierPath! internal(set) var layoutView:GZImageLayoutView? public init(layoutView:GZImageLayoutView? = nil, position:GZPosition! = nil, frame:CGRect = CGRect()){ super.init(frame:frame) self.layoutView = layoutView self.configure(position) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configure(nil) } internal func configure(position:GZPosition!){ self.position = position } internal func applyMask(size:CGSize){ let maskLayer = CAShapeLayer() if let position = self.position{ self.maskBezierPath = UIBezierPath() self.maskBezierPath.appendPath(position.maskBezierPath) self.maskBezierPath.applyTransform(CGAffineTransformMakeScale(size.width, size.height)) maskLayer.path = self.maskBezierPath.CGPath } self.layer.mask = maskLayer //決定position的位置 let bezierPath = UIBezierPath() bezierPath.appendPath(self.position.bezierPath) bezierPath.applyTransform(CGAffineTransformMakeScale(size.width, size.height)) self.frame = bezierPath.bounds self.layoutIfNeeded() } override public func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if let maskLayer = self.layer.mask as? CAShapeLayer { let borderBeizerPath = UIBezierPath(CGPath: maskLayer.path!) return borderBeizerPath.containsPoint(point) } return false } } //MARK: - GZHighlightView public class GZHighlightView: GZPositionView { private var componentConstraints:[String:[NSLayoutConstraint]] = [:] private lazy var borderView:GZHighlightBorderView = { var borderView = GZHighlightBorderView() borderView.translatesAutoresizingMaskIntoConstraints = false return borderView }() internal lazy var cameraView:GZCameraView = { var cameraView = GZCameraView() cameraView.userInteractionEnabled = false cameraView.translatesAutoresizingMaskIntoConstraints = false return cameraView }() public var borderColor:UIColor{ set{ self.borderView.borderColor = newValue } get{ return self.borderView.borderColor } } public var borderWidth:CGFloat { set{ self.borderView.borderWidth = newValue } get{ return self.borderView.borderWidth } } override func configure(position: GZPosition!) { super.configure(position) self.layoutMargins = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.userInteractionEnabled = false self.addSubview(self.cameraView) self.addSubview(self.borderView) self.setNeedsUpdateConstraints() } override func applyMask(size: CGSize) { super.applyMask(size) // self.borderView.bezierPath = self.maskBezierPath self.setNeedsLayout() } override public func updateConstraints() { super.updateConstraints() self.removeConstraints(self.componentConstraints["CameraView"] ?? []) self.removeConstraints(self.componentConstraints["BorderView"] ?? []) var constraints = [NSLayoutConstraint]() var metrics:[String:AnyObject] = [:] metrics["super_margin_left"] = self.layoutMargins.left metrics["super_margin_right"] = self.layoutMargins.right metrics["super_margin_top"] = self.layoutMargins.top metrics["super_margin_bottom"] = self.layoutMargins.bottom let viewsDict:[String:AnyObject] = ["camera_view":self.cameraView, "border_view":self.borderView] let vCameraViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-super_margin_top-[camera_view]-super_margin_bottom-|", options: NSLayoutFormatOptions(), metrics: metrics, views: viewsDict) let hCameraViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-super_margin_left-[camera_view]-super_margin_right-|", options: NSLayoutFormatOptions(), metrics: metrics, views: viewsDict) let cameraConstraints = [] + vCameraViewConstraints + hCameraViewConstraints self.componentConstraints["CameraView"] = cameraConstraints constraints += cameraConstraints let vBorderViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-super_margin_top-[border_view]-super_margin_bottom-|", options: NSLayoutFormatOptions(), metrics: metrics, views: viewsDict) let hBorderViewConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-super_margin_left-[border_view]-super_margin_right-|", options: NSLayoutFormatOptions(), metrics: metrics, views: viewsDict) let borderConstraints = [] + vBorderViewConstraints + hBorderViewConstraints self.componentConstraints["BorderView"] = borderConstraints constraints += borderConstraints self.addConstraints(constraints) } } /** 主要呈現出外框用 */ public class GZHighlightBorderView: UIView { public var borderWidth:CGFloat = 2.0{ didSet{ self.setNeedsDisplay() } } public var borderColor:UIColor = UIColor.blackColor(){ didSet{ self.setNeedsDisplay() } } public var layout:GZLayout = GZLayout.fullLayout() public init() { super.init(frame : CGRect.zero) self.setup() } public override init(frame: CGRect) { super.init(frame: frame) self.setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override public func layoutSubviews() { super.layoutSubviews() self.setNeedsDisplay() } private func setup(){ self.backgroundColor = UIColor.clearColor() self.userInteractionEnabled = false } override public func drawRect(rect: CGRect) { let halfBorderWidth = self.borderWidth * 0.5 let borderBeizerPath = self.layout.unitBorderBezierPath() borderBeizerPath.lineWidth = self.borderWidth var transform = CGAffineTransformMakeTranslation(halfBorderWidth, halfBorderWidth) transform = CGAffineTransformScale(transform, self.bounds.width-self.borderWidth, self.bounds.height-self.borderWidth) borderBeizerPath.applyTransform(transform) self.borderColor.setStroke() borderBeizerPath.stroke() } }
apache-2.0
7383fd54e32e52d8061466d2d3884e7b
27.472527
213
0.608774
5.447092
false
false
false
false
scherersoftware/SSHolidays
SSHolidays/HolidayMapsDE.swift
1
5988
// // HolidayMapsDE.swift // SSHolidays // // Created by Ralf Peters on 26/07/16. // Copyright © 2016 scherer software. All rights reserved. // import UIKit // MARK: Constants struct GermanHolidayConstants { // MARK: all german holiday names struct kGermanHolidayNames { static let kNewYear = "Neujahr" static let kLaborDay = "Tag der deutschen Arbeit" static let kDayOfGermanUnity = "Tag der deutschen Einheit" static let kFirstChristmasDay = "1. Weihnachtstag" static let kSecondChristmasDay = "2. Weihnachtstag" static let kEpiphany = "Heilige Drei Könige" static let kReformationDay = "Reformationstag" static let kAllHallows = "Allerheiligen" } } struct GermanStatesConstants { // MARK: all german States struct kStates { static let kStateBW = "Baden-Württemberg" static let kStateBY = "Bayern" static let kStateBE = "Berlin" static let kStateBB = "Brandenburg" static let kStateHB = "Freie Hansestadt Bremen" static let kStateHH = "Hamburg" static let kStateHE = "Hessen" static let kStateMV = "Mecklenburg-Vorpommern" static let kStateNI = "Niedersachsen" static let kStateNW = "Nordrhein-Westfalen" static let kStateRP = "Reinland-Pfalz" static let kStateSL = "Saarland" static let kStateSN = "Sachsen" static let kStateST = "Sachsen-Anhalt" static let kStateSH = "Schleswig-Holstein" static let kStateTH = "Thüringen" } } class HolidayMapsDE: NSObject { static func getDEHolidays(year year: Int) -> Array<Holiday> { var holidays = Array<Holiday>() // MARK: Fixed with State let newYear = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kNewYear, year: year, month: 1, day: 1, fixedWithStates: false, states: []) holidays.append(newYear) let laborDay = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kLaborDay, year: year, month: 5, day: 1, fixedWithStates: false, states: []) holidays.append(laborDay) let unityDay = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kDayOfGermanUnity, year: year, month: 10, day: 3, fixedWithStates: false, states: []) holidays.append(unityDay) let firstChristmasDay = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kFirstChristmasDay, year: year, month: 12, day: 25, fixedWithStates: false, states: []) holidays.append(firstChristmasDay) let secondChristmasDay = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kSecondChristmasDay, year: year, month: 12, day: 26, fixedWithStates: false, states: []) holidays.append(secondChristmasDay) // MARK: Variable with State let epiphany = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kEpiphany, year: year, month: 1, day: 6, fixedWithStates: true, states: [ GermanStatesConstants.kStates.kStateBW, GermanStatesConstants.kStates.kStateBY, GermanStatesConstants.kStates.kStateST ]) holidays.append(epiphany) let reformation = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kReformationDay, year: year, month: 10, day: 31, fixedWithStates: true, states: [ GermanStatesConstants.kStates.kStateBB, GermanStatesConstants.kStates.kStateMV, GermanStatesConstants.kStates.kStateSN, GermanStatesConstants.kStates.kStateST, GermanStatesConstants.kStates.kStateTH ]) holidays.append(reformation) let allHallows = Holiday(name: GermanHolidayConstants.kGermanHolidayNames.kAllHallows, year: year, month: 11, day: 1, fixedWithStates: true, states: [ GermanStatesConstants.kStates.kStateBW, GermanStatesConstants.kStates.kStateBY, GermanStatesConstants.kStates.kStateNW, GermanStatesConstants.kStates.kStateRP, GermanStatesConstants.kStates.kStateSL ]) holidays.append(allHallows) return holidays; } }
mit
e354aaf33a3a34dfb3d71de3f8e43635
38.893333
110
0.473095
5.140893
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/Open.swift
1
1476
// // Open.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML Open /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="open" type="boolean" default="0"/> public class Open:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue { public static var elementName: String = "open" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Document: v.value.open = self case let v as Folder: v.value.open = self case let v as Placemark: v.value.open = self case let v as NetworkLink: v.value.open = self case let v as GroundOverlay:v.value.open = self case let v as PhotoOverlay: v.value.open = self case let v as ScreenOverlay:v.value.open = self default: break } } } } public var value: Bool = false // 0 public func makeRelation(contents: String, parent: SPXMLElement) -> SPXMLElement { self.value = contents == "1" self.parent = parent return parent } }
mit
c8f92e22aafc2f7552a0330c7b080ba1
32.785714
86
0.574348
3.91989
false
false
false
false
jedlewison/AsyncOpKit
Tests/AsyncOpTests/AsyncOpResultStatusTests.swift
1
2780
// // AsyncOpResultStatus.swift // AsyncOp // // Created by Jed Lewison on 9/7/15. // Copyright © 2015 Magic App Factory. All rights reserved. // import Foundation import Quick import Nimble @testable import AsyncOpKit class AsyncOpResultStatusTests : QuickSpec { override func spec() { var randomOutputNumber = 0 var subject: AsyncOp<AsyncVoid, Int>? var opQ: NSOperationQueue? describe("Result status") { beforeEach { randomOutputNumber = random() subject = AsyncOp() opQ = NSOperationQueue() } afterEach { subject = nil opQ = nil } context("Operation hasn't finished") { beforeEach { subject?.onStart { op in usleep(200000) op.finish(with: randomOutputNumber) } opQ?.addOperations([subject!], waitUntilFinished: false) } it("the result status should be pending") { expect(subject?.resultStatus).to(equal(AsyncOpResultStatus.Pending)) } } context("Operation has finished with success") { beforeEach { subject?.onStart { op in op.finish(with: randomOutputNumber) } opQ?.addOperations([subject!], waitUntilFinished: true) } it("the result status should be succeeded") { expect(subject?.resultStatus).to(equal(AsyncOpResultStatus.Succeeded)) } } context("Operation has finished because it was cancelled") { beforeEach { subject?.addPreconditionEvaluator { return .Cancel } opQ?.addOperations([subject!], waitUntilFinished: true) } it("the result status should be cancelled") { expect(subject?.resultStatus).to(equal(AsyncOpResultStatus.Cancelled)) } } context("Operation has finished because it failed") { beforeEach { subject?.onStart { op in op.finish(with: AsyncOpError.Unspecified) } opQ?.addOperations([subject!], waitUntilFinished: true) } it("the result status should be failed") { expect(subject?.resultStatus).to(equal(AsyncOpResultStatus.Failed)) } } } } }
mit
878b1713f76457acabbf6d5c47671f95
27.649485
90
0.484707
5.900212
false
false
false
false
swilliams/SoundyBoardy
SoundyBoardy/DropView.swift
1
1515
// // DropView.swift // SoundyBoardy // // Created by Scott Williams on 10/10/15. // Copyright © 2015 swilliams. All rights reserved. // import Cocoa typealias AudioFileDroppedBlock = (draggingInfo: NSDraggingInfo) -> () class DropView: NSView { var filesDropped: AudioFileDroppedBlock? override func awakeFromNib() { super.awakeFromNib() Swift.print("hiya") } override func draggingEntered(sender: NSDraggingInfo) -> NSDragOperation { Swift.print("drag enter") if dragSenderHasValidFile(sender) { return .Copy } return .None } override func draggingEnded(sender: NSDraggingInfo?) { Swift.print("drag end") if let sender = sender where dragSenderHasValidFile(sender) { filesDropped?(draggingInfo: sender) } } private func dragSenderHasValidFile(sender: NSDraggingInfo) -> Bool { if let draggedFilenames = sender.draggingPasteboard().propertyListForType(NSFilenamesPboardType) as? [NSString] { for filename: NSString in draggedFilenames { if allowedExtensions.contains(filename.pathExtension) { return true } } } return false } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) let layer = CALayer() layer.backgroundColor = NSColor.clearColor().CGColor self.wantsLayer = true self.layer = layer } }
mit
86c83e63f2cefe718d6a5dd3f84a5f0c
25.103448
121
0.627477
4.746082
false
false
false
false
JockerLUO/ShiftLibra
ShiftLibra/ShiftLibra/Class/Tools/SLSQLManager.swift
1
4637
// // SLSQLManager.swift // ShiftLibra // // Created by LUO on 2017/8/1. // Copyright © 2017年 JockerLuo. All rights reserved. // import UIKit import FMDB // 数据库名 private let dbName = "currency.db" class SLSQLManager{ // 全局访问点 static let shared: SLSQLManager = SLSQLManager() static let sharedTmp : SLSQLManager = SLSQLManager(istmp: true) // 串行队列 let queue: FMDatabaseQueue // 路径 let path = (NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent(dbName) let tmpPath = Bundle.main.path(forResource: "currency_tmp.db", ofType: nil) ?? "" // 类的构造函数 private init() { queue = FMDatabaseQueue(path: path) createTable() } private init(istmp : Bool ) { queue = FMDatabaseQueue(path: tmpPath) createTable() } // 创建表 private func createTable(){ let file = Bundle.main.path(forResource: "currency.db", ofType: nil)! let sql = try! String(contentsOfFile: file) queue.inDatabase { (db) in if db.executeStatements(sql) == true{ // print("创建表成功") } else { print("创建表失败") } } } } extension SLSQLManager{ func insertToSQL(dataList : [SLCurrency]) -> () { queue.inTransaction({ (db, rollback) in for obj in dataList { let sql = "INSERT INTO T_Currency (name,code) VALUES('\(obj.name!)','\(obj.code!)')" db.executeStatements(sql) } }) } func insertToSQL(sql : String) -> () { queue.inTransaction({ (db, rollback) in db.executeStatements(sql) }) } func orderSQL() -> [String : [SLCurrency]]? { var list : [String: [SLCurrency]] = [String : [SLCurrency]]() let sql = "SELECT * FROM T_Currency ORDER BY code AND query != 'customize';" queue.inDatabase { (db) -> Void in guard let rs = db.executeQuery(sql, withParameterDictionary: nil) else { return } while rs.next() { let obj : SLCurrency = SLCurrency() obj.name = rs.string(forColumn: "name") obj.code = rs.string(forColumn: "code") obj.updatetime = rs.string(forColumn: "updatetime") obj.exchange = rs.double(forColumn: "exchange") obj.query = rs.string(forColumn: "query") obj.name_English = rs.string(forColumn: "name_English") let mainString = obj.code ?? "CNY" let index = mainString.index(mainString.startIndex, offsetBy: 1) let key = String(mainString[..<index]) if list[key] == nil { list[key] = [SLCurrency]() } list[key]?.append(obj) } } return list } func selectSQL(sql : String) -> [SLCurrency] { var list : [SLCurrency] = [SLCurrency]() queue.inDatabase { (db) in guard let rs = db.executeQuery(sql, withParameterDictionary: nil) else { return } while rs.next() { let obj : SLCurrency = SLCurrency() obj.name = rs.string(forColumn: "name") obj.code = rs.string(forColumn: "code") obj.updatetime = rs.string(forColumn: "updatetime") obj.exchange = rs.double(forColumn: "exchange") obj.query = rs.string(forColumn: "query") obj.name_English = rs.string(forColumn: "name_English") list.append(obj) } } return list } func updateSQL(sql : String) -> () { queue.inTransaction { (db, rollback) in db.executeStatements(sql) } } }
mit
7c45b3f33bddbe5eea4e3419e0d49314
25.858824
207
0.470434
4.904404
false
false
false
false
vanjakom/photo-db
photodb view/photodb view/TagsListVC.swift
1
3710
// // TagsListVC.swift // photodb view // // Created by Vanja Komadinovic on 2/3/16. // Copyright © 2016 mungolab.com. All rights reserved. // import UIKit class TagNameCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! } class TagsListVC: UITableViewController { var photoDbClient: PhotoDBClient! = nil var tags: [Tag]? = nil var rootTags: [Tag] = [] override func viewDidLoad() { //self.photoDbClient = SimplePhotoDBClient(serverUri: "10.255.198.81:8988") if (self.photoDbClient == nil) { self.photoDbClient = SimplePhotoDBClient(serverUri: "192.168.88.32:8988") } //self.photoDbClient = SimplePhotoDBClient(serverUri: "127.0.0.1:8988") let viewBarButton = UIBarButtonItem(title: "View", style: .plain, target: self, action: #selector(viewTagsPressed)) self.navigationItem.rightBarButtonItem = viewBarButton } override func viewWillAppear(_ animated: Bool) { if (self.rootTags.count == 0) { self.photoDbClient.listTags { (tagsList: [Tag]?) -> Void in if let tags: [Tag] = tagsList { self.tags = tags self.tableView.reloadData() } } } else { self.navigationItem.title = self.rootTags.last?.name self.photoDbClient.tagView(self.rootTags, callback: { (_, tags: [Tag]?) in if let tags = tags { self.tags = tags self.tableView.reloadData() } else { print("[ERROR] TagsListVC:viewWillAppear unable to retrieve tags") } }) } } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let _: Int = tags?.count { return tags!.count } else { return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: "TagNameCell") as! TagNameCell cell.nameLabel.text = self.tags![(indexPath as NSIndexPath).row].name return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let tagListVC = self.storyboard?.instantiateViewController(withIdentifier: "TagsListVC") as! TagsListVC tagListVC.photoDbClient = self.photoDbClient var newRootTags = self.rootTags newRootTags.append(self.tags![indexPath.row]) tagListVC.rootTags = newRootTags self.navigationController?.pushViewController(tagListVC, animated: false) /* self.present(tagThumbnailViewVC, animated: false) { // empty } */ /* let tagViewVC = self.storyboard?.instantiateViewControllerWithIdentifier("TagViewVC") as! TagViewVC tagViewVC.tag = tags![indexPath.row].name self.presentViewController(tagViewVC, animated: false) { () -> Void in // empty } */ } func viewTagsPressed() -> Void { let tagThumbnailViewVC = self.storyboard?.instantiateViewController(withIdentifier: "TagThumbnailViewVC") as! TagThumbnailViewVC tagThumbnailViewVC.photoDbClient = self.photoDbClient tagThumbnailViewVC.tags = self.rootTags self.navigationController?.pushViewController(tagThumbnailViewVC, animated: false) } }
mit
23cd55bf9d53e52f050022ea3a1f2763
33.990566
136
0.607711
4.556511
false
false
false
false
CorlaOnline/AlamofireRouter
AlamofireRouter/Classes/AlamofireRouter.swift
1
1246
// // Router.swift // // Created by Alex Corlatti on 31/05/16. // Copyright © 2016 CorlaOnline. All rights reserved. // import Alamofire // MARK: - Router struct public struct Router { var baseURL = "" public init(baseURL: String) { self.baseURL = baseURL } public func endPoint(path: String, method: Alamofire.HTTPMethod = .get, parameters: [String : Any] = [ : ], encoding: ParameterEncoding = URLEncoding.default, headers: [[String: String]] = [[ : ]]) -> URLRequest { guard let url = URL(string: baseURL + path) else { return try! URLEncoding.default.encode(URLRequest(url: URL(string: "")!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30), with: nil) } var request = try! encoding.encode(URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30), with: parameters) request.httpMethod = method.rawValue for header in headers { for (field, value) in header { request.addValue(value, forHTTPHeaderField: field) } } return request } } // MARK: - RouterProtocol public protocol RouterProtocol: URLRequestConvertible { var router: Router { get } }
mit
260c5bf6a59f663493d8585833a47082
22.490566
217
0.636948
4.368421
false
false
false
false
prolificinteractive/Kumi-iOS
Kumi/Core/Font/FontTheme.swift
1
10541
// // FontTheme.Swift // Kumi // // Created by Prolific Interactive on 3/14/17. // Copyright © 2017 Prolific Interactive. All rights reserved. // import Marker /// Text styles used throughout the app. public final class FontTheme { /// Tab Bar Badge Text Style. public var tabBarBadgeTextStyle: TextStyleSet! /// Tab Bar Item Inactive Text Style. public var tabBarItemInactiveTextStyle: TextStyleSet! /// Tab Bar Item Text Style. public var tabBarItemTextStyle: TextStyleSet! /// Snackbar Text Text Style. public var snackbarTextTextStyle: TextStyleSet! /// Snackbar Action Button Title Text Style. public var snackbarActionButtonTitleTextStyle: TextStyleSet! /// Segmented Title Text Style. public var segmentedTitleTextStyle: TextStyleSet! /// Menu Text Style. public var menuTextStyle: TextStyleSet! /// Chip Text Style. public var chipTextStyle: TextStyleSet! /// Tooltips Text Style. public var tooltipsTextStyle: TextStyleSet! /// Top Item Subtitle Text Style. public var topItemSubtitleTextStyle: TextStyleSet! /// Top Item Button Title Text Style. public var topItemButtonTitleTextStyle: TextStyleSet! /// Top Item Title Small Text Style. public var topItemTitleSmallTextStyle: TextStyleSet! /// Top Item Title Large Text Style. public var topItemTitleLargeTextStyle: TextStyleSet! /// Top Item Title Normal Text Style. public var topItemTitleNormalTextStyle: TextStyleSet! /// Text Field Hint Small Text Style. public var textFieldHintSmallTextStyle: TextStyleSet! /// Text Field Hint Large Text Style. public var textFieldHintLargeTextStyle: TextStyleSet! /// Text Field Hint Normal Text Style. public var textFieldHintNormalTextStyle: TextStyleSet! /// Text Field Label Small Text Style. public var textFieldLabelSmallTextStyle: TextStyleSet! /// Text Field Label Large Text Style. public var textFieldLabelLargeTextStyle: TextStyleSet! /// Text Field Label Normal Text Style. public var textFieldLabelNormalTextStyle: TextStyleSet! /// Text Field Input Small Text Style. public var textFieldInputSmallTextStyle: TextStyleSet! /// Text Field Input Large Text Style. public var textFieldInputLargeTextStyle: TextStyleSet! /// Text Field Input Normal Text Style. public var textFieldInputNormalTextStyle: TextStyleSet! /// Button Title Small Text Style. public var buttonTitleSmallTextStyle: TextStyleSet! /// Button Title Large Text Style. public var buttonTitleLargeTextStyle: TextStyleSet! /// Button Title Normal Text Style. public var buttonTitleNormalTextStyle: TextStyleSet! /// Button Flat Title Small Text Style. public var buttonFlatTitleSmallTextStyle: TextStyleSet! /// Button Flat Title Large Text Style. public var buttonFlatTitleLargeTextStyle: TextStyleSet! /// Button Flat Title Normal Text Style. public var buttonFlatTitleNormalTextStyle: TextStyleSet! /// Caption Small Text Style. public var captionSmallTextStyle: TextStyleSet! /// Caption Large Text Style. public var captionLargeTextStyle: TextStyleSet! /// Caption Normal Text Style. public var captionNormalTextStyle: TextStyleSet! // /// Body Small Text Style. public var bodySmallTextStyle: TextStyleSet! /// Body Large Text Style. public var bodyLargeTextStyle: TextStyleSet! /// Body Normal Text Style. public var bodyNormalTextStyle: TextStyleSet /// Sub Headline Small Text Style. public var subHeadlineSmallTextStyle: TextStyleSet! /// Sub Headline Large Text Style. public var subHeadlineLargeTextStyle: TextStyleSet! /// Sub Headline Normal Text Style. public var subHeadlineNormalTextStyle: TextStyleSet! /// Headline6 Text Style. public var headline6TextStyle: TextStyleSet! /// Headline5 Text Style. public var headline5TextStyle: TextStyleSet! /// Headline4 Text Style. public var headline4TextStyle: TextStyleSet! /// Headline3 Text Style. public var headline3TextStyle: TextStyleSet! /// Headline2 Text Style. public var headline2TextStyle: TextStyleSet! /// Headline1 Text Style. public var headline1TextStyle: TextStyleSet! /// Display Small Text Style. public var displaySmallTextStyle: TextStyleSet! /// Display Large Text Style. public var displayLargeTextStyle: TextStyleSet! /// Display Normal Text Style. public var displayNormalTextStyle: TextStyleSet! public init?(json: JSON) { let bodyNormalTextStyle = TextStyleSet(json: json["bodyNormal"]) ?? .default self.bodyNormalTextStyle = bodyNormalTextStyle bodySmallTextStyle = TextStyleSet(json: json["bodySmall"], defaultStyle: bodyNormalTextStyle.regular) bodyLargeTextStyle = TextStyleSet(json: json["bodyLarge"], defaultStyle: bodyNormalTextStyle.regular) headline1TextStyle = TextStyleSet(json: json["headline1"], defaultStyle: bodyNormalTextStyle.regular) headline2TextStyle = TextStyleSet(json: json["headline2"], defaultStyle: headline1TextStyle.regular) headline3TextStyle = TextStyleSet(json: json["headline3"], defaultStyle: headline2TextStyle.regular) headline4TextStyle = TextStyleSet(json: json["headline4"], defaultStyle: headline3TextStyle.regular) headline5TextStyle = TextStyleSet(json: json["headline5"], defaultStyle: headline4TextStyle.regular) headline6TextStyle = TextStyleSet(json: json["headline6"], defaultStyle: headline5TextStyle.regular) displayNormalTextStyle = TextStyleSet(json: json["displayNormal"], defaultStyle: headline1TextStyle.regular) displaySmallTextStyle = TextStyleSet(json: json["displaySmall"], defaultStyle: displayNormalTextStyle.regular) displayLargeTextStyle = TextStyleSet(json: json["displayLarge"], defaultStyle: displayNormalTextStyle.regular) captionNormalTextStyle = TextStyleSet(json: json["captionNormal"], defaultStyle: headline1TextStyle.regular) captionSmallTextStyle = TextStyleSet(json: json["captionSmall"], defaultStyle: captionNormalTextStyle.regular) captionLargeTextStyle = TextStyleSet(json: json["captionLarge"], defaultStyle: captionNormalTextStyle.regular) tabBarItemTextStyle = TextStyleSet(json: json["tabBarItem"], defaultStyle: captionNormalTextStyle.regular) tabBarItemInactiveTextStyle = TextStyleSet(json: json["tabBarItemInactive"], defaultStyle: tabBarItemTextStyle.regular) tabBarBadgeTextStyle = TextStyleSet(json: json["tabBarBadge"], defaultStyle: tabBarItemTextStyle.regular) topItemSubtitleTextStyle = TextStyleSet(json: json["topItemSubtitle"], defaultStyle: captionNormalTextStyle.regular) subHeadlineNormalTextStyle = TextStyleSet(json: json["subHeadlineNormal"], defaultStyle: bodyNormalTextStyle.regular) subHeadlineSmallTextStyle = TextStyleSet(json: json["subHeadlineSmall"], defaultStyle: subHeadlineNormalTextStyle.regular) subHeadlineLargeTextStyle = TextStyleSet(json: json["subHeadlineLarge"], defaultStyle: subHeadlineNormalTextStyle.regular) buttonTitleNormalTextStyle = TextStyleSet(json: json["buttonTitleNormal"], defaultStyle: bodyNormalTextStyle.regular) buttonTitleSmallTextStyle = TextStyleSet(json: json["buttonTitleSmall"], defaultStyle: buttonTitleNormalTextStyle.regular) buttonTitleLargeTextStyle = TextStyleSet(json: json["buttonTitleLarge"], defaultStyle: buttonTitleNormalTextStyle.regular) buttonFlatTitleNormalTextStyle = TextStyleSet(json: json["buttonFlatTitleNormal"], defaultStyle: bodyNormalTextStyle.regular) buttonFlatTitleSmallTextStyle = TextStyleSet(json: json["buttonFlatTitleSmall"], defaultStyle: buttonFlatTitleNormalTextStyle.regular) buttonFlatTitleLargeTextStyle = TextStyleSet(json: json["buttonFlatTitleLarge"], defaultStyle: buttonFlatTitleNormalTextStyle.regular) textFieldInputNormalTextStyle = TextStyleSet(json: json["textFieldInputNormal"], defaultStyle: bodyNormalTextStyle.regular) textFieldInputSmallTextStyle = TextStyleSet(json: json["textFieldInputSmall"], defaultStyle: textFieldInputNormalTextStyle.regular) textFieldInputLargeTextStyle = TextStyleSet(json: json["textFieldInputLarge"], defaultStyle: textFieldInputNormalTextStyle.regular) textFieldLabelNormalTextStyle = TextStyleSet(json: json["textFieldLabelNormal"], defaultStyle: textFieldInputNormalTextStyle.regular) textFieldLabelSmallTextStyle = TextStyleSet(json: json["textFieldLabelSmall"], defaultStyle: textFieldLabelNormalTextStyle.regular) textFieldLabelLargeTextStyle = TextStyleSet(json: json["textFieldLabelLarge"], defaultStyle: textFieldLabelNormalTextStyle.regular) textFieldHintNormalTextStyle = TextStyleSet(json: json["textFieldHintNormal"], defaultStyle: textFieldInputNormalTextStyle.regular) textFieldHintSmallTextStyle = TextStyleSet(json: json["textFieldHintSmall"], defaultStyle: textFieldHintNormalTextStyle.regular) textFieldHintLargeTextStyle = TextStyleSet(json: json["textFieldHintLarge"], defaultStyle: textFieldHintNormalTextStyle.regular) topItemTitleNormalTextStyle = TextStyleSet(json: json["topItemTitleNormal"], defaultStyle: bodyNormalTextStyle.regular) topItemTitleSmallTextStyle = TextStyleSet(json: json["topItemTitleSmall"], defaultStyle: topItemTitleNormalTextStyle.regular) topItemTitleLargeTextStyle = TextStyleSet(json: json["topItemTitleLarge"], defaultStyle: topItemTitleNormalTextStyle.regular) topItemButtonTitleTextStyle = TextStyleSet(json: json["topItemButtonTitle"], defaultStyle: topItemTitleNormalTextStyle.regular) tooltipsTextStyle = TextStyleSet(json: json["tooltips"], defaultStyle: bodyNormalTextStyle.regular) chipTextStyle = TextStyleSet(json: json["chip"], defaultStyle: bodyNormalTextStyle.regular) menuTextStyle = TextStyleSet(json: json["menu"], defaultStyle: bodyNormalTextStyle.regular) segmentedTitleTextStyle = TextStyleSet(json: json["segmentedTitle"], defaultStyle: bodyNormalTextStyle.regular) snackbarTextTextStyle = TextStyleSet(json: json["snackbarText"], defaultStyle: bodyNormalTextStyle.regular) snackbarActionButtonTitleTextStyle = TextStyleSet(json: json["snackbarActionButtonTitle"], defaultStyle: bodyNormalTextStyle.regular) } }
mit
dee38a57a881252ba6f0d6d8ed111092
45.637168
142
0.764137
4.916045
false
false
false
false
Somnibyte/MLKit
MLKit-PlayGround.playground/Contents.swift
1
9715
//: Playground - noun: a place where people can play import UIKit import Upsurge import MachineLearningKit /* Already implemented in MachineLearningKit extension Collection { /// Return a copy of `self` with its elements shuffled func shuffle() -> [Iterator.Element] { var list = Array(self) list.shuffle() return list } } extension MutableCollection where Indices.Iterator.Element == Index { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) swap(&self[firstUnshuffled], &self[i]) } } } struct InputDataType { var data: [(input: [Float], target:[Float])] var lengthOfTrainingData: Int { get { return data.count } } } class Layer { var layerSize: (rows: Int, columns: Int)? public var bias: Matrix<Float>? public var weights: Matrix<Float>? public var input: Matrix<Float>? public var zValues: Matrix<Float>? public var activationValues: Matrix<Float>? public var Δw: Matrix<Float>? public var Δb: Matrix<Float>? public var activationFnc: Bool = false init(size: (rows: Int, columns: Int)){ self.layerSize = size self.bias = generateRandomBiases() self.weights = generateRandomWeights() self.Δb = Matrix<Float>([Array<Float>(repeating: 0.0, count: (self.bias?.elements.count)!)]) self.Δw = Matrix<Float>([Array<Float>(repeating: 0.0, count: (self.weights?.elements.count)!)]) } public func fncStep(val: Float) -> Float { return val >= 0 ? 1.0 : 0.0 } func forward(activation:Matrix<Float>) -> Matrix<Float> { var a = activation self.input = activation a = (self.weights! * a) a = Matrix<Float>(rows: a.rows, columns: a.columns, elements: a.elements + self.bias!.elements) self.zValues = a if activationFnc == true { a = Matrix<Float>(rows: a.rows, columns: a.columns, elements: a.elements.map(fncStep)) }else{ a = Matrix<Float>(rows: a.rows, columns: a.columns, elements: a.elements.map(fncSigLog)) } self.activationValues = a return a } func produceOuputError(cost: Matrix<Float>) -> Matrix<Float> { var z = self.zValues z = Matrix<Float>(rows: (z?.rows)!, columns: (z?.columns)!, elements:ValueArray<Float>(z!.elements.map(derivativeOfSigLog))) var sigmaPrime = z var Δ = cost * sigmaPrime! return Δ } func propagateError(previousLayerDelta: Matrix<Float>, nextLayer: Layer) -> Matrix <Float> { // Compute the current layers δ value. var nextLayerWeightTranspose = transpose(nextLayer.weights!) var deltaMultipliedBywT = nextLayerWeightTranspose * previousLayerDelta var sigmaPrime = Matrix<Float>(rows: (self.zValues?.rows)!, columns: (self.zValues?.columns)!, elements: ValueArray(self.zValues!.elements.map(derivativeOfSigLog))) var currentLayerDelta = Matrix<Float>(rows: deltaMultipliedBywT.rows, columns: deltaMultipliedBywT.columns, elements: ValueArray(deltaMultipliedBywT.elements * sigmaPrime.elements)) // Update the current layers weights var inputTranspose = transpose(self.input!) var updatedWeights = currentLayerDelta * inputTranspose self.Δw = updatedWeights // Update the current layers bias self.Δb = currentLayerDelta return currentLayerDelta } func updateWeights(miniBatchSize: Int, eta: Float){ var learningRate = eta/Float(miniBatchSize) var changeInWeights = learningRate * self.Δw! var changedBiases = learningRate * self.Δb! self.weights = self.weights! - changeInWeights self.bias = self.bias! - changedBiases } // TODO: Make private method func generateRandomBiases() -> Matrix<Float> { var biasValues: [Float] = [] for i in 0..<layerSize!.columns { var biasValue = generateRandomNumber() biasValues.append(biasValue) } return Matrix<Float>(rows: (layerSize?.columns)!, columns: 1, elements: ValueArray<Float>(biasValues)) } func generateRandomWeights() -> Matrix<Float>{ var weightValues: [Float] = [] for i in 0..<(layerSize!.rows * layerSize!.columns) { var weightValue = generateRandomNumber() weightValues.append(weightValue) } return Matrix<Float>(rows: layerSize!.columns, columns: layerSize!.rows, elements: ValueArray<Float>(weightValues)) } /** The generateRandomNumber generates a random number (normal distribution using Box-Muller tranform). - returns: A random number (normal distribution). */ func generateRandomNumber() -> Float{ let u = Float(arc4random()) / Float(UINT32_MAX) let v = Float(arc4random()) / Float(UINT32_MAX) let randomNum = sqrt( -2 * log(u) ) * cos( Float(2) * Float(M_PI) * v ) return randomNum } public func fncSigLog(val: Float) -> Float { return 1.0 / (1.0 + exp(-val)) } public func derivativeOfSigLog(val: Float) -> Float { return fncSigLog(val: val) * (1.0 - fncSigLog(val: val)) } } // Feed Forward Implementation class NeuralNetwork { public var layers: [Layer] = [] public var numberOfLayers: Int? public var networkSize: (inputLayerSize:Int, outputLayerSize:Int)? init(size:(Int, Int)){ self.networkSize = size } func addLayer(layer: Layer){ self.layers.append(layer) } public func feedforward(input:Matrix<Float>) -> Matrix<Float> { var a = input for l in layers { a = l.forward(activation: a) } return a } public func SGD(trainingData: InputDataType, epochs: Int, miniBatchSize: Int, eta: Float, testData: InputDataType? = nil){ for i in 0..<epochs { var shuffledData = trainingData.data.shuffle() let miniBatches = stride(from: 0, to: shuffledData.count, by: miniBatchSize).map { Array(shuffledData[$0..<min($0 + miniBatchSize, shuffledData.count)]) } for batch in miniBatches { var b = InputDataType(data: batch) self.updateMiniBatch(miniBatch: b, eta: eta) } } } public func updateMiniBatch(miniBatch: InputDataType, eta: Float){ for batch in miniBatch.data { var inputMatrix = Matrix<Float>(rows: batch.input.count, columns: 1, elements: batch.input) var outputMatrix = Matrix<Float>(rows: batch.target.count, columns: 1, elements: batch.target) self.backpropagate(input: inputMatrix, target: outputMatrix) } for layer in layers { layer.updateWeights(miniBatchSize: miniBatch.lengthOfTrainingData, eta: eta) } } public func backpropagate(input: Matrix<Float>, target: Matrix<Float>){ // Feedforward let feedForwardOutput = feedforward(input: input) // Output Error let outputError = Matrix<Float>(rows: feedForwardOutput.rows, columns: feedForwardOutput.columns, elements: feedForwardOutput.elements - target.elements) // Output Layer Delta var delta = layers.last?.produceOuputError(cost: outputError) // Set the change in weights and bias for the last layer self.layers.last?.Δb = delta var activationValuesforTheSecondToLastLayer = layers[layers.count-2].activationValues self.layers.last?.Δw = delta! * transpose(activationValuesforTheSecondToLastLayer!) // Propogate error through each layer (except last) for i in (0..<layers.count-1).reversed() { delta = layers[i].propagateError(previousLayerDelta: delta!, nextLayer: layers[i+1]) } } } /* var nn = NeuralNetwork(size: [2,3,1]) var a = Matrix<Float>(rows: 2, columns: 1, elements: [2.0,10.0]) var trainingData = InputDataType( data: [ ([0.0,0.0], [0.0]), ([1.0,1.0],[1.0]) ] ) print(nn.weights?[0]) print("\n") print(Layer(size: (2,3)).generateRandomWeights()) */ /* var bias = nn.bias var weights = nn.weights var a = Matrix<Float>(rows: 2, columns: 1, elements: [1.0,1.0]) var b = weights![0] * a var c = (b + bias![0]) c.elements.map(nn.fncSigLog) //print(c) var d = weights![1] * c var e = (d + bias![1]) e.elements.map(nn.fncSigLog) print(e) */ /* var nn = NeuralNetwork(size: (2,1)) nn.addLayer(layer: Layer(size: (2,3))) nn.addLayer(layer: Layer(size: (3,1))) var trainingData = InputDataType(data: [ ([0.0, 0.0], [0.0]), ([1.0, 1.0], [1.0]), ([1.0, 0.0], [0.0]), ([0.0, 1.0], [0.0])]) var input1 = Matrix<Float>(rows: 2, columns: 1, elements: [0.0,0.0]) var input2 = Matrix<Float>(rows: 2, columns: 1, elements: [0.0,1.0]) var input3 = Matrix<Float>(rows: 2, columns: 1, elements: [1.0,0.0]) var input4 = Matrix<Float>(rows: 2, columns: 1, elements: [1.0,1.0]) nn.layers[0].activationFnc = false nn.layers[1].activationFnc = true nn.SGD(trainingData: trainingData, epochs: 200, miniBatchSize: 3, eta: 0.5) print(nn.feedforward(input: input1)) print(nn.feedforward(input: input2)) print(nn.feedforward(input: input3)) print(nn.feedforward(input: input4)) */ */
mit
6d0e00edcfccf98a186559015f369ef2
26.176471
191
0.62853
3.721519
false
false
false
false
jiamao130/DouYuSwift
DouYuBroad/DouYuBroad/Main/PageContentView.swift
1
5204
// // JMPageContentView.swift // DouYuBroad // // Created by 贾卯 on 2017/8/9. // Copyright © 2017年 贾卯. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(_ contentView:PageContentView,progress:CGFloat,sourceIndex: Int,targetIndex: Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { fileprivate var childVcs: [UIViewController] fileprivate weak var parentViewController: UIViewController? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollDelegate : Bool = false weak var delegate: PageContentViewDelegate? fileprivate lazy var collectionView: UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.scrollsToTop = false collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //自定义构造函数 init(frame: CGRect,childVcs: [UIViewController],parentViewController : UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView{ fileprivate func setupUI(){ for childVc in childVcs { parentViewController?.addChildViewController(childVc) } addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[(indexPath as NSIndexPath).item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } extension PageContentView: UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } // 1.定义获取需要的数据 var progress : CGFloat = 0 var sourceIndex : Int = 0 var targetIndex : Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { // 右滑 // 1.计算progress progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } extension PageContentView{ func setCurrentIndex(_ currentIndex:Int){ isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false) } }
mit
6b5c94f20b3353a83142cd3e4cec5e00
32.480263
121
0.640008
6.008264
false
false
false
false
brentsimmons/Evergreen
iOS/Add/AddFeedFolderViewController.swift
1
2878
// // AddFeedFolderViewController.swift // NetNewsWire-iOS // // Created by Maurice Parker on 11/16/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import RSCore import Account protocol AddFeedFolderViewControllerDelegate { func didSelect(container: Container) } class AddFeedFolderViewController: UITableViewController { var delegate: AddFeedFolderViewControllerDelegate? var addFeedType = AddFeedType.web var initialContainer: Container? var containers = [Container]() override func viewDidLoad() { super.viewDidLoad() var sortedActiveAccounts: [Account] if addFeedType == .web { sortedActiveAccounts = AccountManager.shared.sortedActiveAccounts } else { sortedActiveAccounts = AccountManager.shared.sortedActiveAccounts.filter { $0.type == .onMyMac || $0.type == .cloudKit } } for account in sortedActiveAccounts { containers.append(account) if let sortedFolders = account.sortedFolders { containers.append(contentsOf: sortedFolders) } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return containers.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let container = containers[indexPath.row] let cell: AddComboTableViewCell = { if container is Account { return tableView.dequeueReusableCell(withIdentifier: "AccountCell", for: indexPath) as! AddComboTableViewCell } else { return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! AddComboTableViewCell } }() if let smallIconProvider = container as? SmallIconProvider { cell.icon?.image = smallIconProvider.smallIcon?.image } if let displayNameProvider = container as? DisplayNameProvider { cell.label?.text = displayNameProvider.nameForDisplay } if let compContainer = initialContainer, container === compContainer { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let container = containers[indexPath.row] if let account = container as? Account, account.behaviors.contains(.disallowFeedInRootFolder) { tableView.selectRow(at: nil, animated: false, scrollPosition: .none) } else { let cell = tableView.cellForRow(at: indexPath) cell?.accessoryType = .checkmark delegate?.didSelect(container: container) dismiss() } } // MARK: Actions @IBAction func cancel(_ sender: Any) { dismiss() } } private extension AddFeedFolderViewController { func dismiss() { dismiss(animated: true) } }
mit
b586e9dd03f8cd1c1f1a2c95ac2938fa
25.88785
123
0.728537
4.169565
false
false
false
false
ps2/rileylink_ios
OmniKitUI/ViewModels/OmnipodSettingsViewModel.swift
1
21072
// // OmnipodSettingsViewModel.swift // OmniKit // // Created by Pete Schwamb on 3/8/20. // Copyright © 2021 LoopKit Authors. All rights reserved. // import SwiftUI import LoopKit import LoopKitUI import HealthKit import OmniKit import Combine enum OmnipodSettingsViewAlert { case suspendError(Error) case resumeError(Error) case cancelManualBasalError(Error) case syncTimeError(OmnipodPumpManagerError) } struct OmnipodSettingsNotice { let title: String let description: String } class OmnipodSettingsViewModel: ObservableObject { @Published var lifeState: PodLifeState @Published var activatedAt: Date? @Published var expiresAt: Date? @Published var beepPreference: BeepPreference @Published var rileylinkConnected: Bool var activatedAtString: String { if let activatedAt = activatedAt { return dateFormatter.string(from: activatedAt) } else { return "—" } } var expiresAtString: String { if let expiresAt = expiresAt { return dateFormatter.string(from: expiresAt) } else { return "—" } } var serviceTimeRemainingString: String? { if let serviceTimeRemaining = pumpManager.podServiceTimeRemaining, let serviceTimeRemainingString = timeRemainingFormatter.string(from: serviceTimeRemaining) { return serviceTimeRemainingString } else { return nil } } // Expiration reminder date for current pod @Published var expirationReminderDate: Date? var allowedScheduledReminderDates: [Date]? { return pumpManager.allowedExpirationReminderDates } // Hours before expiration @Published var expirationReminderDefault: Int { didSet { self.pumpManager.defaultExpirationReminderOffset = .hours(Double(expirationReminderDefault)) } } // Units to alert at @Published var lowReservoirAlertValue: Int @Published var basalDeliveryState: PumpManagerStatus.BasalDeliveryState? @Published var basalDeliveryRate: Double? @Published var activeAlert: OmnipodSettingsViewAlert? = nil { didSet { if activeAlert != nil { alertIsPresented = true } } } @Published var alertIsPresented: Bool = false { didSet { if !alertIsPresented { activeAlert = nil } } } @Published var reservoirLevel: ReservoirLevel? @Published var reservoirLevelHighlightState: ReservoirLevelHighlightState? @Published var synchronizingTime: Bool = false @Published var podCommState: PodCommState @Published var insulinType: InsulinType? @Published var podDetails: PodDetails? @Published var previousPodDetails: PodDetails? var timeZone: TimeZone { return pumpManager.status.timeZone } var viewTitle: String { return pumpManager.localizedTitle } var isClockOffset: Bool { return pumpManager.isClockOffset } var isPodDataStale: Bool { return Date().timeIntervalSince(pumpManager.lastSync ?? .distantPast) > .minutes(12) } var recoveryText: String? { if case .fault = podCommState { return LocalizedString("Insulin delivery stopped. Change Pod now.", comment: "The action string on pod status page when pod faulted") } else if podOk && isPodDataStale { return LocalizedString("Make sure your phone and pod are close to each other. If communication issues persist, move to a new area.", comment: "The action string on pod status page when pod data is stale") } else if let serviceTimeRemaining = pumpManager.podServiceTimeRemaining, serviceTimeRemaining <= Pod.serviceDuration - Pod.nominalPodLife { if let serviceTimeRemainingString = serviceTimeRemainingString { return String(format: LocalizedString("Change Pod now. Insulin delivery will stop in %1$@ or when no more insulin remains.", comment: "Format string for the action string on pod status page when pod expired. (1: service time remaining)"), serviceTimeRemainingString) } else { return LocalizedString("Change Pod now. Insulin delivery will stop 8 hours after the Pod has expired or when no more insulin remains.", comment: "The action string on pod status page when pod expired") } } else { return nil } } var notice: OmnipodSettingsNotice? { if pumpManager.isClockOffset { return OmnipodSettingsNotice( title: LocalizedString("Time Change Detected", comment: "title for time change detected notice"), description: LocalizedString("The time on your pump is different from the current time. Your pump’s time controls your scheduled basal rates. You can review the time difference and configure your pump.", comment: "description for time change detected notice")) } else { return nil } } var isScheduledBasal: Bool { switch basalDeliveryState { case .active(_), .initiatingTempBasal: return true case .tempBasal(_), .cancelingTempBasal, .suspending, .suspended(_), .resuming, .none: return false } } let dateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.timeStyle = .short dateFormatter.dateStyle = .medium dateFormatter.doesRelativeDateFormatting = true return dateFormatter }() let timeFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.timeStyle = .short dateFormatter.dateStyle = .none return dateFormatter }() let timeRemainingFormatter: DateComponentsFormatter = { let dateComponentsFormatter = DateComponentsFormatter() dateComponentsFormatter.allowedUnits = [.hour, .minute] dateComponentsFormatter.unitsStyle = .full dateComponentsFormatter.zeroFormattingBehavior = .dropAll return dateComponentsFormatter }() let basalRateFormatter: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.minimumFractionDigits = 1 numberFormatter.minimumIntegerDigits = 1 return numberFormatter }() var manualBasalTimeRemaining: TimeInterval? { if case .tempBasal(let dose) = basalDeliveryState, !(dose.automatic ?? true) { let remaining = dose.endDate.timeIntervalSinceNow if remaining > 0 { return remaining } } return nil } let reservoirVolumeFormatter = QuantityFormatter(for: .internationalUnit()) var didFinish: (() -> Void)? var navigateTo: ((OmnipodUIScreen) -> Void)? private let pumpManager: OmnipodPumpManager private lazy var cancellables = Set<AnyCancellable>() init(pumpManager: OmnipodPumpManager) { self.pumpManager = pumpManager lifeState = pumpManager.lifeState activatedAt = pumpManager.podActivatedAt expiresAt = pumpManager.expiresAt basalDeliveryState = pumpManager.status.basalDeliveryState basalDeliveryRate = self.pumpManager.basalDeliveryRate reservoirLevel = self.pumpManager.reservoirLevel reservoirLevelHighlightState = self.pumpManager.reservoirLevelHighlightState expirationReminderDate = self.pumpManager.scheduledExpirationReminder expirationReminderDefault = Int(self.pumpManager.defaultExpirationReminderOffset.hours) lowReservoirAlertValue = Int(self.pumpManager.state.lowReservoirReminderValue) podCommState = self.pumpManager.podCommState beepPreference = self.pumpManager.beepPreference insulinType = self.pumpManager.insulinType podDetails = self.pumpManager.podDetails previousPodDetails = self.pumpManager.previousPodDetails // TODO: rileylinkConnected = false pumpManager.addPodStateObserver(self, queue: DispatchQueue.main) pumpManager.addStatusObserver(self, queue: DispatchQueue.main) // Register for device notifications NotificationCenter.default.publisher(for: .DeviceConnectionStateDidChange) .sink { [weak self] _ in self?.updateConnectionStatus() } .store(in: &cancellables) // Trigger refresh pumpManager.getPodStatus() { _ in } updateConnectionStatus() } func updateConnectionStatus() { pumpManager.rileyLinkDeviceProvider.getDevices { (devices) in DispatchQueue.main.async { [weak self] in self?.rileylinkConnected = devices.firstConnected != nil } } } func changeTimeZoneTapped() { synchronizingTime = true pumpManager.setTime { (error) in DispatchQueue.main.async { self.synchronizingTime = false self.lifeState = self.pumpManager.lifeState if let error = error { self.activeAlert = .syncTimeError(error) } } } } func doneTapped() { self.didFinish?() } func stopUsingOmnipodTapped() { self.pumpManager.notifyDelegateOfDeactivation { DispatchQueue.main.async { self.didFinish?() } } } func suspendDelivery(duration: TimeInterval) { pumpManager.suspendDelivery(withSuspendReminders: duration) { (error) in DispatchQueue.main.async { if let error = error { self.activeAlert = .suspendError(error) } } } } func resumeDelivery() { pumpManager.resumeDelivery { (error) in DispatchQueue.main.async { if let error = error { self.activeAlert = .resumeError(error) } } } } func runTemporaryBasalProgram(unitsPerHour: Double, for duration: TimeInterval, completion: @escaping (PumpManagerError?) -> Void) { pumpManager.runTemporaryBasalProgram(unitsPerHour: unitsPerHour, for: duration, automatic: false, completion: completion) } func saveScheduledExpirationReminder(_ selectedDate: Date?, _ completion: @escaping (Error?) -> Void) { if let podExpiresAt = pumpManager.podExpiresAt { var intervalBeforeExpiration : TimeInterval? if let selectedDate = selectedDate { intervalBeforeExpiration = .hours(round(podExpiresAt.timeIntervalSince(selectedDate).hours)) } pumpManager.updateExpirationReminder(intervalBeforeExpiration) { (error) in DispatchQueue.main.async { if error == nil { self.expirationReminderDate = selectedDate } completion(error) } } } } func saveLowReservoirReminder(_ selectedValue: Int, _ completion: @escaping (Error?) -> Void) { pumpManager.updateLowReservoirReminder(selectedValue) { (error) in DispatchQueue.main.async { if error == nil { self.lowReservoirAlertValue = selectedValue } completion(error) } } } func playTestBeeps(_ completion: @escaping (Error?) -> Void) { pumpManager.playTestBeeps(completion: completion) } func setConfirmationBeeps(_ preference: BeepPreference, _ completion: @escaping (_ error: LocalizedError?) -> Void) { pumpManager.setConfirmationBeeps(newPreference: preference) { error in DispatchQueue.main.async { if error == nil { self.beepPreference = preference } completion(error) } } } func didChangeInsulinType(_ newType: InsulinType?) { self.pumpManager.insulinType = newType } var podOk: Bool { guard basalDeliveryState != nil else { return false } switch podCommState { case .noPod, .activating, .deactivating, .fault: return false default: return true } } var podError: String? { switch podCommState { case .fault(let status): switch status.faultEventCode.faultType { case .reservoirEmpty: return LocalizedString("No Insulin", comment: "Error message for reservoir view when reservoir empty") case .exceededMaximumPodLife80Hrs: return LocalizedString("Pod Expired", comment: "Error message for reservoir view when pod expired") case .occluded, .occlusionCheckStartup1, .occlusionCheckStartup2, .occlusionCheckTimeouts1, .occlusionCheckTimeouts2, .occlusionCheckTimeouts3, .occlusionCheckPulseIssue, .occlusionCheckBolusProblem, .occlusionCheckAboveThreshold, .occlusionCheckValueTooHigh: return LocalizedString("Pod Occlusion", comment: "Error message for reservoir view when pod occlusion checks failed") default: return LocalizedString("Pod Error", comment: "Error message for reservoir view during general pod fault") } case .active: if isPodDataStale { return LocalizedString("Signal Loss", comment: "Error message for reservoir view during general pod fault") } else { return nil } default: return nil } } func reservoirText(for level: ReservoirLevel) -> String { switch level { case .aboveThreshold: let quantity = HKQuantity(unit: .internationalUnit(), doubleValue: Pod.maximumReservoirReading) let thresholdString = reservoirVolumeFormatter.string(from: quantity, for: .internationalUnit(), includeUnit: false) ?? "" let unitString = reservoirVolumeFormatter.string(from: .internationalUnit(), forValue: Pod.maximumReservoirReading, avoidLineBreaking: true) return String(format: LocalizedString("%1$@+ %2$@", comment: "Format string for reservoir level above max measurable threshold. (1: measurable reservoir threshold) (2: units)"), thresholdString, unitString) case .valid(let value): let quantity = HKQuantity(unit: .internationalUnit(), doubleValue: value) return reservoirVolumeFormatter.string(from: quantity, for: .internationalUnit()) ?? "" } } var suspendResumeActionText: String { let defaultText = LocalizedString("Suspend Insulin Delivery", comment: "Text for suspend resume button when insulin delivery active") guard podOk else { return defaultText } switch basalDeliveryState { case .suspending: return LocalizedString("Suspending insulin delivery...", comment: "Text for suspend resume button when insulin delivery is suspending") case .suspended: return LocalizedString("Resume Insulin Delivery", comment: "Text for suspend resume button when insulin delivery is suspended") case .resuming: return LocalizedString("Resuming insulin delivery...", comment: "Text for suspend resume button when insulin delivery is resuming") default: return defaultText } } var basalTransitioning: Bool { switch basalDeliveryState { case .suspending, .resuming: return true default: return false } } func suspendResumeButtonColor(guidanceColors: GuidanceColors) -> Color { guard podOk else { return Color.secondary } switch basalDeliveryState { case .suspending, .resuming: return Color.secondary case .suspended: return guidanceColors.warning default: return .accentColor } } func suspendResumeActionColor() -> Color { guard podOk else { return Color.secondary } switch basalDeliveryState { case .suspending, .resuming: return Color.secondary default: return Color.accentColor } } var isSuspendedOrResuming: Bool { switch basalDeliveryState { case .suspended, .resuming: return true default: return false } } public var allowedTempBasalRates: [Double] { return Pod.supportedTempBasalRates.filter { $0 <= pumpManager.state.maximumTempBasalRate } } } extension OmnipodSettingsViewModel: PodStateObserver { func podStateDidUpdate(_ state: PodState?) { lifeState = self.pumpManager.lifeState basalDeliveryRate = self.pumpManager.basalDeliveryRate reservoirLevel = self.pumpManager.reservoirLevel activatedAt = state?.activatedAt expiresAt = state?.expiresAt reservoirLevelHighlightState = self.pumpManager.reservoirLevelHighlightState expirationReminderDate = self.pumpManager.scheduledExpirationReminder podCommState = self.pumpManager.podCommState beepPreference = self.pumpManager.beepPreference insulinType = self.pumpManager.insulinType podDetails = self.pumpManager.podDetails previousPodDetails = self.pumpManager.previousPodDetails } func podConnectionStateDidChange(isConnected: Bool) { self.rileylinkConnected = isConnected } } extension OmnipodSettingsViewModel: PumpManagerStatusObserver { func pumpManager(_ pumpManager: PumpManager, didUpdate status: PumpManagerStatus, oldStatus: PumpManagerStatus) { basalDeliveryState = self.pumpManager.status.basalDeliveryState } } extension OmnipodPumpManager { var lifeState: PodLifeState { switch podCommState { case .fault(let status): switch status.faultEventCode.faultType { case .exceededMaximumPodLife80Hrs: return .expired default: let remaining = Pod.nominalPodLife - (status.faultEventTimeSinceActivation ?? Pod.nominalPodLife) if remaining > 0 { return .timeRemaining(remaining) } else { return .expired } } case .noPod: return .noPod case .activating: return .podActivating case .deactivating: return .podDeactivating case .active: if let podTimeRemaining = podTimeRemaining { if podTimeRemaining > 0 { return .timeRemaining(podTimeRemaining) } else { return .expired } } else { return .podDeactivating } } } var basalDeliveryRate: Double? { if let tempBasal = state.podState?.unfinalizedTempBasal, !tempBasal.isFinished() { return tempBasal.rate } else { switch state.podState?.suspendState { case .resumed: var calendar = Calendar(identifier: .gregorian) calendar.timeZone = state.timeZone return state.basalSchedule.currentRate(using: calendar, at: dateGenerator()) case .suspended, .none: return nil } } } fileprivate var podServiceTimeRemaining : TimeInterval? { guard let podTimeRemaining = podTimeRemaining else { return nil; } return max(0, Pod.serviceDuration - Pod.nominalPodLife + podTimeRemaining); } private func podDetails(fromPodState podState: PodState) -> PodDetails { return PodDetails( lotNumber: podState.lot, sequenceNumber: podState.tid, piVersion: podState.piVersion, pmVersion: podState.pmVersion, totalDelivery: podState.lastInsulinMeasurements?.delivered, lastStatus: podState.lastInsulinMeasurements?.validTime, fault: podState.fault?.faultEventCode, activatedAt: podState.activatedAt, activeTime: podState.activeTime, pdmRef: podState.fault?.pdmRef ) } public var podDetails: PodDetails? { guard let podState = state.podState else { return nil } return podDetails(fromPodState: podState) } public var previousPodDetails: PodDetails? { guard let podState = state.previousPodState else { return nil } return podDetails(fromPodState: podState) } }
mit
f3daa31ce8a525fd562fb675e4b1385a
34.462963
282
0.633468
5.386091
false
false
false
false
Obisoft2017/BeautyTeamiOS
BeautyTeam/BeautyTeam/ObisoftUser.swift
1
3779
// // ObisoftUser.swift // BeautyTeam // // Created by Carl Lee on 4/16/16. // Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved. // import Foundation class ObisoftUser: ObisoftAnotherUser { var schoolId: Int? var schoolAccount: String! var schoolPassAes: String! var schoolBinded: Bool! var schoolAccountSet: Bool! var GU_Relations = [GroupUserRelation]() var TU_Relations = [TeamUserRelation]() var EU_Relations = [TeamEventRelation]() var personalTasks = [PersonalTask]() var personalEvents = [PersonalEvent]() var allowSeeImFree: Bool! var allowSeeWhatImDoing: Bool! var allowAddtoMyCalendar: Bool! var allowSeeMySchoolAndAccount: Bool! var openid: String! required init(rawData: [String : AnyObject?]) { super.init(rawData: rawData) if let _ = rawData["SchoolId"] as? NSNull { self.schoolId = nil } else { guard let schoolId = rawData["SchoolId"] as? Int else { fatalError() } self.schoolId = schoolId } if let _ = rawData["SchoolAccount"] as? NSNull { self.schoolAccount = "" } else { guard let schoolAccount = rawData["SchoolAccount"] as? String else { fatalError() } self.schoolAccount = schoolAccount } if let _ = rawData["SchoolPassAes"] as? NSNull { self.schoolPassAes = "" } else { guard let schoolPassAes = rawData["SchoolPassAes"] as? String else { fatalError() } self.schoolPassAes = schoolPassAes } guard let schoolBinded = rawData["SchoolBinded"] as? Bool else { fatalError() } guard let schoolAccountSet = rawData["SchoolAccountSet"] as? Bool else { fatalError() } guard let GU_Relations_raw = rawData["GU_Relations"] as? Array<Dictionary<String, AnyObject>> else { fatalError() } guard let TU_Relations_raw = rawData["TU_Relations"] as? Array<Dictionary<String, AnyObject>> else { fatalError() } guard let EU_Relations_raw = rawData["EU_Relations"] as? Array<Dictionary<String, AnyObject>> else { fatalError() } guard let allowSeeImFree = rawData["AllowSeeImFree"] as? Bool else { fatalError() } guard let allowSeeWhatImDoing = rawData["AllowSeeWhatImDoing"] as? Bool else { fatalError() } guard let allowAddtoMyCalendar = rawData["AllowAddtoMyCalendar"] as? Bool else { fatalError() } guard let allowSeeMySchoolAndAccount = rawData["AllowSeeMySchoolAndAccount"] as? Bool else { fatalError() } guard let openid = rawData["openid"] as? String else { fatalError() } self.schoolBinded = schoolBinded self.schoolAccountSet = schoolAccountSet for element in GU_Relations_raw { self.GU_Relations.append(GroupUserRelation(rawData: element)) } for element in TU_Relations_raw { self.TU_Relations.append(TeamUserRelation(rawData: element)) } for element in EU_Relations_raw { self.EU_Relations.append(TeamEventRelation(rawData: element)) } self.allowSeeImFree = allowSeeImFree self.allowSeeMySchoolAndAccount = allowSeeMySchoolAndAccount self.allowAddtoMyCalendar = allowAddtoMyCalendar self.allowSeeWhatImDoing = allowSeeWhatImDoing self.openid = openid } }
apache-2.0
08238dd7261361d44160a2ba97afb577
31.568966
108
0.586818
4.429074
false
false
false
false
iranjith4/RWSBounceButton
RWSBounceButton/Classes/RWSBounceButton.swift
1
5083
// // RWSBounceButton.swift // Ranjithkumar Matheswaran // // Created by Ranjithkumar on 06/05/16. // Copyright © 2016 Ranjith Work Studio - http://iranjith4.com. All rights reserved. // import UIKit public class RWSBounceButton: UIButton { var selectedColor = UIColor.orangeColor() var normalColor = UIColor.whiteColor() var selectedBorderColor = UIColor.orangeColor() var normalBorderColor = UIColor.orangeColor() private var isShrinked : Bool = false var isShrinking : Bool = false var touchEnded : Bool = false var touchDelayTimer : NSTimer! var isButtonSelected : Bool = false public init(frame: CGRect, selectedString : String, normalString : String) { super.init(frame: frame) self.setTitle(normalString, forState: UIControlState.Normal) self.setTitle(selectedString, forState: UIControlState.Selected) self.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) self.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Selected) self.addTarget(self, action: #selector(changeState), forControlEvents: UIControlEvents.TouchUpInside) self.layer.cornerRadius = 8 self.layer.borderWidth = 2 self.layer.borderColor = UIColor.orangeColor().CGColor self.layer.masksToBounds = true } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.adjustsImageWhenHighlighted = true self.tintColor = UIColor.orangeColor() self.layer.borderWidth = 2 self.layer.borderColor = UIColor.orangeColor().CGColor self.layer.masksToBounds = true } //Animations for the buttons func beginShrinkAnimation(){ self.touchDelayTimer.invalidate() self.isShrinked = true UIView.animateWithDuration(0.3) { self.isShrinking = true self.transform = CGAffineTransformMakeScale(0.83, 0.83) } UIView.animateWithDuration(0.18, animations: { if (self.touchEnded) { self.isShrinking = false return } self.transform = CGAffineTransformMakeScale(0.85, 0.85) }) {(finished) in self.isShrinking = false } } func beginEnlargeAnimation(){ self.isShrinked = false if self.isShrinking { self.isShrinking = false let presentationLayer = self.layer.presentationLayer() self.transform = CATransform3DGetAffineTransform((presentationLayer?.transform)!) UIView.animateWithDuration(0.1, animations: { self.transform = CGAffineTransformMakeScale(0.85, 0.85) }) }else{ UIView.animateWithDuration(0.1, animations: { self.transform = CGAffineTransformMakeScale(0.85, 0.85) }) } UIView.animateWithDuration(0.18, animations: { self.transform = CGAffineTransformMakeScale(1.05, 1.05) }) UIView.animateWithDuration(0.18, animations: { self.transform = CGAffineTransformMakeScale(0.98, 0.98) }) UIView.animateWithDuration(0.17, animations: { self.transform = CGAffineTransformMakeScale(1.01, 1.01) }) UIView.animateWithDuration(0.17, animations: { self.transform = CGAffineTransformIdentity }) } //MARK: - Touch Event override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) self.touchEnded = false self.touchDelayTimer = NSTimer.scheduledTimerWithTimeInterval(0.15, target: self, selector: #selector(beginShrinkAnimation), userInfo: nil, repeats: false) NSRunLoop.currentRunLoop().addTimer(self.touchDelayTimer, forMode: NSRunLoopCommonModes) } override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) self.touchEnded = true self.touchDelayTimer.invalidate() beginEnlargeAnimation() } override public func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesEnded(touches!, withEvent: event) self.touchEnded = true self.touchDelayTimer.invalidate() if self.isShrinked { self.beginEnlargeAnimation() } } //MARK : Selector Method public func changeState(){ if self.isButtonSelected { isButtonSelected = false self.selected = false self.backgroundColor = normalColor }else{ isButtonSelected = true self.selected = true self.backgroundColor = selectedColor } } public func setButtonSelected(selected : Bool){ self.isButtonSelected = selected changeState() } }
mit
fcd7d5e67ae7f3edf04f7450511de49b
33.571429
163
0.630854
4.962891
false
false
false
false