repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Shopify/mobile-buy-sdk-ios
refs/heads/main
Buy/Generated/Storefront/CheckoutShippingLineUpdatePayload.swift
mit
1
// // CheckoutShippingLineUpdatePayload.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Return type for `checkoutShippingLineUpdate` mutation. open class CheckoutShippingLineUpdatePayloadQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = CheckoutShippingLineUpdatePayload /// The updated checkout object. @discardableResult open func checkout(alias: String? = nil, _ subfields: (CheckoutQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery { let subquery = CheckoutQuery() subfields(subquery) addField(field: "checkout", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @discardableResult open func checkoutUserErrors(alias: String? = nil, _ subfields: (CheckoutUserErrorQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery { let subquery = CheckoutUserErrorQuery() subfields(subquery) addField(field: "checkoutUserErrors", aliasSuffix: alias, subfields: subquery) return self } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") @discardableResult open func userErrors(alias: String? = nil, _ subfields: (UserErrorQuery) -> Void) -> CheckoutShippingLineUpdatePayloadQuery { let subquery = UserErrorQuery() subfields(subquery) addField(field: "userErrors", aliasSuffix: alias, subfields: subquery) return self } } /// Return type for `checkoutShippingLineUpdate` mutation. open class CheckoutShippingLineUpdatePayload: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = CheckoutShippingLineUpdatePayloadQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "checkout": if value is NSNull { return nil } guard let value = value as? [String: Any] else { throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue) } return try Checkout(fields: value) case "checkoutUserErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try CheckoutUserError(fields: $0) } case "userErrors": guard let value = value as? [[String: Any]] else { throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue) } return try value.map { return try UserError(fields: $0) } default: throw SchemaViolationError(type: CheckoutShippingLineUpdatePayload.self, field: fieldName, value: fieldValue) } } /// The updated checkout object. open var checkout: Storefront.Checkout? { return internalGetCheckout() } func internalGetCheckout(alias: String? = nil) -> Storefront.Checkout? { return field(field: "checkout", aliasSuffix: alias) as! Storefront.Checkout? } /// The list of errors that occurred from executing the mutation. open var checkoutUserErrors: [Storefront.CheckoutUserError] { return internalGetCheckoutUserErrors() } func internalGetCheckoutUserErrors(alias: String? = nil) -> [Storefront.CheckoutUserError] { return field(field: "checkoutUserErrors", aliasSuffix: alias) as! [Storefront.CheckoutUserError] } /// The list of errors that occurred from executing the mutation. @available(*, deprecated, message:"Use `checkoutUserErrors` instead.") open var userErrors: [Storefront.UserError] { return internalGetUserErrors() } func internalGetUserErrors(alias: String? = nil) -> [Storefront.UserError] { return field(field: "userErrors", aliasSuffix: alias) as! [Storefront.UserError] } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "checkout": if let value = internalGetCheckout() { response.append(value) response.append(contentsOf: value.childResponseObjectMap()) } case "checkoutUserErrors": internalGetCheckoutUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } case "userErrors": internalGetUserErrors().forEach { response.append($0) response.append(contentsOf: $0.childResponseObjectMap()) } default: break } } return response } } }
8600adc3ae9ba8c4f3ec678dd1720c4a
36.519481
143
0.733645
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/extensions.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Foo { // CHECK-LABEL: sil hidden @_T010extensions3FooC3zim{{[_0-9a-zA-Z]*}}F func zim() {} } extension Foo { // CHECK-LABEL: sil hidden @_T010extensions3FooC4zang{{[_0-9a-zA-Z]*}}F func zang() {} // CHECK-LABEL: sil hidden @_T010extensions3FooC7zippitySifg var zippity: Int { return 0 } } struct Bar { // CHECK-LABEL: sil hidden @_T010extensions3BarV4zung{{[_0-9a-zA-Z]*}}F func zung() {} } extension Bar { // CHECK-LABEL: sil hidden @_T010extensions3BarV4zoom{{[_0-9a-zA-Z]*}}F func zoom() {} } // CHECK-LABEL: sil hidden @_T010extensions19extensionReferencesyAA3FooCF func extensionReferences(_ x: Foo) { // Non-objc extension methods are statically dispatched. // CHECK: function_ref @_T010extensions3FooC4zang{{[_0-9a-zA-Z]*}}F x.zang() // CHECK: function_ref @_T010extensions3FooC7zippitySifg _ = x.zippity } func extensionMethodCurrying(_ x: Foo) { _ = x.zang } // CHECK-LABEL: sil shared [thunk] @_T010extensions3FooC4zang{{[_0-9a-zA-Z]*}}F // CHECK: function_ref @_T010extensions3FooC4zang{{[_0-9a-zA-Z]*}}F // Extensions of generic types with stored property initializers // CHECK-LABEL: sil hidden [transparent] @_T010extensions3BoxV1txSgvfi : $@convention(thin) <T> () -> @out Optional<T> // CHECK: bb0(%0 : $*Optional<T>): // CHECK: [[FN:%.*]] = function_ref @_T0SqxSgyt10nilLiteral_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0> // CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optional<T>.Type // CHECK-NEXT: apply [[FN]]<T>(%0, [[METATYPE]]) : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() struct Box<T> { let t: T? = nil } // CHECK-LABEL: sil hidden @_T010extensions3BoxVACyxGx1t_tcfC : $@convention(method) <T> (@in T, @thin Box<T>.Type) -> @out Box<T> // CHECK: [[SELF_BOX:%.*]] = alloc_box $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK-NEXT: [[SELF_ADDR:%.*]] = project_box [[SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK: [[SELF_PTR:%.*]] = mark_uninitialized [rootself] [[SELF_ADDR]] : $*Box<T> // CHECK: [[INIT:%.*]] = function_ref @_T010extensions3BoxV1txSgvfi : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK-NEXT: apply [[INIT]]<T>([[RESULT]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0> // CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[SELF_PTR]] : $*Box<T>, #Box.t // CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T> // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Optional<T> // CHECK-NEXT: [[RESULT_ADDR:%.*]] = init_enum_data_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %1 to [initialization] %14 : $*T // CHECK-NEXT: inject_enum_addr [[RESULT]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: [[T_ADDR:%.*]] = struct_element_addr [[SELF_PTR]] : $*Box<T>, #Box.t // CHECK-NEXT: copy_addr [take] [[RESULT]] to [[T_ADDR:%.*]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[RESULT]] : $*Optional<T> // CHECK-NEXT: copy_addr [[SELF_PTR]] to [initialization] %0 : $*Box<T> // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: destroy_value [[SELF_BOX]] : $<τ_0_0> { var Box<τ_0_0> } <T> // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() extension Box { init(t: T) { self.t = t } }
f84f8253e6b118e595c0404c78aafb5d
41.464286
153
0.617606
false
false
false
false
prine/ROGenericTableViewController
refs/heads/master
ROGenericTableViewController/NavigationViewController.swift
mit
1
// // NavigationViewController.swift // ROTableViewController // // Created by Robin Oster on 27/03/15. // Copyright (c) 2015 Rascor International AG. All rights reserved. // import UIKit class User { var firstname:String = "" var lastname:String = "" init(_ firstname:String, _ lastname:String) { self.firstname = firstname self.lastname = lastname } } class NavigationViewController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() let user1 = User("Hugo", "Walker") let user2 = User("Texas", "Ranger") let cellForRow = ({ (tableView:UITableView, user:User) -> UITableViewCell in // CellForRowAtIndexPath var customCell:CustomTableViewCell? = tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomTableViewCell? if customCell == nil { customCell = CustomTableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "CustomCell") as CustomTableViewCell } customCell!.setUser(user) return customCell! }) let didCellSelect = ({(user:User) -> () in let detailViewController = self.storyboardLoad("DetailViewControllerScene") as DetailViewController self.pushViewController(detailViewController, animated: true) }) // Generic CustomTableViewCell solution let tableViewController = createViewControllerGeneric([user1, user2], cellForRow: cellForRow, select: didCellSelect, storyboardName: "Main", tableViewControllerIdentifier: "TableViewControllerScene") as! ROGenericTableViewController // If you need swipe actions just set the swipe actions variable tableViewController.swipeActions = createSwipeActions() // Update later on the data (need to use the generic outside method) updateItems(tableViewController, items: [user1, user2, user1, user2]) tableViewController.tableView.reloadData() self.viewControllers = [tableViewController] } func createSwipeActions() -> [UITableViewRowAction] { let favAction = UITableViewRowAction(style: .normal, title: "Swipe 1") { (action, indexPath) -> Void in print("Swipe 1") } favAction.backgroundColor = UIColor.brown return [favAction] } func storyboardLoad<T>(_ sceneName:String) -> T { return self.storyboard?.instantiateViewController(withIdentifier: sceneName) as! T } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
06d3a3b608ccf9816ade71e28a51842c
33.923077
240
0.64978
false
false
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Apps/Parking/model/Registration/ParkingRegistrationClient.swift
apache-2.0
1
// // ParkingRegistrationClient.swift // byuSuite // // Created by Erik Brady on 11/16/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let BASE_URL = "https://api.byu.edu/domains/parking/rest/v2" class ParkingRegistrationClient: ByuClient2 { static func getAllCodes(codesetId: String, callback: @escaping ([TrafficCode]?, ByuError?) -> Void) { makeRequest(createRequest(pathParams: ["codes", codesetId])) { (response) in if response.succeeded, let data = response.getDataJson() as? [[String: Any]] { do { callback(try data.map { return try TrafficCode(dict: $0) }.sorted(), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func getAllVehicles(callback: @escaping ([Vehicle]?, ByuError?) -> Void) { makeRequest(createRequest(pathParams: ["vehicles"])) { (response) in if response.succeeded, let data = response.getDataJson() as? [[String: Any]] { do { callback(try data.map { return try Vehicle(dict: $0, active: true) }, nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func getAllInactiveVehicles(callback: @escaping ([Vehicle]?, ByuError?) -> Void) { makeRequest(createRequest(pathParams: ["vehicles", "inactive"])) { (response) in if response.succeeded, let data = response.getDataJson() as? [[String: Any]] { do { callback(try data.map { return try Vehicle(dict: $0, active: false) }, nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func getPrivilegeInfo(callback: @escaping (PrivilegeWrapper?, ByuError?) -> Void) { makeRequest(createRequest(pathParams: ["privileges"])) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try PrivilegeWrapper(dict: data), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func getVehicleLimitInfo(callback: @escaping (AddVehicleEligibility?, ByuError?) -> Void) { makeRequest(createRequest(pathParams: ["vehicles", "limit"])) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { callback(AddVehicleEligibility(dict: data), nil) } else { callback(nil, response.error) } } } static func createVehicle(vehicle: Vehicle, callback: @escaping (Vehicle?, ByuError?) -> Void) { makeRequest(createRequest(method: .POST, pathParams: ["vehicles"], data: vehicle.toDictionary())) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try Vehicle(dict: data, active: true), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func editVehicle(vehicle: Vehicle, callback: @escaping (Vehicle?, ByuError?) -> Void) { if let vehicleId = vehicle.vehicleId { makeRequest(createRequest(method: .PUT, pathParams: ["vehicles", "\(vehicleId)"], data: vehicle.toDictionary())) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try Vehicle(dict: data, active: true), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } else { callback(nil, InvalidModelError.byuError) } } static func registerVehicle(vehicle: Vehicle, callback: @escaping (Vehicle?, ByuError?) -> Void) { makeRequest(createRequest(method: .POST, pathParams: ["vehicles", "registration"], data: vehicle.toDictionary())) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try Vehicle(dict: data, active: true), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func deleteVehicle(vehicleId: Int, callback: @escaping (ByuError?) -> Void) { makeRequest(createRequest(method: .DELETE, pathParams: ["vehicles", "inactive", "\(vehicleId)"])) { (response) in callback(response.succeeded ? nil : response.error) } } static func unregisterVehicle(vehicle: Vehicle, callback: @escaping (Vehicle?, ByuError?) -> Void) { if let vehicleId = vehicle.vehicleId { makeRequest(createRequest(method: .DELETE, pathParams: ["vehicles", "registration", "\(vehicleId)"], data: vehicle.toDictionary())) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try Vehicle(dict: data, active: false), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } else { callback(nil, InvalidModelError.byuError) } } static func startPayment(callback: @escaping (ParkingPaymentInfoWrapper?, ByuError?) -> Void) { makeRequest(createRequest(method: .POST, pathParams: ["payments"])) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any] { do { callback(try ParkingPaymentInfoWrapper(dict: data), nil) } catch { callback(nil, InvalidModelError.byuError) } } else { callback(nil, response.error) } } } static func completePayment(paymentId: Int, paymentWrapper: ParkingCompletePaymentWrapper, callback: @escaping (String?, ByuError?) -> Void) { makeRequest(createRequest(method: .POST, pathParams: ["payments", "\(paymentId)"], data: paymentWrapper.toDictionary())) { (response) in if response.succeeded, let data = response.getDataJson() as? [String: Any], let invoiceId = data["invoiceId"] as? String { callback(invoiceId, nil) } else { callback(nil, response.error) } } } private static func createRequest(method: ByuRequest2.RequestMethod = .GET, pathParams: [String], data: [String: Any]? = nil) -> ByuRequest2 { let request = ByuRequest2(requestMethod: method, url: super.url(base: BASE_URL, pathParams: pathParams), contentType: .JSON, pathToReadableError: "message") if let body = data { request.body = try? JSONSerialization.data(withJSONObject: body) } return request } }
48de3e3911e907fef7474947438252e4
34.115385
158
0.672821
false
false
false
false
ReactKit/SwiftState
refs/heads/swift/5.0
Tests/SwiftStateTests/MiscTests.swift
mit
1
// // MiscTests.swift // SwiftState // // Created by Yasuhiro Inami on 2015-12-05. // Copyright © 2015 Yasuhiro Inami. All rights reserved. // import SwiftState import XCTest /// Unarranged tests. class MiscTests: _TestCase { func testREADME_string() { let machine = StateMachine<String, NoEvent>(state: ".State0") { machine in machine.addRoute(".State0" => ".State1") machine.addRoute(.any => ".State2") { context in print("Any => 2, msg=\(String(describing: context.userInfo))") } machine.addRoute(".State2" => .any) { context in print("2 => Any, msg=\(String(describing: context.userInfo))") } // add handler (handlerContext = (event, transition, order, userInfo)) machine.addHandler(".State0" => ".State1") { context in print("0 => 1") } // add errorHandler machine.addErrorHandler { context in print("[ERROR] \(context.fromState) => \(context.toState)") } } // tryState 0 => 1 => 2 => 1 => 0 machine <- ".State1" XCTAssertEqual(machine.state, ".State1") machine <- (".State2", "Hello") XCTAssertEqual(machine.state, ".State2") machine <- (".State1", "Bye") XCTAssertEqual(machine.state, ".State1") machine <- ".State0" // fail: no 1 => 0 XCTAssertEqual(machine.state, ".State1") print("machine.state = \(machine.state)") } // StateType + associated value func testREADME_associatedValue() { let machine = StateMachine<StrState, StrEvent>(state: .str("0")) { machine in machine.addRoute(.str("0") => .str("1")) machine.addRoute(.any => .str("2")) { context in print("Any => 2, msg=\(String(describing: context.userInfo))") } machine.addRoute(.str("2") => .any) { context in print("2 => Any, msg=\(String(describing: context.userInfo))") } // add handler (handlerContext = (event, transition, order, userInfo)) machine.addHandler(.str("0") => .str("1")) { context in print("0 => 1") } // add errorHandler machine.addErrorHandler { context in print("[ERROR] \(context.fromState) => \(context.toState)") } } // tryState 0 => 1 => 2 => 1 => 0 machine <- .str("1") XCTAssertEqual(machine.state, StrState.str("1")) machine <- (.str("2"), "Hello") XCTAssertEqual(machine.state, StrState.str("2")) machine <- (.str("1"), "Bye") XCTAssertEqual(machine.state, StrState.str("1")) machine <- .str("0") // fail: no 1 => 0 XCTAssertEqual(machine.state, StrState.str("1")) print("machine.state = \(machine.state)") } func testExample() { let machine = StateMachine<MyState, NoEvent>(state: .state0) { // add 0 => 1 $0.addRoute(.state0 => .state1) { context in print("[Transition 0=>1] \(context.fromState) => \(context.toState)") } // add 0 => 1 once more $0.addRoute(.state0 => .state1) { context in print("[Transition 0=>1b] \(context.fromState) => \(context.toState)") } // add 2 => Any $0.addRoute(.state2 => .any) { context in print("[Transition exit 2] \(context.fromState) => \(context.toState) (Any)") } // add Any => 2 $0.addRoute(.any => .state2) { context in print("[Transition Entry 2] \(context.fromState) (Any) => \(context.toState)") } // add 1 => 0 (no handler) $0.addRoute(.state1 => .state0) } // 0 => 1 XCTAssertTrue(machine.hasRoute(.state0 => .state1)) // 1 => 0 XCTAssertTrue(machine.hasRoute(.state1 => .state0)) // 2 => Any XCTAssertTrue(machine.hasRoute(.state2 => .state0)) XCTAssertTrue(machine.hasRoute(.state2 => .state1)) XCTAssertTrue(machine.hasRoute(.state2 => .state2)) XCTAssertTrue(machine.hasRoute(.state2 => .state3)) // Any => 2 XCTAssertTrue(machine.hasRoute(.state0 => .state2)) XCTAssertTrue(machine.hasRoute(.state1 => .state2)) XCTAssertTrue(machine.hasRoute(.state3 => .state2)) // others XCTAssertFalse(machine.hasRoute(.state0 => .state0)) XCTAssertFalse(machine.hasRoute(.state0 => .state3)) XCTAssertFalse(machine.hasRoute(.state1 => .state1)) XCTAssertFalse(machine.hasRoute(.state1 => .state3)) XCTAssertFalse(machine.hasRoute(.state3 => .state0)) XCTAssertFalse(machine.hasRoute(.state3 => .state1)) XCTAssertFalse(machine.hasRoute(.state3 => .state3)) machine.configure { // add error handlers $0.addErrorHandler { context in print("[ERROR 1] \(context.fromState) => \(context.toState)") } // add entry handlers $0.addHandler(.any => .state0) { context in print("[Entry 0] \(context.fromState) => \(context.toState)") // NOTE: this should not be called } $0.addHandler(.any => .state1) { context in print("[Entry 1] \(context.fromState) => \(context.toState)") } $0.addHandler(.any => .state2) { context in print("[Entry 2] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))") } $0.addHandler(.any => .state2) { context in print("[Entry 2b] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))") } // add exit handlers $0.addHandler(.state0 => .any) { context in print("[Exit 0] \(context.fromState) => \(context.toState)") } $0.addHandler(.state1 => .any) { context in print("[Exit 1] \(context.fromState) => \(context.toState)") } $0.addHandler(.state2 => .any) { context in print("[Exit 2] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))") } $0.addHandler(.state2 => .any) { context in print("[Exit 2b] \(context.fromState) => \(context.toState), userInfo = \(String(describing: context.userInfo))") } } XCTAssertEqual(machine.state, MyState.state0) // tryState 0 => 1 => 2 => 1 => 0 => 3 machine <- .state1 XCTAssertEqual(machine.state, MyState.state1) machine <- (.state2, "State2 activate") XCTAssertEqual(machine.state, MyState.state2) machine <- (.state1, "State2 deactivate") XCTAssertEqual(machine.state, MyState.state1) machine <- .state0 XCTAssertEqual(machine.state, MyState.state0) machine <- .state3 XCTAssertEqual(machine.state, MyState.state0, "No 0 => 3.") } }
b11923757920c1d973bc7ab0da64982a
35.793814
130
0.543149
false
false
false
false
Kezuino/SMPT31
refs/heads/master
NOtification/NOKit/JSONManager.swift
mit
1
// // JSONManager.swift // NOtification // // Created by Bas on 29/05/2015. // Copyright (c) 2015 Bas. All rights reserved. // import Foundation import SwiftyJSON import SwiftSerializer import SocketRocket public class JSONManager: NSObject { /// The Singleton instance of this class. public static let sharedInstance = JSONManager() let request = NSURLRequest(URL: NSURL(string: "ws://192.168.27.20:8821")!) let webSocket: SRWebSocket! var openSocket = false private override init() { self.webSocket = SRWebSocket(URLRequest: request) super.init() self.webSocket.delegate = self self.webSocket.open() } /** Creates a User instance from JSON. :param: json The JSON to parse. :returns: The User instance if valid, else nil. */ public func userFromJSON(json: JSON) -> User? { if let name = json["name"].string, phoneNumber = json["phoneNumber"].string { return User(name: name, phoneNumber: phoneNumber) } println("Something went wrong in \(__FUNCTION__) with JSON: \(json)") return nil } /** Creates a Message instance from JSON. :param: json The JSON to parse. :returns: The Message instance if valid, else nil. */ public func messageFromJSON(json: JSON) -> Message? { if let _from = json["from"].dictionary, _to = json["to"].dictionary, message = json["message"].string, timestamp = json["timestamp"].double { if let from = self.userFromDictionary(_from), let to = self.userFromDictionary(_to) { return Message(from: from, to: to, message: message, timestamp: timestamp) } } println("Something went wrong in \(__FUNCTION__) with JSON: \(json)") return nil } /** Creates a Location instance from JSON. :param: json The JSON to parse. :returns: The Location instance if valid, else nil. */ public func locationFromJSON(json: JSON) -> Location? { if let name = json["name"].string, ssid = json["ssid"].string, _vips = json["vips"].array { var vips = [VIP]() for vip in _vips { if let vipName = vip.string { vips.append(VIP(name: vipName)) } } return Location(name: name, ssid: ssid, vips: vips) } println("Something went wrong in \(__FUNCTION__) with JSON: \(json)") return nil } /** Creates JSON from a User instance. :param: location The User instance to convert to JSON. :returns: The JSON if valid, else nil. */ public func JSONFromUser(user: User) -> JSON? { return JSON(data: user.toJson()) } /** Creates JSON from a Message instance. :param: location The Message instance to convert to JSON. :returns: The JSON if valid, else nil. */ public func JSONFromMessage(message: Message) -> JSON? { return JSON(data: message.toJson()) } /** Creates JSON from a Location instance. :param: location The Location instance to convert to JSON. :returns: The JSON if valid, else nil. */ public func JSONFromLocation(location: Location) -> JSON? { return JSON(data: location.toJson()) } } extension JSONManager { /** Creates a User instance from a dictionary. :param: dictionary The dictionary to parse. :returns: The User instance if valid, else nil. */ private func userFromDictionary(dictionary: [String: JSON]) -> User? { if let name = dictionary["name"]!.string, phoneNumber = dictionary["phoneNumber"]!.string { return User(name: name, phoneNumber: phoneNumber) } return nil } } // MARK: - SRWebSocketDelegate extension JSONManager: SRWebSocketDelegate { public func webSocketDidOpen(webSocket: SRWebSocket!) { println("\(__FUNCTION__), webSocket: \(webSocket)") self.openSocket = true let thing = "{message: {From: {Name: \"Bas\", PhoneNumber: \"+31681789369\"}, Type: 0}}" webSocket.send("\(thing)") } public func webSocket(webSocket: SRWebSocket!, didReceiveMessage message: AnyObject!) { println("\(__FUNCTION__), message: \(message)") let messages = Testsetup().messages() let message1 = messages[0] webSocket.send("{message: {From: {Name: \"Bas\", PhoneNumber: \"+31681789369\"}, To: {Name: \"Joost\", PhoneNumber: \"+31652849963\"}, Type: 3}}") } public func webSocket(webSocket: SRWebSocket!, didFailWithError error: NSError!) { println("\(__FUNCTION__), error: \(error.localizedDescription)") } public func webSocket(webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) { println("\(__FUNCTION__), closeCode: \(code), reason: \(reason), wasClean: \(wasClean)") } }
32e350ae08fc57f1dc4b262ab7d7e47a
24.553672
148
0.669394
false
false
false
false
SemperIdem/SwiftMarkdownParser
refs/heads/master
Sources/WKWebView+Markdown.swift
mit
1
// // WKWebView+Markdown.swift // SwiftMarkdownParserExamples // // Created by Semper_Idem on 16/3/21. // Copyright © 2016年 星夜暮晨. All rights reserved. // import WebKit extension WKWebView { /// Load Markdown HTML String func loadMarkdownString(markdown: String, atBaseURL baseURL: NSURL? = nil, withStyleSheet sheet: String? = nil) { let URL = baseURL ?? NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath) let html = MarkdownParse.convertMarkdownString(markdown) let fullHTMLPage: String if let sheet = sheet { fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><style type=\"text/css\">\(sheet)</style></head><body>\(html)</body></html>" } else { fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><style type=\"text/css\">body { font-family:sans-serif; font-size:10pt; }</style></head><body>\(html)</body></html>" } loadHTMLString(fullHTMLPage, baseURL: URL) } /// Load Markdown HTML String func loadMarkdownString(markdown: String, atBaseURL baseURL: NSURL? = nil, withStylesheetFile filename: String, andSurroundedByHTML surround: String? = nil) { let URL = baseURL ?? NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath) let html = MarkdownParse.convertMarkdownString(markdown) let fullHTMLPage: String if let surround = surround { fullHTMLPage = surround + filename + html } else { fullHTMLPage = "<html><head><meta name=\"viewport\" content=\"width=device-width\"><link rel=\"stylesheet\" href=\"\(filename)\" /></head><body>\(html)</body></html>" } loadHTMLString(fullHTMLPage, baseURL: URL) } }
591058f9c9c0e065456f0f587810d1cc
41.302326
211
0.636964
false
false
false
false
Nexmind/Swiftizy
refs/heads/master
Swiftizy/Classes/Manager/Counting.swift
mit
1
// // Counting.swift // Pods // // Created by Julien Henrard on 2/05/16. // // import Foundation import CoreData public class Counting { var managedContext : NSManagedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) init(context: NSManagedObjectContext) { self.managedContext = context } public func all(entity: AnyClass) -> Int { let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: NSStringFromClass(entity).pathExtension) request.includesSubentities = false do { let count: Int = try self.managedContext.count(for: request) if(count == NSNotFound) { return 0 } return count } catch { return 0 } } public func custom(entity: AnyClass, predicate: NSPredicate) -> Int{ let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: NSStringFromClass(entity).pathExtension) request.predicate = predicate request.includesSubentities = false do { let count: Int = try self.managedContext.count(for: request) if(count == NSNotFound) { return 0 } return count } catch { return 0 } } }
3955d1dfe3b5f4144eac4774842e5592
26.5
127
0.598545
false
false
false
false
tomkowz/Swifternalization
refs/heads/master
Swifternalization/InequalityExpressionParser.swift
mit
1
// // InequalityExpressionParser.swift // Swifternalization // // Created by Tomasz Szulc on 27/06/15. // Copyright (c) 2015 Tomasz Szulc. All rights reserved. // import Foundation /** Parses inequality expression patterns. e.g. `ie:x=5`. */ class InequalityExpressionParser: ExpressionParser { /** A pattern of expression. */ let pattern: ExpressionPattern /** Initializes parser. :param: pattern A pattern that will be parsed. */ required init(_ pattern: ExpressionPattern) { self.pattern = pattern } /** Parses `pattern` passed during initialization. :returns: `ExpressionMatcher` object or nil if pattern cannot be parsed. */ func parse() -> ExpressionMatcher? { if let sign = sign(), let value = value() { return InequalityExpressionMatcher(sign: sign, value: value) } return nil } /** Get mathematical inequality sign. :returns: `InequalitySign` or nil if sign cannot be found. */ private func sign() -> InequalitySign? { return getSign(ExpressionPatternType.Inequality.rawValue+":x(<=|<|=|>=|>)", failureMessage: "Cannot find any sign", capturingGroupIdx: 1) } /** Get value - Double. :returns: value or nil if value cannot be found */ private func value() -> Double? { return getValue(ExpressionPatternType.Inequality.rawValue+":x[^-\\d]{1,2}(-?\\d+[.]{0,1}[\\d]{0,})", failureMessage: "Cannot find any value", capturingGroupIdx: 1) } // MARK: Helpers /** Get value with regex and prints failure message if not found. :param: regex A regular expression. :param: failureMessage A message that is printed out in console on failure. :returns: A value or nil if value cannot be found. */ func getValue(_ regex: String, failureMessage: String, capturingGroupIdx: Int? = nil) -> Double? { if let value = Regex.matchInString(pattern, pattern: regex, capturingGroupIdx: capturingGroupIdx) { return NSString(string: value).doubleValue } else { print("\(failureMessage), pattern: \(pattern), regex: \(regex)") return nil } } /** Get sign with regex and prints failure message if not found. :param: regex A regular expression. :param: failureMessage A message that is printed out in console on failure. :returns: A sign or nil if value cannot be found. */ func getSign(_ regex: String, failureMessage: String, capturingGroupIdx: Int? = nil) -> InequalitySign? { if let rawValue = Regex.matchInString(pattern, pattern: regex, capturingGroupIdx: capturingGroupIdx), let sign = InequalitySign(rawValue: rawValue) { return sign } else { print("\(failureMessage), pattern: \(pattern), regex: \(regex)") return nil } } }
912497ac7fb984c69c7db6a440b21c18
29.989583
171
0.621176
false
false
false
false
hryk224/IPhotoBrowser
refs/heads/master
IPhotoBrowserExample/IPhotoBrowserExample/Sources/View/TableViewCell/WebImageTableViewCell.swift
mit
1
// // WebImageTableViewCell.swift // IPhotoBrowserExample // // Created by yoshida hiroyuki on 2017/02/16. // Copyright © 2017年 hryk224. All rights reserved. // import UIKit.UITableViewCell final class WebImageTableViewCell: UITableViewCell { private static let className: String = "WebImageTableViewCell" static var identifier: String { return className } static var nib: UINib { return UINib(nibName: className, bundle: Bundle(for: self)) } @IBOutlet weak var webImageView: UIImageView! @IBOutlet weak var indicatorView: UIActivityIndicatorView! private var imageUrl: URL? override func awakeFromNib() { super.awakeFromNib() selectionStyle = .none } override func prepareForReuse() { super.prepareForReuse() webImageView.image = nil } func configure(imageUrl: URL) { self.imageUrl = imageUrl self.indicatorView.isHidden = false webImageView.loadWebImage(imageUrl: imageUrl) { [weak self] image, imageUrl in guard self?.imageUrl?.absoluteString == imageUrl.absoluteString else { return } self?.webImageView.image = image self?.indicatorView.isHidden = true self?.setNeedsLayout() self?.layoutIfNeeded() } } }
a624d649607dfc98f780b92b3e0acf75
31
91
0.664634
false
false
false
false
daher-alfawares/model
refs/heads/master
Model/Model/Notifier.swift
apache-2.0
1
// // ModelNotifier.swift // Model // // Created by Brandon Chow on 5/13/16. // Copyright © 2016 Brandon Chow, 2016 Daher Alfawares. All rights reserved. // import Foundation public class Notifier { static let sharedInstance = Notifier() private var listenerGroups = [String : WeakRef<ListenerGroup>]() public func notify(newModel model: Model) { listenerGroups[model.key()]?.reference?.notify(newModel: model) } internal func addListener(listener: Listener, forModelType modelType: Model.Type){ let modelTypeKey = "\(modelType)" let group = groupFor(modelTypeKey) group.add(listener) listener.group = group } private func groupFor(modelTypeKey: String) -> ListenerGroup { if let group = listenerGroups[modelTypeKey]?.reference { return group } else { let group = ListenerGroup(key: modelTypeKey) listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group) return group } } private func addListenerToNewGroup(newListener: Listener, forModelTypeKey modelTypeKey: String){ let group = ListenerGroup(key: modelTypeKey) newListener.group = group listenerGroups[modelTypeKey] = WeakRef<ListenerGroup>(ref: group) group.add(newListener) } internal func remove(listenerGroup : ListenerGroup) { listenerGroups.removeValueForKey(listenerGroup.key) } }
048f4f0484abfcfd341988c02f59096c
29
100
0.653333
false
false
false
false
ryanorendorff/tablescope
refs/heads/develop
tablescope/ViewController.swift
gpl-3.0
1
// // ViewController.swift // tablescope // // Created by Ryan Orendorff on 6/2/15. // Copyright (c) 2015 cellscope. All rights reserved. // // TODO: Make this not backwards (specify start time as the start of the // day mode instead of the start of the night mode). // Taken from the tutorial at // jamesonquave.com/blog/ // taking-control-of-the-iphone-camera-in-ios-8-with-swift-part-1/ import UIKit import AVFoundation let day_in_sec : NSTimeInterval = 86400 let sleepTimeStart = (hour: 17, minute: 30) let sleepTimeStop = (hour: 8, minute: 30) class ViewController: UIViewController { var startToday : NSDate? var stopToday : NSDate? let captureSession = AVCaptureSession() var previewLayer : AVCaptureVideoPreviewLayer? // If we find a device we'll store it here for later use var captureDevice : AVCaptureDevice? override func viewDidLoad() -> Void { super.viewDidLoad() // Do any additional setup after loading the view. captureSession.sessionPreset = AVCaptureSessionPresetHigh let devices = AVCaptureDevice.devices() // Loop through all the capture devices on this phone for device in devices { // Make sure this particular device supports video if (device.hasMediaType(AVMediaTypeVideo)) { // Check the position and confirm we've got the back camera if(device.position == AVCaptureDevicePosition.Back) { captureDevice = device as? AVCaptureDevice if captureDevice != nil { captureSession.sessionPreset = AVCaptureSessionPresetPhoto do { try captureSession.addInput( AVCaptureDeviceInput(device: captureDevice)) } catch { print("error initializing device") } } } } } // Disable the screen lock from occurring. UIApplication.sharedApplication().idleTimerDisabled = true assert(sleepTimeStart.hour > sleepTimeStop.hour || (sleepTimeStart.hour == sleepTimeStop.hour && sleepTimeStart.minute > sleepTimeStop.minute), "Sleep start and stop are in the wrong order!") // When starting the app, we are going to figure out if we are // in a night session time or a day session time. let now = NSDate() setStartStopDate(now) // TODO: If we switch to Swift 1.2+, use the late binding let // instead of var. // // Here we will start the manipulations of the [start/stop]Today // dates to reflect the correct days to trigger on. This case // corresponds to being in the morning night session. var startDate = startToday! var stopDate = stopToday! // Figure out if we are in a day or night session, and start the // app in the correct configuration when first launched. if now < startToday && now >= stopToday { daySession() // We are during the day so we need to move the stop date to // trigger tomorrow for the first time (today's time has passed) stopDate = stopToday!.dateByAddingTimeInterval(day_in_sec) } else { nightSession() // We are during the later night period so we need to move both // the start and the stop stop date to trigger tomorrow for the // first time (today's time has passed) if now >= startToday { startDate = startToday!.dateByAddingTimeInterval(day_in_sec) stopDate = stopToday!.dateByAddingTimeInterval(day_in_sec) } } // Finally set the timers. Timer.scheduledTimerWithTimeInterval( startDate, interval: day_in_sec, repeats: true, f: { self.nightSession() }) Timer.scheduledTimerWithTimeInterval( stopDate, interval: day_in_sec, repeats: true, f: { self.daySession() }) // If we press down on the screen for 2 seconds switch current // mode let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPress:") longPressRecognizer.minimumPressDuration = 2.0 self.view.addGestureRecognizer(longPressRecognizer) } // end viewDidLoad // Session modes func daySession() -> Void { UIScreen.mainScreen().brightness = CGFloat(1) if !captureSession.running{ previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) //previewLayer?.transform = CATransform3DMakeScale(-1, -1, 1) self.view.layer.addSublayer(previewLayer!) previewLayer?.frame = self.view.layer.frame captureSession.startRunning() } } func nightSession() -> Void { UIScreen.mainScreen().brightness = CGFloat(0) if captureSession.running{ self.previewLayer?.removeFromSuperlayer() captureSession.stopRunning() } } func switchSession() -> Void { if !captureSession.running{ daySession() } else { nightSession() } } // Used by the long press to switch the session mode func longPress(sender: UILongPressGestureRecognizer) { if sender.state == UIGestureRecognizerState.Began { switchSession() } } func modeWakeUpFromBackground(){ let now = NSDate() if now < startToday && now >= stopToday { daySession() } else { nightSession() } } func setStartStopDate(now : NSDate) { let calendar = NSCalendar( calendarIdentifier: NSCalendarIdentifierGregorian) // The components and [start/stop]Today are specified for a start // and stop time that are both in the current day. This situation // only occurs if we are before the stop time on the current day. // Otherwise we will need to either add a day to the start or the // end dates in order to trigger them correctly. let start_components = calendar!.components([.Year, .Month, .Day], fromDate: now) start_components.hour = sleepTimeStart.hour start_components.minute = sleepTimeStart.minute self.startToday = calendar!.dateFromComponents(start_components) let stop_components = calendar!.components([.Year, .Month, .Day], fromDate: startToday!) stop_components.hour = sleepTimeStop.hour stop_components.minute = sleepTimeStop.minute self.stopToday = calendar!.dateFromComponents(stop_components) } }
c2788f953529d502dc16f68b972be022
32.736585
76
0.607577
false
false
false
false
itaen/30DaysSwift
refs/heads/master
001_StopWatch/StopWatch/StopWatch/AppDelegate.swift
mit
1
// // AppDelegate.swift // StopWatch // // Created by itaen on 13/07/2017. // Copyright © 2017 itaen. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "StopWatch") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
6df4131bce8d642bc7339874a4a7b8ad
48.27957
285
0.685577
false
false
false
false
Jpoliachik/DroidconBoston-iOS
refs/heads/master
DroidconBoston/Pods/XLPagerTabStrip/Sources/SegmentedPagerTabStripViewController.swift
apache-2.0
6
// SegmentedPagerTabStripViewController.swift // XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip ) // // Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public struct SegmentedPagerTabStripSettings { public struct Style { public var segmentedControlColor: UIColor? } public var style = Style() } open class SegmentedPagerTabStripViewController: PagerTabStripViewController, PagerTabStripDataSource, PagerTabStripDelegate { @IBOutlet weak public var segmentedControl: UISegmentedControl! open var settings = SegmentedPagerTabStripSettings() public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) pagerBehaviour = PagerTabStripBehaviour.common(skipIntermediateViewControllers: true) delegate = self datasource = self } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) pagerBehaviour = PagerTabStripBehaviour.common(skipIntermediateViewControllers: true) delegate = self datasource = self } private(set) var shouldUpdateSegmentedControl = true open override func viewDidLoad() { super.viewDidLoad() segmentedControl = segmentedControl ?? UISegmentedControl() if segmentedControl.superview == nil { navigationItem.titleView = segmentedControl } segmentedControl.tintColor = settings.style.segmentedControlColor ?? segmentedControl.tintColor segmentedControl.addTarget(self, action: #selector(SegmentedPagerTabStripViewController.segmentedControlChanged(_:)), for: .valueChanged) reloadSegmentedControl() } open override func reloadPagerTabStripView() { super.reloadPagerTabStripView() if isViewLoaded { reloadSegmentedControl() } } func reloadSegmentedControl() { segmentedControl.removeAllSegments() for (index, item) in viewControllers.enumerated(){ let child = item as! IndicatorInfoProvider if let image = child.indicatorInfo(for: self).image { segmentedControl.insertSegment(with: image, at: index, animated: false) } else { segmentedControl.insertSegment(withTitle: child.indicatorInfo(for: self).title, at: index, animated: false) } } segmentedControl.selectedSegmentIndex = currentIndex } func segmentedControlChanged(_ sender: UISegmentedControl) { let index = sender.selectedSegmentIndex updateIndicator(for: self, fromIndex: currentIndex, toIndex: index) shouldUpdateSegmentedControl = false moveToViewController(at: index) } // MARK: - PagerTabStripDelegate open func updateIndicator(for viewController: PagerTabStripViewController, fromIndex: Int, toIndex: Int) { if shouldUpdateSegmentedControl { segmentedControl.selectedSegmentIndex = toIndex } } // MARK: - UIScrollViewDelegate open override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { super.scrollViewDidEndScrollingAnimation(scrollView) shouldUpdateSegmentedControl = true } }
224c08d7821aee6b3ced8090bdda5a4d
38.75
145
0.709119
false
false
false
false
baiyidjp/SwiftWB
refs/heads/master
SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/SwiftExtension/UIPageControl+Extensions.swift
mit
1
// // UIPageControl+Extensions.swift // SwiftWeibo // // Created by tztddong on 2016/11/28. // Copyright © 2016年 dongjiangpeng. All rights reserved. // import Foundation extension UIPageControl { /// UIPageControl /// /// - Parameters: /// - frame: 布局 /// - numberOfPages: 总页数 /// - currentPage: 当前页数 /// - pageIndicatorTintColor: 未选中页颜色 /// - currentPageIndicatorTintColor: 当前选中页颜色 convenience init(numberOfPages: Int = 0,currentPage: Int = 0,pageIndicatorTintColor: UIColor = UIColor.black,currentPageIndicatorTintColor :UIColor = UIColor.orange) { self.init() self.numberOfPages = numberOfPages self.currentPage = currentPage self.pageIndicatorTintColor = pageIndicatorTintColor self.currentPageIndicatorTintColor = currentPageIndicatorTintColor } }
00a93f0e3aca08f2613c5f2795683a8d
28.482759
171
0.681871
false
false
false
false
burtherman/StreamBaseKit
refs/heads/master
StreamBaseExample/StreamBaseExample/Environment.swift
mit
2
// // Environment.swift // StreamBaseExample // // Created by Steve Farrell on 9/14/15. // Copyright (c) 2015 Movem3nt. All rights reserved. // import Foundation import Firebase import StreamBaseKit class Environment { let resourceBase: ResourceBase static let sharedEnv: Environment = { let firebase = Firebase(url: "https://streambase-example.firebaseio.com") let resourceBase = ResourceBase(firebase: firebase) let registry: ResourceRegistry = resourceBase registry.resource(Message.self, path: "/message/@") return Environment(resourceBase: resourceBase) }() init(resourceBase: ResourceBase) { self.resourceBase = resourceBase } }
6163f346d6c1cbeff019bd24d053282f
24.413793
81
0.672554
false
false
false
false
tresorit/ZeroKit-Realm-encrypted-tasks
refs/heads/master
ios/RealmTasks iOS/AccountViewController.swift
bsd-3-clause
1
import UIKit import RealmSwift import ZeroKit class AccountViewController: UIViewController { @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var zeroKitIdLabel: UILabel! @IBOutlet weak var realmIdLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() self.title = "Account" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.usernameLabel.text = nil self.zeroKitIdLabel.text = nil ZeroKitManager.shared.backend.getProfile { profile, _ in if let profile = profile, let profileData = profile.data(using: .utf8), let json = (try? JSONSerialization.jsonObject(with: profileData, options: [])) as? [String: Any] { self.usernameLabel.text = json[ProfileField.alias.rawValue] as? String } else { self.usernameLabel.text = nil } } ZeroKitManager.shared.zeroKit.whoAmI { (userId, _) in self.zeroKitIdLabel.text = userId } realmIdLabel.text = SyncUser.current?.identity } @IBAction func logoutButtonTapped(sender: UIButton) { let alert = UIAlertController(title: "Log out?", message: nil, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Log out", style: .default, handler: { _ in (UIApplication.shared.delegate as! AppDelegate).logOut() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } }
82f6b9f3f91f11fe5e8633086b3e0351
33.659574
114
0.635359
false
false
false
false
IBAnimatable/IBAnimatable
refs/heads/master
Sources/Enums/BorderSide.swift
mit
2
// // Created by Jake Lin on 12/9/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import Foundation public enum BorderSide: String { case top case right case bottom case left } public struct BorderSides: OptionSet { public let rawValue: Int public static let unknown = BorderSides(rawValue: 0) public static let top = BorderSides(rawValue: 1) public static let right = BorderSides(rawValue: 1 << 1) public static let bottom = BorderSides(rawValue: 1 << 2) public static let left = BorderSides(rawValue: 1 << 3) public static let AllSides: BorderSides = [.top, .right, .bottom, .left] public init(rawValue: Int) { self.rawValue = rawValue } init(rawValue: String?) { guard let rawValue = rawValue, !rawValue.isEmpty else { self = .AllSides return } let sideElements = rawValue.lowercased().split(separator: ",") .map(String.init) .map { BorderSide(rawValue: $0.trimmingCharacters(in: CharacterSet.whitespaces)) } .map { BorderSides(side: $0) } guard !sideElements.contains(.unknown) else { self = .AllSides return } self = BorderSides(sideElements) } init(side: BorderSide?) { guard let side = side else { self = .unknown return } switch side { case .top: self = .top case .right: self = .right case .bottom: self = .bottom case .left: self = .left } } }
f8b8c9e156131ff626a97d5567a8b944
21.714286
88
0.6471
false
false
false
false
Eonil/EditorLegacy
refs/heads/trial1
Modules/Editor/Sources/Documents/RustProjectDocument.swift
mit
1
//// //// RustProjectDocument.swift //// RustCodeEditor //// //// Created by Hoon H. on 11/11/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation //import AppKit //import PrecompilationOfExternalToolSupport // //class RustProjectDocument : NSDocument { // let projectWindowController = PlainFileFolderWindowController() // let programExecutionController = RustProgramExecutionController() // // override func makeWindowControllers() { // super.makeWindowControllers() // self.addWindowController(projectWindowController) // } // // override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? { // let s1 = projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string! // let d1 = s1.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! // return d1 // } // // override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool { // let s1 = NSString(data: data, encoding: NSUTF8StringEncoding)! // projectWindowController.codeEditingViewController.codeTextViewController.codeTextView.string = s1 //// let p2 = self.fileURL!.path! //// let p3 = p2.stringByDeletingLastPathComponent //// projectWindowController.mainViewController.navigationViewController.fileTreeViewController.pathRepresentation = p3 // // let u2 = self.fileURL!.URLByDeletingLastPathComponent // projectWindowController.mainViewController.navigationViewController.fileTreeViewController.URLRepresentation = u2 // return true // } // // // // override func saveDocument(sender: AnyObject?) { // // Do not route save messages to current document. // // Saving of a project will be done at somewhere else, and this makes annoying alerts. // /// This prevents the alerts. //// super.saveDocument(sender) // // projectWindowController.codeEditingViewController.trySavingInPlace() // } // // // // // // override class func autosavesInPlace() -> Bool { // return false // } //} // //extension RustProjectDocument { // // @IBAction // func menuProjectRun(sender:AnyObject?) { // if let u1 = self.fileURL { // self.saveDocument(self) // let srcFilePath1 = u1.path! // let srcDirPath1 = srcFilePath1.stringByDeletingLastPathComponent // let outFilePath1 = srcDirPath1.stringByAppendingPathComponent("program.executable") // let conf1 = RustProgramExecutionController.Configuration(sourceFilePaths: [srcFilePath1], outputFilePath: outFilePath1, extraArguments: ["-Z", "verbose"]) // // let s1 = mainEditorWindowController.splitter.codeEditingViewController.textViewController.textView.string! // let r1 = programExecutionController.execute(conf1) // projectWindowController.commandConsoleViewController.textView.string = r1 // // let ss1 = RustCompilerIssueParsing.process(r1, sourceFilePath: srcFilePath1) // projectWindowController.mainViewController.navigationViewController.issueListingViewController.issues = ss1 // // } else { // NSAlert(error: NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "This file has not been save yet. Cannot compile now."])).runModal() // } // } // //} // // //
d7a487c4b0b238b81c2d7979d2bd34c4
36.588235
161
0.746792
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/Authentication/Event Handlers/Post-Login/Backup/AuthenticationBackupReadyEventHandler.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireCommonComponents import WireSyncEngine /** * Handles the notification informing the user that backups are ready to be imported. */ final class AuthenticationBackupReadyEventHandler: AuthenticationEventHandler { weak var statusProvider: AuthenticationStatusProvider? func handleEvent(currentStep: AuthenticationFlowStep, context: Bool) -> [AuthenticationCoordinatorAction]? { let existingAccount = context // Automatically complete the backup for @fastLogin automation guard AutomationHelper.sharedHelper.automationEmailCredentials == nil else { return [.showLoadingView, .configureNotifications, .completeBackupStep] } // Get the signed-in user credentials let authenticationCredentials: ZMCredentials? switch currentStep { case .authenticateEmailCredentials(let credentials): authenticationCredentials = credentials case .authenticatePhoneCredentials(let credentials): authenticationCredentials = credentials case .companyLogin: authenticationCredentials = nil case .noHistory: return [.hideLoadingView] default: return nil } // Prepare the backup step let context: NoHistoryContext = existingAccount ? .loggedOut : .newDevice let nextStep = AuthenticationFlowStep.noHistory(credentials: authenticationCredentials, context: context) return [.hideLoadingView, .transition(nextStep, mode: .reset)] } }
f4cb253c9fda20c223e57e2a1bb79498
35.451613
113
0.720354
false
false
false
false
zhubofei/IGListKit
refs/heads/master
Examples/Examples-macOS/IGListKitExamples/Helpers/UsersProvider.swift
mit
1
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation final class UsersProvider { enum UsersError: Error { case invalidData } let users: [User] init(with file: URL) throws { let data = try Data(contentsOf: file) let json = try JSONSerialization.jsonObject(with: data, options: []) guard let dicts = json as? [[String: String]] else { throw UsersError.invalidData } self.users = dicts.enumerated().compactMap { index, dict in guard let name = dict["name"] else { return nil } return User(pk: index, name: name.capitalized) }.sorted(by: { $0.name < $1.name }) } }
318974585f98876c65bd1542d746d8d8
31.9
80
0.68693
false
false
false
false
gitkong/FLTableViewComponent
refs/heads/master
FLComponentDemo/FLComponentDemo/FLCollectionViewHandler.swift
mit
2
// // FLCollectionViewHandler.swift // FLComponentDemo // // Created by 孔凡列 on 2017/6/19. // Copyright © 2017年 YY Inc. All rights reserved. // import UIKit @objc protocol FLCollectionViewHandlerDelegate { @objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, itemAt indexPath : IndexPath) @objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, headerAt section : NSInteger) @objc optional func collectionViewDidClick(_ handler : FLCollectionViewHandler, footerAt section : NSInteger) } class FLCollectionViewHandler: NSObject { private(set) lazy var componentsDict : NSMutableDictionary = { return NSMutableDictionary.init() }() var components : Array<FLCollectionBaseComponent> = [] { didSet { self.collectionView?.handler = self componentsDict.removeAllObjects() for section in 0..<components.count { let component = components[section] component.section = section // same key will override the old value, so the last component will alaways remove first componentsDict.setValue(component, forKey: component.componentIdentifier) } } } var delegate : FLCollectionViewHandlerDelegate? var collectionView : UICollectionView? { return components.first?.collectionView } } // Mark : component control extension FLCollectionViewHandler : FLCollectionViewHandlerProtocol { func component(at index : NSInteger) -> FLCollectionBaseComponent? { guard components.count > 0, index < components.count else { return nil } return components[index] } func exchange(_ component : FLCollectionBaseComponent, by exchangeComponent : FLCollectionBaseComponent) { self.components.exchange(component.section!, by: exchangeComponent.section!) } func replace(_ component : FLCollectionBaseComponent, by replacementComponent : FLCollectionBaseComponent) { self.components.replaceSubrange(component.section!...component.section!, with: [replacementComponent]) } func addAfterIdentifier(_ component : FLCollectionBaseComponent, after identifier : String) { if let afterComponent = self.component(by: identifier) { self.addAfterComponent(component, after: afterComponent) } } func addAfterComponent(_ component : FLCollectionBaseComponent, after afterComponent : FLCollectionBaseComponent) { self.addAfterSection(component, after: afterComponent.section!) } func addAfterSection(_ component : FLCollectionBaseComponent, after index : NSInteger) { guard components.count > 0, index < components.count else { return } self.components.insert(component, at: index) } func add(_ component : FLCollectionBaseComponent) { guard components.count > 0 else { return } self.components.append(component) } func removeComponent(by identifier : String, removeType : FLComponentRemoveType) { guard components.count > 0 else { return } if let component = self.component(by: identifier) { self.componentsDict.removeObject(forKey: identifier) if removeType == .All { self.components = self.components.filter({ $0 != component }) } else if removeType == .Last { self.removeComponent(component) } } } func removeComponent(_ component : FLCollectionBaseComponent?) { guard component != nil else { return } self.removeComponent(at: component!.section!) } func removeComponent(at index : NSInteger) { guard index < components.count else { return } self.components.remove(at: index) } func reloadComponents() { self.collectionView?.reloadData() } func reloadComponents(_ components : [FLCollectionBaseComponent]) { guard self.components.count > 0, components.count <= self.components.count else { return } for component in components { self.reloadComponent(at: component.section!) } } func reloadComponent(_ component : FLCollectionBaseComponent) { self.reloadComponent(at: component.section!) } func reloadComponent(at index : NSInteger) { guard components.count > 0, index < components.count else { return } self.collectionView?.reloadSections(IndexSet.init(integer: index)) } func component(by identifier : String) -> FLCollectionBaseComponent? { guard componentsDict.count > 0, !identifier.isEmpty else { return nil } return componentsDict.value(forKey: identifier) as? FLCollectionBaseComponent } } // MARK : dataSources customizaion extension FLCollectionViewHandler : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{ final func numberOfSections(in collectionView: UICollectionView) -> Int { return components.count } final func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard components.count > 0 else { return 0 } return components[section].numberOfItems() } final func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard components.count > 0 else { return UICollectionViewCell() } let component : FLCollectionBaseComponent = components[indexPath.section] component.section = indexPath.section return component.cellForItem(at: indexPath.item) } } // MARK : display method customizaion extension FLCollectionViewHandler : UICollectionViewDelegate { final func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard components.count > 0, indexPath.section < components.count else { return } components[indexPath.section].collectionView(willDisplayCell: cell, at: indexPath.item) } final func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard components.count > 0, indexPath.section < components.count else { return } components[indexPath.section].collectionView(didEndDisplayCell: cell, at: indexPath.item) } final func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { guard components.count > 0, indexPath.section < components.count else { return } components[indexPath.section].collectionView(willDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind) } final func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath){ guard components.count > 0, indexPath.section < components.count else { return } components[indexPath.section].collectionView(didEndDisplayView: view as! FLCollectionHeaderFooterView, viewOfKind: elementKind) } } // MARK : header or footer customizaion extension FLCollectionViewHandler { final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { guard components.count > 0, section < components.count else { return CGSize.zero } return CGSize.init(width: collectionView.bounds.size.width, height: components[section].heightForHeader()) } final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { guard components.count > 0, section < components.count else { return CGSize.zero } return CGSize.init(width: collectionView.bounds.size.width, height: components[section].heightForFooter()) } final func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { guard components.count > 0, indexPath.section < components.count else { return UICollectionReusableView() } let component = components[indexPath.section] let headerFooterView :FLCollectionHeaderFooterView = component.collectionView(viewOfKind: kind) headerFooterView.delegate = self headerFooterView.section = indexPath.section // add gesture let tapG : UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(self.headerFooterDidClick)) headerFooterView.addGestureRecognizer(tapG) return headerFooterView } func headerFooterDidClick(GesR : UIGestureRecognizer) { let headerFooterView : FLCollectionHeaderFooterView = GesR.view as! FLCollectionHeaderFooterView guard let identifierType = FLIdentifierType.type(of: headerFooterView.reuseIdentifier) , let section = headerFooterView.section else { return } switch identifierType { case .Header: self.collectionHeaderView(headerFooterView, didClickSectionAt: section) case .Footer: self.collectionFooterView(headerFooterView, didClickSectionAt: section) default : break } } } // MARK : layout customization extension FLCollectionViewHandler { final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard components.count > 0, indexPath.section < components.count else { return CGSize.zero } var size : CGSize = components[indexPath.section].sizeForItem(at: indexPath.item) if size == .zero { if self.collectionView?.collectionViewLayout is FLCollectionViewFlowLayout { let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout size = flowLayout.itemSize } else { size = (collectionViewLayout.layoutAttributesForItem(at: indexPath) != nil) ? collectionViewLayout.layoutAttributesForItem(at: indexPath)!.size : CGSize.zero } } return size } final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { guard components.count > 0, section < components.count else { return UIEdgeInsets.zero } let inset : UIEdgeInsets = components[section].sectionInset() // set sectionInset, because custom flowLayout can not get that automatily if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout { flowLayout.sectionInsetArray.append(inset) } return inset } final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { guard components.count > 0, section < components.count else { return 0 } let minimumLineSpacing : CGFloat = components[section].minimumLineSpacing() // set minimumLineSpacing, because custom flowLayout can not get that automatily if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout { flowLayout.minimumLineSpacingArray.append(minimumLineSpacing) } return minimumLineSpacing } final func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { guard components.count > 0, section < components.count else { return 0 } let minimumInteritemSpacing : CGFloat = components[section].minimumInteritemSpacing() // set minimumInteritemSpacing, because custom flowLayout can not get that automatily if let flowLayout = self.collectionView?.collectionViewLayout as? FLCollectionViewFlowLayout { flowLayout.minimumInteritemSpacingArray.append(minimumInteritemSpacing) } return minimumInteritemSpacing } } // MARK : Managing Actions for Cells extension FLCollectionViewHandler { final func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { guard components.count > 0, indexPath.section < components.count else { return false } return components[indexPath.section].shouldShowMenu(at: indexPath.item) } final func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { guard components.count > 0, indexPath.section < components.count else { return false } return components[indexPath.section].canPerform(selector: action, forItemAt: indexPath.item, withSender: sender) } func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { guard components.count > 0, indexPath.section < components.count else { return } components[indexPath.section].perform(selector: action, forItemAt: indexPath.item, withSender: sender) } } // MARK :Event extension FLCollectionViewHandler : FLCollectionComponentEvent { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { self.delegate?.collectionViewDidClick?(self, itemAt: indexPath) } func collectionHeaderView(_ headerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) { self.delegate?.collectionViewDidClick?(self, headerAt: section) } func collectionFooterView(_ footerView: FLCollectionHeaderFooterView, didClickSectionAt section: Int) { self.delegate?.collectionViewDidClick?(self, footerAt: section) } }
8c7523a9f74c46d944231621018ca338
40.706704
195
0.688835
false
false
false
false
Stitch7/Instapod
refs/heads/master
Instapod/Player/Remote/ProgressSlider/PlayerRemoteProgressSliderScrubbingSpeed.swift
mit
1
// // PlayerRemoteProgressSliderScrubbingSpeed.swift // Instapod // // Created by Christopher Reitz on 16.04.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit enum PlayerRemoteProgressSliderScrubbingSpeed: Float { case high = 1.0 case half = 0.5 case slow = 0.25 case fine = 0.1 var allValues: [PlayerRemoteProgressSliderScrubbingSpeed] { return [ .high, .half, .slow, .fine, ] } var stringValue: String { // TODO: i18n switch self { case .high: return "High-Speed Scrubbing" case .half: return "Half-Speed Scrubbing" case .slow: return "Quarter-Speed Scrubbing" case .fine: return "Fine Scrubbing" } } var offset: Float { switch self { case .high: return 0.0 case .half: return 50.0 case .slow: return 150.0 case .fine: return 225.0 } } var offsets: [Float] { var offsets = [Float]() for value in allValues { offsets.append(value.offset) } return offsets } func lowerScrubbingSpeed(forOffset offset: CGFloat) -> PlayerRemoteProgressSliderScrubbingSpeed? { var lowerScrubbingSpeedIndex: Int? for (i, scrubbingSpeedOffset) in self.offsets.enumerated() { if Float(offset) > scrubbingSpeedOffset { lowerScrubbingSpeedIndex = i } } if let newScrubbingSpeedIndex = lowerScrubbingSpeedIndex { if self != allValues[newScrubbingSpeedIndex] { return allValues[newScrubbingSpeedIndex] } } return nil } }
53b0e484cb5dec703a170e71c5f59d4a
24.115942
102
0.579342
false
false
false
false
karstengresch/rw_studies
refs/heads/master
RWBooks/RWBooks/StatView.swift
unlicense
1
// // StatView.swift // MyStats3 // // Created by Main Account on 5/11/15. // Copyright (c) 2015 Razeware LLC. All rights reserved. // import UIKit @IBDesignable class StatView: UIView { let circleBackgroundLayer = CAShapeLayer() let circleForegroundLayer = CAShapeLayer() let percentLabel = UILabel() let captionLabel = UILabel() @IBInspectable var circleBackgroundColor: UIColor = UIColor.grayColor() { didSet { configure() } } @IBInspectable var circleForegroundColor: UIColor = UIColor.whiteColor() { didSet { configure() } } var range = CGFloat(10) var curValue = CGFloat(0) { didSet { // configure() animateCircle() } } let margin = CGFloat(10) override func awakeFromNib() { super.awakeFromNib() setup() configure() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() configure() } func setup() { // Setup circle background layer circleBackgroundLayer.lineWidth = CGFloat(20.0) circleBackgroundLayer.fillColor = UIColor.clearColor().CGColor circleBackgroundLayer.strokeEnd = 1 layer.addSublayer(circleBackgroundLayer) // Setup circle foreground layer circleForegroundLayer.lineWidth = CGFloat(20.0) circleForegroundLayer.fillColor = UIColor.clearColor().CGColor circleForegroundLayer.strokeEnd = 0 layer.addSublayer(circleForegroundLayer) // Setup percent label percentLabel.font = UIFont(name: "Avenir Next", size: 26) percentLabel.textColor = UIColor.whiteColor() percentLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(percentLabel) // Setup caption label captionLabel.font = UIFont(name: "Avenir Next", size: 26) captionLabel.text = "Chapters Read" captionLabel.textColor = UIColor.whiteColor() captionLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(captionLabel) // Setup constraints let percentLabelCenterX = NSLayoutConstraint(item: percentLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0) let percentLabelCenterY = NSLayoutConstraint(item: percentLabel, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: -margin) NSLayoutConstraint.activateConstraints([percentLabelCenterX, percentLabelCenterY]) let captionLabelCenterX = NSLayoutConstraint(item: captionLabel, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: -margin) let captionLabelBottomY = NSLayoutConstraint(item: captionLabel, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: -margin) NSLayoutConstraint.activateConstraints([captionLabelCenterX, captionLabelBottomY]) } func configure() { percentLabel.text = String(format: "%.0f/%.0f", curValue, range) circleBackgroundLayer.strokeColor = circleBackgroundColor.CGColor circleForegroundLayer.strokeColor = circleForegroundColor.CGColor } override func layoutSubviews() { super.layoutSubviews() setupShapeLayer(circleBackgroundLayer) setupShapeLayer(circleForegroundLayer) } func setupShapeLayer(shapeLayer: CAShapeLayer) { shapeLayer.frame = self.bounds let center = percentLabel.center let radius = CGFloat(CGRectGetWidth(self.bounds) * 0.35) let startAngle = DegreesToRadians(135.0) let endAngle = DegreesToRadians(45.0) let path = UIBezierPath(arcCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true) shapeLayer.path = path.CGPath } func animateCircle() { percentLabel.text = String(format: "%.0f/%.0f",curValue, range) // setup values var fromValue = circleForegroundLayer.strokeEnd let toValue = curValue / range if let _ = circleForegroundLayer.presentationLayer() as? CAShapeLayer { fromValue = (circleForegroundLayer.presentationLayer()?.strokeEnd)! } let percentageChange = abs(fromValue - toValue) // setup animation let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = fromValue animation.toValue = toValue animation.duration = CFTimeInterval(percentageChange * 4) circleForegroundLayer.removeAnimationForKey("stroke") circleForegroundLayer.addAnimation(animation, forKey: "stroke") CATransaction.begin() CATransaction.setDisableActions(true) circleForegroundLayer.strokeEnd = toValue CATransaction.commit() } }
9287923065c4563642993c19650eb8fa
31.622378
179
0.721484
false
false
false
false
jozsef-vesza/algorithms
refs/heads/master
Swift/Algorithms.playground/Pages/Sorting.xcplaygroundpage/Contents.swift
mit
1
import Foundation extension Array { func randomElement() -> Generator.Element { return self[Int(arc4random_uniform(UInt32(count)))] } } extension Array where Element: Comparable { func mergeWith(other:[Generator.Element]) -> [Generator.Element] { var output: [Generator.Element] = [] var leftIndex = startIndex var rightIndex = other.startIndex while leftIndex != endIndex && rightIndex != other.endIndex { let leftValue = self[leftIndex] let rightValue = other[rightIndex] if leftValue < rightValue { output.append(leftValue) leftIndex = leftIndex.successor() } else { output.append(rightValue) rightIndex = rightIndex.successor() } } output += self[leftIndex ..< endIndex] output += other[rightIndex ..< other.endIndex] return output } } extension CollectionType where Generator.Element: Comparable, Index.Distance == Int { func insertionSort() -> [Generator.Element] { var output = Array(self) for primaryIndex in 0 ..< output.count { let key = output[primaryIndex] for var secondaryIndex = primaryIndex; secondaryIndex > -1; secondaryIndex-- { if key < output[secondaryIndex] { output.removeAtIndex(secondaryIndex + 1) output.insert(key, atIndex: secondaryIndex) } } } return output } func selectionSort() -> [Generator.Element] { var output = Array(self) var indexOfSmallest = 0 for primaryIndex in 0 ..< output.count { indexOfSmallest = primaryIndex for secondaryIndex in primaryIndex + 1 ..< output.count { if output[secondaryIndex] < output[indexOfSmallest] { indexOfSmallest = secondaryIndex } } if primaryIndex != indexOfSmallest { swap(&output[primaryIndex], &output[indexOfSmallest]) } } return output } func bubbleSort() -> [Generator.Element] { var output = Array(self) var shouldRepeat = true while shouldRepeat { shouldRepeat = false for index in 1 ..< output.count { if output[index] < output[index - 1] { swap(&output[index], &output[index - 1]) shouldRepeat = true } } } return output } func mergeSort() -> [Generator.Element] { let arrayRepresentation = Array(self) if count < 2 { return arrayRepresentation } let middleIndex = count / 2 let left = arrayRepresentation[0 ..< middleIndex].mergeSort() let right = arrayRepresentation[middleIndex ..< count].mergeSort() return left.mergeWith(right) } func quickSort() -> [Generator.Element] { if self.count < 1 { return [] } let unsorted = Array(self) var less: [Generator.Element] = [] var more: [Generator.Element] = [] let pivot = unsorted.randomElement() for element in unsorted where element != pivot { if element < pivot { less.append(element) } else { more.append(element) } } return less.quickSort() + [pivot] + more.quickSort() } } let numbers = [9, 8, 7, 5, 6] let strings = ["gnu", "zebra", "antelope", "aardvark", "yak", "iguana"] let nums2 = numbers.insertionSort() let sortedStr2 = strings.insertionSort() let set = Set(numbers) let sortedSet = set.insertionSort() let selectionSortedNums = numbers.selectionSort() let selectionSortedStrings = strings.selectionSort() let bubbleSortedNums = numbers.bubbleSort() let mergeSortedNums = numbers.mergeSort() let quickSortedNums = numbers.quickSort() //: [Next](@next)
09e777cbff3bbfb953b7ce276465b921
25.885542
90
0.514452
false
false
false
false
cuzv/Redes
refs/heads/master
RedesSample/Helpers.swift
mit
1
// // Helpers.swift // Copyright (c) 2015-2016 Moch Xiao (http://mochxiao.com). // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Dictionary { /// URL query string. public var queryString: String { let mappedList = map { return "\($0.0)=\($0.1)" } return mappedList.sorted().joined(separator: "&") } } // MARK: - md5 // https://github.com/onevcat/Kingfisher/blob/master/Sources/String%2BMD5.swift public extension String { var md5: String { if let data = self.data(using: .utf8, allowLossyConversion: true) { let message = data.withUnsafeBytes { bytes -> [UInt8] in return Array(UnsafeBufferPointer(start: bytes, count: data.count)) } let MD5Calculator = MD5(message) let MD5Data = MD5Calculator.calculate() let MD5String = NSMutableString() for c in MD5Data { MD5String.appendFormat("%02x", c) } return MD5String as String } else { return self } } } /** array of bytes, little-endian representation */ func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] { let totalBytes = length ?? (MemoryLayout<T>.size * 8) let valuePointer = UnsafeMutablePointer<T>.allocate(capacity: 1) valuePointer.pointee = value let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in var bytes = [UInt8](repeating: 0, count: totalBytes) for j in 0..<min(MemoryLayout<T>.size, totalBytes) { bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee } return bytes } valuePointer.deinitialize() valuePointer.deallocate(capacity: 1) return bytes } extension Int { /** Array of bytes with optional padding (little-endian) */ func bytes(_ totalBytes: Int = MemoryLayout<Int>.size) -> [UInt8] { return arrayOfBytes(self, length: totalBytes) } } extension NSMutableData { /** Convenient way to append bytes */ func appendBytes(_ arrayOfBytes: [UInt8]) { append(arrayOfBytes, length: arrayOfBytes.count) } } protocol HashProtocol { var message: Array<UInt8> { get } /** Common part for hash calculation. Prepare header data. */ func prepare(_ len: Int) -> Array<UInt8> } extension HashProtocol { func prepare(_ len: Int) -> Array<UInt8> { var tmpMessage = message // Step 1. Append Padding Bits tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message // append "0" bit until message length in bits ≡ 448 (mod 512) var msgLength = tmpMessage.count var counter = 0 while msgLength % len != (len - 8) { counter += 1 msgLength += 1 } tmpMessage += Array<UInt8>(repeating: 0, count: counter) return tmpMessage } } func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> { var result = Array<UInt32>() result.reserveCapacity(16) for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) { let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 let d3 = UInt32(slice[idx]) let val: UInt32 = d0 | d1 | d2 | d3 result.append(val) } return result } struct BytesIterator: IteratorProtocol { let chunkSize: Int let data: [UInt8] init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } var offset = 0 mutating func next() -> ArraySlice<UInt8>? { let end = min(chunkSize, data.count - offset) let result = data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] func makeIterator() -> BytesIterator { return BytesIterator(chunkSize: chunkSize, data: data) } } func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) } class MD5: HashProtocol { static let size = 16 // 128 / 8 let message: [UInt8] init (_ message: [UInt8]) { self.message = message } /** specifies the per-round shift amounts */ private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] /** binary integer part of the sines of integers (Radians) */ private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] func calculate() -> [UInt8] { var tmpMessage = prepare(64) tmpMessage.reserveCapacity(tmpMessage.count + 4) // hash values var hh = hashes // Step 2. Append Length a 64-bit representation of lengthInBits let lengthInBits = (message.count * 8) let lengthBytes = lengthInBits.bytes(64 / 8) tmpMessage += lengthBytes.reversed() // Process the message in successive 512-bit chunks: let chunkSizeBytes = 512 / 8 // 64 for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 var M = toUInt32Array(chunk) assert(M.count == 16, "Invalid array") // Initialize hash value for this chunk: var A: UInt32 = hh[0] var B: UInt32 = hh[1] var C: UInt32 = hh[2] var D: UInt32 = hh[3] var dTemp: UInt32 = 0 // Main loop for j in 0 ..< sines.count { var g = 0 var F: UInt32 = 0 switch j { case 0...15: F = (B & C) | ((~B) & D) g = j break case 16...31: F = (D & B) | (~D & C) g = (5 * j + 1) % 16 break case 32...47: F = B ^ C ^ D g = (3 * j + 5) % 16 break case 48...63: F = C ^ (B | (~D)) g = (7 * j) % 16 break default: break } dTemp = D D = C C = B B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) A = dTemp } hh[0] = hh[0] &+ A hh[1] = hh[1] &+ B hh[2] = hh[2] &+ C hh[3] = hh[3] &+ D } var result = [UInt8]() result.reserveCapacity(hh.count / 4) hh.forEach { let itemLE = $0.littleEndian result += [UInt8(itemLE & 0xff), UInt8((itemLE >> 8) & 0xff), UInt8((itemLE >> 16) & 0xff), UInt8((itemLE >> 24) & 0xff)] } return result } }
bad9671d738164af86b015fa8f0af4ae
33.820069
133
0.530856
false
false
false
false
OpenMindBR/swift-diversidade-app
refs/heads/master
Diversidade/Address.swift
mit
1
// // Address.swift // Diversidade // // Created by Francisco José A. C. Souza on 07/04/16. // Copyright © 2016 Francisco José A. C. Souza. All rights reserved. // import UIKit class Address: NSObject { let line1: String let number: String let neighborhood: String let city: String let region: String let zip: String init(line1: String, number:String, neighborhood: String, city: String, region: String, zip: String) { self.line1 = line1 self.number = number self.neighborhood = neighborhood self.city = city self.region = region self.zip = zip } override var description: String { return "\(self.line1), \(self.number), \(self.neighborhood) \n \(self.city) - \(self.region)" } }
cbabd34fe24bb1e093a42231856b44e5
24
105
0.61375
false
false
false
false
pccole/GitHubJobs-iOS
refs/heads/master
GitHubJobs/PreviewContent/PreviewData.swift
mit
1
// // PreviewData.swift // GitHubJobs // // Created by Phil Cole on 4/22/20. // Copyright © 2020 Cole LLC. All rights reserved. // import Foundation public struct PreviewData { public static func load() -> [GithubJob] { let data: Data let filename = "Jobs.json" guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else { fatalError("Couldn't find \(filename) in main bundle.") } do { data = try Data(contentsOf: file) } catch { fatalError("Couldn't load \(filename) from main bundle:\n\(error)") } do { guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext else { fatalError("Failed to retrieve context") } let decoder = JSONDecoder() decoder.userInfo[codingUserInfoKeyManagedObjectContext] = DataStore.shared.persistentContainer.viewContext let json = try decoder.decode([GithubJob].self, from: data) // print(json) return json } catch { fatalError("Couldn't parse \(filename) as \([GithubJob].self):\n\(error)") } } }
2e9b76a0f09cc5f7a26906a102020e79
30.675
118
0.575375
false
false
false
false
SwiftKitz/Appz
refs/heads/master
Appz/AppzTests/AppsTests/InstagramTests.swift
mit
1
// // InstagramTests.swift // Appz // // Created by Suraj Shirvankar on 12/6/15. // Copyright © 2015 kitz. All rights reserved. // import XCTest @testable import Appz class InstagramTests: XCTestCase { let appCaller = ApplicationCallerMock() func testConfiguration() { let instagram = Applications.Instagram() XCTAssertEqual(instagram.scheme, "instagram:") XCTAssertEqual(instagram.fallbackURL, "https://instagram.com/") } func testOpen() { let action = Applications.Instagram.Action.open XCTAssertEqual(action.paths.app.pathComponents, ["app"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } func testCamera() { let action = Applications.Instagram.Action.camera XCTAssertEqual(action.paths.app.pathComponents, ["camera"]) XCTAssertEqual(action.paths.app.queryParameters, [:]) XCTAssertEqual(action.paths.web, Path()) } func testLibrary() { let action = Applications.Instagram.Action.library(id: "1") XCTAssertEqual(action.paths.app.pathComponents, ["library"]) XCTAssertEqual(action.paths.app.queryParameters, ["LocalIdentifier":"1"]) XCTAssertEqual(action.paths.web, Path()) } func testMedia() { let action = Applications.Instagram.Action.media(id: "1") XCTAssertEqual(action.paths.app.pathComponents, ["media"]) XCTAssertEqual(action.paths.app.queryParameters, ["id":"1"]) XCTAssertEqual(action.paths.web.pathComponents, ["p", "1"]) } func testUsername() { let action = Applications.Instagram.Action.username("test") XCTAssertEqual(action.paths.app.pathComponents, ["user"]) XCTAssertEqual(action.paths.app.queryParameters, ["username":"test"]) XCTAssertEqual(action.paths.web.pathComponents, ["test"]) } func testLocation() { let action = Applications.Instagram.Action.location(id: "111") XCTAssertEqual(action.paths.app.pathComponents, ["location"]) XCTAssertEqual(action.paths.app.queryParameters, ["id":"111"]) XCTAssertEqual(action.paths.web, Path()) } func testTag() { let action = Applications.Instagram.Action.tag(name: "tag") XCTAssertEqual(action.paths.app.pathComponents, ["tag"]) XCTAssertEqual(action.paths.app.queryParameters, ["name":"tag"]) XCTAssertEqual(action.paths.web.pathComponents, ["explore", "tags", "tag"]) } }
85d90100c1d82a4e8995f674c03720e1
30.395349
83
0.623333
false
true
false
false
NSSimpleApps/WatchConnector
refs/heads/master
WatchConnector/WatchConnector/Keys.swift
mit
1
// // Keys.swift // WatchConnector // // Created by NSSimpleApps on 13.03.16. // Copyright © 2016 NSSimpleApps. All rights reserved. // import Foundation let UpdateUIKey = "UpdateUIKey" let DataRequest = "DataRequest" let DeleteNote = "DeleteNote" let Notes = "Notes" let URIRepresentation = "URIRepresentation" let ReloadData = "ReloadData"
f5650b2d352e8320ac9ca371e8c5dc36
17.473684
55
0.731429
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/Extensions/Challenge-Extensions.swift
gpl-3.0
1
// // Challenge-Extensions.swift // Habitica // // Created by Elliot Schrock on 1/30/18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models extension ChallengeProtocol { func shouldBePublishable() -> Bool { if !isOwner() { return false } else { return hasTasks() } } func shouldBeUnpublishable() -> Bool { if !isOwner() { return false } else { return !hasTasks() } } func shouldEnable() -> Bool { if !isOwner() { return true } else { return hasTasks() } } func isOwner() -> Bool { return false } func isPublished() -> Bool { return true } func isEndable() -> Bool { return isOwner() && isPublished() } func hasTasks() -> Bool { let hasDailies = dailies.isEmpty == false let hasHabits = habits.isEmpty == false let hasTodos = todos.isEmpty == false let hasRewards = rewards.isEmpty == false return hasDailies || hasHabits || hasTodos || hasRewards } }
583c078fa50e46a25d141f53c19053ea
19.644068
64
0.517241
false
false
false
false
stockx/Punchcard
refs/heads/master
Source/UIView+AutoLayout.swift
mit
1
// // UIView+AutoLayout.swift // Punchcard // // Created by Josh Sklar on 2/1/17. // Copyright © 2017 StockX. All rights reserved. // import UIKit extension UIView { // MARK: Edges /** Makes the edges of the receiver equal to the edges of `view`. Note: `view` must already be constrained, and both the receiver and `view` must have a common superview. */ func makeEdgesEqualTo(_ view: UIView) { makeAttribute(.leading, equalToOtherView: view, attribute: .leading) makeAttribute(.trailing, equalToOtherView: view, attribute: .trailing) makeAttribute(.top, equalToOtherView: view, attribute: .top) makeAttribute(.bottom, equalToOtherView: view, attribute: .bottom) } /** Makes the edges of the receiver equal to its superview with an otion to specify an inset value. If the receiver does not have a superview, this does nothing. */ func makeEdgesEqualToSuperview(inset: CGFloat = 0) { makeAttributesEqualToSuperview([.leading, .top], offset: inset) makeAttributesEqualToSuperview([.trailing, .bottom], offset: -inset) } // MARK: Attributes /** Applies constraints to the receiver with attributes `attributes` all equal to its superview. */ func makeAttributesEqualToSuperview(_ attributes: [NSLayoutAttribute], offset: CGFloat = 0) { guard let superview = superview else { return } translatesAutoresizingMaskIntoConstraints = false attributes.forEach { superview.addConstraint(NSLayoutConstraint(item: self, attribute: $0, relatedBy: .equal, toItem: superview, attribute: $0, multiplier: 1.0, constant: offset)) } } /** Applies a constraint to the receiver with attribute `attribute` and the specified constant. */ func makeAttribute(_ attribute: NSLayoutAttribute, equalTo constant: CGFloat) { guard let superview = superview else { return } translatesAutoresizingMaskIntoConstraints = false superview.addConstraint(NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: constant)) } /** Applies a constraint with the attribute `attribute` from the receiver to the view `otherView` with attribute `attribute`. */ func makeAttribute(_ attribute: NSLayoutAttribute, equalToOtherView otherView: UIView, attribute otherAttribute: NSLayoutAttribute, constant: CGFloat = 0) { guard let sv = otherView.superview, sv == self.superview else { return } translatesAutoresizingMaskIntoConstraints = false sv.addConstraint(NSLayoutConstraint(item: self, attribute: attribute, relatedBy: .equal, toItem: otherView, attribute: otherAttribute, multiplier: 1.0, constant: constant)) } // MARK: Utility /** Removes all the constrains where the receiver is either the firstItem or secondItem. If the receiver does not have a superview, this only removes the constraints that the receiver owns. */ func removeAllConstraints() { guard let superview = superview else { removeConstraints(constraints) return } for constraint in superview.constraints where (constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self) { superview.removeConstraint(constraint) } removeConstraints(constraints) } }
aa488cb4f9a1b87e3d169e1832be93a3
35.046512
141
0.517849
false
false
false
false
CodaFi/swift-compiler-crashes
refs/heads/master
crashes-duplicates/00073-llvm-errs.swift
mit
12
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func kj<ts>() -> (ts, ts -> ts) -> ts { nm ml nm.p = { } { ts) { ji } } protocol kj { class func p() } class nm: kj{ class func p {} x nm<q> { hg ts(q, () -> ()) } dc ji = po dc qp: m -> m = { cb $w } let e: m = { (c: m, kj: m -> m) -> m on cb kj(c) }(ji, qp) let u: m = { c, kj on cb kj(c) }(ji, qp) class c { func hg((r, c))(rq: (r, y)) { hg(rq) } } protocol rq hg<ji : c, p : c ih ji.ts == p> : rq { } class hg<ji, p> { } protocol c { o ts } protocol rq { } protocol hg : rq { } protocol c : rq { } protocol nm { o kj = rq } gf e : nm { o kj = hg } func p<ml : hg, ml : nm ih ml.kj == ml> (cb: ml) { } func p<v : nm ih v.kj == c> (cb: v) { } p(e()) func c<nm { x c { func e dc _ = e } } protocol kj { } gf v : kj { } gf ts<hg, p: kj ih hg.ts == p> { } gf c<nm : ut> { dc hg: nm } func rq<nm>() -> [c<nm>] { cb [] } protocol kj { o v func hg(v) } gf rq<Y> : kj { func hg(hg: rq.lk) { } } class rq<kj : hg, ts : hg ih kj.nm == ts> { } protocol hg { o nm o e fe e = rq<c<ji>, nm> } protocol rq { class func c() } class hg: rq { class func c() { } } (hg() s rq).t.c() func sr(ed: ml) -> <q>(() -> q) -> ml { cb { ts on "\(ed): \(ts())" } } gf kj<q> { let rq: [(q, () -> ())] = [] } func() { x hg { hg c } } func rq(hg: m = w) { } let c = rq
bf27267305004aca975b7eb1a7f53011
13.009009
87
0.451447
false
false
false
false
eselkin/DirectionFieldiOS
refs/heads/master
DirectionField/Complex.swift
gpl-3.0
1
// // Complex.swift // DirectionField // // Created by Eli Selkin on 12/27/15. // Copyright © 2015 DifferentialEq. All rights reserved. // import Foundation enum ComplexError: ErrorType { case BadRegexConstruction(message: String) case BadStringConstruction(message: String) } class Complex : CustomStringConvertible { let epsilon:Float32 = 1e-5 var real:Float32 var imaginary:Float32 var description:String { get { return String(format: "%+5.4f%+5.4fi", self.real, self.imaginary) } } /* constructor -- initializer with 0, 1, or 2 Float32 attributes */ init(r: Float32 = 0.0, i: Float32 = 0.0){ self.real = r self.imaginary = i } /* constructor -- initializer with 0, 1, or 2 integer attributes */ init(r: Int = 0, i: Int = 0){ self.real = Float32(r) self.imaginary = Float32(i) } /* Constructor -- initializer for string interpolation FAILABLE convenience! */ convenience init (realimag: String) throws { // first conveniently create a new Complex instance self.init(r: 0.0, i: 0.0) // then try to store the real values do { let internalRegularExpression = try NSRegularExpression(pattern: "^([+-]?[0-9]*[.]?[0-9]+)([+-][0-9]*[.]?[0-9]+)[i]$", options: .CaseInsensitive) let matches = internalRegularExpression.matchesInString(realimag, options: .Anchored, range: NSRange(location: 0, length: realimag.utf16.count)) for match in matches as [NSTextCheckingResult] { let realString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(1)) self.real = realString.floatValue let imagString:NSString = (realimag as NSString).substringWithRange(match.rangeAtIndex(2)) self.imaginary = imagString.floatValue } } catch { throw ComplexError.BadRegexConstruction(message: "Bad expression") } } /** * http://floating-point-gui.de/errors/comparison/ Comparing complex conjugate to 0.0+0.0i */ func isZero() -> Bool { let absR = abs(self.real) let absI = abs(self.imaginary) if (self.real == 0 && self.imaginary == 0){ return true } else if (absR <= epsilon && absI <= epsilon){ self.real = 0 self.imaginary = 0 return true } else { return false } } /** Distance on CxR plane */ func distanceFromZero() -> Float32 { return sqrtf((self.real*self.real)+(self.imaginary*self.imaginary)) } } func +(LHS: Complex, RHS: Complex) -> Complex{ return Complex(r: (LHS.real + RHS.real), i: (LHS.imaginary + RHS.imaginary)) } func -(LHS: Complex, RHS: Complex) -> Complex { return Complex(r: (LHS.real - RHS.real), i: (LHS.imaginary - RHS.imaginary)) } func *(LHS: Complex, RHS: Complex) -> Complex { return Complex(r: (LHS.real*RHS.real)-(LHS.imaginary*RHS.imaginary), i: (LHS.real*RHS.imaginary)+(LHS.imaginary*RHS.real)) } func /(LHS: Complex, RHS: Complex) -> Complex { if LHS.isZero() { return Complex(r: 0.0, i: 0.0) } var real:Float32 = LHS.real * RHS.real real += LHS.imaginary * RHS.imaginary var imaginary = LHS.real * RHS.imaginary * -1.0 imaginary += LHS.imaginary * RHS.real let denominator:Float32 = RHS.real * RHS.real + RHS.imaginary * RHS.imaginary return Complex(r: real/denominator, i: imaginary/denominator) } func >= (LHS: Complex, RHS: Complex) -> Bool { return (LHS.real >= RHS.real) } func == (LHS: Complex, RHS: Complex) -> Bool { return (approxEqual(LHS.real, RHS: RHS.real, epsilon: 1E-10) && approxEqual(LHS.imaginary, RHS: RHS.imaginary, epsilon: 1E-10)) } func square(base:Complex) -> Complex { return base*base } func realSqrt(radicand: Complex) -> Complex { return Complex(r: sqrtf(radicand.real)) }
6ff74241a24e62ec779a3cf500a60132
30.390625
157
0.610254
false
false
false
false
tadija/AELog
refs/heads/master
Sources/AELog/Settings.swift
mit
1
/** * https://github.com/tadija/AELog * Copyright © 2016-2020 Marko Tadić * Licensed under the MIT license */ import Foundation /// Log settings open class Settings { // MARK: Constants private struct Defaults { static let isEnabled = true static let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" static let template = "{date} -- [{thread}] {file} ({line}) -> {function} > {text}" } // MARK: Properties /// Logging enabled flag (defaults to `true`) public var isEnabled = Defaults.isEnabled /// Date format which will be used in log lines. (defaults to "yyyy-MM-dd HH:mm:ss.SSS") public var dateFormat = Defaults.dateFormat { didSet { dateFormatter.dateFormat = dateFormat } } /// Log lines template. /// Defaults to: "{date} -- [{thread}] {file} ({line}) -> {function} > {text}" public var template = Defaults.template /// Key: file name without extension (defaults to empty - logging enabled in all files) public var files = [String : Bool]() internal let dateFormatter = DateFormatter() // MARK: Init internal init() { dateFormatter.dateFormat = dateFormat } }
db095f15c97cc93312b19a14508c1574
24.723404
92
0.61952
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Localization/Sources/Localization/LocalizationConstants+Tour.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. // swiftlint:disable all import Foundation extension LocalizationConstants { public enum Tour { public static let carouselBrokerageScreenMessage = NSLocalizedString( "Instantly Buy, Sell and Swap Crypto.", comment: "Main text that appears in the Brokerage view inside the onboarding tour" ) public static let carouselEarnScreenMessage = NSLocalizedString( "Earn Rewards on Your Crypto.", comment: "Main text that appears in the Earn view inside the onboarding tour" ) public static let carouselKeysScreenMessage = NSLocalizedString( "Control Your Crypto with Private Keys.", comment: "Main text that appears in the Keys view inside the onboarding tour" ) public static let carouselPricesScreenTitle = NSLocalizedString( "Never Miss a Crypto Moment.", comment: "Title text that appears in the Prices view inside the onboarding tour" ) public static let carouselPricesScreenLivePrices = NSLocalizedString( "Live Prices", comment: "Message that appears as a header of the prices list on the Prices screen inside the onboarding tour" ) public static let createAccountButtonTitle = NSLocalizedString( "Create an Account", comment: "Title of the button the user can tap when they want to create an account" ) public static let restoreButtonTitle = NSLocalizedString( "Restore", comment: "Title of the button the user can tap when they want to restore an account" ) public static let loginButtonTitle = NSLocalizedString( "Log In ->", comment: "Title of the button the user can tap when they want to login into an account" ) public static let manualLoginButtonTitle = NSLocalizedString( "Manual Pairing", comment: "Title of the button the user can tap when they want to manual pair the wallet" ) } }
735c68247651af2065e2494a40a6e967
37.836364
122
0.654963
false
false
false
false
JaSpa/swift
refs/heads/master
benchmark/single-source/CharacterLiteralsSmall.swift
apache-2.0
8
//===--- CharacterLiteralsSmall.swift -------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test tests the performance of Characters initialized from literals that // fit within the small (63 bits or fewer) representation and can be // represented as a packed integer. import TestsUtils @inline(never) func makeCharacter_UTF8Length1() -> Character { return "a" } @inline(never) func makeCharacter_UTF8Length2() -> Character { return "\u{00a9}" } @inline(never) func makeCharacter_UTF8Length3() -> Character { return "a\u{0300}" } @inline(never) func makeCharacter_UTF8Length4() -> Character { return "\u{00a9}\u{0300}" } @inline(never) func makeCharacter_UTF8Length5() -> Character { return "a\u{0300}\u{0301}" } @inline(never) func makeCharacter_UTF8Length6() -> Character { return "\u{00a9}\u{0300}\u{0301}" } @inline(never) func makeCharacter_UTF8Length7() -> Character { return "a\u{0300}\u{0301}\u{0302}" } @inline(never) func makeCharacter_UTF8Length8() -> Character { return "\u{00a9}\u{0300}\u{0301}\u{0302}" } public func run_CharacterLiteralsSmall(_ N: Int) { for _ in 0...10000 * N { _ = makeCharacter_UTF8Length1() _ = makeCharacter_UTF8Length2() _ = makeCharacter_UTF8Length3() _ = makeCharacter_UTF8Length4() _ = makeCharacter_UTF8Length5() _ = makeCharacter_UTF8Length6() _ = makeCharacter_UTF8Length7() _ = makeCharacter_UTF8Length8() } }
9bef7f60876820284c6d6959b3a6b97e
25.84058
80
0.654968
false
false
false
false
jearle/DeckOCards
refs/heads/master
Pod/Classes/Deck.swift
mit
1
// // Deck.swift // Pods // // Created by Jesse Earle on 8/6/15. // // public func createDeck() -> [Card] { println("Creating Deck") var deck = [Card]() var suitValue = 0 while let suit = Suit(rawValue: suitValue) { var rankValue = 0 while let rank = Rank(rawValue: rankValue) { deck.append(Card(suit: suit, rank: rank)) rankValue++ } suitValue++ } return deck } public func shuffledDeck () -> [Card] { return shuffle(createDeck()) } // http://stackoverflow.com/a/24029847 public func shuffle<C: MutableCollectionType where C.Index == Int>(var list: C) -> C { let c = count(list) if c < 2 { return list } for i in 0..<(c - 1) { let j = Int(arc4random_uniform(UInt32(c - i))) + i swap(&list[i], &list[j]) } return list }
cf8031a5cd5d1c46a61e8f65b96974ea
16.084746
86
0.47123
false
false
false
false
damouse/DSON
refs/heads/master
DSONTests/ConversionTests.swift
mit
1
// // ConversionTests.swift // Deferred // // Created by damouse on 5/17/16. // Copyright © 2016 I. All rights reserved. // // These tests cover converstion TO swift types // Note that "Primitives" refers to JSON types that arent collections import XCTest @testable import DSON // Primitives class StringConversion: XCTestCase { func testSameType() { let a: String = "asdf" let b = try! convert(a, to: String.self) XCTAssert(a == b) } func testFromFoundation() { let a: NSString = "asdf" let b = try! convert(a, to: String.self) XCTAssert(a == b) } } class IntConversion: XCTestCase { func testSameType() { let a: Int = 1 let b = try! convert(a, to: Int.self) XCTAssert(a == b) } func testFromFoundation() { let a: NSNumber = 1 let b = try! convert(a, to: Int.self) XCTAssert(a == b) } } class FloatConversion: XCTestCase { func testSameType() { let a: Float = 123.456 let b = try! convert(a, to: Float.self) XCTAssert(a == b) } func testFromFoundation() { let a: NSNumber = 123.456 let b = try! convert(a, to: Float.self) XCTAssert(b == 123.456) } } class DoubleConversion: XCTestCase { func testSameType() { let a: Double = 123.456 let b = try! convert(a, to: Double.self) XCTAssert(a == b) } func testFromFoundation() { let a: NSNumber = 123.456 let b = try! convert(a, to: Double.self) XCTAssert(b == 123.456) } } class BoolConversion: XCTestCase { func testSameType() { let a: Bool = true let b = try! convert(a, to: Bool.self) XCTAssert(a == b) } func testFromFoundation() { let a: ObjCBool = true let b = try! convert(a, to: Bool.self) XCTAssert(b == true) } } // Collections class ArrayConversion: XCTestCase { func testSameType() { let a: [String] = ["asdf", "qwer"] let b = try! convert(a, to: [String].self) XCTAssert(a == b) } // NSArray with Convertible elements func testFoundationArray() { let a: NSArray = NSArray(objects: "asdf", "qwer") let b = try! convert(a, to: [String].self) XCTAssert(a == b) } // Swift array with Foundation elements func testFoundationElements() { let a: [NSString] = [NSString(string: "asdf"), NSString(string: "qwer")] let b = try! convert(a, to: [String].self) XCTAssert(a == b) } // NSArray array with Foundation elements func testFoundationArrayElements() { let a: NSArray = NSArray(objects: NSString(string: "asdf"), NSString(string: "qwer")) let b = try! convert(a, to: [String].self) XCTAssert(a == b) } } class DictionaryConversion: XCTestCase { func testSameType() { let a: [String: String] = ["asdf": "qwer"] let b = try! convert(a, to: [String: String].self) XCTAssert(a == b) } func testAnyObject() { let a: [String: AnyObject] = ["asdf": "qwer"] let b = try! convert(a, to: [String: String].self) XCTAssert(b.count == 1) XCTAssert(b["asdf"] == "qwer") } func testFoundationDictionary() { let a: NSDictionary = NSDictionary(dictionary: ["asdf": "qwer"]) let b = try! convert(a, to: [String: String].self) XCTAssert(a == b) } func testFoundationKeys() { let a: [NSString: String] = [NSString(string: "asdf"): "qwer"] let b = try! convert(a, to: [String: String].self) XCTAssert(b.count == 1) XCTAssert(b["asdf"] == "qwer") } func testFoundationValues() { let a: [String: NSString] = ["asdf": NSString(string: "qwer")] let b = try! convert(a, to: [String: String].self) XCTAssert(b.count == 1) XCTAssert(b["asdf"] == "qwer") } func testFoundationKeysValues() { let a: [NSString: NSString] = [NSString(string: "asdf"): NSString(string: "qwer")] let b = try! convert(a, to: [String: String].self) XCTAssert(b.count == 1) XCTAssert(b["asdf"] == "qwer") } }
bbcd270bdb214842128fd14bb790ab70
19.9375
93
0.547646
false
true
false
false
coderMONSTER/iosstar
refs/heads/master
iOSStar/Model/StarListModel/StarListModel.swift
gpl-3.0
1
// // StarListModel.swift // iOSStar // // Created by sum on 2017/5/11. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import RealmSwift class BaseModel: OEZModel { override class func jsonKeyPostfix(_ name: String!) -> String! { return ""; } deinit { } } class StarListModel: BaseModel { var depositsinfo : [StarInfoModel]? class func depositsinfoModelClass() ->AnyClass { return StarInfoModel.classForCoder() } } class StartModel: Object { dynamic var accid : String = "" dynamic var brief : Int64 = 0 dynamic var code : String = " " dynamic var gender : Int64 = 0 dynamic var name : String = "" dynamic var phone : String = "" dynamic var price : Int64 = 0 dynamic var pic_url = "" override static func primaryKey() -> String?{ return "code" } static func getStartName(startCode:String,complete: CompleteBlock?){ let realm = try! Realm() let filterStr = "code = '\(startCode)'" let user = realm.objects(StartModel.self).filter(filterStr).first if user != nil{ complete?(user as AnyObject) }else{ complete?(nil) } } } class StarInfoModel: NSObject { var faccid : String = "" var status : Int64 = 0 var ownseconds : Int64 = 0 var appoint : Int64 = 0 var starcode : String = "" var starname : String = "" var uid : Int64 = 0 var accid : String = "" }
a3f6bc4011f8e5c3779668ba116bd845
19.76
73
0.574823
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
refs/heads/master
iOS/Venue/Views/POIAnnotation.swift
epl-1.0
1
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// Subclass of VenueMapAnnotation. Represents a Point of Interest on the map. class POIAnnotation: VenueMapAnnotation { var poiObject: POI! private var referencePoint = CGPoint() private let scale: CGFloat = 0.7 init(poi: POI, location: CGPoint, zoomScale: CGFloat) { self.poiObject = poi let firstType = poiObject.types.first! let backgroundImage = UIImage(named: firstType.pin_image_name)! let width = backgroundImage.size.width * scale let height = backgroundImage.size.height * scale // Setup the frame of the button. The bottom middle point of the annotation is the reference point referencePoint = location let x = self.referencePoint.x * zoomScale - (width / 2) let y = self.referencePoint.y * zoomScale - (height) super.init(frame: CGRect(x: x, y: y, width: width, height: height)) self.setBackgroundImage(backgroundImage, forState: UIControlState.Normal) self.accessibilityIdentifier = self.poiObject.name self.accessibilityHint = firstType.name } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func updateLocation(mapZoomScale: CGFloat) { // This point needs to move to keep the bottom middle of the image in the same location. The other annotation // types moves to keep the center of the annotation in the same relative spot self.frame.origin.x = (self.referencePoint.x * mapZoomScale) - (self.frame.size.width / 2) self.frame.origin.y = (self.referencePoint.y * mapZoomScale) - (self.frame.size.height) } override func updateReferencePoint(newReferencePoint: CGPoint, mapZoomScale: CGFloat) { self.referencePoint = newReferencePoint self.updateLocation(mapZoomScale) } override func getReferencePoint() -> CGPoint { return self.referencePoint } private func calculateOriginPoint(width: CGFloat, height: CGFloat, zoomScale: CGFloat) -> CGPoint { let x = (self.referencePoint.x * zoomScale) - (width / 2) let y = (self.referencePoint.y * zoomScale) - (height) return CGPoint(x: x, y: y) } /** When this annotation is selected, change the frame of the annotation accordingly. - parameter mapZoomScale: The zoom scale of the containing scroll view */ override func annotationSelected(mapZoomScale: CGFloat) { currentlySelected = !currentlySelected let backgroundImage = self.backgroundImageForState(.Normal)! let width : CGFloat! let height : CGFloat! if currentlySelected { width = backgroundImage.size.width height = backgroundImage.size.height } else { width = backgroundImage.size.width * scale height = backgroundImage.size.height * scale } let newOrigin = self.calculateOriginPoint(width, height: height, zoomScale: mapZoomScale) UIView.animateWithDuration(0.3, animations: { Void in self.frame = CGRect(x: newOrigin.x, y: newOrigin.y, width: width, height: height) }) } /** Applies the given filters to this annotation - parameter filter: The filter array of the different types */ func applyFilter(filter: [Type]) { // Filter based on type for poiType in poiObject.types { for type in filter { if poiType.id == type.id { if type.shouldDisplay { self.hidden = false return } else { self.hidden = true } } } } } /** Filter based on the minimum height requirement - parameter heightFilter: The int value for minimum height - returns: Bool indicating if this annotation is now hidden or not */ func filterHeight(heightFilter: Int) -> Bool { if (poiObject.height_requirement > 0) && (poiObject.height_requirement > heightFilter) { self.hidden = true } else { self.hidden = false } return self.hidden } /** Filter based on maximum wait time - parameter waitTime: The int value for maximum wait - returns: Bool indicating if this annotation is now hidden or not */ func filterWaitTime(waitTime: Int) -> Bool { if (poiObject.wait_time > 0) && (poiObject.wait_time > waitTime) { self.hidden = true } else { self.hidden = false } return self.hidden } }
928978c8720299ac5809e97caf534d0a
34.202899
117
0.615274
false
false
false
false
ZamzamInc/SwiftyPress
refs/heads/main
Sources/SwiftyPress/Repositories/Author/AuthorAPI.swift
mit
1
// // AuthorAPI.swift // SwiftyPress // // Created by Basem Emara on 2018-06-04. // Copyright © 2019 Zamzam Inc. All rights reserved. // import ZamzamCore // MARK: - Services public protocol AuthorService { func fetch(with request: AuthorAPI.FetchRequest, completion: @escaping (Result<Author, SwiftyPressError>) -> Void) } // MARK: - Cache public protocol AuthorCache { func fetch(with request: AuthorAPI.FetchRequest, completion: @escaping (Result<Author, SwiftyPressError>) -> Void) func createOrUpdate(_ request: Author, completion: @escaping (Result<Author, SwiftyPressError>) -> Void) func subscribe( with request: AuthorAPI.FetchRequest, in cancellable: inout Cancellable?, change block: @escaping (ChangeResult<Author, SwiftyPressError>) -> Void ) } // MARK: - Namespace public enum AuthorAPI { public struct FetchRequest: Hashable { public let id: Int public init(id: Int) { self.id = id } } public struct FetchCancellable { private let service: AuthorService private let cache: AuthorCache? private let request: FetchRequest private let block: (ChangeResult<Author, SwiftyPressError>) -> Void init( service: AuthorService, cache: AuthorCache?, request: FetchRequest, change block: @escaping (ChangeResult<Author, SwiftyPressError>) -> Void ) { self.service = service self.cache = cache self.request = request self.block = block } /// Stores the cancellable object for subscriptions to be delievered during its lifetime. /// /// A subscription is automatically cancelled when the object is deinitialized. /// /// - Parameter cancellable: A subscription token which must be held for as long as you want updates to be delivered. public func store(in cancellable: inout Cancellable?) { guard let cache = cache else { service.fetch(with: request, completion: { $0(self.block) }) return } cache.subscribe(with: request, in: &cancellable, change: block) } } }
a89e407ba0158ebfe5ed26ed1b36999b
30.094595
125
0.615385
false
false
false
false
22377832/swiftdemo
refs/heads/master
TouchsDemo/TouchsDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // TouchsDemo // // Created by adults on 2017/4/5. // Copyright © 2017年 adults. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. guard let splitVC = self.window?.rootViewController as? UISplitViewController else { print("error") fatalError("error") } splitVC.delegate = self return true } func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } // Return true if the `sampleTitle` has not been set, collapsing the secondary controller. return topAsDetailController.sampleTitle == nil } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
ec96dce000fc0d75e8418f6e17ff6200
47.301587
285
0.739073
false
false
false
false
JadenGeller/Mailbox
refs/heads/master
mailbox.swift
mit
1
import Foundation public protocol OutgoingMailboxType { typealias Message func send(message: Message) } public protocol IncomingMailboxType { typealias Message func receive() -> Message } public protocol ClosableMailboxType { typealias Message func close() } public protocol ClosableIncomingMailboxType : ClosableMailboxType { func receive() -> Message? } // Used to connect concurrent threads and communicate values across them. // For more info, visit https://gobyexample.com/channels public class Mailbox<T> : IncomingMailboxType, OutgoingMailboxType { // Signals--communicating mailbox and delivery status between threads private let mailboxNotFull: dispatch_queue_t private let messageSent: dispatch_queue_t private let messageReceived: dispatch_queue_t // Locks--syncronizing blocks of code so that only one thread can perform // a given action at a time, preventing state corruption private let receiveMessage = dispatch_semaphore_create(1) private let sendMessage = dispatch_semaphore_create(1) private let openMailbox = dispatch_semaphore_create(1) // Stores messages in transit between threads private var mailbox = [T]() // Maximum number of messages that can be stored in our given mailbox at // a time before we start blocking threads public let capacity: Int // Capacity argument specifies the number of messages that can be sent, // unreceieved, before sending starts to block the thread. By default, // the capacity is 0, and every sent message is blocking until it is // received.` public init(capacity: Int = 0) { // Check to make sure that the capacity is non-negative assert(capacity >= 0, "Channel capacity must be a positive value") self.capacity = capacity // Keeps track of how much space is left in our mailbox so that // only add new values when there is enough space. Our mailbox can hold // one more than capacity messages because we need to hold also hold the // message currently in transit. self.mailboxNotFull = dispatch_semaphore_create(capacity + 1) // Notifies the recipient when a message has been sent so that it can // pick it up. If multiple messages are sent without being received, // these notifcations to the recipient pile up, waiting. self.messageSent = dispatch_semaphore_create(0) // Keeps track of how many messages in our mailbox are still waiting to // be received. This allows us to block the thread when our mailbox is // over capacity and unblock it once a message has been received so we // are again at normal capacity. self.messageReceived = dispatch_semaphore_create(capacity) } public func send(message: T) { // Wait in the line to send your message. dispatch_semaphore_wait(sendMessage, DISPATCH_TIME_FOREVER) // Wait until there is space in the mailbox to store your message. dispatch_semaphore_wait(mailboxNotFull, DISPATCH_TIME_FOREVER) // Claim the mailbox once it's not in use, and store your message in it. dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER) mailbox.append(message) dispatch_semaphore_signal(openMailbox) // Close the mailbox // Let the recipient know that there is a message waiting for them. dispatch_semaphore_signal(messageSent) // If the mailbox too full, don't leave your message unattended // until another message is received first. dispatch_semaphore_wait(messageReceived, DISPATCH_TIME_FOREVER) // You sent your message, so get out of line and let the next thread // send its mail! dispatch_semaphore_signal(sendMessage) } public func receive() -> T { // Wait in the line to receive you message. dispatch_semaphore_wait(receiveMessage, DISPATCH_TIME_FOREVER) // Wait until somebody sends a message so that there's a message // available for you in the mailbox. dispatch_semaphore_wait(messageSent, DISPATCH_TIME_FOREVER) // Claim the mailbox once it's not in use, and grab your message from it. dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER) let message = mailbox.removeAtIndex(0) dispatch_semaphore_signal(openMailbox) // Close the mailbox // Signal that the mailbox is no longer full (as we just removed a // message from it) so that senders can put more messages in it. dispatch_semaphore_signal(mailboxNotFull) // Signal that the mailbox is no longer too full so that any other poor // thread waiting next to it can finally insert his message and leave. dispatch_semaphore_signal(messageReceived) // You received your message, so get out of line and let the next thead // retrieve its mail! dispatch_semaphore_signal(receiveMessage) return message } } public class ClosableMailbox<T> : Mailbox<T>, ClosableMailboxType, SequenceType { // Signals when a message is added to the mailbox so we can defer checking // the closed state to the last possible moment. private let mailboxReady = dispatch_semaphore_create(0) // Lock used to keep synchronous the checking and changing of the closed flag private let keepState = dispatch_semaphore_create(1) override init(capacity: Int = 0) { super.init(capacity: capacity) } // Tracks whether or not the mailbox has been closed private var isClosed = false override public func send(message: T) { // Signals that a message was sent to that we can stop deferring our // empty and closed checks dispatch_semaphore_signal(mailboxReady) super.send(message) } // Receieve optional messages: T? while the mailbox is open // and nil once the mailbox has been closed public func receive() -> T? { // Defers checking the mailbox until last minute (aka until something // has actually been added). dispatch_semaphore_wait(mailboxReady, DISPATCH_TIME_FOREVER) // Claims the mailbox and checks if it is empty dispatch_semaphore_wait(openMailbox, DISPATCH_TIME_FOREVER) let empty = mailbox.isEmpty dispatch_semaphore_signal(openMailbox) // If the mailbox was empty, we should check if it is closed if empty { // Claim mailbox so that we can check if it is closed dispatch_semaphore_wait(keepState, DISPATCH_TIME_FOREVER) let closed = self.isClosed dispatch_semaphore_signal(keepState) // It the mailbox was closed, we ought to return nil from this // function if closed { return nil } } return super.receive() } override public func receive() -> T { fatalError("ClosableMailbox instance must use the optional recieve function") } public func close() { // Claim mailbox so that we can set the closed state dispatch_semaphore_wait(self.keepState, DISPATCH_TIME_FOREVER) self.isClosed = true dispatch_semaphore_signal(self.keepState) dispatch_semaphore_signal(mailboxReady) } public func generate() -> ClosableMailboxGenerator<T> { return ClosableMailboxGenerator<T>(mailbox: self) } } public struct ClosableMailboxGenerator<T> : GeneratorType { private let mailbox: ClosableMailbox<T> public mutating func next() -> T? { return mailbox.receive() } } // Custom operators for sending and recieving mail. prefix operator <- { } infix operator <- { } public prefix func <-<M : IncomingMailboxType>(rhs: M) -> M.Message { return rhs.receive() } public prefix func <-<M : ClosableIncomingMailboxType>(rhs: M) -> M.Message? { return rhs.receive() } public func <-<M : OutgoingMailboxType>(lhs: M, rhs: M.Message) { return lhs.send(rhs) } // Calls the passed in function or closure on a background thread. Equivalent // to Go's "go" keyword. public func dispatch(routine: () -> ()) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), routine) } // Calls the passed in function or closure on the main thead. Important for // UI work! public func main(routine: () -> ()) { dispatch_async(dispatch_get_main_queue(), routine) }
6264cc36df4a124e9eb777461b2f7df3
37.564444
101
0.669356
false
false
false
false
bastiangardel/EasyPayClientSeller
refs/heads/master
TB_Client_Seller/TB_Client_Seller/ViewControllerLogin.swift
mit
1
// // ViewController.swift // TB_Client_Seller // // Created by Bastian Gardel on 20.06.16. // // Copyright © 2016 Bastian Gardel // // 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 KeychainSwift import BButton import MBProgressHUD import SCLAlertView // ** Class ViewControllerLogin ** // // View Login Controller // // Author: Bastian Gardel // Version: 1.0 class ViewControllerLogin: UIViewController { @IBOutlet weak var LoginTF: UITextField! @IBOutlet weak var PasswordTF: UITextField! @IBOutlet weak var SaveLP: UISwitch! @IBOutlet weak var loginButton: BButton! let keychain = KeychainSwift() var httpsSession = HTTPSSession.sharedInstance var hud: MBProgressHUD? //End edition mode if click outside of the textfield override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { LoginTF.endEditing(true) PasswordTF.endEditing(true) } //View initialisation override func viewDidLoad() { super.viewDidLoad() loginButton.color = UIColor.bb_successColorV2() loginButton.setStyle(BButtonStyle.BootstrapV2) loginButton.setType(BButtonType.Success) loginButton.addAwesomeIcon(FAIcon.FASignIn, beforeTitle: false) if ((keychain.get("login")) != nil && (keychain.get("password")) != nil) { LoginTF.text = keychain.get("login"); PasswordTF.text = keychain.get("password") } if keychain.getBool("SaveLP") != nil { SaveLP.setOn(keychain.getBool("SaveLP")!, animated: false) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Click on login button handler @IBAction func loginAction(sender: AnyObject) { keychain.set(SaveLP.on, forKey: "SaveLP"); let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: "HelveticaNeue", size: 30)!, kTextFont: UIFont(name: "HelveticaNeue", size: 30)!, kButtonFont: UIFont(name: "HelveticaNeue-Bold", size: 25)!, kWindowWidth: 500.0, kWindowHeight: 500.0, kTitleHeight: 50 ) loginButton.enabled = false LoginTF.endEditing(true) PasswordTF.endEditing(true) hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) hud?.labelText = "Login Request in Progress" hud?.labelFont = UIFont(name: "HelveticaNeue", size: 30)! httpsSession.login(LoginTF.text!, password: PasswordTF.text!){ (success: Bool, errorDescription:String) in self.hud!.hide(true) if(success) { if(self.SaveLP.on) { self.keychain.set(self.LoginTF.text!, forKey: "login"); self.keychain.set(self.PasswordTF.text!, forKey: "password"); } else { self.keychain.delete("login") self.keychain.delete("password"); } self.performSegueWithIdentifier("loginSegue", sender: self) } else { let alertView = SCLAlertView(appearance: appearance) alertView.showError("Login Error", subTitle: errorDescription) self.loginButton.enabled = true } } } }
e9d3ce6e7cfd11799365df9b57e8af0c
30.479167
86
0.641518
false
false
false
false
apiaryio/polls-app
refs/heads/master
Polls/ViewModels/CreateQuestionViewModel.swift
mit
1
// // CreateQuestionViewModel.swift // Polls // // Created by Kyle Fuller on 02/04/2015. // Copyright (c) 2015 Apiary. All rights reserved. // import Foundation import Representor import Hyperdrive /// A view model for creating a question class CreateQuestionViewModel { typealias DidAddCallback = (Representor<HTTPTransition>) -> () private let didAddCallback:DidAddCallback? private let hyperdrive:Hyperdrive private var transition:HTTPTransition init(hyperdrive:Hyperdrive, transition:HTTPTransition, didAddCallback:DidAddCallback? = nil) { self.hyperdrive = hyperdrive self.transition = transition self.didAddCallback = didAddCallback } /// Validates if the given question is valid func validate(question question:String) -> Bool { if let attribute = transition.attributes["question"] { let required = attribute.required ?? false if required { return !question.isEmpty } } return true } /// Asyncronously creates a question with the given choices calling a completion closure when complete func create(question:String, choices:[String], completion:(() -> ())) { hyperdrive.request(transition, attributes: ["question": question, "choices": choices]) { result in switch result { case .Success(let representor): self.didAddCallback?(representor) completion() case .Failure(let error): print("Failure \(error)") completion() } } } }
20ae8bc03bbf3a5d5a1a0fa301406f4b
27
104
0.695418
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
refs/heads/master
精通Swift设计模式/Chapter 16/Facade/Facade/Facade.swift
mit
1
import Foundation enum TreasureTypes { case SHIP; case BURIED; case SUNKEN; } class PirateFacade { let map = TreasureMap(); let ship = PirateShip(); let crew = PirateCrew(); func getTreasure(type:TreasureTypes) -> Int? { var prizeAmount:Int?; // select the treasure type var treasureMapType:TreasureMap.Treasures; var crewWorkType:PirateCrew.Actions; switch (type) { case .SHIP: treasureMapType = TreasureMap.Treasures.GALLEON; crewWorkType = PirateCrew.Actions.ATTACK_SHIP; case .BURIED: treasureMapType = TreasureMap.Treasures.BURIED_GOLD; crewWorkType = PirateCrew.Actions.DIG_FOR_GOLD; case .SUNKEN: treasureMapType = TreasureMap.Treasures.SUNKEN_JEWELS; crewWorkType = PirateCrew.Actions.DIVE_FOR_JEWELS; } let treasureLocation = map.findTreasure(treasureMapType); // convert from map to ship coordinates let sequence:[Character] = ["A", "B", "C", "D", "E", "F", "G"]; let eastWestPos = find(sequence, treasureLocation.gridLetter); let shipTarget = PirateShip.ShipLocation(NorthSouth: Int(treasureLocation.gridNumber), EastWest: eastWestPos!); let semaphore = dispatch_semaphore_create(0); // relocate ship ship.moveToLocation(shipTarget, callback: {location in self.crew.performAction(crewWorkType, {prize in prizeAmount = prize; dispatch_semaphore_signal(semaphore); }); }); dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); return prizeAmount; } }
e2f2bc6478323e77db599deff8043a29
32.358491
71
0.60181
false
false
false
false
Dreezydraig/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/Controllers Support/EditTextController.swift
mit
34
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class EditTextController: AAViewController { private var textView = UITextView() private var completition: (String) -> () init(title: String, actionTitle: String, content: String, completition: (String) -> ()) { self.completition = completition super.init(nibName: nil, bundle: nil) self.navigationItem.title = title self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: actionTitle, style: UIBarButtonItemStyle.Done, target: self, action: "doSave") self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: localized("NavigationCancel"), style: UIBarButtonItemStyle.Plain, target: self, action: "doCancel") self.textView.text = content self.textView.font = UIFont.systemFontOfSize(18) self.view.backgroundColor = UIColor.whiteColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(textView) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.textView.becomeFirstResponder() } func doSave() { self.completition(textView.text) self.dismissViewControllerAnimated(true, completion: nil) } func doCancel() { self.dismissViewControllerAnimated(true, completion: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.textView.frame = CGRectMake(7, 7, self.view.bounds.width - 14, self.view.bounds.height - 14) } }
c49017f1d726ae0caa8d676b31bdbd87
29.508475
170
0.647778
false
false
false
false
raphaelhanneken/iconizer
refs/heads/master
Iconizer/Helper/Asset/AssetSize.swift
mit
1
// // AssetSize.swift // Iconizer // https://github.com/raphaelhanneken/iconizer // import Foundation struct AssetSize { let string: String let width: Float let height: Float /** Parse string like 50x45 * or 50.5x25.5 * ! 50.5.5x60.5.6 will not work */ init(size: String) throws { let regex = "^([\\d\\.]+)x([\\d\\.]+)$" if let expression = try? NSRegularExpression(pattern: regex) { let range = NSRange(size.startIndex..<size.endIndex, in: size) var widthResult: Float? var heightResult: Float? expression.enumerateMatches(in: size, options: [], range: range) { (match, _, stop) in defer { stop.pointee = true } guard let match = match else { return } if match.numberOfRanges == 3, let wRange = Range(match.range(at: 1), in: size), let hRange = Range(match.range(at: 2), in: size) { widthResult = Float(size[wRange]) heightResult = Float(size[hRange]) } } if let width = widthResult, let height = heightResult { self.string = size self.width = width self.height = height return } } throw AssetCatalogError.invalidFormat(format: .size) } func multiply(_ scale: AssetScale) -> NSSize { let width = Int(self.width * Float(scale.value)) let height = Int(self.height * Float(scale.value)) return NSSize(width: width, height: height) } }
50086a8da78d22c9046d774260dcf077
28.763636
98
0.532682
false
false
false
false
tilltue/TLPhotoPicker
refs/heads/master
TLPhotoPicker/Classes/TLBundle.swift
mit
1
// // TLBundle.swift // Pods // // Created by wade.hawk on 2017. 5. 9.. // // import UIKit open class TLBundle { open class func podBundleImage(named: String) -> UIImage? { let podBundle = Bundle(for: TLBundle.self) if let url = podBundle.url(forResource: "TLPhotoPickerController", withExtension: "bundle") { let bundle = Bundle(url: url) return UIImage(named: named, in: bundle, compatibleWith: nil) } return nil } class func bundle() -> Bundle { let podBundle = Bundle(for: TLBundle.self) if let url = podBundle.url(forResource: "TLPhotoPicker", withExtension: "bundle") { let bundle = Bundle(url: url) return bundle ?? podBundle } return podBundle } }
ed150af073829585cd943b70cd1f94ce
26.37931
101
0.595718
false
false
false
false
alexandreblin/ios-car-dashboard
refs/heads/master
CarDash/AppDelegate.swift
mit
1
// // AppDelegate.swift // CarDash // // Created by Alexandre Blin on 12/06/2016. // Copyright © 2016 Alexandre Blin. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? private var dashboardViewController: DashboardViewController? { return self.window?.rootViewController?.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController") as? DashboardViewController } var externalWindow: UIWindow? var sleepPreventer: MMPDeepSleepPreventer { return MMPDeepSleepPreventer() } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { sleepPreventer.startPreventSleep() // Register for connect/disconnect notifications NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.screenDidConnect(_:)), name: NSNotification.Name.UIScreenDidConnect, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.screenDidDisconnect(_:)), name: NSNotification.Name.UIScreenDidDisconnect, object: nil) // Setup external screen if it's already connected when starting the app if UIScreen.screens.count >= 2 { setupScreen(UIScreen.screens[1]) } return true } func setupScreen(_ screen: UIScreen) { // Undocumented overscanCompensation value to disable it completely screen.overscanCompensation = UIScreenOverscanCompensation(rawValue: 3)! let window = UIWindow(frame: screen.bounds) window.screen = screen window.rootViewController = dashboardViewController window.isHidden = false window.makeKeyAndVisible() externalWindow = window } func screenDidConnect(_ notification: Notification) { guard let screen = notification.object as? UIScreen else { return } if UIScreen.screens.index(of: screen) == 1 { setupScreen(screen) } } func screenDidDisconnect(_ notification: Notification) { externalWindow?.isHidden = true externalWindow = nil } }
6aff814ef933bb25fb97b9af231486af
32.279412
172
0.702607
false
false
false
false
mzp/OctoEye
refs/heads/master
Tests/Snapshot/SnapshotHelper.swift
mit
1
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // // ----------------------------------------------------- // IMPORTANT: When modifying this file, make sure to // increment the version number at the very // bottom of the file to notify users about // the new SnapshotHelper.swift // ----------------------------------------------------- // swiftlint:disable line_length implicitly_unwrapped_optional conditional_returns_on_newline operator_usage_whitespace import Foundation import XCTest internal var deviceLanguage = "" internal var locale = "" @available(*, deprecated, message: "use setupSnapshot: instead") internal func setLanguage(_ app: XCUIApplication) { setupSnapshot(app) } internal func setupSnapshot(_ app: XCUIApplication) { Snapshot.setupSnapshot(app) } internal func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator) } internal enum SnapshotError: Error, CustomDebugStringConvertible { case cannotDetectUser case cannotFindHomeDirectory case cannotFindSimulatorHomeDirectory case cannotAccessSimulatorHomeDirectory(String) var debugDescription: String { switch self { case .cannotDetectUser: return "Couldn't find Snapshot configuration files - can't detect current user " case .cannotFindHomeDirectory: return "Couldn't find Snapshot configuration files - can't detect `Users` dir" case .cannotFindSimulatorHomeDirectory: return "Couldn't find simulator home location. Please, check SIMULATOR_HOST_HOME env variable." case .cannotAccessSimulatorHomeDirectory(let simulatorHostHome): return "Can't prepare environment. Simulator home location is inaccessible. Does \(simulatorHostHome) exist?" } } } open class Snapshot: NSObject { static var app: XCUIApplication! static var cacheDirectory: URL! static var screenshotsDirectory: URL? { return cacheDirectory.appendingPathComponent("screenshots", isDirectory: true) } open class func setupSnapshot(_ app: XCUIApplication) { do { let cacheDir = try pathPrefix() Snapshot.cacheDirectory = cacheDir Snapshot.app = app setLanguage(app) setLocale(app) setLaunchArguments(app) } catch let error { print(error) } } class func setLanguage(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("language.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines deviceLanguage = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) app.launchArguments += ["-AppleLanguages", "(\(deviceLanguage))"] } catch { print("Couldn't detect/set language...") } } class func setLocale(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("locale.txt") do { let trimCharacterSet = CharacterSet.whitespacesAndNewlines locale = try String(contentsOf: path, encoding: .utf8).trimmingCharacters(in: trimCharacterSet) } catch { print("Couldn't detect/set locale...") } if locale.isEmpty { locale = Locale(identifier: deviceLanguage).identifier } app.launchArguments += ["-AppleLocale", "\"\(locale)\""] } class func setLaunchArguments(_ app: XCUIApplication) { let path = cacheDirectory.appendingPathComponent("snapshot-launch_arguments.txt") app.launchArguments += ["-FASTLANE_SNAPSHOT", "YES", "-ui_testing"] do { let launchArguments = try String(contentsOf: path, encoding: String.Encoding.utf8) let regex = try NSRegularExpression(pattern: "(\\\".+?\\\"|\\S+)", options: []) let matches = regex.matches(in: launchArguments, options: [], range: NSRange(location:0, length:launchArguments.characters.count)) let results = matches.map { result -> String in (launchArguments as NSString).substring(with: result.range) } app.launchArguments += results } catch { print("Couldn't detect/set launch_arguments...") } } open class func snapshot(_ name: String, waitForLoadingIndicator: Bool = true) { if waitForLoadingIndicator { waitForLoadingIndicatorToDisappear() } print("snapshot: \(name)") // more information about this, check out https://github.com/fastlane/fastlane/tree/master/snapshot#how-does-it-work sleep(1) // Waiting for the animation to be finished (kind of) #if os(OSX) XCUIApplication().typeKey(XCUIKeyboardKeySecondaryFn, modifierFlags: []) #else let screenshot = app.windows.firstMatch.screenshot() guard let simulator = ProcessInfo().environment["SIMULATOR_DEVICE_NAME"], let screenshotsDir = screenshotsDirectory else { return } let path = screenshotsDir.appendingPathComponent("\(simulator)-\(name).png") do { try screenshot.pngRepresentation.write(to: path) } catch let error { print("Problem writing screenshot: \(name) to \(path)") print(error) } #endif } class func waitForLoadingIndicatorToDisappear() { #if os(tvOS) return #endif let query = XCUIApplication().statusBars.children(matching: .other).element(boundBy: 1).children(matching: .other) while (0..<query.count).map({ query.element(boundBy: $0) }).contains(where: { $0.isLoadingIndicator }) { sleep(1) print("Waiting for loading indicator to disappear...") } } class func pathPrefix() throws -> URL? { let homeDir: URL // on OSX config is stored in /Users/<username>/Library // and on iOS/tvOS/WatchOS it's in simulator's home dir #if os(OSX) guard let user = ProcessInfo().environment["USER"] else { throw SnapshotError.cannotDetectUser } guard let usersDir = FileManager.default.urls(for: .userDirectory, in: .localDomainMask).first else { throw SnapshotError.cannotFindHomeDirectory } homeDir = usersDir.appendingPathComponent(user) #else guard let simulatorHostHome = ProcessInfo().environment["SIMULATOR_HOST_HOME"] else { throw SnapshotError.cannotFindSimulatorHomeDirectory } guard let homeDirUrl = URL(string: simulatorHostHome) else { throw SnapshotError.cannotAccessSimulatorHomeDirectory(simulatorHostHome) } homeDir = URL(fileURLWithPath: homeDirUrl.path) #endif return homeDir.appendingPathComponent("Library/Caches/tools.fastlane") } } extension XCUIElement { var isLoadingIndicator: Bool { let whiteListedLoaders = ["GeofenceLocationTrackingOn", "StandardLocationTrackingOn"] if whiteListedLoaders.contains(self.identifier) { return false } return self.frame.size == CGSize(width: 10, height: 20) } } // Please don't remove the lines below // They are used to detect outdated configuration files // SnapshotHelperVersion [1.5]
7fb14d7a05e73348a7294c60ccd93eae
38.005128
151
0.638443
false
false
false
false
darren90/Gankoo_Swift
refs/heads/master
Gankoo/Gankoo/Classes/Home/HomeViewController.swift
apache-2.0
1
// // HomeViewController.swift // Gankoo // // Created by Fengtf on 2017/2/7. // Copyright © 2017年 ftf. All rights reserved. // import UIKit import SafariServices class HomeViewController: BaseViewController { @IBOutlet weak var tableView: UITableView! var getDate:Date = Date() var dataArray:[DataListModel]? { didSet{ tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() launchAnimation() automaticallyAdjustsScrollViewInsets = false tableView.separatorStyle = .none //最底部的空间,设置距离底部的间距(autolayout),然后再设置这两个属性,就可以自动计算高度 tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100 let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: #selector(self.loadNew)) tableView.mj_header = header tableView.mj_header.beginRefreshing() } func loadNew() { GankooApi.shareInstance.getHomeData(date:getDate) { ( result : [DataListModel]?, error : NSError?) in self.endReresh() if error == nil{ self.dataArray = result }else{ } } } func endReresh(){ self.tableView.mj_header.endRefreshing() self.tableView.mj_header.isHidden = true // self.tableView.mj_footer.endRefreshing() } @IBAction func dateAction(_ sender: UIBarButtonItem) { datePickAction() } func datePickAction() { let current = Date() let min = Date().addingTimeInterval(-60 * 60 * 24 * 15) let max = Date().addingTimeInterval(60 * 60 * 24 * 15) let picker = DateTimePicker.show(selected: current, minimumDate: min, maximumDate: max) picker.highlightColor = UIColor(red: 255.0/255.0, green: 138.0/255.0, blue: 138.0/255.0, alpha: 1) picker.doneButtonTitle = "!! DONE DONE !!" picker.todayButtonTitle = "Today" picker.completionHandler = { date in // self.current = date self.getDate = date self.loadNew() } } } extension HomeViewController : UITableViewDataSource,UITableViewDelegate{ func numberOfSections(in tableView: UITableView) -> Int { noDataView.isHidden = !(dataArray?.count == 0) return dataArray?.count ?? 0; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let array = dataArray?[section].dataArray return array?.count ?? 0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = DataSectionHeaderView.headerWithTableView(tableView: tableView) let listModel = dataArray?[section] header.title = listModel?.name return header } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0000001 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = DataListCell.cellWithTableView(tableView: tableView) let listModel = dataArray?[indexPath.section] let model = listModel?.dataArray?[indexPath.row] cell.model = model return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let listModel = dataArray?[indexPath.section] let model = listModel?.dataArray?[indexPath.row] guard let urlStr = model?.url else { return } let url = URL(string: urlStr) let vc = DataDetailController(url: url!, entersReaderIfAvailable: true) vc.model = model present(vc, animated: true, completion: nil) tableView.deselectRow(at: indexPath, animated: true) } } extension HomeViewController { //播放启动画面动画 func launchAnimation() { //获取启动视图 let vc = UIStoryboard(name: "LaunchScreen", bundle: nil) .instantiateViewController(withIdentifier: "launch") let launchview = vc.view! let delegate = UIApplication.shared.delegate delegate?.window!!.addSubview(launchview) //self.view.addSubview(launchview) //如果没有导航栏,直接添加到当前的view即可 //播放动画效果,完毕后将其移除 UIView.animate(withDuration: 1, delay: 1.2, options: .curveLinear, animations: { launchview.alpha = 0.0 let transform = CATransform3DScale(CATransform3DIdentity, 1.5, 1.5, 1.0) launchview.layer.transform = transform }) { (finished) in launchview.removeFromSuperview() } } }
f0bc2e6ff9038fdc0aeccc2459885f52
30.56129
109
0.623671
false
false
false
false
SioJL13/tec_ios
refs/heads/master
Serie_numeros.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play import UIKit var numeros = 0...100 for n in numeros{ //Div 5, par y rango if n%5 == 0 && n%2==0 && n>=30 && n<=40{ println("\(n) Bingo, #par, Viva Swift") } //Div 5, impar y rango if n%5 == 0 && n%2 != 0 && n>=30 && n<=40{ println("\(n) Bingo, #impar, Viva Swift") } //Div 5 y par else if n%5 == 0 && n%2==0{ println("\(n) Bingo y #par ") } //Div 5 e impar else if n%5 == 0 && n%2 != 0{ println("\(n) Bingo e #impar") } //Par else if n%2 == 0{ println("\(n) #par") } //Impar else if n%2 != 0{ println("\(n) #impar") } //Rango else if n>30 && n<40{ println("\(n) Viva swift") } }
875b10121e8660722dabbe7626f3e38e
20.081081
52
0.44359
false
false
false
false
kazarus/OcPack
refs/heads/master
Sources/NetClient.swift
mit
1
// // NetEngine.swift // example10014 // // Created by kazarus on 7/19/16. // Copyright © 2016 kazarus. All rights reserved. // import Foundation enum THttpMethod: String { case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" } class TNetClient:NSObject,URLSessionDelegate{ private let baseURL: String /* func URLSession(session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let credential = URLCredential(forTrust: challenge.protectionSpace.serverTrust!) completionHandler(URLSession.AuthChallengeDisposition.UseCredential, credential) } } */ public init(baseURL: String) { self.baseURL = baseURL } public func run(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){ let session = URLSession.shared //var request = NSMutableURLRequest(url:URL(string:target)!) var request = URLRequest(url:URL(string:target)!) request.httpMethod=method.rawValue if params.count>0{ } else{ } /* let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in callback(data,response,error) }) */ let task = session.dataTask(with: request){ (data,response,error) in DispatchQueue.main.async { completionHandler(data,response,error) } } task.resume() } public func mul(method:THttpMethod,target:String,params: Dictionary<String, AnyObject> = Dictionary<String, AnyObject>(),completionHandler: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void){ //#let session = URLSession.shared let session = URLSession(configuration:URLSession.shared.configuration,delegate:self,delegateQueue:URLSession.shared.delegateQueue) //#let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue)) //#print(charset as Any) var request = URLRequest(url:URL(string:self.baseURL+target)!) request.httpMethod=method.rawValue; //var request = URLRequest(url:URL(string:target)!) //#request.httpMethod=method.rawValue //request.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") var para = "" for item in params { para = item.key+"="+(item.value as! String) } print(para) request.httpBody = para.data(using: String.Encoding.utf8)//; charset=\(charset) request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //#request.addValue("application/json;text/html", forHTTPHeaderField: "Content-Type") //#request.addValue("application/json", forHTTPHeaderField: "Accept") //#request.addValue("\(paramsData.count)", forHTTPHeaderField: "Content-Length") //#request.addValue("192.168.0.3", forHTTPHeaderField: "Host") let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in DispatchQueue.main.async { completionHandler(data,response,error) } }) task.resume() } static func joinPath(with path:String)->String{ let result = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0]+"/"+path return result } func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!)) } }
1093002b971f140e80942b403526ce70
35.087302
222
0.638223
false
false
false
false
mlilback/MessagePackSwift
refs/heads/master
MessagePackSwift/MessageValue.swift
isc
1
// // MessageValue.swift // // Copyright ©2016 Mark Lilback. This file is licensed under the ISC license. // import Foundation public class MessageValueArray: NSObject { let array:[MessageValue] ///creates a wrapper around inArray public init(_ inArray:[MessageValue]) { array = inArray } ///creates a new array converting each value in nativeArray to an appropriate MessageValue public init(nativeArray:[AnyObject]) { array = nativeArray.map() { MessageValue.forValue($0) } } override public func isEqual(object: AnyObject?) -> Bool { guard let other = object as? MessageValueArray else { return false } if array.count != other.array.count { return false } if array.dynamicType != other.array.dynamicType { return false } if array.count < 1 { return true } for i in 0..<array.count { if array[i] != other.array[i] { return false } } return true } public func nativeValue() -> [AnyObject] { return array.map() { $0.nativeValue() } } } public class MessageValueDictionary: NSObject { let dict:[String:MessageValue] ///creates a wrapper around inDict public init(_ inDict:[String:MessageValue]) { self.dict = inDict } ///creates a new dictionary converting each value in nativeDict to an appropriate MessageValue public init(nativeDict:[String:AnyObject]) { var converted = [String:MessageValue]() for aKey in nativeDict.keys { let aValue = MessageValue.forValue(nativeDict[aKey]!) converted[aKey] = aValue } dict = converted } public func nativeValue() -> [String:AnyObject] { var nativeDict = [String:AnyObject]() for aKey in dict.keys { let aValue = dict[aKey]!.nativeValue() nativeDict[aKey] = aValue } return nativeDict } override public func isEqual(object: AnyObject?) -> Bool { guard let other = object as? MessageValueDictionary else { return false } guard dict.count == other.dict.count else { return false } for aKey in dict.keys { if dict[aKey] != other.dict[aKey] { return false } } return true } } public enum MessageValue: Equatable { case NilValue case BooleanValue(Bool) ///on 64-bit platforms, this is returned for all int/uint values except 64 bit uints which are returned as UInt case IntValue(Int) ///this is only returned for 64-bit uints. all others can fit in range of Int case UIntValue(UInt) case FloatValue(Float) case DoubleValue(Double) case StringValue(String) case BinaryValue(NSData) case ExtValue(NSData) case ArrayValue(MessageValueArray) case DictionaryValue(MessageValueDictionary) static public func forValue(value:AnyObject) -> MessageValue { switch(value) { case is NSNull: return .NilValue //due to foundation, this case will catch anything that can be represented by NSNumber //likely only need one of the tests, but doesn't hurt to add them all case is NSNumber: return forNumericValue(value as! NSNumber) case is String: return .StringValue(value as! String) case is NSData: return .BinaryValue(value as! NSData) case is MessageValueArray: return .ArrayValue(value as! MessageValueArray) case is Array<AnyObject>: return .ArrayValue(MessageValueArray(nativeArray: value as! Array<AnyObject>)) case is MessageValueDictionary: return .DictionaryValue(value as! MessageValueDictionary) case is Dictionary<String,AnyObject>: return .DictionaryValue(MessageValueDictionary(nativeDict: value as! Dictionary<String,AnyObject>)) default: fatalError("\(value) cannot be converted to a MessageValue") } } static public func forNumericValue(value:NSNumber) -> MessageValue { if value === kCFBooleanTrue { return .BooleanValue(true) } if value === kCFBooleanFalse { return .BooleanValue(false) } let type = String.fromCString(value.objCType)! if type == "Q" { return .UIntValue(UInt(value.unsignedLongLongValue)) } return .IntValue(Int(value)) } static public func forValue(dict:[String:MessageValue]) -> MessageValue { return .DictionaryValue(MessageValueDictionary(dict)) } static public func forValue(value:[MessageValue]) -> MessageValue { return .ArrayValue(MessageValueArray(value)) } public func nativeValue() -> AnyObject { switch(self) { case .NilValue: return NSNull() case .BooleanValue(let bval): return bval case .StringValue(let sval): return sval case .IntValue(let ival): return ival case .UIntValue(let u64val): return u64val case .BinaryValue(let data): return data case .ExtValue(let ext): return ext case .FloatValue(let fval): return fval case .DoubleValue(let dval): return dval case .ArrayValue(let arrayvalue): // return arrayvalue return arrayvalue.nativeValue() case .DictionaryValue(let dict): return dict.nativeValue() } } var nilValue:NSNull? { if case MessageValue.NilValue = self { return NSNull() } return nil } var booleanValue:Bool? { if case MessageValue.BooleanValue(let bval) = self { return bval } return nil } var floatValue:Float? { if case MessageValue.FloatValue(let val) = self { return val } return nil } var doubleValue:Double? { if case MessageValue.DoubleValue(let val) = self { return val } return nil } var intValue:Int? { if case MessageValue.IntValue(let val) = self { return val } return nil } var uintValue:UInt? { if case MessageValue.UIntValue(let val) = self { return val } return nil } var stringValue:String? { if case MessageValue.StringValue(let val) = self { return val } return nil } var binaryValue:NSData? { if case MessageValue.BinaryValue(let val) = self { return val } return nil } var arrayValue:MessageValueArray? { if case MessageValue.ArrayValue(let val) = self { return val } return nil } var dictionaryValue:MessageValueDictionary? { if case MessageValue.DictionaryValue(let val) = self { return val } return nil } var nativeDictionaryValue:[String:AnyObject]? { if case MessageValue.DictionaryValue(let val) = self { return val.nativeValue() } return nil } } public func ==(lhs:MessageValue, rhs:MessageValue) -> Bool { switch(lhs, rhs) { case (.BooleanValue(let a), .BooleanValue(let b)): return a == b case (.NilValue, .NilValue): return true case (.IntValue(let a), .IntValue(let b)): return a == b case (.UIntValue(let a), .UIntValue(let b)): return a == b case (.StringValue(let a), .StringValue(let b)): return a == b case (.BinaryValue(let a), .BinaryValue(let b)): return a == b case (.FloatValue(let a), .FloatValue(let b)): return a == b case (.DoubleValue(let a), .DoubleValue(let b)): return a == b case (.ArrayValue(let a), .ArrayValue(let b)): return a == b case (.DictionaryValue(let a), .DictionaryValue(let b)): return a == b case (.ExtValue(let a), .ExtValue(let b)): return a == b default: return false } } public enum MessagePackError: Int, ErrorType { case InvalidBinaryData case UnsupportedDictionaryKey case NoMoreData }
429932c63b61c8367aac46bb014bca68
28.164557
112
0.716869
false
false
false
false
neonichu/ECoXiS
refs/heads/master
ECoXiS/Model.swift
mit
1
// TODO: add deep copying public enum XMLNodeType { case Element, Text, Comment, ProcessingInstruction } public protocol XMLNode: Printable { var nodeType: XMLNodeType { get } } public func == (left: XMLNode, right: XMLNode) -> Bool { if left.nodeType != right.nodeType { return false } switch left.nodeType { case .Element: return (left as! XMLElement) != right as! XMLElement case .Text: return (left as! XMLText) != right as! XMLText case .Comment: return (left as! XMLComment) != right as! XMLComment case .ProcessingInstruction: return left as! XMLProcessingInstruction != right as! XMLProcessingInstruction } } public func != (left: XMLNode, right: XMLNode) -> Bool { return !(left == right) } public func == (left: [XMLNode], right: [XMLNode]) -> Bool { if left.count != right.count { return false } for (leftNode, rightNode) in Zip2(left, right) { if leftNode != rightNode { return false } } return true } public protocol XMLMiscNode: XMLNode {} public func == (left: XMLMiscNode, right: XMLMiscNode) -> Bool { return left as XMLNode == right as XMLNode } public func != (left: XMLMiscNode, right: XMLMiscNode) -> Bool { return (left as XMLNode) != right as XMLNode } public func == (left: [XMLMiscNode], right: [XMLMiscNode]) -> Bool { if left.count != right.count { return false } for (leftNode, rightNode) in Zip2(left, right) { if leftNode != rightNode { return false } } return true } public func += (inout left: [XMLNode], right: [XMLMiscNode]) { for node in right { left.append(node) } } public func == (left: String, right: XMLText) -> Bool { return left == right.content } public func == (left: XMLText, right: String) -> Bool { return left.content == right } public enum XMLNameSettingResult { case InvalidName, ModifiedName, ValidName } public class XMLAttributes: SequenceType, Equatable { private var _attributes = [String: String]() public var count: Int { return _attributes.count } // MARK: BUG: making "attributes" unnamed yields compiler error init(attributes: [String: String] = [:]) { update(attributes) } public func set(name: String, _ value: String?) -> XMLNameSettingResult { if let _name = XMLUtilities.enforceName(name) { if !_name.isEmpty { _attributes[_name] = value return _name == name ? .ValidName : .ModifiedName } } return .InvalidName } public func contains(name: String) -> Bool { return _attributes[name] != nil } public func update(attributes: [String: String]) { for (name, value) in attributes { set(name, value) } } public func generate() -> GeneratorOf<(String, String)> { return GeneratorOf(_attributes.generate()) } public subscript(name: String) -> String? { get { return _attributes[name] } set { set(name, newValue) } } class func createString(var attributeGenerator: GeneratorOf<(String, String)>) -> String { var result = "" while let (name, value) = attributeGenerator.next() { var escapedValue = XMLUtilities.escape(value, .EscapeQuot) result += " \(name)=\"\(escapedValue)\"" } return result } func toString() -> String { return XMLAttributes.createString(self.generate()) } func equals(other: XMLAttributes) -> Bool { return self._attributes == other._attributes } } public func == (left: XMLAttributes, right: XMLAttributes) -> Bool { return left.equals(right) } public class XMLElement: XMLNode, Equatable { public let nodeType = XMLNodeType.Element private var _name: String? public var name: String? { get { return _name } set { if let name = newValue { _name = XMLUtilities.enforceName(name) } else { _name = nil } } } public let attributes: XMLAttributes public var children: [XMLNode] public var description:String { if let n = name { return XMLElement.createString(n, attributesString: attributes.toString(), childrenString: XMLElement.createChildrenString(children)) } return "" } public init(_ name: String, attributes: [String: String] = [:], children: [XMLNode] = []) { self.attributes = XMLAttributes(attributes: attributes) self.children = children self.name = name } public subscript(name: String) -> String? { get { return attributes[name] } set { attributes[name] = newValue } } public subscript(index: Int) -> XMLNode? { get { if index < children.count { return children[index] } return nil } set { if let node = newValue { if index == children.count { children.append(node) } else { children[index] = node } } else { children.removeAtIndex(index) } } } class func createChildrenString(children: [XMLNode]) -> String { var childrenString = "" for child in children { childrenString += child.description } return childrenString } class func createString(name: String, attributesString: String = "", childrenString: String = "") -> String { var result = "<\(name)\(attributesString)" if childrenString.isEmpty { result += "/>" } else { result += ">\(childrenString)</\(name)>" } return result } } public func == (left: XMLElement, right: XMLElement) -> Bool { if left.name != right.name || left.attributes != right.attributes { return false } return left.children == right.children } public class XMLDocumentTypeDeclaration: Equatable { private var _systemID: String? private var _publicID: String? private var _useQuotForSystemID = false public var useQuotForSystemID: Bool { return _useQuotForSystemID } public var systemID: String? { get { return _systemID } set { (_useQuotForSystemID, _systemID) = XMLUtilities.enforceDoctypeSystemID(newValue) } } public var publicID: String? { get { return _publicID } set { _publicID = XMLUtilities.enforceDoctypePublicID(newValue) } } public init(publicID: String? = nil, systemID: String? = nil) { self.publicID = publicID self.systemID = systemID } public func toString(name: String) -> String { var result = "<!DOCTYPE \(name)" if let sID = systemID { if let pID = publicID { result += " PUBLIC \"\(pID)\" " } else { result += " SYSTEM " } if useQuotForSystemID { result += "\"\(sID)\"" } else { result += "'\(sID)'" } } result += ">" return result } } public func == (left: XMLDocumentTypeDeclaration, right: XMLDocumentTypeDeclaration) -> Bool { return left.publicID == right.publicID && left.systemID == right.systemID } public class XMLDocument: SequenceType, Equatable { public var omitXMLDeclaration: Bool public var doctype: XMLDocumentTypeDeclaration? public var beforeElement: [XMLMiscNode] public var element: XMLElement public var afterElement: [XMLMiscNode] public var count: Int { return beforeElement.count + 1 + afterElement.count } public init(_ element: XMLElement, beforeElement: [XMLMiscNode] = [], afterElement: [XMLMiscNode] = [], omitXMLDeclaration:Bool = false, doctype: XMLDocumentTypeDeclaration? = nil) { self.beforeElement = beforeElement self.element = element self.afterElement = afterElement self.omitXMLDeclaration = omitXMLDeclaration self.doctype = doctype } public func generate() -> GeneratorOf<XMLNode> { var nodes = [XMLNode]() nodes += beforeElement nodes.append(element) nodes += afterElement return GeneratorOf(nodes.generate()) } class func createString(#omitXMLDeclaration: Bool, encoding: String? = nil, doctypeString: String?, childrenString: String) -> String { var result = "" if !omitXMLDeclaration { result += "<?xml version=\"1.0\"" if let e = encoding { result += " encoding=\"\(e)\"" } result += "?>" } if let dtString = doctypeString { result += dtString } result += childrenString return result } public func toString(encoding: String? = nil) -> String { if element.name == nil { return "" } var doctypeString: String? if let dt = doctype { if let n = element.name { doctypeString = dt.toString(n) } } var childrenString = "" for child in self { childrenString += child.description } return XMLDocument.createString(omitXMLDeclaration: omitXMLDeclaration, encoding: encoding, doctypeString: doctypeString, childrenString: childrenString) } } public func == (left: XMLDocument, right: XMLDocument) -> Bool { return left.omitXMLDeclaration == right.omitXMLDeclaration && left.doctype == right.doctype && left.beforeElement == right.beforeElement && left.element == right.element && left.afterElement == right.afterElement } public class XMLText: XMLNode, Equatable { public let nodeType = XMLNodeType.Text public var content: String public var description: String { return XMLText.createString(content) } public init(_ content: String) { self.content = content } class func createString(content: String) -> String { return XMLUtilities.escape(content) } } public func == (left: XMLText, right: XMLText) -> Bool { return left.content == right.content } /** Represents a XML comment node. Note that a value assigned to the property/initialization parameter `content` is stripped of invalid character combinations: a dash ("-") may not appear at the beginning or the end and in between only single dashes may appear. */ public class XMLComment: XMLMiscNode, Equatable { public let nodeType = XMLNodeType.Comment private var _content: String? public var content: String? { get { return _content } set { _content = XMLUtilities.enforceCommentContent(newValue) } } public var description: String { if let c = content { return XMLComment.createString(c) } return "" } public init(_ content: String) { self.content = content } class func createString(content: String) -> String { return "<!--\(content)-->" } } public func == (left: XMLComment, right: XMLComment) -> Bool { return left.content == right.content } public class XMLProcessingInstruction: XMLMiscNode, Equatable { public let nodeType = XMLNodeType.ProcessingInstruction private var _target: String? public var target: String? { get { return _target } set { _target = XMLUtilities.enforceProcessingInstructionTarget(newValue) } } private var _value: String? public var value: String? { get { return _value } set { _value = XMLUtilities.enforceProcessingInstructionValue(newValue) } } public var description: String { if let t = target { return XMLProcessingInstruction.createString(t, value: value) } return "" } public init(_ target: String, _ value: String? = nil) { self.target = target self.value = value } class func createString(target: String, value: String?) -> String { var result = "" result += "<?\(target)" if let v = value { result += " \(v)" } result += "?>" return result } } public func == (left: XMLProcessingInstruction, right: XMLProcessingInstruction) -> Bool { return left.target == right.target && left.value == right.value }
0732965431e9bb10c5242f1373c12db7
24.057471
80
0.573089
false
false
false
false
zjjzmw1/speedxSwift
refs/heads/master
speedxSwift/speedxSwift/Tool/UIView+Util.swift
mit
1
// // UIView+Util.swift // speedxSwift // // Created by speedx on 16/4/21. // Copyright © 2016年 speedx. All rights reserved. // import Foundation import UIKit extension UIView { /// 左边 - 读、写 func left() -> CGFloat! { return self.frame.origin.x } func left(x:CGFloat) { var aFrame : CGRect = self.frame aFrame.origin.x = x self.frame = aFrame } /// 上边 - 读、写 func top() -> CGFloat! { return self.frame.origin.y } func top(y:CGFloat) { var aFrame : CGRect = self.frame aFrame.origin.y = y self.frame = aFrame } /// 宽度 - 读、写 func width() -> CGFloat! { return self.frame.size.width } func width(w:CGFloat) { var aFrame : CGRect = self.frame aFrame.size.width = w self.frame = aFrame } /// 高度 - 读、写 func height() -> CGFloat! { return self.frame.size.height } func height(h:CGFloat) { var aFrame : CGRect = self.frame aFrame.size.height = h self.frame = aFrame } /// 右边 - 读 func right() -> CGFloat! { return self.frame.origin.x + self.frame.size.width } /// 下边 - 读 func bottom() -> CGFloat! { return self.frame.origin.y + self.frame.size.height } /// 中心x - 读、写 func centerX() -> CGFloat! { return self.center.x } func centerX(cX:CGFloat) { self.center = CGPointMake(cX, self.center.y) } /// 中心y - 读、写 func centerY() -> CGFloat! { return self.center.y } func centerY(cY:CGFloat) { self.center = CGPointMake(self.center.x, cY) } /// 删除所有子视图 func removeAllSubViews() { while self.subviews.count > 0 { let child : UIView = self.subviews.last! child.removeFromSuperview() } } }
73b3c7e1b837286545a5917adcc02549
22.097561
59
0.525092
false
false
false
false
pyanfield/ataturk_olympic
refs/heads/master
swift_programming_properties_methods.playground/section-1.swift
mit
1
// Playground - noun: a place where people can play import UIKit // 2.10 // 由于结构体(struct)属于值类型。当值类型的实例被声明为常量的时候,它的所有属性也就成了常量。 // 引用类型的类(class)则不一样,把一个引用类型的实例赋给一个常量后,仍然可以修改实例的变量属性。 // 延迟存储属性 // 延迟存储属性是指当第一次被调用的时候才会计算其初始值的属性。在属性声明前使用 lazy 来标示一个延迟存储属性。 // 必须将延迟存储属性声明成变量(使用 var 关键字),因为属性的值在实例构造完成之前可能无法得到。 // 而常量属性在构造过程完成之前必须要有初始值,因此无法声明成延迟属性。 // 延迟属性很有用,当属性的值依赖于在实例的构造过程结束前无法知道具体值的外部因素时,或者当属性的值需要复杂或大量计算时,可以只在需要的时候来计算它。 // 因为对于某些诸如导入文件等消耗时间的操作,可以将其声明为 lazy 属性,这样只有在用的时候再去实例化。 class DataImporter { /* DataImporter 是一个将外部文件中的数据导入的类。 这个类的初始化会消耗不少时间。 */ var fileName = "data.txt" // 这是提供数据导入功能 } class DataManager { lazy var importer = DataImporter() var data = [String]() // 这是提供数据管理功能 } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") // DataImporter 实例的 importer 属性还没有被创建 println(manager.importer.fileName) // DataImporter 实例的 importer 属性现在被创建了 // 输出 "data.txt” // 计算属性 struct Point { var x = 0.0, y = 0.0 } struct Size { var width = 0.0, height = 0.0 } struct Rect { var origin = Point() var size = Size() var center: Point { get { let centerX = origin.x + (size.width / 2) let centerY = origin.y + (size.height / 2) return Point(x: centerX, y: centerY) } set(newCenter) { // 如果不设置 newCenter,将自动使用 newValue 作为设置的新值的参数名 origin.x = newCenter.x - (size.width / 2) origin.y = newCenter.y - (size.height / 2) } } } var square = Rect(origin: Point(x: 0.0, y: 0.0), size: Size(width: 10.0, height: 10.0)) let initialSquareCenter = square.center square.center = Point(x: 15.0, y: 15.0) println("square.origin is now at (\(square.origin.x), \(square.origin.y))") // 只读计算属性 // 只有 getter 没有 setter 的计算属性就是只读计算属性。只读计算属性总是返回一个值,可以通过点运算符访问,但不能设置新的值。 struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 // 只读属性,可以省略 get 关键字和花括号 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") // 属性观察器 // 属性观察器监控和响应属性值的变化,每次属性被设置值的时候都会调用属性观察器,甚至新的值和现在的值相同的时候也不例外。 // willSet 在设置新的值之前调用 // didSet 在新的值被设置之后立即调用, 如果在didSet观察器里为属性赋值,这个值会替换观察器之前设置的值。 class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { // 如果不设置参数名,则默认是 newValue println("About to set totalSteps to \(newTotalSteps)") } didSet { // 可以自定义参数名称,如果不设置参数名,则默认是 oldValue if totalSteps > oldValue { println("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 // About to set totalSteps to 200 // Added 200 steps stepCounter.totalSteps = 360 // About to set totalSteps to 360 // Added 160 steps // 计算属性和属性观察器所描述的模式也可以用于全局变量和局部变量. // 全局的常量或变量都是延迟计算的,跟延迟存储属性相似,不同的地方在于,全局的常量或变量不需要标记lazy特性。 // 局部范围的常量或变量不会延迟计算。 // 类型属性 // 类型属性用于定义特定类型所有实例共享的数据,比如所有实例都能用的一个常量(就像 C 语言中的静态常量),或者所有实例都能访问的一个变量(就像 C 语言中的静态变量)。 // 使用关键字static来定义值类型的类型属性,关键字class来为类(class)定义类型属性。 struct SomeStructure { // 对于 struct , enum 这样值类型的,可以定义存储型,也可以是计算类型属性 static var storedTypeProperty = "Some value." static var computedTypeProperty: Int{ return 999 } } enum SomeEnumeration { static var storedTypeProperty = "Some value." static var computedTypeProperty = 2 } class SomeClass { // 对于类,只能定义计算类型属性 class var computedTypeProperty: Int{ return 999 } } SomeClass.computedTypeProperty SomeEnumeration.storedTypeProperty SomeStructure.computedTypeProperty // 2.11 class Counter { var count: Int = 0 // 默认第二个参数如果没有设置外部参数名,则外部参数名和内部参数名一致,类似默认条件了 # func incrementBy(amount: Int, numberOfTimes: Int) { // 该处可以使用 self.count, 如果参数名中有 count ,则必须使用 self.count count += amount * numberOfTimes } // 设置外部参数名给第二个参数 // 默认调用的时候可以省略第一参数名 func add(number: Int, toNumber number2: Int) -> Int{ return number + number2 } // 强制第一个参数名内外一致, 第二个参数省略参数名 func subduction(#number:Int, _ second:Int) -> Int{ return number - second } } let counter = Counter() counter.incrementBy(10, numberOfTimes: 2) counter.count counter.add(10, toNumber: 10) counter.subduction(number: 10, 10) // 结构体和枚举是值类型。一般情况下,值类型的属性不能在它的实例方法中被修改。 // 如果你确实需要在某个具体的方法中修改结构体或者枚举的属性,你可以选择变异(mutating)这个方法,然后方法就可以从方法内部改变它的属性 struct MutablePoint { var x = 0.0, y = 0.0 // 注意这里用 mutating 来修饰 mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } mutating func moveBackBy(deltaX: Double, deltaY: Double){ // mutating 方法能赋值给隐含属性 self 一个全新的实例 self = MutablePoint(x: x-deltaX, y: y-deltaY) } } var somePoint = MutablePoint(x: 1.0, y: 1.0) somePoint.moveByX(2.0, y: 3.0) println("The point is now at (\(somePoint.x), \(somePoint.y))") somePoint.moveBackBy(1.0, deltaY: 1.0) println("The point is now at (\(somePoint.x), \(somePoint.y))") enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case Off: self = Low case Low: self = High case High: self = Off } } } var ovenLight = TriStateSwitch.Low ovenLight.next() // ovenLight 现在等于 .High ovenLight.next() // ovenLight 现在等于 .Off // 类型方法(Type Methods) // 声明类的类型方法,在方法的func关键字之前加上关键字class;声明结构体和枚举的类型方法,在方法的func关键字之前加上关键字static。 class SomeClassA { class func someTypeMethod() { println("called from class method") } } SomeClassA.someTypeMethod() // 游戏初始时,所有的游戏等级(除了等级 1)都被锁定。每次有玩家完成一个等级,这个等级就对这个设备上的所有玩家解锁。 // 同时检测玩家的当前等级。 struct LevelTracker { static var highestUnlockedLevel = 1 // 类型方法 static func unlockLevel(level: Int) { if level > highestUnlockedLevel { // bug here: 在 playground 中,如果直接给 highestUnlockedLevel = level ,会报错 EXC_BAD_ACCESS (code=EXC_I386_GPFLT) // 但是如果在 Application 中就不会有这个错误 LevelTracker.highestUnlockedLevel = level } } static func levelIsUnlocked(level: Int) -> Bool { return level <= highestUnlockedLevel } var currentLevel = 1 mutating func advanceToLevel(level: Int) -> Bool { if LevelTracker.levelIsUnlocked(level) { currentLevel = level return true } else { return false } } } class Player { var tracker = LevelTracker() // 注意这里是 let 定义的常量,在 init 初始化的时候可以设置初始值,之后就不能改变了。 let playerName: String func completedLevel(level: Int) { LevelTracker.unlockLevel(level + 1) tracker.advanceToLevel(level + 1) } init(name: String) { playerName = name } } var player = Player(name: "Argyrios") player.completedLevel(2) player.playerName //println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")
aaab314c592cdd034f03711faf340bca
26.808765
117
0.663037
false
false
false
false
limaoxuan/MXAutoLayoutScrollView
refs/heads/master
MXAutoLayoutScrollView/MXAutoLayoutScrollView/MXConstrains.swift
apache-2.0
3
// // CCConstrains.swift // MyNews // // Created by 李茂轩 on 15/1/29. // Copyright (c) 2015年 lee. All rights reserved. // import UIKit func setConstraintsWithStringWithCurrentView(format : String,superView : UIView,viewDic : NSDictionary)->Void{ var constaraints = NSLayoutConstraint.constraintsWithVisualFormat(format, options: NSLayoutFormatOptions(0), metrics: nil, views:viewDic as [NSObject : AnyObject]) superView.addConstraints(constaraints) } func setConstraintsWithStringHandVWithCurrentView(formatH : String,formatV : String,superView : UIView,viewDic : NSDictionary)->Void{ setConstraintsWithStringWithCurrentView(formatH, superView, viewDic) setConstraintsWithStringWithCurrentView(formatV, superView, viewDic) } func setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterY(superView :UIView,currentView:UIView,height:Int)->Void{ let dic = ["currentView":currentView] setConstraintsWithStringWithCurrentView("V:[currentView(\(height))]", superView, dic) let constaraint = NSLayoutConstraint(item: currentView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0) superView.addConstraint(constaraint) } func setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterX(superView :UIView,currentView:UIView,width:String)->Void{ let dic = ["currentView":currentView] setConstraintsWithStringWithCurrentView("H:[currentView(\(width))]", superView, dic) let constaraint = NSLayoutConstraint(item: currentView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: superView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0) superView.addConstraint(constaraint) } /** This is setting a view that It is in the superview center :param: superView superView His father view :param: currentView currentView son view */ /** 设置一个居于父级视图中心的视图 :param: superView 父亲视图 :param: currentView 儿子视图 */ func setLocationCurrentInSuperViewlocationCenter(superView :UIView,currentView:UIView,width:String,height:Int)->Void{ setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterX(superView, currentView,width) setLocationAccrodingWithSuperViewAndCurrentViewSetLayoutAttributeCenterY(superView, currentView,height) }
5b8403568c4605182c58307a00d4acae
28.547619
220
0.771958
false
false
false
false
codwam/NPB
refs/heads/master
Demos/SystemDemo/SystemDemo/Custom Test/TestPopAnimation.swift
mit
1
// // TestPopAnimation.swift // NPBDemo // // Created by 李辉 on 2017/4/7. // Copyright © 2017年 codwam. All rights reserved. // import UIKit /* Copy From https://github.com/zys456465111/CustomPopAnimation 里面写得很详细,不清楚的可以看里面的源码 */ enum PopAnimationType { case pop case flipFromLeft case cube } class TestPopAnimation: NSObject, UIViewControllerAnimatedTransitioning { fileprivate var transitionContext: UIViewControllerContextTransitioning? fileprivate let popAnimationType: PopAnimationType = .pop // MARK: - UIViewControllerAnimatedTransitioning func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.25 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromViewController = transitionContext.viewController(forKey: .from)! let toViewController = transitionContext.viewController(forKey: .to)! let containerView = transitionContext.containerView containerView.insertSubview(toViewController.view, belowSubview: fromViewController.view) // 动画时间 let duration = transitionDuration(using: transitionContext) self.transitionContext = transitionContext switch self.popAnimationType { case .pop: // 模仿系统pop UIView.animate(withDuration: duration, animations: { let x = fromViewController.view.bounds.width let transform = CGAffineTransform(translationX: x, y: 0) fromViewController.view.transform = transform // 实际上系统的左边还有点偏移 // let toTransform = CGAffineTransform(translationX: -20, y: 0) // toViewController.view.transform = toTransform }) { (_) in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) // toViewController.view.transform = .identity } case .flipFromLeft: //----------------pop动画一-------------------------// UIView.beginAnimations("View Flip", context: nil) UIView.setAnimationDuration(duration) UIView.setAnimationTransition(.flipFromLeft, for: containerView, cache: true) UIView.setAnimationDelegate(self) UIView.setAnimationDidStop(#selector(TestPopAnimation.animationDidStop(_:finished:))) UIView.commitAnimations() containerView.exchangeSubview(at: 0, withSubviewAt: 1) case .cube: //----------------pop动画二-------------------------// let transition = CATransition() transition.type = "cube" transition.subtype = kCATransitionFromLeft transition.duration = duration transition.isRemovedOnCompletion = false transition.fillMode = kCAFillModeForwards transition.delegate = self containerView.layer.add(transition, forKey: nil) containerView.exchangeSubview(at: 0, withSubviewAt: 1) } } } extension TestPopAnimation: CAAnimationDelegate { func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let transitionContext = self.transitionContext { transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } }
c89730549e308cd78e0f8528e485016b
38.034483
109
0.655183
false
false
false
false
Quick/Spry
refs/heads/master
Source/Spry/Matchers/beginWith.swift
apache-2.0
1
import Foundation /// A Nimble matcher that succeeds when the actual sequence's first element /// is equal to the expected value. public func beginWith<S: Sequence, T: Equatable>(_ startingElement: T) -> Matcher<S> where S.Iterator.Element == T { return Matcher { actualExpression in if let actualValue = try actualExpression.evaluate() { var actualGenerator = actualValue.makeIterator() return actualGenerator.next() == startingElement } return false } } /// A Nimble matcher that succeeds when the actual string contains expected substring /// where the expected substring's location is zero. public func beginWith(_ startingSubstring: String) -> Matcher<String> { return Matcher { actualExpression in if let actual = try actualExpression.evaluate() { let range = actual.range(of: startingSubstring) return range != nil && range!.lowerBound == actual.startIndex } return false } }
c7fd85b1ac23e372349693d0026b0bbc
37.148148
85
0.659223
false
false
false
false
LDlalala/LDZBLiving
refs/heads/master
LDZBLiving/LDZBLiving/Classes/Main/LDPageView/LDContentView.swift
mit
1
// // LDContentView.swift // LDPageView // // Created by 李丹 on 17/8/2. // Copyright © 2017年 LD. All rights reserved. // import UIKit private let cellID : String = "cellID" protocol LDContentViewDelegate : class { func contentView(_ contentView : LDContentView, targetIndex : Int, progress : CGFloat) } class LDContentView: UIView { weak var delegate : LDContentViewDelegate? fileprivate var childVcs : [UIViewController]! fileprivate var parent : UIViewController! fileprivate var startOffsetX : CGFloat = 0 fileprivate lazy var collectionView : UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: self.bounds.width, height: self.bounds.height) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: layout) collectionView.delegate = self collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID) collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.showsHorizontalScrollIndicator = false collectionView.scrollsToTop = false return collectionView }() init(frame : CGRect , childVcs : [UIViewController] , parent : UIViewController) { super.init(frame: frame) self.childVcs = childVcs self.parent = parent setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension LDContentView { fileprivate func setupUI(){ for vc in childVcs { parent.addChildViewController(vc) } // 添加conllection addSubview(collectionView) } } // MARK:- UICollectionViewDataSource extension LDContentView : 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: cellID, for: indexPath) cell.backgroundColor = UIColor.randomColor() for subview in cell.contentView.subviews { subview.removeFromSuperview() } let childVc = childVcs[indexPath.row] childVc.view.frame = cell.bounds cell.contentView.addSubview(childVc.view) return cell } } // MARK:- UICollectionViewDelegate extension LDContentView : UICollectionViewDelegate { // 开始拖拽 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { startOffsetX = scrollView.contentOffset.x } // 停止滚动 func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollEnd(scrollView) } // 手动拖拽时停止 func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate == false { scrollEnd(scrollView) } } // 滚动停止的事件处理 private func scrollEnd(_ scrollView : UIScrollView){ // 记录偏移量 let offsetX = scrollView.contentOffset.x - startOffsetX let targetIndex = scrollView.contentOffset.x / bounds.width // 通知titleview做点击选中处理 delegate?.contentView(self, targetIndex: Int(targetIndex), progress: offsetX) } } // MARK:- 实现titleView的代理方法 extension LDContentView : LDTitleViewDelegate{ func titleView(_ titleView : LDTitleView, targetIndex : Int) { let indexPath = IndexPath.init(row: targetIndex, section: 0) collectionView.scrollToItem(at: indexPath, at: .right, animated: false) } }
a27a60c959974d1ced55b096a3a21a13
28.15942
121
0.66327
false
false
false
false
netguru/inbbbox-ios
refs/heads/develop
Unit Tests/AutoScrollableShotsAnimatorSpec.swift
gpl-3.0
1
// // AutoScrollableShotsAnimatorSpec.swift // Inbbbox // // Created by Patryk Kaczmarek on 31/12/15. // Copyright © 2015 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble @testable import Inbbbox class AutoScrollableShotsAnimatorSpec: QuickSpec { override func spec() { var sut: AutoScrollableShotsAnimator! var collectionViews: [UICollectionView]! // keep reference to be able to check expectation let content = [ UIImage.referenceImageWithColor(.green), UIImage.referenceImageWithColor(.yellow), UIImage.referenceImageWithColor(.red) ] var mockSuperview: UIView! beforeEach { let collectionView_1 = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout()) let collectionView_2 = UICollectionView(frame: CGRect(x: 0, y: 0, width: 100, height: 200), collectionViewLayout: UICollectionViewFlowLayout()) collectionViews = [collectionView_1, collectionView_2] let bindForAnimation = collectionViews.map { (collectionView: $0, shots: content) } mockSuperview = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) mockSuperview.addSubview(collectionView_1) mockSuperview.addSubview(collectionView_2) sut = AutoScrollableShotsAnimator(bindForAnimation: bindForAnimation) } afterEach { sut = nil collectionViews = nil mockSuperview = nil } it("when newly created, content offset should be 0") { expect(collectionViews.map{ $0.contentOffset }).to(equal([CGPoint.zero, CGPoint.zero])) } describe("when scrolling to middle") { beforeEach { sut.scrollToMiddleInstantly() } it("collection views should be in the middle") { let middlePoint = CGPoint(x: 0, y: -100) expect(collectionViews.map{ $0.contentOffset }).to(equal([middlePoint, middlePoint])) } } describe("when performing scroll animation") { afterEach { sut.stopAnimation() } context("first collection view") { var initialValueY: CGFloat! beforeEach { initialValueY = collectionViews[0].contentOffset.y sut.startScrollAnimationInfinitely() RunLoop.current.run(until: NSDate() as Date) } it("should be scrolled up") { expect(collectionViews[0].contentOffset.y).toEventually(beGreaterThan(initialValueY)) } } context("collection view") { var initialValueY: CGFloat! beforeEach { initialValueY = collectionViews[1].contentOffset.y sut.startScrollAnimationInfinitely() RunLoop.current.run(until: NSDate() as Date) } it("should be scrolled down") { expect(collectionViews[1].contentOffset.y).toEventually(beLessThan(initialValueY)) } } context("and stopping it") { beforeEach { sut.stopAnimation() } context("first collection view") { var initialValueY: CGFloat! beforeEach { initialValueY = collectionViews[0].contentOffset.y } it("first collection view should be in same place") { expect(collectionViews[0].contentOffset.y).toEventually(equal(initialValueY)) } } context("second collection view") { var initialValueY: CGFloat! beforeEach { initialValueY = collectionViews[1].contentOffset.y } it("first collection view should be in same place") { expect(collectionViews[1].contentOffset.y).toEventually(equal(initialValueY)) } } } } } }
0003c5f52118619525eaa3da256155ef
34.644444
155
0.497091
false
false
false
false
jorjuela33/JOCoreDataKit
refs/heads/master
JOCoreDataKit/Extensions/NSPersistentStoreCoordinator+Additions.swift
mit
1
// // NSPersistentStoreCoordinator+Additions.swift // // Copyright © 2017. All rights reserved. // // 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 CoreData extension NSPersistentStoreCoordinator { // MARK: Instance methods /// creates a new store /// /// url - the location for the store /// type - the store type @discardableResult public func createPersistentStore(atURL url: URL?, type: String = NSSQLiteStoreType) -> Error? { var error: Error? do { let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] try addPersistentStore(ofType: type, configurationName: nil, at: url, options: options) } catch let storeError { error = storeError } return error } /// destroy the persistent store for the given context /// /// url - the url for the store location /// type - the store type public func destroyPersistentStore(atURL url: URL, type: String = NSSQLiteStoreType) { do { if #available(iOS 9.0, *) { try destroyPersistentStore(at: url, ofType: type, options: nil) } else if let persistentStore = persistentStores.last { try remove(persistentStore) try FileManager.default.removeItem(at: url) } } catch { print("unable to destroy perstistent store at url: \(url), type: \(type)") } } /// migrates the current store to the given url /// /// url - the new location for the store public func migrate(to url: URL) { guard let currentStore = persistentStores.last else { return } try! migratePersistentStore(currentStore, to: url, options: nil, withType: NSSQLiteStoreType) } }
2522ff002fdaa8d0489d6e35465f8cb7
38.2
124
0.662245
false
false
false
false
SASAbus/SASAbus-ios
refs/heads/master
SASAbus/Data/Vdv/DataDownloader.swift
gpl-3.0
1
import Foundation import RxSwift import RxCocoa import Alamofire class DataDownloader { static let FILENAME_OFFLINE = "data.zip" static func downloadFile(destinationUrl: URL) -> Observable<Float> { return Observable.create { observer in Log.debug("Downloading planned data to \(destinationUrl)") let fileManager = FileManager.default // Delete old files let dataDirectory = IOUtils.dataDir() if fileManager.fileExists(atPath: dataDirectory.path) { do { try fileManager.removeItem(at: dataDirectory) Log.warning("Deleted old data directory") } catch let error { ErrorHelper.log(error, message: "Could not delete old data directory: \(error)") } } if fileManager.fileExists(atPath: destinationUrl.path) { do { try fileManager.removeItem(at: destinationUrl) Log.warning("Deleted old data.zip") } catch let error { ErrorHelper.log(error, message: "Could not delete data.zip: \(error)") } } // Download new planned data let destination: DownloadRequest.DownloadFileDestination = { _, _ in return (destinationUrl, [.removePreviousFile, .createIntermediateDirectories]) } let progress: Alamofire.Request.ProgressHandler = { progress in observer.on(.next(Float(progress.fractionCompleted))) } let zipUrl = Endpoint.newDataApiUrl Log.info("Data url is '\(zipUrl)'") // Download new data let request = Alamofire.download(zipUrl, to: destination) .downloadProgress(queue: DispatchQueue.main, closure: progress) .response(queue: DispatchQueue(label: "com.sasabus.download", qos: .utility, attributes: [.concurrent])) { response in if let error = response.error { observer.on(.error(error)) return } do { Log.info("Unzipping zip file '\(destination)'") try ZipUtils.unzipFile(from: destinationUrl, to: IOUtils.dataDir()) let fileManager = FileManager.default try fileManager.removeItem(atPath: destinationUrl.path) } catch { observer.on(.error(error)) return } PlannedData.dataAvailable = true PlannedData.setUpdateAvailable(false) PlannedData.setUpdateDate() do { try VdvHandler.loadBlocking(observer) } catch { observer.on(.error(error)) return } observer.on(.completed) } return Disposables.create { request.cancel() } } } static func downloadPlanData() -> Observable<Float> { Log.warning("Starting plan data download") let baseUrl = IOUtils.storageDir() let destinationUrl = baseUrl.appendingPathComponent(FILENAME_OFFLINE) return downloadFile(destinationUrl: destinationUrl) } }
ab8b048476603e0fc2a2f5dd23012bc9
35.823529
134
0.492545
false
false
false
false
MAARK/Charts
refs/heads/master
ChartsDemo-iOS/Swift/Demos/MultipleLinesChartViewController.swift
apache-2.0
2
// // MultipleLinesChartViewController.swift // ChartsDemo-iOS // // Created by Jacob Christie on 2017-07-09. // Copyright © 2017 jc. All rights reserved. // import UIKit import Charts class MultipleLinesChartViewController: DemoBaseViewController { @IBOutlet var chartView: LineChartView! @IBOutlet var sliderX: UISlider! @IBOutlet var sliderY: UISlider! @IBOutlet var sliderTextX: UITextField! @IBOutlet var sliderTextY: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.title = "Multiple Lines Chart" self.options = [.toggleValues, .toggleFilled, .toggleCircles, .toggleCubic, .toggleStepped, .toggleHighlight, .animateX, .animateY, .animateXY, .saveToGallery, .togglePinchZoom, .toggleAutoScaleMinMax, .toggleData] chartView.delegate = self chartView.chartDescription?.enabled = false chartView.leftAxis.enabled = false chartView.rightAxis.drawAxisLineEnabled = false chartView.xAxis.drawAxisLineEnabled = false chartView.drawBordersEnabled = false chartView.setScaleEnabled(true) let l = chartView.legend l.horizontalAlignment = .right l.verticalAlignment = .top l.orientation = .vertical l.drawInside = false // chartView.legend = l sliderX.value = 20 sliderY.value = 100 slidersValueChanged(nil) } override func updateChartData() { if self.shouldHideData { chartView.data = nil return } self.setDataCount(Int(sliderX.value), range: UInt32(sliderY.value)) } // TODO: Refine data creation func setDataCount(_ count: Int, range: UInt32) { let colors = ChartColorTemplates.vordiplom()[0...2] let block: (Int) -> ChartDataEntry = { (i) -> ChartDataEntry in let val = Double(arc4random_uniform(range) + 3) return ChartDataEntry(x: Double(i), y: val) } let dataSets = (0..<3).map { i -> LineChartDataSet in let yVals = (0..<count).map(block) let set = LineChartDataSet(entries: yVals, label: "DataSet \(i)") set.lineWidth = 2.5 set.circleRadius = 4 set.circleHoleRadius = 2 let color = colors[i % colors.count] set.setColor(color) set.setCircleColor(color) return set } dataSets[0].lineDashLengths = [5, 5] dataSets[0].colors = ChartColorTemplates.vordiplom() dataSets[0].circleColors = ChartColorTemplates.vordiplom() let data = LineChartData(dataSets: dataSets) data.setValueFont(.systemFont(ofSize: 7, weight: .light)) chartView.data = data } override func optionTapped(_ option: Option) { switch option { case .toggleFilled: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawFilledEnabled = !set.drawFilledEnabled } chartView.setNeedsDisplay() case .toggleCircles: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.drawCirclesEnabled = !set.drawCirclesEnabled } chartView.setNeedsDisplay() case .toggleCubic: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .cubicBezier) ? .linear : .cubicBezier } chartView.setNeedsDisplay() case .toggleStepped: for set in chartView.data!.dataSets as! [LineChartDataSet] { set.mode = (set.mode == .stepped) ? .linear : .stepped } chartView.setNeedsDisplay() default: super.handleOption(option, forChartView: chartView) } } @IBAction func slidersValueChanged(_ sender: Any?) { sliderTextX.text = "\(Int(sliderX.value))" sliderTextY.text = "\(Int(sliderY.value))" self.updateChartData() } }
bad8b34d70c88ebe8ebb73d1a861b00f
31.724638
78
0.556466
false
false
false
false
iachievedit/moreswift
refs/heads/master
foundation/notification.swift
apache-2.0
1
import Foundation import Glibc let inputNotificationName = Notification.Name(rawValue:"InputNotification") let inputNotification = Notification(name:inputNotificationName, object:nil) let nc = NotificationCenter.default var availableData = "" let readThread = Thread(){ print("Entering thread... type something and have it echoed.") let delim:Character = "\n" var input:String = "" while true { let c = Character(UnicodeScalar(UInt32(fgetc(stdin)))!) if c == delim { availableData = input nc.post(inputNotification) input = "" } else { input.append(c) } } // Our read thread never exits } _ = nc.addObserver(forName:inputNotificationName, object:nil, queue:nil) { (_) in print("Echo: \(availableData)") } readThread.start() select(0, nil, nil, nil, nil) // Forever sleep
efd57d6d322e8e22e9f050b9bb64ec49
24.333333
76
0.686603
false
false
false
false
cloudinary/cloudinary_ios
refs/heads/master
Cloudinary/Classes/Core/Utils/CLDImageCache.swift
mit
1
// // CLDImageCache.swift // // Copyright (c) 2016 Cloudinary (http://cloudinary.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import UIKit @objc public enum CLDImageCachePolicy: Int { case none, memory, disk } internal struct Defines { static let cacheDefaultName = "defaultImageCache" static let cacheAssetDefaultName = "defaultAssetCache" static let cacheBaseName = "com.cloudinary.sdk.imageCache" static let readWriteQueueName = "com.cloudinary.sdk.imageCache.readWriteQueue" static let defaultMemoryTotalCostLimit = 30 * 1024 * 1024 // 30 MB static let defaultMaxDiskCapacity = 150 * 1024 * 1024 // 150 MB static let thresholdPercentSize = UInt64(0.8) static let defaultBytesPerPixel = 4 } internal class CLDImageCache { internal var cachePolicy = CLDImageCachePolicy.disk fileprivate let memoryCache = NSCache<NSString, UIImage>() internal var maxMemoryTotalCost: Int = Defines.defaultMemoryTotalCostLimit { didSet{ memoryCache.totalCostLimit = maxMemoryTotalCost self.clearMemoryCache() } } fileprivate let diskCacheDir: String // Disk Size Control internal var maxDiskCapacity: UInt64 = UInt64(Defines.defaultMaxDiskCapacity) { didSet { clearDiskToMatchCapacityIfNeeded() } } fileprivate var usedCacheSize: UInt64 = 0 fileprivate let readWriteQueue: DispatchQueue //MARK: - Lifecycle init(name: String, diskCachePath: String? = nil) { let cacheName = "\(Defines.cacheBaseName).\(name)" memoryCache.name = cacheName // We have to set this manually here since `maxMemoryTotalCost.didSet()` is never triggered during init memoryCache.totalCostLimit = maxMemoryTotalCost let diskPath = diskCachePath ?? NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! diskCacheDir = diskPath.cldStringByAppendingPathComponent(str: cacheName) readWriteQueue = DispatchQueue(label: Defines.readWriteQueueName + name, attributes: []) calculateCurrentDiskCacheSize() clearDiskToMatchCapacityIfNeeded() NotificationCenter.default.addObserver(self, selector: #selector(CLDImageCache.clearMemoryCache), name: UIApplication.didReceiveMemoryWarningNotification, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Get Object internal func getImageForKey(_ key: String, completion: @escaping (_ image: UIImage?) -> ()) { let callCompletionClosureOnMain = { (image: UIImage?) in DispatchQueue.main.async { completion(image) } } if let memoryImage = memoryCache.object(forKey: key as NSString) { let path = getFilePathFromKey(key) readWriteQueue.async { self.updateDiskImageModifiedDate(path) } callCompletionClosureOnMain(memoryImage) } else { readWriteQueue.async { if let diskImage = self.getImageFromDiskForKey(key) { callCompletionClosureOnMain(diskImage) self.cacheImage(diskImage, data: nil, key: key, includingDisk: false, completion: nil) } else { callCompletionClosureOnMain(nil) } } } } // MARK: - Set Object internal func cacheImage(_ image: UIImage, data: Data?, key: String, completion: (() -> ())?) { cacheImage(image, data: data, key: key, includingDisk: true, completion: completion) } func costFor(image: UIImage) -> Int { if let imageRef = image.cgImage { return imageRef.bytesPerRow * imageRef.height } // Without the underlying cgImage we can only estimate, assuming 4 bytes per pixel (RGBA): return Int(image.size.height * image.scale * image.size.width * image.scale) * Defines.defaultBytesPerPixel } fileprivate func cacheImage(_ image: UIImage, data: Data?, key: String, includingDisk: Bool, completion: (() -> ())?) { if cachePolicy == .memory || cachePolicy == .disk { let cost = costFor(image: image) memoryCache.setObject(image, forKey: key as NSString, cost: cost) } if cachePolicy == .disk && includingDisk { let path = getFilePathFromKey(key) readWriteQueue.async { // If the original data was passed, save the data to the disk, otherwise default to UIImagePNGRepresentation to create the data from the image if let data = data ?? image.pngData() { // create the cach directory if it doesn't exist if !FileManager.default.fileExists(atPath: self.diskCacheDir) { do { try FileManager.default.createDirectory(atPath: self.diskCacheDir, withIntermediateDirectories: true, attributes: nil) } catch { printLog(.warning, text: "Failed while attempting to create the image cache directory.") } } FileManager.default.createFile(atPath: path, contents: data, attributes: nil) self.usedCacheSize += UInt64(data.count) self.clearDiskToMatchCapacityIfNeeded() } else { printLog(.warning, text: "Couldn't convert image to data for key: \(key)") } completion?() } } else { completion?() } } // MARK: - Remove Object internal func removeCacheImageForKey(_ key: String) { memoryCache.removeObject(forKey: key as NSString) let path = getFilePathFromKey(key) removeFileAtPath(path) } fileprivate func removeFileAtPath(_ path: String) { readWriteQueue.async { if let fileAttr = self.getFileAttributes(path) { let fileSize = fileAttr.fileSize() do { try FileManager.default.removeItem(atPath: path) self.usedCacheSize = self.usedCacheSize > fileSize ? self.usedCacheSize - fileSize : 0 } catch { printLog(.warning, text: "Failed while attempting to remove a cached file") } } } } // MARK: - Clear fileprivate func clearDiskToMatchCapacityIfNeeded() { if usedCacheSize < maxDiskCapacity { return } if let sortedUrls = sortedDiskImagesByModifiedDate() { for url in sortedUrls { removeFileAtPath(url.path) if usedCacheSize <= UInt64(maxDiskCapacity * Defines.thresholdPercentSize) { break } } } } @objc fileprivate func clearMemoryCache() { memoryCache.removeAllObjects() } // MARK: - State internal func hasCachedImageForKey(_ key: String) -> Bool { var hasCachedImage = false if memoryCache.object(forKey: key as NSString) != nil { hasCachedImage = true } else { let imagePath = getFilePathFromKey(key) hasCachedImage = hasCachedDiskImageAtPath(imagePath) } return hasCachedImage } fileprivate func hasCachedDiskImageAtPath(_ path: String) -> Bool { var hasCachedImage = false readWriteQueue.sync { hasCachedImage = FileManager.default.fileExists(atPath: path) } return hasCachedImage } // MARK: - Disk Image Helpers fileprivate func getImageFromDiskForKey(_ key: String) -> UIImage? { if let data = getDataFromDiskForKey(key) { return data.cldToUIImageThreadSafe() } return nil } fileprivate func getDataFromDiskForKey(_ key: String) -> Data? { let imagePath = getFilePathFromKey(key) updateDiskImageModifiedDate(imagePath) return (try? Data(contentsOf: URL(fileURLWithPath: imagePath))) } fileprivate func getFilePathFromKey(_ key: String) -> String { let fileName = getFileNameFromKey(key) return diskCacheDir.cldStringByAppendingPathComponent(str: fileName) } fileprivate func getFileNameFromKey(_ key: String) -> String { return key.sha256_base64() } fileprivate func updateDiskImageModifiedDate(_ path: String) { do { try FileManager.default.setAttributes([FileAttributeKey.modificationDate : Date()], ofItemAtPath: path) } catch { printLog(.warning, text: "Failed attempting to update cached file modified date.") } } // MARK: - Disk Capacity Helpers fileprivate func calculateCurrentDiskCacheSize() { let fileManager = FileManager.default usedCacheSize = 0 do { let contents = try fileManager.contentsOfDirectory(atPath: diskCacheDir) for pathComponent in contents { let filePath = diskCacheDir.cldStringByAppendingPathComponent(str: pathComponent) if let fileAttr = getFileAttributes(filePath) { usedCacheSize += fileAttr.fileSize() } } } catch { printLog(.warning, text: "Failed listing cache directory") } } fileprivate func sortedDiskImagesByModifiedDate() -> [URL]? { let dirUrl = URL(fileURLWithPath: diskCacheDir) do { let urlArray = try FileManager.default.contentsOfDirectory(at: dirUrl, includingPropertiesForKeys: [URLResourceKey.contentModificationDateKey], options:.skipsHiddenFiles) return urlArray.map { url -> (URL, TimeInterval) in var lastModified : AnyObject? _ = try? (url as NSURL).getResourceValue(&lastModified, forKey: URLResourceKey.contentModificationDateKey) return (url, lastModified?.timeIntervalSinceReferenceDate ?? 0) } .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates .map { $0.0 } } catch { printLog(.warning, text: "Failed listing cache directory") return nil } } fileprivate func getFileAttributes(_ path: String) -> NSDictionary? { var fileAttr: NSDictionary? do { fileAttr = try FileManager.default.attributesOfItem(atPath: path) as NSDictionary } catch { printLog(.warning, text: "Failed while attempting to retrive a cached file attributes for filr at path: \(path)") } return fileAttr } }
545d2b50c9b7581ab2c855a29a8715ca
36.990625
182
0.613145
false
false
false
false
KrishMunot/swift
refs/heads/master
test/Parse/enum.swift
apache-2.0
8
// RUN: %target-parse-verify-swift // FIXME: this test only passes on platforms which have Float80. // <rdar://problem/19508460> Floating point enum raw values are not portable // REQUIRES: CPU=i386_or_x86_64 enum Empty {} enum Boolish { case falsy case truthy init() { self = .falsy } } var b = Boolish.falsy b = .truthy enum Optionable<T> { case Nought case Mere(T) } var o = Optionable<Int>.Nought o = .Mere(0) enum Color { case Red, Green, Grayscale(Int), Blue } var c = Color.Red c = .Green c = .Grayscale(255) c = .Blue let partialApplication = Color.Grayscale // Cases are excluded from non-enums. case FloatingCase // expected-error{{enum 'case' is not allowed outside of an enum}} struct SomeStruct { case StructCase // expected-error{{enum 'case' is not allowed outside of an enum}} } class SomeClass { case ClassCase // expected-error{{enum 'case' is not allowed outside of an enum}} } enum EnumWithExtension1 { case A1 } extension EnumWithExtension1 { case A2 // expected-error{{enum 'case' is not allowed outside of an enum}} } // Attributes for enum cases. enum EnumCaseAttributes { @xyz case EmptyAttributes // expected-error {{unknown attribute 'xyz'}} } // Recover when a switch 'case' label is spelled inside an enum (or outside). enum SwitchEnvy { case X: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X, Y: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y), Z(W): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y) where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} case _: // expected-error{{'case' label can only appear inside a 'switch' statement}} case (_, var x, 0): // expected-error{{'case' label can only appear inside a 'switch' statement}} } enum HasMethodsPropertiesAndCtors { case TweedleDee case TweedleDum func method() {} func staticMethod() {} init() {} subscript(x:Int) -> Int { return 0 } var property : Int { return 0 } } enum ImproperlyHasIVars { case Flopsy case Mopsy var ivar : Int // expected-error{{enums may not contain stored properties}} } // We used to crash on this. rdar://14678675 enum rdar14678675 { case U1, case U2 // expected-error{{expected identifier after comma in enum 'case' declaration}} case U3 } enum Recovery1 { case: // expected-error {{'case' label can only appear inside a 'switch' statement}} expected-error {{expected pattern}} } enum Recovery2 { case UE1: // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery3 { case UE2(): // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery4 { // expected-note {{in declaration of 'Recovery4'}} case Self Self // expected-error {{expected identifier in enum 'case' declaration}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{12-12=;}} expected-error {{expected declaration}} } enum Recovery5 { case .UE3 // expected-error {{extraneous '.' in enum 'case' declaration}} {{8-9=}} case .UE4, .UE5 // expected-error@-1{{extraneous '.' in enum 'case' declaration}} {{8-9=}} // expected-error@-2{{extraneous '.' in enum 'case' declaration}} {{14-15=}} } enum Recovery6 { case Snout, _; // expected-error {{expected identifier after comma in enum 'case' declaration}} case _; // expected-error {{expected identifier in enum 'case' declaration}} case Tusk, // expected-error {{expected pattern}} } // expected-error {{expected identifier after comma in enum 'case' declaration}} enum RawTypeEmpty : Int {} // expected-error {{an enum with no cases cannot declare a raw type}} // expected-error@-1{{type 'RawTypeEmpty' does not conform to protocol 'RawRepresentable'}} enum Raw : Int { case Ankeny, Burnside } enum MultiRawType : Int64, Int32 { // expected-error {{multiple enum raw types 'Int64' and 'Int32'}} case Couch, Davis } protocol RawTypeNotFirstProtocol {} enum RawTypeNotFirst : RawTypeNotFirstProtocol, Int { // expected-error {{raw type 'Int' must appear first in the enum inheritance clause}} {{24-24=Int, }} {{47-52=}} case E } enum RawTypeNotLiteralConvertible : Array<Int> { // expected-error {{raw type 'Array<Int>' is not convertible from any literal}} // expected-error@-1{{type 'RawTypeNotLiteralConvertible' does not conform to protocol 'RawRepresentable'}} case Ladd, Elliott, Sixteenth, Harrison } enum RawTypeCircularityA : RawTypeCircularityB, IntegerLiteralConvertible { // expected-error {{circular enum raw types 'RawTypeCircularityA' -> 'RawTypeCircularityB' -> 'RawTypeCircularityA'}} FIXME: expected-error{{RawRepresentable}} case Morrison, Belmont, Madison, Hawthorne init(integerLiteral value: Int) { self = .Morrison } } enum RawTypeCircularityB : RawTypeCircularityA, IntegerLiteralConvertible { // expected-note {{enum 'RawTypeCircularityB' declared here}} case Willamette, Columbia, Sandy, Multnomah init(integerLiteral value: Int) { self = .Willamette } } struct FloatLiteralConvertibleOnly : FloatLiteralConvertible { init(floatLiteral: Double) {} } enum RawTypeNotIntegerLiteralConvertible : FloatLiteralConvertibleOnly { // expected-error {{RawRepresentable 'init' cannot be synthesized because raw type 'FloatLiteralConvertibleOnly' is not Equatable}} case Everett // expected-error {{enum cases require explicit raw values when the raw type is not integer or string literal convertible}} case Flanders } enum RawTypeWithIntValues : Int { case Glisan = 17, Hoyt = 219, Irving, Johnson = 97209 } enum RawTypeWithNegativeValues : Int { case Glisan = -17, Hoyt = -219, Irving, Johnson = -97209 case AutoIncAcrossZero = -1, Zero, One } enum RawTypeWithUnicodeScalarValues : UnicodeScalar { case Kearney = "K" case Lovejoy // expected-error {{enum cases require explicit raw values when the raw type is not integer or string literal convertible}} case Marshall = "M" } enum RawTypeWithCharacterValues : Character { case First = "い" case Second // expected-error {{enum cases require explicit raw values when the raw type is not integer or string literal convertible}} case Third = "は" } enum RawTypeWithCharacterValues_Error1 : Character { case First = "abc" // expected-error {{cannot convert value of type 'String' to raw type 'Character'}} } enum RawTypeWithFloatValues : Float { case Northrup = 1.5 case Overton // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} case Pettygrove = 2.25 } enum RawTypeWithStringValues : String { case Primrose // okay case Quimby = "Lucky Lab" case Raleigh // okay case Savier = "McMenamin's", Thurman = "Kenny and Zuke's" } enum RawValuesWithoutRawType { case Upshur = 22 // expected-error {{enum case cannot have a raw value if the enum does not have a raw type}} } enum RawTypeWithRepeatValues : Int { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues2 : Double { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues3 : Double { // 2^63-1 case Vaughn = 9223372036854775807 // expected-note {{raw value previously used here}} case Wilson = 9223372036854775807.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues4 : Double { // 2^64-1 case Vaughn = 18446744073709551615 // expected-note {{raw value previously used here}} case Wilson = 18446744073709551615.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues5 : Double { // FIXME: should reject. // 2^65-1 case Vaughn = 36893488147419103231 case Wilson = 36893488147419103231.0 } enum RawTypeWithRepeatValues6 : Double { // FIXME: should reject. // 2^127-1 case Vaughn = 170141183460469231731687303715884105727 case Wilson = 170141183460469231731687303715884105727.0 } enum RawTypeWithRepeatValues7 : Double { // FIXME: should reject. // 2^128-1 case Vaughn = 340282366920938463463374607431768211455 case Wilson = 340282366920938463463374607431768211455.0 } enum RawTypeWithRepeatValues8 : String { case Vaughn = "XYZ" // expected-note {{raw value previously used here}} case Wilson = "XYZ" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithNonRepeatValues : Double { case SantaClara = 3.7 case SanFernando = 7.4 case SanAntonio = -3.7 case SanCarlos = -7.4 } enum RawTypeWithRepeatValuesAutoInc : Double { case Vaughn = 22 // expected-note {{raw value auto-incremented from here}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 23 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc2 : Double { case Vaughn = 23 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-note {{raw value auto-incremented from here}} case Yeon // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc3 : Double { case Vaughn // expected-note {{raw value implicitly auto-incremented from zero}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 1 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc4 : String { case A = "B" // expected-note {{raw value previously used here}} case B // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc5 : String { case A // expected-note {{raw value previously used here}} case B = "A" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc6 : String { case A case B // expected-note {{raw value previously used here}} case C = "B" // expected-error {{raw value for enum case is not unique}} } enum NonliteralRawValue : Int { case Yeon = 100 + 20 + 3 // expected-error {{raw value for enum case must be a literal}} } enum RawTypeWithPayload : Int { // expected-note {{declared raw type 'Int' here}} expected-note {{declared raw type 'Int' here}} case Powell(Int) // expected-error {{enum with raw type cannot have cases with arguments}} case Terwilliger(Int) = 17 // expected-error {{enum with raw type cannot have cases with arguments}} } enum RawTypeMismatch : Int { case Barbur = "foo" // expected-error {{}} } enum DuplicateMembers1 { case Foo // expected-note {{previous definition of 'Foo' is here}} case Foo // expected-error {{duplicate definition of enum element}} } enum DuplicateMembers2 { case Foo, Bar // expected-note {{previous definition of 'Foo' is here}} expected-note {{previous definition of 'Bar' is here}} case Foo // expected-error {{duplicate definition of enum element}} case Bar // expected-error {{duplicate definition of enum element}} } enum DuplicateMembers3 { case Foo // expected-note {{previous definition of 'Foo' is here}} case Foo(Int) // expected-error {{duplicate definition of enum element}} } enum DuplicateMembers4 : Int { case Foo = 1 // expected-note {{previous definition of 'Foo' is here}} case Foo = 2 // expected-error {{duplicate definition of enum element}} } enum DuplicateMembers5 : Int { case Foo = 1 // expected-note {{previous definition of 'Foo' is here}} case Foo = 1 + 1 // expected-error {{duplicate definition of enum element}} expected-error {{raw value for enum case must be a literal}} } enum DuplicateMembers6 { case Foo // expected-note 2{{previous definition of 'Foo' is here}} case Foo // expected-error {{duplicate definition of enum element}} case Foo // expected-error {{duplicate definition of enum element}} } enum DuplicateMembers7 : String { case Foo // expected-note {{previous definition of 'Foo' is here}} case Foo = "Bar" // expected-error {{duplicate definition of enum element}} } // Refs to duplicated enum cases shouldn't crash the compiler. // rdar://problem/20922401 func check20922401() -> String { let x: DuplicateMembers1 = .Foo switch x { case .Foo: return "Foo" } } enum PlaygroundRepresentation : UInt8 { case Class = 1 case Struct = 2 case Tuple = 3 case Enum = 4 case Aggregate = 5 case Container = 6 case IDERepr = 7 case Gap = 8 case ScopeEntry = 9 case ScopeExit = 10 case Error = 11 case IndexContainer = 12 case KeyContainer = 13 case MembershipContainer = 14 case Unknown = 0xFF static func fromByte(byte : UInt8) -> PlaygroundRepresentation { let repr = PlaygroundRepresentation(rawValue: byte) if repr == .none { return .Unknown } else { return repr! } } } struct ManyLiteralable : IntegerLiteralConvertible, StringLiteralConvertible, Equatable { init(stringLiteral: String) {} init(integerLiteral: Int) {} init(unicodeScalarLiteral: String) {} init(extendedGraphemeClusterLiteral: String) {} } func ==(lhs: ManyLiteralable, rhs: ManyLiteralable) -> Bool { return true } enum ManyLiteralA : ManyLiteralable { case A // expected-note {{raw value previously used here}} expected-note {{raw value implicitly auto-incremented from zero}} case B = 0 // expected-error {{raw value for enum case is not unique}} } enum ManyLiteralB : ManyLiteralable { case A = "abc" case B // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} } enum ManyLiteralC : ManyLiteralable { case A case B = "0" } // rdar://problem/22476643 public protocol RawValueA: RawRepresentable { var rawValue: Double { get } } enum RawValueATest: Double, RawValueA { case A, B } public protocol RawValueB { var rawValue: Double { get } } enum RawValueBTest: Double, RawValueB { case A, B } enum foo : String { case bar = nil // expected-error {{cannot convert nil to raw type 'String'}} }
a6bddc9b977bd5288fb8a6fa08b4c59a
32.055172
235
0.716531
false
false
false
false
elliottminns/blackfire
refs/heads/master
Sources/Blackfire/RequestHandler.swift
apache-2.0
2
// // RequestHandler.swift // Blackfire // // Created by Elliott Minns on 20/01/2017. // // import Foundation struct RequestHandler { let nodes: [Node] init(nodes: [Node]) { self.nodes = nodes } func handle(request: HTTPRequest, response: HTTPResponse) { let handlers = nodes.last?.handlers[request.method] ?? [] guard handlers.count > 0 else { response.send(status: 404) return } /* let comps = request.path.components(separatedBy: "/") let params = self.nodes.reduce((0, [:])) { (result, node) -> (Int, [String: String]) in if !node.path.isEmpty && node.path[node.path.startIndex] == ":" { let key = node.path.substring(from: node.path.index(after: node.path.startIndex)) let value = comps[result.0] return (result.0 + 1, [key: value]) } else { return (result.0 + 1, result.1) } }.1 */ let params: [String: String] = [:] let request = Request(params: params, raw: request) handlers.forEach { handler in handler(request, response) } } }
859bf2bafff6aa152bb891d2106c872b
24.116279
91
0.597222
false
false
false
false
uvitar/EMSProject
refs/heads/master
OpenEmsConnectorTests/OpenEmsConnectorTests.swift
gpl-3.0
2
// // OpenEmsConnectorTests.swift // OpenEmsConnectorTests // // Created by steff3 on 02/09/16. // Copyright © 2016 touchLOGIE. All rights reserved. // import XCTest @testable import OpenEmsConnector class OpenEmsConnectorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } func testMessage() { let mess1 = OpenEmsHelper.constructMessage(channel: 0, intensity: 85, onTime: 100) let mess2 = OpenEmsHelper.constructMessage(channel: 1, intensity: 50, onTime: 100) let mess3 = OpenEmsHelper.constructMessage(channel: 4, intensity: 150, onTime: 10000) XCTAssertTrue(mess1.payload == "C0I85T100G") XCTAssertTrue(mess2.payload == "C1I50T100G") XCTAssertTrue(mess3.payload == "C1I100T1000G") } func testDescriptorCheckPasses() { XCTAssertTrue(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5365-7276-6963652D424C4531", descriptor: OpenEmsConstants.serviceDescriptor)) XCTAssertTrue(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5374-6575-6572756E672D4348", descriptor: OpenEmsConstants.characteristicDescriptor)) } func testDescriptorCheckFails() { XCTAssertFalse(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5365-7276-6963652D424C4531", descriptor: OpenEmsConstants.characteristicDescriptor)) XCTAssertFalse(OpenEmsHelper.checkUUIDString(uuid: "454D532D-5374-6575-6572756E672D4348", descriptor: OpenEmsConstants.serviceDescriptor)) } }
82420f502f25e790bcdefaf3ad46b47f
37.301587
111
0.628678
false
true
false
false
spire-inc/JustLog
refs/heads/master
JustLog/Extensions/Dictionary+Flattening.swift
apache-2.0
1
// // Dictionary+Flattening.swift // JustLog // // Created by Alberto De Bortoli on 15/12/2016. // Copyright © 2017 Just Eat. All rights reserved. // import Foundation extension Dictionary { mutating func merge(with dictionary: Dictionary) { dictionary.forEach { _ = updateValue($1, forKey: $0) } } func merged(with dictionary: Dictionary) -> Dictionary { var dict = self dict.merge(with: dictionary) return dict } func flattened() -> [String : Any] { var retVal = [String : Any]() for (k, v) in self { switch v { case is String: retVal.updateValue(v, forKey: k as! String) case is Int: retVal.updateValue(v, forKey: k as! String) case is Double: retVal.updateValue(v, forKey: k as! String) case is Bool: retVal.updateValue(v, forKey: k as! String) case is Dictionary: let inner = (v as! [String : Any]).flattened() retVal = retVal.merged(with: inner) case is Array<Any>: retVal.updateValue(String(describing: v), forKey: k as! String) case is NSError: let inner = (v as! NSError) retVal = retVal.merged(with: inner.userInfo.flattened()) default: continue } } return retVal } }
c37c63a9bde1184c644cd379517f91f1
27.132075
79
0.519115
false
false
false
false
bestwpw/APNGKit
refs/heads/master
APNGKit/Disassembler.swift
mit
7
// // Disassembler.swift // APNGKit // // Created by Wei Wang on 15/8/27. // // Copyright (c) 2015 Wei Wang <[email protected]> // // 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 let signatureOfPNGLength = 8 let kMaxPNGSize: UInt32 = 1000000; // Reading callback for libpng func readData(pngPointer: png_structp, outBytes: png_bytep, byteCountToRead: png_size_t) { let ioPointer = png_get_io_ptr(pngPointer) var reader = UnsafePointer<Reader>(ioPointer).memory reader.read(outBytes, bytesCount: byteCountToRead) } /** Disassembler Errors. An error will be thrown if the disassembler encounters unexpected error. - InvalidFormat: The file is not a PNG format. - PNGStructureFailure: Fail on creating a PNG structure. It might due to out of memory. - PNGInternalError: Internal error when decoding a PNG image. - FileSizeExceeded: The file is too large. There is a limitation of APNGKit that the max width and height is 1M pixel. */ public enum DisassemblerError: ErrorType { case InvalidFormat case PNGStructureFailure case PNGInternalError case FileSizeExceeded } /** * Disassemble APNG data. * See APNG Specification: https://wiki.mozilla.org/APNG_Specification for defination of APNG. * This Disassembler is using a patched libpng with supporting of apng to read APNG data. * See https://github.com/onevcat/libpng for more. */ public struct Disassembler { private(set) var reader: Reader let originalData: NSData /** Init a disassembler with APNG data. - parameter data: Data object of an APNG file. - returns: The disassembler ready to use. */ public init(data: NSData) { reader = Reader(data: data) originalData = data } /** Decode the data to a high level `APNGImage` object. - parameter scale: The screen scale should be used when decoding. You should pass 1 if you want to use the dosassembler separately. If you need to display the image on the screen later, use `UIScreen.mainScreen().scale`. Default is 1.0. - throws: A `DisassemblerError` when error happens. - returns: A decoded `APNGImage` object at given scale. */ public mutating func decode(scale: CGFloat = 1) throws -> APNGImage { let (frames, size, repeatCount, bitDepth, firstFrameHidden) = try decodeToElements(scale) // Setup apng properties let apng = APNGImage(frames: frames, size: size, scale: scale, bitDepth: bitDepth, repeatCount: repeatCount, firstFrameHidden: firstFrameHidden) return apng } mutating func decodeToElements(scale: CGFloat = 1) throws -> (frames: [Frame], size: CGSize, repeatCount: Int, bitDepth: Int, firstFrameHidden: Bool) { reader.beginReading() defer { reader.endReading() } try checkFormat() var pngPointer = png_create_read_struct(PNG_LIBPNG_VER_STRING, nil, nil, nil) if pngPointer == nil { throw DisassemblerError.PNGStructureFailure } var infoPointer = png_create_info_struct(pngPointer) defer { png_destroy_read_struct(&pngPointer, &infoPointer, nil) } if infoPointer == nil { throw DisassemblerError.PNGStructureFailure } if setjmp(png_jmpbuf(pngPointer)) != 0 { throw DisassemblerError.PNGInternalError } png_set_read_fn(pngPointer, &reader, readData) png_read_info(pngPointer, infoPointer) var width: UInt32 = 0, height: UInt32 = 0, bitDepth: Int32 = 0, colorType: Int32 = 0 // Decode IHDR png_get_IHDR(pngPointer, infoPointer, &width, &height, &bitDepth, &colorType, nil, nil, nil) if width > kMaxPNGSize || height > kMaxPNGSize { throw DisassemblerError.FileSizeExceeded } // Transforms. We only handle 8-bit RGBA images. png_set_expand(pngPointer) if bitDepth == 16 { png_set_strip_16(pngPointer) } if colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA { png_set_gray_to_rgb(pngPointer); } if colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_PALETTE || colorType == PNG_COLOR_TYPE_GRAY { png_set_add_alpha(pngPointer, 0xff, PNG_FILLER_AFTER); } png_set_interlace_handling(pngPointer); png_read_update_info(pngPointer, infoPointer); // Update information from updated info pointer width = png_get_image_width(pngPointer, infoPointer) height = png_get_image_height(pngPointer, infoPointer) let rowBytes = UInt32(png_get_rowbytes(pngPointer, infoPointer)) let length = height * rowBytes // Decode acTL var frameCount: UInt32 = 0, playCount: UInt32 = 0 png_get_acTL(pngPointer, infoPointer, &frameCount, &playCount) if frameCount == 0 { // Fallback to regular PNG var currentFrame = Frame(length: length, bytesInRow: rowBytes) currentFrame.duration = Double.infinity png_read_image(pngPointer, &currentFrame.byteRows) currentFrame.updateCGImageRef(Int(width), height: Int(height), bits: Int(bitDepth), scale: scale) png_read_end(pngPointer, infoPointer) return ([currentFrame], CGSize(width: CGFloat(width), height: CGFloat(height)), Int(playCount) - 1, Int(bitDepth), false) } var bufferFrame = Frame(length: length, bytesInRow: rowBytes) var currentFrame = Frame(length: length, bytesInRow: rowBytes) var nextFrame: Frame! // Setup values for reading frames var frameWidth: UInt32 = 0, frameHeight: UInt32 = 0, offsetX: UInt32 = 0, offsetY: UInt32 = 0, delayNum: UInt16 = 0, delayDen: UInt16 = 0, disposeOP: UInt8 = 0, blendOP: UInt8 = 0 let firstImageIndex: Int let firstFrameHidden = png_get_first_frame_is_hidden(pngPointer, infoPointer) != 0 firstImageIndex = firstFrameHidden ? 1 : 0 var frames = [Frame]() // Decode frames for i in 0 ..< frameCount { let currentIndex = Int(i) // Read header png_read_frame_head(pngPointer, infoPointer) // Decode fcTL png_get_next_frame_fcTL(pngPointer, infoPointer, &frameWidth, &frameHeight, &offsetX, &offsetY, &delayNum, &delayDen, &disposeOP, &blendOP) // Update disposeOP for first visable frame if currentIndex == firstImageIndex { blendOP = UInt8(PNG_BLEND_OP_SOURCE) if disposeOP == UInt8(PNG_DISPOSE_OP_PREVIOUS) { disposeOP = UInt8(PNG_DISPOSE_OP_BACKGROUND) } } nextFrame = Frame(length: length, bytesInRow: rowBytes) if (disposeOP == UInt8(PNG_DISPOSE_OP_PREVIOUS)) { // For the first frame, currentFrame is not inited yet. // But we can ensure the disposeOP is not PNG_DISPOSE_OP_PREVIOUS for the 1st frame memcpy(nextFrame.bytes, currentFrame.bytes, Int(length)); } // Decode fdATs png_read_image(pngPointer, &bufferFrame.byteRows) blendFrameDstBytes(currentFrame.byteRows, srcBytes: bufferFrame.byteRows, blendOP: blendOP, offsetX: offsetX, offsetY: offsetY, width: frameWidth, height: frameHeight) // Calculating delay (duration) if delayDen == 0 { delayDen = 100 } let duration = Double(delayNum) / Double(delayDen) currentFrame.duration = duration currentFrame.updateCGImageRef(Int(width), height: Int(height), bits: Int(bitDepth), scale: scale) frames.append(currentFrame) if disposeOP != UInt8(PNG_DISPOSE_OP_PREVIOUS) { memcpy(nextFrame.bytes, currentFrame.bytes, Int(length)) if disposeOP == UInt8(PNG_DISPOSE_OP_BACKGROUND) { for j in 0 ..< frameHeight { let tarPointer = nextFrame.byteRows[Int(offsetY + j)].advancedBy(Int(offsetX) * 4) memset(tarPointer, 0, Int(frameWidth) * 4) } } } currentFrame.bytes = nextFrame.bytes currentFrame.byteRows = nextFrame.byteRows } // End png_read_end(pngPointer, infoPointer) bufferFrame.clean() currentFrame.clean() return (frames, CGSize(width: CGFloat(width), height: CGFloat(height)), Int(playCount) - 1, Int(bitDepth), firstFrameHidden) } func blendFrameDstBytes(dstBytes: Array<UnsafeMutablePointer<UInt8>>, srcBytes: Array<UnsafeMutablePointer<UInt8>>, blendOP: UInt8, offsetX: UInt32, offsetY: UInt32, width: UInt32, height: UInt32) { var u: Int = 0, v: Int = 0, al: Int = 0 for j in 0 ..< Int(height) { var sp = srcBytes[j] var dp = (dstBytes[j + Int(offsetY)]).advancedBy(Int(offsetX) * 4) //We will always handle 4 channels and 8-bits if blendOP == UInt8(PNG_BLEND_OP_SOURCE) { memcpy(dp, sp, Int(width) * 4) } else { // APNG_BLEND_OP_OVER for var i = 0; i < Int(width); i++, sp = sp.advancedBy(4), dp = dp.advancedBy(4) { let srcAlpha = Int(sp.advancedBy(3).memory) // Blend alpha to dst if srcAlpha == 0xff { memcpy(dp, sp, 4) } else if srcAlpha != 0 { let dstAlpha = Int(dp.advancedBy(3).memory) if dstAlpha != 0 { u = srcAlpha * 255 v = (255 - srcAlpha) * dstAlpha al = u + v for bit in 0 ..< 3 { dp.advancedBy(bit).memory = UInt8( (Int(sp.advancedBy(bit).memory) * u + Int(dp.advancedBy(bit).memory) * v) / al ) } dp.advancedBy(4).memory = UInt8(al / 255) } else { memcpy(dp, sp, 4) } } } } } } func checkFormat() throws { guard originalData.length > 8 else { throw DisassemblerError.InvalidFormat } var sig = [UInt8](count: signatureOfPNGLength, repeatedValue: 0) originalData.getBytes(&sig, length: signatureOfPNGLength) guard png_sig_cmp(&sig, 0, signatureOfPNGLength) == 0 else { throw DisassemblerError.InvalidFormat } } }
2b5ae0144883f5874a390c2e47a92ba5
38.003077
133
0.572308
false
false
false
false
wangyaqing/LeetCode-swift
refs/heads/master
Solutions/12. Integer to Roman.playground/Contents.swift
mit
1
import UIKit class Solution { func intToRoman(_ num: Int) -> String { if num >= 1000 { return "M"+intToRoman(num-1000) } else if num >= 900 { return "CM"+intToRoman(num-900) } else if num >= 500 { return "D"+intToRoman(num-500) } else if num >= 400 { return "CD"+intToRoman(num-400) } else if num >= 100 { return "C"+intToRoman(num-100) } else if num >= 90 { return "XC"+intToRoman(num-90) } else if num >= 50 { return "L"+intToRoman(num-50) } else if num >= 40 { return "XL"+intToRoman(num-40) } else if num >= 10 { return "X"+intToRoman(num-10) } else if num >= 9 { return "IX"+intToRoman(num-9) } else if num >= 5 { return "V"+intToRoman(num-5) } else if num >= 4 { return "IV"+intToRoman(num-4) } else if num >= 1 { return "I"+intToRoman(num-1) } return "" } } Solution().intToRoman(200)
7d20c593642481949f016b3cc3e91133
28.944444
43
0.474954
false
false
false
false
MarkQSchultz/NilLiterally
refs/heads/master
LiterallyNil.playground/Pages/Optional.xcplaygroundpage/Contents.swift
mit
1
//: [Next](@next) //: ### Optionals //: #### `.None` /*: public enum Optional<Wrapped> { case None case Some(Wrapped) } */ let a: Int? = nil let aIsNil = a == nil let aIsNone = a == .None //: `Int? == Optional<Int>` //: [Previous](@previous)
e5b8f3c6e08886532fabe9a26b96da44
6
35
0.465986
false
false
false
false
klone1127/yuan
refs/heads/master
yuan/UIView+Common.swift
mit
1
// // UIView+Common.swift // yuan // // Created by CF on 2017/6/10. // Copyright © 2017年 klone. All rights reserved. // import Foundation import UIKit private let colorValue: CGFloat = 1.0 extension UIView { /// add line open func addLine() { self.addLineToTop() self.addLineToBottom() } /// 底部添加 Line open func addLineToBottom() { let line = UIView() line.backgroundColor = UIColor.init(red: colorValue, green: colorValue, blue: colorValue, alpha: 1.0) self.addSubview(line) line.snp.makeConstraints { (make) in make.left.right.bottom.equalTo(self) make.height.equalTo(1.0) } } /// 顶部添加 Line open func addLineToTop() { let line = UIView() line.backgroundColor = UIColor.init(red: colorValue, green: colorValue, blue: colorValue, alpha: 1.0) self.addSubview(line) line.snp.makeConstraints { (make) in make.left.right.top.equalTo(self) make.height.equalTo(1.0) } } /// 拖拽卡片 /// /// - Parameters: /// - translation: point /// - Returns: open func panTransform(for translation: CGPoint) -> CGAffineTransform { let moveBy = CGAffineTransform(translationX: translation.x, y: translation.y) let rotation = -sin(translation.x / (self.frame.width * 4.0)) return moveBy.rotated(by: rotation) } /// 抖动 open func shakeAnimation() { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 1.0, options: [], animations: { self.transform = .identity }, completion: nil) } }
d02b0faa408c6fddec7c3f5acd6ae3c1
24.581081
109
0.538299
false
false
false
false
darkzero/SimplePlayer
refs/heads/master
SimplePlayer/UI/Library/PlaylistViewController.swift
mit
1
// // PlaylistViewController.swift // SimplePlayer // // Created by darkzero on 14-6-11. // Copyright (c) 2014 darkzero. All rights reserved. // import UIKit import MediaPlayer class PlaylistViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var songsTable : UITableView!; var playlistList:NSMutableArray; override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.playlistList = MusicLibrary.defaultPlayer().getiPodPlaylists(); super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } required init(coder aDecoder: NSCoder) { self.playlistList = MusicLibrary.defaultPlayer().getiPodPlaylists(); super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated); //self.songsTable.reloadData(); } /* // #pragma 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. } */ // #pragma mark - Navigation func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.playlistList.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier = "SongCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell; if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier); } cell!.textLabel!.text = (self.playlistList[indexPath.row] as MPMediaPlaylist).name; //NSLog("%@", self.playlistList[indexPath.row]); return cell!; } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //var mediaItem:MPMediaItem = self.playlistList[indexPath.row] as MPMediaItem; var songsVC:SongsViewController = SongsViewController(nibName: "SongsViewController", bundle: nil); var mCollection:MPMediaItemCollection = self.playlistList[indexPath.row] as MPMediaItemCollection; songsVC.itemCollection = mCollection; self.navigationController?.pushViewController(songsVC, animated: true); // var player = MusicPlayer.defaultPlayer(); // player.player.setQueueWithItemCollection(MPMediaItemCollection(items:self.getiPodPlaylists)); // player.player.nowPlayingItem = mediaItem; // player.player.play(); //self.dismissModalViewControllerAnimated(true); } }
648d4e0fc67b662c8bf5d3d79119fcdc
34.467391
109
0.682807
false
false
false
false
LamGiauKhongKhoTeam/LGKK
refs/heads/master
DemoVideoByGPU/DemoVideoByGPU/ModelController.swift
mit
1
// // ModelController.swift // DemoVideoByGPU // // Created by Nguyen Minh on 5/2/17. // Copyright © 2017 AHDEnglish. All rights reserved. // import UIKit /* A controller object that manages a simple model -- a collection of month names. The controller serves as the data source for the page view controller; it therefore implements pageViewController:viewControllerBeforeViewController: and pageViewController:viewControllerAfterViewController:. It also implements a custom method, viewControllerAtIndex: which is useful in the implementation of the data source methods, and in the initial configuration of the application. There is no need to actually create view controllers for each page in advance -- indeed doing so incurs unnecessary overhead. Given the data model, these methods create, configure, and return a new view controller on demand. */ class ModelController: NSObject, UIPageViewControllerDataSource { var pageData: [String] = [] override init() { super.init() // Create the data model. let dateFormatter = DateFormatter() pageData = dateFormatter.monthSymbols } func viewControllerAtIndex(_ index: Int, storyboard: UIStoryboard) -> DataViewController? { // Return the data view controller for the given index. if (self.pageData.count == 0) || (index >= self.pageData.count) { return nil } // Create a new view controller and pass suitable data. let dataViewController = storyboard.instantiateViewController(withIdentifier: "DataViewController") as! DataViewController dataViewController.dataObject = self.pageData[index] return dataViewController } func indexOfViewController(_ viewController: DataViewController) -> Int { // Return the index of the given data view controller. // For simplicity, this implementation uses a static array of model objects and the view controller stores the model object; you can therefore use the model object to identify the index. return pageData.index(of: viewController.dataObject) ?? NSNotFound } // MARK: - Page View Controller Data Source func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if (index == 0) || (index == NSNotFound) { return nil } index -= 1 return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index = self.indexOfViewController(viewController as! DataViewController) if index == NSNotFound { return nil } index += 1 if index == self.pageData.count { return nil } return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!) } }
d77ed7a30c0446603756cea2dc341c81
39.571429
225
0.709987
false
false
false
false
ddaguro/clintonconcord
refs/heads/master
OIMApp/Requests.swift
mit
1
// // Requests.swift // OIMApp // // Created by Linh NGUYEN on 5/26/15. // Copyright (c) 2015 Persistent Systems. All rights reserved. // import Foundation public class Requests { var reqId : String! var reqStatus : String! var reqCreatedOn : String! var reqType : String! var reqJustification : String! var reqTargetEntities : [TargetEntities]! var reqBeneficiaryList : [BeneficiaryList]! init(data : NSDictionary){ self.reqId = Utils.getStringFromJSON(data, key: "reqId") self.reqStatus = Utils.getStringFromJSON(data, key: "reqStatus") self.reqCreatedOn = Utils.getStringFromJSON(data, key: "reqCreatedOn") self.reqType = Utils.getStringFromJSON(data, key: "reqType") self.reqJustification = Utils.getStringFromJSON(data, key: "reqJustification") if let results: NSArray = data["reqTargetEntities"] as? NSArray { var ents = [TargetEntities]() for ent in results{ let ent = TargetEntities(data: ent as! NSDictionary) ents.append(ent) } self.reqTargetEntities = ents } if let beneficiaryresults: NSArray = data["reqBeneficiaryList"] as? NSArray { var bens = [BeneficiaryList]() for ben in beneficiaryresults { let ben = BeneficiaryList(data: ben as! NSDictionary) bens.append(ben) } self.reqBeneficiaryList = bens } } } class TargetEntities { var catalogid: String! var entityid: String! var entitytype: String! var entityname: String! init(data : NSDictionary){ self.catalogid = Utils.getStringFromJSON(data, key: "catalogId") self.entityid = Utils.getStringFromJSON(data, key: "entityId") self.entitytype = Utils.getStringFromJSON(data, key: "entityType") self.entityname = Utils.getStringFromJSON(data, key: "entityName") } } class BeneficiaryList { var userlogin: String! var displayname: String! init(data : NSDictionary){ self.userlogin = Utils.getStringFromJSON(data, key: "User Login") self.displayname = Utils.getStringFromJSON(data, key: "Display Name") } } class OperationCounts { var approvals : Int! var certifications : Int! var requests : Int! init(data : NSDictionary){ self.approvals = data["approvals"] as! Int self.certifications = data["certifications"] as! Int self.requests = data["requests"] as! Int } }
a7dfd1f7138b6d1d6fff39d37787d27d
28.153846
86
0.611006
false
false
false
false
ioscreator/ioscreator
refs/heads/master
IOSSpriteKitParallaxScrollingTutorial/IOSSpriteKitParallaxScrollingTutorial/GameScene.swift
mit
1
// // GameScene.swift // IOSSpriteKitParallaxScrollingTutorial // // Created by Arthur Knopper on 19/01/2020. // Copyright © 2020 Arthur Knopper. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { override func didMove(to view: SKView) { createBackground() } override func update(_ currentTime: TimeInterval) { scrollBackground() } func createBackground() { for i in 0...2 { let sky = SKSpriteNode(imageNamed: "clouds") sky.name = "clouds" sky.size = CGSize(width: (self.scene?.size.width)!, height: (self.scene?.size.height)!) sky.position = CGPoint(x: CGFloat(i) * sky.size.width , y: (self.frame.size.height / 2)) self.addChild(sky) } } func scrollBackground(){ self.enumerateChildNodes(withName: "clouds", using: ({ (node, error) in node.position.x -= 4 print("node position x = \(node.position.x)") if node.position.x < -(self.scene?.size.width)! { node.position.x += (self.scene?.size.width)! * 3 } })) } }
c2cddc676bbb38ed4161b539f5b6196d
26.355556
100
0.549959
false
false
false
false
modesty/wearableD
refs/heads/master
WearableD/HomeViewController.swift
apache-2.0
2
// // ViewController.swift // WearableD // // Created by Zhang, Modesty on 1/9/15. // Copyright (c) 2015 Intuit. All rights reserved. // import UIKit class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleWatchKitNotification:", name: "WearableDWKMsg", object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { // self.navigationController?.setNavigationBarHidden(true, animated: animated) self.title = "Wearable Transcript" super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { // self.navigationController?.setNavigationBarHidden(false, animated: animated) self.title = "Home" super.viewWillDisappear(animated) } func handleWatchKitNotification(notification: NSNotification) { println("Got notification: \(notification.object)") if let userInfo = notification.object as? [String:String] { if let viewNameStr = userInfo["viewName"] { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let topVC = self.navigationController?.topViewController var bleVC: UIViewController? = nil if viewNameStr == "requestDoc" { if (topVC is CentralViewController) == false { self.returnToRoot() bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("CentralViewController") as! CentralViewController } } else if viewNameStr == "shareDoc" { if (topVC is PeripheralViewController) == false { self.returnToRoot() bleVC = mainStoryboard.instantiateViewControllerWithIdentifier("PeripheralViewController") as! PeripheralViewController } } if bleVC != nil { self.navigationController?.pushViewController(bleVC!, animated: true) } } } } func returnToRoot() { self.dismissViewControllerAnimated(true, completion: nil) self.navigationController?.popToRootViewControllerAnimated(true) } }
5fed0124e12d87d740c359e5ce755c80
35.184211
143
0.610182
false
false
false
false
hooman/swift
refs/heads/main
test/SILOptimizer/closure_lifetime_fixup.swift
apache-2.0
3
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %S/../Inputs/resilient_struct.swift -enable-library-evolution -emit-module -emit-module-path %t/resilient_struct.swiftmodule // RUN: %target-swift-frontend %S/../Inputs/resilient_enum.swift -I %t -enable-library-evolution -emit-module -emit-module-path %t/resilient_enum.swiftmodule // RUN: %target-swift-frontend %s -sil-verify-all -emit-sil -disable-copy-propagation -I %t -o - | %FileCheck %s // Using -disable-copy-propagation to pattern match against older SIL // output. At least until -enable-copy-propagation has been around // long enough in the same form to be worth rewriting CHECK lines. import resilient_struct import resilient_enum func use_closure(_ c : () -> () ) { c() } func use_closureGeneric<T>(_ c : () -> T ) { _ = c() } public class C { func doIt() {} func returnInt() -> Int { return 0 } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup10testSimple1cyAA1CC_tF : $@convention(thin) (@guaranteed C) -> () { // CHECK: bb0([[ARG:%.*]] : $C): // CHECK: [[F:%.*]] = function_ref @$s22closure_lifetime_fixup10testSimple1cyAA1CC_tFyyXEfU_ // CHECK-NEXT: strong_retain [[ARG]] : $C // CHECK-NEXT: [[PA:%.*]] = partial_apply [callee_guaranteed] [on_stack] [[F]]([[ARG]]) : $@convention(thin) (@guaranteed C) -> () // CHECK-NEXT: [[CL:%.*]] = mark_dependence [[PA]] : $@noescape @callee_guaranteed () -> () on [[ARG]] : $C // CHECK-NEXT: // function_ref use_closure(_:) // CHECK-NEXT: [[F2:%.*]] = function_ref @$s22closure_lifetime_fixup04use_A0yyyyXEF : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK-NEXT: apply [[F2]]([[CL]]) : $@convention(thin) (@noescape @callee_guaranteed () -> ()) -> () // CHECK-NEXT: dealloc_stack [[PA]] : $@noescape @callee_guaranteed () -> () // CHECK-NEXT: strong_release [[ARG]] : $C // CHECK-NEXT: tuple () // CHECK-NEXT: return {{.*}} : $() public func testSimple(c: C) { use_closure { c.doIt() } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup11testGeneric1cyAA1CC_tF : $@convention(thin) (@guaranteed C) -> () { // CHECK:bb0([[ARG:%.*]] : $C): // CHECK: [[F:%.*]] = function_ref @$s22closure_lifetime_fixup11testGeneric1cyAA1CC_tFSiyXEfU_ : $@convention(thin) (@guaranteed C) -> Int // CHECK-NEXT: strong_retain [[ARG]] : $C // CHECK-NEXT: [[PA:%.*]] = partial_apply [callee_guaranteed] [on_stack] [[F]]([[ARG]]) : // CHECK-NEXT: [[MD:%.*]] = mark_dependence [[PA]] : $@noescape @callee_guaranteed () -> Int on [[ARG]] : $C // CHECK-NEXT: // function_ref thunk for @callee_guaranteed () -> (@unowned Int) // CHECK-NEXT: [[F:%.*]] = function_ref @$sSiIgd_SiIegr_TR : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> @out Int // CHECK-NEXT: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] [[F]]([[MD]]) : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> @out Int // CHECK-NEXT: [[CF2:%.*]] = convert_function [[PA2]] // CHECK-NEXT: // function_ref use_closureGeneric<A>(_:) // CHECK-NEXT: [[F2:%.*]] = function_ref @$s22closure_lifetime_fixup04use_A7GenericyyxyXElF : // CHECK-NEXT: apply [[F2]]<Int>([[CF2]]) : // CHECK-NEXT: dealloc_stack [[PA2]] // CHECK-NEXT: dealloc_stack [[PA]] // CHECK-NEXT: strong_release [[ARG]] // CHECK-NEXT: tuple () // CHECK-NEXT: return {{.*}} : $() public func testGeneric(c: C) { use_closureGeneric { return c.returnInt() } } public protocol P { associatedtype Element subscript<U>(a: (Element) -> U, b: (U) -> Element) -> U { get set } } // Make sure we keep the closure alive up until after the write back. // CHECK-LABEL: sil @$s22closure_lifetime_fixup10testModify1pyxz_tAA1PRzSS7ElementRtzlF : $@convention(thin) <T where T : P, T.Element == String> (@inout T) -> () { // CHECK: bb0 // CHECK: [[PA1:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CF1:%.*]] = convert_function [[PA1]] // CHECK: [[CVT1:%.*]] = convert_escape_to_noescape [[CF1]] // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] // CHECK: [[CF2:%.*]] = convert_function [[PA2]] // CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[CF2]] // CHECK: [[W:%.*]] = witness_method $T, #P.subscript!modify // CHECK: ([[BUFFER:%.*]], [[TOKEN:%.*]]) = begin_apply [[W]]<T, Int>([[CVT1]], [[CVT2]], {{.*}}) // CHECK: end_apply [[TOKEN]] // CHECK: strong_release [[CF1]] // CHECK: strong_release [[CF2]] public func testModify<T : P>(p: inout T) where T.Element == String { p[{Int($0)!}, {String($0)}] += 1 } public func dontCrash<In, Out>(test: Bool, body: @escaping ((In) -> Out, In) -> Out ) -> (In) -> Out { var result: ((In) -> Out)! result = { (x: In) in if test { return body(result, x) } let r = body(result, x) return r } return result } // CHECK-LABEL: sil @$s22closure_lifetime_fixup28to_stack_of_convert_function1pySvSg_tF // CHECK: [[FN:%.*]] = function_ref @$s22closure_lifetime_fixup28to_stack_of_convert_function1pySvSg_tFSSSvcfu_ : $@convention(thin) (UnsafeMutableRawPointer) -> @owned String // CHECK: [[PA:%.*]] = thin_to_thick_function [[FN]] // CHECK: [[CVT:%.*]] = convert_function [[PA]] // CHECK: [[CVT2:%.*]] = convert_escape_to_noescape [[CVT]] // CHECK: [[REABSTRACT:%.*]] = function_ref @$sSvSSs5Error_pIgyozo_SvSSsAA_pIegnrzo_TR // CHECK: [[PA2:%.*]] = partial_apply [callee_guaranteed] [on_stack] [[REABSTRACT]]([[CVT2]]) // CHECK: [[CF2:%.*]] = convert_function [[PA2]] // CHECK: [[MAP:%.*]] = function_ref @$sSq3mapyqd__Sgqd__xKXEKlF // CHECK: try_apply [[MAP]]<UnsafeMutableRawPointer, String>({{.*}}, [[CF2]], {{.*}}) public func to_stack_of_convert_function(p: UnsafeMutableRawPointer?) { _ = p.map(String.init(describing:)) } public func no_dealloc_stack_before_unreachable(_ message: String, fileName: StaticString = #file, lineNumber: Int = #line) -> Never { Swift.fatalError(message, file: fileName, line: UInt(lineNumber)) } // Make sure closures are allocated on the stack. func useClosure(_ c: () -> ()) { } func useClosureThrowing(_ c: () throws -> ()) throws { } func useGenericClosure<T, V>(_ c : (T) -> V) { } func useGenericClosureThrowing<T, V>(_ c: (T) throws -> V) throws { } // CHECK-LABEL: sil @$s22closure_lifetime_fixup12captureClass1c1dyAA1CC_AFtKF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup10useClosureyyyyXEF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup18useClosureThrowingyyyyKXEKF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$sIg_ytytIegnr_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup17useGenericClosureyyq_xXEr0_lF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$ss5Error_pIgzo_ytytsAA_pIegnrzo_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup25useGenericClosureThrowingyyq_xKXEKr0_l public func captureClass(c: C, d: C) throws { useClosure { c.doIt() d.doIt() } try useClosureThrowing { c.doIt() d.doIt() } useGenericClosure { c.doIt() d.doIt() } try useGenericClosureThrowing { c.doIt() d.doIt() } } public protocol DoIt { func doIt() } // CHECK-LABEL: sil @$s22closure_lifetime_fixup14captureGeneric1c1dyx_q_tKAA4DoItRzAaER_r0_lF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup10useClosureyyyyXEF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup18useClosureThrowingyyyyKXEKF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$sIg_ytytIegnr_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup17useGenericClosureyyq_xXEr0_lF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$ss5Error_pIgzo_ytytsAA_pIegnrzo_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup25useGenericClosureThrowingyyq_xKXEKr0_lF public func captureGeneric<C :DoIt,D: DoIt>(c: C, d: D) throws { useClosure { c.doIt() d.doIt() } try useClosureThrowing { c.doIt() d.doIt() } useGenericClosure { c.doIt() d.doIt() } try useGenericClosureThrowing { c.doIt() d.doIt() } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup14captureClosure1c1d1tyq_xXE_q_xXExtKr0_lF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup10useClosureyyyyXEF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup18useClosureThrowingyyyyKXEKF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$sIg_ytytIegnr_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup17useGenericClosureyyq_xXEr0_lF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$ss5Error_pIgzo_ytytsAA_pIegnrzo_TR // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: function_ref @$s22closure_lifetime_fixup25useGenericClosureThrowingyyq_xKXEKr0_lF public func captureClosure<T, V>(c : (T) ->V, d: (T) -> V, t: T) throws { useClosure { c(t) d(t) } try useClosureThrowing { c(t) d(t) } useGenericClosure { c(t) d(t) } try useGenericClosureThrowing { c(t) d(t) } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup16captureResilient // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func captureResilient(c: Size) throws { useClosure { c.method() } try useClosureThrowing { c.method() } useGenericClosure { c.method() } try useGenericClosureThrowing { c.method() } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup10capturePOD1cy16resilient_struct5PointV_tKF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func capturePOD(c: Point) throws { useClosure { c.method() } try useClosureThrowing { c.method() } useGenericClosure { c.method() } try useGenericClosureThrowing { c.method() } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup11captureEnum // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func captureEnum(c: FullyFixedLayout, d: CustomColor) throws { useClosure { _ = c _ = d } try useClosureThrowing { _ = c _ = d } useGenericClosure { _ = c _ = d } try useGenericClosureThrowing { _ = c _ = d } } public protocol EmptyP {} public struct AddressOnlyStruct : EmptyP {} public enum AddressOnlyEnum { case nought case mere(EmptyP) case phantom(AddressOnlyStruct) } // CHECK-LABEL: sil @$s22closure_lifetime_fixup22captureAddressOnlyEnum // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func captureAddressOnlyEnum(c: AddressOnlyEnum, d: AddressOnlyEnum) throws { useClosure { _ = c _ = d } try useClosureThrowing { _ = c _ = d } useGenericClosure { _ = c _ = d } try useGenericClosureThrowing { _ = c _ = d } } // CHECK-LABEL: sil @$s22closure_lifetime_fixup15captureProtocol // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func captureProtocol(c: EmptyP, d: EmptyP) throws { useClosure { _ = c _ = d } try useClosureThrowing { _ = c _ = d } useGenericClosure { () -> Int in _ = c _ = d return 0 } try useGenericClosureThrowing { () -> Int in _ = c _ = d return 0 } } public protocol Q { associatedtype Element func test<U>(_ c: (Element) -> U) throws } // CHECK-LABEL: sil @$s22closure_lifetime_fixup0A18WithAssociatedType1c1eyx_7ElementQztKAA1QRzlF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: try_apply public func closureWithAssociatedType<C : Q> (c: C, e: C.Element) throws { try c.test( { _ in _ = e }) } public class F<T> { func test<V>(_ c: (V) throws -> T) {} let t : T? = nil } // CHECK-LABEL: s22closure_lifetime_fixup22testClosureMethodParam1fyAA1FCyxG_tKlF // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: partial_apply [callee_guaranteed] [on_stack] // CHECK: apply public func testClosureMethodParam<T>(f: F<T>) throws { try f.test { return f.t! } }
34bd14b49ff069f2594939267dada3bc
30.054466
176
0.661007
false
false
false
false
sheepy1/SelectionOfZhihu
refs/heads/master
SelectionOfZhihu/Constant.swift
mit
1
// // Constant.swift // SelectionOfZhihu // // Created by 杨洋 on 15/12/22. // Copyright © 2015年 Sheepy. All rights reserved. // import UIKit let ScreenBounds = UIScreen.mainScreen().bounds let ScreenWidth = ScreenBounds.width let ScreenHeight = ScreenBounds.height let BarHeight = UIApplication.sharedApplication().statusBarFrame.height struct ArticleCagetory { static let categoryDict = [ "archive": "历史精华", "recent": "近日热门", "yesterday": "昨日最新" ] } struct CellReuseIdentifier { static let Home = "HomeCell" static let Answer = "AnswerCell" static let User = "UserCell" static let UserInfo = "UserInfo" static let UserMenu = "UserMenu" static let UserDynamic = "UserDynamic" static let TopAnswer = "TopAnswer" static let SearchedUser = "SearchedUser" } struct SegueId { static let PopoverSortOrderMenu = "PopoverSortOrderMenu" static let SelectedTableItem = "SelectedTableItem" static let UserDetail = "UserDetail" } struct API { static let APIHost = "http://api.kanzhihu.com/" static let ArticleHost = "http://www.zhihu.com" static let ZhuanlanHost = "http://zhuanlan.zhihu.com" static let Home = APIHost + "getposts" static let AnswerList = APIHost + "getpostanswers/" static let Article = ArticleHost + "/question/" static let TopUserAPI = APIHost + "topuser/" static let TopUserOrderByAgreeNum = TopUserAPI + "agree/" static let UserDetail = APIHost + "userdetail2/" static let SearchUser = APIHost + "searchuser/" }
bb4194c3b4da772c396ffb9c8cae08cd
25.032787
71
0.679269
false
false
false
false
AlexanderMazaletskiy/realm-cocoa
refs/heads/master
Carthage/Checkouts/realm-cocoa/examples/ios/swift-1.2/Migration/AppDelegate.swift
apache-2.0
22
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import UIKit import RealmSwift // Old data models /* V0 class Person: Object { dynamic var firstName = "" dynamic var lastName = "" dynamic var age = 0 } */ /* V1 class Person: Object { dynamic var fullName = "" // combine firstName and lastName into single field dynamic var age = 0 } */ /* V2 */ class Pet: Object { dynamic var name = "" dynamic var type = "" } class Person: Object { dynamic var fullName = "" dynamic var age = 0 let pets = List<Pet>() // Add pets field } func bundlePath(path: String) -> String? { return NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent(path) } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = UIViewController() window?.makeKeyAndVisible() // copy over old data files for migration let defaultPath = Realm.Configuration.defaultConfiguration.path! let defaultParentPath = defaultPath.stringByDeletingLastPathComponent if let v0Path = bundlePath("default-v0.realm") { NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil) NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath, error: nil) } // define a migration block // you can define this inline, but we will reuse this to migrate realm files from multiple versions // to the most current version of our data model let migrationBlock: MigrationBlock = { migration, oldSchemaVersion in if oldSchemaVersion < 1 { migration.enumerate(Person.className()) { oldObject, newObject in if oldSchemaVersion < 1 { // combine name fields into a single field let firstName = oldObject!["firstName"] as! String let lastName = oldObject!["lastName"] as! String newObject?["fullName"] = "\(firstName) \(lastName)" } } } if oldSchemaVersion < 2 { migration.enumerate(Person.className()) { oldObject, newObject in // give JP a dog if newObject?["fullName"] as? String == "JP McDonald" { let jpsDog = migration.create(Pet.className(), value: ["Jimbo", "dog"]) let dogs = newObject?["pets"] as? List<MigrationObject> dogs?.append(jpsDog) } } } println("Migration complete.") } Realm.Configuration.defaultConfiguration = Realm.Configuration(schemaVersion: 3, migrationBlock: migrationBlock) // print out all migrated objects in the default realm // migration is performed implicitly on Realm access println("Migrated objects in the default Realm: \(Realm().objects(Person))") // // Migrate a realms at a custom paths // if let v1Path = bundlePath("default-v1.realm"), v2Path = bundlePath("default-v2.realm") { let realmv1Path = defaultParentPath.stringByAppendingPathComponent("default-v1.realm") let realmv2Path = defaultParentPath.stringByAppendingPathComponent("default-v2.realm") let realmv1Configuration = Realm.Configuration(path: realmv1Path, schemaVersion: 3, migrationBlock: migrationBlock) let realmv2Configuration = Realm.Configuration(path: realmv2Path, schemaVersion: 3, migrationBlock: migrationBlock) NSFileManager.defaultManager().removeItemAtPath(realmv1Path, error: nil) NSFileManager.defaultManager().copyItemAtPath(v1Path, toPath: realmv1Path, error: nil) NSFileManager.defaultManager().removeItemAtPath(realmv2Path, error: nil) NSFileManager.defaultManager().copyItemAtPath(v2Path, toPath: realmv2Path, error: nil) // migrate realms at realmv1Path manually, realmv2Path is migrated automatically on access migrateRealm(configuration: realmv1Configuration) // print out all migrated objects in the migrated realms let realmv1 = Realm(configuration: realmv1Configuration)! println("Migrated objects in the Realm migrated from v1: \(realmv1.objects(Person))") let realmv2 = Realm(configuration: realmv2Configuration)! println("Migrated objects in the Realm migrated from v2: \(realmv2.objects(Person))") } return true } }
34da43883c83deb3ad457f02b3adf979
40.571429
128
0.632664
false
true
false
false
quells/SwiftManagedModel
refs/heads/master
Example/Person.swift
mit
1
// // Person.swift // SQLiteDB Example // // Created by Kai Wells on 8/11/14. // Copyright (c) 2014 Kai Wells. All rights reserved. // import UIKit public class Person: Model { override public func className() -> String { return "Person" } public var id: String = NSUUID.UUID().UUIDString public var name: String = "" public var age: Int = 0 public var dateCreated: NSDate = NSDate() public var dateModified: NSDate = NSDate() override init() { super.init() shouldUpdate() } override public func shouldUpdate() -> Bool { dateModified = NSDate() self._properties = [id, name, age, dateCreated, dateModified] return true } override public func shouldInsert() -> Bool { shouldUpdate() return true } override public func shouldDelete() -> Bool { shouldUpdate() return true } override public var description: String { return "<\(self.name) age \(self.age), created \(self.dateCreated)>" } } public class People: Model { override public func className() -> String { return "People" } public var id: Int = 0 public var people: NSArray = NSArray() public var dateModified: NSDate = NSDate() override init() { super.init() shouldUpdate() } override public func shouldUpdate() -> Bool { dateModified = NSDate() self._properties = [id, people, dateModified] return true } public func add(person: Person) { var temp = self.people.mutableCopy() as NSMutableArray temp.insertObject(person.id, atIndex: 0) self.people = temp.copy() as NSArray shouldUpdate() } public func remove(person: Person) { var temp = self.people.mutableCopy() as NSMutableArray temp.removeObject(person.id) self.people = temp.copy() as NSArray shouldUpdate() } }
48152f46ffac57ea96fe23b62c767ae6
22.752941
76
0.587215
false
false
false
false
antonyharfield/grader
refs/heads/master
Sources/App/Web/ViewRenderers/ViewWrapper.swift
mit
1
import Vapor func render(_ viewName: String, _ data: [String: NodeRepresentable] = [:], for request: HTTP.Request, with renderer: ViewRenderer) throws -> View { var wrappedData = wrap(data, request: request) if let user = request.user { wrappedData = wrap(wrappedData, user: user) } return try renderer.make(viewName, wrappedData, for: request) } fileprivate func wrap(_ data: [String: NodeRepresentable], user: User) -> [String: NodeRepresentable] { var result = data result["authenticated"] = true result["authenticatedUser"] = user user.role.permitted.forEach { result["can\($0.rawValue.capitalized)"] = true } return result } fileprivate func wrap(_ data: [String: NodeRepresentable], request: HTTP.Request) -> [String: NodeRepresentable] { var result = data result["path"] = request.uri.path.components(separatedBy: "/").filter { $0 != "" } result["flash"] = try! request.storage["_flash"].makeNode(in: nil) return result }
3e0267095d5c823594083dc6502b7ff9
36
147
0.676677
false
false
false
false
anurse/advent-of-code
refs/heads/main
2021/adventofcode/day02.swift
apache-2.0
1
// // Created by Andrew Stanton-Nurse on 12/3/21. // import Foundation struct Coordinate { var depth = 0 var position = 0 } extension Coordinate { static func +(left: Coordinate, right: Coordinate) -> Coordinate { Coordinate(depth: left.depth + right.depth, position: left.position + right.position) } } class Submarine { var location = Coordinate() var aim = 0 func move(by: Coordinate) { aim += by.depth location = Coordinate( depth: location.depth + (by.position * aim), position: location.position + by.position) } } func parseInstruction(s: Substring) throws -> Coordinate { let splat = s.split(separator: " ") if splat.count != 2 { throw SimpleError.error("Invalid instruction: \(s))") } guard let count = Int(splat[1]) else { throw SimpleError.error("Distance is not an integer: \(splat[1])") } switch splat[0] { case "forward": return Coordinate(depth: 0, position: count) case "down": return Coordinate(depth: count, position: 0) case "up": return Coordinate(depth: -count, position: 0) case let x: throw SimpleError.error("Unknown direction: \(x)") } } func day02(_ args: ArraySlice<String>) throws { guard let input = args.first else { throw SimpleError.error("Usage: adventofcode 2 <input>") } let data = try parseLines(path: input, converter: parseInstruction) let part1 = data.reduce(Coordinate(), +) print("Part 1:") dumpResult(result: part1) let sub = Submarine() for inst in data { sub.move(by: inst) } print("Part 2") dumpResult(result: sub.location) } func dumpResult(result: Coordinate) { print(" Depth: \(result.depth)") print(" Position: \(result.position)") print(" Result: \(result.position * result.depth)") }
5a162acfdad1d49d0034b1cc55e7f5b1
24.890411
93
0.620434
false
false
false
false
xiaoyouPrince/WeiBo
refs/heads/master
WeiBo/WeiBo/Classes/Main/Visitor/VisitorView.swift
mit
1
// // VisitorView.swift // WeiBo // // Created by 渠晓友 on 2017/5/19. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // import UIKit class VisitorView: UIView { // 创建一个对外的公开快速创建的方法 class func visitorView() -> VisitorView { return Bundle.main.loadNibNamed("VisitorView", owner: nil, options: nil)?.first as! VisitorView } // MARK: - 内部属性 @IBOutlet weak var rotationView: UIImageView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var tipsLabel: UILabel! @IBOutlet weak var registerBtn: UIButton! @IBOutlet weak var loginBtn: UIButton! /// 设置内部visitorView的信息 func setupVisitorViewInfo(iconName : String , tips : String) { rotationView.isHidden = true iconView.image = UIImage(named: iconName) tipsLabel.text = tips } /// 设置rotationView旋转起来 func addRotationAnim() { // 创建动画 let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") // 设置动画基本属性 rotationAnim.fromValue = 0 rotationAnim.toValue = Double.pi * 2 rotationAnim.repeatCount = MAXFLOAT rotationAnim.duration = 5 // 设置当完成不消失,退后台和其他页面无影响 rotationAnim.isRemovedOnCompletion = false // 将动画添加到对应的layer层上面 rotationView.layer.add(rotationAnim, forKey: nil) } }
4a4d0c7605d4aa36eb1e928809e215de
22.916667
103
0.612544
false
false
false
false
webim/webim-client-sdk-ios
refs/heads/master
Example/WebimClientLibrary/AppearanceSettings/StringConstants.swift
mit
1
// // StringConstants.swift // WebimClientLibrary_Example // // Created by Nikita Lazarev-Zubov on 19.10.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation enum PopupAction: String { case reply = "Reply" // "Reply".localized case copy = "Copy" // "Copy".localized case edit = "Edit" // "Edit".localized case delete = "Delete" // "Delete".localized case like = "Like" case dislike = "Dislike" } enum OperatorAvatar: String { case placeholder = "NoAvatarURL" case empty = "GhostImage" }
73d14d25bd9558e2dfdeead68636bb07
38.902439
82
0.724939
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceKit/Sources/EurofurenceWebAPI/Requests/Login.swift
mit
1
import Foundation extension APIRequests { /// A request to login to the Eurofurence application service. public struct Login: APIRequest { public typealias Output = AuthenticatedUser /// The registration number of the user within the registration system. public var registrationNumber: Int /// The associated username of the user within the registration system. public var username: String /// The password associated with the user's registration number. public var password: String public init(registrationNumber: Int, username: String, password: String) { self.registrationNumber = registrationNumber self.username = username self.password = password } public func execute(with context: APIRequestExecutionContext) async throws -> AuthenticatedUser { let url = context.makeURL(subpath: "Tokens/RegSys") let request = LoginPayload(RegNo: registrationNumber, Username: username, Password: password) let encoder = JSONEncoder() let body = try encoder.encode(request) let networkRequest = NetworkRequest(url: url, body: body, method: .post) let response = try await context.network.perform(request: networkRequest) let loginResponse = try context.decoder.decode(LoginResponse.self, from: response) return AuthenticatedUser( userIdentifier: loginResponse.Uid, username: loginResponse.Username, token: loginResponse.Token, tokenExpires: loginResponse.TokenValidUntil ) } private struct LoginPayload: Encodable { var RegNo: Int var Username: String var Password: String } private struct LoginResponse: Decodable { private enum CodingKeys: String, CodingKey { case Uid case Username case Token case TokenValidUntil } var Uid: Int var Username: String var Token: String var TokenValidUntil: Date init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // UIDs look like: RegSys:EF26:<ID> let uidString = try container.decode(String.self, forKey: .Uid) let splitIdentifier = uidString.components(separatedBy: ":") if let stringIdentifier = splitIdentifier.last, let registrationIdentifier = Int(stringIdentifier) { Uid = registrationIdentifier } else { throw CouldNotParseRegistrationIdentifier(uid: uidString) } Username = try container.decode(String.self, forKey: .Username) Token = try container.decode(String.self, forKey: .Token) TokenValidUntil = try container.decode(Date.self, forKey: .TokenValidUntil) } private struct CouldNotParseRegistrationIdentifier: Error { var uid: String } } } }
b0184c7377bddc10e939151702261f32
37.411111
116
0.56523
false
false
false
false
auth0/Lock.swift
refs/heads/master
LockTests/Router/ClassicRouterSpec.swift
mit
1
// ClassicRouterSpec.swift // // Copyright (c) 2016 Auth0 (http://auth0.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 import Nimble import Quick import Auth0 @testable import Lock class ClassicRouterSpec: QuickSpec { override func spec() { var lock: Lock! var controller: MockLockController! var router: ClassicRouter! var header: HeaderView! beforeEach { lock = Lock(authentication: Auth0.authentication(clientId: "CLIENT_ID", domain: "samples.auth0.com"), webAuth: MockWebAuth()) _ = lock.withConnections { $0.database(name: "connection", requiresUsername: false) } controller = MockLockController(lock: lock) header = HeaderView() controller.headerView = header router = ClassicRouter(lock: lock, controller: controller) } describe("root") { beforeEach { lock = Lock(authentication: Auth0.authentication(clientId: "CLIENT_ID", domain: "samples.auth0.com"), webAuth: MockWebAuth()) controller = MockLockController(lock: lock) router = ClassicRouter(lock: lock, controller: controller) } it("should be in classic mode") { expect(lock.classicMode) == true } it("should return root for single database connection") { _ = lock.withConnections { $0.database(name: connection, requiresUsername: true) } let root = router.root as? DatabasePresenter expect(root).toNot(beNil()) expect(root?.authPresenter).to(beNil()) } it("should return root for single database connection and social") { _ = lock.withConnections { $0.database(name: connection, requiresUsername: true) $0.social(name: "facebook", style: .Facebook) } let root = router.root as? DatabasePresenter expect(root).toNot(beNil()) expect(root?.authPresenter).toNot(beNil()) } it("should return root for single database connection and social and enterprise") { _ = lock.withConnections { $0.database(name: connection, requiresUsername: true) $0.social(name: "facebook", style: .Facebook) $0.enterprise(name: "testAD", domains: ["testAD.com"]) } let root = router.root as? DatabasePresenter expect(root).toNot(beNil()) expect(root?.authPresenter).toNot(beNil()) expect(root?.enterpriseInteractor).toNot(beNil()) } it("should return root for single enterprise and social") { _ = lock.withConnections { $0.social(name: "facebook", style: .Facebook) $0.enterprise(name: "testAD", domains: ["testAD.com"]) } let root = router.root as? AuthPresenter expect(root).toNot(beNil()) } it("should return root for only social connections") { _ = lock.withConnections { $0.social(name: "dropbox", style: AuthStyle(name: "Dropbox")) } expect(router.root as? AuthPresenter).toNot(beNil()) } it("should return root for only enterprise connections") { _ = lock.withConnections { $0.enterprise(name: "testAD", domains: ["testAD.com"]) $0.enterprise(name: "validAD", domains: ["validAD.com"]) } expect(router.root as? EnterpriseDomainPresenter).toNot(beNil()) } it("should return root for one enterprise") { _ = lock.withConnections { $0.enterprise(name: "testAD", domains: ["testAD.com"]) } expect(router.root as? AuthPresenter).toNot(beNil()) } it("should return root for one enterprise with active auth") { _ = lock.withConnections { $0.enterprise(name: "testAD", domains: ["testAD.com"]) }.withOptions { $0.enterpriseConnectionUsingActiveAuth = ["testAD"] } expect(router.root as? EnterpriseActiveAuthPresenter).toNot(beNil()) } it("should return root for loading connection from CDN") { expect(router.root as? ConnectionLoadingPresenter).toNot(beNil()) } it("should return root when only reset password is allowed and there is a database connection") { _ = lock .withConnections { $0.database(name: connection, requiresUsername: false) } .withOptions { $0.allow = [.ResetPassword] } expect(router.root as? DatabaseForgotPasswordPresenter).toNot(beNil()) } it("should return root when reset password is the initial screen and there is a database connection") { _ = lock .withConnections { $0.database(name: connection, requiresUsername: false) } .withOptions { $0.allow = [.ResetPassword] } expect(router.root as? DatabaseForgotPasswordPresenter).toNot(beNil()) } it("should return root for single native social") { _ = lock.withConnections { $0.social(name: "facebook", style: .Facebook) }.nativeAuthentication(forConnection: "facebook", handler: MockNativeAuthHandler()) expect(router.root as? AuthPresenter).toNot(beNil()) } describe("passwordless") { it("should not return root for passwordless email connection") { _ = lock.withConnections { $0.email(name: "custom-email") } let presenter = router.root as? PasswordlessPresenter expect(presenter).to(beNil()) } it("should not return root for passwordless sms connection") { _ = lock.withConnections { $0.sms(name: "custom-sms") } let presenter = router.root as? PasswordlessPresenter expect(presenter).to(beNil()) } } } describe("events") { describe("back") { beforeEach { router.navigate(.multifactor) } it("should navigate back to root") { router.onBack() expect(controller.routes.current) == Route.root } it("should clean user email") { router.user.email = email router.onBack() expect(router.user.email).to(beNil()) } it("should clean user username") { router.user.username = username router.onBack() expect(router.user.username).to(beNil()) } it("should clean user password") { router.user.password = password router.onBack() expect(router.user.password).to(beNil()) } it("should not clean valid user email") { router.user.email = email router.user.validEmail = true router.onBack() expect(router.user.email) == email } it("should not clean valid user username") { router.user.username = username router.user.validUsername = true router.onBack() expect(router.user.username) == username } it("should always clean user password") { router.user.password = password router.user.validPassword = true router.onBack() expect(router.user.password).to(beNil()) } } describe("exit") { var presenting: MockViewController! beforeEach { presenting = MockViewController() presenting.presented = controller controller.presenting = presenting } it("should dismiss controller") { router.exit(withError: UnrecoverableError.invalidClientOrDomain) expect(presenting.presented).toEventually(beNil()) } it("should pass error in callback") { waitUntil(timeout: .seconds(2)) { done in lock.observerStore.onFailure = { cause in if case UnrecoverableError.invalidClientOrDomain = cause { done() } } router.exit(withError: UnrecoverableError.invalidClientOrDomain) } } } } describe("navigate") { it("should set title for root") { router.navigate(.forgotPassword) router.navigate(.root) expect(controller.headerView.title) == Style.Auth0.title } it("should not show root again") { expect(controller.routes.current).toNot(beNil()) router.navigate(.root) expect(controller.presentable).to(beNil()) } it("should show forgot pwd screen") { router.navigate(.forgotPassword) expect(controller.presentable as? DatabaseForgotPasswordPresenter).toNot(beNil()) expect(controller.headerView.title) == "Reset Password" } it("should show multifactor screen") { router.navigate(.multifactor) expect(controller.presentable as? MultifactorPresenter).toNot(beNil()) expect(controller.headerView.title) == "Two Step Verification" } it("should show multifactor screen for .multifactorWithToken ") { router.navigate(.multifactorWithToken("TOKEN")) expect(controller.presentable as? MultifactorPresenter).toNot(beNil()) expect(controller.headerView.title) == "Two Step Verification" } it("should show enterprise active auth screen") { router.navigate(.enterpriseActiveAuth(connection: EnterpriseConnection(name: "testAD", domains: ["testad.com"]), domain: "testad.com")) expect(controller.presentable as? EnterpriseActiveAuthPresenter).toNot(beNil()) expect(controller.headerView.title) == Style.Auth0.title } it("should show connection error screen") { router.navigate(.unrecoverableError(error: UnrecoverableError.connectionTimeout)) expect(controller.presentable as? UnrecoverableErrorPresenter).toNot(beNil()) } context("no connection") { beforeEach { lock = Lock(authentication: Auth0.authentication(clientId: "CLIENT_ID", domain: "samples.auth0.com"), webAuth: MockWebAuth()) controller = MockLockController(lock: lock) controller.headerView = header router = ClassicRouter(lock: lock, controller: controller) } it("should fail multifactor screen") { router.navigate(.multifactor) expect(controller.presentable).to(beNil()) } it("should fail forgotPassword screen") { router.navigate(.forgotPassword) expect(controller.presentable).to(beNil()) } } } it("should present view controller") { let presented = UIViewController() router.present(presented) expect(controller.presented) == presented } describe("reload") { beforeEach { let presenting = MockViewController() presenting.presented = controller controller.presenting = presenting } it("should override connections") { var connections = OfflineConnections() connections.social(name: "facebook", style: .Facebook) router.reload(with: connections) let actual = router.lock.connections expect(actual.isEmpty) == false expect(actual.oauth2.map { $0.name }).to(contain("facebook")) } it("should show root") { var connections = OfflineConnections() connections.social(name: "facebook", style: .Facebook) router.reload(with: connections) expect(controller.presentable).toNot(beNil()) expect(controller.routes.history).to(beEmpty()) } it("should select when overriding connections") { lock = Lock(authentication: Auth0.authentication(clientId: "CLIENT_ID", domain: "samples.auth0.com"), webAuth: MockWebAuth()).allowedConnections(["facebook"]) controller = MockLockController(lock: lock) controller.headerView = header router = ClassicRouter(lock: lock, controller: controller) var connections = OfflineConnections() connections.social(name: "facebook", style: .Facebook) connections.social(name: "twitter", style: .Twitter) router.reload(with: connections) let actual = router.lock.connections expect(actual.oauth2.map { $0.name }).toNot(contain("twitter")) expect(actual.oauth2.map { $0.name }).to(contain("facebook")) } it("should exit with error when connections are empty") { waitUntil(timeout: .seconds(2)) { done in lock.observerStore.onFailure = { cause in if case UnrecoverableError.clientWithNoConnections = cause { done() } } router.reload(with: OfflineConnections()) } } } describe("route equatable") { it("root should should be equatable with root") { let match = Route.root == Route.root expect(match).to(beTrue()) } it("Multifactor should should be equatable with Multifactor") { let match = Route.multifactor == Route.multifactor expect(match).to(beTrue()) } it("ForgotPassword should should be equatable with ForgotPassword") { let match = Route.forgotPassword == Route.forgotPassword expect(match).to(beTrue()) } it("EnterpriseActiveAuth should should be equatable with EnterpriseActiveAuth") { let enterpriseConnection = EnterpriseConnection(name: "TestAD", domains: ["test.com"]) let match = Route.enterpriseActiveAuth(connection: enterpriseConnection, domain: "test.com") == Route.enterpriseActiveAuth(connection: enterpriseConnection, domain: "test.com") expect(match).to(beTrue()) } it("UnrecoverableError should should be equatable with UnrecoverableError") { let error = UnrecoverableError.connectionTimeout let match = Route.unrecoverableError(error: error) == Route.unrecoverableError(error: error) expect(match).to(beTrue()) } it("root should should not be equatable with Multifactor") { let match = Route.root == Route.multifactor expect(match).to(beFalse()) } } } }
334f87613457061c05cdeb30ae9489e3
41.621027
192
0.545262
false
false
false
false
mpeyrotc/tiro_parabolico
refs/heads/master
ChartsAPI/Source/Charts/Data/Implementations/Standard/ChartDataSet.swift
apache-2.0
3
// // ChartDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation /// Determines how to round DataSet index values for `ChartDataSet.entryIndex(x, rounding)` when an exact x-value is not found. @objc public enum ChartDataSetRounding: Int { case up = 0 case down = 1 case closest = 2 } /// The DataSet class represents one group or type of entries (Entry) in the Chart that belong together. /// It is designed to logically separate different groups of values inside the Chart (e.g. the values for a specific line in the LineChart, or the values of a specific group of bars in the BarChart). open class ChartDataSet: ChartBaseDataSet { public required init() { super.init() _values = [ChartDataEntry]() } public override init(label: String?) { super.init(label: label) _values = [ChartDataEntry]() } public init(values: [ChartDataEntry]?, label: String?) { super.init(label: label) _values = values == nil ? [ChartDataEntry]() : values self.calcMinMax() } public convenience init(values: [ChartDataEntry]?) { self.init(values: values, label: "DataSet") } // MARK: - Data functions and accessors /// the entries that this dataset represents / holds together internal var _values: [ChartDataEntry]! /// maximum y-value in the value array internal var _yMax: Double = -DBL_MAX /// minimum y-value in the value array internal var _yMin: Double = DBL_MAX /// maximum x-value in the value array internal var _xMax: Double = -DBL_MAX /// minimum x-value in the value array internal var _xMin: Double = DBL_MAX /// * /// - note: Calls `notifyDataSetChanged()` after setting a new value. /// - returns: The array of y-values that this DataSet represents. open var values: [ChartDataEntry] { get { return _values } set { _values = newValue notifyDataSetChanged() } } /// Use this method to tell the data set that the underlying data has changed open override func notifyDataSetChanged() { calcMinMax() } open override func calcMinMax() { if _values.count == 0 { return } _yMax = -DBL_MAX _yMin = DBL_MAX _xMax = -DBL_MAX _xMin = DBL_MAX for e in _values { calcMinMax(entry: e) } } open override func calcMinMaxY(fromX: Double, toX: Double) { if _values.count == 0 { return } _yMax = -DBL_MAX _yMin = DBL_MAX let indexFrom = entryIndex(x: fromX, closestToY: Double.nan, rounding: .down) let indexTo = entryIndex(x: toX, closestToY: Double.nan, rounding: .up) if indexTo <= indexFrom { return } for i in indexFrom..<indexTo { // only recalculate y calcMinMaxY(entry: _values[i]) } } open func calcMinMaxX(entry e: ChartDataEntry) { if e.x < _xMin { _xMin = e.x } if e.x > _xMax { _xMax = e.x } } open func calcMinMaxY(entry e: ChartDataEntry) { if e.y < _yMin { _yMin = e.y } if e.y > _yMax { _yMax = e.y } } /// Updates the min and max x and y value of this DataSet based on the given Entry. /// /// - parameter e: internal func calcMinMax(entry e: ChartDataEntry) { calcMinMaxX(entry: e) calcMinMaxY(entry: e) } /// - returns: The minimum y-value this DataSet holds open override var yMin: Double { return _yMin } /// - returns: The maximum y-value this DataSet holds open override var yMax: Double { return _yMax } /// - returns: The minimum x-value this DataSet holds open override var xMin: Double { return _xMin } /// - returns: The maximum x-value this DataSet holds open override var xMax: Double { return _xMax } /// - returns: The number of y-values this DataSet represents open override var entryCount: Int { return _values?.count ?? 0 } /// - returns: The entry object found at the given index (not x-value!) /// - throws: out of bounds /// if `i` is out of bounds, it may throw an out-of-bounds exception open override func entryForIndex(_ i: Int) -> ChartDataEntry? { guard i >= 0 && i < _values.count else { return nil } return _values[i] } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value according to the rounding. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: determine whether to round up/down/closest if there is no Entry matching the provided x-value open override func entryForXValue( _ xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> ChartDataEntry? { let index = self.entryIndex(x: xValue, closestToY: yValue, rounding: rounding) if index > -1 { return _values[index] } return nil } /// - returns: The first Entry object found at the given x-value with binary search. /// If the no Entry at the specified x-value is found, this method returns the Entry at the closest x-value. /// nil if no Entry object at that x-value. /// - parameter xValue: the x-value /// - parameter closestToY: If there are multiple y-values for the specified x-value, open override func entryForXValue( _ xValue: Double, closestToY yValue: Double) -> ChartDataEntry? { return entryForXValue(xValue, closestToY: yValue, rounding: .closest) } /// - returns: All Entry objects found at the given xIndex with binary search. /// An empty array if no Entry object at that index. open override func entriesForXValue(_ xValue: Double) -> [ChartDataEntry] { var entries = [ChartDataEntry]() var low = 0 var high = _values.count - 1 while low <= high { var m = (high + low) / 2 var entry = _values[m] // if we have a match if xValue == entry.x { while m > 0 && _values[m - 1].x == xValue { m -= 1 } high = _values.count // loop over all "equal" entries while m < high { entry = _values[m] if entry.x == xValue { entries.append(entry) } else { break } m += 1 } break } else { if xValue > entry.x { low = m + 1 } else { high = m - 1 } } } return entries } /// - returns: The array-index of the specified entry. /// If the no Entry at the specified x-value is found, this method returns the index of the Entry at the closest x-value according to the rounding. /// /// - parameter xValue: x-value of the entry to search for /// - parameter closestToY: If there are multiple y-values for the specified x-value, /// - parameter rounding: Rounding method if exact value was not found open override func entryIndex( x xValue: Double, closestToY yValue: Double, rounding: ChartDataSetRounding) -> Int { var low = 0 var high = _values.count - 1 var closest = high while low < high { let m = (low + high) / 2 let d1 = _values[m].x - xValue let d2 = _values[m + 1].x - xValue let ad1 = abs(d1), ad2 = abs(d2) if ad2 < ad1 { // [m + 1] is closer to xValue // Search in an higher place low = m + 1 } else if ad1 < ad2 { // [m] is closer to xValue // Search in a lower place high = m } else { // We have multiple sequential x-value with same distance if d1 >= 0.0 { // Search in a lower place high = m } else if d1 < 0.0 { // Search in an higher place low = m + 1 } } closest = high } if closest != -1 { let closestXValue = _values[closest].x if rounding == .up { // If rounding up, and found x-value is lower than specified x, and we can go upper... if closestXValue < xValue && closest < _values.count - 1 { closest += 1 } } else if rounding == .down { // If rounding down, and found x-value is upper than specified x, and we can go lower... if closestXValue > xValue && closest > 0 { closest -= 1 } } // Search by closest to y-value if !yValue.isNaN { while closest > 0 && _values[closest - 1].x == closestXValue { closest -= 1 } var closestYValue = _values[closest].y var closestYIndex = closest while true { closest += 1 if closest >= _values.count { break } let value = _values[closest] if value.x != closestXValue { break } if abs(value.y - yValue) < abs(closestYValue - yValue) { closestYValue = yValue closestYIndex = closest } } closest = closestYIndex } } return closest } /// - returns: The array-index of the specified entry /// /// - parameter e: the entry to search for open override func entryIndex(entry e: ChartDataEntry) -> Int { for i in 0 ..< _values.count { if _values[i] === e { return i } } return -1 } /// Adds an Entry to the DataSet dynamically. /// Entries are added to the end of the list. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntry(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) _values.append(e) return true } /// Adds an Entry to the DataSet dynamically. /// Entries are added to their appropriate index respective to it's x-index. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter e: the entry to add /// - returns: True open override func addEntryOrdered(_ e: ChartDataEntry) -> Bool { if _values == nil { _values = [ChartDataEntry]() } calcMinMax(entry: e) if _values.count > 0 && _values.last!.x > e.x { var closestIndex = entryIndex(x: e.x, closestToY: e.y, rounding: .up) while _values[closestIndex].x < e.x { closestIndex += 1 } _values.insert(e, at: closestIndex) } else { _values.append(e) } return true } /// Removes an Entry from the DataSet dynamically. /// This will also recalculate the current minimum and maximum values of the DataSet and the value-sum. /// - parameter entry: the entry to remove /// - returns: `true` if the entry was removed successfully, else if the entry does not exist open override func removeEntry(_ entry: ChartDataEntry) -> Bool { var removed = false for i in 0 ..< _values.count { if _values[i] === entry { _values.remove(at: i) removed = true break } } if removed { calcMinMax() } return removed } /// Removes the first Entry (at index 0) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeFirst() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeFirst() let removed = entry != nil if removed { calcMinMax() } return removed } /// Removes the last Entry (at index size-1) of this DataSet from the entries array. /// /// - returns: `true` if successful, `false` ifnot. open override func removeLast() -> Bool { let entry: ChartDataEntry? = _values.isEmpty ? nil : _values.removeLast() let removed = entry != nil if removed { calcMinMax() } return removed } /// Checks if this DataSet contains the specified Entry. /// - returns: `true` if contains the entry, `false` ifnot. open override func contains(_ e: ChartDataEntry) -> Bool { for entry in _values { if (entry.isEqual(e)) { return true } } return false } /// Removes all values from this DataSet and recalculates min and max value. open override func clear() { _values.removeAll(keepingCapacity: true) notifyDataSetChanged() } // MARK: - Data functions and accessors // MARK: - NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! ChartDataSet copy._values = _values copy._yMax = _yMax copy._yMin = _yMin return copy } }
abc5f5b42d8f076d227aee3fa1cff67d
27.564982
199
0.496682
false
false
false
false
buyiyang/iosstar
refs/heads/master
iOSStar/Scenes/Discover/Controllers/StarInteractiveViewController.swift
gpl-3.0
3
// // StarInteractiveViewController.swift // iOSStar // // Created by J-bb on 17/7/6. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import MJRefresh class StarInteractiveViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var dataSource:[StarSortListModel]? var imageNames:[String]? let header = MJRefreshNormalHeader() override func viewDidLoad() { super.viewDidLoad() header.setRefreshingTarget(self, refreshingAction: #selector(requestStar)) self.tableView!.mj_header = header self.tableView.mj_header.beginRefreshing() tableView.register(NoDataCell.self, forCellReuseIdentifier: "NoDataCell") configImageNames() // requestStar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } func configImageNames() { imageNames = [] for index in 0...10 { imageNames?.append("starList_back\(index)") } } func requestStar() { let requestModel = StarSortListRequestModel() AppAPIHelper.discoverAPI().requestStarList(requestModel: requestModel, complete: { (response) in if let models = response as? [StarSortListModel] { self.header.endRefreshing() self.dataSource = models self.tableView.reloadData() } self.header.endRefreshing() }) { (error) in self.header.endRefreshing() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if dataSource == nil || dataSource!.count == 0{ return } if let indexPath = sender as? IndexPath { let model = dataSource![indexPath.item] let vc = segue.destination if segue.identifier == "InterToIntroduce" { if let introVC = vc as? StarIntroduceViewController { introVC.starModel = model } } if segue.identifier == "StarNewsVC" { if let introVC = vc as? StarNewsVC { introVC.starModel = model } } } } } extension StarInteractiveViewController:UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return self.dataSource == nil ? UIScreen.main.bounds.size.height - 150 : 130 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.count ?? 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.dataSource == nil{ let cell = tableView.dequeueReusableCell(withIdentifier: NoDataCell.className(), for: indexPath) as! NoDataCell cell.imageView?.image = UIImage.init(named: "nodata") return cell } let cell = tableView.dequeueReusableCell(withIdentifier: StarInfoCell.className(), for: indexPath) as! StarInfoCell cell.setStarModel(starModel:dataSource![indexPath.row]) cell.setBackImage(imageName: (imageNames?[indexPath.row % 10])!) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if dataSource == nil || dataSource?.count == 0{ return } if checkLogin(){ if let model: StarSortListModel = dataSource![indexPath.row] as? StarSortListModel{ ShareDataModel.share().selectStarCode = model.symbol performSegue(withIdentifier: StarNewsVC.className(), sender: indexPath) } } } }
ce7a4f0d460ccc07613a71d677ca7709
32.8
123
0.602521
false
false
false
false
NicholasMata/SimpleTabBarController
refs/heads/master
SimpleTabBarController/SimpleAnimators/SimpleIrregularAppearance.swift
mit
1
// // SimpleIrregularAnimator.swift // Pods // // Created by Nicholas Mata on 10/25/16. // // import UIKit open class SimpleIrregularAppearance: SimpleBarItemAppearance { open var borderWidth: CGFloat = 3.0 open var borderColor = UIColor(white: 235 / 255.0, alpha: 1.0) open var radius: CGFloat = 35 open var insets: UIEdgeInsets = UIEdgeInsets(top: -32, left: 0, bottom: 0, right: 0) open var irregularBackgroundColor: UIColor = .gray open override var content: UIView? { didSet { if let content = content as? SimpleBarItemContent { content.imageView.backgroundColor = irregularBackgroundColor content.imageView.layer.borderWidth = borderWidth content.imageView.layer.borderColor = borderColor.cgColor content.imageView.layer.cornerRadius = radius content.insets = insets let transform = CGAffineTransform.identity content.imageView.transform = transform content.superview?.bringSubviewToFront(content) } } } public required init() { super.init() textColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) highlightTextColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) iconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) highlightIconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) backgroundColor = UIColor.clear highlightBackgroundColor = UIColor.clear } open override func selectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) { super.selectAnimation(content: content, animated: animated, completion: completion) } open override func reselectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) { super.reselectAnimation(content: content, animated: animated, completion: completion) } open override func deselectAnimation(content: UIView, animated: Bool, completion: (() -> ())?) { super.deselectAnimation(content: content, animated: animated, completion: completion) } open override func highlightAnimation(content: UIView, animated: Bool, completion: (() -> ())?) { super.highlightAnimation(content: content, animated: animated, completion: completion) } open override func dehighlightAnimation(content: UIView, animated: Bool, completion: (() -> ())?) { super.dehighlightAnimation(content: content, animated: animated, completion: completion) } }
7c8a300dbca3a0ba261951176797795d
35.633803
103
0.64975
false
false
false
false
billdonner/sheetcheats9
refs/heads/master
sc9/ColorUtil.swift
apache-2.0
1
// // ColorUtil.swift // sc9 // // Created by william donner on 12/20/16. // Copyright © 2016 shovelreadyapps. All rights reserved. // // from // ColorUtil.swift // // Created by Ben Dalziel on 2/17/16. //https://medium.com/ios-os-x-development/codifying-style-guides-in-swift-6a27b742f441#.uo3m17xvd //import SwiftHEXColors struct Col { enum AppUIColors: Int { case navBarBackground, navBarTint, navBarShadow, launchBackground, mainViewControllerBackground, modalmenuBackground, previewBackground, // all help and info helpActivityIndicator, helpBackground, helpText, helpAltText, //settings page settingsBackground, settingsButton, settingsText, settingsAltText, //search,list,history tableActivityIndicator, tableBackground, tableSeparator, tableCellSelectedBackground, tableCellSelectedBackgroundDark, tableSearchIndexText, tableSectionText, tableSectionHeaderText, tableSectionHeaderAltText, tableRefreshText, //gig matrix is collection view collectionActivityIndicator, collectionBackground, collectionSeparator, collectionCellSelectedBackground, collectionCellSelectedBackgroundDark, collectionSectionText, collectionSectionHeaderText, collectionSectionHeaderAltText, collectionRefreshText, //colors on outer menus gigMatrixMenuTitle, gigMatrixMenuBackground, searchMenuTitle, searchMenuBackground, gigListMenuTitle, gigListMenuBackground, settingsMenuTitle, settingsMenuBackground, historyMenuTitle, historyMenuBackground } private enum AppColors: String { case // colors on the menu should be all we use lightBlue = "#3091FF", green = "#38BD00", red = "#F53B36", purple = "#8225FF", orange = "#FF6200", blue = "#141459", almostWhite = "#F8FAFD", darkGray = "#222222", black = "#000000", //old detritus beige = "#f5efe0", gold = "#cda582", goldAlt = "#e1b996" } /// usage: Col.r( appUIColor) /// eg let backgroundColor = Col.r(.gigListMenuBackgrond) static func r(_ appUIColor: AppUIColors) -> UIColor { func colorWithAlpha(_ appColor: AppColors, alpha: Float) -> UIColor { return UIColor(hexString: appColor.rawValue, alpha: alpha)! } func color(_ appColor: AppColors) -> UIColor { return UIColor(hexString: appColor.rawValue)! } switch appUIColor { case .navBarBackground: return color(.beige) case .navBarTint : return color(.gold) case .navBarShadow : return colorWithAlpha(.goldAlt, alpha: 0.7) case .modalmenuBackground: return color(.blue) // settings case .settingsBackground,.previewBackground: return color(.almostWhite) case .settingsText : return color(.lightBlue) case .settingsAltText: return color(.green) case .settingsButton: return color(.black) // help case .helpBackground,.helpActivityIndicator: return color(.almostWhite) case .helpText,.helpAltText: return color(.black) // all lists case .tableSearchIndexText: return color(.red) case .tableBackground, .tableSeparator, .tableCellSelectedBackground, .tableCellSelectedBackgroundDark: return color(.blue) case .tableActivityIndicator, .tableSectionText, .tableSectionHeaderText, .tableSectionHeaderAltText, .tableRefreshText: return color(.almostWhite) //GigMatrix is collectionview case .collectionBackground, .collectionSeparator, .collectionCellSelectedBackground, .collectionCellSelectedBackgroundDark : return color(.blue) case .collectionActivityIndicator, .collectionSectionText, .collectionSectionHeaderText, .collectionSectionHeaderAltText, .collectionRefreshText: return color(.almostWhite) // menus case .gigMatrixMenuTitle: return color(.almostWhite) case .gigMatrixMenuBackground: return color(.lightBlue) case .searchMenuTitle: return color(.almostWhite) case .searchMenuBackground: return color(.green) case .gigListMenuTitle: return color(.almostWhite) case .gigListMenuBackground: return color(.red) case .settingsMenuTitle: return color(.almostWhite) case .settingsMenuBackground: return color(.purple) case .historyMenuTitle: return color(.almostWhite) case .historyMenuBackground: return color(.orange) default: return color(.gold) } } /// Background Pattern Images // not currently used enum AppUIPatterns: Int { case gigMatrixBackground, exportsBackground, grabPhotosBackground, importItunesBackground, remoteImportBackground, helpBackground, settingsBackground, launchBackground } static func uiPattern(appUIPattern: AppUIPatterns) -> UIColor { switch appUIPattern { case .gigMatrixBackground: return UIColor(patternImage: UIImage.init(named: "FML Pattern Light")!) case .exportsBackground, .grabPhotosBackground, .importItunesBackground, .remoteImportBackground, . helpBackground, .settingsBackground: // Subtle return UIColor(patternImage: UIImage.init(named: "FML Pattern Light")!) case .launchBackground : return UIColor(patternImage: UIImage.init(named: "FML Pattern Dark Subtle - Launch")!) } } }
4c9169d56a532d37b374966698f3b0f4
27.106557
98
0.555118
false
false
false
false
bmichotte/HSTracker
refs/heads/master
HSTracker/Hearthstone/Secrets/Secret.swift
mit
1
// // Secret.swift // HSTracker // // Created by Benjamin Michotte on 9/03/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import CleanroomLogger import RealmSwift class Secret { private(set) var cardId: String var count: Int init(cardId: String, count: Int) { self.cardId = cardId self.count = count } private func activeDeckIsConstructed(game: Game) -> Bool { guard let deck = game.currentDeck else { return false } return !deck.isArena } func adjustedCount(game: Game) -> Int { return ((game.currentGameMode == .casual || game.currentGameMode == .ranked || game.currentGameMode == .friendly || game.currentGameMode == .practice || activeDeckIsConstructed(game: game)) && game.opponent.revealedEntities.filter { $0.id < 68 && $0.cardId == self.cardId } .count >= 2) ? 0 : self.count } }
e210851d4e47f5b4024d4569d3b2769e
25.916667
95
0.617131
false
false
false
false
azizuysal/NetKit
refs/heads/master
NetKit/NetKit/WebRequest.swift
mit
1
// // WebRequest.swift // NetKit // // Created by Aziz Uysal on 2/12/16. // Copyright © 2016 Aziz Uysal. All rights reserved. // import Foundation public struct WebRequest { public struct Headers { public static let userAgent = "User-Agent" public static let contentType = "Content-Type" public static let contentLength = "Content-Length" public static let accept = "Accept" public static let cacheControl = "Cache-Control" public struct ContentType { public static let json = "application/json" public static let xml = "text/xml" public static let formEncoded = "application/x-www-form-urlencoded" } } public enum Method: String { case HEAD = "HEAD" case GET = "GET" case POST = "POST" case PUT = "PUT" case DELETE = "DELETE" } public enum ParameterEncoding { case percent, json public func encodeURL(_ url: URL, parameters: [String:Any]) -> URL? { if var components = URLComponents(url: url, resolvingAgainstBaseURL: false) { components.appendPercentEncodedQuery(parameters.percentEncodedQueryString) return components.url } return nil } public func encodeBody(_ parameters: [String:Any]) -> Data? { switch self { case .percent: return parameters.percentEncodedQueryString.data(using: String.Encoding.utf8, allowLossyConversion: false) case .json: do { return try JSONSerialization.data(withJSONObject: parameters, options: []) } catch { return nil } } } } let method: Method private(set) var url: URL var body: Data? var cachePolicy = URLRequest.CachePolicy.useProtocolCachePolicy var urlParameters = [String:Any]() var bodyParameters = [String:Any]() var parameterEncoding = ParameterEncoding.percent { didSet { if parameterEncoding == .json { contentType = Headers.ContentType.json } } } var restPath = "" { didSet { url = url.appendingPathComponent(restPath) } } var headers = [String:String]() var contentType: String? { set { headers[Headers.contentType] = newValue } get { return headers[Headers.contentType] } } var urlRequest: URLRequest { let request = NSMutableURLRequest(url: url) request.httpMethod = method.rawValue request.cachePolicy = cachePolicy for (name, value) in headers { request.addValue(value, forHTTPHeaderField: name) } if urlParameters.count > 0 { if let url = request.url, let encodedURL = parameterEncoding.encodeURL(url, parameters: urlParameters) { request.url = encodedURL } } if bodyParameters.count > 0 { if let data = parameterEncoding.encodeBody(bodyParameters) { request.httpBody = data if request.value(forHTTPHeaderField: Headers.contentType) == nil { request.setValue(Headers.ContentType.formEncoded, forHTTPHeaderField: Headers.contentType) } } } if let body = body { request.httpBody = body } return request.copy() as! URLRequest } public init(method: Method, url: URL) { self.method = method self.url = url } } extension URLComponents { mutating func appendPercentEncodedQuery(_ query: String) { percentEncodedQuery = percentEncodedQuery == nil ? query : "\(percentEncodedQuery ?? "")&\(query)" } } extension Dictionary { var percentEncodedQueryString: String { var components = [String]() for (name, value) in self { if let percentEncodedPair = percentEncode((name, value)) { components.append(percentEncodedPair) } } return components.joined(separator: "&") } func percentEncode(_ element: Element) -> String? { let (name, value) = element if let encodedName = "\(name)".percentEncodeURLQueryCharacters, let encodedValue = "\(value)".percentEncodeURLQueryCharacters { return "\(encodedName)=\(encodedValue)" } return nil } } extension String { var percentEncodeURLQueryCharacters: String? { let allowedCharacterSet = CharacterSet(charactersIn: "\\!*'();:@&=+$,/?%#[] ").inverted return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet /*.urlQueryAllowed*/) } }
d7e81ab69ad4e63eb9e7a790a5dd7f4b
26.717949
131
0.654024
false
false
false
false
ChristianKienle/highway
refs/heads/master
Sources/FSKit/Implementations/AnchoredFileSystem.swift
mit
1
import Foundation public final class AnchoredFileSystem { // MARK: - Init public init(underlyingFileSystem: FileSystem, achnoredAt root: Absolute) { self.underlyingFileSystem = underlyingFileSystem self.root = root } // MARL: Properties public let underlyingFileSystem: FileSystem public let root: Absolute } extension AnchoredFileSystem: FileSystem { public func assertItem(at url: Absolute, is itemType: Metadata.ItemType) throws { let meta = try itemMetadata(at: url) guard meta.type == itemType else { throw FSError.typeMismatch } } public func itemMetadata(at url: Absolute) throws -> Metadata { return try underlyingFileSystem.itemMetadata(at: _completeUrl(url)) } public func homeDirectoryUrl() throws -> Absolute { return try underlyingFileSystem.homeDirectoryUrl() } public func temporaryDirectoryUrl() throws -> Absolute { return try underlyingFileSystem.temporaryDirectoryUrl() } public func createDirectory(at url: Absolute) throws { try underlyingFileSystem.createDirectory(at: _completeUrl(url)) } public func writeData(_ data: Data, to url: Absolute) throws { try underlyingFileSystem.writeData(data, to: _completeUrl(url)) } public func data(at url: Absolute) throws -> Data { return try underlyingFileSystem.data(at: _completeUrl(url)) } public func deleteItem(at url: Absolute) throws { try underlyingFileSystem.deleteItem(at: _completeUrl(url)) } public func writeString(_ string: String, to url: Absolute) throws { guard let data = string.data(using: .utf8) else { throw FSError.other("Failed to convert data to utf8 string.") } try writeData(data, to: url) } // MARK: - Convenience public func file(at url: Absolute) -> File { return File(url: url, fileSystem: self) } public func directory(at url: Absolute) -> Directory { return Directory(url: url, in: self) } public func stringContentsOfFile(at url: Absolute) throws -> String { return try file(at: _completeUrl(url)).string() } public func dataContentsOfFile(at url: Absolute) throws -> Data { return try file(at: _completeUrl(url)).data() } private func _completeUrl(_ proposedUrl: Absolute) -> Absolute { if proposedUrl == Absolute.root { return root } else { let relativePath = proposedUrl.asRelativePath return Absolute(path: relativePath, relativeTo: root) } } }
4d53edb42a0e61ccc6ce47a9b2061565
32.721519
85
0.649399
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Telephone Digits.xcplaygroundpage/Contents.swift
mit
1
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Telephone Digits //: ### The dial tone is not the only sound on your phone that is just two sine waves, so are all the digits. import XCPlayground import AudioKit //: Here is the canonical specification of DTMF Tones var keys = [String: [Double]]() keys["1"] = [697, 1209] keys["2"] = [697, 1336] keys["3"] = [697, 1477] keys["4"] = [770, 1209] keys["5"] = [770, 1336] keys["6"] = [770, 1477] keys["7"] = [852, 1209] keys["8"] = [852, 1336] keys["9"] = [852, 1477] keys["*"] = [941, 1209] keys["0"] = [941, 1336] keys["#"] = [941, 1477] let keyPressTone = AKOperation.sineWave(frequency: AKOperation.parameters(0)) + AKOperation.sineWave(frequency: AKOperation.parameters(1)) let momentaryPress = keyPressTone.triggeredWithEnvelope( AKOperation.trigger, attack: 0.01, hold: 0.1, release: 0.01) let generator = AKOperationGenerator( operation: momentaryPress * 0.4) AudioKit.output = generator AudioKit.start() generator.start() //: Let's call Jenny and Mary! let phoneNumber = "8675309 3212333 222 333 3212333322321" for number in phoneNumber.characters { if keys.keys.contains(String(number)) { generator.trigger(keys[String(number)]!) } usleep(250000) } //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
263d2670671805afa15a207a5733c457
27.479167
109
0.664228
false
false
false
false