repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
criticalmaps/criticalmaps-ios
CriticalMapsKit/Sources/MapFeature/RiderAnnotationUpdateClient.swift
1
1389
import Foundation import MapKit import SharedModels /// A client to update rider annotations on a map. public enum RiderAnnotationUpdateClient { /// Calculates the difference between displayed annotations and a collection of new rider elements. /// /// - Parameters: /// - riderCoordinates: Collection of rider elements that should be displayed /// - mapView: A MapView in which the annotations should be displayed /// - Returns: A tuple containing annotations that should be added and removed public static func update( _ riderCoordinates: [Rider], _ mapView: MKMapView ) -> ( removedAnnotations: [RiderAnnotation], addedAnnotations: [RiderAnnotation] ) { let currentlyDisplayedPOIs = mapView.annotations.compactMap { $0 as? RiderAnnotation } .map(\.rider) // Riders that should be added let addedRider = Set(riderCoordinates).subtracting(currentlyDisplayedPOIs) // Riders that are not on the map anymore let removedRider = Set(currentlyDisplayedPOIs).subtracting(riderCoordinates) let addedAnnotations = addedRider.map(RiderAnnotation.init(rider:)) // Annotations that should be removed let removedAnnotations = mapView.annotations .compactMap { $0 as? RiderAnnotation } .filter { removedRider.contains($0.rider) } return (removedAnnotations, addedAnnotations) } }
mit
6b6da1645795361c3498a8147a8d34d1
35.552632
101
0.720662
4.72449
false
false
false
false
zalando/zmon-ios
zmon/controllers/ZmonDashboardVC.swift
1
3779
// // ZmonDashboardVC.swift // zmon // // Created by Andrej Kincel on 16/12/15. // Copyright © 2015 Zalando Tech. All rights reserved. // import UIKit class ZmonDashboardVC: BaseVC, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var table: UITableView! let zmonAlertsService: ZmonAlertsService = ZmonAlertsService() var dataUpdatesTimer: NSTimer? var alertList: [ZmonAlertStatus] = [] override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "ZmonDashboard".localized self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Pause", style:.Plain, target: self, action: #selector(ZmonDashboardVC.toggleDataUpdates)) self.table.dataSource = self self.table.delegate = self self.updateZmonDashboard() self.startDataUpdates() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.stopDataUpdates() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK:- UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.alertList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let alert: ZmonAlertStatus = self.alertList[indexPath.row] let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("AlertCell")! cell.textLabel!.text = alert.message; setBackgroundColor(cell: cell, priority: alert.alertDefinition?.priority ?? 0) return cell } private func setBackgroundColor(cell cell: UITableViewCell, priority: Int) { switch (priority) { case 1: cell.backgroundColor = ZmonColor.alertCritical break; case 2: cell.backgroundColor = ZmonColor.alertMedium break; default: cell.backgroundColor = ZmonColor.alertLow break; } } //MARK: - Data tasks func toggleDataUpdates() { if self.dataUpdatesTimer == nil { startDataUpdates() self.navigationItem.rightBarButtonItem!.title = "Pause" } else { stopDataUpdates() self.navigationItem.rightBarButtonItem!.title = "Start" } } private func startDataUpdates(){ stopDataUpdates() log.debug("Starting ZMON Dashboard updates") self.dataUpdatesTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(ZmonDashboardVC.updateZmonDashboard), userInfo: nil, repeats: true) } private func stopDataUpdates(){ if let timer = self.dataUpdatesTimer { log.debug("Stopping ZMON Dashboard updates") timer.invalidate() self.dataUpdatesTimer = nil } } func updateZmonDashboard() { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let teamList: [String] = Team.allObservedTeamNames() self.zmonAlertsService.listByTeam(teamName: teamList.joinWithSeparator(","), success: { (alerts: [ZmonAlertStatus]) -> () in self.alertList = alerts self.alertList.sortInPlace({ (a: ZmonAlertStatus, b: ZmonAlertStatus) -> Bool in return a.alertDefinition?.priority < b.alertDefinition?.priority }) self.table.reloadData() }) } } }
mit
26d1fcc07ed5a4787f44d47fe2f55375
32.433628
162
0.625463
4.837388
false
false
false
false
daviejaneway/OrbitFrontend
Tests/OrbitFrontendTests/ParserTests.swift
1
40547
// // ParserTests.swift // OrbitFrontend // // Created by Davie Janeway on 28/05/2017. // // import XCTest @testable import OrbitFrontend import OrbitCompilerUtils //precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } // //infix operator ** : PowerPrecedence //func ** (radix: Int, power: Int) -> Int { // return Int(pow(Double(radix), Double(power))) //} // //class ParserTests: XCTestCase { // // func lex(source: String) -> [Token] { // let lexer = Lexer() // // do { // return try lexer.execute(input: source) // } catch let ex { // print(ex) // } // // return [] // } // // func interpretIntLiteralExpression(expression: Expression) throws -> Int { // if let expr = expression as? BinaryExpression { // let lhs = try interpretIntLiteralExpression(expression: expr.left) // let rhs = try interpretIntLiteralExpression(expression: expr.right) // // switch expr.op { // case Operator.Addition: return lhs + rhs // case Operator.Subtraction: return lhs - rhs // case Operator.Multiplication: return lhs * rhs // case Operator.Division: return lhs / rhs // case Operator.Power: return lhs ** rhs // // default: throw OrbitError.unknownOperator(symbol: expr.op.symbol, position: .Infix, token: Token(type: .Whitespace, value: "")) // } // } else if let expr = expression as? UnaryExpression { // let value = try interpretIntLiteralExpression(expression: expr.value) // // return value * -1 // } else if let expr = expression as? IntLiteralExpression { // return expr.value // } // // XCTFail("Got into a weird state") // // return 0 // } // ((-5) * (7 ** 2)) - 2 + (-4) + 3 // // func testParserNothingToParser() { // let tokens = lex(source: "") // let parser = Parser() // // XCTAssertThrowsError(try parser.execute(input: tokens)) // } // // func testParserConsume() { // let tokens = lex(source: "123 456") // let parser = Parser() // // parser.tokens = tokens // // let token1 = try! parser.consume() // let token2 = try! parser.consume() // // XCTAssertEqual(TokenType.Int, token1.type) // XCTAssertEqual("123", token1.value) // // XCTAssertEqual(TokenType.Int, token2.type) // XCTAssertEqual("456", token2.value) // // // Run out of tokens // XCTAssertThrowsError(try parser.consume()) // } // // func testParserPeek() { // let tokens = lex(source: "123 456") // let parser = Parser() // // parser.tokens = tokens // // let result = try! parser.peek() // // XCTAssertEqual(TokenType.Int, result.type) // XCTAssertEqual("123", result.value) // // parser.tokens = [] // // XCTAssertThrowsError(try parser.peek()) // } // // func testParserExpect() { // let tokens = lex(source: "abc = 123") // let parser = Parser() // // parser.tokens = tokens // // let token1 = try! parser.expect(tokenType: .Identifier) { token in // return token.value == "abc" // } // // XCTAssertEqual(TokenType.Identifier, token1.type) // XCTAssertEqual("abc", token1.value) // // XCTAssertThrowsError(try parser.expect(tokenType: .Int, requirements: { token in // return token.value == "999" // })) // } // // func testParseSimpleAPI() { // let tokens = lex(source: "api Test {}") // let parser = Parser() // // do { // let result = try parser.execute(input: tokens) // // XCTAssertEqual(1, result.body.count) // } catch let ex as OrbitError { // XCTFail(ex.message) // } catch { // XCTFail("Other") // } // } // // func testParseAPIWithSimpleTypeDef() { // let tokens = lex(source: "api Test { type Foo() }") // let parser = Parser() // // do { // let result = try parser.execute(input: tokens) // // XCTAssertEqual(1, result.body.count) // // let api = result.body[0].expression as! APIExpression // // XCTAssertEqual("Test", api.name.value) // // let def = api.body[0] as! TypeDefExpression // // XCTAssertEqual("Foo", def.name.value) // } catch let ex as OrbitError { // XCTFail(ex.message) // } catch let ex { // XCTFail(ex.localizedDescription) // } // } // // func testParseIdentifier() { // let tokens = lex(source: "a") // let parser = Parser() // // parser.tokens = tokens // // let result = try! parser.parseIdentifier() // // XCTAssertEqual("a", result.value) // } // // func testParseTypeIdentifier() { // let tokens = lex(source: "Foo") // let parser = Parser() // // parser.tokens = tokens // // var result = try! parser.parseTypeIdentifier() // // XCTAssertEqual("Foo", result.value) // // parser.tokens = lex(source: "[Bar]") // // result = try! parser.parseTypeIdentifier() // // XCTAssertTrue(result is ListTypeIdentifierExpression) // XCTAssertEqual("Bar", result.value) // // parser.tokens = lex(source: "[Foo::Bar::Baz]") // // result = try! parser.parseTypeIdentifier() // // XCTAssertTrue(result is ListTypeIdentifierExpression) // XCTAssertEqual("Foo.Bar.Baz", result.value) // // // Recursive lists // // parser.tokens = lex(source: "[[[Foo]]]") // // result = try! parser.parseTypeIdentifier() // // XCTAssertTrue(result is ListTypeIdentifierExpression) // XCTAssertTrue((result as! ListTypeIdentifierExpression).elementType is ListTypeIdentifierExpression) // // parser.tokens = lex(source: "Orb::Core::Types::Int") // // result = try! parser.parseTypeIdentifier() // // XCTAssertEqual("Orb.Core.Types.Int", result.value) // } // // func testParseSimpleTypeDef() { // let tokens = lex(source: "type Foo()") // let parser = Parser() // // parser.tokens = tokens // // let result = try! parser.parseTypeDef() // // XCTAssertEqual("Foo", result.name.value) // XCTAssertEqual(1, result.constructorSignatures.count) // XCTAssertEqual(0, result.constructorSignatures[0].parameters.count) // } // // func testParseComplexTypeDef1() { // let tokens = lex(source: "type Foo(x Int, y Real)") // let parser = Parser() // // parser.tokens = tokens // // var result = try! parser.parseTypeDef() // // XCTAssertEqual("Foo", result.name.value) // XCTAssertEqual(2, result.properties.count) // // let p1 = result.properties[0] // let p2 = result.properties[1] // // XCTAssertEqual("x", p1.name.value) // XCTAssertEqual("Int", p1.type.value) // // XCTAssertEqual("y", p2.name.value) // XCTAssertEqual("Real", p2.type.value) // // XCTAssertEqual(1, result.constructorSignatures.count) // XCTAssertEqual(2, result.constructorSignatures[0].parameters.count) // // parser.tokens = lex(source: "type A(x Int) : TraitA") // // result = try! parser.parseTypeDef() // // XCTAssertEqual(1, result.adoptedTraits.count) // // parser.tokens = lex(source: "type A(x Int) : TraitA, TraitB") // // result = try! parser.parseTypeDef() // // XCTAssertEqual(2, result.adoptedTraits.count) // // parser.tokens = lex(source: "type A(x Int) : TraitA, TraitB, TraitC") // // result = try! parser.parseTypeDef() // // XCTAssertEqual(3, result.adoptedTraits.count) // // parser.tokens = lex(source: "type A() : TraitA") // // result = try! parser.parseTypeDef() // // XCTAssertEqual(1, result.adoptedTraits.count) // } // // func testParsePair() { // let tokens = lex(source: "str String") // let parser = Parser() // // parser.tokens = tokens // // var result = try! parser.parsePair() // // XCTAssertEqual("str", result.name.value) // XCTAssertEqual("String", result.type.value) // // parser.tokens = lex(source: "xs [Int]") // // result = try! parser.parsePair() // // XCTAssertEqual("xs", result.name.value) // XCTAssertTrue(result.type is ListTypeIdentifierExpression) // XCTAssertEqual("Int", result.type.value) // } // // func testParsePairs() { // let tokens = lex(source: "str String, i Int, xyz Real") // let parser = Parser() // // parser.tokens = tokens // // var result = try! parser.parsePairs() // // XCTAssertEqual(3, result.count) // // let p1 = result[0] // let p2 = result[1] // let p3 = result[2] // // XCTAssertEqual("str", p1.name.value) // XCTAssertEqual("String", p1.type.value) // // XCTAssertEqual("i", p2.name.value) // XCTAssertEqual("Int", p2.type.value) // // XCTAssertEqual("xyz", p3.name.value) // XCTAssertEqual("Real", p3.type.value) // // parser.tokens = lex(source: "i Int, j Int") // // result = try! parser.parsePairs() // // XCTAssertEqual(2, result.count) // // let p4 = result[0] // let p5 = result[1] // // XCTAssertEqual("i", p4.name.value) // XCTAssertEqual("Int", p4.type.value) // // XCTAssertEqual("j", p5.name.value) // XCTAssertEqual("Int", p5.type.value) // // parser.tokens = lex(source: "str String") // // result = try! parser.parsePairs() // // XCTAssertEqual(1, result.count) // // let p6 = result[0] // // XCTAssertEqual("str", p6.name.value) // XCTAssertEqual("String", p6.type.value) // } // // func testParseIdentifiers() { // let parser = Parser() // // parser.tokens = lex(source: "a, b, cdef") // // var result = try! parser.parseIdentifiers() // // XCTAssertEqual(3, result.count) // // let id1 = result[0] // let id2 = result[1] // let id3 = result[2] // // XCTAssertEqual("a", id1.value) // XCTAssertEqual("b", id2.value) // XCTAssertEqual("cdef", id3.value) // // parser.tokens = lex(source: "a, b") // // result = try! parser.parseIdentifiers() // // XCTAssertEqual(2, result.count) // // let id4 = result[0] // let id5 = result[1] // // XCTAssertEqual("a", id4.value) // XCTAssertEqual("b", id5.value) // // parser.tokens = lex(source: "a") // // result = try! parser.parseIdentifiers() // // XCTAssertEqual(1, result.count) // // let id6 = result[0] // // XCTAssertEqual("a", id6.value) // } // // func testParseTypeIdentifiers() { // let parser = Parser() // // parser.tokens = lex(source: "Int, Real, String") // // var result = try! parser.parseTypeIdentifiers() // // XCTAssertEqual(3, result.count) // // let id1 = result[0] // let id2 = result[1] // let id3 = result[2] // // XCTAssertEqual("Int", id1.value) // XCTAssertEqual("Real", id2.value) // XCTAssertEqual("String", id3.value) // // parser.tokens = lex(source: "Int, Orb::Core::Types::Real") // // result = try! parser.parseTypeIdentifiers() // // XCTAssertEqual(2, result.count) // // let id4 = result[0] // let id5 = result[1] // // XCTAssertEqual("Int", id4.value) // XCTAssertEqual("Orb.Core.Types.Real", id5.value) // // parser.tokens = lex(source: "Int") // // result = try! parser.parseTypeIdentifiers() // // XCTAssertEqual(1, result.count) // // let id6 = result[0] // // XCTAssertEqual("Int", id6.value) // } // // func testParseIdentifierList() { // let parser = Parser() // // parser.tokens = lex(source: "()") // // var result = try! parser.parseIdentifierList() // // XCTAssertEqual(0, result.count) // // parser.tokens = lex(source: "(a)") // // result = try! parser.parseIdentifierList() // // XCTAssertEqual(1, result.count) // // let id1 = result[0] // // XCTAssertEqual("a", id1.value) // // parser.tokens = lex(source: "(a, b)") // // result = try! parser.parseIdentifierList() // // XCTAssertEqual(2, result.count) // // let id2 = result[0] // let id3 = result[1] // // XCTAssertEqual("a", id2.value) // XCTAssertEqual("b", id3.value) // // parser.tokens = lex(source: "(a, b, cdef)") // // result = try! parser.parseIdentifierList() // // XCTAssertEqual(3, result.count) // // let id4 = result[0] // let id5 = result[1] // let id6 = result[2] // // XCTAssertEqual("a", id4.value) // XCTAssertEqual("b", id5.value) // XCTAssertEqual("cdef", id6.value) // } // // func testParseTypeIdentifierList() { // let parser = Parser() // // parser.tokens = lex(source: "()") // // var result = try! parser.parseTypeIdentifierList() // // XCTAssertEqual(0, result.count) // // parser.tokens = lex(source: "(Int)") // // result = try! parser.parseTypeIdentifierList() // // XCTAssertEqual(1, result.count) // // let id1 = result[0] // // XCTAssertEqual("Int", id1.value) // // parser.tokens = lex(source: "(Orb::Core::Int, Real)") // // result = try! parser.parseTypeIdentifierList() // // XCTAssertEqual(2, result.count) // // let id2 = result[0] // let id3 = result[1] // // XCTAssertEqual("Orb.Core.Int", id2.value) // XCTAssertEqual("Real", id3.value) // // parser.tokens = lex(source: "(Int, Real, [String])") // // result = try! parser.parseTypeIdentifierList() // // XCTAssertEqual(3, result.count) // // let id4 = result[0] // let id5 = result[1] // let id6 = result[2] // // XCTAssertEqual("Int", id4.value) // XCTAssertEqual("Real", id5.value) // XCTAssertEqual("String", id6.value) // XCTAssertTrue(id6 is ListTypeIdentifierExpression) // } // // func testOperatorPrecedenceOpposite() { // XCTAssertEqual(OperatorPrecedence.Equal, OperatorPrecedence.Equal.opposite()) // XCTAssertEqual(OperatorPrecedence.Lesser, OperatorPrecedence.Greater.opposite()) // XCTAssertEqual(OperatorPrecedence.Greater, OperatorPrecedence.Lesser.opposite()) // } // // func testOperatorInit() { // let op1 = Operator(symbol: "+", relationships: [:]) // let op2 = Operator(symbol: "-", relationships: [:]) // // XCTAssertNotEqual(op1.hashValue, op2.hashValue) // } // // func testRedclareOperator() { // let op = Operator(symbol: "+") // XCTAssertThrowsError(try Operator.declare(op: op, token: Token(type: .Operator, value: "+"))) // // let before = Operator.operators.count // // let newOp = Operator(symbol: "+++++") // XCTAssertNoThrow(try Operator.declare(op: newOp, token: Token(type: .Operator, value: "+++++"))) // XCTAssertEqual(before + 1, Operator.operators.count) // } // // func testOperatorDefineRelationship() { // let newOp = Operator(symbol: "++") // // try! Operator.Addition.defineRelationship(other: newOp, precedence: .Lesser) // // XCTAssertEqual(OperatorPrecedence.Lesser, Operator.Addition.relationships[newOp]) // // XCTAssertThrowsError(try Operator.Addition.defineRelationship(other: newOp, precedence: .Equal)) // } // // // Debug test for dumping operator precedence //// func testOperatorSort() { //// do { //// try Operator.initialiseBuiltInOperators() //// } catch let ex { //// print(ex) //// } //// } // // func testParsePairList() { // let parser = Parser() // // parser.tokens = lex(source: "()") // // var result = try! parser.parsePairList() // // XCTAssertEqual(0, result.count) // // parser.tokens = lex(source: "(a Int)") // // result = try! parser.parsePairList() // // XCTAssertEqual(1, result.count) // // let id1 = result[0] // // XCTAssertEqual("a", id1.name.value) // XCTAssertEqual("Int", id1.type.value) // // parser.tokens = lex(source: "(a Int, b Real)") // // result = try! parser.parsePairList() // // XCTAssertEqual(2, result.count) // // let id2 = result[0] // let id3 = result[1] // // XCTAssertEqual("a", id2.name.value) // XCTAssertEqual("Int", id2.type.value) // // XCTAssertEqual("b", id3.name.value) // XCTAssertEqual("Real", id3.type.value) // // parser.tokens = lex(source: "(a Int, b Real, cdef String)") // // result = try! parser.parsePairList() // // XCTAssertEqual(3, result.count) // // let id4 = result[0] // let id5 = result[1] // let id6 = result[2] // // XCTAssertEqual("a", id4.name.value) // XCTAssertEqual("Int", id4.type.value) // // XCTAssertEqual("b", id5.name.value) // XCTAssertEqual("Real", id5.type.value) // // XCTAssertEqual("cdef", id6.name.value) // XCTAssertEqual("String", id6.type.value) // } // // func testParseExpression() { // let parser = Parser() // // parser.tokens = lex(source: "-2") // // let unary = try! (parser.parseUnary() as! UnaryExpression) // // XCTAssertEqual("-", unary.op.symbol) // // parser.tokens = lex(source: "a + b") // // var result = try! (parser.parseExpression() as! BinaryExpression) // // XCTAssertEqual("a", (result.left as! IdentifierExpression).value) // XCTAssertEqual("b", (result.right as! IdentifierExpression).value) // // parser.tokens = lex(source: "1 + 2") // // result = try! (parser.parseExpression() as! BinaryExpression) // // XCTAssertEqual(1, (result.left as! IntLiteralExpression).value) // XCTAssertEqual(2, (result.right as! IntLiteralExpression).value) // // parser.tokens = lex(source: "1.2 + 3.44") // // result = try! (parser.parseExpression() as! BinaryExpression) // // XCTAssertEqual(1.2, (result.left as! RealLiteralExpression).value) // XCTAssertEqual(3.44, (result.right as! RealLiteralExpression).value) // //// parser.tokens = lex(source: "-5 * 7 ** 2 - 9 + -4 + 3") //// //// result = try! parser.parseExpression() as! BinaryExpression //// //// XCTAssertTrue(result.left is IntLiteralExpression) //// XCTAssertTrue(result.right is BinaryExpression) //// //// let lhs = result.left as! IntLiteralExpression //// let rhs = result.right as! BinaryExpression //// //// XCTAssertEqual(1, lhs.value) //// XCTAssertEqual(2, (rhs.left as! IntLiteralExpression).value) //// XCTAssertEqual(3, (rhs.right as! IntLiteralExpression).value) // // parser.tokens = lex(source: "(1 * 2) + 3") // // result = try! (parser.parseExpression() as! BinaryExpression) // // XCTAssertTrue(result.left is BinaryExpression) // XCTAssertTrue(result.right is IntLiteralExpression) // // let lhs2 = result.left as! BinaryExpression // let rhs2 = result.right as! IntLiteralExpression // // XCTAssertEqual(1, (lhs2.left as! IntLiteralExpression).value) // XCTAssertEqual(2, (lhs2.right as! IntLiteralExpression).value) // XCTAssertEqual(3, rhs2.value) // // parser.tokens = lex(source: "2 * 3 + 2") // // result = (try! parser.parseExpression() as! BinaryExpression) // // print(result) // // parser.tokens = lex(source: "2") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "2.2") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "a") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2.2)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(a)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "2 + 2") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "2.2 + 2.3") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "a + b") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2 + 2)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2.3 + 2.1)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(abc + xyz)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2 * 3) + (99)") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "(2 * 3 - 2) + (99) * 75 + 9") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "!(10 + -3)") // //XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "-55 - -55") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "2 + 2") // var expr = try! parser.parseExpression() // var value = try! interpretIntLiteralExpression(expression: expr) // XCTAssertEqual(4, value) // // parser.tokens = lex(source: "2 + 2 + 2") // expr = try! parser.parseExpression() // value = try! interpretIntLiteralExpression(expression: expr) // XCTAssertEqual(6, value) // // parser.tokens = lex(source: "4 * 3 + 2") // expr = try! parser.parseExpression() // value = try! interpretIntLiteralExpression(expression: expr) // XCTAssertEqual(14, value) // // parser.tokens = lex(source: "4 * (3 + 2)") // expr = try! parser.parseExpression() // value = try! interpretIntLiteralExpression(expression: expr) // XCTAssertEqual(20, value) // // parser.tokens = lex(source: "-2 * -3") // expr = try! parser.parseExpression() // value = try! interpretIntLiteralExpression(expression: expr) // XCTAssertEqual(6, value) // // parser.tokens = lex(source: "-Int.add(1, 2) * 3") // XCTAssertNoThrow(try parser.parseExpression()) // // parser.tokens = lex(source: "a.b() + c.d()") // result = try! parser.parseExpression() as! BinaryExpression // XCTAssertEqual("(a.b() + c.d())", result.dump()) // // parser.tokens = lex(source: "a.b() + c.d() * xyz.wow(123, 45)") // result = try! parser.parseExpression() as! BinaryExpression // XCTAssertEqual("(a.b() + (c.d() * xyz.wow(123,45)))", result.dump()) // // // BUG //// parser.tokens = lex(source: "-5 * 7 ** 2 - 9 + -4 + 3") //// expr = try! parser.parseExpression() //// value = try! interpretIntLiteralExpression(expression: expr) //// XCTAssertEqual(-255, value) // } // // func testParseListLiteral() { // let parser = Parser() // // parser.tokens = lex(source: "[1, 2, 3]") // // var result = try! parser.parseListLiteral() // // XCTAssertEqual(3, result.value.count) // // parser.tokens = lex(source: "[a, b]") // // result = try! parser.parseListLiteral() // // XCTAssertEqual(2, result.value.count) // // parser.tokens = lex(source: "[(-5 * 3), [a, b, c]]") // // result = try! parser.parseListLiteral() // // XCTAssertEqual(2, result.value.count) // XCTAssertTrue(result.value[0] is BinaryExpression) // XCTAssertTrue(result.value[1] is ListExpression) // // parser.tokens = lex(source: "[]") // // result = try! parser.parseListLiteral() // // XCTAssertEqual(0, result.value.count) // } // // func testParseMapLiteral() { // let parser = Parser() // // parser.tokens = lex(source: "[a: 1, b: 2]") // // var result = try! parser.parseMapLiteral() // // XCTAssertEqual(2, result.value.count) // XCTAssertEqual("a", (result.value[0].value.key as! IdentifierExpression).value) // XCTAssertEqual(1, (result.value[0].value.value as! IntLiteralExpression).value) // XCTAssertEqual("b", (result.value[1].value.key as! IdentifierExpression).value) // XCTAssertEqual(2, (result.value[1].value.value as! IntLiteralExpression).value) // // parser.tokens = lex(source: "[-5: 7 * 2, b: [a: 1]]") // // result = try! parser.parseMapLiteral() // // XCTAssertEqual(2, result.value.count) // XCTAssertTrue(result.value[1].value.value is MapExpression) // } // // func testParseReturn() { // let parser = Parser() // // parser.tokens = lex(source: "return 1") // // let result = try! parser.parseReturn() // // XCTAssertTrue(result.value is IntLiteralExpression) // XCTAssertEqual(1, (result.value as! IntLiteralExpression).value) // } // // func testParseAssignment() { // let parser = Parser() // // parser.tokens = lex(source: "abc = 123") // // var result = try! parser.parseAssignment() // // XCTAssertTrue(result.value is IntLiteralExpression) // XCTAssertEqual(123, (result.value as! IntLiteralExpression).value) // // parser.tokens = lex(source: "x = 1.3") // // result = try! parser.parseAssignment() // // XCTAssertTrue(result.value is RealLiteralExpression) // XCTAssertEqual(1.3, (result.value as! RealLiteralExpression).value) // // parser.tokens = lex(source: "x = a + b") // // result = try! parser.parseAssignment() // // XCTAssertTrue(result.value is BinaryExpression) // XCTAssertTrue((result.value as! BinaryExpression).left is IdentifierExpression) // XCTAssertTrue((result.value as! BinaryExpression).right is IdentifierExpression) // // parser.tokens = lex(source: "x = Int.next(1)") // // result = try! parser.parseAssignment() // // XCTAssertTrue(result.value is StaticCallExpression) // XCTAssertEqual("Int", (result.value as! StaticCallExpression).receiver.value) // XCTAssertEqual("next", (result.value as! StaticCallExpression).methodName.value) // XCTAssertEqual(1, (result.value as! StaticCallExpression).args.count) // } // // func testParseStaticCall() { // let parser = Parser() // // parser.tokens = lex(source: "Int.next()") // // var result = try! parser.parseExpression() as! StaticCallExpression // // XCTAssertEqual("Int", result.receiver.value) // XCTAssertEqual("next", result.methodName.value) // XCTAssertEqual(0, result.args.count) // // parser.tokens = lex(source: "Real.add(2.2, 3.3)") // // result = try! parser.parseExpression() as! StaticCallExpression // // XCTAssertEqual("Real", result.receiver.value) // XCTAssertEqual("add", result.methodName.value) // XCTAssertEqual(2, result.args.count) // // XCTAssertTrue(result.args[0] is RealLiteralExpression) // XCTAssertTrue(result.args[1] is RealLiteralExpression) // // parser.tokens = lex(source: "Real.max(2.2, 3.3, 9.99, 5.123)") // // result = try! parser.parseExpression() as! StaticCallExpression // // XCTAssertEqual("Real", result.receiver.value) // XCTAssertEqual("max", result.methodName.value) // XCTAssertEqual(4, result.args.count) // // XCTAssertTrue(result.args[0] is RealLiteralExpression) // XCTAssertTrue(result.args[1] is RealLiteralExpression) // XCTAssertTrue(result.args[2] is RealLiteralExpression) // XCTAssertTrue(result.args[3] is RealLiteralExpression) // // parser.tokens = lex(source: "Foo.bar(") // // XCTAssertThrowsError(try parser.parseStaticCall()) // // parser.tokens = lex(source: "Real.max(2.2, 3.3, 9.99, 5.123).foo().bar(1).baz(99)") // // let result2 = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("Real.max(2.2,3.3,9.99,5.123).foo().bar(1).baz(99)", result2.dump()) // // // Test constructor calls // parser.tokens = lex(source: "Main(1, 2, 3)") // // result = try! parser.parseExpression() as! StaticCallExpression // // XCTAssertEqual("Main", result.receiver.value) // XCTAssertEqual(3, result.args.count) // // parser.tokens = lex(source: "Main()") // // result = try! parser.parseExpression() as! StaticCallExpression // // XCTAssertEqual("Main", result.receiver.value) // XCTAssertEqual(0, result.args.count) // } // // func testParseInstanceCall() { // let parser = Parser() // // // Test property access // parser.tokens = lex(source: "foo.xyz") // // var acc = try! parser.parseExpression() as! PropertyAccessExpression // // XCTAssertEqual("foo", (acc.receiver as! IdentifierExpression).value) // XCTAssertEqual("xyz", acc.propertyName.value) // // parser.tokens = lex(source: "foo.bar.baz.quux") // // acc = try! parser.parseExpression() as! PropertyAccessExpression // // XCTAssertTrue(acc.receiver is PropertyAccessExpression) // // parser.tokens = lex(source: "foo.bar.baz()") // // let access = try! parser.parseExpression() as! InstanceCallExpression // // XCTAssertTrue(access.receiver is PropertyAccessExpression) // // parser.tokens = lex(source: "foo.bar().baz") // // acc = try! parser.parseExpression() as! PropertyAccessExpression // // XCTAssertTrue(acc.receiver is InstanceCallExpression) // // // Test index access // // parser.tokens = lex(source: "foo.bar()[0]") // // var idx = try! parser.parseExpression() as! IndexAccessExpression // // XCTAssert(idx.receiver is InstanceCallExpression) // XCTAssertEqual(1, idx.indices.count) // // parser.tokens = lex(source: "foo[0, foo[1]]") // // idx = try! parser.parseExpression() as! IndexAccessExpression // // XCTAssertEqual("foo", (idx.receiver as! IdentifierExpression).value) // XCTAssertEqual(0, (idx.indices[0] as! IntLiteralExpression).value) // XCTAssertTrue(idx.indices[1] is IndexAccessExpression) // // parser.tokens = lex(source: "foo.bar()") // // var result = try! parser.parseExpression() as! InstanceCallExpression // // XCTAssertTrue(result.receiver is IdentifierExpression) // XCTAssertEqual("foo", (result.receiver as! IdentifierExpression).value) // XCTAssertEqual("bar", result.methodName.value) // XCTAssertEqual(0, result.args.count) // // parser.tokens = lex(source: "1.add(2, 3, 4, 5)") // // result = try! parser.parseExpression() as! InstanceCallExpression // // XCTAssertTrue(result.receiver is IntLiteralExpression) // XCTAssertEqual(1, (result.receiver as! IntLiteralExpression).value) // XCTAssertEqual("add", result.methodName.value) // XCTAssertEqual(4, result.args.count) // // parser.tokens = lex(source: "1.add(2).add(3)") // // result = try! parser.parseExpression() as! InstanceCallExpression // // XCTAssertTrue(result.receiver is InstanceCallExpression) // // parser.tokens = lex(source: "a.b(1).c().d(2, 3).e().f(a, b)") // result = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("a.b(1).c().d(2,3).e().f(a,b)", result.dump()) // // parser.tokens = lex(source: "[1, 2, 3].insert(4)") // result = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("[1,2,3].insert(4)", result.dump()) // // parser.tokens = lex(source: "[a: 1, b: 2].insert(c, 2)") // result = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("[(a:1),(b:2)].insert(c,2)", result.dump()) // // parser.tokens = lex(source: "a.insert([1, 2, 3])") // result = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("a.insert([1,2,3])", result.dump()) // // parser.tokens = lex(source: "a.insert([abc: 123, def: 456])") // result = try! parser.parseExpression() as! InstanceCallExpression // XCTAssertEqual("a.insert([(abc:123),(def:456)])", result.dump()) // } // // func testParseGenerics() { // let parser = Parser() // // parser.tokens = lex(source: "<>") // // XCTAssertThrowsError(try parser.parseTypeConstraints()) // // parser.tokens = lex(source: "<T>") // // var result = try! parser.parseTypeConstraints() // // XCTAssertEqual(1, result.value.count) // // parser.tokens = lex(source: "<T, U, V>") // // result = try! parser.parseTypeConstraints() // // XCTAssertEqual(3, result.value.count) // } // // func testParseStaticSignature() { // let parser = Parser() // // parser.tokens = lex(source: "(Int) power<T> (x T, y T) (T)") // // var result = try! parser.parseStaticSignature() // // XCTAssertEqual("Int", result.receiverType.value) // XCTAssertEqual("power", result.name.value) // XCTAssertEqual(1, result.genericConstraints!.value.count) // XCTAssertEqual(2, result.parameters.count) // XCTAssertEqual("T", result.returnType!.value) // // parser.tokens = lex(source: "(Int) power (x Int, y Int) (Int)") // // result = try! parser.parseStaticSignature() // // XCTAssertEqual("Int", result.receiverType.value) // XCTAssertEqual("power", result.name.value) // XCTAssertNil(result.genericConstraints) // XCTAssertEqual(2, result.parameters.count) // XCTAssertEqual("Int", result.returnType!.value) // // parser.tokens = lex(source: "(Int) power (x Int, y Int) ()") // // result = try! parser.parseStaticSignature() // // XCTAssertNil(result.returnType) // } // // func testParseInstanceSignature() { // let parser = Parser() // // parser.tokens = lex(source: "(self Int) power<T> (x T, y T) (T)") // // var result = try! parser.parseInstanceSignature() // // XCTAssertEqual("Int", result.receiverType.value) // XCTAssertEqual("power", result.name.value) // XCTAssertEqual(1, result.genericConstraints!.value.count) // XCTAssertEqual(3, result.parameters.count) // XCTAssertEqual("T", result.returnType!.value) // // parser.tokens = lex(source: "(self Int) power (x Int, y Int) (Int)") // // result = try! parser.parseInstanceSignature() // // XCTAssertEqual("Int", result.receiverType.value) // XCTAssertEqual("power", result.name.value) // XCTAssertNil(result.genericConstraints) // XCTAssertEqual(3, result.parameters.count) // XCTAssertEqual("Int", result.returnType!.value) // // parser.tokens = lex(source: "(self Int) power (x Int, y Int) ()") // // result = try! parser.parseInstanceSignature() // // XCTAssertNil(result.returnType) // } // // func testParseMethod() { // let parser = Parser() // // parser.tokens = lex(source: "(self Int) power<T> (x T, y T) (T) {" + // " z = x ** y" + // " return z" + // "}") // // let result = try! parser.parseMethod() as! MethodExpression // // XCTAssertEqual(2, result.body.count) // // parser.tokens = lex(source: "(Int) power<T> (x T, y T) (T) {" + // " z = x ** y" + // " return z" + // "}") // // let result2 = try! parser.parseMethod() as! MethodExpression // // XCTAssertEqual(2, result2.body.count) // } // // func testParseAPI() { // let src = // "api Main within Main " + // "with \"test.orb\" " + // "with \"test2.orb\" {" + // "trait A(x Int) " + // "(Main) main (argc Int8, argv [String]) () {" + // "Main.puti32(argc)" + // "Main.puti32(argv.size())" + // "}" + // "}" // // let parser = Parser() // // parser.tokens = lex(source: src) // // do { // let result = try parser.execute(input: parser.tokens) // // XCTAssertEqual(1, result.body.count) // XCTAssertTrue(result.body[0].expression is APIExpression) // XCTAssertTrue((result.body[0].expression as! APIExpression).body[0] is TraitDefExpression) // XCTAssertTrue((result.body[0].expression as! APIExpression).body[1] is MethodExpression) // XCTAssertTrue((result.body[0].expression as! APIExpression).importPaths.count == 2) // XCTAssertEqual("test.orb", (result.body[0].expression as! APIExpression).importPaths[0].value) // XCTAssertEqual("test2.orb", (result.body[0].expression as! APIExpression).importPaths[1].value) // XCTAssertEqual("Main", (result.body[0].expression as! APIExpression).within!) // } catch let ex as OrbitError { // print(ex.message) // } catch { // // } // } // // func testParseStringLiteral() { // let parser = Parser() // // parser.tokens = lex(source: "\"abc\"") // // do { // var result = try parser.parseStringLiteral() // // XCTAssertEqual("abc", result.value) // // parser.tokens = lex(source: "\"a b c \\(def) 123\"") // // result = try parser.parseStringLiteral() // // XCTAssertEqual("a b c \\(def) 123", result.value) // // parser.tokens = lex(source: "\"Hello, \\u1234\"") // // result = try parser.parseStringLiteral() // // XCTAssertEqual("Hello, \\u1234", result.value) // } catch let ex { // print(ex) // } // } // // func testParseDebug() { // let parser = Parser() // // parser.tokens = lex(source: "debug \"abc\"") // // var result = try! parser.parseDebug() // // XCTAssertTrue(result.debuggable is StringLiteralExpression) // // parser.tokens = lex(source: "debug abc") // // result = try! parser.parseDebug() // // XCTAssertTrue(result.debuggable is IdentifierExpression) // // parser.tokens = lex(source: "debug self.argv[0]") // // result = try! parser.parseDebug() // // XCTAssertTrue(result.debuggable is IndexAccessExpression) // XCTAssertTrue((result.debuggable as! IndexAccessExpression).receiver is PropertyAccessExpression) // // parser.tokens = lex(source: "debug self[0].argv") // // result = try! parser.parseDebug() // // XCTAssertTrue(result.debuggable is PropertyAccessExpression) // XCTAssertTrue((result.debuggable as! PropertyAccessExpression).receiver is IndexAccessExpression) // } // // func testSimpleTraitDef() { // let parser = Parser() // // parser.tokens = lex(source: "trait IntWrapper()") // // var result = try! parser.parseTraitDef() // // XCTAssertEqual("IntWrapper", result.name.value) // XCTAssertEqual(0, result.properties.count) // // parser.tokens = lex(source: "trait IntWrapper(x Int)") // // result = try! parser.parseTraitDef() // // XCTAssertEqual("IntWrapper", result.name.value) // XCTAssertEqual(1, result.properties.count) // } // // func testComplexTraitDef() { // let parser = Parser() // // parser.tokens = lex(source: "trait IntWrapper() { (self Self) foo () () }") // // var result = try! parser.parseTraitDef() // // XCTAssertEqual(1, result.signatures.count) // // parser.tokens = lex(source: // "trait IntWrapper() {" + // " (self Self) foo () () " + // " (self Self) bar (other Self) (Self) " + // " (self Self) baz (x Int, thing Self) (Int) " + // "}" // ) // // result = try! parser.parseTraitDef() // // XCTAssertEqual(3, result.signatures.count) // } //}
mit
886f61257f1ea8ca2a64949e82a9bc98
31.515638
145
0.578958
3.557066
false
false
false
false
shlyren/ONE-Swift
ONE_Swift/Classes/Main-主要/Controller/JENPastListViewController.swift
1
3512
// // JENPastListViewController.swift // ONE_Swift // // Created by 任玉祥 on 16/4/28. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit class JENPastListViewController: UITableViewController { var endMonth = "" var pastLists: [String] { get { return arrayFromStr(endMonth) } } override func viewDidLoad() { super.viewDidLoad() title = "往期列表" } private func arrayFromStr(endDate: String) -> [String] { if !endDate.containsString("-") {return []} let formatter = NSDateFormatter() formatter.dateFormat = "yyyy-MM" var currentDate = formatter.stringFromDate(NSDate()) as NSString let currentYear = currentDate.integerValue let range = currentDate.rangeOfString("-") if range.location != NSNotFound { currentDate = currentDate.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "") } let currentMonth = currentDate.integerValue var endDataStr = endDate as NSString let endYear = endDataStr.integerValue if range.location != NSNotFound { endDataStr = endDataStr.stringByReplacingCharactersInRange(NSMakeRange(0, range.location + range.length), withString: "") } let endMonth = endDataStr.integerValue var maxMonth = 0 var minMonth = 0 var monthArr = [String]() var resYear = currentYear while resYear >= endYear { maxMonth = resYear == currentYear ? currentMonth: 12; minMonth = resYear == endYear ? endMonth: 1; var resMonth = maxMonth while resMonth >= minMonth { monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth])) resMonth -= 1 } resYear -= 1 } // for var resYear = currentYear; resYear >= endYear; resYear -= 1 { // maxMonth = resYear == currentYear ? currentMonth: 12; // minMonth = resYear == endYear ? endMonth: 1; // // for var resMonth = maxMonth; resMonth >= minMonth; resMonth -= 1 { // monthArr.append(String(format: "%zd-%02d", arguments: [resYear, resMonth])) // } // } return monthArr } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { tableView.tableViewWithNoData(nil, rowCount: pastLists.count) return pastLists.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { tableView.tableViewSetExtraCellLineHidden() var cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "reuseIdentifier") } if indexPath.row == 0 { cell?.textLabel?.text = "本月" } else { cell?.textLabel?.text = pastLists[indexPath.row] } return cell! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
4654559f01cde6eb96e38cb93393226c
31.877358
135
0.588235
4.901547
false
false
false
false
LYM-mg/DemoTest
indexView/indexView/One/TableView的头部展开与折叠/View/XJLHeaderFooterView.swift
1
2255
// // XJLHeaderFooterView.swift // OccupationClassify // // Created by i-Techsys.com on 17/3/27. // Copyright © 2017年 MESMKEE. All rights reserved. // import UIKit class XJLHeaderFooterView: UITableViewHeaderFooterView { private lazy var image = UIImageView() private lazy var label = UILabel() var btnBlock: ((_ dict: XJLGroupModel,_ hearderView: XJLHeaderFooterView)->())? // 头部点击回调 // 模型 var gruop: XJLGroupModel? { didSet { if (gruop!.isExpaned) { // 已经展开 image.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)/2); } else { // 未展开 image.transform = CGAffineTransform.identity; } label.text = gruop?.models.first?.industry_name ?? "笨蛋" } } override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setUpUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setUpUI() { self.layoutIfNeeded() contentView.backgroundColor = UIColor.orange.withAlphaComponent(0.7) image = UIImageView(frame: CGRect(x: 10, y: 12, width: 7, height: 10)) image.image = UIImage(named: "xiala") image.center = CGPoint(x: 10, y: 44/2) label = UILabel(frame: CGRect(x: 20, y: 0, width: 300, height: 44)) label.textColor = UIColor.white let btn = UIButton(frame: CGRect(x: 0, y: 0, width: MGScreenW, height: 44)) btn.backgroundColor = UIColor.clear btn.addTarget(self, action: #selector(XJLHeaderFooterView.btnClick(_:)), for: .touchUpInside) self.addSubview(image) self.addSubview(label) self.addSubview(btn) } @objc func btnClick(_ btn: UIButton) { gruop!.isExpaned = !gruop!.isExpaned if (gruop!.isExpaned) { // 已经展开 image.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi)/2) } else { // 未展开 image.transform = CGAffineTransform.identity; } if btnBlock != nil { btnBlock!(gruop!,self) } } }
mit
de3746752caae3a7143b4c98ddbb216c
30.042254
101
0.586661
4.058932
false
false
false
false
magnetsystems/message-samples-ios
Soapbox/Pods/MagnetMaxCore/MagnetMax/Core/Operations/MMReachabilityCondition.swift
7
2277
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: This file shows an example of implementing the OperationCondition protocol. */ import Foundation import AFNetworking /** This is a condition that performs a very high-level reachability check. It does *not* perform a long-running reachability check, nor does it respond to changes in reachability. Reachability is evaluated once when the operation to which this is attached is asked about its readiness. */ public struct MMReachabilityCondition: OperationCondition { static let hostKey = "Host" public static let name = "MMReachability" public static let isMutuallyExclusive = false let reachabilityController: MMReachabilityController public init() { self.reachabilityController = MMReachabilityController() } public func dependencyForOperation(operation: Operation) -> NSOperation? { return nil } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { switch reachabilityController.status { case .ReachableViaWiFi, .ReachableViaWWAN: completion(.Satisfied) NSNotificationCenter.defaultCenter().removeObserver(reachabilityController) default: reachabilityController.completionHandler = completion NSNotificationCenter.defaultCenter().addObserver(reachabilityController, selector: "reachabilityChangeReceived:", name: AFNetworkingReachabilityDidChangeNotification, object: nil) } } } @objc public class MMReachabilityController: NSObject { var completionHandler : (OperationConditionResult -> Void)? var status: AFNetworkReachabilityStatus = AFNetworkReachabilityStatus.Unknown func reachabilityChangeReceived(notification: NSNotification) { let userInfo = notification.userInfo as! [String: NSNumber] let statusNumber = userInfo[AFNetworkingReachabilityNotificationStatusItem] status = AFNetworkReachabilityStatus(rawValue: (statusNumber?.integerValue)!)! if status == .ReachableViaWiFi || status == .ReachableViaWWAN { completionHandler?(.Satisfied) } } }
apache-2.0
b8476db7054eafd7f579adabc09d180a
38.929825
191
0.738462
5.863402
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/FrozenAnimationViewController.swift
1
2943
// // FrozenAnimationViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/20/16. // Copyright © 2016 suzp1984@gmail.com. All rights reserved. // import UIKit class FrozenAnimationViewController: UIViewController { var shape : CAShapeLayer! var v : UIView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white let slide = UISlider() self.view.addSubview(slide) slide.translatesAutoresizingMaskIntoConstraints = false slide.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor, constant: 10).isActive = true slide.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 30).isActive = true slide.widthAnchor.constraint(equalTo: self.view.widthAnchor, constant: -60).isActive = true slide.heightAnchor.constraint(equalToConstant: 20.0).isActive = true slide.addTarget(self, action: #selector(FrozenAnimationViewController.doSlide(_:)), for: .valueChanged) slide.backgroundColor = UIColor.clear slide.minimumValue = 0.0 slide.maximumValue = 1.0 slide.isContinuous = true slide.value = 0 CATransaction.setDisableActions(true) // add view self.v = UIView() self.view.addSubview(v) v.backgroundColor = UIColor.clear v.translatesAutoresizingMaskIntoConstraints = false v.topAnchor.constraint(equalTo: slide.bottomAnchor, constant: 10).isActive = true v.widthAnchor.constraint(equalToConstant: 200).isActive = true v.heightAnchor.constraint(equalToConstant: 200).isActive = true v.centerXAnchor.constraint(equalTo: self.view.centerXAnchor, constant: 0.0).isActive = true // add shape sublayer self.shape = CAShapeLayer() self.v.layer.addSublayer(shape) } override func viewDidLayoutSubviews() { print(self.v.bounds) self.shape.frame = self.v.bounds self.shape.fillColor = UIColor.clear.cgColor self.shape.strokeColor = UIColor.red.cgColor // self.shape.lineWidth = 4.0 let path = CGPath(rect: shape.bounds, transform: nil) self.shape.path = path let path2 = CGPath(ellipseIn: shape.bounds, transform: nil) let ba = CABasicAnimation(keyPath: "path") ba.duration = 1 ba.fromValue = path ba.toValue = path2 shape.speed = 0 shape.timeOffset = 0 shape.add(ba, forKey: nil) shape.opacity = 1.0 } func doSlide(_ sender: UISlider!) { print(sender.value) self.shape.timeOffset = Double(sender.value) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
eeaf4f4739eef57f647b7b51f9adc2a5
32.05618
111
0.638001
4.7072
false
false
false
false
sora0077/NicoKit
NicoKit/src/Endpoint/GetThumbInfo.swift
1
3560
// // GetThumbInfo.swift // NicoKit // // Created by 林達也 on 2015/06/06. // Copyright (c) 2015年 林達也. All rights reserved. // import Foundation import APIKit import Ono import LoggingKit public class GetThumbInfo { public let videos: [String] public init(videos: [String]) { self.videos = videos } } extension GetThumbInfo: RequestToken { public typealias Response = [NicoVideo] public typealias SerializedType = ONOXMLDocument public var method: HTTPMethod { return .GET } public var URL: String { return "http://i.nicovideo.jp/v3/video.array" } public var headers: [String: AnyObject]? { return nil } public var parameters: [String: AnyObject]? { return ["v": videos] } public var encoding: RequestEncoding { return .URL } public var resonseEncoding: ResponseEncoding { return .Custom({ URLRequest, response, data in var error: NSError? let xml = ONOXMLDocument(data: data, error: &error) if let e = error { return (nil, e) } return (xml, nil) }) } } extension GetThumbInfo { public static func transform(request: NSURLRequest, response: NSHTTPURLResponse?, object: SerializedType) -> Result<Response> { let xml = object if "ok" == xml.rootElement["status"] as? NSString { var videos: [NicoVideo] = [] xml.enumerateElementsWithXPath("//video_info") { video, idx, stop in videos.append(NicoVideo.fromXML(video)) } return Result(videos) } else { let description = xml.rootElement.firstChildWithTag("error").firstChildWithTag("description").stringValue() return Result.Failure(error(.ParseError, description)) } } } extension NicoVideo { static func fromXML(xml: ONOXMLElement) -> NicoVideo { let video = xml.firstChildWithTag("video") let id = video.firstChildWithTag("id").stringValue() let user_id = video.firstChildWithTag("user_id").numberValue().integerValue let title = video.firstChildWithTag("title").stringValue() let description = video.firstChildWithTag("description").stringValue() let thumbnail_url = video.firstChildWithTag("thumbnail_url").stringValue() let length_seconds = video.firstChildWithTag("length_in_seconds").numberValue().integerValue let view_counter = video.firstChildWithTag("view_counter").numberValue().integerValue let mylist_counter = video.firstChildWithTag("mylist_counter").numberValue().integerValue let comment_counter = xml.firstChildWithTag("thread").firstChildWithTag("num_res").numberValue().integerValue var tags: [String] = [] let v = NSFastGenerator(xml.XPath("//tags/tag_info/tag")) while let v = v.next() as? ONOXMLElement { tags.append(v.stringValue()) } return self( id: id, user_id: user_id, title: title, description: description, thumbnail_url: thumbnail_url, length_seconds: length_seconds, view_counter: view_counter, mylist_counter: mylist_counter, comment_counter: comment_counter, tags: tags ) } }
mit
9a67eba58b1e130c3c6c06c94bd9b0f7
28.55
131
0.589961
4.605195
false
false
false
false
mightydeveloper/swift
stdlib/public/core/FlatMap.swift
10
2079
//===--- FlatMap.swift ----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension LazySequenceType { /// Returns the concatenated results of mapping `transform` over /// `self`. Equivalent to /// /// self.map(transform).flatten() /// /// - Complexity: O(1) @warn_unused_result public func flatMap<Intermediate: SequenceType>( transform: (Elements.Generator.Element)->Intermediate ) -> LazySequence< FlattenSequence<LazyMapSequence<Elements, Intermediate>>> { return self.map(transform).flatten() } } extension LazyCollectionType { /// Returns the concatenated results of mapping `transform` over /// `self`. Equivalent to /// /// self.map(transform).flatten() /// /// - Complexity: O(1) @warn_unused_result public func flatMap<Intermediate: CollectionType>( transform: (Elements.Generator.Element)->Intermediate ) -> LazyCollection< FlattenCollection< LazyMapCollection<Elements, Intermediate>> > { return self.map(transform).flatten() } } extension LazyCollectionType where Elements.Index : BidirectionalIndexType { /// Returns the concatenated results of mapping `transform` over /// `self`. Equivalent to /// /// self.map(transform).flatten() /// /// - Complexity: O(1) @warn_unused_result public func flatMap< Intermediate: CollectionType where Intermediate.Index : BidirectionalIndexType >( transform: (Elements.Generator.Element)->Intermediate ) -> LazyCollection< FlattenBidirectionalCollection< LazyMapCollection<Elements, Intermediate> >> { return self.map(transform).flatten() } }
apache-2.0
43e5732661c1ef3d89473e9d21415666
30.029851
80
0.650794
4.735763
false
false
false
false
tevelee/CodeGenerator
output/swift/RecordLenses.swift
1
1561
import Foundation extension Record { struct Lenses { static let name: Lens<Record, String> = Lens( get: { $0.name }, set: { (record, name) in var builder = RecordBuilder(existingRecord: record) return builder.withName(name).build() } ) static let creator: Lens<Record, Person> = Lens( get: { $0.creator }, set: { (record, creator) in var builder = RecordBuilder(existingRecord: record) return builder.withCreator(creator).build() } ) static let date: Lens<Record, Date> = Lens( get: { $0.date }, set: { (record, date) in var builder = RecordBuilder(existingRecord: record) return builder.withDate(date).build() } ) } } struct BoundLensToRecord<Whole>: BoundLensType { typealias Part = Record let storage: BoundLensStorage<Whole, Part> var name: BoundLens<Whole, String> { return BoundLens<Whole, String>(parent: self, sublens: Record.Lenses.name) } var creator: BoundLensToPerson<Whole> { return BoundLensToPerson<Whole>(parent: self, sublens: Record.Lenses.creator) } var date: BoundLens<Whole, Date> { return BoundLens<Whole, Date>(parent: self, sublens: Record.Lenses.date) } } extension Record { var lens: BoundLensToRecord<Record> { return BoundLensToRecord<Record>(instance: self, lens: createIdentityLens()) } }
mit
778628fbe3d7204c0b5e59a6e850097d
30.22
85
0.58296
4.107895
false
false
false
false
galacemiguel/bluehacks2017
Project Civ-1/Project Civ/ProjectNameLocationViewCell.swift
1
3607
// // ProjectNameLocationViewCell.swift // Project Civ // // Created by Carlos Arcenas on 2/18/17. // Copyright © 2017 Rogue Three. All rights reserved. // import UIKit import QuartzCore class ProjectNameLocationViewCell: UICollectionViewCell { static let commonInsets = UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15) static let nameFont = UIFont(name: "Tofino-Bold", size: 25)! static let locationFont = UIFont(name: "Tofino-Book", size: 12)! static func cellSize(width: CGFloat, nameString: String, locationString: String) -> CGSize { let nameBounds = TextSize.size(nameString, font: ProjectNameLocationViewCell.nameFont, width: width, insets: UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)) let locationBounds = TextSize.size(locationString, font: ProjectNameLocationViewCell.locationFont, width: width, insets: ProjectNameLocationViewCell.commonInsets) return CGSize(width: width, height: nameBounds.height + locationBounds.height) } lazy var gradientLayer: CAGradientLayer! = { let layer = CAGradientLayer() layer.frame = self.bounds layer.colors = [UIColor.clear.cgColor, UIColor.black.cgColor] layer.locations = [0.6, 1.0] return layer }() let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill // imageView.image = UIImage(named: "Arete.jpg") return imageView }() let nameLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.numberOfLines = 0 label.font = ProjectNameLocationViewCell.nameFont // label.textColor = UIColor(hex6: 0x387780) // label.textColor = UIColor(hex6: 0xE83151) label.textColor = UIColor.white return label }() let locationLabel: UILabel = { let label = UILabel() label.backgroundColor = UIColor.clear label.numberOfLines = 0 label.font = ProjectNameLocationViewCell.locationFont label.textColor = UIColor(hex6: 0xDBD4D3) // label.textColor = UIColor(hex6: 0xE83151) // label.textColor = UIColor.white return label }() override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(imageView) imageView.layer.addSublayer(gradientLayer) contentView.addSubview(nameLabel) contentView.addSubview(locationLabel) clipsToBounds = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() imageView.frame = self.frame let locationLabelRect = TextSize.size(locationLabel.text!, font: ProjectNameLocationViewCell.locationFont, width: frame.width, insets: ProjectNameLocationViewCell.commonInsets) locationLabel.frame = UIEdgeInsetsInsetRect(locationLabelRect, ProjectNameLocationViewCell.commonInsets) locationLabel.frame.origin.y = frame.height - locationLabelRect.size.height let nameLabelRect = TextSize.size(nameLabel.text!, font: ProjectNameLocationViewCell.nameFont, width: frame.width, insets: UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)) nameLabel.frame = UIEdgeInsetsInsetRect(nameLabelRect, UIEdgeInsets(top: 8, left: 15, bottom: 10, right: 15)) nameLabel.frame.origin.y = locationLabel.frame.origin.y - nameLabel.frame.height } }
mit
c9fb4de94e37dfd2eeaafac9467b0d94
38.626374
185
0.673877
4.468401
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/S3Control/S3Control_Paginator.swift
1
9994
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension S3Control { /// Returns a list of the access points currently associated with the specified bucket. You can retrieve up to 1000 access points per call. If the specified bucket has more than 1,000 access points (or the number specified in maxResults, whichever is less), the response will include a continuation token that you can use to list the additional access points. All Amazon S3 on Outposts REST API requests for this action require an additional parameter of outpost-id to be passed with the request and an S3 on Outposts endpoint hostname prefix instead of s3-control. For an example of the request syntax for Amazon S3 on Outposts that uses the S3 on Outposts endpoint hostname prefix and the outpost-id derived using the access point ARN, see the Example section below. The following actions are related to ListAccessPoints: CreateAccessPoint DeleteAccessPoint GetAccessPoint /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listAccessPointsPaginator<Result>( _ input: ListAccessPointsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListAccessPointsResult, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listAccessPoints, tokenKey: \ListAccessPointsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listAccessPointsPaginator( _ input: ListAccessPointsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListAccessPointsResult, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listAccessPoints, tokenKey: \ListAccessPointsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Lists current S3 Batch Operations jobs and jobs that have ended within the last 30 days for the AWS account making the request. For more information, see S3 Batch Operations in the Amazon Simple Storage Service Developer Guide. Related actions include: CreateJob DescribeJob UpdateJobPriority UpdateJobStatus /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listJobsPaginator<Result>( _ input: ListJobsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListJobsResult, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listJobs, tokenKey: \ListJobsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listJobsPaginator( _ input: ListJobsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListJobsResult, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listJobs, tokenKey: \ListJobsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a list of all Outposts buckets in an Outposts that are owned by the authenticated sender of the request. For more information, see Using Amazon S3 on Outposts in the Amazon Simple Storage Service Developer Guide. For an example of the request syntax for Amazon S3 on Outposts that uses the S3 on Outposts endpoint hostname prefix and outpost-id in your API request, see the Example section below. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listRegionalBucketsPaginator<Result>( _ input: ListRegionalBucketsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListRegionalBucketsResult, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listRegionalBuckets, tokenKey: \ListRegionalBucketsResult.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listRegionalBucketsPaginator( _ input: ListRegionalBucketsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListRegionalBucketsResult, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listRegionalBuckets, tokenKey: \ListRegionalBucketsResult.nextToken, on: eventLoop, onPage: onPage ) } } extension S3Control.ListAccessPointsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> S3Control.ListAccessPointsRequest { return .init( accountId: self.accountId, bucket: self.bucket, maxResults: self.maxResults, nextToken: token ) } } extension S3Control.ListJobsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> S3Control.ListJobsRequest { return .init( accountId: self.accountId, jobStatuses: self.jobStatuses, maxResults: self.maxResults, nextToken: token ) } } extension S3Control.ListRegionalBucketsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> S3Control.ListRegionalBucketsRequest { return .init( accountId: self.accountId, maxResults: self.maxResults, nextToken: token, outpostId: self.outpostId ) } }
apache-2.0
03b20da5061dfd405f1925c7631a3932
47.280193
892
0.657895
4.949975
false
false
false
false
zzcgumn/MvvmTouch
MvvmTouch/MvvmTouch/Table/MvvmCellTableViewController.swift
1
1094
// // MvvmTableViewController.swift // MvvmTouch // // Created by Martin Nygren on 06/02/2017. // Copyright © 2017 Martin Nygren. All rights reserved. // import UIKit /** Connects a UITableView with a MvvmTableViewDataSource */ open class MvvmCellModelTableViewController: UIViewController { public let tableView = UITableView() public let dataSource = MvvmUITableViewDataSource(sections: []) open override func awakeFromNib() { super.awakeFromNib() self.view.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false } open override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = dataSource tableView.translatesAutoresizingMaskIntoConstraints = false view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(tableView) view.addConstraints(constraintsForTableView()) } open func constraintsForTableView() -> [NSLayoutConstraint] { return makeFillViewConstraints(subView: tableView) } }
mit
485e2560516a202755050cf55b0705fc
28.540541
67
0.728271
5.384236
false
false
false
false
SmallElephant/FEAlgorithm-Swift
1-SearchForDimension/1-SearchForDimension/SearchDimension.swift
1
1020
// // SearchDimension.swift // 1-SearchForDimension // // Created by keso on 16/6/10. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class SearchDimension: NSObject { func searchNumber(data:Array<AnyObject>,number:NSInteger)->Bool{ if data.count>0 && data[0].count>0 { var row=0 let rows=data[0].count let columns=data.count var column=columns-1 while row<rows && column>=0 { let rightValue=data[row][column] as! NSInteger //存在 if rightValue==number { print("current row:\(row)--current column:\(column)") return true } else if rightValue>number {//数值小于右上角的值,排除一列 column=column-1 } else {//数值大于右上角的值,排除一列 row=row+1 } } } return false; } }
mit
009fba6b1f4cae5dfcb612f1a3548f69
26.342857
73
0.508882
4.29148
false
false
false
false
JosephNK/SwiftyIamport
SwiftyIamportDemo/Controller/Html5InicisViewController.swift
1
3994
// // Html5InicisViewController.swift // SwiftIamport // // Created by JosephNK on 2017. 4. 21.. // Copyright © 2017년 JosephNK. All rights reserved. // import UIKit import SwiftyIamport class Html5InicisViewController: UIViewController { lazy var webView: UIWebView = { var view = UIWebView() view.backgroundColor = UIColor.clear view.delegate = self return view }() override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(webView) self.webView.frame = self.view.bounds // 결제 환경 설정 IAMPortPay.sharedInstance.configure(scheme: "iamporttest", // info.plist에 설정한 scheme storeIdentifier: "imp68124833") // iamport 에서 부여받은 가맹점 식별코드 IAMPortPay.sharedInstance .setPGType(.html5_inicis) // PG사 타입 .setIdName(nil) // 상점아이디 ({PG사명}.{상점아이디}으로 생성시 사용) .setPayMethod(.card) // 결제 형식 .setWebView(self.webView) // 현재 Controller에 있는 WebView 지정 .setRedirectUrl(nil) // m_redirect_url 주소 // 결제 정보 데이타 let parameters: IAMPortParameters = [ "merchant_uid": String(format: "merchant_%@", String(Int(NSDate().timeIntervalSince1970 * 1000))), "name": "결제테스트", "amount": "1004", "buyer_email": "iamport@siot.do", "buyer_name": "구매자", "buyer_tel": "010-1234-5678", "buyer_addr": "서울특별시 강남구 삼성동", "buyer_postcode": "123-456", "custom_data": ["A1": 123, "B1": "Hello"] //"custom_data": "24" ] IAMPortPay.sharedInstance.setParameters(parameters).commit() // 결제 웹페이지(Local) 파일 호출 if let url = IAMPortPay.sharedInstance.urlFromLocalHtmlFile() { let request = URLRequest(url: url) self.webView.loadRequest(request) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension Html5InicisViewController: UIWebViewDelegate { func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool { // 해당 함수는 redirecURL의 결과를 직접 처리하고 할 때 사용하는 함수 (IAMPortPay.sharedInstance.configure m_redirect_url 값을 설정해야함.) IAMPortPay.sharedInstance.requestRedirectUrl(for: request, parser: { (data, response, error) -> Any? in // Background Thread var resultData: [String: Any]? if let httpResponse = response as? HTTPURLResponse { let statusCode = httpResponse.statusCode switch statusCode { case 200: resultData = [ "isSuccess": "OK" ] break default: break } } return resultData }) { (pasingData) in // Main Thread } return IAMPortPay.sharedInstance.requestAction(for: request) } func webViewDidFinishLoad(_ webView: UIWebView) { // 결제 환경으로 설정에 의한 웹페이지(Local) 호출 결과 IAMPortPay.sharedInstance.requestIAMPortPayWebViewDidFinishLoad(webView) { (error) in if error != nil { switch error! { case .custom(let reason): print("error: \(reason)") break } }else { print("OK") } } } }
mit
9635d8e13744a6a28feb9ef56a06cc3e
33.95283
131
0.529555
4.328271
false
false
false
false
kzaher/RxSwift
RxCocoa/Traits/Signal/Signal+Subscription.swift
2
5589
// // Signal+Subscription.swift // RxCocoa // // Created by Krunoslav Zaher on 9/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import RxSwift import RxRelay extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter to: Observers that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func emit<Observer: ObserverType>(to observers: Observer...) -> Disposable where Observer.Element == Element { return self.asSharedSequence() .asObservable() .subscribe { event in observers.forEach { $0.on(event) } } } /** Creates new subscription and sends elements to observer. In this form it's equivalent to `subscribe` method, but it communicates intent better. - parameter to: Observers that receives events. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public func emit<Observer: ObserverType>(to observers: Observer...) -> Disposable where Observer.Element == Element? { return self.asSharedSequence() .asObservable() .map { $0 as Element? } .subscribe { event in observers.forEach { $0.on(event) } } } /** Creates new subscription and sends elements to `BehaviorRelay`. - parameter to: Target relays for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: BehaviorRelay<Element>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Creates new subscription and sends elements to `BehaviorRelay`. - parameter to: Target relays for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: BehaviorRelay<Element?>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Creates new subscription and sends elements to `PublishRelay`. - parameter to: Target relays for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: PublishRelay<Element>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Creates new subscription and sends elements to `PublishRelay`. - parameter to: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: PublishRelay<Element?>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Creates new subscription and sends elements to `ReplayRelay`. - parameter to: Target relays for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: ReplayRelay<Element>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Creates new subscription and sends elements to `ReplayRelay`. - parameter to: Target relay for sequence elements. - returns: Disposable object that can be used to unsubscribe the observer from the relay. */ public func emit(to relays: ReplayRelay<Element?>...) -> Disposable { return self.emit(onNext: { e in relays.forEach { $0.accept(e) } }) } /** Subscribes an element handler, a completion handler and disposed handler to an observable sequence. Error callback is not exposed because `Signal` can't error out. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. gracefully completed, errored, or if the generation is canceled by disposing subscription) - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription) - returns: Subscription object used to unsubscribe from the observable sequence. */ public func emit(onNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) } /** Subscribes to this `Signal` with a no-op. This method can be only called from `MainThread`. - note: This is an alias of `emit(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 - returns: Subscription object used to unsubscribe from the observable sequence. */ public func emit() -> Disposable { emit(onNext: nil, onCompleted: nil, onDisposed: nil) } }
mit
998e714088b9155d0779b4730d7bd42a
38.076923
164
0.651396
4.83391
false
false
false
false
AlanJN/TextFieldEffects
TextFieldEffects/TextFieldEffects/HoshiTextField.swift
1
5922
// // HoshiTextField.swift // TextFieldEffects // // Created by Raúl Riera on 24/01/2015. // Copyright (c) 2015 Raul Riera. All rights reserved. // import UIKit @IBDesignable public class HoshiTextField: TextFieldEffects { @IBInspectable dynamic public var borderInactiveColor: UIColor? { didSet { updateBorder() } } @IBInspectable dynamic public var borderActiveColor: UIColor? { didSet { updateBorder() } } @IBInspectable dynamic public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { updateBorder() updatePlaceholder() } } private let borderThickness: (active: CGFloat, inactive: CGFloat) = (active: 2, inactive: 0.5) private let placeholderInsets = CGPoint(x: 0, y: 6) private let textFieldInsets = CGPoint(x: 0, y: 12) private let inactiveBorderLayer = CALayer() private let activeBorderLayer = CALayer() private var inactivePlaceholderPoint: CGPoint = CGPointZero private var activePlaceholderPoint: CGPoint = CGPointZero // MARK: - TextFieldsEffectsProtocol override public func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font!) updateBorder() updatePlaceholder() layer.addSublayer(inactiveBorderLayer) layer.addSublayer(activeBorderLayer) addSubview(placeholderLabel) inactivePlaceholderPoint = placeholderLabel.frame.origin activePlaceholderPoint = CGPoint(x: placeholderLabel.frame.origin.x, y: placeholderLabel.frame.origin.y - placeholderLabel.frame.size.height - placeholderInsets.y) } private func updateBorder() { inactiveBorderLayer.frame = rectForBorder(borderThickness.inactive, isFilled: true) inactiveBorderLayer.backgroundColor = borderInactiveColor?.CGColor activeBorderLayer.frame = rectForBorder(borderThickness.active, isFilled: false) activeBorderLayer.backgroundColor = borderActiveColor?.CGColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor placeholderLabel.sizeToFit() layoutPlaceholderInTextRect() if isFirstResponder() || text!.isNotEmpty { animateViewsForTextEntry() } } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.65) return smallerFont } private func rectForBorder(thickness: CGFloat, isFilled: Bool) -> CGRect { if isFilled { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: CGRectGetWidth(frame), height: thickness)) } else { return CGRect(origin: CGPoint(x: 0, y: CGRectGetHeight(frame)-thickness), size: CGSize(width: 0, height: thickness)) } } private func layoutPlaceholderInTextRect() { let textRect = textRectForBounds(bounds) var originX = textRect.origin.x switch self.textAlignment { case .Center: originX += textRect.size.width/2 - placeholderLabel.bounds.width/2 case .Right: originX += textRect.size.width - placeholderLabel.bounds.width default: break } placeholderLabel.frame = CGRect(x: originX, y: textRect.height/2, width: placeholderLabel.bounds.width, height: placeholderLabel.bounds.height) } override public func animateViewsForTextEntry() { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.0, options: .BeginFromCurrentState, animations: ({ if self.text!.isEmpty { self.placeholderLabel.frame.origin = CGPoint(x: 10, y: self.placeholderLabel.frame.origin.y) self.placeholderLabel.alpha = 0 } }), completion: { (completed) in self.layoutPlaceholderInTextRect() self.placeholderLabel.frame.origin = self.activePlaceholderPoint UIView.animateWithDuration(0.2, animations: { self.placeholderLabel.alpha = 0.5 }) }) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: true) } override public func animateViewsForTextDisplay() { if text!.isEmpty { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ [unowned self] in self.layoutPlaceholderInTextRect() self.placeholderLabel.alpha = 1 }), completion: nil) self.activeBorderLayer.frame = self.rectForBorder(self.borderThickness.active, isFilled: false) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { return CGRectOffset(bounds, textFieldInsets.x, textFieldInsets.y) } }
mit
54a06bc96874c8bfaa4f31da624e44bf
36.245283
201
0.638912
5.372958
false
false
false
false
mspvirajpatel/SwiftyBase
SwiftyBase/Classes/Extensions/TimerExtension.swift
1
1741
// // NSTimerExtension.swift // Pods // // Created by MacMini-2 on 11/09/17. // // import Foundation // MARK: - Timer Extension - private class NSTimerActor { var block: () -> () init(_ block: @escaping () -> ()) { self.block = block } @objc func fire() { block() } } public extension Timer { class func new(after interval: TimeInterval, _ block: @escaping () -> ()) -> Timer { let actor = NSTimerActor(block) return self.init(timeInterval: interval, target: actor, selector: #selector(NSTimerActor.fire), userInfo: nil, repeats: false) } class func new(every interval: TimeInterval, _ block: @escaping () -> ()) -> Timer { let actor = NSTimerActor(block) return self.init(timeInterval: interval, target: actor, selector: #selector(NSTimerActor.fire), userInfo: nil, repeats: true) } class func after(interval: TimeInterval, _ block: @escaping () -> ()) -> Timer { let timer = Timer.new(after: interval, block) RunLoop.current.add(timer, forMode: RunLoop.Mode.default) return timer } class func every(interval: TimeInterval, _ block: @escaping () -> ()) -> Timer { let timer = Timer.new(every: interval, block) RunLoop.current.add(timer, forMode: RunLoop.Mode.default) return timer } } //Use //NSTimer.after(1.minute) { // println("Are you still here?") //} // //// Repeating an action //NSTimer.every(0.7.seconds) { // statusItem.blink() //} // //// Pass a method reference instead of a closure //NSTimer.every(30.seconds, align) // //// Make a timer object without scheduling //let timer = NSTimer.new(every: 1.second) { // println(self.status) //}
mit
fc061ef034f6a88c706638a0a0231460
25.784615
134
0.615164
3.80131
false
false
false
false
brentdax/swift
stdlib/public/core/ShadowProtocols.swift
2
6096
//===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===// // // 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 // //===----------------------------------------------------------------------===// // // To implement bridging, the core standard library needs to interact // a little bit with Cocoa. Because we want to keep the core // decoupled from the Foundation module, we can't use foundation // classes such as NSArray directly. We _can_, however, use an @objc // protocols whose API is "layout-compatible" with that of NSArray, // and use unsafe casts to treat NSArray instances as instances of // that protocol. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims @objc public protocol _ShadowProtocol {} /// A shadow for the `NSFastEnumeration` protocol. @objc public protocol _NSFastEnumeration : _ShadowProtocol { @objc(countByEnumeratingWithState:objects:count:) func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int } /// A shadow for the `NSEnumerator` class. @objc public protocol _NSEnumerator : _ShadowProtocol { init() func nextObject() -> AnyObject? } /// A token that can be used for `NSZone*`. public typealias _SwiftNSZone = OpaquePointer /// A shadow for the `NSCopying` protocol. @objc public protocol _NSCopying : _ShadowProtocol { @objc(copyWithZone:) func copy(with zone: _SwiftNSZone?) -> AnyObject } /// A shadow for the "core operations" of NSArray. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSArray` subclass. @unsafe_no_objc_tagged_pointer @objc public protocol _NSArrayCore : _NSCopying, _NSFastEnumeration { @objc(objectAtIndex:) func objectAt(_ index: Int) -> AnyObject func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange) @objc(countByEnumeratingWithState:objects:count:) override func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int var count: Int { get } } /// A shadow for the "core operations" of NSDictionary. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSDictionary` subclass. @objc public protocol _NSDictionaryCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSDictionary subclass. // The designated initializer of `NSDictionary`. init( objects: UnsafePointer<AnyObject?>, forKeys: UnsafeRawPointer, count: Int) var count: Int { get } @objc(objectForKey:) func object(forKey aKey: AnyObject) -> AnyObject? func keyEnumerator() -> _NSEnumerator // We also override the following methods for efficiency. @objc(copyWithZone:) override func copy(with zone: _SwiftNSZone?) -> AnyObject @objc(getObjects:andKeys:count:) func getObjects( _ objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>?, count: Int ) @objc(countByEnumeratingWithState:objects:count:) override func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int } /// A shadow for the API of `NSDictionary` we will use in the core /// stdlib. /// /// `NSDictionary` operations, in addition to those on /// `_NSDictionaryCore`, that we need to use from the core stdlib. /// Distinct from `_NSDictionaryCore` because we don't want to be /// forced to implement operations that `NSDictionary` already /// supplies. @unsafe_no_objc_tagged_pointer @objc public protocol _NSDictionary : _NSDictionaryCore { // Note! This API's type is different from what is imported by the clang // importer. override func getObjects( _ objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>?, count: Int) } /// A shadow for the "core operations" of NSSet. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSSet` subclass. @objc public protocol _NSSetCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSSet subclass. // The designated initializer of `NSSet`. init(objects: UnsafePointer<AnyObject?>, count: Int) var count: Int { get } func member(_ object: AnyObject) -> AnyObject? func objectEnumerator() -> _NSEnumerator // We also override the following methods for efficiency. @objc(copyWithZone:) override func copy(with zone: _SwiftNSZone?) -> AnyObject @objc(countByEnumeratingWithState:objects:count:) override func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int } /// A shadow for the API of NSSet we will use in the core /// stdlib. /// /// `NSSet` operations, in addition to those on /// `_NSSetCore`, that we need to use from the core stdlib. /// Distinct from `_NSSetCore` because we don't want to be /// forced to implement operations that `NSSet` already /// supplies. @unsafe_no_objc_tagged_pointer @objc public protocol _NSSet : _NSSetCore { } /// A shadow for the API of NSNumber we will use in the core /// stdlib. @objc public protocol _NSNumber { var doubleValue: Double { get } var floatValue: Float { get } var unsignedLongLongValue: UInt64 { get } var longLongValue: Int64 { get } var objCType: UnsafePointer<Int8> { get } } #else public protocol _NSArrayCore {} public protocol _NSDictionaryCore {} public protocol _NSSetCore {} #endif
apache-2.0
86a91793fbcaf667aed7965e8f85bbfb
29.944162
80
0.709154
4.505543
false
false
false
false
february29/Learning
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Enumerated.swift
38
1934
// // Enumerated.swift // RxSwift // // Created by Krunoslav Zaher on 8/6/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Enumerates the elements of an observable sequence. - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) - returns: An observable sequence that contains tuples of source sequence elements and their indexes. */ public func enumerated() -> Observable<(index: Int, element: E)> { return Enumerated(source: self.asObservable()) } } final fileprivate class EnumeratedSink<Element, O : ObserverType>: Sink<O>, ObserverType where O.E == (index: Int, element: Element) { typealias E = Element var index = 0 func on(_ event: Event<Element>) { switch event { case .next(let value): do { let nextIndex = try incrementChecked(&index) let next = (index: nextIndex, element: value) forwardOn(.next(next)) } catch let e { forwardOn(.error(e)) dispose() } case .completed: forwardOn(.completed) dispose() case .error(let error): forwardOn(.error(error)) dispose() } } } final fileprivate class Enumerated<Element> : Producer<(index: Int, element: Element)> { private let _source: Observable<Element> init(source: Observable<Element>) { _source = source } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == (index: Int, element: Element) { let sink = EnumeratedSink<Element, O>(observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
51e23da7fea0858335dfbf4b29d0f82d
30.177419
167
0.604242
4.516355
false
false
false
false
codefellows/sea-b23-iOS
HashTable.playground/section-1.swift
1
1724
// Playground - noun: a place where people can play import UIKit class HashTable { var size : Int var hashArray = [HashBucket]() var count = 0 init(size : Int) { self.size = size for i in 0..<size { var bucket = HashBucket() self.hashArray.append(bucket) } } func hash(key : String) -> Int { var total = 0 for character in key.unicodeScalars { var asc = Int(character.value) total += asc } return total % self.size } func setObject(objectToStore : AnyObject, forKey key : String) { var index = self.hash(key) var bucket = HashBucket() bucket.key = key bucket.value = objectToStore bucket.next = self.hashArray[index] self.hashArray[index] = bucket self.count++ } func removeObjectForKey(key : String) { var index = self.hash(key) var previousBucket : HashBucket? var bucket : HashBucket? = self.hashArray[index] while bucket != nil { if bucket!.key == key { var nextBucket = bucket?.next //self.hashArray[index] ?? bucket?.next! self.hashArray[index] = bucket!.next! bucket = self.hashArray[index].next } else { previousBucket!.next = bucket?.next } self.count-- return } } } class HashBucket { var next : HashBucket? var value : AnyObject? var key : String? }
mit
6f3f167c2a01a30d892ad942bc8d70d6
19.771084
68
0.483759
4.684783
false
false
false
false
Stitch7/Instapod
Instapod/Extensions/UIViewController+loadingHUD.swift
1
768
// // UIViewController+loadingHUD.swift // Instapod // // Created by Christopher Reitz on 06.03.16. // Copyright © 2016 Christopher Reitz. All rights reserved. // import UIKit import PKHUD extension UIViewController { func loadingHUD(show: Bool, dimsBackground: Bool = false) { if show { UIApplication.shared.isNetworkActivityIndicatorVisible = true PKHUD.sharedHUD.dimsBackground = dimsBackground PKHUD.sharedHUD.userInteractionOnUnderlyingViewsEnabled = !dimsBackground HUD.show(.progress) } else { UIApplication.shared.isNetworkActivityIndicatorVisible = false HUD.hide(animated: true) } } func errorHUD() { HUD.show(.error) } }
mit
2d8eb3b5b07dc7cf58fe1f5258f14fed
25.448276
85
0.65189
4.620482
false
false
false
false
AlesTsurko/DNMKit
DNM_iOS/DNM_iOS/SubdivisionGraphic.swift
1
2475
// // SubdivisionGraphic.swift // denm_view // // Created by James Bean on 8/19/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit public class SubdivisionGraphic: CAShapeLayer, BuildPattern { public var x: CGFloat = 0 public var top: CGFloat = 0 public var height: CGFloat = 0 public var width: CGFloat { get { return 0.382 * height } } public var stemDirection: StemDirection = .Down public var amountBeams: Int = 0 public var hasBeenBuilt: Bool = false public init( x: CGFloat, top: CGFloat, height: CGFloat, stemDirection: StemDirection, amountBeams: Int ) { self.x = x self.top = top self.height = height self.stemDirection = stemDirection self.amountBeams = amountBeams super.init() build() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public func build() { setFrame() path = makePath() setVisualAttributes() hasBeenBuilt = true } private func makePath() -> CGPath { let path = UIBezierPath() addStemToPath(path) addBeamsToPath(path) return path.CGPath } private func addStemToPath(path: UIBezierPath) { let stemWidth = 0.0382 * height let x = stemDirection == .Down ? 0 : width - stemWidth let stem = UIBezierPath(rect: CGRectMake(x, 0, stemWidth, height)) path.appendPath(stem) } private func addBeamsToPath(path: UIBezierPath) { let beamWidth = (0.25 - (0.0382 * CGFloat(amountBeams))) * height let beamΔY = (0.382 - (0.0382 * CGFloat(amountBeams))) * height let beamsInitY = stemDirection == .Down ? 0 : height - beamWidth for b in 0..<amountBeams { let y = stemDirection == .Down ? beamsInitY + CGFloat(b) * beamΔY : beamsInitY - CGFloat(b) * beamΔY let beam = UIBezierPath(rect: CGRectMake(0, y, width, beamWidth)) path.appendPath(beam) } } private func setVisualAttributes() { fillColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor lineWidth = 0 backgroundColor = DNMColorManager.backgroundColor.CGColor } private func setFrame() { frame = CGRectMake(x - 0.5 * width, top, width, height) } }
gpl-2.0
21baab51c9960fdbc9994e87505fbfc2
28.070588
82
0.594091
4.173986
false
false
false
false
IBM-Swift/Swift-cfenv
Sources/CloudFoundryEnv/AppEnv.swift
1
10196
/** * Copyright IBM Corporation 2016,2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import Configuration import LoggerAPI extension ConfigurationManager { public var isLocal: Bool { let vcapApplication = self["VCAP_APPLICATION"] return (vcapApplication == nil) } public var app: [String : Any] { let app = self["VCAP_APPLICATION"] as? [String : Any] ?? self["vcap:application"] as? [String : Any] ?? [:] return app } public var port: Int { if let portString: String = self["PORT"] as? String ?? self["CF_INSTANCE_PORT"] as? String ?? self["VCAP_APP_PORT"] as? String { if let port = Int(portString) { return port } } return self["PORT"] as? Int ?? 8080 } public var name: String? { let name: String? = self["name"] as? String ?? app["name"] as? String // TODO: Add logic for parsing manifest.yml to get name // https://github.com/behrang/YamlSwift // http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file return name } public var bind: String { let bind = app["host"] as? String ?? "0.0.0.0" return bind } public var urls: [String] { var uris: [String] = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris") if isLocal { uris = ["localhost:\(port)"] } else { if uris.count == 0 { uris = ["localhost"] } } let scheme: String = self["protocol"] as? String ?? (isLocal ? "http" : "https") var urls: [String] = [] for uri in uris { urls.append("\(scheme)://\(uri)") } return urls } public var url: String { let url = urls[0] return url } public var services: [String : Any] { let services = self["VCAP_SERVICES"] as? [String : Any] ?? self["vcap:services"] as? [String : Any] ?? [:] return services } /** * Returns an App object. */ public func getApp() -> App? { // Get limits let limits: App.Limits if let limitsMap = app["limits"] as? [String : Int], let memory = limitsMap["mem"], let disk = limitsMap["disk"], let fds = limitsMap["fds"] { limits = App.Limits(memory: memory, disk: disk, fds: fds) } else { return nil } // Get uris let uris = JSONUtils.convertJSONArrayToStringArray(json: app, fieldName: "uris") // Create DateUtils instance let dateUtils = DateUtils() // App instance should only be created if all required variables exist let appObj = App.Builder() .setId(id: app["application_id"] as? String) .setName(name: app["application_name"] as? String) .setUris(uris: uris) .setVersion(version: app["version"] as? String) .setInstanceId(instanceId: app["instance_id"] as? String) .setInstanceIndex(instanceIndex: app["instance_index"] as? Int) .setLimits(limits: limits) .setPort(port: app["port"] as? Int) .setSpaceId(spaceId: app["space_id"] as? String) .setStartedAt(startedAt: dateUtils.convertStringToNSDate(dateString: app["started_at"] as? String)) .build() return appObj } /** * Returns all services bound to the application in a dictionary. The key in * the dictionary is the name of the service, while the value is a Service * object that contains all the properties for the service. */ public func getServices() -> [String:Service] { var results: [String:Service] = [:] for (_, servs) in services { if let servsArray = servs as? [[String:Any]] { for serv in servsArray { // A service must have a name and a label let tags = JSONUtils.convertJSONArrayToStringArray(json: serv, fieldName: "tags") let credentials: [String:Any]? = serv["credentials"] as? [String:Any] if let name: String = serv["name"] as? String, let service = Service.Builder() .setName(name: serv["name"] as? String) .setLabel(label: serv["label"] as? String) .setTags(tags: tags) .setPlan(plan: serv["plan"] as? String) .setCredentials(credentials: credentials) .build() { results[name] = service } } } } return results } /** * Returns an array of Service objects that match the specified type. If there are * no services that match the type parameter, this method returns an empty array. */ public func getServices(type: String) -> [Service] { if let servs = services[type] as? [[String:Any]] { return parseServices(servs: servs) } else { let filteredServs = Array(services.filterWithRegex(regex: type).values) .map { (array: Any) -> [String:Any] in if let array = array as? [Any] { for innerArray in array { if let dict = innerArray as? [String:Any] { return dict } } } return [:] } .filter{ (dict: [String:Any]) -> Bool in dict.count > 0 } return parseServices(servs: filteredServs) } } /** * Returns a Service object with the properties for the specified Cloud Foundry * service. The spec parameter should be the name of the service * or a regex to look up the service. If there is no service that matches the * spec parameter, this method returns nil. */ public func getService(spec: String) -> Service? { let services = getServices() if let service = services[spec] { return service } do { let regex = try NSRegularExpression(pattern: spec, options: NSRegularExpression.Options.caseInsensitive) for (name, serv) in services { let numberOfMatches = regex.numberOfMatches(in: name, options: [], range: NSMakeRange(0, String(describing: name).count)) if numberOfMatches > 0 { return serv } } } catch { Log.error("Error code: \(error)") } return nil } /** * Returns a URL generated from VCAP_SERVICES for the specified service or nil * if service is not found. The spec parameter should be the name of the * service or a regex to look up the service. * * The replacements parameter is a JSON object with the properties found in * Foundation's URLComponents class. */ public func getServiceURL(spec: String, replacements: [String:Any]?) -> String? { var substitutions: [String:Any] = replacements ?? [:] let service = getService(spec: spec) guard let credentials = service?.credentials else { return nil } guard let url: String = credentials[substitutions["url"] as? String ?? "url"] as? String ?? credentials["uri"] as? String else { return nil } substitutions["url"] = nil guard var parsedURL = URLComponents(string: url) else { return nil } // Set replacements in a predefined order // Before, we were just iterating over the keys in the JSON object, // but unfortunately the order of the keys returned were different on // OS X and Linux, which resulted in different outcomes. if let user = substitutions["user"] as? String { parsedURL.user = user } if let password = substitutions["password"] as? String { parsedURL.password = password } if let port = substitutions["port"] as? Int { parsedURL.port = port } if let host = substitutions["host"] as? String { parsedURL.host = host } if let scheme = substitutions["scheme"] as? String { parsedURL.scheme = scheme } if let query = substitutions["query"] as? String { parsedURL.query = query } if let queryItems = substitutions["queryItems"] as? [[String:Any]] { var urlQueryItems: [URLQueryItem] = [] for queryItem in queryItems { if let name = queryItem["name"] as? String { let urlQueryItem = URLQueryItem(name: name, value: queryItem["value"] as? String) urlQueryItems.append(urlQueryItem) } } if urlQueryItems.count > 0 { parsedURL.queryItems = urlQueryItems } } // These are being ignored at the moment // if let fragment = substitutions["fragment"].string { // parsedURL.fragment = fragment // } // if let path = substitutions["path"].string { // parsedURL.path = path // } return parsedURL.string } /** * Returns a JSON object that contains the credentials for the specified * Cloud Foundry service. The spec parameter should be the name of the service * or a regex to look up the service. If there is no service that matches the * spec parameter, this method returns nil. In the case there is no credentials * property for the specified service, an empty JSON is returned. */ public func getServiceCreds(spec: String) -> [String:Any]? { guard let service = getService(spec: spec) else { return nil } if let credentials = service.credentials { return credentials } else { return [:] } } private func parseServices(servs: [[String:Any]]) -> [Service] { let results = servs.map { (serv) -> Service? in let tags = JSONUtils.convertJSONArrayToStringArray(json: serv, fieldName: "tags") let credentials: [String:Any]? = serv["credentials"] as? [String:Any] let service = Service.Builder() .setName(name: serv["name"] as? String) .setLabel(label: serv["label"] as? String) .setTags(tags: tags) .setPlan(plan: serv["plan"] as? String) .setCredentials(credentials: credentials) .build() return service } print("results: \(results)") #if swift(>=4.1) return results.compactMap { $0 } #else return results.flatMap { $0 } #endif } }
apache-2.0
3f5c82045b559eef61670949c265dbe2
32.211726
132
0.632405
4.025266
false
false
false
false
zmeyc/GRDB.swift
Tests/GRDBTests/FoundationNSDataTests.swift
1
1475
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif class FoundationNSDataTests: GRDBTestCase { func testDatabaseValueCanNotStoreEmptyData() { // SQLite can't store zero-length blob. let databaseValue = NSData().databaseValue XCTAssertEqual(databaseValue, DatabaseValue.null) } func testNSDataDatabaseValueRoundTrip() { func roundTrip(_ value: NSData) -> Bool { let databaseValue = value.databaseValue guard let back = NSData.fromDatabaseValue(databaseValue) else { XCTFail("Failed to convert from DatabaseValue to NSData") return false } return back == value } XCTAssertTrue(roundTrip(NSData(data: "bar".data(using: .utf8)!))) } func testNSDataFromDatabaseValueFailure() { let databaseValue_Null = DatabaseValue.null let databaseValue_Int64 = Int64(1).databaseValue let databaseValue_Double = Double(100000.1).databaseValue let databaseValue_String = "foo".databaseValue XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Null)) XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Int64)) XCTAssertNil(NSData.fromDatabaseValue(databaseValue_Double)) XCTAssertNil(NSData.fromDatabaseValue(databaseValue_String)) } }
mit
f46bed2f34a84fd632548edef4d6ec59
32.522727
73
0.664407
5.524345
false
true
false
false
CD1212/Doughnut
Doughnut/Preference/PrefLibraryViewController.swift
1
2628
/* * Doughnut Podcast Client * Copyright (C) 2017 Chris Dyer * * 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 Cocoa import MASPreferences @objcMembers class PrefLibraryViewController: NSViewController { static func instantiate() -> PrefLibraryViewController { let storyboard = NSStoryboard(name: NSStoryboard.Name(rawValue: "Preferences"), bundle: nil) return storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("PrefLibraryViewController")) as! PrefLibraryViewController } var viewIdentifier: String = "PrefLibraryViewController" var toolbarItemImage: NSImage { get { return NSImage(named: NSImage.Name(rawValue: "PrefLibrary"))! } } var toolbarItemLabel: String? { get { view.layoutSubtreeIfNeeded() return " Library " } } override func viewDidAppear() { super.viewDidAppear() calculateLibrarySize() } var hasResizableWidth: Bool = false var hasResizableHeight: Bool = false @IBOutlet weak var librarySizeTxt: NSTextField! func calculateLibrarySize() { if let librarySize = Storage.librarySize() { librarySizeTxt.stringValue = librarySize } } @IBAction func changeLibraryLocation(_ sender: Any) { let panel = NSOpenPanel() panel.canChooseDirectories = true panel.canChooseFiles = false panel.allowsMultipleSelection = false if panel.runModal() == .OK { if let url = panel.url { Preference.set(url, for: Preference.Key.libraryPath) let alert = NSAlert() alert.addButton(withTitle: "Ok") alert.messageText = "Doughnut Will Restart" alert.informativeText = "Please relaunch Doughnut in order to use the new library location" alert.runModal() exit(0) } } } @IBAction func revealLibraryFinder(_ sender: Any) { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: Preference.url(for: Preference.Key.libraryPath)?.path ?? "~") } }
gpl-3.0
035da270d02d732d80cae9a30d2f6ee7
29.917647
148
0.701294
4.53886
false
false
false
false
apple/swift
stdlib/private/OSLog/OSLogIntegerTypes.swift
5
9996
//===----------------- OSLogIntegerTypes.swift ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This file defines extensions for interpolating integer expressions into an // OSLogMessage. It defines `appendInterpolation` functions for standard integer // types. It also defines extensions for serializing integer types into the // argument buffer passed to os_log ABIs. // // The `appendInterpolation` functions defined in this file accept formatting, // privacy and alignment options along with the interpolated expression as // shown below: // // 1. "\(x, format: .hex, privacy: .private, align: .right\)" // 2. "\(x, format: .hex(minDigits: 10), align: .right(columns: 10)\)" import ObjectiveC extension OSLogInterpolation { /// Defines interpolation for expressions of type Int. /// /// Do not call this function directly. It will be called automatically when interpolating /// a value of type `Int` in the string interpolations passed to the log APIs. /// /// - Parameters: /// - number: The interpolated expression of type Int, which is autoclosured. /// - format: A formatting option available for integer types, defined by the /// type: `OSLogIntegerFormatting`. The default is `.decimal`. /// - align: Left or right alignment with the minimum number of columns as /// defined by the type `OSLogStringAlignment`. /// - privacy: A privacy qualifier which is either private or public. /// It is auto-inferred by default. @_semantics("constant_evaluable") @inlinable @_optimize(none) @_semantics("oslog.requires_constant_arguments") public mutating func appendInterpolation( _ number: @autoclosure @escaping () -> Int, format: OSLogIntegerFormatting = .decimal, align: OSLogStringAlignment = .none, privacy: OSLogPrivacy = .auto ) { appendInteger(number, format: format, align: align, privacy: privacy) } // Define appendInterpolation overloads for fixed-size integers. @_semantics("constant_evaluable") @inlinable @_optimize(none) @_semantics("oslog.requires_constant_arguments") public mutating func appendInterpolation( _ number: @autoclosure @escaping () -> Int32, format: OSLogIntegerFormatting = .decimal, align: OSLogStringAlignment = .none, privacy: OSLogPrivacy = .auto ) { appendInteger(number, format: format, align: align, privacy: privacy) } /// Defines interpolation for expressions of type UInt. /// /// Do not call this function directly. It will be called automatically when interpolating /// a value of type `Int` in the string interpolations passed to the log APIs. /// /// - Parameters: /// - number: The interpolated expression of type UInt, which is autoclosured. /// - format: A formatting option available for integer types, defined by the /// type `OSLogIntegerFormatting`. /// - align: Left or right alignment with the minimum number of columns as /// defined by the type `OSLogStringAlignment`. /// - privacy: A privacy qualifier which is either private or public. /// It is auto-inferred by default. @_semantics("constant_evaluable") @inlinable @_optimize(none) @_semantics("oslog.requires_constant_arguments") public mutating func appendInterpolation( _ number: @autoclosure @escaping () -> UInt, format: OSLogIntegerFormatting = .decimal, align: OSLogStringAlignment = .none, privacy: OSLogPrivacy = .auto ) { appendInteger(number, format: format, align: align, privacy: privacy) } /// Given an integer, create and append a format specifier for the integer to the /// format string property. Also, append the integer along with necessary headers /// to the OSLogArguments property. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func appendInteger<T>( _ number: @escaping () -> T, format: OSLogIntegerFormatting, align: OSLogStringAlignment, privacy: OSLogPrivacy ) where T: FixedWidthInteger { guard argumentCount < maxOSLogArgumentCount else { return } formatString += format.formatSpecifier(for: T.self, align: align, privacy: privacy) // If minimum column width is specified, append this value first. Note that // the format specifier would use a '*' for width e.g. %*d. if let minColumns = align.minimumColumnWidth { appendAlignmentArgument(minColumns) } // If the privacy has a mask, append the mask argument, which is a constant payload. // Note that this should come after the width but before the precision. if privacy.hasMask { appendMaskArgument(privacy) } // If minimum number of digits (precision) is specified, append the // precision before the argument. Note that the format specifier would use // a '*' for precision: %.*d. if let minDigits = format.minDigits { appendPrecisionArgument(minDigits) } // Append the integer. addIntHeaders(privacy, sizeForEncoding(T.self)) arguments.append(number) argumentCount += 1 } /// Update preamble and append argument headers based on the parameters of /// the interpolation. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func addIntHeaders( _ privacy: OSLogPrivacy, _ byteCount: Int ) { // Append argument header. let argumentHeader = getArgumentHeader(privacy: privacy, type: .scalar) arguments.append(argumentHeader) // Append number of bytes needed to serialize the argument. arguments.append(UInt8(byteCount)) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += byteCount + 2 preamble = getUpdatedPreamble(privacy: privacy, isScalar: true) } // Append argument indicating precision or width of a format specifier to the buffer. // These specify the value of the '*' in a format specifier like: %*.*ld. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func appendPrecisionArgument(_ count: @escaping () -> Int) { appendPrecisionAlignCount( count, getArgumentHeader(privacy: .auto, type: .count)) } @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func appendAlignmentArgument(_ count: @escaping () -> Int) { appendPrecisionAlignCount( count, getArgumentHeader(privacy: .auto, type: .scalar)) } // This is made transparent to minimize compile time overheads. The function's // implementation also uses literals whenever possible for the same reason. @_transparent @inlinable internal mutating func appendPrecisionAlignCount( _ count: @escaping () -> Int, _ argumentHeader: UInt8 ) { arguments.append(argumentHeader) // Append number of bytes needed to serialize the argument. arguments.append(4) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += 6 // The count is expected to be a CInt. arguments.append({ CInt(count()) }) argumentCount += 1 // Note that we don't have to update the preamble here. } @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func appendMaskArgument(_ privacy: OSLogPrivacy) { arguments.append(getArgumentHeader(privacy: .auto, type: .mask)) // Append number of bytes needed to serialize the mask. Mask is 64 bit payload. arguments.append(8) // Increment total byte size by the number of bytes needed for this // argument, which is the sum of the byte size of the argument and // two bytes needed for the headers. totalBytesForSerializingArguments += 10 // Append the mask value. This is a compile-time constant. let maskValue = privacy.maskValue arguments.append({ maskValue }) argumentCount += 1 // Note that we don't have to update the preamble here. } } extension OSLogArguments { /// Append an (autoclosured) interpolated expression of integer type, passed to /// `OSLogMessage.appendInterpolation`, to the array of closures tracked /// by this instance. @_semantics("constant_evaluable") @inlinable @_optimize(none) internal mutating func append<T>( _ value: @escaping () -> T ) where T: FixedWidthInteger { argumentClosures.append({ (position, _, _) in serialize(value(), at: &position) }) } } /// Return the number of bytes needed for serializing an integer argument as /// specified by os_log. This function must be constant evaluable. Note that /// it is marked transparent instead of @inline(__always) as it is used in /// optimize(none) functions. @_transparent @_alwaysEmitIntoClient internal func sizeForEncoding<T>( _ type: T.Type ) -> Int where T : FixedWidthInteger { return type.bitWidth &>> logBitsPerByte } /// Serialize an integer at the buffer location that `position` points to and /// increment `position` by the byte size of `T`. @_alwaysEmitIntoClient @inline(__always) internal func serialize<T>( _ value: T, at bufferPosition: inout ByteBufferPointer ) where T : FixedWidthInteger { let byteCount = sizeForEncoding(T.self) let dest = UnsafeMutableRawBufferPointer(start: bufferPosition, count: byteCount) withUnsafeBytes(of: value) { dest.copyMemory(from: $0) } bufferPosition += byteCount }
apache-2.0
d3078e9e269ef4f920cc24c4beaf0de8
37.152672
92
0.70078
4.502703
false
false
false
false
inamiy/RxAutomaton
Tests/RxAutomatonTests/EffectMappingLatestSpec.swift
1
3257
// // StrategyLatestSpec.swift // RxAutomaton // // Created by Yasuhiro Inami on 2016-08-15. // Copyright © 2016 Yasuhiro Inami. All rights reserved. // import RxSwift import RxAutomaton import Quick import Nimble /// EffectMapping tests with `strategy = .latest`. class EffectMappingLatestSpec: QuickSpec { override func spec() { typealias Automaton = RxAutomaton.Automaton<AuthState, AuthInput> typealias EffectMapping = Automaton.EffectMapping let (signal, observer) = Observable<AuthInput>.pipe() var automaton: Automaton? var lastReply: Reply<AuthState, AuthInput>? describe("strategy = `.latest`") { var testScheduler: TestScheduler! beforeEach { testScheduler = TestScheduler() /// Sends `.loginOK` after delay, simulating async work during `.loggingIn`. let loginOKProducer = Observable.just(AuthInput.loginOK) .delay(1, onScheduler: testScheduler) /// Sends `.logoutOK` after delay, simulating async work during `.loggingOut`. let logoutOKProducer = Observable.just(AuthInput.logoutOK) .delay(1, onScheduler: testScheduler) let mappings: [Automaton.EffectMapping] = [ .login | .loggedOut => .loggingIn | loginOKProducer, .loginOK | .loggingIn => .loggedIn | .empty(), .logout | .loggedIn => .loggingOut | logoutOKProducer, .logoutOK | .loggingOut => .loggedOut | .empty(), ] // strategy = `.latest` automaton = Automaton(state: .loggedOut, input: signal, mapping: reduce(mappings), strategy: .latest) automaton?.replies.observeValues { reply in lastReply = reply } lastReply = nil } it("`strategy = .latest` should not interrupt inner effects when transition fails") { expect(automaton?.state.value) == .loggedOut expect(lastReply).to(beNil()) observer.send(next: .login) expect(lastReply?.input) == .login expect(lastReply?.fromState) == .loggedOut expect(lastReply?.toState) == .loggingIn expect(automaton?.state.value) == .loggingIn testScheduler.advanceByInterval(0.1) // fails (`loginOKProducer` will not be interrupted) observer.send(next: .login) expect(lastReply?.input) == .login expect(lastReply?.fromState) == .loggingIn expect(lastReply?.toState).to(beNil()) expect(automaton?.state.value) == .loggingIn // `loginOKProducer` will automatically send `.loginOK` testScheduler.advanceByInterval(1) expect(lastReply?.input) == .loginOK expect(lastReply?.fromState) == .loggingIn expect(lastReply?.toState) == .loggedIn expect(automaton?.state.value) == .loggedIn } } } }
mit
005f8ded33ea404d98e306bc181676a0
34.010753
117
0.555283
5.285714
false
true
false
false
LeeShiYoung/LSYWeibo
LSYWeiBo/Main/MainViewController.swift
1
3081
// // MainViewController.swift // LSYWeiBo // // Created by 李世洋 on 16/5/1. // Copyright © 2016年 李世洋. All rights reserved. // import UIKit import SVProgressHUD class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //添加子视图 addChildViewControllers() } @objc private func sendMessage() { // 判断是否登录 let login = UserAccount.userLogin() if !login { SVProgressHUD.showInfoWithStatus("登陆后才可发送微博") SVProgressHUD.setDefaultStyle(.Dark) SVProgressHUD.setDefaultMaskType(.Clear) return } let smVC = "EmojiViewController".storyBoard() self.presentViewController(smVC, animated: true, completion: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tabBar.addSubview(midBth) let w = LSYStruct.screen_w / CGFloat(viewControllers!.count) midBth.frame = CGRectOffset(CGRect(x: 0, y: 0, width: w, height: 49), 2 * w, 0) midBth.addTarget(self, action: #selector(MainViewController.sendMessage), forControlEvents: UIControlEvents.TouchUpInside) } private func addChildViewControllers() { let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil) let data = NSData(contentsOfFile: path!) do { let jsonArr = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) for dict in jsonArr as! [[String: String]] { addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } } catch { print(error) addChildViewController("HomeTableViewController", title: "首页", imageName: "tabbar_home") addChildViewController("MessageTableViewController", title: "消息", imageName: "tabbar_message_center") addChildViewController("DiscoverTableViewController", title: "广场", imageName: "tabbar_discover") addChildViewController("DiscoverTableViewController", title: "我", imageName: "tabbar_profile") } } private func addChildViewController(clildControllerName: String, title: String, imageName: String) { let vc = UIStoryboard(name: clildControllerName, bundle: nil).instantiateInitialViewController() vc?.tabBarItem.image = UIImage(named: imageName) vc?.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") vc?.title = title addChildViewController(vc!) } // MARK: - 懒加载 中间 加号 按钮 private lazy var midBth: UIButton = { let btn = NSBundle.mainBundle().loadNibNamed("MiddleButton", owner: self, options: nil).last as! UIButton return btn }() }
artistic-2.0
3de25f7b2c6312681ecc1cf2447ad070
33.022727
130
0.622578
5.179931
false
false
false
false
S-Shimotori/Chalcedony
Chalcedony/Chalcedony/CCDStayLaboDataProcessor.swift
1
6664
// // CCDStayLaboDataProcessor.swift // Chalcedony // // Created by S-Shimotori on 6/28/15. // Copyright (c) 2015 S-Shimotori. All rights reserved. // import UIKit class CCDStayLaboDataProcessor { private let stayLaboDataList: [CCDStayLaboData] private let dateFormatter = NSDateFormatter() private let calendar = NSCalendar.currentCalendar() private let unitFlags: NSCalendarUnit = .CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitWeekday | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond init(stayLaboDataList: [CCDStayLaboData]) { self.stayLaboDataList = stayLaboDataList } func processStayLaboData() -> CCDCalculatedData { var numberByWeekday = [Int](count: 7, repeatedValue: 0) var numberByMonth = [Int](count: 12, repeatedValue: 0) var totalByWeekday = [Double](count: 7, repeatedValue: 0) var totalByMonth = [Double](count: 12, repeatedValue: 0) var sortedStayLaboDataList = stayLaboDataList sortedStayLaboDataList.sort(<) var lastLaboridaDate: NSDate? for stayLaboData in sortedStayLaboDataList { //らぼりだ時間が前データらぼりだ時間と同じかそれより前なら if let lastLaboridaDate = lastLaboridaDate where stayLaboData.laboridaDate.compare(lastLaboridaDate) != .OrderedDescending { continue } //らぼいん時間が前データらぼりだ時間より前なら let laboridaDate = stayLaboData.laboridaDate let laboinDate: NSDate if let lastLaboridaDate = lastLaboridaDate where stayLaboData.laboinDate.compare(lastLaboridaDate) == .OrderedAscending { laboinDate = lastLaboridaDate } else { laboinDate = stayLaboData.laboinDate } //もし前データが存在するなら if let lastLaboridaDate = lastLaboridaDate { //前データらぼりだの翌日の日付を取得 var components = calendar.components(unitFlags, fromDate: lastLaboridaDate) components.day++ var dayAfterLastLaboridaDate = calendar.dateFromComponents(components)! //同じ日になるまでカウント while dayAfterLastLaboridaDate.isAscendingWithoutTime(laboinDate) { //曜日カウント numberByWeekday[dayAfterLastLaboridaDate.date().weekday.hashValue]++ //月代わりに月カウント if dayAfterLastLaboridaDate.date().day == 1 { numberByMonth[dayAfterLastLaboridaDate.date().month.hashValue]++ } //次の日へ components = calendar.components(unitFlags, fromDate: dayAfterLastLaboridaDate) components.day++ dayAfterLastLaboridaDate = calendar.dateFromComponents(components)! } } else { //月母数カウント if laboinDate.date().day != 1 { numberByMonth[laboinDate.date().month.hashValue]++ } } //らぼいんとりだが同じ日 if laboinDate.isEqualWithoutTime(laboridaDate) { let howManySecondsStay = laboridaDate.timeIntervalSinceDate(laboinDate) totalByWeekday[laboinDate.date().weekday.hashValue] += howManySecondsStay totalByMonth[laboinDate.date().month.hashValue] += howManySecondsStay if let lastLaboridaDate = lastLaboridaDate where !laboinDate.isEqualWithoutTime(lastLaboridaDate) { numberByWeekday[laboinDate.date().weekday.hashValue]++ if laboinDate.date().day == 1 { numberByMonth[laboinDate.date().month.hashValue]++ } } else if lastLaboridaDate == nil { numberByWeekday[laboinDate.date().weekday.hashValue]++ if laboinDate.date().day == 1 { numberByMonth[laboinDate.date().month.hashValue]++ } } } else { //翌日の日付午前0時 var components = calendar.components(unitFlags, fromDate: laboinDate) components.day++ components.hour = 0 components.minute = 0 components.second = 0 var date0 = laboinDate var date1 = calendar.dateFromComponents(components)! //終了日になるまでカウント while !date1.isDescendingWithoutTime(laboridaDate) { let howManySecondsStay = date1.timeIntervalSinceDate(date0) totalByWeekday[date0.date().weekday.hashValue] += howManySecondsStay if let lastLaboridaDate = lastLaboridaDate where !date0.isEqualWithoutTime(lastLaboridaDate) { numberByWeekday[date0.date().weekday.hashValue]++ } else if lastLaboridaDate == nil { numberByWeekday[date0.date().weekday.hashValue]++ } totalByMonth[date0.date().month.hashValue] += howManySecondsStay if date0.date().day == 1 { numberByMonth[date0.date().month.hashValue]++ } components = calendar.components(unitFlags, fromDate: date1) components.day++ components.hour = 0 components.minute = 0 components.second = 0 date0 = date1 date1 = calendar.dateFromComponents(components)! } //終了日の時刻計算 let howManySecondsStay = laboridaDate.timeIntervalSinceDate(date0) totalByWeekday[laboridaDate.date().weekday.hashValue] += howManySecondsStay numberByWeekday[laboridaDate.date().weekday.hashValue]++ totalByMonth[laboridaDate.date().month.hashValue] += howManySecondsStay if laboridaDate.date().day == 1 { numberByMonth[laboridaDate.date().month.hashValue]++ } } lastLaboridaDate = laboridaDate } return CCDCalculatedData(numberByWeekday: numberByWeekday, numberByMonth: numberByMonth, totalByWeekday: totalByWeekday, totalByMonth: totalByMonth) } }
mit
d92635ca17fe82fbae75f4afa4ed4ab8
45.007246
156
0.584909
4.464135
false
false
false
false
nmdias/FeedKit
Sources/FeedKit/Models/Namespaces/Media/MediaScene.swift
2
2362
// // MediaScene.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // 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 /// Optional element to specify various scenes within a media object. It can /// have multiple child <media:scene> elements, where each <media:scene> /// element contains information about a particular scene. <media:scene> has /// the optional sub-elements <sceneTitle>, <sceneDescription>, /// <sceneStartTime> and <sceneEndTime>, which contains title, description, /// start and end time of a particular scene in the media, respectively. public class MediaScene { /// The scene's title. public var sceneTitle: String? /// The scene's description. public var sceneDescription: String? /// The scene's start time. public var sceneStartTime: TimeInterval? /// The scene's end time. public var sceneEndTime: TimeInterval? public init() { } } // MARK: - Equatable extension MediaScene: Equatable { public static func ==(lhs: MediaScene, rhs: MediaScene) -> Bool { return lhs.sceneTitle == rhs.sceneTitle && lhs.sceneDescription == rhs.sceneDescription && lhs.sceneStartTime == rhs.sceneStartTime && lhs.sceneEndTime == rhs.sceneEndTime } }
mit
2eef63678258400c4331dc5bb3c464b6
36.492063
82
0.706181
4.43152
false
false
false
false
PANDA-Guide/PandaGuideApp
Carthage/Checkouts/facebook-sdk-swift/Sources/Core/AppEvents/AppEventsLogger.swift
1
9114
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved. // // You are hereby granted a non-exclusive, worldwide, royalty-free license to use, // copy, modify, and distribute this software in source code or binary form for use // in connection with the web services and APIs provided by Facebook. // // As with any software that integrates with the Facebook platform, your use of // this software is subject to the Facebook Developer Principles and Policies // [http://developers.facebook.com/policy/]. This copyright 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 FBSDKCoreKit.FBSDKAppEvents /** Client-side event logging for specialized application analytics available through Facebook App Insights and for use with Facebook Ads conversion tracking and optimization. The `AppEventsLogger` static class has a few related roles: + Logging predefined and application-defined events to Facebook App Insights with a numeric value to sum across a large number of events, and an optional set of key/value parameters that define "segments" for this event (e.g., 'purchaserStatus' : 'frequent', or 'gamerLevel' : 'intermediate') + Logging events to later be used for ads optimization around lifetime value. + Methods that control the way in which events are flushed out to the Facebook servers. Here are some important characteristics of the logging mechanism provided by `AppEventsLogger`: + Events are not sent immediately when logged. They're cached and flushed out to the Facebook servers in a number of situations: - when an event count threshold is passed (currently 100 logged events). - when a time threshold is passed (currently 15 seconds). - when an app has gone to background and is then brought back to the foreground. + Events will be accumulated when the app is in a disconnected state, and sent when the connection is restored and one of the above 'flush' conditions are met. + The `AppEventsLogger` class is thread-safe in that events may be logged from any of the app's threads. + The developer can set the `flushBehavior` to force the flushing of events to only occur on an explicit call to the `flush` method. + The developer can turn on console debug output for event logging and flushing to the server by using the `FBSDKLoggingBehaviorAppEvents` value in `[FBSettings setLoggingBehavior:]`. Some things to note when logging events: + There is a limit on the number of unique event names an app can use, on the order of 1000. + There is a limit to the number of unique parameter names in the provided parameters that can be used per event, on the order of 25. This is not just for an individual call, but for all invocations for that eventName. + Event names and parameter names (the keys in the Dictionary) must be between 2 and 40 characters, and must consist of alphanumeric characters, _, -, or spaces. + The length of each parameter value can be no more than on the order of 100 characters. */ public class AppEventsLogger { //-------------------------------------- // MARK: - Activate //-------------------------------------- /** Notifies the events system that the app has launched and, when appropriate, logs an "activated app" event. Should typically be placed in the app delegates' `applicationDidBecomeActive()` function. This method also takes care of logging the event indicating the first time this app has been launched, which, among other things, is used to track user acquisition and app install ads conversions. `activate()` will not log an event on every app launch, since launches happen every time the app is backgrounded and then foregrounded. "activated app" events will be logged when the app has not been active for more than 60 seconds. This method also causes a "deactivated app" event to be logged when sessions are "completed", and these events are logged with the session length, with an indication of how much time has elapsed between sessions, and with the number of background/foreground interruptions that session had. This data is all visible in your app's App Events Insights. - parameter application: Optional instance of UIApplication. Default: `UIApplication.sharedApplication()`. */ public static func activate(_ application: UIApplication = UIApplication.shared) { FBSDKAppEvents.activateApp() } //-------------------------------------- // MARK: - Log Events //-------------------------------------- /** Log an app event. - parameter event: The application event to log. - parameter accessToken: Optional access token to use to log the event. Default: `AccessToken.current`. */ public static func log(_ event: AppEventLoggable, accessToken: AccessToken? = AccessToken.current) { let valueToSum = event.valueToSum.map({ NSNumber(value: $0 as Double) }) let parameters = event.parameters.keyValueMap { ($0.0.rawValue as NSString, $0.1.appEventParameterValue) } FBSDKAppEvents.logEvent(event.name.rawValue, valueToSum: valueToSum, parameters: parameters, accessToken: accessToken?.sdkAccessTokenRepresentation) } /** Log an app event. This overload is required, so dot-syntax works in this example: ``` AppEventsLogger().log(.Searched()) ``` - parameter event: The application event to log. - parameter accessToken: Optional access token to use to log the event. Default: `AccessToken.current`. */ public static func log(_ event: AppEvent, accessToken: AccessToken? = AccessToken.current) { log(event as AppEventLoggable, accessToken: accessToken) } /** Log an app event. - parameter eventName: The name of the event to record. - parameter parameters: Arbitrary parameter dictionary of characteristics. - parameter valueToSum: Amount to be aggregated into all events of this eventName, and App Insights will report the cumulative and average value of this amount. - parameter accessToken: The optional access token to log the event as. Default: `AccessToken.current`. */ public static func log(_ eventName: String, parameters: AppEvent.ParametersDictionary = [:], valueToSum: Double? = nil, accessToken: AccessToken? = AccessToken.current) { let event = AppEvent(name: AppEventName(eventName), parameters: parameters, valueToSum: valueToSum) log(event, accessToken: accessToken) } //-------------------------------------- // MARK: - Push Notifications //-------------------------------------- /** Sets a device token to register the current application installation for push notifications. */ public static var pushNotificationsDeviceToken: Data? { didSet{ FBSDKAppEvents.setPushNotificationsDeviceToken(pushNotificationsDeviceToken) } } //-------------------------------------- // MARK: - Flush //-------------------------------------- /** The current event flushing behavior specifying when events are sent to Facebook. */ public static var flushBehavior: FlushBehavior { get { return FlushBehavior(sdkFlushBehavior: FBSDKAppEvents.flushBehavior()) } set { FBSDKAppEvents.setFlushBehavior(newValue.sdkFlushBehavior) } } /** Explicitly kick off flushing of events to Facebook. This is an asynchronous method, but it does initiate an immediate kick off. Server failures will be reported through the NotificationCenter with notification ID `FBSDKAppEventsLoggingResultNotification`. */ public static func flush() { FBSDKAppEvents.flush() } //-------------------------------------- // MARK: - Override App Id //-------------------------------------- /** Facebook application id that is going to be used for logging all app events. In some cases, you might want to use one Facebook App ID for login and social presence and another for App Event logging. (An example is if multiple apps from the same company share an app ID for login, but want distinct logging.) By default, this value defers to the `FBSDKAppEventsOverrideAppIDBundleKey` plist value. If that's not set, it defaults to `FBSDKSettings.appId`. */ public static var loggingAppId: String? { get { if let appId = FBSDKAppEvents.loggingOverrideAppID() { return appId } return FBSDKSettings.appID() } set { return FBSDKAppEvents.setLoggingOverrideAppID(newValue) } } }
gpl-3.0
1aae5d54d6eaa8f4fcebeda09403c4c7
43.676471
139
0.701448
4.955954
false
false
false
false
kagemiku/ios-clean-architecture-sample
ios-clean-architecture-sample/Application/Network/APIClient.swift
1
2125
// // APIClient.swift // ios-clean-architecture-sample // // Created by KAGE on 1/16/17. // Copyright © 2017 KAGE. All rights reserved. // import Foundation import Alamofire import ObjectMapper public enum Result<T> { case success(T) case error(Error) } public protocol Routable { var urlString: String { get } var parameters: Parameters { get } } open class APIClient { typealias CompletionHandler<T> = (Result<T>) -> Void class func request<T: Mappable>(url: URLConvertible, method: Alamofire.HTTPMethod, parameters: Parameters? = nil, headers: HTTPHeaders? = nil, completionHandler: CompletionHandler<T>? = nil) { Alamofire.request(url, method: method, parameters: parameters, headers: headers) .validate() .responseJSON { response in switch response.result { case .success(let value): if let entity = Mapper<T>().map(JSONObject: value) { completionHandler?(Result<T>.success(entity)) } case .failure(let error): completionHandler?(Result<T>.error(error)) } } } class func requestRawString(url: URLConvertible, method: Alamofire.HTTPMethod, parameters: Parameters? = nil, headers: HTTPHeaders? = nil, completionHandler: CompletionHandler<String>? = nil) { Alamofire.request(url, method: method, parameters: parameters, headers: headers) .validate() .responseString { response in switch response.result { case .success(let value): completionHandler?(Result<String>.success(value)) case .failure(let error): completionHandler?(Result<String>.error(error)) } } } }
mit
69569104e29a25b8e4f61fae031c7c0d
33.258065
88
0.522128
5.363636
false
false
false
false
iOSDevLog/iOSDevLog
MyLocations/MyLocations/Location.swift
1
1764
// // Location.swift // MyLocations // // Created by iosdevlog on 16/2/16. // Copyright © 2016年 iosdevlog. All rights reserved. // import Foundation import CoreData import MapKit @objc(Location) class Location: NSManagedObject, MKAnnotation { // MARK: - MKAnnotation var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake(latitude, longitude) } var title: String? { if locationDescription.isEmpty { return "(No Description)" } else { return locationDescription } } var subtitle: String? { return category } var hasPhoto: Bool { return photoID != nil } var photoPath: String { assert(photoID != nil, "No photo ID set") let filename = "Photo-\(photoID!.integerValue).jpg" return (applicationDocumentsDirectory as NSString).stringByAppendingPathComponent(filename) } var photoImage: UIImage? { return UIImage(contentsOfFile: photoPath) } class func nextPhotoID() -> Int { let userDefaults = NSUserDefaults.standardUserDefaults() let currentID = userDefaults.integerForKey("PhotoID") userDefaults.setInteger(currentID + 1, forKey: "PhotoID") userDefaults.synchronize() return currentID } func removePhotoFile() { if hasPhoto { let path = photoPath let fileManager = NSFileManager.defaultManager() if fileManager.fileExistsAtPath(path) { do { try fileManager.removeItemAtPath(path) } catch { print("Error removing file: \(error)") } } } } }
mit
c425750b35d00c3b6674eba8b2be3125
25.283582
99
0.592845
5.119186
false
false
false
false
softdevstory/yata
yata/Sources/ViewModels/PageListViewModel.swift
1
4055
// // PageListViewModel.swift // yata // // Created by HS Song on 2017. 7. 4.. // Copyright © 2017년 HS Song. All rights reserved. // import Foundation import RxSwift class PageListViewModel { private let telegraph = Telegraph.shared var totalPageCount = 0 private let bag = DisposeBag() var pages: Variable<[Page]> = Variable<[Page]>([]) func numberOfRows() -> Int { return pages.value.count } func isLastRowAndNeedToLoad(row: Int) -> Bool { if row == pages.value.count - 1 { if totalPageCount == pages.value.count { return false } else { return true } } else { return false } } func getPage(row: Int) -> Observable<Page> { let observable = Observable<Page>.create { observer in let page = self.pages.value[row] if let _ = page.content { observer.onNext(page) observer.onCompleted() } else { guard let path = page.path else { observer.onError(YataError.NoPagePath) return Disposables.create() } self.telegraph.getPage(path: path) .observeOn(MainScheduler.instance) .subscribe(onNext: { page in self.pages.value[row].content = page.content observer.onNext(page) observer.onCompleted() }, onError: { error in observer.onError(error) }) .disposed(by: self.bag) } return Disposables.create() } return observable } func loadNextPageList() -> Observable<Void> { let observable = Observable<Void>.create { observer in if self.pages.value.count >= self.totalPageCount { observer.onCompleted() return Disposables.create() } guard let accessToken = AccessTokenStorage.loadAccessToken() else { observer.onError(YataError.NoAccessToken) return Disposables.create() } let disposable = self.telegraph.getPageList(accessToken: accessToken, offset: self.pages.value.count) .observeOn(MainScheduler.instance) .subscribe(onNext: { pageList in self.totalPageCount = pageList.totalCount! self.pages.value.append(contentsOf: pageList.pages!) observer.onCompleted() }, onError: { error in observer.onError(error) }) return Disposables.create { disposable.dispose() } } return observable } func loadPageList() -> Observable<Void> { let observable = Observable<Void>.create { observer in guard let accessToken = AccessTokenStorage.loadAccessToken() else { observer.onError(YataError.NoAccessToken) return Disposables.create() } let disposable = self.telegraph.getPageList(accessToken: accessToken) .observeOn(MainScheduler.instance) .subscribe(onNext: { pageList in self.totalPageCount = pageList.totalCount! self.pages.value = pageList.pages! observer.onCompleted() }, onError: { error in observer.onError(error) }) return Disposables.create { disposable.dispose() } } return observable } }
mit
c9d64dc6048eef4188c145fe685e81dd
28.576642
113
0.484946
5.635605
false
false
false
false
ilyapuchka/VIPER-SWIFT
VIPER-SWIFT/Classes/Modules/Add/User Interface/Transition/AddPresentationTransition.swift
1
2035
// // AddPresentationTransition.swift // VIPER-SWIFT // // Created by Conrad Stoll on 6/4/14. // Copyright (c) 2014 Mutual Mobile. All rights reserved. // import Foundation import UIKit class AddPresentationTransition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.72 } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)! let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! AddViewController toVC.transitioningBackgroundView.backgroundColor = UIColor.darkGrayColor() toVC.transitioningBackgroundView.alpha = 0.0 toVC.transitioningBackgroundView.frame = UIScreen.mainScreen().bounds let containerView = transitionContext.containerView() containerView.addSubview(toVC.transitioningBackgroundView) containerView.addSubview(toVC.view) let toViewFrame = CGRectMake(0, 0, 260, 300) toVC.view.frame = toViewFrame let finalCenter = CGPoint(x: fromVC.view.bounds.size.width / 2, y: 20 + toViewFrame.size.height / 2) toVC.view.center = CGPoint(x: finalCenter.x, y: finalCenter.y - 1000) let options = UIViewAnimationOptions.CurveEaseIn UIView.animateWithDuration(self.transitionDuration(transitionContext), delay: 0.0, usingSpringWithDamping: 0.64, initialSpringVelocity: 0.22, options: options, animations: { toVC.view.center = finalCenter toVC.transitioningBackgroundView.alpha = 0.7 }, completion: { finished in toVC.view.center = finalCenter transitionContext.completeTransition(true) } ) } }
mit
b499e412230b9239735a385c91a9e1f3
37.396226
119
0.677641
5.590659
false
false
false
false
BanyaKrylov/Learn-Swift
Skill/Homework 14/Homework 14/AppDelegate.swift
1
3712
// // AppDelegate.swift // Homework 14 // // Created by Ivan Krylov on 25.02.2020. // Copyright © 2020 Ivan Krylov. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } // 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: "Homework_14") 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)") } } } }
apache-2.0
481f9923394b2d6f65cd4f4f7494bb53
44.256098
199
0.668283
5.899841
false
true
false
false
matrix-org/matrix-ios-sdk
MatrixSDKTests/Crypto/MXOlmDeviceUnitTests.swift
1
5178
// // Copyright 2022 The Matrix.org Foundation C.I.C // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation @testable import MatrixSDK class MXOlmDeviceUnitTests: XCTestCase { /// Stubbed olm session that overrides first known index class MXOlmSessionStub: MXOlmInboundGroupSession { class OlmSessionStub: OLMInboundGroupSession { override func firstKnownIndex() -> UInt { return UInt.max } } override var session: OLMInboundGroupSession! { return OlmSessionStub() } } /// Crypto store spy used to assert on for the test outcome class CryptoStoreSpy: MXRealmCryptoStore { var session: MXOlmInboundGroupSession? override func inboundGroupSession(withId sessionId: String!, andSenderKey senderKey: String!) -> MXOlmInboundGroupSession! { return session } override func store(_ sessions: [MXOlmInboundGroupSession]!) { session = sessions.first } } let senderKey = "ABC" let roomId = "123" var store: CryptoStoreSpy! var device: MXOlmDevice! override func setUp() { super.setUp() MXSDKOptions.sharedInstance().enableRoomSharedHistoryOnInvite = true store = CryptoStoreSpy() device = MXOlmDevice(store: store) } private func addInboundGroupSession( sessionId: String, sessionKey: String, roomId: String, sharedHistory: Bool ) { device.addInboundGroupSession( sessionId, sessionKey: sessionKey, roomId: roomId, senderKey: senderKey, forwardingCurve25519KeyChain: [], keysClaimed: [:], exportFormat: false, sharedHistory: sharedHistory, untrusted: false ) } func test_addInboundGroupSession_storesSharedHistory() { let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)! addInboundGroupSession( sessionId: session.sessionId, sessionKey: session.sessionKey, roomId: roomId, sharedHistory: true ) XCTAssertNotNil(store.session) XCTAssertTrue(store.session!.sharedHistory) } func test_addInboundGroupSession_doesNotOverrideSharedHistory() { let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)! // Add first inbound session that is not sharing history addInboundGroupSession( sessionId: session.sessionId, sessionKey: session.sessionKey, roomId: roomId, sharedHistory: false ) // Modify the now stored session so that it will be considered outdated store.session = stubbedSession(for: store.session!) // Add second inbound session with the same ID which is sharing history addInboundGroupSession( sessionId: session.sessionId, sessionKey: session.sessionKey, roomId: roomId, sharedHistory: true ) // After the update the shared history should not be changed XCTAssertNotNil(store.session) XCTAssertFalse(store.session!.sharedHistory) } func test_addMultipleInboundGroupSessions_doesNotOverrideSharedHistory() { let session = device.createOutboundGroupSessionForRoom(withRoomId: roomId)! // Add first inbound session that is not sharing history addInboundGroupSession( sessionId: session.sessionId, sessionKey: session.sessionKey, roomId: roomId, sharedHistory: false ) // Modify the now stored session so that it will be considered outdated store.session = stubbedSession(for: store.session!) // Add multiple sessions via exported data which are sharing history let data = store.session!.exportData()! data.sharedHistory = true device.importInboundGroupSessions([data]) // After the update the shared history should not be changed XCTAssertNotNil(store.session) XCTAssertFalse(store.session!.sharedHistory) } // MARK: - Helpers /// Create a stubbed version of olm session with custom index private func stubbedSession(for session: MXOlmInboundGroupSession) -> MXOlmSessionStub { let data = session.exportData()! return MXOlmSessionStub(importedSessionData: data)! } }
apache-2.0
ff55d5f1f429a17e784387864764ee5b
33.291391
132
0.638664
5.147117
false
false
false
false
m-alani/contests
leetcode/integerToRoman.swift
1
1195
// // integerToRoman.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/integer-to-roman/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func intToRoman(_ number: Int) -> String { var result = "" var num = number while (num > 0) { switch num { case 1000..<4000: result.append("M"); num -= 1000 case 900..<1000: result.append("CM"); num -= 900 case 500..<900: result.append("D"); num -= 500 case 400..<500: result.append("CD"); num -= 400 case 100..<400: result.append("C"); num -= 100 case 90..<100: result.append("XC"); num -= 90 case 50..<90: result.append("L"); num -= 50 case 40..<50: result.append("XL"); num -= 40 case 10..<40: result.append("X"); num -= 10 case 9: result.append("IX"); num -= 9 case 5..<9: result.append("V"); num -= 5 case 4: result.append("IV"); num -= 4 case 1..<4: result.append("I"); num -= 1 default: num -= num } } return result } }
mit
1b5468edc0f718e52fd3d3e2f94ae831
34.147059
117
0.562343
3.588589
false
false
false
false
ilyahal/VKMusic
VkPlaylist/MusicFromInternetTableViewController.swift
1
26677
// // MusicFromInternetTableViewController.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreData /// Контроллер отображающий музыку из интернета, с возможностью Pull-To-Refresh class MusicFromInternetTableViewController: UITableViewController { /// Идентификатор текущего списка аудиозаписей var playlistIdentifier: String? /// Состояние авторизации пользователя при последнем отображении контроллера var currentAuthorizationStatus: Bool! /// Массив аудиозаписей, полученный в результате успешного выполнения запроса к серверу var music = [Track]() /// Массив аудиозаписей, отображаемых на экране var activeArray: [Track] { return music } /// Запрос на получение данных с сервера var getRequest: (() -> Void)! { return nil } /// Статус выполнения запроса к серверу var requestManagerStatus: RequestManagerObject.State { return RequestManagerObject.State.NotSearchedYet } /// Ошибки при выполнении запроса к серверу var requestManagerError: RequestManagerObject.ErrorRequest { return RequestManagerObject.ErrorRequest.None } /// Массив аудиозаписей, загружаемых сейчас var activeDownloads: [String: Download] { return DownloadManager.sharedInstance.activeDownloads } override func viewDidLoad() { super.viewDidLoad() currentAuthorizationStatus = VKAPIManager.isAuthorized DownloadManager.sharedInstance.addDelegate(self) DataManager.sharedInstance.addDataManagerDownloadsDelegate(self) // Настройка Pull-To-Refresh pullToRefreshEnable(VKAPIManager.isAuthorized) // Кастомизация tableView tableView.tableFooterView = UIView() // Чистим пустое пространство под таблицей // Регистрация ячеек var cellNib = UINib(nibName: TableViewCellIdentifiers.noAuthorizedCell, bundle: nil) // Ячейка "Необходимо авторизоваться" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.noAuthorizedCell) cellNib = UINib(nibName: TableViewCellIdentifiers.networkErrorCell, bundle: nil) // Ячейка "Ошибка при подключении к интернету" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.networkErrorCell) cellNib = UINib(nibName: TableViewCellIdentifiers.accessErrorCell, bundle: nil) // Ячейка "Ошибка доступа" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.accessErrorCell) cellNib = UINib(nibName: TableViewCellIdentifiers.nothingFoundCell, bundle: nil) // Ячейка "Ничего не найдено" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.nothingFoundCell) cellNib = UINib(nibName: TableViewCellIdentifiers.loadingCell, bundle: nil) // Ячейка "Загрузка" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.loadingCell) cellNib = UINib(nibName: TableViewCellIdentifiers.audioCell, bundle: nil) // Ячейка с аудиозаписью tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.audioCell) cellNib = UINib(nibName: TableViewCellIdentifiers.numberOfRowsCell, bundle: nil) // Ячейка с количеством строк tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.numberOfRowsCell) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if currentAuthorizationStatus != VKAPIManager.isAuthorized { pullToRefreshEnable(VKAPIManager.isAuthorized) if !VKAPIManager.isAuthorized { music.removeAll() } } } /// Перезагрузить таблицу func reloadTableView() { dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } // MARK: Pull-to-Refresh /// Управление доступностью Pull-to-Refresh func pullToRefreshEnable(enable: Bool) { if enable { if refreshControl == nil { refreshControl = UIRefreshControl() //refreshControl!.attributedTitle = NSAttributedString(string: "Потяните, чтобы обновить...") // Все крашится :с refreshControl!.addTarget(self, action: #selector(refreshMusic), forControlEvents: .ValueChanged) // Добавляем обработчик контроллера обновления } } else { if let refreshControl = refreshControl { if refreshControl.refreshing { refreshControl.endRefreshing() } refreshControl.removeTarget(self, action: #selector(refreshMusic), forControlEvents: .ValueChanged) // Удаляем обработчик контроллера обновления } refreshControl = nil } } /// Запрос на обновление при Pull-to-Refresh func refreshMusic() { getRequest() } // MARK: Загрузка helpers /// Получение индекса трека в активном массиве для загрузки func trackIndexForDownload(download: Download) -> Int? { if let index = activeArray.indexOf({ $0 === download.track }) { return index } return nil } // MARK: Менеджер загруженных треков helpers /// Получение индекса трека в активном массиве с указанным id и id владельца func trackIndexWithID(id: Int32, andOwnerID ownerID: Int32) -> Int? { for (index, track) in activeArray.enumerate() { if id == track.id && ownerID == track.owner_id { return index } } return nil } // MARK: Получение количества строк таблицы /// Количества строк в таблице при статусе "NotSearchedYet" и ошибкой при подключении к интернету func numberOfRowsForNotSearchedYetStatusWithInternetErrorInSection(section: Int) -> Int { return 1 // Ячейка с сообщением об отсутствии интернет соединения } /// Количества строк в таблице при статусе "NotSearchedYet" и ошибкой при подключении к интернету func numberOfRowsForNotSearchedYetStatusWithAccessErrorInSection(section: Int) -> Int { return 1 // Ячейка с сообщением об отсутствии доступа } /// Количества строк в таблице при статусе "NotSearchedYet" func numberOfRowsForNotSearchedYetStatusInSection(section: Int) -> Int { return 0 } /// Количества строк в таблице при статусе "Loading" func numberOfRowsForLoadingStatusInSection(section: Int) -> Int { if let refreshControl = refreshControl where refreshControl.refreshing { return activeArray.count + 1 } return 1 // Ячейка с индикатором загрузки } /// Количества строк в таблице при статусе "NoResults" func numberOfRowsForNoResultsStatusInSection(section: Int) -> Int { return 1 // Ячейки с сообщением об отсутствии личных аудиозаписей } /// Количества строк в таблице при статусе "Results" func numberOfRowsForResultsStatusInSection(section: Int) -> Int { return activeArray.count + 1 // +1 - ячейка для вывода количества строк } /// Количества строк в таблице при статусе "Не авторизован" func numberOfRowsForNoAuthorizedStatusInSection(section: Int) -> Int { return 1 // Ячейка с сообщением о необходимости авторизоваться } // MARK: Получение ячеек для строк таблицы helpers /// Текст для ячейки с сообщением о том, что сервер вернул пустой массив var noResultsLabelText: String { return "Список пуст" } /// Получение количества треков в списке для ячейки с количеством аудиозаписей func numberOfAudioForIndexPath(indexPath: NSIndexPath) -> Int? { if activeArray.count != 0 && activeArray.count == indexPath.row { return activeArray.count } else { return nil } } /// Получение трека для ячейки с треком func trackForIndexPath(indexPath: NSIndexPath) -> Track { return activeArray[indexPath.row] } /// Текст для ячейки с сообщением о необходимости авторизоваться var noAuthorizedLabelText: String { return "Необходимо авторизоваться" } // MARK: Получение ячеек для строк таблицы /// Ячейка для строки когда поиск еще не выполнялся и была получена ошибка при подключении к интернету func getCellForNotSearchedYetRowWithInternetErrorForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.networkErrorCell, forIndexPath: indexPath) as! NetworkErrorCell return cell } /// Ячейка для строки когда поиск еще не выполнялся и была получена ошибка доступа func getCellForNotSearchedYetRowWithAccessErrorForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.accessErrorCell, forIndexPath: indexPath) as! AccessErrorCell return cell } /// Ячейка для строки когда поиск еще не выполнялся func getCellForNotSearchedYetRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { return UITableViewCell() } /// Ячейка для строки с сообщением что сервер вернул пустой массив func getCellForNoResultsRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell cell.messageLabel.text = noResultsLabelText return cell } /// Ячейка для строки с сообщением о загрузке func getCellForLoadingRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.loadingCell, forIndexPath: indexPath) as! LoadingCell cell.activityIndicator.startAnimating() return cell } /// Попытка получить ячейку для строки с количеством аудиозаписей func getCellForNumberOfAudioRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell? { let count = numberOfAudioForIndexPath(indexPath) if let count = count { let numberOfRowsCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.numberOfRowsCell) as! NumberOfRowsCell numberOfRowsCell.configureForType(.Audio, withCount: count) return numberOfRowsCell } return nil } /// Ячейка для строки с аудиозаписью func getCellForRowWithAudioForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let track = trackForIndexPath(indexPath) let downloaded = DataManager.sharedInstance.isDownloadedTrack(track) // Загружен ли трек let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.audioCell, forIndexPath: indexPath) as! AudioCell cell.delegate = self cell.configureForTrack(track) var showDownloadControls = false // Отображать ли кнопки "Пауза" и "Отмена" и индикатор выполнения загрузки с меткой для отображения прогресса загрузки if let download = activeDownloads[track.url] { // Если аудиозапись есть в списке активных загрузок showDownloadControls = true cell.progressBar.progress = download.progress cell.progressLabel.text = download.isDownloading ? (download.totalSize == nil ? "Загружается..." : String(format: "%.1f%% из %@", download.progress * 100, download.totalSize!)) : (download.inQueue ? "В очереди" : "Пауза") let title = download.isDownloading ? "Пауза" : (download.inQueue ? "Пауза" : "Продолжить") cell.pauseButton.setTitle(title, forState: UIControlState.Normal) } cell.progressBar.hidden = !showDownloadControls cell.progressLabel.hidden = !showDownloadControls cell.downloadButton.hidden = downloaded || showDownloadControls cell.pauseButton.hidden = !showDownloadControls cell.cancelButton.hidden = !showDownloadControls return cell } /// Ячейка для строки с сообщением о необходимости авторизоваться func getCellForNoAuthorizedRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.noAuthorizedCell, forIndexPath: indexPath) as! NoAuthorizedCell cell.messageLabel.text = noAuthorizedLabelText return cell } } // MARK: UITableViewDataSource private typealias _MusicFromInternetTableViewControllerDataSource = MusicFromInternetTableViewController extension _MusicFromInternetTableViewControllerDataSource { // Получение количества строк таблицы override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .NotSearchedYet where requestManagerError == .NetworkError: return numberOfRowsForNotSearchedYetStatusWithInternetErrorInSection(section) case .NotSearchedYet where requestManagerError == .AccessError: return numberOfRowsForNotSearchedYetStatusWithAccessErrorInSection(section) case .NotSearchedYet: return numberOfRowsForNotSearchedYetStatusInSection(section) case .Loading: return numberOfRowsForLoadingStatusInSection(section) case .NoResults: return numberOfRowsForNoResultsStatusInSection(section) case .Results: return numberOfRowsForResultsStatusInSection(section) } } return numberOfRowsForNoAuthorizedStatusInSection(section) } // Получение ячейки для строки таблицы override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if VKAPIManager.isAuthorized { switch requestManagerStatus { case .NotSearchedYet where requestManagerError == .NetworkError: return getCellForNotSearchedYetRowWithInternetErrorForIndexPath(indexPath) case .NotSearchedYet where requestManagerError == .AccessError: return getCellForNotSearchedYetRowWithAccessErrorForIndexPath(indexPath) case .NotSearchedYet: return getCellForNotSearchedYetRowForIndexPath(indexPath) case .NoResults: return getCellForNoResultsRowForIndexPath(indexPath) case .Loading: if let refreshControl = refreshControl where refreshControl.refreshing { if music.count != 0 { if let numberOfRowsCell = getCellForNumberOfAudioRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForRowWithAudioForIndexPath(indexPath) } } return getCellForLoadingRowForIndexPath(indexPath) case .Results: if let numberOfRowsCell = getCellForNumberOfAudioRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForRowWithAudioForIndexPath(indexPath) } } return getCellForNoAuthorizedRowForIndexPath(indexPath) } } // MARK: UITableViewDelegate private typealias _MusicFromInternetTableViewControllerDelegate = MusicFromInternetTableViewController extension _MusicFromInternetTableViewControllerDelegate { // Высота каждой строки override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if VKAPIManager.isAuthorized { if requestManagerStatus == .Results { if activeArray.count != 0 { if activeArray.count == indexPath.row { return 44 } } } } return 62 } // Вызывается при тапе по строке таблицы override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if tableView.cellForRowAtIndexPath(indexPath) is AudioCell { let track = activeArray[indexPath.row] let index = music.indexOf({ $0 === track })! PlayerManager.sharedInstance.playItemWithIndex(index, inPlaylist: music, withPlaylistIdentifier: playlistIdentifier!) } } } // MARK: DownloadManagerDelegate extension MusicFromInternetTableViewController: DownloadManagerDelegate { // Менеджер загрузок начал новую загрузку func downloadManagerStartTrackDownload(download: Download) { // Обновляем ячейку if let index = trackIndexForDownload(download) { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .None) }) } } // Менеджер загрузок изменил состояние загрузки func downloadManagerUpdateStateTrackDownload(download: Download) { // Обновляем ячейку if let index = trackIndexForDownload(download) { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .None) }) } } // Менеджер загрузок отменил выполнение загрузки func downloadManagerCancelTrackDownload(download: Download) { // Обновляем ячейку if let index = trackIndexForDownload(download) { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .None) }) } } // Менеджер загрузок завершил загрузку func downloadManagerdidFinishDownloadingDownload(download: Download) { // Обновляем ячейку if let index = trackIndexForDownload(download) { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .None) }) } } // Менеджер загрузок получил часть данных func downloadManagerURLSessionDidWriteDataForDownload(download: Download) { // Обновляем ячейку if let index = trackIndexForDownload(download), audioCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as? AudioCell { dispatch_async(dispatch_get_main_queue(), { audioCell.cancelButton.hidden = download.progress == 1 audioCell.pauseButton.hidden = download.progress == 1 audioCell.progressBar.progress = download.progress audioCell.progressLabel.text = download.progress == 1 ? "Сохраняется..." : String(format: "%.1f%% из %@", download.progress * 100, download.totalSize!) }) } } } // MARK: DataManagerDownloadsDelegate extension MusicFromInternetTableViewController: DataManagerDownloadsDelegate { // Контроллер удалил трек с указанным id и id владельца func downloadManagerDeleteTrackWithID(id: Int32, andOwnerID ownerID: Int32) { // Обновляем ячейку if let trackIndex = trackIndexWithID(id, andOwnerID: ownerID) { dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: trackIndex, inSection: 0)], withRowAnimation: .None) }) } } // Контроллер массива загруженных аудиозаписей начал изменять контент func dataManagerDownloadsControllerWillChangeContent() {} // Контроллер массива загруженных аудиозаписей совершил изменения определенного типа в укзанном объекте по указанному пути (опционально новый путь) func dataManagerDownloadsControllerDidChangeObject(anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {} // Контроллер массива загруженных аудиозаписей закончил изменять контент func dataManagerDownloadsControllerDidChangeContent() {} } // MARK: AudioCellDelegate extension MusicFromInternetTableViewController: AudioCellDelegate { /// Кнопка "Пауза" была нажата func pauseTapped(cell: AudioCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = activeArray[indexPath.row] DownloadManager.sharedInstance.pauseDownloadTrack(track) } } // Кнопка "Продолжить" была нажата func resumeTapped(cell: AudioCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = activeArray[indexPath.row] DownloadManager.sharedInstance.resumeDownloadTrack(track) } } // Кнопка "Отмена" была нажата func cancelTapped(cell: AudioCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = activeArray[indexPath.row] DownloadManager.sharedInstance.cancelDownloadTrack(track) } } // Кнопка "Скачать" была нажата func downloadTapped(cell: AudioCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = activeArray[indexPath.row] DownloadManager.sharedInstance.downloadTrack(track) } } }
mit
dc24343f2e91fc7ee19d272939f2011e
39.975567
191
0.674206
5.059914
false
false
false
false
AlbertXYZ/HDCP
HDCP/HDCP/HDHM07Controller.swift
1
3782
// // HDHM07Controller.swift // HDCP // // Created by 徐琰璋 on 16/1/15. // Copyright © 2016年 batonsoft. All rights reserved. // import UIKit class HDHM07Controller: UITableViewController { var dataArray: NSMutableArray! var offset: Int! override func viewDidLoad() { super.viewDidLoad() offset = 0 dataArray = NSMutableArray() setupUI() showHud() doGetRequestData(10, offset: self.offset) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.title = "厨房宝典" self.navigationItem.leftBarButtonItem = CoreUtils.HDBackBarButtonItem(#selector(backAction), taget: self) } deinit { HDLog.LogClassDestory("HDHM07Controller") } // MARK: - 创建UI视图 func setupUI() { self.tableView.tableFooterView = UIView() self.tableView.register(HDHM07Cell.classForCoder(), forCellReuseIdentifier: "myCell") self.tableView.backgroundColor = Constants.HDBGViewColor //当列表滚动到底端 视图自动刷新 unowned let WS = self self.tableView?.mj_footer = HDRefreshGifFooter(refreshingBlock: { () -> Void in WS.doGetRequestData(10, offset: WS.offset) }) //兼容IOS11 if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never; } } // MARK: - 提示动画显示和隐藏 func showHud() { CoreUtils.showProgressHUD(self.view) } func hidenHud() { CoreUtils.hidProgressHUD(self.view) } // MARK: - events @objc func backAction() { navigationController!.popViewController(animated: true) } // MARK: - 数据加载 func doGetRequestData(_ limit: Int, offset: Int) { unowned let WS = self HDHM07Service().doGetRequest_HDHM07_URL(limit, offset: offset, successBlock: { (hm07Response) -> Void in WS.offset = self.offset + 10 WS.hidenHud() WS.dataArray.addObjects(from: (hm07Response.result?.list)!) WS.tableView.mj_footer.endRefreshing() WS.tableView.reloadData() }) { (error) -> Void in WS.tableView.mj_footer.endRefreshing() CoreUtils.showWarningHUD(WS.view, title: Constants.HD_NO_NET_MSG) } } // MARK: - UITableView delegate/datasource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView .dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! HDHM07Cell let model = dataArray[(indexPath as NSIndexPath).row] as! HDHM07ListModel cell.coverImageV?.kf.setImage(with: URL(string: model.image!), placeholder: UIImage(named: "noDataDefaultIcon"), options: nil, progressBlock: nil, completionHandler: nil) cell.title?.text = model.title cell.content?.text = model.content return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let model = dataArray[(indexPath as NSIndexPath).row] as! HDHM07ListModel let hdWebVC = HDWebController() hdWebVC.name = model.title hdWebVC.url = model.url self.hidesBottomBarWhenPushed = true; self.navigationController?.pushViewController(hdWebVC, animated: true) } }
mit
e0ea35833e6b1c2b5b5806e1b3648a99
25.421429
178
0.644499
4.419355
false
false
false
false
benlangmuir/swift
test/Interpreter/availability_weak_linking.swift
6
7881
// RUN: %empty-directory(%t) // RUN: cp -R %S/Inputs/FakeUnavailableObjCFramework.framework %t // RUN: %target-clang -dynamiclib %S/Inputs/FakeUnavailableObjCFramework.m -fmodules -F %t -framework Foundation -o %t/FakeUnavailableObjCFramework.framework/FakeUnavailableObjCFramework // RUN: %target-codesign %t/FakeUnavailableObjCFramework.framework/FakeUnavailableObjCFramework // RUN: %target-build-swift-dylib(%t/%target-library-name(FakeUnavailableSwiftDylib)) -emit-module -emit-module-path %t/FakeUnavailableSwiftDylib.swiftmodule %S/Inputs/FakeUnavailableSwiftDylib.swift // RUN: %target-codesign %t/%target-library-name(FakeUnavailableSwiftDylib) // RUN: %target-build-swift %t/%target-library-name(FakeUnavailableSwiftDylib) -I %t -F %t %s -o %t/UseWeaklinkedUnavailableObjCFramework // RUN: %target-build-swift -O %t/%target-library-name(FakeUnavailableSwiftDylib) -I %t -F %t %s -o %t/UseWeaklinkedUnavailableObjCFramework.opt // These tests emulate deploying back to an older OS where newer APIs are not // available by linking to an Objective-C framework where APIs have been // annotated to only be available in the far future (version 1066.0 of all // platforms) and then moving the framework aside so that it can't be found // at run time. // RUN: mv %t/FakeUnavailableObjCFramework.framework %t/FakeUnavailableObjCFramework-MovedAside.framework // RUN: mv %t/%target-library-name(FakeUnavailableSwiftDylib) %t/%target-library-name(FakeUnavailableSwiftDylib)-MovedAside // RUN: %target-codesign %t/UseWeaklinkedUnavailableObjCFramework // RUN: %target-codesign %t/UseWeaklinkedUnavailableObjCFramework.opt // RUN: %target-run %t/UseWeaklinkedUnavailableObjCFramework | %FileCheck %s // RUN: %target-run %t/UseWeaklinkedUnavailableObjCFramework.opt | %FileCheck %s // REQUIRES: objc_interop // REQUIRES: executable_test import StdlibUnittest import FakeUnavailableObjCFramework import FakeUnavailableSwiftDylib import Foundation // CHECK: Running print("Running...") func useUnavailableObjCGlobal() { if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let g = UnavailableObjCGlobalVariable _blackHole(g) } } useUnavailableObjCGlobal() @objc class ClassConformingToUnavailableObjCProtocol : NSObject, UnavailableObjCProtocol { func someMethod() { print("Executed ClassConformingToUnavailableObjCProtocol.someMethod()") } } func useClassConformingToUnavailableObjCProtocol() { let o = ClassConformingToUnavailableObjCProtocol() o.someMethod() if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let oAsUP: UnavailableObjCProtocol = o as UnavailableObjCProtocol oAsUP.someMethod() } } // CHECK-NEXT: Executed ClassConformingToUnavailableObjCProtocol.someMethod() useClassConformingToUnavailableObjCProtocol() @objc class ClassThatWillBeExtendedToConformToUnavailableObjCProtocol : NSObject { } extension ClassThatWillBeExtendedToConformToUnavailableObjCProtocol : UnavailableObjCProtocol { func someMethod() { print("Executed ClassThatWillBeExtendedToConformToUnavailableObjCProtocol.someMethod()") } } func useClassThatWillBeExtendedToConformToUnavailableObjCProtocol() { let o = ClassThatWillBeExtendedToConformToUnavailableObjCProtocol() o.someMethod() if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let oAsUP: UnavailableObjCProtocol = o as UnavailableObjCProtocol oAsUP.someMethod() } } // CHECK-NEXT: Executed ClassThatWillBeExtendedToConformToUnavailableObjCProtocol.someMethod() useClassThatWillBeExtendedToConformToUnavailableObjCProtocol() // We need to gracefully handle ObjC protocols missing availability annotations // because it is quite common in frameworks. (Historically, for Objective-C, // missing availability annotations on protocols has not been problematic // because Objective-C protocol metadata is compiled into any code that // references it -- it is not weakly linked.) @objc class ClassConformingToUnannotatedUnavailableObjCProtocol : NSObject, UnannotatedUnavailableObjCProtocol { func someMethod() { print("Executed ClassConformingToUnannotatedUnavailableObjCProtocol.someMethod()") } } func useClassConformingToUnannotatedUnavailableObjCProtocol() { let o = ClassConformingToUnannotatedUnavailableObjCProtocol() o.someMethod() let oAsUP: UnannotatedUnavailableObjCProtocol = (o as AnyObject) as! UnannotatedUnavailableObjCProtocol oAsUP.someMethod() } // CHECK-NEXT: Executed ClassConformingToUnannotatedUnavailableObjCProtocol.someMethod() // CHECK-NEXT: Executed ClassConformingToUnannotatedUnavailableObjCProtocol.someMethod() useClassConformingToUnannotatedUnavailableObjCProtocol() func printClassMetadataViaGeneric<T>() -> T { print("\(T.self)") fatalError("This should never be called") } func useUnavailableObjCClass() { if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let o = UnavailableObjCClass() o.someMethod() } for i in 0 ..< getInt(5) { if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let o: UnavailableObjCClass = printClassMetadataViaGeneric() _blackHole(o) } } class SomeClass { } let someObject: AnyObject = _opaqueIdentity(SomeClass() as AnyObject) for i in 0 ..< getInt(5) { if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let isUnavailable = someObject is UnavailableObjCClass _blackHole(isUnavailable) } } for i in 0 ..< getInt(5) { if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let asUnavailable = someObject as? UnavailableObjCClass _blackHole(asUnavailable) } } } @available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) func wrapUnavailableFunction() { someFunction() } useUnavailableObjCClass() // Allow extending a weakly-linked class to conform to a protocol. protocol SomeSwiftProtocol { } @available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) extension UnavailableObjCClass : SomeSwiftProtocol { } @available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) extension UnavailableSwiftClass : SomeSwiftProtocol { } func checkSwiftProtocolConformance() { // Make sure the runtime doesn't crash in the presence of a conformance // record for a class that doesn't exist at runtime. let x: Any = 42 _blackHole(x as? SomeSwiftProtocol) } checkSwiftProtocolConformance() class ClassConformingToUnavailableSwiftProtocol : UnavailableSwiftProtocol { func someMethod() { print("Executed ClassConformingToUnavailableSwiftProtocol.someMethod()") } } func useClassConformingToUnavailableSwiftProtocol() { let o = ClassConformingToUnavailableSwiftProtocol() o.someMethod() if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let oAsUP: UnavailableSwiftProtocol = o as UnavailableSwiftProtocol oAsUP.someMethod() } } // CHECK-NEXT: Executed ClassConformingToUnavailableSwiftProtocol.someMethod() useClassConformingToUnavailableSwiftProtocol() class ClassThatWillBeExtendedToConformToUnavailableSwiftProtocol { } extension ClassThatWillBeExtendedToConformToUnavailableSwiftProtocol : UnavailableSwiftProtocol { func someMethod() { print("Executed ClassThatWillBeExtendedToConformToUnavailableSwiftProtocol.someMethod()") } } func useClassThatWillBeExtendedToConformToUnavailableSwiftProtocol() { let o = ClassThatWillBeExtendedToConformToUnavailableSwiftProtocol() o.someMethod() if #available(OSX 1066.0, iOS 1066.0, watchOS 1066.0, tvOS 1066.0, *) { let oAsUP: UnavailableSwiftProtocol = o as UnavailableSwiftProtocol oAsUP.someMethod() } } // CHECK-NEXT: Executed ClassThatWillBeExtendedToConformToUnavailableSwiftProtocol.someMethod() useClassThatWillBeExtendedToConformToUnavailableSwiftProtocol() // CHECK-NEXT: Done print("Done")
apache-2.0
cda58b5f309ff713c33ca856def2669a
35.486111
199
0.780865
3.948397
false
false
false
false
wireapp/wire-ios-sync-engine
Source/UserSession/ZMUserSession+Logs.swift
1
2545
// // Wire // Copyright (C) 2016 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 WireDataModel // MARK: - Error on context save debugging public enum ContextType: String { case UI case Sync case Search case Other } extension NSManagedObjectContext { var type: ContextType { if self.zm_isSyncContext { return .Sync } if self.zm_isUserInterfaceContext { return .UI } if self.zm_isSearchContext { return .Search } return .Other } } extension ZMUserSession { public typealias SaveFailureCallback = (_ metadata: [String: Any], _ type: ContextType, _ error: NSError, _ userInfo: [String: Any]) -> Void /// Register a handle for monitoring when one of the manage object contexts fails /// to save and is rolled back. The call is invoked on the context queue, so it might not be on the main thread public func registerForSaveFailure(handler: @escaping SaveFailureCallback) { self.managedObjectContext.errorOnSaveCallback = { (context, error) in let metadata: [String: Any] = context.persistentStoreCoordinator!.persistentStores[0].metadata as [String: Any] let type = context.type let userInfo: [String: Any] = context.userInfo.asDictionary() as! [String: Any] handler(metadata, type, error, userInfo) } self.syncManagedObjectContext.performGroupedBlock { self.syncManagedObjectContext.errorOnSaveCallback = { (context, error) in let metadata: [String: Any] = context.persistentStoreCoordinator!.persistentStores[0].metadata as [String: Any] let type = context.type let userInfo: [String: Any] = context.userInfo.asDictionary() as! [String: Any] handler(metadata, type, error, userInfo) } } } }
gpl-3.0
d821c28b5362e9d55420a339a9842c9b
35.884058
144
0.668369
4.585586
false
false
false
false
bastie/swjft
swjft/swjft/lang/Throwable.swift
1
1705
// // Throwable.swift // swjft // // Created by Sebastian Ritter on 12.12.15. // Copyright © 2015 Sebastian Ritter. All rights reserved. // extension lang { public class Throwable : Object, ErrorType { private var detailMessage : lang.String? private var cause : lang.Throwable? public override init (){} public init(message : lang.String) { self.detailMessage = message } public init(detailMessage : Swift.String) { self.detailMessage = lang.String(otherString: detailMessage) } public init (message : lang.String, cause : lang.Throwable) { self.detailMessage = message self.cause = cause } public init (detailMessage : Swift.String, cause : lang.Throwable) { self.detailMessage = lang.String(otherString: detailMessage) self.cause = cause } public init (cause : lang.Throwable) { self.detailMessage = cause.toStringJ() self.cause = cause } /* NOT YET IMPLEMENTED - JDK 7 public init (message : lang.String, cause : lang.Throwable, enableSuppression : Bool, writableStackTrace: Bool) { self.detailMessage = message self.cause = cause self.suppressionEnable = enableSuppression self.stackTraceWritable = writableStackTrace } public init (detailMessage : Swift.String, cause : lang.Throwable, enableSuppression : Bool, writableStackTrace: Bool) { self.detailMessage = lang.String(otherString: detailMessage) self.cause = cause self.suppressionEnable = enableSuppression self.stackTraceWritable = writableStackTrace }*/ } }
isc
5749fa82999b730d04948abf60afb986
31.788462
126
0.642606
4.544
false
false
false
false
dfelber/SwiftStringScore
String+Score.swift
1
4892
// // String+Score.swift // // Created by Dominik Felber on 07.04.2016. // Copyright (c) 2016 Dominik Felber. All rights reserved. // // Based on the Objective-C implementation of Nicholas Bruning https://github.com/thetron/StringScore // and the original JavaScript implementation of Joshaven Potter https://github.com/joshaven/string_score // import Foundation enum StringScoreOption { case None case FavorSmallerWords case ReducedLongStringPenalty } extension String { /// Calculates a score describing how good two strings match. /// (0 => no match / 1 => perfect match) /// /// - parameter otherString: The string to compare to /// - parameter fuzziness: How fuzzy the matching calculation is (0...1) /// - parameter option: Optional comparison options /// - returns: A Float in the range of 0...1 /// func scoreAgainst(otherString: String, fuzziness: Float? = nil, option: StringScoreOption = .None) -> Float { // Both strings are identical if self == otherString { return 1 } // Other string is empty if otherString.isEmpty { return 0 } let otherStringLength = Float(otherString.characters.count) let stringLength = Float(self.characters.count) var totalCharacterScore: Float = 0 var otherStringScore: Float = 0 var fuzzies: Float = 1 var finalScore: Float = 0 var workingString = self var startOfStringBonus = false // Ensure that the fuzziness is in the range of 0...1 var fuzzyFactor = fuzziness if let f = fuzzyFactor { fuzzyFactor = 1 - max(min(1.0, f), 0.0) } for (index, character) in otherString.characters.enumerate() { let range = workingString.startIndex..<workingString.endIndex let indexInString = workingString.rangeOfString("\(character)", options: .CaseInsensitiveSearch, range: range, locale: nil) var characterScore: Float = 0.1 if let indexInString = indexInString { // Same case bonus let char = workingString.characters[indexInString.startIndex] if character == char { characterScore += 0.1 } // Consecutive letter & start-of-string bonus if indexInString.startIndex == otherString.startIndex { // Increase the score when matching first character of the remainder of the string characterScore += 0.6 // If match is the first character of the string // & the first character of abbreviation, add a // start-of-string match bonus. if index == 0 { startOfStringBonus = true } } else { // Acronym Bonus // Weighing Logic: Typing the first character of an acronym is as if you // preceded it with two perfect character matches. if workingString.substringWithRange(indexInString.startIndex.advancedBy(-1)..<indexInString.endIndex.advancedBy(-1)) == " " { characterScore += 0.8 } } // Left trim the already matched part of the string // (forces sequential matching). workingString = workingString.substringFromIndex(indexInString.startIndex.advancedBy(1)) } else { if let fuzzyFactor = fuzzyFactor { fuzzies += fuzzyFactor } else { return 0 } } totalCharacterScore += characterScore } if option == .FavorSmallerWords { // Weigh smaller words higher return totalCharacterScore / stringLength } otherStringScore = totalCharacterScore / otherStringLength if option == .ReducedLongStringPenalty { // Reduce the penalty for longer words let percentageOfMatchedString = otherStringLength / stringLength let wordScore = otherStringScore * percentageOfMatchedString finalScore = (wordScore + otherStringScore) / 2 } else { finalScore = ((otherStringScore * otherStringLength / stringLength) + otherStringScore) / 2 } finalScore = finalScore / fuzzies if startOfStringBonus && finalScore + 0.15 < 1 { finalScore += 0.15 } return finalScore } }
mit
51877885b9754647251473c7754663df
36.068182
145
0.55417
5.369923
false
false
false
false
richardpiazza/MiseEnPlace
Sources/MiseEnPlace/Multimedia.swift
1
4648
import Foundation /// Parameter and helper methods for managing a single image representation of an object. /// /// ## Required Conformance /// /// ```swift /// // A localized platform path to the image data. /// var imagePath: String? { get set } /// ``` /// public protocol Multimedia { var imagePath: String? { get set } var fileManager: FileManager { get } } public extension Multimedia { var fileManager: FileManager { return .default } /// A File URL representation of the `imagePath`. var imageURL: URL? { guard let path = self.imagePath else { return nil } return imageDirectory.appendingPathComponent(path) } /// A reference to the directory where images for this `Multimedia` type /// can be found. var imageDirectory: URL { return fileManager.imageDirectory(for: self) } /// Creates a local copy of asset at the supplied URL. mutating func copyImage(atURL url: URL) { self.imagePath = fileManager.imagePath(for: self, copyingImageAtURL: url) } mutating func writeImage(_ data: Data, name: String = UUID().uuidString, ext: String = "png") { imagePath = fileManager.imagePath(for: self, writingData: data, name: name, ext: ext) } mutating func removeImage() { self.imagePath = nil fileManager.removeImage(for: self) } } internal extension FileManager { var supportDirectory: URL { let directory: URL do { #if os(Linux) directory = try url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #elseif os(Windows) directory = try url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #elseif os(tvOS) // The 'Application Support' directory is not available on tvOS. directory = try url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #else directory = try url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) #endif } catch { fatalError(error.localizedDescription) } return directory.appendingPathComponent("MiseEnPlace") } } public extension FileManager { /// A reference to the directory where images for this `Multimedia` type /// can be found. func imageDirectory(for multimedia: Multimedia) -> URL { var pathURL: URL switch type(of: self) { case is Ingredient.Type: pathURL = supportDirectory.appendingPathComponent("Images/Ingredient") case is Recipe.Type: pathURL = supportDirectory.appendingPathComponent("Images/Recipe") case is ProcedureElement.Type: pathURL = supportDirectory.appendingPathComponent("Images/ProcedureElement") default: pathURL = supportDirectory.appendingPathComponent("Images/Other") } if !fileExists(atPath: pathURL.path) { do { try createDirectory(at: pathURL, withIntermediateDirectories: true, attributes: nil) } catch { print(error) } } return pathURL } func imagePath(for multimedia: Multimedia, copyingImageAtURL url: URL) -> String? { guard fileExists(atPath: url.path) else { print("No File Found at path: '\(url.path)'") return nil } let filename = url.lastPathComponent let localURL = imageDirectory(for: multimedia).appendingPathComponent(filename) do { try copyItem(at: url, to: localURL) return filename } catch { print(error) return nil } } func imagePath(for multimedia: Multimedia, writingData data: Data, name: String = UUID().uuidString, ext: String = "png") -> String? { let url = imageDirectory(for: multimedia).appendingPathComponent(name).appendingPathExtension(ext) do { try data.write(to: url, options: .atomic) return url.lastPathComponent } catch { print(error) return nil } } func removeImage(for multimedia: Multimedia) { guard let url = multimedia.imageURL else { return } do { try removeItem(atPath: url.path) } catch { print(error) } } }
mit
26cc636ad65ef28e224eed61bc08fdb5
31.277778
138
0.597676
4.939426
false
false
false
false
jphacks/TK_21
ios/Alamofire/Tests/DownloadTests.swift
21
18174
// DownloadTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Alamofire import Foundation import XCTest class DownloadInitializationTestCase: BaseTestCase { let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask func testDownloadClassMethodWithMethodURLAndDestination() { // Given let URLString = "https://httpbin.org/" let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain) // When let request = Alamofire.download(.GET, URLString, destination: destination) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") XCTAssertNil(request.response, "response should be nil") } func testDownloadClassMethodWithMethodURLHeadersAndDestination() { // Given let URLString = "https://httpbin.org/" let destination = Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain) // When let request = Alamofire.download(.GET, URLString, headers: ["Authorization": "123456"], destination: destination) // Then XCTAssertNotNil(request.request, "request should not be nil") XCTAssertEqual(request.request?.HTTPMethod ?? "", "GET", "request HTTP method should be GET") XCTAssertEqual(request.request?.URLString ?? "", URLString, "request URL string should be equal") let authorizationHeader = request.request?.valueForHTTPHeaderField("Authorization") ?? "" XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect") XCTAssertNil(request.response, "response should be nil") } } // MARK: - class DownloadResponseTestCase: BaseTestCase { let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask let cachesURL: NSURL = { let cachesDirectory = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first! let cachesURL = NSURL(fileURLWithPath: cachesDirectory, isDirectory: true) return cachesURL }() var randomCachesFileURL: NSURL { return cachesURL.URLByAppendingPathComponent("\(NSUUID().UUIDString).json") } func testDownloadRequest() { // Given let numberOfLines = 100 let URLString = "https://httpbin.org/stream/\(numberOfLines)" let destination = Alamofire.Request.suggestedDownloadDestination( directory: searchPathDirectory, domain: searchPathDomain ) let expectation = expectationWithDescription("Download request should download data to file: \(URLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var error: NSError? // When Alamofire.download(.GET, URLString, destination: destination) .response { responseRequest, responseResponse, _, responseError in request = responseRequest response = responseResponse error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") let fileManager = NSFileManager.defaultManager() let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0] do { let contents = try fileManager.contentsOfDirectoryAtURL( directory, includingPropertiesForKeys: nil, options: .SkipsHiddenFiles ) #if os(iOS) || os(tvOS) let suggestedFilename = "\(numberOfLines)" #elseif os(OSX) let suggestedFilename = "\(numberOfLines).json" #endif let predicate = NSPredicate(format: "lastPathComponent = '\(suggestedFilename)'") let filteredContents = (contents as NSArray).filteredArrayUsingPredicate(predicate) XCTAssertEqual(filteredContents.count, 1, "should have one file in Documents") if let file = filteredContents.first as? NSURL { XCTAssertEqual( file.lastPathComponent ?? "", "\(suggestedFilename)", "filename should be \(suggestedFilename)" ) if let data = NSData(contentsOfURL: file) { XCTAssertGreaterThan(data.length, 0, "data length should be non-zero") } else { XCTFail("data should exist for contents of URL") } do { try fileManager.removeItemAtURL(file) } catch { XCTFail("file manager should remove item at URL: \(file)") } } else { XCTFail("file should not be nil") } } catch { XCTFail("contents should not be nil") } } func testDownloadRequestWithProgress() { // Given let randomBytes = 4 * 1024 * 1024 let URLString = "https://httpbin.org/bytes/\(randomBytes)" let fileManager = NSFileManager.defaultManager() let directory = fileManager.URLsForDirectory(searchPathDirectory, inDomains: self.searchPathDomain)[0] let filename = "test_download_data" let fileURL = directory.URLByAppendingPathComponent(filename) let expectation = expectationWithDescription("Bytes download progress should be reported: \(URLString)") var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = [] var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = [] var responseRequest: NSURLRequest? var responseResponse: NSHTTPURLResponse? var responseData: NSData? var responseError: ErrorType? // When let download = Alamofire.download(.GET, URLString) { _, _ in return fileURL } download.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in let bytes = (bytes: bytesRead, totalBytes: totalBytesRead, totalBytesExpected: totalBytesExpectedToRead) byteValues.append(bytes) let progress = ( completedUnitCount: download.progress.completedUnitCount, totalUnitCount: download.progress.totalUnitCount ) progressValues.append(progress) } download.response { request, response, data, error in responseRequest = request responseResponse = response responseData = data responseError = error expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(responseRequest, "response request should not be nil") XCTAssertNotNil(responseResponse, "response should not be nil") XCTAssertNil(responseData, "response data should be nil") XCTAssertNil(responseError, "response error should be nil") XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count") if byteValues.count == progressValues.count { for index in 0..<byteValues.count { let byteValue = byteValues[index] let progressValue = progressValues[index] XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0") XCTAssertEqual( byteValue.totalBytes, progressValue.completedUnitCount, "total bytes should be equal to completed unit count" ) XCTAssertEqual( byteValue.totalBytesExpected, progressValue.totalUnitCount, "total bytes expected should be equal to total unit count" ) } } if let lastByteValue = byteValues.last, lastProgressValue = progressValues.last { let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected) let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1) XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0") XCTAssertEqual( progressValueFractionalCompletion, 1.0, "progress value fractional completion should equal 1.0" ) } else { XCTFail("last item in bytesValues and progressValues should not be nil") } do { try fileManager.removeItemAtURL(fileURL) } catch { XCTFail("file manager should remove item at URL: \(fileURL)") } } func testDownloadRequestWithParameters() { // Given let fileURL = randomCachesFileURL let URLString = "https://httpbin.org/get" let parameters = ["foo": "bar"] let destination: Request.DownloadFileDestination = { _, _ in fileURL } let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)") var request: NSURLRequest? var response: NSHTTPURLResponse? var error: NSError? // When Alamofire.download(.GET, URLString, parameters: parameters, destination: destination) .response { responseRequest, responseResponse, _, responseError in request = responseRequest response = responseResponse error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") if let data = NSData(contentsOfURL: fileURL), JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)), JSON = JSONObject as? [String: AnyObject], args = JSON["args"] as? [String: String] { XCTAssertEqual(args["foo"], "bar", "foo parameter should equal bar") } else { XCTFail("args parameter in JSON should not be nil") } } func testDownloadRequestWithHeaders() { // Given let fileURL = randomCachesFileURL let URLString = "https://httpbin.org/get" let headers = ["Authorization": "123456"] let destination: Request.DownloadFileDestination = { _, _ in fileURL } let expectation = expectationWithDescription("Download request should download data to file: \(fileURL)") var request: NSURLRequest? var response: NSHTTPURLResponse? var error: NSError? // When Alamofire.download(.GET, URLString, headers: headers, destination: destination) .response { responseRequest, responseResponse, _, responseError in request = responseRequest response = responseResponse error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNil(error, "error should be nil") if let data = NSData(contentsOfURL: fileURL), JSONObject = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0)), JSON = JSONObject as? [String: AnyObject], headers = JSON["headers"] as? [String: String] { XCTAssertEqual(headers["Authorization"], "123456", "Authorization parameter should equal 123456") } else { XCTFail("headers parameter in JSON should not be nil") } } } // MARK: - class DownloadResumeDataTestCase: BaseTestCase { let URLString = "https://upload.wikimedia.org/wikipedia/commons/6/69/NASA-HS201427a-HubbleUltraDeepField2014-20140603.jpg" let destination: Request.DownloadFileDestination = { let searchPathDirectory: NSSearchPathDirectory = .CachesDirectory let searchPathDomain: NSSearchPathDomainMask = .UserDomainMask return Request.suggestedDownloadDestination(directory: searchPathDirectory, domain: searchPathDomain) }() func testThatImmediatelyCancelledDownloadDoesNotHaveResumeDataAvailable() { // Given let expectation = expectationWithDescription("Download should be cancelled") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When let download = Alamofire.download(.GET, URLString, destination: destination) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } download.cancel() waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertNil(data, "data should be nil") XCTAssertNotNil(error, "error should not be nil") XCTAssertNil(download.resumeData, "resume data should be nil") } func testThatCancelledDownloadResponseDataMatchesResumeData() { // Given let expectation = expectationWithDescription("Download should be cancelled") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: AnyObject? var error: NSError? // When let download = Alamofire.download(.GET, URLString, destination: destination) download.progress { _, _, _ in download.cancel() } download.response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNotNil(error, "error should not be nil") XCTAssertNotNil(download.resumeData, "resume data should not be nil") if let responseData = data as? NSData, resumeData = download.resumeData { XCTAssertEqual(responseData, resumeData, "response data should equal resume data") } else { XCTFail("response data or resume data was unexpectedly nil") } } func testThatCancelledDownloadResumeDataIsAvailableWithJSONResponseSerializer() { // Given let expectation = expectationWithDescription("Download should be cancelled") var response: Response<AnyObject, NSError>? // When let download = Alamofire.download(.GET, URLString, destination: destination) download.progress { _, _, _ in download.cancel() } download.responseJSON { closureResponse in response = closureResponse expectation.fulfill() } waitForExpectationsWithTimeout(timeout, handler: nil) // Then if let response = response { XCTAssertNotNil(response.request, "request should not be nil") XCTAssertNotNil(response.response, "response should not be nil") XCTAssertNotNil(response.data, "data should not be nil") XCTAssertTrue(response.result.isFailure, "result should be failure") XCTAssertNotNil(response.result.error, "result error should not be nil") } else { XCTFail("response should not be nil") } XCTAssertNotNil(download.resumeData, "resume data should not be nil") } }
mit
6a2774843510905fddaee9639d805342
38.590414
126
0.643187
5.886621
false
false
false
false
itsdamslife/Sunshine
iOS/Weather/Weather/Weather.swift
1
581
// // Weather.swift // Weather // // Created by Damodar on 01/03/15. // Copyright (c) 2015 itsdamslife. All rights reserved. // import UIKit class Weather: NSObject { var weatherId: UInt var mainStatus: String? var desc: String? var icon: String? var temp: Double = 0.0 var temp_min: Double = 0.0 var temp_max: Double = 0.0 var humidity: Double = 0.0 override init() { weatherId = 0 mainStatus = "No Data" desc = "No Data Available!" icon = "01d" super.init() } }
mit
cbf689c1a3aa1df38fe3d8d84f30e5f5
16.088235
56
0.550775
3.479042
false
false
false
false
SebastienFCT/FCTBubbleChat
FCTBubbleChat/FCTBubbleChatSample/FCTBubbleChatSample/AppDelegate.swift
1
6127
// // AppDelegate.swift // FCTBubbleChatSample // // Created by sebastien FOCK CHOW THO on 2016-04-14. // Copyright © 2016 sebfct. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "sfct.FCTBubbleChatSample" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("FCTBubbleChatSample", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
9773974b9858bd3630a76fcd1dc5233c
54.189189
291
0.721025
5.851003
false
false
false
false
blinker13/Terminal
Sources/Arguments.swift
1
1501
public final class Arguments { internal let arguments:[Argument] internal var index:Int public init(_ args:[String] = Process.arguments) { let slices = args.map(Argument.parse) let arguments = slices.flatMap { $0 } self.index = arguments.startIndex self.arguments = arguments } } public extension Arguments { convenience init(_ slice:ArraySlice<String>) { let args = Array(slice) self.init(args) } func parse<Value>(_ option:Option<Value>) -> Value { let arg = value(where:option) return option.extract(arg) } func `is`(_ flag:Flag) -> Bool { return index(where:flag.evaluate) != nil } } private extension Arguments { func value<Value>(where option:Option<Value>) -> Value.StringLiteralType? { guard let index = index(where:option.evaluate) else { return nil } guard let next = arguments.successor(index) else { return nil } guard case let .value(value) = arguments[next] else { return nil } return value as? Value.StringLiteralType } func index(where evaluate:(Argument) -> Bool) -> Int? { return arguments.index(where:evaluate) } } extension Arguments : ArrayLiteralConvertible { public convenience init(arrayLiteral args:String ...) { self.init(args) } } extension Arguments : Sequence, IteratorProtocol { public func next() -> String? { guard index < arguments.endIndex else { return nil } guard case let .value(value) = arguments[index] else { return nil } defer { index = arguments.index(index, offsetBy:1) } return value } }
mit
bc9c8c27013903a94c70b13c2e92cd16
24.016667
76
0.706862
3.507009
false
false
false
false
DeKoServidoni/Hackaton2016
Ágora/ListCreateViewController.swift
1
2305
// // ListCreateViewController.swift // Ágora // // Created by Avenue Code on 8/20/16. // Copyright © 2016 Avenue Code. All rights reserved. // import Foundation import UIKit protocol DownloadManagerProtocol { func updateProgress(progress: Float) func downloadDoneWith(status: Bool!, andError: NSError?) } class ListCreateViewController: UITableViewController, SearchDelegate { var list: List? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = list?.title } //MARK: Table delegate override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list!.products.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("productItemId", forIndexPath: indexPath) cell.textLabel?.text = list!.products[indexPath.row].name cell.detailTextLabel?.text = String(format: "%d calorias", list!.products[indexPath.row].calories) return cell } override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let action = UITableViewRowAction(style: .Default, title: "Remover") { (action, indexPath) in self.list!.products.removeAtIndex(indexPath.row) tableView.reloadData() } return [action] } //MARK: Action handlers @IBAction func addItemAction(sender: AnyObject) { let storyBoard: UIStoryboard = UIStoryboard(name: "Searchboard", bundle: nil) let searchController = storyBoard.instantiateViewControllerWithIdentifier("searchId") as! SearchProductViewController searchController.delegate = self self.presentViewController(searchController, animated: true, completion: nil) } //MARK: Search delegate func itemsSelected(products: [Product]) { for item in products { list?.products.append(item) self.tableView.reloadData() ProductStore.setPersonalList(list!.title, products: list!.products) } } }
apache-2.0
4a20b12b0d67a41625c9978ea3a7ded4
31.914286
133
0.669996
5.175281
false
false
false
false
richardxyx/BoardBank
MonoBank/Player.swift
1
978
// // Player.swift // MonoBank // // Created by Richard Neitzke on 03/01/2017. // Copyright © 2017 Richard Neitzke. All rights reserved. // import Foundation /// Represents a player of the current game class Player: NSObject, NSCoding { var name: String var balance: Int var token: Token init(name: String, balance: Int, token: Token) { self.name = name self.balance = balance self.token = token } // Methods to conform to NSCoding required convenience init?(coder aDecoder: NSCoder) { guard let name = aDecoder.decodeObject(forKey: "name") as? String, let tokenRawValue = aDecoder.decodeObject(forKey: "token") as? String else { return nil } self.init(name: name, balance: aDecoder.decodeInteger(forKey: "balance"), token: Token(rawValue: tokenRawValue)!) } func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") aCoder.encode(balance, forKey: "balance") aCoder.encode(token.rawValue, forKey: "token") } }
mit
c90736567a6dd8462e9fa9ca7a777af6
22.829268
115
0.701126
3.42807
false
false
false
false
MainasuK/Bangumi-M
Percolator/Pods/Kanna/Sources/Kanna/Kanna.swift
2
10569
/**@file Kanna.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 libxmlKanna /* ParseOption */ public enum ParseOption { // libxml2 case xmlParseUseLibxml(Libxml2XMLParserOptions) case htmlParseUseLibxml(Libxml2HTMLParserOptions) } public let kDefaultXmlParseOption = ParseOption.xmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) public let kDefaultHtmlParseOption = ParseOption.htmlParseUseLibxml([.RECOVER, .NOERROR, .NOWARNING]) public enum ParseError: Error { case Empty case EncodingMismatch case InvalidOptions } /** Parse XML @param xml an XML string @param url the base URL to use for the document @param encoding the document encoding @param options a ParserOption */ public func XML(xml: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { switch option { case .xmlParseUseLibxml(let opt): return try libxmlXMLDocument(xml: xml, url: url, encoding: encoding, option: opt.rawValue) default: throw ParseError.InvalidOptions } } // NSData public func XML(xml: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { guard let xmlStr = String(data: xml, encoding: encoding) else { throw ParseError.EncodingMismatch } return try XML(xml: xmlStr, url: url, encoding: encoding, option: option) } // NSURL public func XML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultXmlParseOption) throws -> XMLDocument { guard let data = try? Data(contentsOf: url) else { throw ParseError.EncodingMismatch } return try XML(xml: data, url: url.absoluteString, encoding: encoding, option: option) } /** Parse HTML @param html an HTML string @param url the base URL to use for the document @param encoding the document encoding @param options a ParserOption */ public func HTML(html: String, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { switch option { case .htmlParseUseLibxml(let opt): return try libxmlHTMLDocument(html: html, url: url, encoding: encoding, option: opt.rawValue) default: throw ParseError.InvalidOptions } } // NSData public func HTML(html: Data, url: String? = nil, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { guard let htmlStr = String(data: html, encoding: encoding) else { throw ParseError.EncodingMismatch } return try HTML(html: htmlStr, url: url, encoding: encoding, option: option) } // NSURL public func HTML(url: URL, encoding: String.Encoding, option: ParseOption = kDefaultHtmlParseOption) throws -> HTMLDocument { guard let data = try? Data(contentsOf: url) else { throw ParseError.EncodingMismatch } return try HTML(html: data, url: url.absoluteString, encoding: encoding, option: option) } /** Searchable */ public protocol Searchable { /** Search for node from current node by XPath. @param xpath */ func xpath(_ xpath: String, namespaces: [String:String]?) -> XPathObject func xpath(_ xpath: String) -> XPathObject func at_xpath(_ xpath: String, namespaces: [String:String]?) -> XMLElement? func at_xpath(_ xpath: String) -> XMLElement? /** Search for node from current node by CSS selector. @param selector a CSS selector */ func css(_ selector: String, namespaces: [String:String]?) -> XPathObject func css(_ selector: String) -> XPathObject func at_css(_ selector: String, namespaces: [String:String]?) -> XMLElement? func at_css(_ selector: String) -> XMLElement? } /** SearchableNode */ public protocol SearchableNode: Searchable { var text: String? { get } var toHTML: String? { get } var toXML: String? { get } var innerHTML: String? { get } var className: String? { get } var tagName: String? { get set } var content: String? { get set } } /** XMLElement */ public protocol XMLElement: SearchableNode { var parent: XMLElement? { get set } subscript(attr: String) -> String? { get set } func addPrevSibling(_ node: XMLElement) func addNextSibling(_ node: XMLElement) func removeChild(_ node: XMLElement) var nextSibling: XMLElement? { get } var previousSibling: XMLElement? { get } } /** XMLDocument */ public protocol XMLDocument: class, SearchableNode { } /** HTMLDocument */ public protocol HTMLDocument: XMLDocument { var title: String? { get } var head: XMLElement? { get } var body: XMLElement? { get } } /** XMLNodeSet */ public final class XMLNodeSet { fileprivate var nodes: [XMLElement] = [] public var toHTML: String? { let html = nodes.reduce("") { if let text = $1.toHTML { return $0 + text } return $0 } return html.isEmpty == false ? html : nil } public var innerHTML: String? { let html = nodes.reduce("") { if let text = $1.innerHTML { return $0 + text } return $0 } return html.isEmpty == false ? html : nil } public var text: String? { let html = nodes.reduce("") { if let text = $1.text { return $0 + text } return $0 } return html } public subscript(index: Int) -> XMLElement { return nodes[index] } public var count: Int { return nodes.count } internal init() { } internal init(nodes: [XMLElement]) { self.nodes = nodes } public func at(_ index: Int) -> XMLElement? { return count > index ? nodes[index] : nil } public var first: XMLElement? { return at(0) } public var last: XMLElement? { return at(count-1) } } extension XMLNodeSet: Sequence { public typealias Iterator = AnyIterator<XMLElement> public func makeIterator() -> Iterator { var index = 0 return AnyIterator { if index < self.nodes.count { let n = self.nodes[index] index += 1 return n } return nil } } } /** XPathObject */ public enum XPathObject { case none case NodeSet(nodeset: XMLNodeSet) case Bool(bool: Swift.Bool) case Number(num: Double) case String(text: Swift.String) } extension XPathObject { internal init(document: XMLDocument?, docPtr: xmlDocPtr, object: xmlXPathObject) { switch object.type { case XPATH_NODESET: let nodeSet = object.nodesetval if nodeSet == nil || nodeSet?.pointee.nodeNr == 0 || nodeSet?.pointee.nodeTab == nil { self = .none return } var nodes : [XMLElement] = [] let size = Int((nodeSet?.pointee.nodeNr)!) for i in 0 ..< size { let node: xmlNodePtr = nodeSet!.pointee.nodeTab[i]! let htmlNode = libxmlHTMLNode(document: document, docPtr: docPtr, node: node) nodes.append(htmlNode) } self = .NodeSet(nodeset: XMLNodeSet(nodes: nodes)) return case XPATH_BOOLEAN: self = .Bool(bool: object.boolval != 0) return case XPATH_NUMBER: self = .Number(num: object.floatval) case XPATH_STRING: guard let str = UnsafeRawPointer(object.stringval)?.assumingMemoryBound(to: CChar.self) else { self = .String(text: "") return } self = .String(text: Swift.String(cString: str)) return default: self = .none return } } public subscript(index: Int) -> XMLElement { return nodeSet![index] } public var first: XMLElement? { return nodeSet?.first } public var count: Int { guard let nodeset = nodeSet else { return 0 } return nodeset.count } var nodeSet: XMLNodeSet? { if case let .NodeSet(nodeset) = self { return nodeset } return nil } var bool: Swift.Bool? { if case let .Bool(value) = self { return value } return nil } var number: Double? { if case let .Number(value) = self { return value } return nil } var string: Swift.String? { if case let .String(value) = self { return value } return nil } var nodeSetValue: XMLNodeSet { return nodeSet ?? XMLNodeSet() } var boolValue: Swift.Bool { return bool ?? false } var numberValue: Double { return number ?? 0.0 } var stringValue: Swift.String { return string ?? "" } } extension XPathObject: Sequence { public typealias Iterator = AnyIterator<XMLElement> public func makeIterator() -> Iterator { var index = 0 return AnyIterator { if index < self.nodeSetValue.count { let obj = self.nodeSetValue[index] index += 1 return obj } return nil } } }
mit
f5cd57846436186058ec3552367621e3
26.740157
149
0.618223
4.317402
false
false
false
false
SheffieldKevin/SwiftGraphics
SwiftGraphics/Generic Types/GenericGeometryTypes.swift
1
3657
// // IntGeometry.swift // SwiftGraphics // // Created by Jonathan Wight on 1/16/15. // Copyright (c) 2015 schwa.io. All rights reserved. // // MARK: A generic arithmetic type. /* Note this seems to cause the compiler to get very unhappy when inferring types and complain about. You'll see errors like: "error: expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions" To fix this specify the type explicitly so the compiler no longer needs to infer. Look for this comment to see places where I've had to do this: "(Unnecessarily specify CGFloat to prevent compiler from complaining about complexity while inferring type)" */ import CoreGraphics public protocol ArithmeticType: Comparable { func + (lhs: Self, rhs: Self) -> Self func - (lhs: Self, rhs: Self) -> Self func * (lhs: Self, rhs: Self) -> Self func / (lhs: Self, rhs: Self) -> Self } extension Int: ArithmeticType { } extension UInt: ArithmeticType { } extension CGFloat: ArithmeticType { } // MARK: Protocols with associated types /* Due to a bug with Swift (http: //openradar.appspot.com/myradars/edit?id=5241213351362560) we cannot make CG types conform to these protocols. Ideally instead of using CGPoint and friends we could just use PointType and our code would work with all types. */ public protocol PointType { associatedtype ScalarType var x: ScalarType { get } var y: ScalarType { get } } public protocol SizeType { associatedtype ScalarType var width: ScalarType { get } var height: ScalarType { get } } public protocol RectType { associatedtype OriginType associatedtype SizeType var origin: OriginType { get } var size: SizeType { get } } // MARK: Generic Points public struct GenericPoint <T: ArithmeticType> { public let x: T public let y: T public init(x: T, y: T) { self.x = x self.y = y } } extension GenericPoint: PointType { public typealias ScalarType = T } // MARK: Generic Sizes public struct GenericSize <T: ArithmeticType> { public let width: T public let height: T public init(width: T, height: T) { self.width = width self.height = height } } extension GenericSize: SizeType { public typealias ScalarType = T } // MARK: Generic Rects public struct GenericRect <T: PointType, U: SizeType> { public let origin: T public let size: U public init(origin: T, size: U) { self.origin = origin self.size = size } } extension GenericRect: RectType { public typealias OriginType = T public typealias SizeType = U } // MARK: Specialisations of Generic geometric types for Integers. public typealias IntPoint = GenericPoint<Int> public typealias IntSize = GenericSize<Int> public typealias IntRect = GenericRect<IntPoint, IntSize> public typealias UIntPoint = GenericPoint <UInt> public typealias UIntSize = GenericSize <UInt> public typealias UIntRect = GenericRect<UIntPoint, UIntSize> // MARK: Extensions extension GenericPoint: Equatable { } public func == <T> (lhs: GenericPoint <T>, rhs: GenericPoint <T>) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } extension GenericSize: Equatable { } public func == <T> (lhs: GenericSize <T>, rhs: GenericSize <T>) -> Bool { return lhs.width == rhs.width && lhs.height == rhs.height } // TODO: Need more generic magic //extension GenericRect: Equatable { //} //public func == <T,U> (lhs: GenericRect <T,U>, rhs: GenericRect <T,U>) -> Bool { // return lhs.origin == rhs.origin && lhs.size == rhs.size //}
bsd-2-clause
ad68fa276a0773e9a5602e9a8ae6a8b2
23.877551
175
0.688543
3.75462
false
false
false
false
AnRanScheme/magiGlobe
magi/magiGlobe/magiGlobe/Classes/Tool/Extension/UIKit/UIApplication/UIApplication+Man.swift
1
3049
// // UIApplication+Man.swift // swift-magic // // Created by 安然 on 17/2/15. // Copyright © 2017年 安然. All rights reserved. // import UIKit public extension UIApplication{ public var m_applicationFileSize: String { func sizeOfFolderPath(_ folderPath: String) -> Int64 { let contents: [String]? do { contents = try FileManager.default.contentsOfDirectory(atPath: folderPath) } catch _ { contents = nil } var folderSize: Int64 = 0 if let tempContents = contents{ for file in tempContents { let dict = try? FileManager.default.attributesOfItem(atPath: (folderPath as NSString).appendingPathComponent(file)) if dict != nil { folderSize += (dict![FileAttributeKey.size] as? Int64) ?? 0 } } } return folderSize } let docSize = sizeOfFolderPath(self.m_documentPath) let libSzie = sizeOfFolderPath(self.m_libraryPath) let cacheSize = sizeOfFolderPath(self.m_cachePath) let total = docSize + libSzie + cacheSize + cacheSize let folderSizeStr = ByteCountFormatter.string(fromByteCount: total, countStyle: .file) return folderSizeStr } public var m_documentPath: String { let dstPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! return dstPath } public var m_libraryPath: String { let dstPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! return dstPath } public var m_cachePath: String { let dstPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! return dstPath } } /* - (NSString *)ez_applicationFileSize{ unsigned long long docSize = [self __ez_sizeOfFolder:[self __ez_documentPath]]; unsigned long long libSize = [self __ez_sizeOfFolder:[self __ez_libraryPath]]; unsigned long long cacheSize = [self __ez_sizeOfFolder:[self __ez_cachePath]]; unsigned long long total = docSize + libSize + cacheSize; NSString *folderSizeStr = [NSByteCountFormatter stringFromByteCount:total countStyle:NSByteCountFormatterCountStyleFile]; return folderSizeStr; } -(unsigned long long)__ez_sizeOfFolder:(NSString *)folderPath { NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:nil]; NSEnumerator *contentsEnumurator = [contents objectEnumerator]; NSString *file; unsigned long long folderSize = 0; while (file = [contentsEnumurator nextObject]) { NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[folderPath stringByAppendingPathComponent:file] error:nil]; folderSize += [[fileAttributes objectForKey:NSFileSize] intValue]; } return folderSize; } */
mit
a22b96bda51bcc38821bc1f5949b24d9
31.666667
147
0.654707
4.972177
false
false
false
false
marcdaywalker/MMACodeReader
MMACodeReader/MMACodeReader/MMACodeReader/MMACodeReader.swift
1
5841
// // MMACodeReader.swift // import UIKit import AVFoundation protocol MMACodeReaderDelegate { func reader (reader: MMACodeReader, didRead value: String) func readerDidFailRead (reader: MMACodeReader) func readerDidRejectAccess (reader: MMACodeReader) } public class MMACodeReader: UIView { var avCaptureSession = AVCaptureSession() var avCaptureVideoPreviewLayer:AVCaptureVideoPreviewLayer? var codeView = UIView() var enableRecognition = true @IBOutlet weak var delegate : NSObject? private var readerDelegate : MMACodeReaderDelegate? { return delegate as? MMACodeReaderDelegate } public init() { super.init(frame: CGRectZero) setupUI() } public override init(frame: CGRect) { super.init(frame: frame) setupUI() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } public override func awakeFromNib() { setupUI() } override public func layoutSubviews() { avCaptureVideoPreviewLayer?.frame = self.layer.bounds } private func setupUI (){ let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) if status == AVAuthorizationStatus.Authorized { setupCamera() } else if status == AVAuthorizationStatus.NotDetermined { AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) -> Void in NSOperationQueue.mainQueue().addOperationWithBlock({ if granted { self.setupCamera() } else { self.readerDelegate?.readerDidRejectAccess(self) } }) }) } else { readerDelegate?.readerDidRejectAccess(self) } } private func setupCamera() { let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) do { // Get an instance of the AVCaptureDeviceInput class using the previous device object. let input = try AVCaptureDeviceInput(device: captureDevice) avCaptureSession.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() avCaptureSession.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode] avCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: avCaptureSession) avCaptureVideoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill self.layer.addSublayer(avCaptureVideoPreviewLayer!) avCaptureSession.startRunning() codeView.layer.borderColor = UIColor.redColor().CGColor codeView.layer.borderWidth = 4 self.addSubview(codeView) } catch { // If any error occurs, simply print it out and don't continue any more. print(error) return } } func startCamera () { if let output = avCaptureSession.outputs.first { output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) } } func stopCamera () { if let output = avCaptureSession.outputs.first { output.setMetadataObjectsDelegate(nil, queue: dispatch_get_main_queue()) } codeView.frame = CGRectZero } func pauseCamera () { self.avCaptureVideoPreviewLayer?.connection.enabled = false if let output = avCaptureSession.outputs.first { output.setMetadataObjectsDelegate(nil, queue: dispatch_get_main_queue()) } } func resumeCamera() { avCaptureVideoPreviewLayer?.connection.enabled = true startCamera() codeView.frame = CGRectZero } } extension MMACodeReader: AVCaptureMetadataOutputObjectsDelegate { public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if !enableRecognition { return } if let metadataObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject { if metadataObj.type == AVMetadataObjectTypeQRCode { let barCodeObject = avCaptureVideoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj) if CGRectContainsRect(bounds, barCodeObject!.bounds) { codeView.frame = barCodeObject!.bounds if metadataObj.stringValue != nil { self.pauseCamera() delay(1, closure: { self.readerDelegate?.reader(self, didRead: metadataObj.stringValue) }) } } } } else { codeView.frame = CGRectZero readerDelegate?.readerDidFailRead(self) } } private func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } }
mit
8e2134e415027993a9a127312cf10c3b
35.279503
372
0.626947
5.905966
false
false
false
false
nostramap/nostra-sdk-sample-ios
RouteSample/Swift/RouteSample/RouteDetailViewController.swift
1
1350
// // RouteDetailViewController.swift // RouteSample // // Copyright © 2559 Globtech. All rights reserved. // import UIKit import NOSTRASDK import ArcGIS class RouteDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var directions: [NTDirection]! = nil; override func viewDidLoad() { super.viewDidLoad(); tableView.estimatedRowHeight = 44.0; tableView.rowHeight = UITableViewAutomaticDimension; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell"); let direction = directions[indexPath.row]; let lblDirection = cell?.viewWithTag(101) as! UILabel; let lblLength = cell?.viewWithTag(102) as! UILabel; lblDirection.text = direction.text; lblLength.text = String.init(format: "%.1f Km.", direction.length / 1000); return cell!; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return directions != nil ? directions.count : 0; } func numberOfSections(in tableView: UITableView) -> Int { return 1; } }
apache-2.0
bcfb8f24dded36dfd0746219d37d5430
27.104167
100
0.646405
5.109848
false
false
false
false
PlutoMa/SwiftProjects
027.Carousel Effect/CarouselEffect/CarouselEffect/CustomCollectionViewLayout.swift
1
2310
// // CustomCollectionViewLayout.swift // CarouselEffect // // Created by Dareway on 2017/11/7. // Copyright © 2017年 Pluto. All rights reserved. // import UIKit class CustomCollectionViewLayout: UICollectionViewFlowLayout { var itemWH: CGFloat! var inset: CGFloat! override func prepare() { super.prepare() let collectionW = self.collectionView?.frame.size.width let collectionH = self.collectionView?.frame.size.height self.itemSize = CGSize(width: collectionW! * 0.5, height: collectionW! * 0.6) let leftRight = (collectionW! - self.itemSize.width) * 0.5 let topBottom = (collectionH! - self.itemSize.height) * 0.5 self.sectionInset = UIEdgeInsetsMake(topBottom, leftRight, topBottom, leftRight) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var lastRect = CGRect() lastRect.size = (self.collectionView?.frame.size)! lastRect.origin = proposedContentOffset; let centerX = proposedContentOffset.x + (self.collectionView?.frame.size.width)! * 0.5 var adjustX = MAXFLOAT let array = self.layoutAttributesForElements(in: lastRect) for attr in array! { if (abs(Float(attr.center.x - centerX)) < abs(adjustX)) { adjustX = Float(attr.center.x - centerX) } } return CGPoint(x: proposedContentOffset.x + CGFloat(adjustX), y: proposedContentOffset.y) } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let newArr = super.layoutAttributesForElements(in: rect) let collectionViewCenterX = (self.collectionView?.frame.size.width)! * 0.5 + (self.collectionView?.contentOffset.x)! for attributes in newArr! { let scale = 1 - abs(attributes.center.x - collectionViewCenterX) / (self.collectionView?.frame.size.width)! * 0.5; attributes.transform = CGAffineTransform(scaleX: scale, y: scale); } return newArr } }
mit
66ec0e3a0eebf3418f6d116bdb0860ba
37.45
148
0.65453
4.660606
false
false
false
false
lYcHeeM/ZJImageBrowser
ZJImageBrowser/ZJImageBrowser/ZJImageCell.swift
1
21723
// // ZJImageCell.swift // ProgressView // // Created by luozhijun on 2017/7/5. // Copyright © 2017年 RickLuo. All rights reserved. // import UIKit import Photos import PhotosUI import SDWebImage class ZJImageCell: UICollectionViewCell { static let reuseIdentifier = "ZJImageCell" fileprivate var scrollView : UIScrollView = UIScrollView() fileprivate var imageView : UIImageView = UIImageView() fileprivate var progressView: ZJProgressView! fileprivate var retryButton : UIButton! fileprivate var imageWrapper: ZJImageWrapper? fileprivate var livePhotoView: UIView! #if DEBUG fileprivate var hud: ZJImageBrowserHUD? #endif /// urlMap, 用于和图片url字符串的hashValue做对比, 目的是防止下载图片过程中滑动到其他页面(cell)时, 下载进度回调被交叉执行。 /// 因为,一旦imageView被重用, 则滑动之前的下载进度回调和滑动之后的下载进度回调会在同一个cell中交叉触发(如果都在同一个线程中的话)。 /// 图片下载完成时, 设置图片等操作之前对urlMap的检验同理。 /// Apple文档说"hashValue"不能保证在不同的App启动环境中得到相同的结果, 并不影响此处的检验. /// Use to compare to the hash value of url string, in order to avoid 'progress' call back excuting crossly when scrolling pages. /// Because of reusing mechanism, onece 'imageView' is reused, the 'progress' call back of previous image downing and the 'progress' call back of the current image downing will execute in the same cell crossly (or concurrently). /// The same checking will be done in the 'completeion' call back. fileprivate var urlMap: Int = -1 fileprivate var imageRequestId: PHImageRequestID? var imageContainer: UIImageView { return imageView } /// 注意: 此闭包将不在主线程执行 /// Note: this closure excutes in global queue. var imageQueryingFinished: ((Bool, UIImage?) -> Swift.Void)? var singleTapped : ((UITapGestureRecognizer) -> Swift.Void)? var imageDragedDistanceChanged: ((ZJImageCell, CGFloat) -> Swift.Void)? var imageDragingEnd : ((ZJImageCell, Bool) -> Swift.Void)? fileprivate weak var singleTapGesture: UITapGestureRecognizer? fileprivate var imageViewOriginalFrame: CGRect = .zero fileprivate var imageViewOriginalCenter: CGPoint = .zero /// 拖动距离与宽度的比 fileprivate var dragedDistanceRatio: CGFloat = 0 var image: UIImage? { didSet { guard oldValue != image else { return } adjustSubviewFrames() } } override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - Setup UI extension ZJImageCell { override func layoutSubviews() { super.layoutSubviews() scrollView.frame = CGRect(x: 0, y: 0, width: frame.width - ZJImageBrowser.pageSpacing, height: frame.height) if let retryButton = retryButton { retryButton.frame.origin = CGPoint(x: ZJImageBrowser.buttonHorizontalPadding, y: frame.size.height - ZJImageBrowser.buttonVerticalPadding - ZJImageBrowser.buttonHeight) retryButton.frame.size.height = ZJImageBrowser.buttonHeight } adjustSubviewFrames() } override func prepareForReuse() { #if DEBUG hud?.hide(animated: false) hud = nil #endif progressView?.removeFromSuperview() progressView = nil super.prepareForReuse() } fileprivate func setupSubviews() { let singleTap = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap)) singleTap.delaysTouchesBegan = true let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)) doubleTap.numberOfTapsRequired = 2 singleTap.require(toFail: doubleTap) singleTapGesture = singleTap contentView.addSubview(scrollView) scrollView.backgroundColor = UIColor.clear scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.delegate = self scrollView.addGestureRecognizer(singleTap) scrollView.addGestureRecognizer(doubleTap) scrollView.addSubview(imageView) imageView.isUserInteractionEnabled = true imageView.contentMode = .scaleAspectFill let pangesture = UIPanGestureRecognizer(target: self, action: #selector(handlePangesture)) scrollView.addGestureRecognizer(pangesture) pangesture.delegate = self } fileprivate func setupRetryButton() { guard retryButton == nil else { return } retryButton = UIButton(type: .system) retryButton.isHidden = true retryButton.setTitle(" \(ZJImageBrowser.retryButtonTitle) ", for: .normal) retryButton.titleLabel?.font = UIFont.systemFont(ofSize: 12) retryButton.tintColor = UIColor.white retryButton.layer.cornerRadius = 3 retryButton.layer.borderWidth = 1.5/UIScreen.main.scale retryButton.layer.borderColor = UIColor.white.cgColor retryButton.backgroundColor = UIColor(white: 0, alpha: 0.5) retryButton.sizeToFit() retryButton.addTarget(self, action: #selector(retryButtonClicked), for: .touchUpInside) contentView.addSubview(retryButton) retryButton.frame.origin = CGPoint(x: ZJImageBrowser.buttonHorizontalPadding, y: frame.size.height - ZJImageBrowser.buttonVerticalPadding - ZJImageBrowser.buttonHeight) } fileprivate func adjustSubviewFrames() { if let image = image { // 使imageView宽度和屏慕宽度保持一致, 宽高比和图片的宽高比一致 // Make enlargingViewEndFrame's width equals to screen width, and its aspect ratio the same as its inner image; imageView.frame.size.width = scrollView.frame.width imageView.frame.size.height = imageView.frame.width * (image.size.height/image.size.width) scrollView.contentSize = imageView.frame.size imageView.center = scrollViewContentCenter //CGPoint(x: frame.width/2, y: frame.height/2) imageView.image = image // 根据图片大小找到合适的放大系数,放大图片时不留黑边 // Find a appropriate zoom scale according to the imageView size in order to // 先设置为高度放大系数 // By default, set 'maxZoomScale' as height zoom scale. var maxZoomScale: CGFloat = scrollView.frame.height / imageView.frame.height let widthZoomScale = scrollView.frame.width/imageView.frame.width // 如果小于宽度放大系数, 则设为宽度放大系数 // If height zoom scale were less than width zoom scale, then use width zoom scale. if maxZoomScale < widthZoomScale { maxZoomScale = widthZoomScale } // 如果小于设定的放大系数, 即设定的放大系数已足够令屏幕不留黑边时, 直接用设定的放大系数即可. // Finally, if the computed max zoom scale were less than the preset value "maximumZoomScale", then discard it. if maxZoomScale < ZJImageBrowser.maximumZoomScale { maxZoomScale = ZJImageBrowser.maximumZoomScale } scrollView.minimumZoomScale = 1 scrollView.maximumZoomScale = maxZoomScale scrollView.zoomScale = 1 } else { imageView.frame.size.width = scrollView.frame.width imageView.frame.size.height = imageView.frame.width imageView.center = CGPoint(x: scrollView.frame.width/2, y: scrollView.frame.height/2) } scrollView.contentOffset = .zero } /// 默认情况下, scrollView放大其子视图后会改变contentSize, 当contentSize小于scrollView.bounds.size时, 有可能使子视图不居中(比如令图片往下掉) /// By default, UIScrollView usually change its 'contentSize' after zooming subviews, and when 'contentSize < scrollView.bounds.size', zoomed subviews may shift (such as a familiar phenomenon: centered image would drop down if you do nothing). So we should get the real cotnetCenter of scrollView. fileprivate var scrollViewContentCenter: CGPoint { var offsetX: CGFloat = 0 var offsetY: CGFloat = 0 if scrollView.frame.width > scrollView.contentSize.width { offsetX = (scrollView.frame.width - scrollView.contentSize.width) * 0.5 } if scrollView.frame.height > scrollView.contentSize.height { offsetY = (scrollView.frame.height - scrollView.contentSize.height) * 0.5 } return CGPoint(x: scrollView.contentSize.width * 0.5 + offsetX, y: scrollView.contentSize.height * 0.5 + offsetY) } } extension ZJImageCell { private func setupProgressView(with style: ZJProgressViewStyle) { progressView?.removeFromSuperview() let progressViewSize: CGFloat = 50 let progressViewFrame = CGRect(x: (frame.width - progressViewSize)/2, y: (frame.height - progressViewSize)/2, width: progressViewSize, height: progressViewSize) progressView = ZJProgressView(frame: progressViewFrame, style: style) contentView.addSubview(progressView) } func setImage(with imageWrapper: ZJImageWrapper) { self.imageWrapper = imageWrapper if let image = imageWrapper.image { self.image = image return } if let asset = imageWrapper.asset { if let imageRequestId = imageRequestId, imageRequestId != PHInvalidImageRequestID { asset.cancelRequest(by: imageRequestId) } setupProgressView(with: imageWrapper.progressStyle) urlMap = asset.hashValue asset.originalImage(shouldSynchronous: false, progress: { fraction, error, stop, info in guard let asset = self.imageWrapper?.asset, self.urlMap == asset.hashValue else { return } self.progressView?.progress = CGFloat(fraction) }, completion: { (image, info) in guard let asset = self.imageWrapper?.asset, self.urlMap == asset.hashValue else { return } self.progressView?.removeFromSuperview() self.image = image guard let error = info?[PHImageErrorKey] as? NSError else { return } if let isIniCloud = info?[PHImageResultIsInCloudKey] as? Bool, isIniCloud { let fullScreenSize = UIScreen.main.bounds.size.width * UIScreen.main.scale asset.image(shouldSynchronous: false, size: CGSize(width: fullScreenSize, height: fullScreenSize), completion: { (image, info) in guard let asset = self.imageWrapper?.asset, self.urlMap == asset.hashValue else { return } self.image = image }) } else { var errorMsg = error.userInfo["ErrorMessage:"] as? String if errorMsg == nil || errorMsg?.isEmpty == true { if let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError { errorMsg = underlyingError.localizedDescription } else { errorMsg = error.localizedDescription } } if errorMsg == nil || errorMsg?.isEmpty == true, let isIniCloud = info?[PHImageResultIsInCloudKey] as? Bool, isIniCloud { errorMsg = ZJImageBrowser.imageHavenotBeenDownloadedFromIcloudHint } if errorMsg?.isEmpty == false { ZJImageBrowserHUD.show(message: errorMsg, inView: self.scrollView, animated: true, needsIndicator: false, hideAfter: 3) } } }) return } guard let usingUrl = URL(string: imageWrapper.highQualityImageUrl) else { return } var placeholderImage = imageWrapper.placeholderImage if placeholderImage == nil { placeholderImage = bundleImage(named: "whiteplaceholder") } retryButton?.isHidden = true progressView?.removeFromSuperview() urlMap = imageWrapper.highQualityImageUrl.hashValue image = placeholderImage guard imageWrapper.shouldDownloadImage else { SDImageCache.shared().queryDiskCache(forKey: imageWrapper.highQualityImageUrl, done: { (image, cacheType) in guard let cachedImage = image else { #if DEBUG if ZJImageBrowser.showsDebugHud { self.hud = ZJImageBrowserHUD.show(message: "Won't download the large image, cause 'shouldDownloadImage' is false.", inView: self.scrollView, animated: true, needsIndicator: false, hideAfter: 3) } #endif return } guard self.urlMap == imageWrapper.highQualityImageUrl.hashValue else { return} DispatchQueue.main.async(execute: { self.image = cachedImage }) }) return } setupProgressView(with: imageWrapper.progressStyle) // 注意到imageView.sd_setImage方法会在开头cancel掉当前imageView关联的上一次下载, // 当cell被重用时, 意味着imageView被重用, 则切换图片时很可能会取消正在下载图片, // 导致重新滑到之前的页面会重新开启下载线程, 浪费资源, 故此处不用该方法. // Realizing 'imageView.sd_setImage...' function cancels previous image downloading which bounds to 'imageView', // thus when cell is resued, it means imageView is reused, switching page would quite likely cancel the downloading progress. What's more, when we scroll to the that page again, a new downloading of the same image would be start. It's quite a waste of resources, so I use 'downloadImage' instead of 'sd_setImage...'. SDWebImageManager.shared().downloadImage(with: usingUrl, options: [.retryFailed], progress: { [weak self] (receivedSize, expectedSize) in // 校验urlMap是防止下载图片过程中滑动到其他页面(cell)时, 下载进度回调被交叉执行。 // 因为,一旦imageView被重用, 则滑动之前的下载进度回调和滑动之后的下载进度回调会在同一个cell中交叉触发(如果都在同一个线程中的话)。 // 图片下载完成时, 设置图片等操作之前对urlMap的检验同理。 // Check 'urlMap' to avoid 'progress' call back excuting crossly when scrolling pages. // Because of reusing mechanism, onece 'imageView' is reused, the 'progress' call back of previous image downing and the 'progress' call back of the current image downing will execute in the same cell crossly (or concurrently). // The same checking will be done in the 'completeion' call back. guard self != nil, self!.urlMap == imageWrapper.highQualityImageUrl.hashValue else { return } let progress = CGFloat(receivedSize)/CGFloat(expectedSize) self?.progressView?.progress = progress }) { [weak self] (image, error, cacheType, finished, imageUrl) in guard self != nil, self!.urlMap == imageWrapper.highQualityImageUrl.hashValue, finished else { return } DispatchQueue.main.async(execute: { if let usingImage = image { self?.image = usingImage } self?.progressView?.removeFromSuperview() if error != nil { self?.setupRetryButton() self?.retryButton.isHidden = false } }) self?.imageQueryingFinished?(error == nil, image) } } } //MARK: - UIScrollViewDelegate extension ZJImageCell: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { if #available(iOS 9.1, *), let livePhotoView = livePhotoView, let asset = imageWrapper?.asset, asset.mediaSubtypes == .photoLive { return livePhotoView } else { return imageView } } func scrollViewDidZoom(_ scrollView: UIScrollView) { // 默认情况下, scrollView放大其子视图后会改变contentSize, 当contentSize小于scrollView.bounds.size时, 有可能使子视图不居中(比如令图片往下掉) // By default, UIScrollView usually change its 'contentSize' after zooming subviews, and when 'contentSize < scrollView.bounds.size', zoomed subviews may shift (such as a familiar phenomenon: centered image would drop down if you do nothing). imageView.center = scrollViewContentCenter } } //MARK: - handle events extension ZJImageCell: UIGestureRecognizerDelegate { @objc fileprivate func handleSingleTap(recognizer: UITapGestureRecognizer) { if scrollView.zoomScale > scrollView.minimumZoomScale { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true) } singleTapped?(recognizer) } @objc fileprivate func handleDoubleTap(recognizer: UITapGestureRecognizer) { // 图片加载过程中不允许放大 // Invalidate zooming when image is loading. if progressView?.superview != nil { return } let touchPoint = recognizer.location(in: contentView) if scrollView.zoomScale <= scrollView.minimumZoomScale { let pointX = touchPoint.x + scrollView.contentOffset.x let pointY = touchPoint.y + scrollView.contentOffset.y scrollView.zoom(to: CGRect(x: pointX, y: pointY, width: 10, height: 10), animated: true) } else { scrollView.setZoomScale(scrollView.minimumZoomScale, animated: true) } } /// 实现图片拖拽缩放,并且,拖到一定程度可以关闭整个图片浏览器 @objc fileprivate func handlePangesture(recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .began: imageViewOriginalFrame = imageView.frame imageViewOriginalCenter = imageView.center case .changed: let point = recognizer.translation(in: scrollView) let dragedDistance = sqrt(point.x * point.x + point.y * point.y) dragedDistanceRatio = dragedDistance / imageViewOriginalFrame.width var sizeScale = 1 - dragedDistanceRatio if sizeScale < 0.67 { sizeScale = 0.67 } imageView.center = CGPoint(x: imageViewOriginalCenter.x + point.x, y: imageViewOriginalCenter.y + point.y) imageView.frame.size = CGSize(width: imageViewOriginalFrame.width * sizeScale, height: imageViewOriginalFrame.height * sizeScale) imageDragedDistanceChanged?(self, dragedDistanceRatio) case .ended: var shouldResetFrame = false if dragedDistanceRatio > 0.45 { if imageDragingEnd == nil { shouldResetFrame = true } } else { shouldResetFrame = true } if shouldResetFrame { UIView.animate(withDuration: 0.25, animations: { self.imageView.frame = self.imageViewOriginalFrame }) } imageDragingEnd?(self, !shouldResetFrame) default: return } } @objc fileprivate func retryButtonClicked() { retryButton.isHidden = true if let imageWrapper = imageWrapper { setImage(with: imageWrapper) } } /// 由于scrollView自带一个用于双向滚动的panGesture, 而为了在向下拖拽的图片区域时候,实现令图片跟踪触摸处并缩放图片的效果,需要再加一个panGesture, 显然这两个panGesture会发生冲突(后来居上,实践发现第二个panGesture的优先级高),所以给第二个panGesture设置了代理,通过下面的方法来限制第二个panGesture的生效范围:3点,1.触摸位置在图片内; 2.scrollView没有被放大;3.垂直方向的距离达到一定值,经过多次测试,1.2是比较合适的值。 override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { singleTapGesture?.isEnabled = false defer { singleTapGesture?.isEnabled = true } if let pan = gestureRecognizer as? UIPanGestureRecognizer { let point = pan.translation(in: imageView) // let point1 = pan.translation(in: scrollView) // let point2 = pan.location(in: imageView) // let point3 = pan.location(in: scrollView) let pointInImageView = imageView.frame.contains(pan.location(in: scrollView)) // print(point, point1, point2, point3, pointInImageView) return pointInImageView && scrollView.zoomScale <= 1 && point.y > 1.2 } return false } }
mit
ed7b9ce72d6e87f87f5eab0c366618a0
48.153285
324
0.643055
4.763499
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/NaturalLanguageUnderstandingV1/Models/Features.swift
1
9135
/** * (C) Copyright IBM Corp. 2022. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import IBMSwiftSDKCore /** Analysis features and options. */ public struct Features: Codable, Equatable { /** Returns text classifications for the content. */ public var classifications: ClassificationsOptions? /** Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. */ public var concepts: ConceptsOptions? /** Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. */ public var emotion: EmotionOptions? /** Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. */ public var entities: EntitiesOptions? /** Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. */ public var keywords: KeywordsOptions? /** Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. */ public var metadata: [String: JSON]? /** Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. */ public var relations: RelationsOptions? /** Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. */ public var semanticRoles: SemanticRolesOptions? /** Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. */ public var sentiment: SentimentOptions? /** (Experimental) Returns a summary of content. Supported languages: English only. */ public var summarization: SummarizationOptions? /** Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. */ public var categories: CategoriesOptions? /** Returns tokens and sentences from the input text. */ public var syntax: SyntaxOptions? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case classifications = "classifications" case concepts = "concepts" case emotion = "emotion" case entities = "entities" case keywords = "keywords" case metadata = "metadata" case relations = "relations" case semanticRoles = "semantic_roles" case sentiment = "sentiment" case summarization = "summarization" case categories = "categories" case syntax = "syntax" } /** Initialize a `Features` with member variables. - parameter classifications: Returns text classifications for the content. - parameter concepts: Returns high-level concepts in the content. For example, a research paper about deep learning might return the concept, "Artificial Intelligence" although the term is not mentioned. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - parameter emotion: Detects anger, disgust, fear, joy, or sadness that is conveyed in the content or by the context around target phrases specified in the targets parameter. You can analyze emotion for detected entities with `entities.emotion` and for keywords with `keywords.emotion`. Supported languages: English. - parameter entities: Identifies people, cities, organizations, and other entities in the content. For more information, see [Entity types and subtypes](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-entity-types). Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. Arabic, Chinese, and Dutch are supported only through custom models. - parameter keywords: Returns important keywords in the content. Supported languages: English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish, Swedish. - parameter metadata: Returns information from the document, including author name, title, RSS/ATOM feeds, prominent page image, and publication date. Supports URL and HTML input types only. - parameter relations: Recognizes when two entities are related and identifies the type of relation. For example, an `awardedTo` relation might connect the entities "Nobel Prize" and "Albert Einstein". For more information, see [Relation types](https://cloud.ibm.com/docs/natural-language-understanding?topic=natural-language-understanding-relations). Supported languages: Arabic, English, German, Japanese, Korean, Spanish. Chinese, Dutch, French, Italian, and Portuguese custom models are also supported. - parameter semanticRoles: Parses sentences into subject, action, and object form. Supported languages: English, German, Japanese, Korean, Spanish. - parameter sentiment: Analyzes the general sentiment of your content or the sentiment toward specific target phrases. You can analyze sentiment for detected entities with `entities.sentiment` and for keywords with `keywords.sentiment`. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Russian, Spanish. - parameter summarization: (Experimental) Returns a summary of content. Supported languages: English only. - parameter categories: Returns a hierarchical taxonomy of the content. The top three categories are returned by default. Supported languages: Arabic, English, French, German, Italian, Japanese, Korean, Portuguese, Spanish. - parameter syntax: Returns tokens and sentences from the input text. - returns: An initialized `Features`. */ public init( classifications: ClassificationsOptions? = nil, concepts: ConceptsOptions? = nil, emotion: EmotionOptions? = nil, entities: EntitiesOptions? = nil, keywords: KeywordsOptions? = nil, metadata: [String: JSON]? = nil, relations: RelationsOptions? = nil, semanticRoles: SemanticRolesOptions? = nil, sentiment: SentimentOptions? = nil, summarization: SummarizationOptions? = nil, categories: CategoriesOptions? = nil, syntax: SyntaxOptions? = nil ) { self.classifications = classifications self.concepts = concepts self.emotion = emotion self.entities = entities self.keywords = keywords self.metadata = metadata self.relations = relations self.semanticRoles = semanticRoles self.sentiment = sentiment self.summarization = summarization self.categories = categories self.syntax = syntax } }
apache-2.0
c05a65f7d74b39f4f064a0cea7b5a639
46.827225
127
0.711877
4.830777
false
false
false
false
dreamsxin/swift
test/expr/unary/selector/selector.swift
2
3669
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -disable-objc-attr-requires-foundation-module -parse %s -verify import ObjectiveC // REQUIRES: objc_interop @objc class A { } @objc class B { } class C1 { @objc init(a: A, b: B) { } @objc func method1(_ a: A, b: B) { } @objc(someMethodWithA:B:) func method2(_ a: A, b: B) { } @objc class func method3(_ a: A, b: B) { } // expected-note{{found this candidate}} @objc class func method3(a: A, b: B) { } // expected-note{{found this candidate}} @objc func getC1() -> AnyObject { return self } @objc func testUnqualifiedSelector(_ a: A, b: B) { _ = #selector(testUnqualifiedSelector(_:b:)) let testUnqualifiedSelector = 1 _ = #selector(testUnqualifiedSelector(_:b:)) _ = testUnqualifiedSelector // suppress unused warning } @objc func testParam(_ testParam: A) { // expected-note{{'testParam' declared here}} _ = #selector(testParam) // expected-error{{argument of '#selector' cannot refer to parameter 'testParam'}} } @objc func testVariable() { let testVariable = 1 // expected-note{{'testVariable' declared here}} _ = #selector(testVariable) // expected-error{{argument of '#selector' cannot refer to variable 'testVariable'}} } } @objc protocol P1 { func method4(_ a: A, b: B) static func method5(_ a: B, b: B) } extension C1 { final func method6() { } // expected-note{{add '@objc' to expose this instance method to Objective-C}}{{3-3=@objc }} } func testSelector(_ c1: C1, p1: P1, obj: AnyObject) { // Instance methods on an instance let sel1 = #selector(c1.method1) _ = #selector(c1.method1(_:b:)) _ = #selector(c1.method2) // Instance methods on a class. _ = #selector(C1.method1) _ = #selector(C1.method1(_:b:)) _ = #selector(C1.method2) // Class methods on a class. _ = #selector(C1.method3(_:b:)) _ = #selector(C1.method3(a:b:)) // Methods on a protocol. _ = #selector(P1.method4) _ = #selector(P1.method4(_:b:)) _ = #selector(P1.method5) // expected-error{{static member 'method5' cannot be used on protocol metatype 'P1.Protocol'}} _ = #selector(P1.method5(_:b:)) // expected-error{{static member 'method5(_:b:)' cannot be used on protocol metatype 'P1.Protocol'}} _ = #selector(p1.method4) _ = #selector(p1.method4(_:b:)) _ = #selector(p1.dynamicType.method5) _ = #selector(p1.dynamicType.method5(_:b:)) // Interesting expressions that refer to methods. _ = #selector(Swift.AnyObject.method1) _ = #selector(AnyObject.method1!) _ = #selector(obj.getC1?().method1) // Initializers _ = #selector(C1.init(a:b:)) // Make sure the result has type "ObjectiveC.Selector" let sel2: Selector sel2 = sel1 _ = sel2 } func testAmbiguity() { _ = #selector(C1.method3) // expected-error{{ambiguous use of 'method3(_:b:)'}} } func testUnusedSelector() { #selector(C1.getC1) // expected-warning{{result of '#selector' is unused}} } func testNonObjC(_ c1: C1) { _ = #selector(c1.method6) // expected-error{{argument of '#selector' refers to instance method 'method6()' that is not exposed to Objective-C}} } func testParseErrors1() { _ = #selector foo // expected-error{{expected '(' following '#selector'}} } func testParseErrors2() { _ = #selector( // expected-error{{expected expression naming a method within '#selector(...)'}} } func testParseErrors3(_ c1: C1) { _ = #selector( // expected-note{{to match this opening '('}} c1.method1(_:b:) // expected-error{{expected ')' to complete '#selector' expression}} } func testParseErrors4() { // Subscripts _ = #selector(C1.subscript) // expected-error{{type 'C1.Type' has no subscript members}} }
apache-2.0
95d668a53db07a1562570a681a63d16d
31.469027
145
0.653857
3.261333
false
true
false
false
xcs-go/swift-Learning
Optional Chaining.playground/Contents.swift
1
2191
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // 可空链式调用 // 可空链式调用是一种可以请求和调用属性、方法及下标的过程,它的可空性体现于请求或调用的目标当前可能为空。如果可空的目标有值,那么调用就会成功;如果选择的目标为空,那么这种调用将返回空。多个连续的调用可以被链接在一起形成一个调用链,如果其中任何一个节点为空将会导致整个链调用失败。 // 使用可空链式强调来强制展开 // 通过在想调用非空的属性、方法、或下标的可空值后面放一个问号,可以定义一个可空链。 class Person { var residence:Residence? } class Residence { var numberOfRooms = 1 } let john = Person() // 使用!强制展开这个john的residence属性的numberOfRooms值,会出发运行时错误 //let roomCount = john.residence!.numberOfRooms // swift 提供了另一种访问numberOfRooms的方法,使用?来代替原来叹号!的位置 if let roomCount = john.residence?.numberOfRooms { print("\(roomCount)") } else { print("unable to retrieve the number of rooms.") } john.residence = Residence() // 为可空链式调用定义模型类 // 通过使用可空链式调用可以调用多层属性,方法,和下标。这样可以通过各种模型访问各种子属性。并且判断能否访问子属性的属性,方法或下标 class Residences { var rooms = [Room]() var numberOfRooms: Int { return rooms.count } subscript(i:Int) -> Room { get { return rooms[i] } set { rooms[i] = newValue } } func printNumberOfRoom() { print("\(numberOfRooms)") } var address:Address? } class Address { var buildingName: String? var buildingNumber: String? var street: String? func buildingIdentifier() -> String? { if buildingName != nil { return buildingName } else if buildingNumber != nil { return buildingNumber } else { return nil } } }
apache-2.0
283382992a978a918f1f81f2d8a3fdb4
15.880435
141
0.644559
3.215321
false
false
false
false
c0der78/swiftactoe
Sources/SwifTacToe/Console.swift
1
3018
class Console: InputSource, OutputSource { internal var outputBuf = [String]() // MARK: Input Methods // read a line from input // hard to believe straight swift has not much for this internal func readln() -> String { var cstr: [UInt8] = [] var c: Int32 = 0 while c != 4 { c = readChar() if c == 10 || c > 255 { break } cstr.append(UInt8(c)) } // always add trailing zero cstr.append(0) return String(cString: &cstr) } // read a point from input func readMove() throws -> Point? { logger.trace { "reading player move" } let str = readln() return Point.parse(str: str.trim()) } func buffer(_ message: String) { self.outputBuf.append(message) } // MARK: Output Methods func promptMove() { logger.trace { "prompting player move" } self.buffer("Your move: ") } } class ConsoleIO: Console, IO { override init() { print("\u{1B}[f\u{1B}[2J", terminator: "") } // read a player from input func readTile() throws -> Tile? { let str = readln() return Tile.parse(str.trim()) } // MARK: Output Methods private func reset() { print("\u{1B}[H\u{1B}[2J", terminator: "") } func promptTile() { print("Do you want to be X or O (X goes first)? ", terminator: "") } func output(board: Board) { self.reset() self.draw(board: board) if !super.outputBuf.isEmpty { print(super.outputBuf.removeLast(), terminator: "") } flush() } //! display the board to output func draw(board: Board) { // dislay the y coords print("\u{1B}[0m", terminator: "") print(" y 1 2 3") // draw the top of the board printLine(length: 13, leftCorner: "x \u{1B}[1;37m┌", rightCorner: "┐", interval: "┬") for i in 0...board.size - 1 { // draw each line print("\u{1B}[0m\(i+1) ", terminator: "") for j in 0...board.size - 1 { print("\u{1B}[1;37m\u{2502}\u{1B}[1;33m", terminator: "") switch board[i, j] { case Player.o: print(" \u{1B}[1;31mO ", terminator: "") break case Player.x: print(" \u{1B}[1;35mX ", terminator: "") break default: print(" ", terminator: "") break } } print("\u{1B}[1;37m│") if (i + 1) != board.size { printLine(length: 13, leftCorner: " \u{1B}[1;37m├", rightCorner: "┤", interval: "┼") } } // draw the bottom border printLine(length: 13, leftCorner: " \u{1B}[1;37m└", rightCorner: "┘\u{1B}[0m", interval: "┴") } //! handy function to print a line for the board private func printLine( length: Int, leftCorner: String = "+", rightCorner: String = "+", interval: String = "-" ) { print(leftCorner, terminator: "") for i in 0...length - 3 { if (i + 1) % 4 == 0 { print(interval, terminator: "") } else { print("─", terminator: "") } } print(rightCorner) } }
unlicense
6821808513230e012fd1a7ab618aab8e
21.870229
98
0.54506
3.303197
false
false
false
false
diejmon/SugarRecord
library/CoreData/Base/iCloudCDStack.swift
1
15716
// // iCloudCDStack.swift // SugarRecord // // Created by Pedro Piñera Buendía on 12/10/14. // Copyright (c) 2014 SugarRecord. All rights reserved. // import Foundation import CoreData /** * Struct with the needed information to initialize the iCloud stack */ public struct iCloudData { /// Is the full AppID (including the Team Prefix). It's needed to change tihs to match the Team Prefix found in the iOS Provisioning profile internal let iCloudAppID: String /// Is the name of the directory where the database will be stored in. It should always end with .nosync internal let iCloudDataDirectoryName: String// = "Data.nosync" /// Is the name of the directory where the database change logs will be stored in internal let iCloudLogsDirectory: String// = "Logs" /** Note: iCloudData = iCloud + DataDirectory iCloudLogs = iCloud + LogsDirectory */ /** Initializer for the struct :param: iCloudAppID iCloud app identifier :param: iCloudDataDirectoryName Directory of the database :param: iCloudLogsDirectory Directory of the database logs :returns: Initialized struct */ public init (iCloudAppID: String, iCloudDataDirectoryName: String?, iCloudLogsDirectory: String?) { self.iCloudAppID = iCloudAppID if (iCloudDataDirectoryName != nil) { self.iCloudDataDirectoryName = iCloudDataDirectoryName! } else { self.iCloudDataDirectoryName = "Data.nosync" } if (iCloudLogsDirectory != nil) { self.iCloudLogsDirectory = iCloudLogsDirectory! } else { self.iCloudLogsDirectory = "Logs" } } } /** * iCloud stack for SugarRecord */ public class iCloudCDStack: DefaultCDStack { //MARK: - Properties /// iCloud Data struct with the information private let icloudData: iCloudData? /// Notification center used for iCloud Notifications lazy var notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter() /** Initialize the CoreData stack :param: databaseURL NSURL with the database path :param: model NSManagedObjectModel with the database model :param: automigrating Bool Indicating if the migration has to be automatically executed :param: icloudData iCloudData information :returns: iCloudCDStack object */ public init(databaseURL: NSURL, model: NSManagedObjectModel?, automigrating: Bool, icloudData: iCloudData) { self.icloudData = icloudData super.init(databaseURL: databaseURL, model: model, automigrating: automigrating) self.automigrating = automigrating self.databasePath = databaseURL self.managedObjectModel = model self.migrationFailedClosure = {} self.name = "iCloudCoreDataStack" self.stackDescription = "Stack to connect your local storage with iCloud" } /** Initialize the CoreData default stack passing the database name and a flag indicating if the automigration has to be automatically executed :param: databaseName String with the database name :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseName: String, icloudData: iCloudData) { self.init(databaseURL: iCloudCDStack.databasePathURLFromName(databaseName), icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path in String format and a flag indicating if the automigration has to be automatically executed :param: databasePath String with the database path :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databasePath: String, icloudData: iCloudData) { self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path URL and a flag indicating if the automigration has to be automatically executed :param: databaseURL NSURL with the database path :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseURL: NSURL, icloudData: iCloudData) { self.init(databaseURL: databaseURL, model: nil, automigrating: true,icloudData: icloudData) } /** Initialize the CoreData default stack passing the database name, the database model object and a flag indicating if the automigration has to be automatically executed :param: databaseName String with the database name :param: model NSManagedObjectModel with the database model :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databaseName: String, model: NSManagedObjectModel, icloudData: iCloudData) { self.init(databaseURL: DefaultCDStack.databasePathURLFromName(databaseName), model: model, automigrating: true, icloudData: icloudData) } /** Initialize the CoreData default stack passing the database path in String format, the database model object and a flag indicating if the automigration has to be automatically executed :param: databasePath String with the database path :param: model NSManagedObjectModel with the database model :param: icloudData iCloud Data struct :returns: DefaultCDStack object */ convenience public init(databasePath: String, model: NSManagedObjectModel, icloudData: iCloudData) { self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, model: model, automigrating: true, icloudData: icloudData) } /** Initialize the stacks components and the connections between them */ public override func initialize() { SugarRecordLogger.logLevelInfo.log("Initializing the stack: \(self.stackDescription)") createManagedObjecModelIfNeeded() persistentStoreCoordinator = createPersistentStoreCoordinator() addDatabase(foriCloud: true, completionClosure: self.dataBaseAddedClosure()) } /** Returns the closure to be execute once the database has been created */ override public func dataBaseAddedClosure() -> CompletionClosure { return { [weak self] (error) -> () in if self == nil { SugarRecordLogger.logLevelFatal.log("The stack was released whil trying to initialize it") return } else if error != nil { SugarRecordLogger.logLevelFatal.log("Something went wrong adding the database") return } self!.rootSavingContext = self!.createRootSavingContext(self!.persistentStoreCoordinator) self!.mainContext = self!.createMainContext(self!.rootSavingContext) self!.addObservers() self!.stackInitialized = true } } //MARK: - Contexts /** Creates a temporary root saving context to be used in background operations Note: This overriding is due to the fact that in this case the merge policy is different :param: persistentStoreCoordinator NSPersistentStoreCoordinator to be set as the persistent store coordinator of the created context :returns: Private NSManageObjectContext */ override internal func createRootSavingContext(persistentStoreCoordinator: NSPersistentStoreCoordinator?) -> NSManagedObjectContext { SugarRecordLogger.logLevelVerbose.log("Creating Root Saving context") var context: NSManagedObjectContext? if persistentStoreCoordinator == nil { SugarRecord.handle(NSError(domain: "The persistent store coordinator is not initialized", code: SugarRecordErrorCodes.CoreDataError.rawValue, userInfo: nil)) } context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) context!.persistentStoreCoordinator = persistentStoreCoordinator! context!.addObserverToGetPermanentIDsBeforeSaving() context!.name = "Root saving context" context!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy SugarRecordLogger.logLevelVerbose.log("Created MAIN context") return context! } //MARK: - Database /** Add iCloud Database */ internal func addDatabase(foriCloud icloud: Bool, completionClosure: CompletionClosure) { /** * In case of not for iCloud */ if !icloud { self.addDatabase(completionClosure) return } /** * Database creation is an asynchronous process */ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] () -> Void in // Ensuring that the stack hasn't been released if self == nil { SugarRecordLogger.logLevelFatal.log("The stack was initialized while trying to add the database") return } // Checking that the PSC exists before adding the store if self!.persistentStoreCoordinator == nil { SugarRecord.handle(NSError()) } // Logging some data let fileManager: NSFileManager = NSFileManager() SugarRecordLogger.logLevelVerbose.log("Initializing iCloud with:") SugarRecordLogger.logLevelVerbose.log("iCloud App ID: \(self!.icloudData?.iCloudAppID)") SugarRecordLogger.logLevelVerbose.log("iCloud Data Directory: \(self!.icloudData?.iCloudDataDirectoryName)") SugarRecordLogger.logLevelVerbose.log("iCloud Logs Directory: \(self!.icloudData?.iCloudLogsDirectory)") //Getting the root path for iCloud let iCloudRootPath: NSURL? = fileManager.URLForUbiquityContainerIdentifier(self!.icloudData?.iCloudAppID) /** * If iCloud if accesible keep creating the PSC */ if iCloudRootPath != nil { let iCloudLogsPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudLogsDirectory))! let iCloudDataPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudDataDirectoryName))! // Creating data path in case of doesn't existing var error: NSError? if !fileManager.fileExistsAtPath(iCloudDataPath.path!) { fileManager.createDirectoryAtPath(iCloudDataPath.path!, withIntermediateDirectories: true, attributes: nil, error: &error) } if error != nil { completionClosure(error: error!) return } /// Getting the database path /// iCloudPath + iCloudDataPath + DatabaseName let path: String? = iCloudRootPath?.path?.stringByAppendingPathComponent((self?.icloudData?.iCloudDataDirectoryName)!).stringByAppendingPathComponent((self?.databasePath?.lastPathComponent)!) self!.databasePath = NSURL(fileURLWithPath: path!) // Adding store self!.persistentStoreCoordinator?.performBlockAndWait({ () -> Void in error = nil var store: NSPersistentStore? = self!.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self!.databasePath, options: iCloudCDStack.icloudStoreOptions(contentNameKey: self!.icloudData!.iCloudAppID, contentURLKey: iCloudLogsPath), error: &error) self!.persistentStore = store! }) // Calling completion closure dispatch_async(dispatch_get_main_queue(), { () -> Void in completionClosure(error: nil) }) } /** * Otherwise use the local store */ else { self!.addDatabase(foriCloud: false, completionClosure: completionClosure) } }) } //MARK: - Database Helpers /** Returns the iCloud options to be used when the NSPersistentStore is initialized :returns: [NSObject: AnyObject] with the options */ internal class func icloudStoreOptions(#contentNameKey: String, contentURLKey: NSURL) -> [NSObject: AnyObject] { var options: [NSObject: AnyObject] = [NSObject: AnyObject] () options[NSMigratePersistentStoresAutomaticallyOption] = NSNumber(bool: true) options[NSInferMappingModelAutomaticallyOption] = NSNumber(bool: true) options[NSPersistentStoreUbiquitousContentNameKey] = contentNameKey options[NSPersistentStoreUbiquitousContentURLKey] = contentURLKey return options } //MARK: - Observers /** Add required observers to detect changes in psc's or contexts */ internal override func addObservers() { super.addObservers() SugarRecordLogger.logLevelVerbose.log("Adding observers to detect changes on iCloud") // Store will change notificationCenter.addObserver(self, selector: Selector("storesWillChange:"), name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: nil) // Store did change notificationCenter.addObserver(self, selector: Selector("storeDidChange:"), name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil) // Did import Ubiquituous Content notificationCenter.addObserver(self, selector: Selector("persistentStoreDidImportUbiquitousContentChanges:"), name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: nil) } /** Detects changes in the Ubiquituous Container (iCloud) and bring them to the stack contexts :param: notification Notification with these changes */ internal func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("Changes detected from iCloud. Merging them into the current CoreData stack") self.rootSavingContext!.performBlock { [weak self] () -> Void in if self == nil { SugarRecordLogger.logLevelWarn.log("The stack was released while trying to bring changes from the iCloud Container") return } self!.rootSavingContext!.mergeChangesFromContextDidSaveNotification(notification) self!.mainContext!.performBlock({ () -> Void in self!.mainContext!.mergeChangesFromContextDidSaveNotification(notification) }) } } /** Posted before the list of open persistent stores changes. :param: notification Notification with these changes */ internal func storesWillChange(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("Stores will change, saving pending changes before changing store") self.saveChanges() } /** Called when the store did change from the persistent store coordinator :param: notification Notification with the information */ internal func storeDidChange(notification: NSNotification) { SugarRecordLogger.logLevelVerbose.log("The persistent store of the psc did change") // Nothing to do here } }
mit
284c8b0be838ca741de914621fa52a2b
39.924479
310
0.67303
5.602139
false
false
false
false
EyreFree/EFCountingLabel
Example/EFCountingLabel/ViewControllers/StoryboardButtonViewController.swift
1
3549
// // StoryboardButtonViewController.swift // EFCountingLabel // // Created by Kirow on 2019-05-26. // // Copyright (c) 2017 EyreFree <eyrefree@eyrefree.org> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit import EFCountingLabel class StoryboardButtonViewController: UIViewController { @IBOutlet weak var countDownButton: EFCountingButton! @IBOutlet weak var stoppableButton: EFCountingButton! override func viewDidLoad() { super.viewDidLoad() let textAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 14, weight: .bold), .foregroundColor: UIColor.darkText ] let valueAttributes: [NSAttributedString.Key: Any] = [ .font: UIFont.systemFont(ofSize: 18, weight: .ultraLight), .foregroundColor: UIColor.red ] stoppableButton.setUpdateBlock { value, button in button.setTitle("\(value)", for: .normal) let attributed = NSMutableAttributedString() attributed.append(NSAttributedString(string: "Current Value:\t", attributes: textAttributes)) attributed.append(NSAttributedString(string: String(format: "%.04f", value), attributes: valueAttributes)) button.setAttributedTitle(attributed, for: .normal) } stoppableButton.setCompletionBlock { button in button.counter.reset() button.setTitle("Press to Start", for: .normal) } countDownButton.setUpdateBlock { value, button in button.setTitle("\(Int(value))", for: .normal) } countDownButton.setCompletionBlock { button in button.setTitle("Count Down", for: .normal) } } @IBAction func didClickCountDownButton(_ sender: EFCountingButton) { if !sender.counter.isCounting { sender.countFrom(10, to: 0, withDuration: 10) } } @IBAction func didClickStopButton(_ sender: EFCountingButton) { if sender.counter.isCounting { sender.stopCountAtCurrentValue() sender.setAttributedTitle(nil, for: .normal) sender.contentHorizontalAlignment = .center sender.setTitle("Press to Resume", for: .normal) } else { sender.contentHorizontalAlignment = .left sender.countFromCurrentValueTo(1000000, withDuration: 20) } } }
mit
e7f9a8f9fff5dc93a36906acb7c947ce
39.329545
118
0.666667
4.789474
false
false
false
false
iZhang/travel-architect
main/Focus Square/FocusSquareSegment.swift
4
4294
/* See LICENSE folder for this sample’s licensing information. Abstract: Corner segments for the focus square UI. */ import SceneKit extension FocusSquare { /* The focus square consists of eight segments as follows, which can be individually animated. s1 s2 _ _ s3 | | s4 s5 | | s6 - - s7 s8 */ enum Corner { case topLeft // s1, s3 case topRight // s2, s4 case bottomRight // s6, s8 case bottomLeft // s5, s7 } enum Alignment { case horizontal // s1, s2, s7, s8 case vertical // s3, s4, s5, s6 } enum Direction { case up, down, left, right var reversed: Direction { switch self { case .up: return .down case .down: return .up case .left: return .right case .right: return .left } } } class Segment: SCNNode { // MARK: - Configuration & Initialization /// Thickness of the focus square lines in m. static let thickness: CGFloat = 0.018 /// Length of the focus square lines in m. static let length: CGFloat = 0.5 // segment length /// Side length of the focus square segments when it is open (w.r.t. to a 1x1 square). static let openLength: CGFloat = 0.2 let corner: Corner let alignment: Alignment let plane: SCNPlane init(name: String, corner: Corner, alignment: Alignment) { self.corner = corner self.alignment = alignment switch alignment { case .vertical: plane = SCNPlane(width: Segment.thickness, height: Segment.length) case .horizontal: plane = SCNPlane(width: Segment.length, height: Segment.thickness) } super.init() self.name = name let material = plane.firstMaterial! material.diffuse.contents = FocusSquare.primaryColor material.isDoubleSided = true material.ambient.contents = UIColor.black material.lightingModel = .constant material.emission.contents = FocusSquare.primaryColor geometry = plane } required init?(coder aDecoder: NSCoder) { fatalError("\(#function) has not been implemented") } // MARK: - Animating Open/Closed var openDirection: Direction { switch (corner, alignment) { case (.topLeft, .horizontal): return .left case (.topLeft, .vertical): return .up case (.topRight, .horizontal): return .right case (.topRight, .vertical): return .up case (.bottomLeft, .horizontal): return .left case (.bottomLeft, .vertical): return .down case (.bottomRight, .horizontal): return .right case (.bottomRight, .vertical): return .down } } func open() { if alignment == .horizontal { plane.width = Segment.openLength } else { plane.height = Segment.openLength } let offset = Segment.length / 2 - Segment.openLength / 2 updatePosition(withOffset: Float(offset), for: openDirection) } func close() { let oldLength: CGFloat if alignment == .horizontal { oldLength = plane.width plane.width = Segment.length } else { oldLength = plane.height plane.height = Segment.length } let offset = Segment.length / 2 - oldLength / 2 updatePosition(withOffset: Float(offset), for: openDirection.reversed) } private func updatePosition(withOffset offset: Float, for direction: Direction) { switch direction { case .left: position.x -= offset case .right: position.x += offset case .up: position.y -= offset case .down: position.y += offset } } } }
mit
d04eaac504d306fe26931bcb5a44f25c
29.439716
95
0.525163
4.905143
false
false
false
false
ruslanskorb/CoreStore
CoreStoreDemo/CoreStoreDemo/Fetching and Querying Demo/FetchingAndQueryingDemoViewController.swift
1
10520
// // FetchingAndQueryingDemoViewController.swift // CoreStoreDemo // // Created by John Rommel Estropia on 2015/06/12. // Copyright © 2018 John Rommel Estropia. All rights reserved. // import UIKit import CoreStore private struct Static { static let timeZonesStack: DataStack = { let dataStack = DataStack() try! dataStack.addStorageAndWait( SQLiteStore( fileName: "TimeZoneDemo.sqlite", configuration: "FetchingAndQueryingDemo", localStorageOptions: .recreateStoreOnModelMismatch ) ) _ = try? dataStack.perform( synchronous: { (transaction) in try transaction.deleteAll(From<TimeZone>()) for name in NSTimeZone.knownTimeZoneNames { let rawTimeZone = NSTimeZone(name: name)! let cachedTimeZone = transaction.create(Into<TimeZone>()) cachedTimeZone.name = rawTimeZone.name cachedTimeZone.abbreviation = rawTimeZone.abbreviation ?? "" cachedTimeZone.secondsFromGMT = Int32(rawTimeZone.secondsFromGMT) cachedTimeZone.hasDaylightSavingTime = rawTimeZone.isDaylightSavingTime cachedTimeZone.daylightSavingTimeOffset = rawTimeZone.daylightSavingTimeOffset } } ) return dataStack }() } // MARK: - FetchingAndQueryingDemoViewController class FetchingAndQueryingDemoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: UIViewController override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if self.didAppearOnce { return } self.didAppearOnce = true let alert = UIAlertController( title: "Fetch and Query Demo", message: "This demo shows how to execute fetches and queries.\n\nEach menu item executes and displays a preconfigured fetch/query.", preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) if let indexPath = sender as? IndexPath { switch segue.destination { case let controller as FetchingResultsViewController: let item = self.fetchingItems[indexPath.row] controller.set(timeZones: item.fetch(), title: item.title) case let controller as QueryingResultsViewController: let item = self.queryingItems[indexPath.row] controller.set(value: item.query(), title: item.title) default: break } } } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch self.segmentedControl?.selectedSegmentIndex { case Section.fetching.rawValue?: return self.fetchingItems.count case Section.querying.rawValue?: return self.queryingItems.count default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell")! switch self.segmentedControl?.selectedSegmentIndex { case Section.fetching.rawValue?: cell.textLabel?.text = self.fetchingItems[indexPath.row].title case Section.querying.rawValue?: cell.textLabel?.text = self.queryingItems[indexPath.row].title default: cell.textLabel?.text = nil } return cell } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch self.segmentedControl?.selectedSegmentIndex { case Section.fetching.rawValue?: self.performSegue(withIdentifier: "FetchingResultsViewController", sender: indexPath) case Section.querying.rawValue?: self.performSegue(withIdentifier: "QueryingResultsViewController", sender: indexPath) default: break } } // MARK: Private private enum Section: Int { case fetching case querying } private let fetchingItems = [ ( title: "All Time Zones", fetch: { () -> [TimeZone] in return try! Static.timeZonesStack.fetchAll( From<TimeZone>() .orderBy(.ascending(\.name)) ) } ), ( title: "Time Zones in Asia", fetch: { () -> [TimeZone] in return try! Static.timeZonesStack.fetchAll( From<TimeZone>() .where( format: "%K BEGINSWITH[c] %@", #keyPath(TimeZone.name), "Asia" ) .orderBy(.ascending(\.secondsFromGMT)) ) } ), ( title: "Time Zones in America and Europe", fetch: { () -> [TimeZone] in return try! Static.timeZonesStack.fetchAll( From<TimeZone>() .where( format: "%K BEGINSWITH[c] %@ OR %K BEGINSWITH[c] %@", #keyPath(TimeZone.name), "America", #keyPath(TimeZone.name), "Europe" ) .orderBy(.ascending(\.secondsFromGMT)) ) } ), ( title: "All Time Zones Except America", fetch: { () -> [TimeZone] in return try! Static.timeZonesStack.fetchAll( From<TimeZone>() .where( format: "%K BEGINSWITH[c] %@", #keyPath(TimeZone.name), "America" ) .orderBy(.ascending(\.secondsFromGMT)) ) } ), ( title: "Time Zones with Summer Time", fetch: { () -> [TimeZone] in return try! Static.timeZonesStack.fetchAll( From<TimeZone>() .where(\.hasDaylightSavingTime == true) .orderBy(.ascending(\.name)) ) } ) ] private let queryingItems: [(title: String, query: () -> Any)] = [ ( title: "Number of Time Zones", query: { () -> Any in return try! Static.timeZonesStack.queryValue( From<TimeZone>() .select(NSNumber.self, .count(\.name)) )! } ), ( title: "Abbreviation For Tokyo's Time Zone", query: { () -> Any in return try! Static.timeZonesStack.queryValue( From<TimeZone>() .select(String.self, .attribute(\.abbreviation)) .where(format: "%K ENDSWITH[c] %@", #keyPath(TimeZone.name), "Tokyo") )! } ), ( title: "All Abbreviations", query: { () -> Any in return try! Static.timeZonesStack.queryAttributes( From<TimeZone>() .select( NSDictionary.self, .attribute(\.name), .attribute(\.abbreviation) ) .orderBy(.ascending(\.name)) ) } ), ( title: "Number of Countries per Time Zone", query: { () -> Any in return try! Static.timeZonesStack.queryAttributes( From<TimeZone>() .select( NSDictionary.self, .count(\.abbreviation), .attribute(\.abbreviation) ) .groupBy(\.abbreviation) .orderBy( .ascending(\.secondsFromGMT), .ascending(\.name) ) ) } ), ( title: "Number of Countries with Summer Time", query: { () -> Any in return try! Static.timeZonesStack.queryAttributes( From<TimeZone>() .select( NSDictionary.self, .count(\.hasDaylightSavingTime, as: "numberOfCountries"), .attribute(\.hasDaylightSavingTime) ) .groupBy(\.hasDaylightSavingTime) .orderBy( .descending(\.hasDaylightSavingTime), .ascending(\.name) ) ) } ) ] var didAppearOnce = false @IBOutlet dynamic weak var segmentedControl: UISegmentedControl? @IBOutlet dynamic weak var tableView: UITableView? @IBAction dynamic func segmentedControlValueChanged(_ sender: AnyObject?) { self.tableView?.reloadData() } }
mit
4687289c09c7e3b36f9e72a6ed1dccc0
31.974922
144
0.466965
6.162273
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxSwift/RxSwift/Observables/Implementations/DistinctUntilChanged.swift
60
2004
// // DistinctUntilChanged.swift // Rx // // Created by Krunoslav Zaher on 3/15/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class DistinctUntilChangedSink<O: ObserverType, Key>: Sink<O>, ObserverType { typealias E = O.E private let _parent: DistinctUntilChanged<E, Key> private var _currentKey: Key? = nil init(parent: DistinctUntilChanged<E, Key>, observer: O) { _parent = parent super.init(observer: observer) } func on(event: Event<E>) { switch event { case .Next(let value): do { let key = try _parent._selector(value) var areEqual = false if let currentKey = _currentKey { areEqual = try _parent._comparer(currentKey, key) } if areEqual { return } _currentKey = key forwardOn(event) } catch let error { forwardOn(.Error(error)) dispose() } case .Error, .Completed: forwardOn(event) dispose() } } } class DistinctUntilChanged<Element, Key>: Producer<Element> { typealias KeySelector = (Element) throws -> Key typealias EqualityComparer = (Key, Key) throws -> Bool private let _source: Observable<Element> private let _selector: KeySelector private let _comparer: EqualityComparer init(source: Observable<Element>, selector: KeySelector, comparer: EqualityComparer) { _source = source _selector = selector _comparer = comparer } override func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable { let sink = DistinctUntilChangedSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } }
mit
796f8d50882cfb677675654cc89104a6
27.628571
90
0.553669
4.921376
false
false
false
false
glock45/swiftX
Source/http/net_linux.swift
1
7820
// // net_linux.swift // swiftx // // Copyright © 2016 kolakowski. All rights reserved. // #if os(Linux) import Glibc public class LinuxAsyncServer: TcpServer { private var backlog = [Int32: Array<(chunk: [UInt8], done: ((Void) -> TcpWriteDoneAction))>]() private var descriptors = [pollfd]() private let server: Int32 public required init(_ port: in_port_t) throws { self.server = try LinuxAsyncServer.nonBlockingSocketForListenening(port) self.descriptors.append(pollfd(fd: self.server, events: Int16(POLLIN), revents: 0)) } deinit { cleanup() } public func write(_ socket: Int32, _ data: Array<UInt8>, _ done: @escaping ((Void) -> TcpWriteDoneAction)) throws { let result = Glibc.write(socket, data, data.count) if result == -1 { defer { self.finish(socket) } throw AsyncError.writeFailed(Process.error) } if result == data.count { if done() == .terminate { self.finish(socket) } return } let leftData = [UInt8](data[result..<data.count]) for i in 0..<descriptors.count { if descriptors[i].fd == socket { self.backlog[socket]?.append((leftData, done)) descriptors[i].events = descriptors[i].events | Int16(POLLOUT) return } } } public func wait(_ callback: ((TcpServerEvent) -> Void)) throws { guard poll(&descriptors, UInt(descriptors.count), -1) != -1 else { throw AsyncError.async(Process.error) } for i in 0..<descriptors.count { if descriptors[i].revents == 0 { continue } if descriptors[i].fd == server { while case let client = accept(server, nil, nil), client > 0 { try LinuxAsyncServer.setSocketNonBlocking(client) self.backlog[Int32(client)] = [] descriptors.append(pollfd(fd: client, events: Int16(POLLIN), revents: 0)) callback(TcpServerEvent.connect("", Int32(client))) } if errno != EWOULDBLOCK { throw AsyncError.acceptFailed(Process.error) } } else { if (descriptors[i].revents & Int16(POLLERR) != 0) || (descriptors[i].revents & Int16(POLLHUP) != 0) || (descriptors[i].revents & Int16(POLLNVAL) != 0) { self.finish(descriptors[i].fd) callback(TcpServerEvent.disconnect("", descriptors[i].fd)) descriptors[i].fd = -1 continue } if descriptors[i].revents & Int16(POLLIN) != 0 { var buffer = [UInt8](repeating: 0, count: 256) readLoop: while true { let result = read(descriptors[i].fd, &buffer, 256) switch result { case -1: if errno != EWOULDBLOCK { callback(TcpServerEvent.disconnect("", descriptors[i].fd)) self.finish(descriptors[i].fd) descriptors[i].fd = -1 } break readLoop case 0: callback(TcpServerEvent.disconnect("", descriptors[i].fd)) self.finish(descriptors[i].fd) descriptors[i].fd = -1 break readLoop default: callback(TcpServerEvent.data("", descriptors[i].fd, buffer[0..<result])) } } } if descriptors[i].revents & Int16(POLLOUT) != 0 { while let backlogElement = self.backlog[Int32(descriptors[i].fd)]?.first { var chunk = backlogElement.chunk let result = Glibc.write(Int32(descriptors[i].fd), chunk, chunk.count) if result == -1 { finish(Int32(descriptors[i].fd)) callback(TcpServerEvent.disconnect("", Int32(descriptors[i].fd))) descriptors[i].fd = -1 return } if result < chunk.count { let leftData = [UInt8](chunk[result..<chunk.count]) self.backlog[Int32(descriptors[i].fd)]?.remove(at: 0) self.backlog[Int32(descriptors[i].fd)]?.insert((chunk: leftData, done: backlogElement.done), at: 0) return } self.backlog[Int32(descriptors[i].fd)]?.removeFirst() if backlogElement.done() == .terminate { finish(Int32(descriptors[i].fd)) callback(TcpServerEvent.disconnect("", Int32(descriptors[i].fd))) descriptors[i].fd = -1 return } } descriptors[i].events = descriptors[i].events & (~Int16(POLLOUT)) } } } for i in (0..<descriptors.count).reversed() { if descriptors[i].fd == -1 { descriptors.remove(at: i) } } } public func finish(_ socket: Int32) { self.backlog[socket] = [] let _ = Glibc.close(socket) } public func cleanup() { for client in self.descriptors { let _ = Glibc.close(client.fd) } let _ = Glibc.close(Int32(server)) } public static func nonBlockingSocketForListenening(_ port: in_port_t = 8080) throws -> Int32 { let server = Glibc.socket(AF_INET, Int32(SOCK_STREAM.rawValue), 0) guard server != -1 else { throw AsyncError.socketCreation(Process.error) } var value: Int32 = 1 if Glibc.setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &value, socklen_t(MemoryLayout<Int32>.size)) == -1 { defer { let _ = Glibc.close(server) } throw AsyncError.setReuseAddrFailed(Process.error) } if Glibc.fcntl(server, F_SETFL, fcntl(server, F_GETFL, 0) | O_NONBLOCK) == -1 { defer { let _ = Glibc.close(server) } throw AsyncError.setNonBlockFailed(Process.error) } var addr = anyAddrForPort(port) if withUnsafePointer(to: &addr, { bind(server, UnsafePointer<sockaddr>(OpaquePointer($0)), socklen_t(MemoryLayout<sockaddr_in>.size)) }) == -1 { defer { let _ = Glibc.close(server) } throw AsyncError.bindFailed(Process.error) } if Glibc.listen(server, SOMAXCONN) == -1 { defer { let _ = Glibc.close(server) } throw AsyncError.listenFailed(Process.error) } return server } public static func anyAddrForPort(_ port: in_port_t) -> sockaddr_in { var addr = sockaddr_in() addr.sin_family = sa_family_t(AF_INET) addr.sin_port = port.bigEndian addr.sin_addr = in_addr(s_addr: in_addr_t(0)) addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0) return addr } public static func setSocketNonBlocking(_ socket: Int32) throws { if Glibc.fcntl(socket, F_SETFL, fcntl(socket, F_GETFL, 0) | O_NONBLOCK) == -1 { throw AsyncError.setNonBlockFailed(Process.error) } } } #endif
bsd-3-clause
22ebe832e19950b0642bedaff17fdde1
39.512953
168
0.493286
4.380392
false
false
false
false
guidomb/Portal
Example/Views/ExamplesView.swift
1
4450
// // ExamplesView.swift // PortalExample // // Created by Argentino Ducret on 8/31/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Portal enum ExamplesScreen { typealias Action = Portal.Action<Route, Message> typealias View = Portal.View<Route, Message, Navigator> static func view() -> View { let items: [TableItemProperties<Action>] = [ verticalCollection(), horizontalCollection(), labelComponent(), textField(), textView(), image(), map(), progress(), segment(), spinner(), tableView(), carouselView() ] return View( navigator: .main, root: .stack(ExampleApplication.navigationBar(title: "Component Examples")), component: table( items: items, style: tableStyleSheet { base, table in base.backgroundColor = .green }, layout: layout { $0.flex = flex { $0.grow = .one } } ) ) } } fileprivate extension ExamplesScreen { fileprivate static func verticalCollection() -> TableItemProperties<Action> { return defaultCell(text: "Vertical Collection", route: .verticalCollectionExample) } fileprivate static func labelComponent() -> TableItemProperties<Action> { return defaultCell(text: "Label", route: .labelExample) } fileprivate static func textView() -> TableItemProperties<Action> { return defaultCell(text: "Text View", route: .textViewExample) } fileprivate static func textField() -> TableItemProperties<Action> { return defaultCell(text: "Text Field", route: .textFieldExample) } fileprivate static func image() -> TableItemProperties<Action> { return defaultCell(text: "Image", route: .imageExample) } fileprivate static func map() -> TableItemProperties<Action> { return defaultCell(text: "Map", route: .mapExample) } fileprivate static func progress() -> TableItemProperties<Action> { return defaultCell(text: "Progress", route: .progressExample) } fileprivate static func segment() -> TableItemProperties<Action> { return defaultCell(text: "Segment", route: .segmentedExample) } fileprivate static func spinner() -> TableItemProperties<Action> { return defaultCell(text: "Spinner", route: .spinnerExample) } fileprivate static func tableView() -> TableItemProperties<Action> { return defaultCell(text: "Table", route: .tableExample) } fileprivate static func carouselView() -> TableItemProperties<Action> { return defaultCell(text: "Carousel", route: .carouselExample) } fileprivate static func horizontalCollection() -> TableItemProperties<Action> { return defaultCell(text: "Horizontal Collection", route: .horizontalCollectionExample) } fileprivate static func defaultCell(text: String, route: Route) -> TableItemProperties<Action> { return tableItem(height: 55, onTap: .navigate(to: route), selectionStyle: .none) { _ in TableItemRender( component: container ( children: [ container( children: [ label(text: text) ], style: styleSheet { $0.backgroundColor = .blue }, layout: layout { $0.alignment = alignment { $0.items = .center } $0.height = Dimension(value: 50) $0.justifyContent = .center $0.margin = .by(edge: Edge(bottom: 5)) } ) ], style: styleSheet { $0.backgroundColor = .green }, layout: layout { $0.height = Dimension(value: 55) } ), typeIdentifier: text ) } } }
mit
1d585a3455f78d1ac0c27b7f2636fb0e
32.704545
100
0.525961
5.386199
false
false
false
false
chamira/SQLiteManager
Sources/SQLitePool.swift
1
2263
// // File.swift // Pods // // Created by Chamira Fernando on 22/11/2016. // // import Foundation //MARK: - SQLitePool Class //SQLitePool class open class SQLitePool { fileprivate init() {} deinit { SQLitePool.closeDatabases() } fileprivate static var instances:[String:SQLite] = [:] fileprivate static var sharedPool:SQLitePool = SQLitePool() internal static func addInstanceFor(database databaseNameWithExtension:String, instance:SQLite) { instances[databaseNameWithExtension] = instance } /** SQLitePool Manager, Singleton access method - returns: SQLitePool class */ open static func manager()->SQLitePool { return sharedPool } /** Returns the instance of a database if its already in the pool, otherwise nil - parameter databaseNameWithExtension: database name with extension - returns: SQLite Database */ open static func getInstanceFor(database databaseNameWithExtension:String)->SQLite? { if (instances.isEmpty) { return nil } let lite = instances[databaseNameWithExtension] return lite } /** Initialize a database and add to SQLitePool, you can initialize many databases as you like. Each database (instance) will be remained in SQLitePool - parameter name: name of the database (without extension) - parameter withExtension: database extension (db, db3, sqlite, sqlite3) without .(dot) - parameter createIfNotExists: create database with given name in application dir If it does not exists, default value is false - throws: NSError - returns: SQLite database */ open func initialize(database name:String, withExtension:String, createIfNotExist:Bool = false) throws -> SQLite { do { let lite = try SQLite().initialize(database: name, withExtension: withExtension, createIfNotExist: createIfNotExist) return lite } catch let e as NSError { throw e } } /** Close all open databases in the pool */ open static func closeDatabases() { instances.forEach { $0.1.closeDatabase() } instances.removeAll() } /// Open databases count open static var databasesCount:Int { return instances.count } /// Returns all instances of databases in the pool open static var databases:[String:SQLite] { return instances } }
mit
410219b2443adf296c5ad6f171a8ea4a
22.572917
128
0.72426
3.949389
false
false
false
false
nwjs/chromium.src
ios/chrome/browser/ui/omnibox/popup/shared/popup_match.swift
1
7062
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import Foundation import SwiftUI @objcMembers public class PopupMatch: NSObject, Identifiable { // The underlying suggestion backing all the data. let suggestion: AutocompleteSuggestion var text: NSAttributedString { return suggestion.text ?? NSAttributedString(string: "") } var detailText: NSAttributedString? { return suggestion.detailText } /// Some suggestions can be appended to omnibox text in order to refine the /// query or URL. var isAppendable: Bool { return suggestion.isAppendable } /// Some suggestions are opened in another tab. var isTabMatch: Bool { return suggestion.isTabMatch } /// Some suggestions are from the clipboard provider. var isClipboardMatch: Bool { return suggestion.isClipboardMatch } /// Some suggestions can be deleted with a swipe-to-delete gesture. var supportsDeletion: Bool { return suggestion.supportsDeletion } /// Some suggestions are answers that are displayed inline, such as for weather or calculator. var hasAnswer: Bool { return suggestion.hasAnswer } /// Suggested number of lines to format |detailText|. var numberOfLines: Int { return suggestion.numberOfLines } /// The pedal for this suggestion. var pedal: OmniboxPedal? { return suggestion.pedal } /// The image shown on the leading edge of the row (an icon, a favicon, /// etc.). lazy var image = suggestion.icon.map { icon in PopupImage(icon: icon) } public init(suggestion: AutocompleteSuggestion) { self.suggestion = suggestion } public var id: String { return text.string } } extension PopupMatch { class FakeAutocompleteSuggestion: NSObject, AutocompleteSuggestion { let text: NSAttributedString? let detailText: NSAttributedString? let isAppendable: Bool let isTabMatch: Bool let isClipboardMatch: Bool let supportsDeletion: Bool let icon: OmniboxIcon? let pedal: (OmniboxIcon & OmniboxPedal)? let hasAnswer: Bool let isURL = false let numberOfLines: Int let isTailSuggestion = false let commonPrefix = "" let matchTypeIcon: UIImage? = nil let isMatchTypeSearch = false let omniboxPreviewText: NSAttributedString? = nil let destinationUrl: CrURL? = nil init( text: String, detailText: String? = nil, isAppendable: Bool = false, isTabMatch: Bool = false, isClipboardMatch: Bool = false, supportsDeletion: Bool = false, icon: OmniboxIcon? = nil, hasAnswer: Bool = false, numberOfLines: Int = 1, pedal: OmniboxPedalData? = nil ) { self.text = NSAttributedString(string: text, attributes: [:]) self.detailText = detailText.flatMap { string in NSAttributedString(string: string, attributes: [:]) } self.isAppendable = isAppendable self.isTabMatch = isTabMatch self.isClipboardMatch = isClipboardMatch self.supportsDeletion = supportsDeletion self.icon = icon self.pedal = pedal self.hasAnswer = hasAnswer self.numberOfLines = numberOfLines } init( attributedText: NSAttributedString, attributedDetailText: NSAttributedString? = nil, isAppendable: Bool = false, isTabMatch: Bool = false, isClipboardMatch: Bool = false, hasAnswer: Bool = false, supportsDeletion: Bool = false, icon: OmniboxIcon? = nil, numberOfLines: Int = 1, pedal: OmniboxPedalData? = nil ) { self.text = attributedText self.detailText = attributedDetailText self.isAppendable = isAppendable self.isTabMatch = isTabMatch self.isClipboardMatch = isClipboardMatch self.supportsDeletion = supportsDeletion self.icon = icon self.pedal = pedal self.hasAnswer = hasAnswer self.numberOfLines = numberOfLines } } static let short = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "Google", detailText: "google.com", icon: FakeOmniboxIcon.suggestionIcon)) static let long = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "1292459 - Overflow menu is displayed on top of NTP ...", detailText: "bugs.chromium.org/p/chromium/issues/detail?id=1292459", icon: FakeOmniboxIcon.favicon)) static let arabic = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "ععععععععع ععععععععع ععععععععع عععععععع عععععععع عععععععع عععععععع عععععع عععععععل", detailText: "letter ع many times, and a single ل in the end", pedal: OmniboxPedalData( title: "Click here", subtitle: "PAR → NYC", accessibilityHint: "a11y hint", imageName: "pedal_dino", type: 123, incognito: false, action: { print("dino pedal clicked") }))) static let pedal = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "This has pedal attached", detailText: "no pedal button in current design", pedal: OmniboxPedalData( title: "Click here", subtitle: "PAR → NYC", accessibilityHint: "a11y hint", imageName: "pedal_dino", type: 123, incognito: false, action: { print("dino pedal clicked") }))) static let appendable = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "is appendable", isAppendable: true, icon: FakeOmniboxIcon.suggestionAnswerIcon)) static let tabMatch = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "Home", isTabMatch: true)) static let added = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "New Match", pedal: OmniboxPedalData( title: "Click here", subtitle: "NYC → PAR", accessibilityHint: "a11y hint", imageName: "pedal_dino", type: 123, incognito: false, action: {}))) static let supportsDeletion = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "supports deletion", isAppendable: true, supportsDeletion: true)) static let definition = PopupMatch( suggestion: FakeAutocompleteSuggestion( text: "Answer: definition", detailText: "this is a definition suggestion that has a very long text that should span multiple lines and not have a gradient fade out", isAppendable: true, supportsDeletion: false, hasAnswer: true, numberOfLines: 3 )) // The blue attribued string is used to verify that keyboard highlighting overrides the attributes. static let blueAttributedText = PopupMatch( suggestion: FakeAutocompleteSuggestion( attributedText: NSAttributedString( string: "blue attr string", attributes: [ NSAttributedString.Key.foregroundColor: UIColor.blue ]), isAppendable: true, supportsDeletion: true)) static let previews = [ short, definition, long, arabic, pedal, appendable, tabMatch, supportsDeletion, blueAttributedText, ] }
bsd-3-clause
f217eda2f94daaddcbedbe96aad9e855
33.389163
133
0.695316
4.274954
false
false
false
false
NewYorkFive/DLCommon
SwiftExtension/UIDevice+Extension.swift
1
5575
// // UIDevice+Extension.swift // KMCamera // // Created by NowOrNever on 11/03/2020. // Copyright © 2020 LL. All rights reserved. // import UIKit public extension UIDevice { static let extension_identifier:String = { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } return identifier }() static let modelName: String = { func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity #if os(iOS) switch identifier { case "iPod5,1": return "iPod touch (5th generation)" case "iPod7,1": return "iPod touch (6th generation)" case "iPod9,1": return "iPod touch (7th generation)" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone8,4": return "iPhone SE" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPhone12,1": return "iPhone 11" case "iPhone12,3": return "iPhone 11 Pro" case "iPhone12,5": return "iPhone 11 Pro Max" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)" case "iPad6,11", "iPad6,12": return "iPad (5th generation)" case "iPad7,5", "iPad7,6": return "iPad (6th generation)" case "iPad7,11", "iPad7,12": return "iPad (7th generation)" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad11,4", "iPad11,5": return "iPad Air (3rd generation)" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3" case "iPad5,1", "iPad5,2": return "iPad mini 4" case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch)" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4":return "iPad Pro (11-inch)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8":return "iPad Pro (12.9-inch) (3rd generation)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #endif } return mapToDevice(identifier: extension_identifier) }() }
mit
387cb5b9585b66da1810b5041a41af82
60.252747
171
0.465913
4.147321
false
false
false
false
corichmond/turbo-adventure
project3/Project1/MasterViewController.swift
20
2080
// // MasterViewController.swift // Project1 // // Created by Hudzilla on 19/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [String]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() let fm = NSFileManager.defaultManager() let items = fm.contentsOfDirectoryAtPath(NSBundle.mainBundle().resourcePath!, error: nil) for item in items as! [String] { if item.hasPrefix("nssl") { objects.append(item ) } } } override func viewWillAppear(animated: Bool) { tableView.selectRowAtIndexPath(nil, animated: true, scrollPosition: .None) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let detailViewController = segue.destinationViewController as! DetailViewController detailViewController.detailItem = objects[indexPath.row] } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = objects[indexPath.row] return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } }
unlicense
8ce50d37a9838a162f41e8905bd9651b
26.012987
115
0.744712
4.369748
false
false
false
false
PurpleSweetPotatoes/SwiftKit
SwiftKit/extension/UIImage+extension.swift
1
4681
// // UIImage+extension.swift // swift4.2Demo // // Created by baiqiang on 2018/10/6. // Copyright © 2018年 baiqiang. All rights reserved. // import UIKit private let colorSpaceRef = CGColorSpaceCreateDeviceRGB() extension UIImage { class func orginImg(name: String) -> UIImage? { return UIImage(named: name)?.withRenderingMode(.alwaysOriginal) } /// 图片质量压缩 /// /// - Parameters: /// - aimLength: 压缩大小(kb) /// - accuracy: 压缩误差范围(kb) /// - Returns: 压缩后的图片数据 func compress(aimLength: Int, accuracy: Int) -> Data { return self.compress(width: self.size.width, aimLength: aimLength, accuracy: accuracy) } /// 图片质量压缩 /// /// - Parameters: /// - width: 压缩后宽最大值 /// - aimLength: 压缩大小(kb) /// - accuracy: 压缩误差范围(kb) /// - Returns: 压缩后的图片数据 func compress(width:CGFloat, aimLength: Int, accuracy: Int) -> Data { let imgWidth = self.size.width let imgHeight = self.size.height var aimSize: CGSize if width >= imgWidth { aimSize = self.size; }else { aimSize = CGSize(width: width,height: width*imgHeight/imgWidth); } UIGraphicsBeginImageContext(aimSize); self.draw(in: CGRect(origin: CGPoint.zero, size: aimSize)) let newImage = UIGraphicsGetImageFromCurrentImageContext()!; UIGraphicsEndImageContext(); let data = newImage.jpegData(compressionQuality: 1)! var dataLen = data.count let aim_max = aimLength * 1024 + accuracy * 1024 let aim_min = aimLength * 1024 - accuracy * 1024 if (dataLen <= aim_max) { return data; } else { var maxQuality: CGFloat = 1.0 var minQuality: CGFloat = 0.0 var flag = 0 while true { let midQuality = (minQuality + maxQuality) * 0.5 if flag > 6 { return newImage.jpegData(compressionQuality: minQuality)! } flag += 1 let imageData = newImage.jpegData(compressionQuality: minQuality)! dataLen = imageData.count if dataLen > aim_max{ maxQuality = midQuality continue } else if dataLen < aim_min { minQuality = midQuality; continue; } else { return imageData; } } } } func fillColor(_ color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) context?.clip(to: rect, mask: self.cgImage!) color.setFill() context?.fill(rect) let newImg = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImg ?? self } /// Process Image use a bitmap context /// /// - Returns: success => an image containing a snapshot of the bitmap context `context' /// fail => self func decompressedImg() -> UIImage { if self.images != nil || self.cgImage == nil { return self } let imgRef = self.cgImage! let hasAlpha = !(imgRef.alphaInfo == .none || imgRef.alphaInfo == .noneSkipFirst || imgRef.alphaInfo == .noneSkipLast) let bitmapInfo = CGBitmapInfo.byteOrder32Little let bitRaw = bitmapInfo.rawValue | (hasAlpha ? CGImageAlphaInfo.premultipliedFirst.rawValue : CGImageAlphaInfo.noneSkipFirst.rawValue) // create bitmap graphics contexts without alpha info let bitContext = CGContext(data: nil, width: imgRef.width, height: imgRef.height, bitsPerComponent: 8, bytesPerRow: 0, space: colorSpaceRef, bitmapInfo: bitRaw) if bitContext == nil { return self } bitContext!.draw(imgRef, in: CGRect(x: 0, y: 0, width: imgRef.width, height: imgRef.height)) let imgRefWithOutAlpha = bitContext!.makeImage()! let backImg = UIImage(cgImage: imgRefWithOutAlpha, scale: self.scale, orientation: self.imageOrientation) return backImg } }
apache-2.0
18785d599b070d11d19a4ff02779668a
34.138462
168
0.565455
4.685128
false
false
false
false
yunzixun/V2ex-Swift
Model/Moya/Observable+Extension.swift
1
3984
// // Observable+Extension.swift // V2ex-Swift // // Created by huangfeng on 2018/6/11. // Copyright © 2018 Fin. All rights reserved. // import UIKit import RxSwift import ObjectMapper import SwiftyJSON import Moya public enum ApiError : Swift.Error { case Error(info: String) case AccountBanned(info: String) } extension Swift.Error { func rawString() -> String { guard let err = self as? ApiError else { return self.localizedDescription } switch err { case let .Error(info): return info case let .AccountBanned(info): return info } } } extension Observable where Element: Moya.Response { /// 过滤 HTTP 错误,例如超时,请求失败等 func filterHttpError() -> Observable<Element> { return filter{ response in if (200...209) ~= response.statusCode { return true } print("网络错误") throw ApiError.Error(info: "网络错误") } } /// 过滤逻辑错误,例如协议里返回 错误CODE func filterResponseError() -> Observable<JSON> { return filterHttpError().map({ (response) -> JSON in let json = JSON(data: response.data) var code = 200 var msg = "" if let codeStr = json["code"].rawString(), let c = Int(codeStr) { code = c } if json["msg"].exists() { msg = json["msg"].rawString()! } else if json["message"].exists() { msg = json["message"].rawString()! } else if json["info"].exists() { msg = json["info"].rawString()! } else if json["description"].exists() { msg = json["description"].rawString()! } if (code == 200 || code == 99999 || code == 80001 || code == 1){ return json } switch code { default: throw ApiError.Error(info: msg) } }) } /// 将Response 转换成 JSON Model /// /// - Parameters: /// - typeName: 要转换的Model Class /// - dataPath: 从哪个节点开始转换,例如 ["data","links"] func mapResponseToObj<T: Mappable>(_ typeName: T.Type , dataPath:[String] = [] ) -> Observable<T> { return filterResponseError().map{ json in var rootJson = json if dataPath.count > 0{ rootJson = rootJson[dataPath] } if let model: T = self.resultFromJSON(json: rootJson) { return model } else{ throw ApiError.Error(info: "json 转换失败") } } } /// 将Response 转换成 JSON Model Array func mapResponseToObjArray<T: Mappable>(_ type: T.Type, dataPath:[String] = [] ) -> Observable<[T]> { return filterResponseError().map{ json in var rootJson = json; if dataPath.count > 0{ rootJson = rootJson[dataPath] } var result = [T]() guard let jsonArray = rootJson.array else{ return result } for json in jsonArray{ if let jsonModel: T = self.resultFromJSON(json: json) { result.append(jsonModel) } else{ throw ApiError.Error(info: "json 转换失败") } } return result } } private func resultFromJSON<T: Mappable>(jsonString:String) -> T? { return T(JSONString: jsonString) } private func resultFromJSON<T: Mappable>(json:JSON) -> T? { if let str = json.rawString(){ return resultFromJSON(jsonString: str) } return nil } }
mit
47f0f7a8498f2397f6aaaa476d88e793
27.879699
105
0.495965
4.605516
false
false
false
false
EsriJapan/startup-swift-ios
sample/ViewController.swift
1
1775
// // ViewController.swift // sample // // Created by esrij on 2015/06/05. // Copyright (c) 2015年 esrij. All rights reserved. // import UIKit import ArcGIS class ViewController: UIViewController, AGSMapViewLayerDelegate { @IBOutlet var mapView: AGSMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //ベースマップの追加 let tiledLayer = AGSTiledMapServiceLayer(url: URL(string:"https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer")) mapView.addMapLayer(tiledLayer, withName:"Tiled Layer") //主題図の追加 let dynamicLayer = AGSDynamicMapServiceLayer(url: URL(string:"https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer")) //レイヤの表示設定 dynamicLayer?.visibleLayers = [2] mapView.addMapLayer(dynamicLayer, withName:"Dynamic Layer") //初期表示範囲の設定 let envelope = AGSEnvelope(xmin:-15000000, ymin:200000, xmax:-7000000, ymax:8000000, spatialReference: self.mapView.spatialReference) mapView.zoom(to: envelope, animated:false) //デリゲートの設定 mapView.layerDelegate = self } func mapViewDidLoad(_ mapView: AGSMapView!) { //デバイスの位置情報サービスとの連携 mapView.locationDisplay.autoPanMode = .navigation mapView.locationDisplay.startDataSource() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
f22a6c3d56b0348d63934ff0bf8cde90
29.722222
178
0.670283
4.264781
false
false
false
false
glessard/swiftian-dispatch
Tests/deferredTests/DeferredExamples.swift
3
3537
// // DeferredExamples.swift // deferred // // Created by Guillaume Lessard on 2019-11-21. // Copyright © 2019-2020 Guillaume Lessard. All rights reserved. // import Foundation import XCTest import Foundation import Dispatch import deferred class DeferredExamples: XCTestCase { func testExample() { print("Starting") let result1 = Deferred(task: { () -> Double in defer { print("Computing result1") } return 10.5 }).delay(.milliseconds(50)) let result2 = result1.map { (d: Double) -> Int in print("Computing result2") return Int(floor(2*d)) }.delay(.milliseconds(500)) let result3 = result1.map { (d: Double) -> String in print("Computing result3") return (3*d).description } result3.onValue { print("Result 3 is: \($0)") } let result4 = combine(result1, result2) let result5 = result2.map(transform: Double.init).timeout(.milliseconds(50)) print("Waiting") print("Result 1: \(result1.value!)") XCTAssertEqual(result1.value, 10.5) print("Result 2: \(result2.value!)") XCTAssertEqual(result2.value, 21) print("Result 3: \(result3.value!)") XCTAssertEqual(result3.value, String(3*result1.value!)) print("Result 4: \(result4.value!)") XCTAssertEqual(result4.value?.0, result1.value) XCTAssertEqual(result4.value?.1, result2.value) print("Result 5: \(result5.error!)") XCTAssertEqual(result5.value, nil) XCTAssertEqual(result5.error, Cancellation.timedOut("")) print("Done") XCTAssertEqual(result1.error, nil) XCTAssertEqual(result2.error, nil) XCTAssertEqual(result3.error, nil) XCTAssertEqual(result4.error, nil) XCTAssertEqual(result5.value, nil) } func testExample2() { let d = Deferred<Double, Never> { resolver in usleep(50000) resolver.resolve(.success(.pi)) } print(d.value!) } func testExample3() { let transform = Deferred<(Int) -> Double, Never> { i in Double(7*i) } // Deferred<Int throws -> Double> let operand = Deferred<Int, Error>(value: 6).delay(seconds: 0.1) // Deferred<Int> let result = operand.apply(transform: transform) // Deferred<Double> print(result.value!) // 42.0 } func testBigComputation() throws { func bigComputation() -> Deferred<Double, Never> { return Deferred { resolver in DispatchQueue.global(qos: .utility).async { var progress = 0 repeat { // first check that a result is still needed guard resolver.needsResolution else { return } // then work towards a partial computation Thread.sleep(until: Date() + 0.001) print(".", terminator: "") progress += 1 } while progress < 20 // we have an answer! resolver.resolve(value: .pi) } } } // let the child `Deferred` keep a reference to our big computation let timeout = 0.1 let validated = bigComputation().validate(predicate: { $0 > 3.14159 && $0 < 3.14160 }) .timeout(seconds: timeout, reason: String(timeout)) do { print(validated.state) // still waiting: no request yet let pi = try validated.get() // make the request and wait for value print(" ", pi) } catch Cancellation.timedOut(let message) { print() assert(message == String(timeout)) } } }
mit
63b92c179f9e0c0216c45f59e7af2928
27.516129
107
0.604072
4.041143
false
false
false
false
eBardX/XestiMonitors
Tests/UIKit/Accessibility/AccessibilityAnnouncementMonitorTests.swift
1
3241
// // AccessibilityAnnouncementMonitorTests.swift // XestiMonitorsTests // // Created by J. G. Pusey on 2017-12-27. // // © 2017 J. G. Pusey (see LICENSE.md) // import UIKit import XCTest @testable import XestiMonitors internal class AccessibilityAnnouncementMonitorTests: XCTestCase { let notificationCenter = MockNotificationCenter() override func setUp() { super.setUp() NotificationCenterInjector.inject = { self.notificationCenter } } func testMonitor_didFinish() { let expectation = self.expectation(description: "Handler called") let expectedStringValue: String = "This is a test" let expectedWasSuccessful: Bool = true var expectedEvent: AccessibilityAnnouncementMonitor.Event? let monitor = AccessibilityAnnouncementMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() simulateDidFinish(stringValue: expectedStringValue, wasSuccessful: expectedWasSuccessful) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didFinish(info) = event { XCTAssertEqual(info.stringValue, expectedStringValue) XCTAssertEqual(info.wasSuccessful, expectedWasSuccessful) } else { XCTFail("Unexpected event") } } func testMonitor_didFinish_badUserInfo() { let expectation = self.expectation(description: "Handler called") let expectedStringValue: String = " " let expectedWasSuccessful: Bool = false var expectedEvent: AccessibilityAnnouncementMonitor.Event? let monitor = AccessibilityAnnouncementMonitor(queue: .main) { event in XCTAssertEqual(OperationQueue.current, .main) expectedEvent = event expectation.fulfill() } monitor.startMonitoring() simulateDidFinish(stringValue: expectedStringValue, wasSuccessful: expectedWasSuccessful, badUserInfo: true) waitForExpectations(timeout: 1) monitor.stopMonitoring() if let event = expectedEvent, case let .didFinish(info) = event { XCTAssertEqual(info.stringValue, expectedStringValue) XCTAssertEqual(info.wasSuccessful, expectedWasSuccessful) } else { XCTFail("Unexpected event") } } private func simulateDidFinish(stringValue: String, wasSuccessful: Bool, badUserInfo: Bool = false) { let userInfo: [AnyHashable: Any]? if badUserInfo { userInfo = nil } else { userInfo = [UIAccessibilityAnnouncementKeyStringValue: stringValue, UIAccessibilityAnnouncementKeyWasSuccessful: NSNumber(value: wasSuccessful)] } notificationCenter.post(name: .UIAccessibilityAnnouncementDidFinish, object: nil, userInfo: userInfo) } }
mit
2ecd1394379b8927c5ffae60720fbd33
33.468085
100
0.625926
5.714286
false
true
false
false
rajeejones/SavingPennies
Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallGridPulse.swift
5
2560
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallGridPulse: ActivityIndicatorAnimating { // MARK: Properties fileprivate let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) // MARK: ActivityIndicatorAnimating public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSpacing: CGFloat = 2 let circleSize = (size.width - circleSpacing * 2) / 3 let x = (layer.bounds.size.width - size.width) / 2 let y = (layer.bounds.size.height - size.height) / 2 let durations: [CFTimeInterval] = [0.72, 1.02, 1.28, 1.42, 1.45, 1.18, 0.87, 1.45, 1.06] let beginTime = CACurrentMediaTime() let beginTimes: [CFTimeInterval] = [-0.06, 0.25, -0.17, 0.48, 0.31, 0.03, 0.46, 0.78, 0.45] let animation = self.animation // Draw circles for i in 0 ..< 3 { for j in 0 ..< 3 { let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color) let frame = CGRect(x: x + circleSize * CGFloat(j) + circleSpacing * CGFloat(j), y: y + circleSize * CGFloat(i) + circleSpacing * CGFloat(i), width: circleSize, height: circleSize) animation.duration = durations[3 * i + j] animation.beginTime = beginTime + beginTimes[3 * i + j] circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } } } } // MARK: - Setup private extension ActivityIndicatorAnimationBallGridPulse { var animation: CAAnimationGroup { let animation = CAAnimationGroup() animation.animations = [scaleAnimation, opacityAnimation] animation.repeatCount = .infinity animation.isRemovedOnCompletion = false return animation } var scaleAnimation: CAKeyframeAnimation { let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.5, 1] return scaleAnimation } var opacityAnimation: CAKeyframeAnimation { let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.keyTimes = [0, 0.5, 1] opacityAnimation.timingFunctions = [timingFunction, timingFunction] opacityAnimation.values = [1, 0.7, 1] return opacityAnimation } }
gpl-3.0
3eb5c4465bcd7574dc7a2a9f0f71d23c
34.068493
127
0.673047
4.353741
false
false
false
false
BasqueVoIPMafia/cordova-plugin-iosrtc
src/PluginRTCAudioController.swift
1
6153
// // AudioOutputController.swift // StreamingDemo // // Created by ows on 6/11/17. // // import Foundation import AVFoundation class PluginRTCAudioController { static private var audioCategory : AVAudioSession.Category = AVAudioSession.Category.playAndRecord static private var audioCategoryOptions : AVAudioSession.CategoryOptions = [ AVAudioSession.CategoryOptions.mixWithOthers, AVAudioSession.CategoryOptions.allowBluetooth, AVAudioSession.CategoryOptions.allowAirPlay, AVAudioSession.CategoryOptions.allowBluetoothA2DP ] /* This mode is intended for Voice over IP (VoIP) apps and can only be used with the playAndRecord category. When this mode is used, the device’s tonal equalization is optimized for voice and the set of allowable audio routes is reduced to only those appropriate for voice chat. See: https://developer.apple.com/documentation/avfoundation/avaudiosession/mode/1616455-voicechat */ static private var audioMode = AVAudioSession.Mode.voiceChat static private var audioModeDefault : AVAudioSession.Mode = AVAudioSession.Mode.default static private var audioInputSelected: AVAudioSessionPortDescription? = nil // // Audio Input // static func initAudioDevices() -> Void { PluginRTCAudioController.setCategory() do { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() try audioSession.setActive(true) } catch { print("Error messing with audio session: \(error)") } } static func setCategory() -> Void { // Enable speaker NSLog("PluginRTCAudioController#setCategory()") do { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() try audioSession.setCategory( PluginRTCAudioController.audioCategory, mode: PluginRTCAudioController.audioMode, options: PluginRTCAudioController.audioCategoryOptions ) } catch { NSLog("PluginRTCAudioController#setCategory() | ERROR \(error)") }; } // Setter function inserted by save specific audio device static func saveInputAudioDevice(inputDeviceUID: String) -> Void { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() let audioInput: AVAudioSessionPortDescription = audioSession.availableInputs!.filter({ (value:AVAudioSessionPortDescription) -> Bool in return value.uid == inputDeviceUID })[0] PluginRTCAudioController.audioInputSelected = audioInput } // Setter function inserted by set specific audio device static func restoreInputOutputAudioDevice() -> Void { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() do { try audioSession.setPreferredInput(PluginRTCAudioController.audioInputSelected) } catch { NSLog("PluginRTCAudioController:restoreInputOutputAudioDevice: Error setting audioSession preferred input.") } PluginRTCAudioController.setOutputSpeakerIfNeed(enabled: speakerEnabled); } static func setOutputSpeakerIfNeed(enabled: Bool) { speakerEnabled = enabled let audioSession: AVAudioSession = AVAudioSession.sharedInstance() let currentRoute = audioSession.currentRoute if currentRoute.outputs.count != 0 { for description in currentRoute.outputs { if ( description.portType == AVAudioSession.Port.headphones || description.portType == AVAudioSession.Port.bluetoothA2DP || description.portType == AVAudioSession.Port.carAudio || description.portType == AVAudioSession.Port.airPlay || description.portType == AVAudioSession.Port.lineOut ) { NSLog("PluginRTCAudioController#setOutputSpeakerIfNeed() | external audio output plugged in -> do nothing") } else { NSLog("PluginRTCAudioController#setOutputSpeakerIfNeed() | external audio pulled out") if (speakerEnabled) { do { try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) } catch { NSLog("PluginRTCAudioController#setOutputSpeakerIfNeed() | ERROR \(error)") }; } } } } else { NSLog("PluginRTCAudioController#setOutputSpeakerIfNeed() | requires connection to device") } } static func selectAudioOutputSpeaker() { // Enable speaker NSLog("PluginRTCAudioController#selectAudioOutputSpeaker()") speakerEnabled = true; setCategory() do { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.speaker) } catch { NSLog("PluginRTCAudioController#selectAudioOutputSpeaker() | ERROR \(error)") }; } static func selectAudioOutputEarpiece() { // Disable speaker, switched to default NSLog("PluginRTCAudioController#selectAudioOutputEarpiece()") speakerEnabled = false; setCategory() do { let audioSession: AVAudioSession = AVAudioSession.sharedInstance() try audioSession.overrideOutputAudioPort(AVAudioSession.PortOverride.none) } catch { NSLog("PluginRTCAudioController#selectAudioOutputEarpiece() | ERROR \(error)") }; } // // Audio Output // static private var speakerEnabled: Bool = false init() { let shouldManualInit = Bundle.main.object(forInfoDictionaryKey: "ManualInitAudioDevice") as? String if(shouldManualInit == "FALSE") { PluginRTCAudioController.initAudioDevices() } NotificationCenter.default.addObserver( self, selector: #selector(self.audioRouteChangeListener(_:)), name: AVAudioSession.routeChangeNotification, object: nil) } @objc dynamic fileprivate func audioRouteChangeListener(_ notification:Notification) { let audioRouteChangeReason = notification.userInfo![AVAudioSessionRouteChangeReasonKey] as! UInt switch audioRouteChangeReason { case AVAudioSession.RouteChangeReason.newDeviceAvailable.rawValue: NSLog("PluginRTCAudioController#audioRouteChangeListener() | headphone plugged in") case AVAudioSession.RouteChangeReason.oldDeviceUnavailable.rawValue: NSLog("PluginRTCAudioController#audioRouteChangeListener() | headphone pulled out -> restore state speakerEnabled: %@", PluginRTCAudioController.speakerEnabled ? "true" : "false") PluginRTCAudioController.setOutputSpeakerIfNeed(enabled: PluginRTCAudioController.speakerEnabled) default: break } } }
mit
532b3226498da79f01533cd8967bf4e0
31.718085
277
0.768656
4.239145
false
false
false
false
dvidlui/iOS8-day-by-day
24-presentation-controllers/BouncyPresent/BouncyPresent/ViewController.swift
1
1442
// // Copyright 2014 Scott Logic // // 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 class ViewController: UIViewController { let overlayTransitioningDelegate = OverlayTransitioningDelegate() override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if segue.identifier == "bouncySegue" { let overlayVC = segue.destinationViewController as UIViewController prepareOverlayVC(overlayVC) } } @IBAction func handleBouncyPresentPressed(sender: AnyObject) { let overlayVC = storyboard?.instantiateViewControllerWithIdentifier("overlayViewController") as UIViewController prepareOverlayVC(overlayVC) presentViewController(overlayVC, animated: true, completion: nil) } private func prepareOverlayVC(overlayVC: UIViewController) { overlayVC.transitioningDelegate = overlayTransitioningDelegate overlayVC.modalPresentationStyle = .Custom } }
apache-2.0
93d5e5457c9ff6beb77f8c7f570b82d4
33.333333
116
0.763523
4.904762
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Cloud/CKDiscoverUserIdentitiesOperation.swift
2
3850
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit /// A generic protocol which exposes the properties used by Apple's CKDiscoverUserIdentitiesOperation. public protocol CKDiscoverUserIdentitiesOperationProtocol: CKOperationProtocol { /// - returns: the user identity lookup info used in discovery var userIdentityLookupInfos: [UserIdentityLookupInfo] { get set } /// - returns: the block used to return discovered user identities var userIdentityDiscoveredBlock: ((UserIdentity, UserIdentityLookupInfo) -> Void)? { get set } /// - returns: the completion block used for discovering user identities var discoverUserIdentitiesCompletionBlock: ((Error?) -> Void)? { get set } } @available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) extension CKDiscoverUserIdentitiesOperation: CKDiscoverUserIdentitiesOperationProtocol, AssociatedErrorProtocol { // The associated error type public typealias AssociatedError = PKCKError } extension CKProcedure where T: CKDiscoverUserIdentitiesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { public var userIdentityLookupInfos: [T.UserIdentityLookupInfo] { get { return operation.userIdentityLookupInfos } set { operation.userIdentityLookupInfos = newValue } } public var userIdentityDiscoveredBlock: CloudKitProcedure<T>.DiscoverUserIdentitiesUserIdentityDiscoveredBlock? { get { return operation.userIdentityDiscoveredBlock } set { operation.userIdentityDiscoveredBlock = newValue } } func setDiscoverUserIdentitiesCompletionBlock(_ block: @escaping CloudKitProcedure<T>.DiscoverUserIdentitiesCompletionBlock) { operation.discoverUserIdentitiesCompletionBlock = { [weak self] error in if let strongSelf = self, let error = error { strongSelf.append(fatalError: PKCKError(underlyingError: error)) } else { block() } } } } extension CloudKitProcedure where T: CKDiscoverUserIdentitiesOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { /// A typealias for the block type used by CloudKitOperation<CKDiscoverUserIdentitiesOperationType> public typealias DiscoverUserIdentitiesUserIdentityDiscoveredBlock = (T.UserIdentity, T.UserIdentityLookupInfo) -> Void /// A typealias for the block type used by CloudKitOperation<CKDiscoverUserIdentitiesOperationType> public typealias DiscoverUserIdentitiesCompletionBlock = () -> Void /// - returns: the user identity lookup info used in discovery public var userIdentityLookupInfos: [T.UserIdentityLookupInfo] { get { return current.userIdentityLookupInfos } set { current.userIdentityLookupInfos = newValue appendConfigureBlock { $0.userIdentityLookupInfos = newValue } } } /// - returns: the block used to return discovered user identities public var userIdentityDiscoveredBlock: DiscoverUserIdentitiesUserIdentityDiscoveredBlock? { get { return current.userIdentityDiscoveredBlock } set { current.userIdentityDiscoveredBlock = newValue appendConfigureBlock { $0.userIdentityDiscoveredBlock = newValue } } } /** Before adding the CloudKitOperation instance to a queue, set a completion block to collect the results in the successful case. Setting this completion block also ensures that error handling gets triggered. - parameter block: a DiscoverUserIdentitiesCompletionBlock block */ public func setDiscoverUserIdentitiesCompletionBlock(block: @escaping DiscoverUserIdentitiesCompletionBlock) { appendConfigureBlock { $0.setDiscoverUserIdentitiesCompletionBlock(block) } } }
mit
08bf1101d68778fb3bcf1b55a5e84d94
42.247191
142
0.74279
5.930663
false
false
false
false
abeschneider/stem
Sources/Tensor/ordereddictionary.swift
1
3204
// // ordereddictionary.swift // stem // // Created by Schneider, Abraham R. on 6/12/16. // Copyright © 2016 none. All rights reserved. // import Foundation /* Provides a method to store a map of <string:[T]> that can also be accessed by position. The order of the key entries follows insertion order. */ public class OrderedDictionary<T>: Swift.Collection { public typealias Index = Array<T>.Index public typealias _Element = [T] public var keys:[String] = [] public var values:[String:_Element] = [:] public var orderedValues:[_Element] = [] public var startIndex:Index { return orderedValues.startIndex } public var endIndex:Int { return orderedValues.endIndex } public init() {} public init(_ values:[(String, T)]) { add(values) } public init(_ values:[(String, _Element)]) { add(values) } public func add(_ values:[(String, T)]) { for (key, value) in values { self[key] = [value] } } public func add(_ values:[(String, _Element)]) { for (key, value) in values { self[key] = value } } public func add(_ key:String, values:[T]) { self[key] = values } func setValue(_ key:String, _ value:T) { if values[key] == nil { // if key is new, insert it into our indices keys.append(key) orderedValues.append([value]) } else { // otherwise, just update its current value let index = keys.index(of: key)! orderedValues[index] = [value] } values[key] = [value] } func setValue(_ key:String, _ value:_Element) { if values[key] == nil { // if key is new, insert it into our indices keys.append(key) orderedValues.append(value) } else { // otherwise, just update its current value let index = keys.index(of: key)! orderedValues[index] = value } values[key] = value } public subscript(key:String) -> [T]? { get { return values[key] } set { setValue(key, newValue!) } } public subscript(key:String) -> T? { get { if let value = values[key] { return value[0] } return nil } set { setValue(key, newValue!) } } public subscript(index:Int) -> [T] { get { return orderedValues[index] } set { orderedValues[index] = newValue } } public subscript(index:Int) -> T { get { precondition(orderedValues[index].count == 1) return orderedValues[index][0] } set { orderedValues[index] = [newValue] } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return i+1 } }
mit
36c5c9e999ccc2e24d8d1abcbfc9729c
24.830645
77
0.526069
4.259309
false
false
false
false
benjohnde/Caffeine
Caffeine/CaffeineInjector.swift
1
1261
// // CaffeineInjector.swift // Caffeine // // Created by Ben John on 10/05/15. // Copyright (c) 2015 Ben John. All rights reserved. // import Foundation import IOKit.pwr_mgt enum CaffeineStatus { case clean case injected } class CaffeineInjector { let reasonForActivity = "Mac stays awake all night long." var assertionID: IOPMAssertionID = IOPMAssertionID(0) var status: CaffeineStatus = CaffeineStatus.clean fileprivate func createAssertion() -> IOReturn { let type = kIOPMAssertPreventUserIdleDisplaySleep let level = IOPMAssertionLevel(kIOPMAssertionLevelOn) return IOPMAssertionCreateWithName(type as CFString!, level, reasonForActivity as CFString!, &assertionID) } func inject() { release() guard createAssertion() == kIOReturnSuccess else { print("Caffeine could not be injected,") return } status = CaffeineStatus.injected } func release() { guard status == CaffeineStatus.injected else { return } guard IOPMAssertionRelease(assertionID) == kIOReturnSuccess else { print("Caffeine could not be released.") return } status = CaffeineStatus.clean } }
mit
65523f08c7a24fbdc5e4e2398ff2c34e
27.022222
114
0.658208
4.289116
false
false
false
false
TwoRingSoft/SemVer
Vendor/Swiftline/SwiftlineTests/SwiftlineTests/RunnerTests.swift
1
7644
import Foundation import Quick import Nimble @testable import Swiftline class RunnerTests: QuickSpec { override func spec() { var promptPrinter: DummyPromptPrinter! beforeEach { promptPrinter = DummyPromptPrinter() PromptSettings.printer = promptPrinter } describe("dummy executor") { var dummyExecutor: DummyTaskExecutor! it("executes a command") { dummyExecutor = DummyTaskExecutor(status: 0, output: "123", error: "") CommandExecutor.currentTaskExecutor = dummyExecutor let res = 🏃.run("ls -all") expect(res.exitStatus).to(equal(0)) expect(res.stdout).to(equal("123")) expect(res.stderr).to(equal("")) expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) } it("execute a command and handle erros") { dummyExecutor = DummyTaskExecutor(status: 1, output: "", error: "123") CommandExecutor.currentTaskExecutor = dummyExecutor let res = 🏃.run("test test test") expect(res.exitStatus).to(equal(1)) expect(res.stdout).to(equal("")) expect(res.stderr).to(equal("123")) expect(dummyExecutor.commandsExecuted).to(equal(["test test test"])) } it("execute a command with arguments seperated") { dummyExecutor = DummyTaskExecutor(status: 1, output: "", error: "123") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls", args: ["-all"]) expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) 🏃.run("echo", args: "bbb") expect(dummyExecutor.commandsExecuted).to(equal(["ls -all", "echo bbb"])) } } describe("With echo") { it("echo back stdout and stderr") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "Command output was", error: "error out") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls", args: ["-all"]) { s in s.echo = [.Stdout, .Stderr] } expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) let output = [ "Stdout: ", "Command output was", "Stderr: ", "error out\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } it("does not echo if empty") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "", error: "error out") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls", args: ["-all"]) { s in s.echo = [.Stdout, .Stderr] } expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) let output = [ "Stderr: ", "error out\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } it("echos only the command") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "", error: "error out") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls", args: ["-all"]) { s in s.echo = .Command } expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) let output = [ "Command: ", "ls -all\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } it("echo back stdout only") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "Command output was 2", error: "error out 2") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls") { $0.echo = .Stdout } let output = [ "Stdout: ", "Command output was 2\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } it("echo back stderr only") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "Command output was 2", error: "error out 2") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls") { $0.echo = .Stderr } let output = [ "Stderr: ", "error out 2\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } it("echo back nothing") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "Command output was 2", error: "error out 2") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls") { $0.echo = .None } expect(promptPrinter.printed).to(equal("")) } it("execute command with an echo") { let dummyExecutor = DummyTaskExecutor(status: 1, output: "Command output was 2", error: "error out 2") CommandExecutor.currentTaskExecutor = dummyExecutor 🏃.run("ls -all", echo: [.Command]) expect(dummyExecutor.commandsExecuted).to(equal(["ls -all"])) let output = [ "Command: ", "ls -all\n"].joinWithSeparator("\n") expect(promptPrinter.printed).to(equal(output)) } } describe("Actual executor") { it("execute ls") { CommandExecutor.currentTaskExecutor = ActualTaskExecutor() let res = 🏃.run("ls -all") expect(res.exitStatus).to(equal(0)) expect(res.stdout).notTo(equal("")) expect(res.stderr).to(equal("")) } } describe("dry run") { it("execute ls") { CommandExecutor.currentTaskExecutor = ActualTaskExecutor() let res = 🏃.run("ls -all") { $0.dryRun = true } expect(res.exitStatus).to(equal(0)) expect(res.stdout).to(equal("")) expect(res.stderr).to(equal("")) expect(promptPrinter.printed).to(equal("Executed command 'ls -all'\n")) } } describe("interactive run") { it("execute ls") { CommandExecutor.currentTaskExecutor = InteractiveTaskExecutor() let res = 🏃.runWithoutCapture("ls -all") expect(res).to(equal(0)) } } } }
apache-2.0
8685469a38621965450c3076a94dbfcb
37.393939
118
0.457774
5.239145
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Control/DataSource.swift
1
1767
// // DataSource.swift // ZeeQL // // Created by Helge Hess on 24/02/17. // Copyright © 2017-2021 ZeeZide GmbH. All rights reserved. // /** * A DataSource performs a query against some 'entity', in the ORM usually a * database table (which is mapped to an Entity). * * The ZeeQL DataSources always have an FetchSpecification which specifies * the environment for fetches. * * The DataSource is very general, but ORM specific subclasses include: * - DatabaseDataSource * - ActiveDataSource * - AdaptorDataSource */ open class DataSource<Object: SwiftObject>: EquatableType, Equatable { // Used to be a protocol, but Swift 3 and generic protocols .... open var fetchSpecification : FetchSpecification? open func fetchObjects(cb: ( Object ) -> Void) throws { fatalError("Subclass must implement: \(#function)") } open func fetchCount() throws -> Int { fatalError("Subclass must implement: \(#function)") } // MARK: - Equatable public func isEqual(to object: Any?) -> Bool { guard let other = object as? DataSource else { return false } return other.isEqual(to: self) } public func isEqual(to object: DataSource) -> Bool { return self === object } public static func ==(lhs: DataSource, rhs: DataSource) -> Bool { return lhs.isEqual(to: rhs) } } /** * Protocol which enforces that a type is a class type (to be used as a generic * constraint). * Like `AnyObject` w/o the `@objc`. */ public protocol SwiftObject: AnyObject { // is there a standard protocol for this? `AnyObject` also does @objc ... } public extension DataSource { func fetchObjects() throws -> [ Object ] { var objects = [ Object ]() try fetchObjects { objects.append($0) } return objects } }
apache-2.0
c937e1650ceb289f9cece0e52181c78a
26.169231
79
0.67667
4.097448
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
92
3766
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit #if !RX_NO_MODULE import RxSwift #endif let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() final class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 0 } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { rxAbstractMethod(message: dataSourceNotSet) } } /// For more information take a look at `DelegateProxyType`. public class RxCollectionViewDataSourceProxy : DelegateProxy , UICollectionViewDataSource , DelegateProxyType { /// Typed parent object. public weak private(set) var collectionView: UICollectionView? private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet /// Initializes `RxCollectionViewDataSourceProxy` /// /// - parameter parentObject: Parent object for delegate proxy. public required init(parentObject: AnyObject) { self.collectionView = castOrFatalError(parentObject) super.init(parentObject: parentObject) } // MARK: delegate /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) } /// Required delegate method implementation. public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) } // MARK: proxy /// For more information take a look at `DelegateProxyType`. public override class func createProxyForObject(_ object: AnyObject) -> AnyObject { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.createRxDataSourceProxy() } /// For more information take a look at `DelegateProxyType`. public override class func delegateAssociatedObjectTag() -> UnsafeRawPointer { return dataSourceAssociatedTag } /// For more information take a look at `DelegateProxyType`. public class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UICollectionView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } /// For more information take a look at `DelegateProxyType`. public class func currentDelegateFor(_ object: AnyObject) -> AnyObject? { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.dataSource } /// For more information take a look at `DelegateProxyType`. public override func setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UICollectionViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
mit
844725f00d5487297aad368ffb58aaa6
37.418367
141
0.747676
6.22314
false
false
false
false
Pyroh/Fluor
Fluor/Controllers/ViewControllers/SwitchMethodSelectionViewController.swift
1
2210
// // SwitchMethodSelectionViewController.swift // Fluor // // Created by Pierre TACCHI on 26/02/2020. // Copyright © 2020 Pyrolyse. All rights reserved. // import Cocoa protocol WelcomeTabViewChildren: NSViewController { var welcomeTabViewController: WelcomeTabViewController? { get } } extension WelcomeTabViewChildren { var welcomeTabViewController: WelcomeTabViewController? { self.presentingViewController as? WelcomeTabViewController } } class SwitchMethodSelectionViewController: NSViewController, WelcomeTabViewChildren { @IBOutlet weak var activeAppSelectableView: SelectableView! @IBOutlet weak var fnKeySelectableView: SelectableView! deinit { self.resignAsObserver() } override func viewDidLoad() { super.viewDidLoad() self.applyAsObserver() } private func applyAsObserver() { self.activeAppSelectableView.addObserver(self, forKeyPath: "isSelected", options: [.new], context: nil) self.fnKeySelectableView.addObserver(self, forKeyPath: "isSelected", options: [.new], context: nil) } private func resignAsObserver() { self.activeAppSelectableView.removeObserver(self, forKeyPath: "isSelected") self.fnKeySelectableView.removeObserver(self, forKeyPath: "isSelected") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case "isSelected": if object as AnyObject === self.activeAppSelectableView, change?[.newKey] as? Bool == true { self.activeAppHasBeenSelected() } if object as AnyObject === self.fnKeySelectableView, change?[.newKey] as? Bool == true { self.fnKeyHasBeenSelected() } default: super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private func activeAppHasBeenSelected() { self.fnKeySelectableView.isSelected = false } private func fnKeyHasBeenSelected() { self.activeAppSelectableView.isSelected = false } }
mit
79d8e8c1e671224a629cdd561c5707e0
32.984615
151
0.683567
4.844298
false
false
false
false
andrea-prearo/SwiftExamples
DataPassing/Delegation/Delegation/ViewControllerA.swift
1
1408
// // ViewControllerA.swift // Delegation // // Created by Andrea Prearo on 2/19/18. // Copyright © 2018 Andrea Prearo. All rights reserved. // import UIKit // Passing Data Between View Controllers in iOS: the Definitive Guide // http://matteomanferdini.com/how-ios-view-controllers-communicate-with-each-other/ protocol ViewControllerADelegate: class { func didChangeTargetLabel(text: String?) } class ViewControllerA: UIViewController, ViewControllerADelegate { @IBOutlet weak var targetLabel: UILabel! @IBOutlet weak var navigateButton: UIButton! private static let toBSegue = "AToBSegue" override func viewDidLoad() { super.viewDidLoad() targetLabel.text = "Test" } // MARK: - ViewControllerADelegate func didChangeTargetLabel(text: String?) { targetLabel.text = text } // MARK: - IBActions @IBAction func didTapNavigateButton(_ sender: Any) { performSegue(withIdentifier: ViewControllerA.toBSegue, sender: self) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == ViewControllerA.toBSegue { guard let viewControllerB = segue.destination as? ViewControllerB else { return } viewControllerB.targetText = targetLabel.text viewControllerB.delegate = self } } }
mit
bbc456a577ccd23495d0772d49bfcd60
27.14
84
0.678038
4.383178
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/CommonTableExpressionTests.swift
1
34903
import XCTest import GRDB class CommonTableExpressionTests: GRDBTestCase { func testInitializers() { // Implicit generic RowDecoder type is Row func acceptRowCTE(_ cte: CommonTableExpression<Row>) { } do { let cte = CommonTableExpression(named: "foo", sql: "") acceptRowCTE(cte) } do { let cte = CommonTableExpression(named: "foo", literal: "") acceptRowCTE(cte) } do { let cte = CommonTableExpression(named: "foo", request: SQLRequest<Void>("")) acceptRowCTE(cte) } // Explicit type struct S { } _ = CommonTableExpression<S>(named: "foo", sql: "") _ = CommonTableExpression<S>(named: "foo", literal: "") _ = CommonTableExpression<S>(named: "foo", request: SQLRequest<Void>("")) } func testQuery() throws { struct T: TableRecord { } try makeDatabaseQueue().write { db in try db.create(table: "t") { t in t.autoIncrementedPrimaryKey("id") } // Just add a WITH clause: sql + arguments do { let cte = CommonTableExpression( named: "cte", sql: "SELECT ?", arguments: ["O'Brien"]) let request = T.all() .with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "t" """) } // Just add a WITH clause: sql interpolation do { let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request = T.all() .with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "t" """) } // Just add a WITH clause: query interface request do { let cteRequest = T.all() let cte = CommonTableExpression(named: "cte", request: cteRequest) let request = T.all() .with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT * FROM "t" """) } // Just add a WITH clause: sql request do { let cteRequest: SQLRequest<Int> = "SELECT \("O'Brien")" let cte = CommonTableExpression(named: "cte", request: cteRequest) let request = T.all() .with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "t" """) } // Include query interface request as a CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(optional: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ LEFT JOIN "cte" ON "t"."id" > "cte"."id" """) } // Include SQL request as a CTE do { let cte = CommonTableExpression( named: "cte", literal: "SELECT 1 as id") let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] == right["id"] })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 1 as id) \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "t"."id" = "cte"."id" """) } // Include a filtered SQL request as a CTE do { let cte = CommonTableExpression( named: "cte", literal: "SELECT 1 AS a") let request = T.all() .with(cte) .including(required: T.association(to: cte).filter(Column("a") != nil)) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 1 AS a) \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "cte"."a" IS NOT NULL """) } // Include SQL request as a CTE (empty columns) do { let cte = CommonTableExpression( named: "cte", columns: [], literal: "SELECT 1 AS id") let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] == right["id"] })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 1 AS id) \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "t"."id" = "cte"."id" """) } // Include SQL request as a CTE (custom column name) do { let cte = CommonTableExpression( named: "cte", columns: ["id", "a"], literal: "SELECT 1, 2") let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] == right["id"] })) try assertEqualSQL(db, request, """ WITH "cte"("id", "a") AS (SELECT 1, 2) \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "t"."id" = "cte"."id" """) } // Include SQL request as a CTE (empty ON clause) do { let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request = T.all() .with(cte) .including(required: T.association(to: cte)) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" """) } // Join query interface request as a CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .joining(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".* \ FROM "t" \ JOIN "cte" ON "t"."id" > "cte"."id" """) } // Include filtered CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte).filter(Column("id") > 0)) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "cte"."id" > 0 """) } // Include ordered CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte).order(Column("id"))) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" \ ORDER BY "cte"."id" """) } // Aliased CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let alias = TableAlias() let request = T.all() .with(cte) .including(required: T.association(to: cte).aliased(alias)) .filter(alias[Column("id")] > 0) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" \ WHERE "cte"."id" > 0 """) } // Include one CTE twice with same key and condition do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON "t"."id" > "cte"."id" """) } // Include one CTE twice with same key but different condition (last condition wins) do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] })) .including(required: T.association(to: cte, on: { (left, right) in left["id"] + right["id"] == 1 })) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte".* \ FROM "t" \ JOIN "cte" ON ("t"."id" + "cte"."id") = 1 """) } // Include one CTE twice with different keys do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .including(required: T.association(to: cte, on: { (left, right) in left["id"] > right["id"] }).forKey("a")) .including(required: T.association(to: cte, on: { (left, right) in left["id"] < right["id"] }).forKey("b")) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT "t".*, "cte1".*, "cte2".* \ FROM "t" \ JOIN "cte" "cte1" ON "t"."id" > "cte1"."id" \ JOIN "cte" "cte2" ON "t"."id" < "cte2"."id" """) } // Chain CTE includes do { enum CTE1 { } enum CTE2 { } let cte1 = CommonTableExpression<CTE1>(named: "cte1", request: T.all()) let cte2 = CommonTableExpression<CTE2>( named: "cte2", literal: "SELECT \("O'Brien")") let assoc1 = T.association(to: cte1) let assoc2 = cte1.association(to: cte2) for assoc3 in [ cte2.association(to: T.self), cte2.association(to: Table("t")), ] { let request = T.all() .with(cte1) .with(cte2) .including(required: assoc1.including(required: assoc2.including(required: assoc3))) try assertEqualSQL(db, request, """ WITH \ "cte1" AS (SELECT * FROM "t"), \ "cte2" AS (SELECT 'O''Brien') \ SELECT "t1".*, "cte1".*, "cte2".*, "t2".* \ FROM "t" "t1" \ JOIN "cte1" \ JOIN "cte2" \ JOIN "t" "t2" """) } } // Use CTE as a subquery do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .annotated(with: cte.all()) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT *, (SELECT * FROM "cte") FROM "t" """) } // Use CTE as a collection do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .filter(cte.contains(Column("id"))) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT * \ FROM "t" \ WHERE "id" IN "cte" """) } // Use filtered CTE as a subquery do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = T.all() .with(cte) .annotated(with: cte.all().filter(Column("id") > 1)) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT *, (SELECT * FROM "cte" WHERE "id" > 1) \ FROM "t" """) } // Select from a CTE do { let cte = CommonTableExpression(named: "cte", request: T.all()) let request = cte.all().with(cte) try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT * FROM "t") \ SELECT * FROM "cte" """) } } } func testFetchFromCTE() throws { try makeDatabaseQueue().read { db in do { // Default row decoder is Row let answer = CommonTableExpression( named: "answer", sql: "SELECT 42 AS value") let row = try answer.all().with(answer).fetchOne(db) XCTAssertEqual(row, ["value": 42]) } do { struct Answer: Decodable, FetchableRecord, Equatable { var value: Int } let cte = CommonTableExpression<Answer>( named: "answer", sql: "SELECT 42 AS value") let answer = try cte.all().with(cte).fetchOne(db) XCTAssertEqual(answer, Answer(value: 42)) } } } func testCTEAsSubquery() throws { try makeDatabaseQueue().write { db in struct Player: Decodable, FetchableRecord, TableRecord { var id: Int64 var score: Int } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("score", .integer) } let answer = CommonTableExpression( named: "answer", sql: "SELECT 42 AS value") let request = Player .filter(Column("score") == answer.all()) .with(answer) try assertEqualSQL(db, request, """ WITH "answer" AS (SELECT 42 AS value) \ SELECT * \ FROM "player" \ WHERE "score" = (SELECT * FROM "answer") """) } } func testChatWithLatestMessage() throws { struct Chat: Codable, FetchableRecord, PersistableRecord, Equatable { var id: Int64 } struct Post: Codable, FetchableRecord, PersistableRecord, Equatable { var id: Int64 var chatID: Int64 var date: Int // easier to test } struct ChatInfo: Decodable, FetchableRecord, Equatable { var chat: Chat var latestPost: Post? } try makeDatabaseQueue().write { db in try db.create(table: "chat") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "post") { t in t.autoIncrementedPrimaryKey("id") t.column("chatID", .integer).notNull().references("chat") t.column("date", .datetime).notNull() } try Chat(id: 1).insert(db) try Post(id: 1, chatID: 1, date: 1).insert(db) try Post(id: 2, chatID: 1, date: 2).insert(db) try Post(id: 3, chatID: 1, date: 3).insert(db) try Chat(id: 2).insert(db) try Post(id: 4, chatID: 2, date: 3).insert(db) try Post(id: 5, chatID: 2, date: 2).insert(db) try Post(id: 6, chatID: 2, date: 1).insert(db) try Chat(id: 3).insert(db) // https://sqlite.org/lang_select.html // > When the min() or max() aggregate functions are used in an // > aggregate query, all bare columns in the result set take values // > from the input row which also contains the minimum or maximum. let latestPostRequest = Post .annotated(with: max(Column("date"))) .group(Column("chatID")) let latestPostCTE = CommonTableExpression( named: "latestPost", request: latestPostRequest) let latestPost = Chat.association(to: latestPostCTE, on: { chat, latestPost in chat[Column("id")] == latestPost[Column("chatID")] }) let request = Chat .with(latestPostCTE) .including(optional: latestPost) .orderByPrimaryKey() .asRequest(of: ChatInfo.self) try assertEqualSQL(db, request, """ WITH "latestPost" AS (SELECT *, MAX("date") FROM "post" GROUP BY "chatID") \ SELECT "chat".*, "latestPost".* \ FROM "chat" \ LEFT JOIN "latestPost" ON "chat"."id" = "latestPost"."chatID" \ ORDER BY "chat"."id" """) let chatInfos = try request.fetchAll(db) XCTAssertEqual(chatInfos, [ ChatInfo(chat: Chat(id: 1), latestPost: Post(id: 3, chatID: 1, date: 3)), ChatInfo(chat: Chat(id: 2), latestPost: Post(id: 4, chatID: 2, date: 3)), ChatInfo(chat: Chat(id: 3), latestPost: nil), ]) } } func testRecursiveCounter() throws { try makeDatabaseQueue().read { db in func counterRequest(range: ClosedRange<Int>) -> QueryInterfaceRequest<Int> { let counter = CommonTableExpression<Int>( recursive: true, named: "counter", columns: ["x"], literal: """ VALUES(\(range.lowerBound)) \ UNION ALL \ SELECT x+1 FROM counter WHERE x < \(range.upperBound) """) return counter.all().with(counter) } try assertEqualSQL(db, counterRequest(range: 0...10), """ WITH RECURSIVE \ "counter"("x") AS (VALUES(0) UNION ALL SELECT x+1 FROM counter WHERE x < 10) \ SELECT * FROM "counter" """) try XCTAssertEqual(counterRequest(range: 0...10).fetchAll(db), Array(0...10)) try XCTAssertEqual(counterRequest(range: 3...7).fetchAll(db), Array(3...7)) } } func testInterpolation() throws { try makeDatabaseQueue().read { db in do { let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request: SQLRequest<Void> = """ WITH \(definitionFor: cte) \ SELECT * FROM \(cte) """ try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "cte" """) } do { let cte = CommonTableExpression( named: "cte", literal: "SELECT \("O'Brien")") let request: SQLRequest<Void> = """ WITH \(definitionFor: cte) \ \(cte.all()) """ try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "cte" """) } do { let cte = CommonTableExpression( named: "cte", columns: [], literal: "SELECT \("O'Brien")") let request: SQLRequest<Void> = """ WITH \(definitionFor: cte) \ SELECT * FROM \(cte) """ try assertEqualSQL(db, request, """ WITH "cte" AS (SELECT 'O''Brien') \ SELECT * FROM "cte" """) } do { let cte = CommonTableExpression( named: "cte", columns: ["name"], literal: "SELECT \("O'Brien")") let request: SQLRequest<Void> = """ WITH \(definitionFor: cte) \ SELECT * FROM \(cte) """ try assertEqualSQL(db, request, """ WITH "cte"("name") AS (SELECT 'O''Brien') \ SELECT * FROM "cte" """) } do { let cte = CommonTableExpression( named: "cte", columns: ["name", "score"], literal: "SELECT \("O'Brien"), 12") let request: SQLRequest<Void> = """ WITH \(definitionFor: cte) \ SELECT * FROM \(cte) """ try assertEqualSQL(db, request, """ WITH "cte"("name", "score") AS (SELECT 'O''Brien', 12) \ SELECT * FROM "cte" """) } } } func testUpdate() throws { try makeDatabaseQueue().write { db in try db.create(table: "t") { t in t.column("a") } struct T: Encodable, PersistableRecord { } let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") try T.with(cte).updateAll(db, Column("a").set(to: cte.all())) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) UPDATE "t" SET "a" = (SELECT * FROM "cte") """) } } func testDelete() throws { try makeDatabaseQueue().write { db in try db.create(table: "t") { t in t.column("a") } struct T: Encodable, PersistableRecord { } let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") try T.with(cte) .filter(cte.contains(Column("a"))) .deleteAll(db) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) \ DELETE FROM "t" \ WHERE "a" IN "cte" """) } } func testAssociation() throws { try makeDatabaseQueue().write { db in try db.create(table: "team") { t in t.autoIncrementedPrimaryKey("id") } try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("teamId", .integer).references("team") } try db.create(table: "award") { t in t.autoIncrementedPrimaryKey("id") t.column("playerId", .integer).references("player") } struct Team: TableRecord { } struct Player: TableRecord { static let team = belongsTo(Team.self) } struct Award: TableRecord { static let player = belongsTo(Player.self) static let team = hasOne(Team.self, through: player, using: Player.team) } do { // CTE on association let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") let request = Award .joining(optional: Award.player.with(cte)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" """) } do { // CTE on hasOneThrough association let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") let request = Award .joining(optional: Award.team.with(cte)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ LEFT JOIN "team" ON "team"."id" = "player"."teamId" """) } do { // CTE on pivot of hasOneThrough association let cte = CommonTableExpression(named: "cte", sql: "SELECT 1") let team = Award.hasOne(Team.self, through: Award.player.with(cte), using: Player.team) let request = Award .joining(optional: team) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ LEFT JOIN "team" ON "team"."id" = "player"."teamId" """) } do { // Distinct CTEs on association and main request let cte1 = CommonTableExpression(named: "cte1", sql: "SELECT 1") let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 2") let request = Award .with(cte1) .joining(optional: Award.player.with(cte2)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte1" AS (SELECT 1), \ "cte2" AS (SELECT 2) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" """) } do { // Conflicting CTEs. The rule is: the last one wins. do { // Conflicting CTE on association and main request let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") let request = Award .with(cte1) .joining(optional: Award.player.with(cte2)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 2) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" """) } do { // Conflicting CTE on two associations let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") let request = Award .joining(optional: Award.player.with(cte1)) .joining(optional: Award.team.with(cte2)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 2) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ LEFT JOIN "team" ON "team"."id" = "player"."teamId" """) } do { // Conflicting CTE on two associations let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") let request = Award .joining(optional: Award.team.with(cte1)) .joining(optional: Award.player.with(cte2)) _ = try Row.fetchAll(db, request) // There's a trick here. The last CTE wins, and the last cte // is cte1: it is plugged on top of Award.player, where cte2 // is attached. XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 1) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" ON "player"."id" = "award"."playerId" \ LEFT JOIN "team" ON "team"."id" = "player"."teamId" """) } do { // Conflicting CTE on two associations let cte1 = CommonTableExpression(named: "cte", sql: "SELECT 1") let cte2 = CommonTableExpression(named: "cte", sql: "SELECT 2") let request = Award .joining(optional: Award.player.forKey("player1").with(cte1)) .joining(optional: Award.player.forKey("player2").with(cte2)) _ = try Row.fetchAll(db, request) XCTAssertEqual(lastSQLQuery, """ WITH "cte" AS (SELECT 2) \ SELECT "award".* \ FROM "award" \ LEFT JOIN "player" "player1" ON "player1"."id" = "award"."playerId" \ LEFT JOIN "player" "player2" ON "player2"."id" = "award"."playerId" """) } } } } // https://github.com/groue/GRDB.swift/issues/1275 func testIssue1275() throws { try makeDatabaseQueue().read { db in do { // Failing case: test that error message suggests to fix the cte // definition by declaring columns. let cte1 = CommonTableExpression(named: "cte1", sql: "SELECT * FROM cte2") let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 1 AS a") let association = cte1.association(to: cte2) let request = cte1.all().with(cte1).with(cte2).including(required: association) _ = try request.asRequest(of: Row.self).fetchOne(db) } catch let error as DatabaseError { XCTAssertEqual(error.resultCode, .SQLITE_ERROR) XCTAssertEqual(error.message, """ Can't compute the number of columns in the "cte1" common table expression: \ no such table: cte2. Check the syntax of the SQL definition, \ or provide the explicit list of selected columns with the \ `columns` parameter in the CommonTableExpression initializer. """) } do { // Fixed case: specify columns let cte1 = CommonTableExpression(named: "cte1", columns: ["a"], sql: "SELECT * FROM cte2") let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 1 AS a") let association = cte1.association(to: cte2) let request = cte1.all().with(cte1).with(cte2).including(required: association) _ = try request.asRequest(of: Row.self).fetchOne(db) } do { // Handled case: no need to specify columns let cte1 = CommonTableExpression(named: "cte1", request: Table("cte2").select(Column("a"))) let cte2 = CommonTableExpression(named: "cte2", sql: "SELECT 1 AS a") let association = cte1.association(to: cte2) let request = cte1.all().with(cte1).with(cte2).including(required: association) _ = try request.asRequest(of: Row.self).fetchOne(db) } } } }
mit
302f8a53c8056abe9d7bb77fe481d4f0
41.204353
127
0.421368
4.840915
false
false
false
false
practicalswift/swift
test/SILOptimizer/let_propagation.swift
13
7629
// RUN: %target-swift-frontend -primary-file %s -emit-sil -enforce-exclusivity=unchecked -O | %FileCheck %s // Check that LoadStoreOpts can handle "let" variables properly. // Such variables should be loaded only once and their loaded values can be reused. // This is safe, because once assigned, these variables cannot change their value. // Helper function, which models an external functions with unknown side-effects. // It is called just to trigger flushing of all known stored in LoadStore optimizations. @inline(never) func action() { print("") } final public class A0 { let x: Int32 let y: Int32 init(_ x: Int32, _ y: Int32) { self.x = x self.y = y } @inline(never) func sum1() -> Int32 { // x and y should be loaded only once. let n = x + y action() let m = x - y action() let p = x - y + 1 return n + m + p } func sum2() -> Int32 { // x and y should be loaded only once. let n = x + y action() let m = x - y action() let p = x - y + 1 return n + m + p } } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that counter computation is completely evaluated // at compile-time, because the value of a.x and a.y are known // from the initializer and propagated into their uses, because // we know that action() invocations do not affect their values. // // DISABLECHECK-LABEL: sil {{.*}}testAllocAndUseLet // DISABLECHECK: bb0 // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: bb1 // DISABLECHECK: function_ref @$s15let_propagation6actionyyF // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: apply // DISABLECHECK: integer_literal $Builtin.Int32, 36 // DISABLECHECK-NEXT: struct $Int32 ({{.*}} : $Builtin.Int32) // DISABLECHECK-NEXT: return @inline(never) public func testAllocAndUseLet() -> Int32 { let a = A0(3, 1) var counter: Int32 // a.x and a.y should be loaded only once. counter = a.sum2() + a.sum2() counter += a.sum2() + a.sum2() return counter } */ /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that a.x and a.y are loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testUseLet // DISABLECHECK: bb0 // DISABLECHECK: ref_element_addr // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK: ref_element_addr // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK-NOT: bb1 // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: load // DISABLECHECK: return @inline(never) public func testUseLet(a: A0) -> Int32 { var counter: Int32 // a.x and a.y should be loaded only once. counter = a.sum2() + a.sum2() counter += a.sum2() + a.sum2() return counter } */ struct Goo { var x: Int32 var y: Int32 } struct Foo { var g: Goo } struct Bar { let f: Foo var h: Foo @inline(never) mutating func action() { } } @inline(never) func getVal() -> Int32 { return 9 } // Global let let gx: Int32 = getVal() let gy: Int32 = getVal() func sum3() -> Int32 { // gx and gy should be loaded only once. let n = gx + gy action() let m = gx - gy action() let p = gx - gy + 1 return n + m + p } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that gx and gy are loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testUseGlobalLet // DISABLECHECK: bb0 // DISABLECHECK: global_addr @$s15let_propagation2gys5Int32Vv // DISABLECHECK: global_addr @$s15let_propagation2gxs5Int32Vv // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK: struct_element_addr // DISABLECHECK: load // DISABLECHECK-NOT: bb1 // DISABLECHECK-NOT: global_addr // DISABLECHECK-NOT: ref_element_addr // DISABLECHECK-NOT: struct_element_addr // DISABLECHECK-NOT: load // DISABLECHECK: return @inline(never) public func testUseGlobalLet() -> Int32 { var counter: Int32 = 0 // gx and gy should be loaded only once. counter = sum3() + sum3() + sum3() + sum3() return counter } */ struct A1 { private let x: Int32 // Propagate the value of the initializer into all instructions // that use it, which in turn would allow for better constant // propagation. private let y: Int32 = 100 init(v: Int32) { if v > 0 { x = 1 } else { x = -1 } } // CHECK-LABEL: sil hidden @$s15let_propagation2A1V2f1{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK: struct_extract {{.*}}#A1.x // CHECK: struct_extract {{.*}}#Int32._value // CHECK-NOT: load // CHECK-NOT: struct_extract // CHECK-NOT: struct_element_addr // CHECK-NOT: ref_element_addr // CHECK-NOT: bb1 // CHECK: return func f1() -> Int32 { // x should be loaded only once. return x + x } // CHECK-LABEL: sil hidden @$s15let_propagation2A1V2f2{{[_0-9a-zA-Z]*}}F // CHECK: bb0 // CHECK: integer_literal $Builtin.Int32, 200 // CHECK-NEXT: struct $Int32 // CHECK-NEXT: return func f2() -> Int32 { // load y only once. return y + y } } class A2 { let x: B2 = B2() // CHECK-LABEL: sil hidden @$s15let_propagation2A2C2af{{[_0-9a-zA-Z]*}}F // bb0 // CHECK: %[[X:[0-9]+]] = ref_element_addr {{.*}}A2.x // CHECK-NEXT: load %[[X]] // CHECK: ref_element_addr {{.*}}B2.i // CHECK: %[[XI:[0-9]+]] = struct_element_addr {{.*}}#Int32._value // CHECK-NEXT: load %[[XI]] // return func af() -> Int32 { // x and x.i should be loaded only once. return x.f() + x.f() } } final class B2 { var i: Int32 = 10 func f() -> Int32 { return i } } @inline(never) func oops() { } struct S { let elt : Int32 } // Check that we can handle reassignments to a variable // of struct type properly. // CHECK-LABEL: sil {{.*}}testStructWithLetElement // CHECK-NOT: function_ref @{{.*}}oops // CHECK: return public func testStructWithLetElement() -> Int32 { var someVar = S(elt: 12) let tmp1 = someVar.elt someVar = S(elt: 15) let tmp2 = someVar.elt // This check should get eliminated if (tmp2 == tmp1) { // If we get here, the compiler has propagated // the old value someVar.elt into tmp2, which // is wrong. oops() } return tmp1+tmp2 } public typealias Tuple3 = (Int32, Int32, Int32) final public class S3 { let x: Tuple3 var y: Tuple3 init(x: Tuple3, y:Tuple3) { self.x = x self.y = y } } /* // DISABLE THIS TEST CASE FOR NOW. AS RLE GETS BETTER. WILL RE-ENABLE. // // Check that s.x.0 is loaded only once and then reused. // DISABLECHECK-LABEL: sil {{.*}}testLetTuple // DISABLECHECK: tuple_element_addr // DISABLECHECK: %[[X:[0-9]+]] = struct_element_addr // DISABLECHECK: load %[[X]] // DISABLECHECK-NOT: load %[[X]] // DISABLECHECK: return public func testLetTuple(s: S3) -> Int32 { var counter: Int32 = 0 counter += s.x.0 action() counter += s.x.0 action() counter += s.x.0 action() counter += s.x.0 action() return counter } */ // Check that s.x.0 is reloaded every time. // CHECK-LABEL: sil {{.*}}testVarTuple // CHECK: tuple_element_addr // CHECK: %[[X:[0-9]+]] = struct_element_addr // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: load %[[X]] // CHECK: return public func testVarTuple(s: S3) -> Int32 { var counter: Int32 = 0 counter += s.y.0 action() counter += s.y.0 action() counter += s.y.0 action() counter += s.y.0 action() return counter }
apache-2.0
fe84c7805d284bf935a71cf538270e55
21.841317
108
0.638091
3.067551
false
false
false
false
Gathros/algorithm-archive
contents/monte_carlo_integration/code/swift/monte_carlo.swift
2
714
func inCircle(x: Double, y: Double, radius: Double) -> Bool { return (x*x) + (y*y) < radius*radius } func monteCarlo(n: Int) -> Double { let radius: Double = 1 var piCount = 0 var randX: Double var randY: Double for _ in 0...n { randX = Double.random(in: 0..<radius) randY = Double.random(in: 0..<radius) if(inCircle(x: randX, y: randY, radius: radius)) { piCount += 1 } } let piEstimate = Double(4 * piCount)/(Double(n)) return piEstimate } func main() { let piEstimate = monteCarlo(n: 10000) print("Pi estimate is: ", piEstimate) print("Percent error is: \(100 * abs(piEstimate - Double.pi)/Double.pi)%") } main()
mit
8963ed0794f790c83ec64a05ba42a112
22.8
78
0.578431
3.201794
false
false
false
false
rc2server/appserver
Sources/appcore/ComputeWorker.swift
1
6236
// // ComputeWorker.swift // kappserver // // Created by Mark Lilback on 9/14/19. // import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif import Logging import Socket import NIO import NIOHTTP1 import WebSocketKit // FIXME: This viersion using KituraWebSocketClient is having serious issues. Saving this version so can re-implement but come back if necessary /// for owner that needs to get callbacks public protocol ComputeWorkerDelegate: AnyObject { /// the data will be invalid after this call. (it is pointing to a raw memory buffer that will be deallocated) func handleCompute(data: Data) func handleCompute(error: ComputeError) /// status updates just inform about a state change. If something failed, an error will be reported after the state change func handleCompute(statusUpdate: ComputeState) /// called when the connection is found to be closed while reading func handleConnectionClosed() } /// used for a state machine of the connection status public enum ComputeState: Int, CaseIterable { case uninitialized case initialHostSearch case loading case connecting case connected case failedToConnect case unusable } /// encapsulates all communication with the compute engine public class ComputeWorker { static func create(wspaceId: Int, sessionId: Int, k8sServer: K8sServer? = nil, eventGroup: EventLoopGroup, config: AppConfiguration, logger: Logger, delegate: ComputeWorkerDelegate, queue: DispatchQueue?) -> ComputeWorker { return ComputeWorker(wspaceId: wspaceId, sessionId: sessionId, config: config, eventGroup: eventGroup, logger: logger, delegate: delegate, queue: queue) } let logger: Logger let config: AppConfiguration let wspaceId: Int let sessionId: Int let k8sServer: K8sServer? let eventGroup: EventLoopGroup var computeWs: WebSocket? var closePromise: EventLoopPromise<Void> private weak var delegate: ComputeWorkerDelegate? private(set) var state: ComputeState = .uninitialized { didSet { delegate?.handleCompute(statusUpdate: state) } } private var podFailureCount = 0 private init(wspaceId: Int, sessionId: Int, k8sServer: K8sServer? = nil, config: AppConfiguration, eventGroup: EventLoopGroup, logger: Logger, delegate: ComputeWorkerDelegate, queue: DispatchQueue?) { self.logger = logger self.config = config self.sessionId = sessionId self.wspaceId = wspaceId self.delegate = delegate self.k8sServer = k8sServer self.eventGroup = eventGroup self.closePromise = eventGroup.next().makePromise(of: Void.self) } // MARK: - functions public func start() throws { assert(state == .uninitialized, "programmer error: invalid state") guard !config.computeViaK8s else { assert(k8sServer != nil, "programmer error: can't use k8s without a k8s server") // need to start dance of finding and/or launching the compute k8s pod state = .initialHostSearch updateStatus() return } print("Initialized Compute redirect") logger.info("getting compute port number") let rc = CaptureRedirect(log: logger) let initReq = URLRequest(url: URL(string: "http://\(config.computeHost):7714/")!) state = .loading rc.perform(request: initReq, callback: handleRedirect(response:request:error:)) } public func shutdown() throws { guard state == .connected, let wsclient = computeWs, !wsclient.isClosed else { logger.info("asked to shutdown when not running") throw ComputeError.notConnected } try wsclient.close().wait() } public func send(data: Data) throws { guard data.count > 0 else { throw ComputeError.sendingEmptyMessage } guard state == .connected, let wsclient = computeWs, !wsclient.isClosed else { throw ComputeError.notConnected } // FIXME: duplicate encoding let str = String(data: data, encoding: .utf8)! if config.logComputeOutgoing { logger.info("sending to compute: \(str)") } wsclient.send(str) } // MARK: - private methods private func handleRedirect(response: HTTPURLResponse?, request: URLRequest?, error: Error?) { logger.info("handleRedirect called") guard error == nil else { self.logger.error("failed to get ws port: \(error?.localizedDescription ?? "no new request")") self.delegate?.handleCompute(error: .failedToConnect) return } guard let rsp = response, rsp.statusCode == 302, var urlstr = rsp.allHeaderFields["Location"] as? String else { self.logger.error("failed to redirect location") self.delegate?.handleCompute(error: .failedToConnect) return } if !urlstr.starts(with: "ws") { urlstr = "ws://\(urlstr)" } logger.info("using \(urlstr)") self.state = .connecting let log = logger // FIXME: this delay should be on compute DispatchQueue.global().asyncAfter(deadline: .now() + .milliseconds(1800)) { log.info("opening ws connection") let connectFuture = WebSocket.connect(to: urlstr, on: self.eventGroup) { ws in self.computeWs = ws ws.onText { [weak self] ws, str in guard let me = self, let del = me.delegate else { return } del.handleCompute(data: str.data(using: .utf8)!) } ws.onBinary { [weak self] ws, bb in guard let me = self, let del = me.delegate else { return } del.handleCompute(data: Data(buffer: bb)) } ws.onClose.cascade(to: self.closePromise) } connectFuture.whenFailureBlocking(onto: .global()) { [weak self] error in log.error("failed to connect ws to compute: \(error.localizedDescription)") self?.delegate?.handleCompute(error: .failedToConnect) } connectFuture.whenSuccess { log.info("ws connected") self.state = .connected } do { try self.closePromise.futureResult.wait() log.info("connection closed") } catch { log.error("error from websocket: \(error)") } } } private func launchCompute() { guard let k8sServer = k8sServer else { fatalError("missing k8s server") } state = .loading k8sServer.launchCompute(wspaceId: wspaceId, sessionId: sessionId).onSuccess { _ in self.updateStatus() }.onFailure { error in self.logger.error("error launching compute: \(error)") self.state = .unusable self.delegate?.handleCompute(error: .failedToConnect) } } private func updateStatus() { fatalError("not implemented") } }
isc
2d89efdd7a90c72f4b89c603116dd56d
33.263736
223
0.728833
3.67472
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureProducts/Tests/FeatureProductsDomainTests/ProductsServiceTests.swift
1
4014
import Errors @testable import FeatureProductsDomain import TestKit import ToolKit import ToolKitMock import XCTest final class ProductsServiceTests: XCTestCase { private var service: ProductsService! private var mockRepository: ProductsRepositoryMock! private var mockFeatureFlagService: MockFeatureFlagsService! override func setUpWithError() throws { try super.setUpWithError() mockRepository = ProductsRepositoryMock() mockFeatureFlagService = MockFeatureFlagsService() service = ProductsService( repository: mockRepository, featureFlagsService: mockFeatureFlagService ) } override func tearDownWithError() throws { service = nil mockRepository = nil try super.tearDownWithError() } // MARK: Fetch func test_fetch_returns_emptyArray_if_featureFlag_isDisabled() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.disable(.productsChecksEnabled)) XCTAssertPublisherValues(service.fetchProducts(), [ProductValue]()) } func test_fetch_returns_repositoryError() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.enable(.productsChecksEnabled)) let error = NabuNetworkError.unknown try stubRepository(with: error) let publisher = service.fetchProducts() XCTAssertPublisherError(publisher, .network(error)) } func test_fetch_returns_repositoryValues() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.enable(.productsChecksEnabled)) let expectedProducts = try stubRepositoryWithDefaultProducts() XCTAssertPublisherValues(service.fetchProducts(), expectedProducts) } func test_stream_returns_repositoryError() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.enable(.productsChecksEnabled)) let error = NabuNetworkError.unknown try stubRepository(with: error) XCTAssertPublisherError(service.fetchProducts(), .network(error)) } // MARK: Stream func test_stream_returns_emptyArray_if_featureFlag_isDisabled() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.disable(.productsChecksEnabled)) XCTAssertPublisherValues(service.streamProducts(), .success([])) } func test_stream_publishes_products() throws { XCTAssertPublisherCompletion(mockFeatureFlagService.enable(.productsChecksEnabled)) let expectedProducts = try stubRepositoryWithDefaultProducts() XCTAssertPublisherValues(service.streamProducts(), .success(expectedProducts)) } // MARK: - Private private func stubRepository(with error: NabuNetworkError) throws { mockRepository.stubbedResponses.fetchProducts = .failure(error) mockRepository.stubbedResponses.streamProducts = .just(.failure(error)) } private func stubRepository(with products: [ProductValue]) throws { mockRepository.stubbedResponses.fetchProducts = .just(products) mockRepository.stubbedResponses.streamProducts = .just(.success(products)) } private func stubRepositoryWithDefaultProducts() throws -> [ProductValue] { let expectedProducts = [ ProductValue( id: .swap, enabled: false, maxOrdersCap: 1, maxOrdersLeft: 0, suggestedUpgrade: ProductSuggestedUpgrade(requiredTier: 2) ), ProductValue( id: .sell, enabled: false, maxOrdersCap: 1, maxOrdersLeft: 0, suggestedUpgrade: ProductSuggestedUpgrade(requiredTier: 2) ), ProductValue( id: .buy, enabled: true, maxOrdersCap: nil, maxOrdersLeft: nil, suggestedUpgrade: nil ) ] try stubRepository(with: expectedProducts) return expectedProducts } }
lgpl-3.0
567899b0f6c719e8354b888636363806
35.490909
92
0.68012
5.36631
false
true
false
false
lerigos/music-service
iOS_9/Pods/VideoSplash/VideoSplash/Source/VideoSplashViewController.swift
3
4512
// // VideoSplashViewController.swift // VideoSplash // // Created by Toygar Dündaralp on 8/3/15. // Copyright (c) 2015 Toygar Dündaralp. All rights reserved. // import UIKit import MediaPlayer import AVKit public enum ScalingMode { case Resize case ResizeAspect case ResizeAspectFill } public class VideoSplashViewController: UIViewController { private let moviePlayer = AVPlayerViewController() private var moviePlayerSoundLevel: Float = 1.0 public var contentURL: NSURL = NSURL() { didSet { setMoviePlayer(contentURL) } } public var videoFrame: CGRect = CGRect() public var startTime: CGFloat = 0.0 public var duration: CGFloat = 0.0 public var backgroundColor: UIColor = UIColor.blackColor() { didSet { view.backgroundColor = backgroundColor } } public var sound: Bool = true { didSet { if sound { moviePlayerSoundLevel = 1.0 }else{ moviePlayerSoundLevel = 0.0 } } } public var alpha: CGFloat = CGFloat() { didSet { moviePlayer.view.alpha = alpha } } public var alwaysRepeat: Bool = true { didSet { if alwaysRepeat { NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd", name: AVPlayerItemDidPlayToEndTimeNotification, object: moviePlayer.player?.currentItem) } } } public var fillMode: ScalingMode = .ResizeAspectFill { didSet { switch fillMode { case .Resize: moviePlayer.videoGravity = AVLayerVideoGravityResize case .ResizeAspect: moviePlayer.videoGravity = AVLayerVideoGravityResizeAspect case .ResizeAspectFill: moviePlayer.videoGravity = AVLayerVideoGravityResizeAspectFill } } } public var restartForeground: Bool = false { didSet { if restartForeground { NSNotificationCenter.defaultCenter().addObserver(self, selector: "playerItemDidReachEnd", name: UIApplicationWillEnterForegroundNotification, object: nil) } } } override public func viewDidAppear(animated: Bool) { moviePlayer.view.frame = videoFrame moviePlayer.showsPlaybackControls = false moviePlayer.view.userInteractionEnabled = false view.addSubview(moviePlayer.view) view.sendSubviewToBack(moviePlayer.view) } override public func viewWillDisappear(animated: Bool) { super.viewDidDisappear(animated) } private func setMoviePlayer(url: NSURL){ let videoCutter = VideoCutter() videoCutter.cropVideoWithUrl( videoUrl: url, startTime: startTime, duration: duration) { (videoPath, error) -> Void in if let path = videoPath as NSURL? { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT dispatch_async(dispatch_get_global_queue(priority, 0)) { dispatch_async(dispatch_get_main_queue()) { self.moviePlayer.player = AVPlayer(URL: path) self.moviePlayer.player?.addObserver( self, forKeyPath: "status", options: .New, context: nil) self.moviePlayer.player?.play() self.moviePlayer.player?.volume = self.moviePlayerSoundLevel } } } } } public override func observeValueForKeyPath( keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { guard let realObject = object where object != nil else { return } if !realObject.isKindOfClass(AVPlayer){ return } if realObject as? AVPlayer != self.moviePlayer.player || keyPath! != "status" { return } if self.moviePlayer.player?.status == AVPlayerStatus.ReadyToPlay{ self.movieReadyToPlay() } } deinit{ self.moviePlayer.player?.removeObserver(self, forKeyPath: "status") NSNotificationCenter.defaultCenter().removeObserver(self) } // Override in subclass public func movieReadyToPlay() { } override public func viewDidLoad() { super.viewDidLoad() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func playerItemDidReachEnd() { moviePlayer.player?.seekToTime(kCMTimeZero) moviePlayer.player?.play() } func playVideo() { moviePlayer.player?.play() } func pauseVideo() { moviePlayer.player?.pause() } }
apache-2.0
acbade8a166cfaeec10385f05634abcf
25.686391
85
0.65255
5.033482
false
false
false
false
huonw/swift
validation-test/stdlib/HashingPrototype.swift
26
4687
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop /* <rdar://problem/14196462> Hashing in the standard library New Hashing APIs ================ This is a proposal for new hashing APIs in the Swift standard library. Current stdlib design has the Hashable protocol with 'hashValue: Int' property, and the library leaves it up to the user how to implement it. In the proposed design in the 99% case the user only has to enumerate the properties they want to be included in the hash, and the Swift library will compute a good hash. Problem ======= Threading a single Hasher through all computations reduces the cost to set up and finalize hash value computation. Unfortunately, it is not clear how to allow this combineIntoHash() API to interoperate with Objective-C, in particular, with Objective-C subclasses of Swift Hashable classes. See FIXME below. */ protocol NewHashable /*: Equatable*/ { func combineIntoHash<H : Hasher>(_ hasher: inout H) } struct UserTypeA : NewHashable { var a1: Int var a2: Float func combineIntoHash<H : Hasher>(_ hasher: inout H) { hasher.combine(a1) hasher.combine(a2) } } struct UserTypeB : NewHashable { var b1: Int var b2: UserTypeA // User-defined hashable type var b3: [Int] func combineIntoHash<H : Hasher>(_ hasher: inout H) { hasher.combine(b1) hasher.combine(b2) hasher.combineSequence(b3) } } class UserClassA : NSObject { var a1: Int = 0 // error: declarations from extensions cannot be overridden yet //func combineIntoHash<H : Hasher>(_ hasher: inout H) { // hasher.combine(a1) //} // FIXME: Problem: what method should a derived Objective-C subclass // override? 'combineIntoHash' is not @objc. } //===----------------------------------------------------------------------===// // Implementation //===----------------------------------------------------------------------===// /// A hasher object computes a hash value. /// /// Precondition: two hasher objects compute the same hash value when /// the same sequence of `combine(...)` calls with equal arguments is /// performed on both of them. protocol Hasher { // // Primary APIs // mutating func combine(_ value: Int) mutating func combine(_ value: Float) // ... overloads for other primitive types... mutating func squeezeHashValue<I : SignedInteger>( _ resultRange: Range<I>) -> I mutating func squeezeHashValue<I : UnsignedInteger>( _ resultRange: Range<I>) -> I // // Convenience APIs; would be completely implemented by default // implementations if we had them. // // This handles arrays, UnsafeBufferPointer, user-defined // collections. mutating func combineSequence< S : Sequence >(_ s: S) where S.Iterator.Element : NewHashable mutating func combine<H : NewHashable>(_ value: H) } /// A hasher for in-process, non-persistent hashtables. struct InProcessHashtableHasher : Hasher { // Only for exposition. var _state: Int init() { // Should initialize to per-process seed. _state = 0 } mutating func combine(_ value: Int) { // Only for exposition. _state = _state ^ value } mutating func combine(_ value: Float) { // Only for exposition. _state = _state ^ Int(value.bitPattern) } mutating func combineSequence< S : Sequence >(_ s: S) where S.Iterator.Element : NewHashable { for v in s { v.combineIntoHash(&self) } } mutating func combine<H : NewHashable>(_ value: H) { value.combineIntoHash(&self) } mutating func squeezeHashValue<I : SignedInteger>( _ resultRange: Range<I>) -> I { // ... finalize hash value computation first... return I(IntMax(_state)) // Should actually clamp the value } mutating func squeezeHashValue<I : UnsignedInteger>( _ resultRange: Range<I>) -> I { // ... finalize hash value computation first... return I(UIntMax(_state)) // Should actually clamp the value } } /// A hasher with 128-bit output and a well-defined algorithm stable /// *across platforms*; useful for on-disk or distributed hash tables. /// Not a cryptographic hash. // struct StableFingerprint128Hasher : Hasher {} extension Int : NewHashable { func combineIntoHash<H : Hasher>(_ hasher: inout H) { hasher.combine(self) } } //===----------------------------------------------------------------------===// // Foundation overlay: interoperability with NSObject.hash //===----------------------------------------------------------------------===// import Foundation extension NSObject : NewHashable { func combineIntoHash<H : Hasher>(_ hasher: inout H) { hasher.combine(self.hash) } }
apache-2.0
164696605ba85878f253f68dd95e991e
25.936782
80
0.644122
4.184821
false
false
false
false
huonw/swift
test/stdlib/OptionalBridge.swift
31
5758
//===--- OptionalBridge.swift - Tests of Optional bridging ----------------===// // // 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 // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import StdlibUnittest let tests = TestSuite("OptionalBridge") // Work around bugs in the type checker preventing casts back to optional. func cast<T>(_ value: AnyObject, to: T.Type) -> T { return value as! T } // expectEqual() helpers for deeper-nested nullability than StdlibUnittest // provides. func expectEqual<T: Equatable>(_ x: T??, _ y: T??) { switch (x, y) { case (.some(let xx), .some(let yy)): expectEqual(xx, yy) case (.none, .none): return default: expectUnreachable("\(T.self)?? values don't match: \(x) vs. \(y)") } } func expectEqual<T: Equatable>(_ x: T???, _ y: T???) { switch (x, y) { case (.some(let xx), .some(let yy)): expectEqual(xx, yy) case (.none, .none): return default: expectUnreachable("\(T.self)??? values don't match: \(x) vs. \(y)") } } tests.test("wrapped value") { let unwrapped = "foo" let wrapped = Optional(unwrapped) let doubleWrapped = Optional(wrapped) let unwrappedBridged = unwrapped as AnyObject let wrappedBridged = wrapped as AnyObject let doubleWrappedBridged = doubleWrapped as AnyObject expectTrue(unwrappedBridged.isEqual(wrappedBridged) && wrappedBridged.isEqual(doubleWrappedBridged)) let unwrappedCastBack = cast(unwrappedBridged, to: String.self) let wrappedCastBack = cast(wrappedBridged, to: Optional<String>.self) let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<String?>.self) expectEqual(unwrapped, unwrappedCastBack) expectEqual(wrapped, wrappedCastBack) expectEqual(doubleWrapped, doubleWrappedCastBack) } struct NotBridged: Hashable { var x: Int var hashValue: Int { return x } static func ==(x: NotBridged, y: NotBridged) -> Bool { return x.x == y.x } } tests.test("wrapped boxed value") { let unwrapped = NotBridged(x: 1738) let wrapped = Optional(unwrapped) let doubleWrapped = Optional(wrapped) let unwrappedBridged = unwrapped as AnyObject let wrappedBridged = wrapped as AnyObject let doubleWrappedBridged = doubleWrapped as AnyObject expectTrue(unwrappedBridged.isEqual(wrappedBridged)) expectTrue(wrappedBridged.isEqual(doubleWrappedBridged)) let unwrappedCastBack = cast(unwrappedBridged, to: NotBridged.self) let wrappedCastBack = cast(wrappedBridged, to: Optional<NotBridged>.self) let doubleWrappedCastBack = cast(doubleWrappedBridged, to: Optional<NotBridged?>.self) expectEqual(unwrapped, unwrappedCastBack) expectEqual(wrapped, wrappedCastBack) expectEqual(doubleWrapped, doubleWrappedCastBack) } tests.test("wrapped class instance") { let unwrapped = LifetimeTracked(0) let wrapped = Optional(unwrapped) expectTrue(wrapped as AnyObject === unwrapped as AnyObject) } tests.test("nil") { let null: String? = nil let wrappedNull = Optional(null) let doubleWrappedNull = Optional(wrappedNull) let nullBridged = null as AnyObject let wrappedNullBridged = wrappedNull as AnyObject let doubleWrappedNullBridged = doubleWrappedNull as AnyObject expectTrue(nullBridged === NSNull()) expectTrue(wrappedNullBridged === NSNull()) expectTrue(doubleWrappedNullBridged === NSNull()) let nullCastBack = cast(nullBridged, to: Optional<String>.self) let wrappedNullCastBack = cast(nullBridged, to: Optional<String?>.self) let doubleWrappedNullCastBack = cast(nullBridged, to: Optional<String??>.self) expectEqual(nullCastBack, null) expectEqual(wrappedNullCastBack, wrappedNull) expectEqual(doubleWrappedNullCastBack, doubleWrappedNull) } tests.test("nil in nested optional") { let doubleNull: String?? = nil let wrappedDoubleNull = Optional(doubleNull) let doubleNullBridged = doubleNull as AnyObject let wrappedDoubleNullBridged = wrappedDoubleNull as AnyObject expectTrue(doubleNullBridged === wrappedDoubleNullBridged) expectTrue(doubleNullBridged !== NSNull()) let doubleNullCastBack = cast(doubleNullBridged, to: Optional<String?>.self) let wrappedDoubleNullCastBack = cast(doubleNullBridged, to: Optional<String??>.self) expectEqual(doubleNullCastBack, doubleNull) expectEqual(wrappedDoubleNullCastBack, wrappedDoubleNull) let tripleNull: String??? = nil let tripleNullBridged = tripleNull as AnyObject expectTrue(doubleNullBridged !== tripleNullBridged) let tripleNullCastBack = cast(tripleNullBridged, to: Optional<String??>.self) expectEqual(tripleNullCastBack, tripleNull) } tests.test("collection of Optional") { let holeyArray: [LifetimeTracked?] = [LifetimeTracked(0), nil, LifetimeTracked(1)] let nsArray = holeyArray as NSArray autoreleasepool { expectTrue((nsArray[0] as AnyObject) === holeyArray[0]!) expectTrue((nsArray[1] as AnyObject) === NSNull()) expectTrue((nsArray[2] as AnyObject) === holeyArray[2]!) } } tests.test("NSArray of NSNull") { let holeyNSArray: NSArray = [LifetimeTracked(2), NSNull(), LifetimeTracked(3)] autoreleasepool { let swiftArray = holeyNSArray as! [LifetimeTracked?] expectTrue(swiftArray[0]! === holeyNSArray[0] as AnyObject) expectTrue(swiftArray[1] == nil) expectTrue(swiftArray[2]! === holeyNSArray[2] as AnyObject) } } runAllTests()
apache-2.0
17266cfe9e5527dfe0ab143fa05061bf
31.902857
88
0.725773
4.38872
false
true
false
false
abiaoLHB/LHBWeiBo-Swift
LHBWeibo/LHBWeibo/AppDelegate.swift
1
3536
// // AppDelegate.swift // LHBWeibo // // Created by LHB on 16/8/15. // Copyright © 2016年 LHB. All rights reserved. // /* 该项目支持iOS9.0及其以上版本 因为用了iOS9.0的新特性之一:storyBoardRefactor 静态库分两种:.a 和 .framework .framework又有两种:静态和动态 swift用的是.framework的动态库 */ //Othe授权 //App Key:1321090536 //App Secret:cdcbf3092f56d5dfe836162905879c54 //回调地址:http://luohongbiaooauth.com //https://api.weibo.com/oauth2/authorize?client_id=1321090536&redirect_uri=http://luohongbiaooauth.com import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { var defaultVC : UIViewController?{ let isLogin = UserAccountViewMdoel.shareInstance.isLogin return isLogin ? WelcomeViewController() : UIStoryboard(name: "Main", bundle: nil).instantiateInitialViewController() } UITabBar.appearance().tintColor = UIColor.orangeColor() UINavigationBar.appearance().tintColor = UIColor.orangeColor() //纯代码方案 //window = UIWindow(frame:UIScreen.mainScreen().bounds) //window?.backgroundColor = UIColor.whiteColor() //window?.rootViewController = MainViewController() //window?.makeKeyAndVisible() //不从MainStoryboard加载,因为当程序打开时,也要显示的是欢迎界面.所以自己创建window //所以在上面写一个计算属性 window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.rootViewController = defaultVC window?.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
0764909dcd036aaedd08e98e55dfc93d
38.141176
285
0.723775
4.78705
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/Pond/Pond.swift
1
3684
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import Foundation /// A protocol where the conforming types provide functionality for key value /// storage. /// /// The library comes with few types out of the box: `UserDefaults`, `Keychain`, /// `InMemory`, `Failing`, `Empty` and `Composite` types. /// /// To allow testability, reliability and predictability for persisting various /// types of data ranging from tokens to perishable user preferences. The /// library comes with few types out of the box to provide consolidated Key /// Value Storage API for Keychain (secure storage), In-Memory (ephemeral /// storage), and UserDefaults (non-sensitive storage). public protocol Pond { typealias Key = PondKey func get<T>(_ type: T.Type, _ key: Key) -> T? func set<T>(_ key: Key, value: T?) /// Returns a boolean value indicating whether the store contains value for the /// given key. func contains(_ key: Key) -> Bool func remove(_ key: Key) } // MARK: - Helpers extension Pond { public func set<T>(_ key: Key, value: T?) where T: RawRepresentable, T.RawValue == String { set(key, value: value?.rawValue) } public func setCodable<T: Codable>(_ key: Key, value: T?, encoder: JSONEncoder? = nil) { do { let data = try (encoder ?? JSONEncoder()).encode(value) set(key, value: data) } catch { #if DEBUG fatalError(String(describing: error)) #else // Return nothing to avoid leaking error details in production. #endif } } } // MARK: - Helpers: Get extension Pond { private func value(_ key: Key) -> StringConverter? { StringConverter(get(key)) } public func get<T>(_ key: Key) -> T? { get(T.self, key) } public func get<T>(_ key: Key, default defaultValue: @autoclosure () -> T) -> T { value(key)?.get() ?? defaultValue() } public func get<T>(_ key: Key, default defaultValue: @autoclosure () -> T) -> T where T: RawRepresentable, T.RawValue == String { value(key)?.get() ?? defaultValue() } /// Returns the value of the key, decoded from a JSON object. /// /// - Parameters: /// - type: The type of the value to decode from the string. /// - decoder: The decoder used to decode the data. If set to `nil`, it uses /// ``JSONDecoder`` with `convertFromSnakeCase` key decoding strategy. /// - Returns: A value of the specified type, if the decoder can parse the data. public func getCodable<T>(_ key: Key, type: T.Type = T.self, decoder: JSONDecoder? = nil) -> T? where T: Decodable { if let data = get(Data.self, key) { return StringConverter.get(type, from: data, decoder: decoder) } if let value = StringConverter(get(String.self, key))?.get(type, decoder: decoder) { return value } return nil } } // MARK: - Dependency extension DependencyValues { private struct XcorePondKey: DependencyKey { static let defaultValue: Pond = { #if DEBUG if ProcessInfo.Arguments.isTesting { return .failing } #endif return .empty }() } /// Provide functionality for key value storage. public var pond: Pond { get { self[XcorePondKey.self] } set { self[XcorePondKey.self] = newValue } } /// Provide functionality for key value storage. @discardableResult public static func pond(_ value: Pond) -> Self.Type { set(\.pond, value) return Self.self } }
mit
00143496f522343d9976a993012ce255
29.691667
133
0.606571
4.115084
false
false
false
false