repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
yonadev/yona-app-ios | Yona/Yona/GoalsRequestManager.swift | 1 | 14228 | //
// GoalsRequestManager.swift
// Yona
//
// Created by Ben Smith on 28/04/16.
// Copyright © 2016 Yona. All rights reserved.
//
import Foundation
//MARK: - Goal APIService
class GoalsRequestManager {
var budgetGoals:[Goal] = [] //Array returning budget goals
var timezoneGoals:[Goal] = [] //Array returning timezone goals
var noGoGoals:[Goal] = [] //Array returning no go goals
fileprivate var newGoal: Goal?
var allTheGoals:[Goal] = [] //Array returning all the goals returned by getGoals
let APIService = APIServiceManager.sharedInstance
let APIUserRequestManager = UserRequestManager.sharedInstance
static let sharedInstance = GoalsRequestManager()
fileprivate init() {}
/**
Helper method for UI to returns the size of the goals arrays, so challenges know how many goals there
- parameter goalType: GoalType, goal type that we want array size for
- parameter onCompletion: APIGoalSizeResponse, returns server response messages, and goal array size
*/
func getGoalsSizeOfGoalType(_ goalType: GoalType, onCompletion: APIGoalSizeResponse) {
switch goalType {
case GoalType.BudgetGoalString:
guard budgetGoals.isEmpty else {
onCompletion(0)
return
}
onCompletion(budgetGoals.count)
case GoalType.TimeZoneGoalString:
guard timezoneGoals.isEmpty else {
onCompletion(0)
return
}
onCompletion(timezoneGoals.count)
case GoalType.NoGoGoalString:
guard noGoGoals.isEmpty else {
onCompletion(0)
return
}
onCompletion(noGoGoals.count)
}
}
/**
Private func used by API service method getGoalsOfType to sort the goals into their appropriate array types and return the array request of that type of goals
- parameter goalType: GoalType, The goaltype that we require the array for
- parameter onCompletion: APIGoalResponse, Returns the array of goals, and success or fail and server messages
- return [Goal] and array of goals
*/
func sortGoalsIntoArray(_ goalType: GoalType, goals: [Goal]) -> [Goal]{
budgetGoals = []
timezoneGoals = []
noGoGoals = []
//sort out the goals into their arrays
for goal in goals {
switch goal.goalType! {
case GoalType.BudgetGoalString.rawValue:
budgetGoals.append(goal)
case GoalType.TimeZoneGoalString.rawValue:
timezoneGoals.append(goal)
case GoalType.NoGoGoalString.rawValue:
noGoGoals.append(goal)
default:
break
}
}
//which array shall we send back?
switch goalType {
case GoalType.BudgetGoalString:
return budgetGoals
case GoalType.TimeZoneGoalString:
return timezoneGoals
case GoalType.NoGoGoalString:
return noGoGoals
}
}
/**
Generic method to get the goals or post a goal, as they require the same actions but just a different httpmethod
- parameter httpmethodParam: httpMethods, The httpmethod enum, POST GET etc
- parameter body: BodyDataDictionary?, body that is needed in a POST call, can be nil
- parameter onCompletion: APIGoalResponse, returns either an array of goals, or a goal, also success or fail, server messages and
*/
fileprivate func goalsHelper(_ httpmethodParam: httpMethods, body: BodyDataDictionary?, goalLinkAction: String?, onCompletion: @escaping APIGoalResponse) {
//success get our activities
ActivitiesRequestManager.sharedInstance.getActivityCategories{ (success, message, serverCode, activities, error) in
if success {
//get the path to get all the goals from user object
if let path = goalLinkAction {
//do request with specific httpmethod
self.APIService.callRequestWithAPIServiceResponse(body, path: path, httpMethod: httpmethodParam, onCompletion: { success, json, error in
if let json = json {
guard success == true else {
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, nil, error)
return
}
//if we get a goals array response, send back the array of goals
self.allTheGoals = []
if let embedded = json[YonaConstants.jsonKeys.embedded],
let embeddedGoals = embedded[YonaConstants.jsonKeys.yonaGoals] as? NSArray{
//iterate embedded goals response
for goal in embeddedGoals {
if let goal = goal as? BodyDataDictionary {
self.newGoal = Goal.init(goalData: goal, activities: activities!)
if let goal = self.newGoal {
if !goal.isHistoryItem {
self.allTheGoals.append(goal)
}
}
}
}
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, self.allTheGoals, error)
} else { //if we just get one goal, for post goal, just that goals is returned so send that back
self.newGoal = Goal.init(goalData: json, activities: activities!)
//add the new goal to the goals array
self.allTheGoals.append(self.newGoal!)
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), self.newGoal, nil, error)
}
} else {
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, nil, error)
}
})
}
} else {
onCompletion(success, error?.userInfo[NSLocalizedDescriptionKey] as? String, self.APIService.determineErrorCode(error), nil, nil, error)
}
}
}
func getAllTheBuddyGoals(_ path : String, onCompletion: @escaping APIGoalResponse) {
self.goalsHelper(httpMethods.get, body: nil, goalLinkAction: path) { (success, message, server, goal, goals, error) in
if success {
onCompletion(true, message, server, goal, goals, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
}
func getAllTheBuddyGoals(_ buddy : Buddies, activities: [Activities], onCompletion: @escaping APIGoalResponse) {
if let path = buddy.buddyGoalSelfLink {
self.goalsHelper(httpMethods.get, body: nil, goalLinkAction: path) { (success, message, server, goal, goals, error) in
#if DEBUG
print("Get all goals API call: " + String(success))
#endif
if success {
onCompletion(true, message, server, nil, goals, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
}
}
/**
Called to get all the users goals
- parameter activities: [Activities], goals need to know about all the activities so they can ID them and set their activity name in the goal (Social, News etc.)
- parameter onCompletion: APIGoalResponse, returns either an array of goals, or a goal, also success or fail, server messages and
*/
func getAllTheGoals(_ activities: [Activities], onCompletion: @escaping APIGoalResponse) {
UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed) { (success, message, code, user) in
//success so get the user?
if success {
if let goalLink = user?.getAllGoalsLink {
self.goalsHelper(httpMethods.get, body: nil, goalLinkAction: user?.getAllGoalsLink!) { (success, message, server, goal, goals, error) in
#if DEBUG
print("Get all goals API call: " + String(success))
#endif
if success {
onCompletion(true, message, server, nil, goals, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
} else {
onCompletion(false, YonaConstants.YonaErrorTypes.UserRequestFailed.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.UserRequestFailed), nil, nil, YonaConstants.YonaErrorTypes.UserRequestFailed)
}
} else {
//response from request failed
onCompletion(false, YonaConstants.YonaErrorTypes.UserRequestFailed.localizedDescription, self.APIService.determineErrorCode(YonaConstants.YonaErrorTypes.UserRequestFailed), nil, nil, YonaConstants.YonaErrorTypes.UserRequestFailed)
}
}
}
/**
Posts a new goal of a certain type defined in the body, sends the goal back to the UI
- parameter body: BodyDataDictionary, the body of the goal that needs to be posted, example below:
- parameter onCompletion: APIGoalResponse, returns either an array of goals, or a goal, also success or fail, server messages and
*/
func postUserGoals(_ body: BodyDataDictionary, onCompletion: @escaping APIGoalResponse) {
UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed) { (success, message, code, user) in
//success so get the user?
if success {
//success so get the user
self.goalsHelper(httpMethods.post, body: body, goalLinkAction: user?.getAllGoalsLink) { (success, message, server, goal, goals, error) in
if success {
onCompletion(true, message, server, goal, nil, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
} else {
//response from request failed
onCompletion(false, message, code, nil, nil, nil)
}
}
}
/**
Updates a goal. UI must send us the editlink of that goal and new body of the goal to update. Sends the updated goal back in a response
- parameter goalEditLink: String? The edit link of the specific goal you want to update
- parameter body: BodyDataDictionary, the body of the goal that needs to be updated, example above in post user goal
- parameter onCompletion: APIGoalResponse, returns either an array of goals, or a goal, also success or fail, server messages and
*/
func updateUserGoal(_ goalEditLink: String?, body: BodyDataDictionary, onCompletion: @escaping APIGoalResponse) {
self.goalsHelper(httpMethods.put, body: body, goalLinkAction: goalEditLink) { (success, message, server, goal, goals, error) in
if success {
onCompletion(true, message, server, goal, nil, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
}
/**
Implements API call get goal with ID, given the self link for a goal it returns the goal requested
- parameter goalSelfLink: String, the self link for the goal that we require
- parameter onCompletion: APIGoalResponse, gives response messages and the goal requested
*/
func getUsersGoalWithSelfLinkID(_ goalSelfLink: String, onCompletion: @escaping APIGoalResponse) {
self.goalsHelper(httpMethods.get, body: nil, goalLinkAction: goalSelfLink) { (success, message, server, goal, goals, error) in
if success {
onCompletion(true, message, server, goal, nil, error)
} else {
onCompletion(false, message, server, nil, nil, error)
}
}
}
/**
Implements API delete goal, given the edit link for the goal (if it exists, as it will not on Mandatory goals)
- parameter goalEditLink: String?, If a goal is not mandatory then it will have and edit link and we will beable to delete it
- parameter onCompletion: APIResponse, returns success or fail of the method and server messages
*/
func deleteUserGoal(_ goalEditLink: String?, onCompletion: @escaping APIGoalResponse) {
self.goalsHelper(httpMethods.delete, body: nil, goalLinkAction: goalEditLink) { (success, message, serverCode, goal, goals, error) in
if success {
ActivitiesRequestManager.sharedInstance.getActivityCategories({ (success, message, code, activities, error) in
if let activities = activities {
self.getAllTheGoals(activities) { (success, message, code, nil, goals, error) in
onCompletion(success, message, serverCode, goal, goals, error)
}
}
})
} else {
onCompletion(false, message, serverCode, nil, nil, error)
}
}
}
}
| mpl-2.0 | 1936ae2ef2c395c218472822d7e5443c | 47.391156 | 250 | 0.583749 | 5.612229 | false | false | false | false |
zvonler/PasswordElephant | external/github.com/apple/swift-protobuf/Tests/SwiftProtobufTests/Test_Timestamp.swift | 10 | 17407 | // Tests/SwiftProtobufTests/Test_Timestamp.swift - VerifyA well-known Timestamp type
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Proto3 defines a standard Timestamp message type that represents a
/// single moment in time with nanosecond precision. The in-memory form
/// stores a count of seconds since the Unix epoch and a separate count
/// of nanoseconds. The binary serialized form is unexceptional. The JSON
/// serialized form represents the time as a string using an ISO8601 variant.
/// The implementation in the runtime library includes a variety of convenience
/// methods to simplify use, including arithmetic operations on timestamps
/// and durations.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
import SwiftProtobuf
class Test_Timestamp: XCTestCase, PBTestHelpers {
typealias MessageTestType = Google_Protobuf_Timestamp
func testJSON() throws {
XCTAssertEqual("\"1970-01-01T00:00:00Z\"",
try Google_Protobuf_Timestamp().jsonString())
assertJSONEncode("\"1970-01-01T00:00:01.000000001Z\"") {
(o: inout MessageTestType) in
o.seconds = 1 // 1 second
o.nanos = 1
}
assertJSONEncode("\"1970-01-01T00:01:00.000000010Z\"") {
(o: inout MessageTestType) in
o.seconds = 60 // 1 minute
o.nanos = 10
}
assertJSONEncode("\"1970-01-01T01:00:00.000000100Z\"") {
(o: inout MessageTestType) in
o.seconds = 3600 // 1 hour
o.nanos = 100
}
assertJSONEncode("\"1970-01-02T00:00:00.000001Z\"") {
(o: inout MessageTestType) in
o.seconds = 86400 // 1 day
o.nanos = 1000
}
assertJSONEncode("\"1970-02-01T00:00:00.000010Z\"") {
(o: inout MessageTestType) in
o.seconds = 2678400 // 1 month
o.nanos = 10000
}
assertJSONEncode("\"1971-01-01T00:00:00.000100Z\"") {
(o: inout MessageTestType) in
o.seconds = 31536000 // 1 year
o.nanos = 100000
}
assertJSONEncode("\"1970-01-01T00:00:01.001Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 1000000
}
assertJSONEncode("\"1970-01-01T00:00:01.010Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 10000000
}
assertJSONEncode("\"1970-01-01T00:00:01.100Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 100000000
}
assertJSONEncode("\"1970-01-01T00:00:01Z\"") {
(o: inout MessageTestType) in
o.seconds = 1
o.nanos = 0
}
// Largest representable date
assertJSONEncode("\"9999-12-31T23:59:59.999999999Z\"") {
(o: inout MessageTestType) in
o.seconds = 253402300799
o.nanos = 999999999
}
// 10 billion seconds after Epoch
assertJSONEncode("\"2286-11-20T17:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 10000000000
o.nanos = 0
}
// 1 billion seconds after Epoch
assertJSONEncode("\"2001-09-09T01:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000000000
o.nanos = 0
}
// 1 million seconds after Epoch
assertJSONEncode("\"1970-01-12T13:46:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000000
o.nanos = 0
}
// 1 thousand seconds after Epoch
assertJSONEncode("\"1970-01-01T00:16:40Z\"") {
(o: inout MessageTestType) in
o.seconds = 1000
o.nanos = 0
}
// 1 thousand seconds before Epoch
assertJSONEncode("\"1969-12-31T23:43:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000
o.nanos = 0
}
// 1 million seconds before Epoch
assertJSONEncode("\"1969-12-20T10:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000000
o.nanos = 0
}
// 1 billion seconds before Epoch
assertJSONEncode("\"1938-04-24T22:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -1000000000
o.nanos = 0
}
// 10 billion seconds before Epoch
assertJSONEncode("\"1653-02-10T06:13:20Z\"") {
(o: inout MessageTestType) in
o.seconds = -10000000000
o.nanos = 0
}
// Earliest leap year
assertJSONEncode("\"0004-02-19T02:50:24Z\"") {
(o: inout MessageTestType) in
o.seconds = -62036744976
o.nanos = 0
}
// Earliest representable date
assertJSONEncode("\"0001-01-01T00:00:00Z\"") {
(o: inout MessageTestType) in
o.seconds = -62135596800
o.nanos = 0
}
}
func testJSON_range() throws {
// Check that JSON timestamps round-trip correctly over a wide range.
// This checks about 15,000 dates scattered over a 10,000 year period
// to verify that our JSON encoder and decoder agree with each other.
// Combined with the above checks of specific known dates, this gives a
// pretty high confidence that our date calculations are correct.
let earliest: Int64 = -62135596800
let latest: Int64 = 253402300799
// Use a smaller increment to get more exhaustive testing. An
// increment of 12345 will test every single day in the entire
// 10,000 year range and require about 15 minutes to run.
// An increment of 12345678 will pick about one day out of
// every 5 months and require only a few seconds to run.
let increment: Int64 = 12345678
var t: Int64 = earliest
// If things are broken, this test can easily generate >10,000 failures.
// That many failures can break a lot of tools (Xcode, for example), so
// we do a little extra work here to only print out the first failure
// of each type and the total number of failures at the end.
var encodingFailures = 0
var decodingFailures = 0
var roundTripFailures = 0
while t < latest {
let start = Google_Protobuf_Timestamp(seconds: t)
do {
let encoded = try start.jsonString()
do {
let decoded = try Google_Protobuf_Timestamp(jsonString: encoded)
if decoded.seconds != t {
if roundTripFailures == 0 {
// Only the first round-trip failure will be reported here
XCTAssertEqual(decoded.seconds, t, "Round-trip failed for \(encoded): \(t) != \(decoded.seconds)")
}
roundTripFailures += 1
}
} catch {
if decodingFailures == 0 {
// Only the first decoding failure will be reported here
XCTFail("Could not decode \(encoded)")
}
decodingFailures += 1
}
} catch {
if encodingFailures == 0 {
// Only the first encoding failure will be reported here
XCTFail("Could not encode \(start)")
}
encodingFailures += 1
}
t += increment
}
// Report the total number of failures (but silence if there weren't any)
XCTAssertEqual(encodingFailures, 0)
XCTAssertEqual(decodingFailures, 0)
XCTAssertEqual(roundTripFailures, 0)
}
func testJSON_timezones() {
assertJSONDecodeSucceeds("\"1970-01-01T08:00:00+08:00\"") {$0.seconds == 0}
assertJSONDecodeSucceeds("\"1969-12-31T16:00:00-08:00\"") {$0.seconds == 0}
assertJSONDecodeFails("\"0001-01-01T00:00:00+23:59\"")
assertJSONDecodeFails("\"9999-12-31T23:59:59-23:59\"")
}
func testJSON_timestampField() throws {
do {
let valid = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00Z\"}")
XCTAssertEqual(valid.optionalTimestamp, Google_Protobuf_Timestamp(seconds: -62135596800))
} catch {
XCTFail("Should have decoded correctly")
}
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"10000-01-01T00:00:00Z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01 00:00:00Z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01T00:00:00z\"}"))
XCTAssertThrowsError(try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: "{\"optionalTimestamp\": \"0001-01-01t00:00:00Z\"}"))
}
// A couple more test cases transcribed from conformance test
func testJSON_conformance() throws {
let t1 = Google_Protobuf_Timestamp(seconds: 0, nanos: 10000000)
var m1 = ProtobufTestMessages_Proto3_TestAllTypesProto3()
m1.optionalTimestamp = t1
let expected1 = "{\"optionalTimestamp\":\"1970-01-01T00:00:00.010Z\"}"
XCTAssertEqual(try m1.jsonString(), expected1)
let json2 = "{\"optionalTimestamp\": \"1970-01-01T00:00:00.010000000Z\"}"
let expected2 = "{\"optionalTimestamp\":\"1970-01-01T00:00:00.010Z\"}"
do {
let m2 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json2)
do {
let recoded2 = try m2.jsonString()
XCTAssertEqual(recoded2, expected2)
} catch {
XCTFail()
}
} catch {
XCTFail()
}
// Extra spaces around all the tokens.
let json3 = " { \"repeatedTimestamp\" : [ \"0001-01-01T00:00:00Z\" , \"9999-12-31T23:59:59.999999999Z\" ] } "
let m3 = try ProtobufTestMessages_Proto3_TestAllTypesProto3(jsonString: json3)
let expected3 = [Google_Protobuf_Timestamp(seconds: -62135596800),
Google_Protobuf_Timestamp(seconds: 253402300799, nanos: 999999999)]
XCTAssertEqual(m3.repeatedTimestamp, expected3)
}
func testSerializationFailure() throws {
let maxOutOfRange = Google_Protobuf_Timestamp(seconds:-62135596800, nanos: -1)
XCTAssertThrowsError(try maxOutOfRange.jsonString())
let minInRange = Google_Protobuf_Timestamp(seconds:-62135596800)
XCTAssertNotNil(try minInRange.jsonString())
let maxInRange = Google_Protobuf_Timestamp(seconds:253402300799, nanos: 999999999)
XCTAssertNotNil(try maxInRange.jsonString())
let minOutOfRange = Google_Protobuf_Timestamp(seconds:253402300800)
XCTAssertThrowsError(try minOutOfRange.jsonString())
}
func testBasicArithmetic() throws {
let tn1_n1 = Google_Protobuf_Timestamp(seconds: -2, nanos: 999999999)
let t0 = Google_Protobuf_Timestamp()
let t1_1 = Google_Protobuf_Timestamp(seconds: 1, nanos: 1)
let t2_2 = Google_Protobuf_Timestamp(seconds: 2, nanos: 2)
let t3_3 = Google_Protobuf_Timestamp(seconds: 3, nanos: 3)
let t4_4 = Google_Protobuf_Timestamp(seconds: 4, nanos: 4)
let dn1_n1 = Google_Protobuf_Duration(seconds: -1, nanos: -1)
let d0 = Google_Protobuf_Duration()
let d1_1 = Google_Protobuf_Duration(seconds: 1, nanos: 1)
let d2_2 = Google_Protobuf_Duration(seconds: 2, nanos: 2)
let d3_3 = Google_Protobuf_Duration(seconds: 3, nanos: 3)
let d4_4 = Google_Protobuf_Duration(seconds: 4, nanos: 4)
// Durations can be added to or subtracted from timestamps
XCTAssertEqual(t1_1, t0 + d1_1)
XCTAssertEqual(t1_1, t1_1 + d0)
XCTAssertEqual(t2_2, t1_1 + d1_1)
XCTAssertEqual(t3_3, t1_1 + d2_2)
XCTAssertEqual(t1_1, t4_4 - d3_3)
XCTAssertEqual(tn1_n1, t3_3 - d4_4)
XCTAssertEqual(tn1_n1, t3_3 + -d4_4)
// Difference of two timestamps is a duration
XCTAssertEqual(d1_1, t4_4 - t3_3)
XCTAssertEqual(dn1_n1, t3_3 - t4_4)
}
func testArithmeticNormalizes() throws {
// Addition normalizes the result
let r1: Google_Protobuf_Timestamp = Google_Protobuf_Timestamp() + Google_Protobuf_Duration(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r1.seconds, 2)
XCTAssertEqual(r1.nanos, 1)
// Subtraction normalizes the result
let r2: Google_Protobuf_Timestamp = Google_Protobuf_Timestamp() - Google_Protobuf_Duration(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r2.seconds, -3)
XCTAssertEqual(r2.nanos, 999999999)
// Subtraction normalizes the result
let r3: Google_Protobuf_Duration = Google_Protobuf_Timestamp() - Google_Protobuf_Timestamp(seconds: 0, nanos: 2000000001)
XCTAssertEqual(r3.seconds, -2)
XCTAssertEqual(r3.nanos, -1)
let r4: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: 1) - Google_Protobuf_Timestamp(nanos: 2000000001)
XCTAssertEqual(r4.seconds, -1)
XCTAssertEqual(r4.nanos, -1)
let r5: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: -1) - Google_Protobuf_Timestamp(nanos: -2000000001)
XCTAssertEqual(r5.seconds, 1)
XCTAssertEqual(r5.nanos, 1)
let r6: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: -10) - Google_Protobuf_Timestamp(nanos: -2000000001)
XCTAssertEqual(r6.seconds, -7)
XCTAssertEqual(r6.nanos, -999999999)
let r7: Google_Protobuf_Duration = Google_Protobuf_Timestamp(seconds: 10) - Google_Protobuf_Timestamp(nanos: 2000000001)
XCTAssertEqual(r7.seconds, 7)
XCTAssertEqual(r7.nanos, 999999999)
}
// TODO: Should setter correct for out-of-range
// nanos and other minor inconsistencies?
func testInitializationByTimestamps() throws {
// Negative timestamp
let t1 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.456)
XCTAssertEqual(t1.seconds, -124)
XCTAssertEqual(t1.nanos, 544000000)
// Full precision
let t2 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.999999999)
XCTAssertEqual(t2.seconds, -124)
XCTAssertEqual(t2.nanos, 1)
// Round up
let t3 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.9999999994)
XCTAssertEqual(t3.seconds, -124)
XCTAssertEqual(t3.nanos, 1)
// Round down
let t4 = Google_Protobuf_Timestamp(timeIntervalSince1970: -123.9999999996)
XCTAssertEqual(t4.seconds, -124)
XCTAssertEqual(t4.nanos, 0)
let t5 = Google_Protobuf_Timestamp(timeIntervalSince1970: 0)
XCTAssertEqual(t5.seconds, 0)
XCTAssertEqual(t5.nanos, 0)
// Positive timestamp
let t6 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.456)
XCTAssertEqual(t6.seconds, 123)
XCTAssertEqual(t6.nanos, 456000000)
// Full precision
let t7 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.999999999)
XCTAssertEqual(t7.seconds, 123)
XCTAssertEqual(t7.nanos, 999999999)
// Round down
let t8 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.9999999994)
XCTAssertEqual(t8.seconds, 123)
XCTAssertEqual(t8.nanos, 999999999)
// Round up
let t9 = Google_Protobuf_Timestamp(timeIntervalSince1970: 123.9999999996)
XCTAssertEqual(t9.seconds, 124)
XCTAssertEqual(t9.nanos, 0)
}
func testInitializationByReferenceTimestamp() throws {
let t1 = Google_Protobuf_Timestamp(timeIntervalSinceReferenceDate: 123.456)
XCTAssertEqual(t1.seconds, 978307323)
XCTAssertEqual(t1.nanos, 456000000)
}
func testInitializationByDates() throws {
let t1 = Google_Protobuf_Timestamp(date: Date(timeIntervalSinceReferenceDate: 123.456))
XCTAssertEqual(t1.seconds, 978307323)
XCTAssertEqual(t1.nanos, 456000000)
}
func testTimestampGetters() throws {
let t1 = Google_Protobuf_Timestamp(seconds: 12345678, nanos: 12345678)
XCTAssertEqual(t1.seconds, 12345678)
XCTAssertEqual(t1.nanos, 12345678)
XCTAssertEqual(t1.timeIntervalSince1970, 12345678.012345678)
XCTAssertEqual(t1.timeIntervalSinceReferenceDate, -965961521.987654322)
let d = t1.date
XCTAssertEqual(d.timeIntervalSinceReferenceDate, -965961521.987654322)
}
}
| gpl-3.0 | b5173e5dbb591dbe7ef6f3b33de86909 | 39.957647 | 146 | 0.609697 | 4.381324 | false | true | false | false |
hyperoslo/Sync | Tests/PropertyMapper/FillWithDictionaryTests.swift | 1 | 2616 | import CoreData
import XCTest
class FillWithDictionaryTests: XCTestCase {
func testBug112() {
let dataStack = Helper.dataStackWithModelName("112")
let owner = Helper.insertEntity("Owner", dataStack: dataStack)
owner.setValue(1, forKey: "id")
let taskList = Helper.insertEntity("TaskList", dataStack: dataStack)
taskList.setValue(1, forKey: "id")
taskList.setValue(owner, forKey: "owner")
let task = Helper.insertEntity("Task", dataStack: dataStack)
task.setValue(1, forKey: "id")
task.setValue(taskList, forKey: "taskList")
task.setValue(owner, forKey: "owner")
try! dataStack.mainContext.save()
let ownerBody = [
"id": 1,
] as [String: Any]
let taskBoby = [
"id": 1,
"owner": ownerBody,
] as [String: Any]
let expected = [
"id": 1,
"owner": ownerBody,
"tasks": [taskBoby],
] as [String: Any]
XCTAssertEqual(expected as NSDictionary, taskList.hyp_dictionary(using: .array) as NSDictionary)
dataStack.drop()
}
func testBug121() {
let dataStack = Helper.dataStackWithModelName("121")
let album = Helper.insertEntity("Album", dataStack: dataStack)
let json = [
"id": "a",
"coverPhoto": ["id": "b"],
] as [String: Any]
album.hyp_fill(with: json)
XCTAssertNotNil(album.value(forKey: "coverPhoto"))
dataStack.drop()
}
func testBug123() {
let dataStack = Helper.dataStackWithModelName("123")
let user = Helper.insertEntity("User", dataStack: dataStack)
user.setValue(1, forKey: "id")
user.setValue("Ignore me", forKey: "name")
try! dataStack.mainContext.save()
let expected = [
"id": 1,
] as [String: Any]
XCTAssertEqual(expected as NSDictionary, user.hyp_dictionary(using: .none) as NSDictionary)
dataStack.drop()
}
func testBug129() {
ValueTransformer.setValueTransformer(BadAPIValueTransformer(), forName: NSValueTransformerName(rawValue: "BadAPIValueTransformer"))
let dataStack = Helper.dataStackWithModelName("129")
let user = Helper.insertEntity("User", dataStack: dataStack)
let json = [
"name": ["bad-backend-dev"],
] as [String: Any]
user.hyp_fill(with: json)
XCTAssertEqual(user.value(forKey: "name") as? String, "bad-backend-dev")
dataStack.drop()
}
}
| mit | 0518221340c2ce0b03b1a0824e2cd033 | 28.727273 | 139 | 0.582187 | 4.471795 | false | true | false | false |
mozilla-mobile/firefox-ios | Client/Nimbus/NimbusManager.swift | 2 | 1615 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
protocol HasNimbusFeatureFlags { }
extension HasNimbusFeatureFlags {
var nimbusFlags: NimbusFeatureFlagLayer {
return NimbusManager.shared.featureFlagLayer
}
}
protocol HasNimbusSearchBar { }
extension HasNimbusSearchBar {
var nimbusSearchBar: NimbusSearchBarLayer {
return NimbusManager.shared.bottomSearchBarLayer
}
}
protocol HasNimbusSponsoredTiles { }
extension HasNimbusSponsoredTiles {
var nimbusSponoredTiles: NimbusSponsoredTileLayer {
return NimbusManager.shared.sponsoredTileLayer
}
}
class NimbusManager {
// MARK: - Singleton
/// To help with access control, we should use protocols to access the required
/// layers. `.shared` should, ideally, never be directly accessed.
static let shared = NimbusManager()
// MARK: - Properties
var featureFlagLayer: NimbusFeatureFlagLayer
var sponsoredTileLayer: NimbusSponsoredTileLayer
var bottomSearchBarLayer: NimbusSearchBarLayer
init(with featureFlagLayer: NimbusFeatureFlagLayer = NimbusFeatureFlagLayer(),
sponsoredTileLayer: NimbusSponsoredTileLayer = NimbusSponsoredTileLayer(),
bottomSearchBarLayer: NimbusSearchBarLayer = NimbusSearchBarLayer()
) {
self.featureFlagLayer = featureFlagLayer
self.sponsoredTileLayer = sponsoredTileLayer
self.bottomSearchBarLayer = bottomSearchBarLayer
}
}
| mpl-2.0 | 8e5dd854a9aee583c176ad5e2b9fbc97 | 30.057692 | 83 | 0.749845 | 4.953988 | false | false | false | false |
squiffy/AlienKit | Pod/Classes/Account.swift | 1 | 1640 | //
// Account.swift
// Pods
//
// Created by Will Estes on 3/21/16.
//
//
import Foundation
import SwiftyJSON
/// `Account` object defined by Reddit.
public class Account: Thing {
public let created: Int?
public let createdUTC: Int?
public let commentKarma: Int?
public let hasMail: Bool?
public let hasModMail: Bool?
public let hasVerifiedEmail: Bool?
public let inboxCount: Int?
public let isFriend: Bool?
public let isGold: Bool?
public let isMod: Bool?
public let modhash: String?
public let over18: Bool?
/**
initialize an `Account` object
- parameter data: JSON data from the API endpoint
- returns: an `Account` object.
*/
init(data: JSON) {
if let created = data["created"].float {
self.created = Int(created)
} else {
created = nil
}
if let createdUTC = data["created_utc"].float {
self.createdUTC = Int(createdUTC)
} else {
createdUTC = nil
}
self.commentKarma = data["comment_karma"].int
self.hasMail = data["has_mail"].bool
self.hasModMail = data["has_mod_mail"].bool
self.hasVerifiedEmail = data["has_verified_email"].bool
self.inboxCount = data["inbox_count"].int
self.isFriend = data["is_friend"].bool
self.isGold = data["is_gold"].bool
self.isMod = data["is_mod"].bool
self.modhash = data["modhash"].string
self.over18 = data["over_18"].bool
super.init(id: data["id"].string, name: data["name"].string)
}
} | mit | 05f1f0984e92acd22ac905533506424c | 25.901639 | 68 | 0.582927 | 3.942308 | false | false | false | false |
duongel/BetterTextField | BetterTextField/BetterTextField.swift | 1 | 3632 | //
// BetterTextField.swift
// Primes
//
// Created by Hua Duong Tran on 06/06/16.
// Copyright © 2017 appic.me. All rights reserved.
//
import UIKit
@IBDesignable
open class BetterTextField: UITextField {
/// A buffer for the placeholder's text.
fileprivate var placeholderText: String?
/// Determines if the user manually changed the text margins.
fileprivate var defaultMode = true
/// The text's margin left manually set by the user.
fileprivate var textMarginLeft: CGFloat = 7.0
/// The text's margin right manually set by the user.
fileprivate var textMarginRight: CGFloat = 7.0
/// The text's margin left.
@IBInspectable open var marginLeft: CGFloat {
get {
if defaultMode && self.clearButtonMode != .never && self.textAlignment == .center {
return 24.0
} else {
return textMarginLeft
}
}
set {
defaultMode = false
textMarginLeft = newValue
}
}
/// The text's margin right.
@IBInspectable open var marginRight: CGFloat {
get {
if defaultMode && self.clearButtonMode != .never {
return 24.0
} else {
return textMarginRight
}
}
set {
defaultMode = false
textMarginRight = newValue
}
}
/// The text field's corner radius. Default is 0.
@IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
/// The text field's border width. Default is 0.
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
/// The text field's border color. Default is nil.
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
// MARK: - Overridden methods
// Insets for the editable text position.
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: UIEdgeInsets.init(top: 0, left: marginLeft, bottom: 0, right: marginRight))
}
// Insets for the placeholder position.
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: UIEdgeInsets.init(top: 0, left: marginLeft, bottom: 0, right: marginRight))
}
// Insets for the text position.
override open func textRect(forBounds bounds: CGRect) -> CGRect {
return bounds.inset(by: UIEdgeInsets.init(top: 0, left: marginLeft, bottom: 0, right: marginRight))
}
/*
* Removes the placeholder text when text field becomes first responder to avoid cursor jumping,
* if text alignment is set to centered.
*/
override open func becomeFirstResponder() -> Bool {
let becameFirstResponder = super.becomeFirstResponder()
if becameFirstResponder {
placeholderText = placeholder
placeholder = ""
}
return becameFirstResponder
}
/*
* Restores the placeholder text to its original value, before it was removed when text field became
* first responder.
*/
override open func resignFirstResponder() -> Bool {
let resigendFirstResponder = super.resignFirstResponder()
if resigendFirstResponder {
placeholder = placeholderText
placeholderText = ""
}
return resigendFirstResponder
}
}
| mit | 16cf4af71a247f336fd6cc1c4c9976c3 | 27.590551 | 107 | 0.6103 | 5.121298 | false | false | false | false |
therealglazou/quaxe-for-swift | quaxe/core/DocumentType.swift | 1 | 1070 | /**
* Quaxe for Swift
*
* Copyright 2016-2017 Disruptive Innovations
*
* Original author:
* Daniel Glazman <[email protected]>
*
* Contributors:
*
*/
/**
* https://dom.spec.whatwg.org/#interface-documenttype
*
* status: done
*/
public class DocumentType: Node, pDocumentType {
internal var mName: DOMString = ""
internal var mPublicId: DOMString = ""
internal var mSystemId: DOMString = ""
/**
* https://dom.spec.whatwg.org/#dom-documenttype-name
*/
public var name: DOMString { return mName }
/**
* https://dom.spec.whatwg.org/#dom-documenttype-publicid
*/
public var publicId: DOMString { return mPublicId }
/**
* https://dom.spec.whatwg.org/#dom-documenttype-systemid
*/
public var systemId: DOMString { return mSystemId }
/**
* https://dom.spec.whatwg.org/#interface-documenttype
*/
init(_ name: DOMString, _ publicId: DOMString = "", _ systemId: DOMString = "") {
self.mName = name
self.mPublicId = publicId
self.mSystemId = systemId
super.init()
}
}
| mpl-2.0 | bf0cc6f2c19913970ae663e2b64a0bcf | 21.291667 | 83 | 0.656075 | 3.728223 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | Session 4/Signup Demo/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift | 13 | 3288 | //
// CurrentThreadScheduler.swift
// Rx
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
let CurrentThreadSchedulerKeyInstance = CurrentThreadSchedulerKey()
class CurrentThreadSchedulerKey : NSObject, NSCopying {
override func isEqual(object: AnyObject?) -> Bool {
return object === CurrentThreadSchedulerKeyInstance
}
override var hashValue: Int { return -904739208 }
override func copy() -> AnyObject {
return CurrentThreadSchedulerKeyInstance
}
func copyWithZone(zone: NSZone) -> AnyObject {
return CurrentThreadSchedulerKeyInstance
}
}
/**
Represents an object that schedules units of work on the current thread.
This is the default scheduler for operators that generate elements.
This scheduler is also sometimes called `trampoline scheduler`.
*/
public class CurrentThreadScheduler : ImmediateSchedulerType {
typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>>
/**
The singleton instance of the current thread scheduler.
*/
public static let instance = CurrentThreadScheduler()
static var queue : ScheduleQueue? {
get {
return NSThread.currentThread().threadDictionary[CurrentThreadSchedulerKeyInstance] as? ScheduleQueue
}
set {
let threadDictionary = NSThread.currentThread().threadDictionary
if let newValue = newValue {
threadDictionary[CurrentThreadSchedulerKeyInstance] = newValue
}
else {
threadDictionary.removeObjectForKey(CurrentThreadSchedulerKeyInstance)
}
}
}
/**
Gets a value that indicates whether the caller must call a `schedule` method.
*/
public static var isScheduleRequired: Bool {
return NSThread.currentThread().threadDictionary[CurrentThreadSchedulerKeyInstance] == nil
}
/**
Schedules an action to be executed as soon as possible on current thread.
If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be
automatically installed and uninstalled after all work is performed.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(state: StateType, action: (StateType) -> Disposable) -> Disposable {
let queue = CurrentThreadScheduler.queue
if let queue = queue {
let scheduledItem = ScheduledItem(action: action, state: state, time: 0)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
let newQueue = RxMutableBox(Queue<ScheduledItemType>(capacity: 0))
CurrentThreadScheduler.queue = newQueue
action(state)
while let latest = newQueue.value.tryDequeue() {
if latest.disposed {
continue
}
latest.invoke()
}
CurrentThreadScheduler.queue = nil
return NopDisposable.instance
}
} | mit | a0968f2cd2ca9353e0464a7c27ca0615 | 31.554455 | 115 | 0.66474 | 5.85918 | false | false | false | false |
CosmicMind/MaterialKit | Sources/iOS/Material+Array.swift | 1 | 2386 | /*
* Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
extension Array where Element: Equatable {
/**
Slices a out a segment of an array based on the start
and end positions.
- Parameter start: A start index.
- Parameter end: An end index.
- Returns: A segmented array based on the start and end
indices.
*/
public func slice(start: Int, end: Int?) -> [Element] {
var e = end ?? count - 1
if e >= count {
e = count - 1
}
guard -1 < start else {
fatalError("Range out of bounds for \(start) - \(end ?? 0), should be 0 - \(count).")
}
var diff = abs(e - start)
guard count > diff else {
return self
}
var ret = [Element]()
while -1 < diff {
ret.insert(self[start + diff], at: 0)
diff -= 1
}
return ret
}
}
| bsd-3-clause | b815f7eb0552ac7bd4cc8d5fd77d7647 | 36.873016 | 91 | 0.697402 | 4.299099 | false | false | false | false |
sagesse-cn/swift-serialize | SerializeTests/SerializeTests.swift | 1 | 32366 | //
// SFSerializeTests.swift
// SFSerializeTests
//
// Created by sagesse on 6/2/15.
// Copyright (c) 2015 Sagesse. All rights reserved.
//
import UIKit
import XCTest
import Serialize
// 如果是自定义的类, 请继承于NSObject
class Example : NSObject {
// 基础类型
var val_int: Int = 0
var val_bool: Bool = false
var val_double: Double = 0
var val_string: String?
var val_array: [Int] = []
var val_dictionary: [Int:Int] = [:]
// 无效的类型
//var val_int_invalid: Int?
//var val_bool_invalid: Bool?
//var val_doulbe_invalid: Double?
//var val_array_invalid: [Int?]?
//var val_dictionary_invalid: [Int:Int?]
// 自定义类型
var val_custom: Custom?
var val_custom_array: [Custom]?
var val_custom_dictionary: [String:Custom]?
class Custom : NSObject {
var val: Example?
}
}
class T1 : NSObject
{
@objc var t_stoi: Int = 0
@objc var t_ftoi: Int = 0
@objc var t_btoi: Int = 0
@objc var t_atoi: Int = 0
@objc var t_dtoi: Int = 0
@objc var t_ntoi: Int = 0
var t_oooi: Int? // 错误的, 这将不能被kvc
@objc var t_stob: Bool = false
@objc var t_ftob: Bool = false
@objc var t_btob: Bool = false
@objc var t_atob: Bool = false
@objc var t_dtob: Bool = false
@objc var t_ntob: Bool = false
var t_ooob: Bool? // 错误的, 这将不能被kvc
@objc var t_stos: String = ""
@objc var t_ftos: String = ""
@objc var t_btos: String = ""
@objc var t_atos: String = ""
@objc var t_dtos: String = ""
@objc var t_ntos: String = ""
@objc var t_stoos: String?
@objc var t_ftoos: String?
@objc var t_btoos: String?
@objc var t_atoos: String?
@objc var t_dtoos: String?
@objc var t_ntoos: String?
@objc var t_stoa: [Int] = []
@objc var t_ftoa: [Int] = []
@objc var t_btoa: [Int] = []
@objc var t_atoa: [Int] = []
@objc var t_dtoa: [Int] = []
@objc var t_ntoa: [Int] = []
@objc var t_stooa: [String]?
@objc var t_ftooa: [String]?
@objc var t_btooa: [String]?
@objc var t_atooa: [String]?
@objc var t_dtooa: [String]?
@objc var t_ntooa: [String]?
@objc var t_stod: [Int:Int] = [:]
@objc var t_ftod: [Int:Int] = [:]
@objc var t_btod: [Int:Int] = [:]
@objc var t_atod: [Int:Int] = [:]
@objc var t_dtod: [Int:Int] = [:]
@objc var t_ntod: [Int:Int] = [:]
@objc var t_stood: [Int:Int]?
@objc var t_ftood: [Int:Int]?
@objc var t_btood: [Int:Int]?
@objc var t_atood: [Int:Int]?
@objc var t_dtood: [Int:Int]?
@objc var t_ntood: [Int:Int]?
@objc var t_atoset = Set<Int>()
@objc var t_atooset: Optional<Set<Int>> = .none
@objc var t_dtot2: T2?
@objc var t_dtot3: T2.T3?
}
class T2 : NSObject {
@objc var t_m : Double = 0
class T3 : NSObject {
@objc var t_m : String?
}
}
class T4 : NSObject {
@objc var i : Int = 0
@objc var f : Float = 0
@objc var s : String = ""
var oi : Int?
var of : Float?
@objc var os : String?
@objc var a : [String] = []
@objc var oa : [Int]?
@objc var t3 : T2.T3?
@objc var d : [Int:Int] = [:]
@objc var od : [Int:Int]?
@objc var odn : [Int:Int]?
@objc var set = Set<Int>()
}
struct s1 {
}
enum e1 {
case zero
}
class c1 {
}
class Test : NSObject {
enum EI : Int {
case s1 = 1
}
enum ES : String {
case S1 = "te"
}
var ei = EI.s1
// var es = ES.S1 // 错误 !!会发生异常
}
class SE1 : InitProvider, ValueProvider {
var a: Optional<Int> = nil
var b: Optional<String> = nil
var c: Optional<Array<Int>> = nil
var u1: Optional<URL> = nil
var u2: Optional<URL> = nil
required init() {
}
func valueForSerialize(_ key: String) -> Any? {
return nil
}
func setValue(_ value: Any?, forSerialize key: String) {
switch key {
case "a": assign(&a, value)
case "b": assign(&b, value)
case "c": assign(&c, value)
case "u1": assign(&u1, value)
case "u2": assign(&u2, value)
default: break
}
}
}
extension SE1 : Hashable {
var hashValue: Int {
return Unmanaged.passUnretained(self).toOpaque().hashValue
}
}
func ==(lhs: SE1, rhs: SE1) -> Bool {
return lhs.hashValue == rhs.hashValue
}
class SE2 : InitProvider, ValueProvider {
var a: Optional<Int> = nil
var b: Optional<String> = nil
var c: Optional<Array<Int>> = nil
var u1: Optional<URL> = nil
var u2: Optional<URL> = nil
required init() {
}
func valueForSerialize(_ key: String) -> Any? {
return nil
}
func setValue(_ value: Any?, forSerialize key: String) {
switch key {
case "a": assign(&a, value)
case "b": assign(&b, value)
case "c": assign(&c, value)
case "u1": assign(&u1, value)
case "u2": assign(&u2, value)
default: break
}
}
}
class SE3<T> : InitProvider, ValueProvider {
var a: Optional<Int> = nil
var b: Optional<String> = nil
var c: Optional<Array<Int>> = nil
var u1: Optional<T> = nil
var u2: Optional<T> = nil
required init() {
}
func valueForSerialize(_ key: String) -> Any? {
return nil
}
func setValue(_ value: Any?, forSerialize key: String) {
switch key {
case "a": assign(&a, value)
case "b": assign(&b, value)
case "c": assign(&c, value)
case "u1": assign(&u1, value)
case "u2": assign(&u2, value)
default: break
}
}
}
class SerializeTests: XCTestCase {
class E1 : NSObject, ValueProvider {
var a: Optional<Int> = nil
@objc var b: Optional<String> = nil
@objc var c: Optional<Array<Int>> = nil
@objc var u1: Optional<URL> = nil
@objc var u2: Optional<URL> = nil
func valueForSerialize(_ key: String) -> Any? {
return nil
}
func setValue(_ value: Any?, forSerialize key: String) {
switch key {
case "a": assign(&a, value)
default: break
}
}
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
/// 测试依赖
func testDepends() {
let i:Int = 0
let f:Float = 0
let d:Double = 0
let s = s1()
let e = e1.zero
let c = c1()
// 基础类型没有显示style
XCTAssert(Mirror(reflecting: i).displayStyle == nil)
XCTAssert(Mirror(reflecting: f).displayStyle == nil)
XCTAssert(Mirror(reflecting: d).displayStyle == nil)
//
XCTAssert(Mirror(reflecting: s).displayStyle == .struct)
XCTAssert(Mirror(reflecting: e).displayStyle == .enum)
XCTAssert(Mirror(reflecting: c).displayStyle == .class)
}
/// 测试解包
func testUnwraps() {
let o: Int?? = 0
let n: Int?? = nil
XCTAssert(type(of: unwraps(o as Any)) is Int.Type)
XCTAssert(type(of: unwraps(n as Any)) is Optional<Optional<Int>>.Type)
}
func testA() {
let s: Dictionary<String, Int>? = Serialize.deserialize(["ss":"22"])
XCTAssert(s != nil)
}
func testSerialize() {
let t = T4()
let t3 = T2.T3()
t3.t_m = "333"
t.i = 2233
t.f = 22.33
t.s = "2233"
t.oi = 2233
t.of = 22.33
t.os = "2233"
t.a = ["1","2","3"]
t.oa = [1,2,3]
t.d = [1:2,3:4,5:6,7:8]
t.od = [1:2,3:4,5:6,7:8]
t.t3 = t3
t.set = [1,2,3]
if let json = Serialize.serialize(t) as? NSDictionary {
XCTAssert(json["i"] as? Int == 2233)
XCTAssert(json["f"] as? Float == 22.33)
XCTAssert(json["s"] as? String == "2233")
XCTAssert(json["oi"] as? Int == 2233)
XCTAssert(json["of"] as? Float == 22.33)
XCTAssert(json["os"] as? String == "2233")
XCTAssert(json["a"] as? Array<String> != nil)
XCTAssert((json["a"] as? NSArray)?.count == 3)
XCTAssert(json["oa"] as? Array<Int> != nil)
XCTAssert((json["oa"] as? NSArray)?.count == 3)
XCTAssert(json["t3"] != nil)
XCTAssert((json["t3"] as? NSDictionary)?["t_m"] != nil)
XCTAssert(json["d"] != nil)
XCTAssert(json["od"] != nil)
XCTAssert((json["d"] as? NSDictionary)?.count == 4)
XCTAssert((json["od"] as? NSDictionary)?.count == 4)
XCTAssert(json["odn"] == nil)
XCTAssert((json["set"] as? NSArray)?.count == 3)
// 测试反序列化
if let tt: T4 = Serialize.deserialize(json) {
XCTAssert(tt.i == 2233)
XCTAssert(tt.f == 22.33)
XCTAssert(tt.s == "2233")
XCTAssert(tt.oi == nil) // 无法反序列化, 没有kvc
XCTAssert(tt.of == nil) // 无法反序列化, 没有kvc
XCTAssert(tt.os == "2233")
XCTAssert(tt.a.count == 3)
XCTAssert(tt.oa != nil)
XCTAssert(tt.oa?.count == 3)
XCTAssert(tt.t3 != nil)
XCTAssert(tt.t3?.t_m == "333")
XCTAssert(tt.d.count == 4)
XCTAssert(tt.od != nil)
XCTAssert(tt.od?.count == 4)
XCTAssert(tt.odn == nil)
XCTAssert(tt.set.count == 3)
}
}
}
func testDeserialize() {
if true {
class T00 : NSObject {
@objc var dress = NSArray()
@objc var djs = NSDictionary()
}
let d = ["dress":[[11000003, 11100079, 11200001, 11300054, 11400112, 11600042],
[11800028, 101]],
"djs":["222":233]
] as [String : Any]
let t0: T00? = Serialize.deserialize(d)
XCTAssert(t0 != nil)
XCTAssert(t0?.dress.count != 0)
XCTAssert(t0?.djs.count != 0)
}
if true {
let json = [
"name":"兔子耳朵",
"classtype":1
] as [String : Any]
class T01 : NSObject {
@objc var name = "unknow"
@objc var classtype: IType = .prop
@objc enum IType : Int, Serializeable {
case prop = 0 ///< 道具
case dress = 1 ///< 时装
case furniture = 2 ///< 家具
case map = 3 ///< 地图
case platform = 4 ///< DJ台
func serialize() -> Any? {
return rawValue.serialize()
}
static func deserialize(_ o: Any) -> IType? {
return IType(rawValue: 1)
}
}
}
let t01 : T01? = Serialize.deserialize(json)
XCTAssert(t01 != nil)
XCTAssert(t01?.name == "兔子耳朵")
XCTAssert(t01?.classtype == .dress)
}
for bundle in Bundle.allBundles {
// 未找到, 忽略
guard let path = bundle.path(forResource: "SerializeTests", ofType: "json") else {
continue
}
// 加载失败
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
XCTAssert(false, "load json fail")
return
}
if let s: T1 = try! Serialize.deserialize(JSONData: data) {
// 检查
XCTAssert(s.t_stoi == 22)
XCTAssert(s.t_ftoi == 22)
XCTAssert(s.t_btoi != 0)
XCTAssert(s.t_atoi == 0)
XCTAssert(s.t_dtoi == 0)
XCTAssert(s.t_ntoi == 0)
XCTAssert(s.t_oooi == nil)
XCTAssert(s.t_stob == true)
XCTAssert(s.t_ftob == true)
XCTAssert(s.t_btob == true)
XCTAssert(s.t_atob == false)
XCTAssert(s.t_dtob == false)
XCTAssert(s.t_ntob == false)
XCTAssert(s.t_ooob == nil)
XCTAssert(s.t_stos == "22.33")
XCTAssert(s.t_ftos == "22.33")
XCTAssert(s.t_btos == "1") ///只能转成数字
XCTAssert(s.t_atos == "")
XCTAssert(s.t_dtos == "")
XCTAssert(s.t_ntos == "")
XCTAssert(s.t_stoos == "22.33")
XCTAssert(s.t_ftoos == "22.33")
XCTAssert(s.t_btoos == "1") ///只能转成数字
XCTAssert(s.t_atoos == nil)
XCTAssert(s.t_dtoos == nil)
XCTAssert(s.t_ntoos == nil)
XCTAssert(s.t_stoa.count == 0)
XCTAssert(s.t_ftoa.count == 0)
XCTAssert(s.t_btoa.count == 0)
XCTAssert(s.t_atoa.count == 2)
XCTAssert(s.t_dtoa.count == 0)
XCTAssert(s.t_ntoa.count == 0)
XCTAssert(s.t_stooa == nil)
XCTAssert(s.t_ftooa == nil)
XCTAssert(s.t_btooa == nil)
XCTAssert(s.t_atooa != nil)
XCTAssert(s.t_dtooa == nil)
XCTAssert(s.t_ntooa == nil)
XCTAssert(s.t_atooa?.count == 2)
XCTAssert(s.t_stod.count == 0)
XCTAssert(s.t_ftod.count == 0)
XCTAssert(s.t_btod.count == 0)
XCTAssert(s.t_atod.count == 0)
XCTAssert(s.t_dtod.count == 1)
XCTAssert(s.t_ntod.count == 0)
XCTAssert(s.t_stood == nil)
XCTAssert(s.t_ftood == nil)
XCTAssert(s.t_btood == nil)
XCTAssert(s.t_atood == nil)
XCTAssert(s.t_dtood != nil)
XCTAssert(s.t_ntood == nil)
XCTAssert(s.t_dtood?.count == 1)
XCTAssert(s.t_dtot2 != nil)
XCTAssert(s.t_dtot2?.t_m == 22.33)
XCTAssert(s.t_dtot3 != nil)
XCTAssert(s.t_dtot3?.t_m == "22.33")
XCTAssert(s.t_atoset.count == 2)
XCTAssert(s.t_atooset?.count == 2)
} else {
XCTAssert(false, "deserialize fail")
}
return
}
XCTAssert(false, "not found SerializeTests.json")
}
func testSwiftAssign() {
struct D {
var i1: Int = 0
var i2: Int = 0
var i3: Int = 0
var i4: Int? = 0
var i5: Int? = 0
var i6: Int? = 0
var i7: Int?? = 0
var i8: Int?? = 0
var i9: Int?? = 0
}
var v = D()
let v1:Any = 1
let v2:Any = Optional<Int>(1) as Any
let v3:Any = Optional<Optional<Int>>(1) as Any
let v4:Any = Optional<Int>.none as Any
let v5:Any = [1,2]
assign(&v.i1, v1)
assign(&v.i2, v4)
assign(&v.i3, v5)
assign(&v.i4, v2)
assign(&v.i5, v4)
assign(&v.i6, v5)
assign(&v.i7, v3)
assign(&v.i8, v4)
assign(&v.i9, v5)
XCTAssert(v.i1 == 1)
XCTAssert(v.i2 == 0)
XCTAssert(v.i3 == 0)
XCTAssert(v.i4 == 1)
XCTAssert(v.i5 == nil)
XCTAssert(v.i6 == nil)
XCTAssert(v.i7! == 1)
XCTAssert(v.i8 == nil)
XCTAssert(v.i9 == nil)
}
func testSwiftKVC() {
struct D : ValueProvider {
var i1: Int = 0
var i2: Int = 0
var i3: Int = 0
var i4: Int? = 0
var i5: Int? = 0
var i6: Int? = 0
var i7: Int?? = 0
var i8: Int?? = 0
var i9: Int?? = 0
func valueForSerialize(_ key: String) -> Any? {
return nil
}
mutating func setValue(_ value: Any?, forSerialize key: String) {
switch key {
case "i1": assign(&self.i1, value)
case "i2": assign(&self.i2, value)
case "i3": assign(&self.i3, value)
case "i4": assign(&self.i4, value)
case "i5": assign(&self.i5, value)
case "i6": assign(&self.i6, value)
case "i7": assign(&self.i7, value)
case "i8": assign(&self.i8, value)
case "i9": assign(&self.i9, value)
default: break
}
}
}
let v1:Any = 1
let v2:Optional<Int> = 1
let v3:Optional<Optional<Int>> = 1
var d = D()
d.setValue(v1 as Any, forSerialize: "i1")
d.setValue(v2 as Any, forSerialize: "i2")
d.setValue(v3 as Any, forSerialize: "i3")
d.setValue(v1 as Any, forSerialize: "i4")
d.setValue(v2 as Any, forSerialize: "i5")
d.setValue(v3 as Any, forSerialize: "i6")
d.setValue(v1 as Any, forSerialize: "i7")
d.setValue(v2 as Any, forSerialize: "i8")
d.setValue(v3 as Any, forSerialize: "i9")
// 可能有bug
XCTAssert(d.i1 == 1)
XCTAssert(d.i2 == 1)
XCTAssert(d.i3 == 1)
XCTAssert(d.i4 == 1)
XCTAssert(d.i5 == 1)
XCTAssert(d.i6 == 1)
XCTAssert(d.i7! == 1)
XCTAssert(d.i8! == 1)
XCTAssert(d.i9! == 1)
}
func testOCBuildtInType() {
let v = Serialize.serialize(1)
XCTAssert(v as? NSNumber == NSNumber(value: 1))
// NSURL
// NSDate
// NSData
// UIImage
// CGFloat
let s = NSSet.deserialize([1,2,3]) as? NSSet
XCTAssert(s != nil)
XCTAssert(s == NSSet(array: [1,2,3]))
let a = NSArray.deserialize([1,2,3])
XCTAssert(a != nil)
XCTAssert(a == [1,2,3])
let d = NSDictionary.deserialize([1:1,2:2,3:3])
XCTAssert(d != nil)
XCTAssert(d == [1:1,2:2,3:3])
}
func testSwiftBuildtInType() {
XCTAssert(Int(1).serialize() as! NSNumber == 1)
XCTAssert(Int8(1).serialize() as! NSNumber == 1)
XCTAssert(Int16(1).serialize() as! NSNumber == 1)
XCTAssert(Int32(1).serialize() as! NSNumber == 1)
XCTAssert(Int64(1).serialize() as! NSNumber == 1)
XCTAssert(UInt(1).serialize() as! NSNumber == 1)
XCTAssert(UInt8(1).serialize() as! NSNumber == 1)
XCTAssert(UInt16(1).serialize() as! NSNumber == 1)
XCTAssert(UInt32(1).serialize() as! NSNumber == 1)
XCTAssert(UInt64(1).serialize() as! NSNumber == 1)
XCTAssert(Float(1).serialize() as! NSNumber == 1)
XCTAssert(Double(1).serialize() as! NSNumber == 1)
XCTAssert(Bool(1).serialize() as! NSNumber == 1)
XCTAssert(String("1").serialize() as! NSString == "1")
XCTAssert(Int.deserialize(1) == 1)
XCTAssert(Int.deserialize("1") == 1)
XCTAssert(Int.deserialize("1.1") == 1)
XCTAssert(Int.deserialize("x") == nil)
XCTAssert(Int8.deserialize(1) == 1)
XCTAssert(Int8.deserialize("1") == 1)
XCTAssert(Int8.deserialize("1.1") == 1)
XCTAssert(Int8.deserialize("x") == nil)
XCTAssert(Int16.deserialize(1) == 1)
XCTAssert(Int16.deserialize("1") == 1)
XCTAssert(Int16.deserialize("1.1") == 1)
XCTAssert(Int16.deserialize("x") == nil)
XCTAssert(Int32.deserialize(1) == 1)
XCTAssert(Int32.deserialize("1") == 1)
XCTAssert(Int32.deserialize("1.1") == 1)
XCTAssert(Int32.deserialize("x") == nil)
XCTAssert(Int64.deserialize(1) == 1)
XCTAssert(Int64.deserialize("1") == 1)
XCTAssert(Int64.deserialize("1.1") == 1)
XCTAssert(Int64.deserialize("x") == nil)
XCTAssert(UInt.deserialize(1) == 1)
XCTAssert(UInt.deserialize("1") == 1)
XCTAssert(UInt.deserialize("1.1") == 1)
XCTAssert(UInt.deserialize("x") == nil)
XCTAssert(UInt8.deserialize(1) == 1)
XCTAssert(UInt8.deserialize("1") == 1)
XCTAssert(UInt8.deserialize("1.1") == 1)
XCTAssert(UInt8.deserialize("x") == nil)
XCTAssert(UInt16.deserialize(1) == 1)
XCTAssert(UInt16.deserialize("1") == 1)
XCTAssert(UInt16.deserialize("1.1") == 1)
XCTAssert(UInt16.deserialize("x") == nil)
XCTAssert(UInt32.deserialize(1) == 1)
XCTAssert(UInt32.deserialize("1") == 1)
XCTAssert(UInt32.deserialize("1.1") == 1)
XCTAssert(UInt32.deserialize("x") == nil)
XCTAssert(UInt64.deserialize(1) == 1)
XCTAssert(UInt64.deserialize("1") == 1)
XCTAssert(UInt64.deserialize("1.1") == 1)
XCTAssert(UInt64.deserialize("x") == nil)
XCTAssert(Float.deserialize(1) == 1.0)
XCTAssert(Float.deserialize("1") == 1.0)
XCTAssert(Float.deserialize("1.1") == 1.1)
XCTAssert(Float.deserialize("x") == nil)
XCTAssert(Double.deserialize(1) == 1.0)
XCTAssert(Double.deserialize("1") == 1.0)
XCTAssert(Double.deserialize("1.1") == 1.1)
XCTAssert(Double.deserialize("x") == nil)
XCTAssert(Bool.deserialize(1) == true)
XCTAssert(Bool.deserialize("0") == false)
XCTAssert(Bool.deserialize("1.1") == true)
XCTAssert(Bool.deserialize("x") == nil)
XCTAssert(String.deserialize(1) == "1")
XCTAssert(String.deserialize("0") == "0")
XCTAssert(String.deserialize("1.1") == "1.1")
XCTAssert(String.deserialize("x") == "x")
XCTAssert(String.deserialize([1]) == nil)
XCTAssert(CGFloat(1).serialize() as! NSNumber == 1)
XCTAssert(CGFloat.deserialize(1) == 1.0)
XCTAssert(CGFloat.deserialize("1") == 1.0)
XCTAssert(CGFloat.deserialize("1.1") == 1.1)
XCTAssert(CGFloat.deserialize("x") == nil)
let a = Array<Array<Int>>.deserialize([[1,2,3]])
XCTAssert(a != nil)
XCTAssert(a![0].count != 0)
XCTAssert(a![0] == [1,2,3])
}
func testSet() {
let si = Set<Int>([1,2]).serialize()
// 序列化结果应为[1,2], 类型应为NSArray
XCTAssert(si != nil, "serialize fail")
XCTAssert(si! is NSArray, "type error")
XCTAssertEqual((si as? [Int])?.sorted(), [1,2], "value error")
let sn = Set<Int>().serialize()
// 序列化结果应为NSArray
XCTAssert(sn == nil, "serialize fail")
let di = Set<Int>.deserialize([1,2])
// 反序列化结果应为123, 类型应为Set<Int>
XCTAssert(di != nil, "serialize fail")
XCTAssertEqual(di!, [2,1], "value error")
let dn = Set<Int>.deserialize("error")
// 反序列化结果应为nil
XCTAssert(dn == nil, "serialize fail")
}
func testArray() {
let si = Array<Int>([1,2]).serialize()
// 序列化结果应为[1,2], 类型应为NSArray
XCTAssert(si != nil, "serialize fail")
XCTAssert(si! is NSArray, "type error")
XCTAssertEqual(si as? NSArray, [1,2], "value error")
let sn = Array<Int>().serialize()
// 序列化结果应为NSArray
XCTAssert(sn == nil, "serialize fail")
let di = Array<Int>.deserialize([1,2])
// 反序列化结果应为123, 类型应为Array<Int>
XCTAssert(di != nil, "serialize fail")
XCTAssertEqual(di!, [1,2], "value error")
let dn = Array<Int>.deserialize("error")
// 反序列化结果应为nil
XCTAssert(dn == nil, "serialize fail")
}
func testDictionary() {
let si = Dictionary<Int, Int>(dictionaryLiteral: (1,2),(2,3)).serialize()
// 序列化结果应为["1":2,"2":3], 类型应为NSDictionary
XCTAssert(si != nil, "serialize fail")
XCTAssert(si! is NSDictionary, "type error")
XCTAssertEqual(si as? NSDictionary, ["1":2,"2":3], "value error")
let sn = Dictionary<Int, Int>().serialize()
// 序列化结果应为NSArray
XCTAssert(sn == nil, "serialize fail")
let di = Dictionary<Int, Int>.deserialize(["1":2,2:3])
// 反序列化结果应为123, 类型应为Array<Int>
XCTAssert(di != nil, "serialize fail")
XCTAssertEqual(di!, [1:2,2:3], "value error")
let dn = Dictionary<Int, Int>.deserialize("error")
// 反序列化结果应为nil
XCTAssert(dn == nil, "serialize fail")
}
func testOptional() {
let si = Optional<Int>(123).serialize()
// 序列化结果应为123, 类型应为NSNumber
XCTAssert(si != nil, "serialize fail")
XCTAssert(si! is NSNumber, "type error")
XCTAssert(si as! NSNumber == 123, "value error")
let sn = Optional<Int>.none.serialize()
// 序列化结果应为nil
XCTAssert(sn == nil, "serialize fail")
let di = Optional<Int>.deserialize(123)
// 反序列化结果应为123, 类型应为Int
XCTAssert(di != nil, "serialize fail")
XCTAssert(di! == 123, "value error")
let dn = Optional<Int>.deserialize("error")
// 反序列化结果应为nil
XCTAssert(dn == nil, "serialize fail")
}
func testSwitfCustomType() {
let td = [
"a":1,
"b":"str",
"c":["1",1],
"u1":"http://www.baidu.com",
"u2":"file://www.baidu.com"
] as [String : Any]
let e1: SE1? = Serialize.deserialize(td)
XCTAssert(e1?.a == 1)
XCTAssert(e1?.b == "str")
XCTAssert(e1!.c! == [1,1])
XCTAssert(e1?.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e1?.u2 == URL(string: "file://www.baidu.com"))
let e2: SE2? = Serialize.deserialize(td)
XCTAssert(e2?.a == 1)
XCTAssert(e2?.b == "str")
XCTAssert(e2!.c! == [1,1])
XCTAssert(e2?.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e2?.u2 == URL(string: "file://www.baidu.com"))
let e3: SE3<URL>? = Serialize.deserialize(td)
XCTAssert(e3?.a == 1)
XCTAssert(e3?.b == "str")
XCTAssert(e3!.c! == [1,1])
XCTAssert(e3?.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e3?.u2 == URL(string: "file://www.baidu.com"))
let e4: SE3<String>? = Serialize.deserialize(td)
XCTAssert(e4?.a == 1)
XCTAssert(e4?.b == "str")
XCTAssert(e4!.c! == [1,1])
XCTAssert(e4?.u1 == "http://www.baidu.com")
XCTAssert(e4?.u2 == "file://www.baidu.com")
let e5 = Array<SE3<URL>>.deserialize([td, td, td, td])
XCTAssert(e5 != nil)
XCTAssert(e5?.count == 4)
for e in e5! {
XCTAssert(e.a == 1)
XCTAssert(e.b == "str")
XCTAssert(e.c! == [1,1])
XCTAssert(e.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e.u2 == URL(string: "file://www.baidu.com"))
}
let e6 = Set<SE1>.deserialize([td, td, td, td])
XCTAssert(e6 != nil)
XCTAssert(e6?.count == 4)
for e in e6! {
XCTAssert(e.a == 1)
XCTAssert(e.b == "str")
XCTAssert(e.c! == [1,1])
XCTAssert(e.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e.u2 == URL(string: "file://www.baidu.com"))
}
let dic: NSDictionary = ["1":td, 2:td, 1:td, [2]:td]
let e7 = Dictionary<Int, SE1>.deserialize(dic)
XCTAssert(e7 != nil)
XCTAssert(e7?.count == 2)
for (_,e) in e7! {
XCTAssert(e.a == 1)
XCTAssert(e.b == "str")
XCTAssert(e.c! == [1,1])
XCTAssert(e.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e.u2 == URL(string: "file://www.baidu.com"))
}
let e8 = Optional<SE1>.deserialize(td as AnyObject)
XCTAssert(e8 != nil)
XCTAssert(e8!!.a == 1)
XCTAssert(e8!!.b == "str")
XCTAssert(e8!!.c! == [1,1])
XCTAssert(e8!!.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e8!!.u2 == URL(string: "file://www.baidu.com"))
}
func testOCCustomType() {
let e = E1.deserialize([
"a":1,
"b":"str",
"c":["1",1],
"u1":"http://www.baidu.com",
"u2":"file://www.baidu.com"
])
XCTAssert(e?.a == 1)
XCTAssert(e?.b == "str")
XCTAssert(e!.c! == [1,1])
XCTAssert(e?.u1 == URL(string: "http://www.baidu.com"))
XCTAssert(e?.u2 == URL(string: "file://www.baidu.com"))
}
func testExample() {
// If it is a custom class that inherits from NSObject, please
class Example : NSObject {
// base type
@objc var val_int: Int = 0
@objc var val_bool: Bool = false
@objc var val_double: Double = 0
@objc var val_string: String?
@objc var val_array: [Int] = []
@objc var val_dictionary: [Int:Int] = [:]
// invalid type
//var val_int_invalid: Int?
//var val_bool_invalid: Bool?
//var val_doulbe_invalid: Double?
//var val_array_invalid: [Int?]?
//var val_dictionary_invalid: [Int:Int?]
// custom type
@objc var val_custom: Custom?
@objc var val_custom_array: [Custom]?
@objc var val_custom_dictionary: [String:Custom]?
class Custom : NSObject {
var val: Example?
}
}
let e1 = Example()
e1.val_int = 123
e1.val_bool = true
e1.val_double = 456.0
e1.val_string = "hello swift"
e1.val_array = [7, 8, 9]
e1.val_dictionary = [10 : 11, 12 : 13, 14 : 15]
// serialize
let json = Serialize.serialize(e1)
let jsonData = try! Serialize.serializeToJSONData(e1)
let jsonString = try! Serialize.serializeToJSONString(e1)
// 138
print(jsonData!.count)
// {"val_string":"hello swift","val_bool":true,"val_dictionary":{"12":13,"14":15,"10":11},"val_array":[7,8,9],"val_int":123,"val_double":456}
print(jsonString!)
// deserialize
let e2: Example? = Serialize.deserialize(json!)
let e3: Example? = Serialize.deserialize(json as Any, Example.self) as? Example
print(e1 == e2)
print(e2 == e3)
}
}
| mit | 23f6e433228a915c584e6a7477d1480d | 30.147894 | 149 | 0.480033 | 3.674832 | false | false | false | false |
dsxNiubility/SXSwiftWeibo | 103 - swiftWeibo/103 - swiftWeibo/Classes/UI/Compose/Emoticons.swift | 1 | 5911 |
//
// Emoticons.swift
// 103 - swiftWeibo
//
// Created by 董 尚先 on 15/3/12.
// Copyright (c) 2015年 shangxianDante. All rights reserved.
//
import Foundation
/// 表情符号数组单例,专供查询使用
class EmoticonList {
/// 单例
private static let instance = EmoticonList()
class var sharedEmoticonList: EmoticonList {
return instance
}
/// 所有自定义表情的大数组,便于查询
var allEmoticons: [Emoticon]
init () {
// 实例化表情数组
allEmoticons = [Emoticon]()
// 填充数据
// 1. 加载分组数据中的表情
let sections = EmoticonsSection.loadEmoticons()
// 2. 合并数组(提示:可以把 emoji 去掉)
for sec in sections {
allEmoticons += sec.emoticons
}
}
}
/// 表情符号分组
class EmoticonsSection {
/// 分组名称
var name: String
/// 类型
var type: String
/// 路径
var path: String
/// 表情符号的数组(每一个 section中应该包含21个表情符号,界面处理是最方便的)
/// 其中21个表情符号中,最后一个删除(就不能使用plist中的数据)
var emoticons: [Emoticon]
init(dict: NSDictionary) {
name = dict["emoticon_group_name"] as! String
type = dict["emoticon_group_type"] as! String
path = dict["emoticon_group_path"] as! String
emoticons = [Emoticon]()
}
/// 加载表情符号的分组数据
class func loadEmoticons() -> [EmoticonsSection] {
let path = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons/emoticons.plist")
/// array是用大plist加载的数组
var array = NSArray(contentsOfFile: path)
/// 对数组进行排序
array = array?.sortedArrayUsingComparator{ (dict1, dict2) -> NSComparisonResult in
let type1 = dict1["emoticon_group_type"] as! String
let type2 = dict2["emoticon_group_type"] as! String
return type1.compare(type2)
}
/// 遍历数组
var result = [EmoticonsSection]()
for dict in array as! [NSDictionary] {
/// 取出大数组中的每一种表情的字典
result += loadEmoticons(dict)
}
return result
}
/// 加载表情符号数组 传入的dict是大数组中的每一种表情字典
class func loadEmoticons(dict:NSDictionary) -> [EmoticonsSection] {
/// 取出主目录数组中的数据,加载不同目录的info.plist
let group_path = dict["emoticon_group_path"] as! String
let path = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons/\(group_path)/info.plist")
/// infoDict是info的小字典
let infoDict = NSDictionary(contentsOfFile: path)!
/// list是每一个表情的组合的数组
let list = infoDict["emoticon_group_emoticons"] as! NSArray
let result = loadArrayEmoticons(list, dict: dict)
return result
}
/// 返回表情数组, 传入的dict是小infoPlist生成的字典
class func loadArrayEmoticons(list:NSArray,dict:NSDictionary) -> [EmoticonsSection] {
/// 规定多少个可以组成一组
let emoticonCount = 20
/// 算出一共会组成多少组
let objCount = (list.count - 1) / emoticonCount + 1
var result = [EmoticonsSection]()
for i in 0..<objCount {
// 通过每一个info建立每一种的表情数组
let emoticonSection = EmoticonsSection(dict: dict)
for count in 0..<20 {
let j = count + i * emoticonCount
var dict: NSDictionary? = nil
/// list是每一个表情的组合的数组
if j < list.count {
dict = list[j] as? NSDictionary
}
/// 这个dict 是表情数组里的每一个表情自己的小字典
let em = Emoticon(dict: dict, path: emoticonSection.path)
emoticonSection.emoticons.append(em)
}
/// 添加删除按钮的模型
let em = Emoticon(dict: nil, path: nil)
em.isDeleteButton = true
emoticonSection.emoticons.append(em)
/// 将每一种添加到大数组
result.append(emoticonSection)
}
return result
}
}
/// 表情符号类
class Emoticon {
/// emoji 的16进制字符串
var code: String?
/// emoji 字符串
var emoji: String?
/// 类型
var type: String?
/// 表情符号的文本 - 发送给服务器的文本
var chs: String?
/// 表情符号的图片 - 本地做图文混排使用的图片
var png: String?
/// 图像的完整路径
var imagePath: String?
/// 是否是删除按钮
var isDeleteButton = false
init(dict:NSDictionary?,path: String? ) {
code = dict?["code"] as? String
type = dict?["type"] as? String
chs = dict?["chs"] as? String
png = dict?["png"] as? String
if path != nil && png != nil {
imagePath = (NSBundle.mainBundle().bundlePath as NSString).stringByAppendingPathComponent("Emoticons/\(path!)/\(png!)")
}
/// 计算 emoji
if code != nil {
let scanner = NSScanner(string: code!)
var value:UInt32 = 0
scanner.scanHexInt(&value)
emoji = "\(Character(UnicodeScalar(value)))"
}
}
} | mit | 51eadf5630c194303b9666c7c18eb2f8 | 26.311828 | 134 | 0.541445 | 4.370912 | false | false | false | false |
pawel-sp/PSZGateTransitioning | PSZGateTransitioning/GateAnimator+Animations.swift | 1 | 5718 | //
// GateAnimator+Animations.swift
// PSZGateTransitioning
//
// Created by Paweł Sporysz on 28.01.2015.
// Copyright (c) 2015 Paweł Sporysz. All rights reserved.
//
import Foundation
typealias GateAnimationCompletionBlock = () -> ()
extension GateAnimator {
func animationForOperation(operation:UINavigationControllerOperation, fromVC:UIViewController, toVC:UIViewController, duration: NSTimeInterval, completionBlock:GateAnimationCompletionBlock? = nil) {
switch operation {
case .Push:
pushAnimation(fromVC: fromVC, toVC: toVC, snapshotViews: snapshotViews!, duration: duration - initialDelay, delay: initialDelay) {
self.animatedSourceSubviewSnapshot?.removeFromSuperview()
fromVC.view.alpha = 1
completionBlock?()
}
case .Pop:
popAnimation(fromVC: fromVC, toVC: toVC, snapshotViews: snapshotViews!, duration: duration, delay: 0) {
toVC.view.alpha = 1
self.snapshotViews?.upperSnapshotView.removeFromSuperview()
self.snapshotViews?.lowerSnapshotView.removeFromSuperview()
self.animatedSourceSubviewSnapshot?.removeFromSuperview()
completionBlock?()
}
default: break
}
}
func popAnimation(fromVC fromVC:UIViewController, toVC:UIViewController, snapshotViews:SnapshotViews, duration:NSTimeInterval, delay:NSTimeInterval, completionBlock:GateAnimationCompletionBlock? = nil) {
UIView.animateKeyframesWithDuration(
duration,
delay: 0,
options: UIViewKeyframeAnimationOptions.CalculationModePaced,
animations: { () -> Void in
// source view
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { () -> Void in
fromVC.view.alpha = 0
})
// snapshots
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { () -> Void in
snapshotViews.upperSnapshotView.transform = CGAffineTransformIdentity
snapshotViews.upperSnapshotView.alpha = 1
snapshotViews.lowerSnapshotView.transform = CGAffineTransformIdentity
snapshotViews.lowerSnapshotView.alpha = 1
})
// animated subview
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { () -> Void in
if self.animatedSourceSubviewSnapshot != nil && self.animatedSubviewDestinationFrame != nil {
self.animatedSourceSubviewSnapshot!.transform = CGAffineTransformMakeTranslation(
self.animatedSubviewDestinationFrame!.origin.x - self.animatedSourceSubviewSnapshot!.frame.origin.x,
self.animatedSubviewDestinationFrame!.origin.y - self.animatedSourceSubviewSnapshot!.frame.origin.y
)
}
})
}, completion: { (finished) -> Void in
completionBlock?()
return
}
)
}
func pushAnimation(fromVC fromVC:UIViewController, toVC:UIViewController, snapshotViews:SnapshotViews, duration:NSTimeInterval, delay:NSTimeInterval, completionBlock:GateAnimationCompletionBlock? = nil) {
// it removes blinking bug
UIView.animateWithDuration(initialDelay, animations: { () -> Void in
snapshotViews.upperSnapshotView.alpha = 1
snapshotViews.lowerSnapshotView.alpha = 1
}, completion: { (_) -> Void in
fromVC.view.alpha = 0
})
UIView.animateKeyframesWithDuration(
duration - initialDelay,
delay: initialDelay,
options: UIViewKeyframeAnimationOptions.CalculationModeCubic,
animations: { () -> Void in
// snapshots
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.35, animations: { () -> Void in
snapshotViews.upperSnapshotView.transform = CGAffineTransformMakeTranslation(0, -snapshotViews.upperSnapshotView.frame.height)
snapshotViews.upperSnapshotView.alpha = 0
snapshotViews.lowerSnapshotView.transform = CGAffineTransformMakeTranslation(0, snapshotViews.lowerSnapshotView.frame.height)
snapshotViews.upperSnapshotView.alpha = 0
})
// destination view
UIView.addKeyframeWithRelativeStartTime(0.55, relativeDuration: 0.35, animations: { () -> Void in
toVC.view.alpha = 1
})
// animated subview
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 1, animations: { () -> Void in
if self.animatedSourceSubviewSnapshot != nil && self.animatedSubviewDestinationFrame != nil {
self.animatedSourceSubviewSnapshot!.transform = CGAffineTransformMakeTranslation(
self.animatedSubviewDestinationFrame!.origin.x - self.animatedSourceSubviewSnapshot!.frame.origin.x,
self.animatedSubviewDestinationFrame!.origin.y - self.animatedSourceSubviewSnapshot!.frame.origin.y
)
}
})
}, completion: { (finished) -> Void in
completionBlock?()
return
}
)
}
} | mit | 5bd1debcee2524ff93ce437c7fd950e8 | 48.284483 | 208 | 0.601819 | 6.63109 | false | false | false | false |
shotaroikeda/LiquidFloatingActionButton | Pod/Classes/SimpleCircleLiquidEngine.swift | 1 | 5676 | //
// SimpleCircleLiquidEngine.swift
// LiquidLoading
//
// Created by Takuma Yoshida on 2015/08/19.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
/**
* This class is so fast, but allowed only same color.
*/
class SimpleCircleLiquidEngine {
let radiusThresh: CGFloat
fileprivate var layer: CALayer = CAShapeLayer()
var viscosity: CGFloat = 0.65
var color: UIColor = UIColor.blue
var angleOpen: CGFloat = 1.0
let ConnectThresh: CGFloat = 0.3
var angleThresh: CGFloat = 0.5
init(radiusThresh: CGFloat, angleThresh: CGFloat) {
self.radiusThresh = radiusThresh
self.angleThresh = angleThresh
}
func push(_ circle: LiquittableCircle, other: LiquittableCircle) -> [LiquittableCircle] {
if let paths = generateConnectedPath(circle, other: other) {
let layers = paths.map(self.constructLayer)
layers.each(layer.addSublayer)
return [circle, other]
}
return []
}
func draw(_ parent: UIView) {
parent.layer.addSublayer(layer)
}
func clear() {
layer.removeFromSuperlayer()
// layer.sublayers?.each{ $0.removeFromSuperlayer() } // let garbage collection handle this
layer = CAShapeLayer()
}
func constructLayer(_ path: UIBezierPath) -> CALayer {
let pathBounds = path.cgPath.boundingBox;
let shape = CAShapeLayer()
shape.fillColor = self.color.cgColor
shape.path = path.cgPath
shape.frame = CGRect(x: 0, y: 0, width: pathBounds.width, height: pathBounds.height)
return shape
}
fileprivate func circleConnectedPoint(_ circle: LiquittableCircle, other: LiquittableCircle, angle: CGFloat) -> (CGPoint, CGPoint) {
let vec = other.center.minus(circle.center)
let radian = atan2(vec.y, vec.x)
let p1 = circle.circlePoint(radian + angle)
let p2 = circle.circlePoint(radian - angle)
return (p1, p2)
}
fileprivate func circleConnectedPoint(_ circle: LiquittableCircle, other: LiquittableCircle) -> (CGPoint, CGPoint) {
var ratio = circleRatio(circle, other: other)
ratio = (ratio + ConnectThresh) / (1.0 + ConnectThresh)
let angle = CGFloat(M_PI_2) * angleOpen * ratio
return circleConnectedPoint(circle, other: other, angle: angle)
}
func generateConnectedPath(_ circle: LiquittableCircle, other: LiquittableCircle) -> [UIBezierPath]? {
if isConnected(circle, other: other) {
let ratio = circleRatio(circle, other: other)
switch ratio {
case angleThresh...1.0:
if let path = normalPath(circle, other: other) {
return [path]
}
return nil
case 0.0..<angleThresh:
return splitPath(circle, other: other, ratio: ratio)
default:
return nil
}
} else {
return nil
}
}
fileprivate func normalPath(_ circle: LiquittableCircle, other: LiquittableCircle) -> UIBezierPath? {
let (p1, p2) = circleConnectedPoint(circle, other: other)
let (p3, p4) = circleConnectedPoint(other, other: circle)
if let crossed = CGPoint.intersection(p1, to: p3, from2: p2, to2: p4) {
return withBezier { path in
let r = self.circleRatio(circle, other: other)
path.move(to: p1)
let r1 = p2.mid(p3)
let r2 = p1.mid(p4)
let rate = (1 - r) / (1 - self.angleThresh) * self.viscosity
let mul = r1.mid(crossed).split(r2, ratio: rate)
let mul2 = r2.mid(crossed).split(r1, ratio: rate)
path.addQuadCurve(to: p4, controlPoint: mul)
path.addLine(to: p3)
path.addQuadCurve(to: p2, controlPoint: mul2)
}
}
return nil
}
fileprivate func splitPath(_ circle: LiquittableCircle, other: LiquittableCircle, ratio: CGFloat) -> [UIBezierPath] {
let (p1, p2) = circleConnectedPoint(circle, other: other, angle: CGMath.degToRad(60))
let (p3, p4) = circleConnectedPoint(other, other: circle, angle: CGMath.degToRad(60))
if let crossed = CGPoint.intersection(p1, to: p3, from2: p2, to2: p4) {
let (d1, _) = self.circleConnectedPoint(circle, other: other, angle: 0)
let (d2, _) = self.circleConnectedPoint(other, other: circle, angle: 0)
let r = (ratio - ConnectThresh) / (angleThresh - ConnectThresh)
let a1 = d2.split(crossed, ratio: (r * r))
let part = withBezier { path in
path.move(to: p1)
path.addQuadCurve(to: p2, controlPoint: a1)
}
let a2 = d1.split(crossed, ratio: (r * r))
let part2 = withBezier { path in
path.move(to: p3)
path.addQuadCurve(to: p4, controlPoint: a2)
}
return [part, part2]
}
return []
}
fileprivate func circleRatio(_ circle: LiquittableCircle, other: LiquittableCircle) -> CGFloat {
let distance = other.center.minus(circle.center).length()
let ratio = 1.0 - (distance - radiusThresh) / (circle.radius + other.radius + radiusThresh)
return min(max(ratio, 0.0), 1.0)
}
func isConnected(_ circle: LiquittableCircle, other: LiquittableCircle) -> Bool {
let distance = circle.center.minus(other.center).length()
return distance - circle.radius - other.radius < radiusThresh
}
}
| mit | 446dad29441669eefbf6718072968c65 | 36.328947 | 136 | 0.595523 | 4.234328 | false | false | false | false |
infobip/mobile-messaging-sdk-ios | Classes/Core/Installation/InstallationAttributeModels.swift | 1 | 18186 | //
// InstallationAttributeModels.swift
// MobileMessaging
//
// Created by Andrey Kadochnikov on 29/11/2018.
//
import Foundation
import CoreLocation
struct DepersonalizationConsts {
static var failuresNumberLimit = 3
}
@objc public enum MMSuccessPending: Int {
case undefined = 0, pending, success
}
final class InternalData : NSObject, NSCoding, NSCopying, ArchivableCurrent, NamedLogger {
static var currentPath = getDocumentsDirectory(filename: "internal-data")
static var cached = ThreadSafeDict<InternalData>()
static var empty: InternalData {
return InternalData(systemDataHash: 0, location: nil, badgeNumber: 0, applicationCode: nil, applicationCodeHash: nil, depersonalizeFailCounter: 0, currentDepersonalizationStatus: .undefined, registrationDate: nil, chatMessageCounter: 0)
}
func removeSensitiveData() {
if MobileMessaging.privacySettings.applicationCodePersistingDisabled {
self.applicationCode = nil
}
}
func handleCurrentChanges(old: InternalData, new: InternalData) {
if old.currentDepersonalizationStatus != new.currentDepersonalizationStatus {
logDebug("setting new depersonalize status: \(self.currentDepersonalizationStatus.rawValue)")
MobileMessaging.sharedInstance?.updateDepersonalizeStatusForSubservices()
}
}
///
var chatMessageCounter: Int
var registrationDate: Date?
var systemDataHash: Int64
var location: CLLocation?
var badgeNumber: Int
var applicationCode: String?
var applicationCodeHash: String?
var depersonalizeFailCounter: Int
var currentDepersonalizationStatus: MMSuccessPending
///
func copy(with zone: NSZone? = nil) -> Any {
let copy = InternalData(systemDataHash: systemDataHash, location: location, badgeNumber: badgeNumber, applicationCode: applicationCode, applicationCodeHash: applicationCodeHash, depersonalizeFailCounter: depersonalizeFailCounter, currentDepersonalizationStatus: currentDepersonalizationStatus, registrationDate: registrationDate, chatMessageCounter: chatMessageCounter)
return copy
}
init(systemDataHash: Int64, location: CLLocation?, badgeNumber: Int, applicationCode: String?, applicationCodeHash: String?, depersonalizeFailCounter: Int, currentDepersonalizationStatus: MMSuccessPending, registrationDate: Date?, chatMessageCounter: Int) {
self.systemDataHash = systemDataHash
self.location = location
self.badgeNumber = badgeNumber
self.applicationCode = applicationCode
self.applicationCodeHash = applicationCodeHash
self.depersonalizeFailCounter = depersonalizeFailCounter
self.currentDepersonalizationStatus = currentDepersonalizationStatus
self.registrationDate = registrationDate
self.chatMessageCounter = chatMessageCounter
}
required public init?(coder aDecoder: NSCoder) {
systemDataHash = aDecoder.decodeInt64(forKey: "systemDataHash")
location = aDecoder.decodeObject(forKey: "location") as? CLLocation
badgeNumber = aDecoder.decodeInteger(forKey: "badgeNumber")
applicationCode = aDecoder.decodeObject(forKey: "applicationCode") as? String
applicationCodeHash = aDecoder.decodeObject(forKey: "applicationCodeHash") as? String
depersonalizeFailCounter = aDecoder.decodeInteger(forKey: "depersonalizeFailCounter")
currentDepersonalizationStatus = MMSuccessPending(rawValue: aDecoder.decodeInteger(forKey: "currentDepersonalizationStatus")) ?? .undefined
registrationDate = aDecoder.decodeObject(forKey: "registrationDate") as? Date
chatMessageCounter = aDecoder.decodeInteger(forKey: "chatMessageCounter")
}
func encode(with aCoder: NSCoder) {
aCoder.encode(systemDataHash, forKey: "systemDataHash")
aCoder.encode(location, forKey: "location")
aCoder.encode(badgeNumber, forKey: "badgeNumber")
aCoder.encode(applicationCode, forKey: "applicationCode")
aCoder.encode(applicationCodeHash, forKey: "applicationCodeHash")
aCoder.encode(depersonalizeFailCounter, forKey: "depersonalizeFailCounter")
aCoder.encode(currentDepersonalizationStatus.rawValue, forKey: "currentDepersonalizationStatus")
aCoder.encode(registrationDate, forKey: "registrationDate")
aCoder.encode(chatMessageCounter, forKey: "chatMessageCounter")
}
}
@objcMembers public final class MMInstallation: NSObject, NSCoding, NSCopying, JSONDecodable, DictionaryRepresentable, Archivable {
var version: Int = 0
static var currentPath = getDocumentsDirectory(filename: "installation")
static var dirtyPath = getDocumentsDirectory(filename: "dirty-installation")
static var cached = ThreadSafeDict<MMInstallation>()
static var empty: MMInstallation {
let systemData = MMUserAgent().systemData
return MMInstallation(applicationUserId: nil, appVersion: systemData.appVer, customAttributes: [:], deviceManufacturer: systemData.deviceManufacturer, deviceModel: systemData.deviceModel, deviceName: systemData.deviceName, deviceSecure: systemData.deviceSecure, deviceTimeZone: systemData.deviceTimeZone, geoEnabled: false, isPrimaryDevice: false, isPushRegistrationEnabled: true, language: systemData.language, notificationsEnabled: systemData.notificationsEnabled ?? true, os: systemData.os, osVersion: systemData.OSVer, pushRegistrationId: nil, pushServiceToken: nil, pushServiceType: systemData.pushServiceType, sdkVersion: systemData.SDKVersion)
}
func removeSensitiveData() {
//nothing is sensitive in installation
}
func handleCurrentChanges(old: MMInstallation, new: MMInstallation) {
if old.pushRegistrationId != new.pushRegistrationId {
UserEventsManager.postRegUpdatedEvent(pushRegistrationId)
}
if old.isPushRegistrationEnabled != new.isPushRegistrationEnabled {
MobileMessaging.sharedInstance?.updateRegistrationEnabledSubservicesStatus()
}
}
func handleDirtyChanges(old: MMInstallation, new: MMInstallation) {
if old.isPushRegistrationEnabled != new.isPushRegistrationEnabled {
MobileMessaging.sharedInstance?.updateRegistrationEnabledSubservicesStatus()
}
}
static var delta: [String: Any]? {
guard let currentDict = MobileMessaging.sharedInstance?.currentInstallation().dictionaryRepresentation, let dirtyDict = MobileMessaging.sharedInstance?.dirtyInstallation().dictionaryRepresentation else {
return [:]
}
return deltaDict(currentDict, dirtyDict)
}
/// If you have a users database where every user has a unique identifier, you would leverage our External User Id API to gather and link all users devices where your application is installed. However if you have several different applications that share a common user data base you would need to separate one push message destination from another (applications may be considered as destinations here). In order to do such message destination separation, you would need to provide us with a unique Application User Id.
public var applicationUserId: String?
/// Returns installations custom data. Arbitrary attributes that are related to the current installation. You can provide additional users information to the server, so that you will be able to send personalised targeted messages to exact user and other nice features.
public var customAttributes: [String: MMAttributeType] {
willSet {
newValue.assertCustomAttributesValid()
}
}
/// Primary device setting
/// Single user profile on Infobip Portal can have one or more mobile devices with the application installed. You might want to mark one of such devices as a primary device and send push messages only to this device (i.e. receive bank authorization codes only on one device).
public var isPrimaryDevice: Bool
/// Current push registration status.
/// The status defines whether the device is allowed to be receiving push notifications (regular push messages/geofencing campaign messages/messages fetched from the server).
/// MobileMessaging SDK has the push registration enabled by default.
public var isPushRegistrationEnabled: Bool
/// Unique push registration identifier issued by server. This identifier matches one to one with APNS cloud token of the particular application installation. This identifier is only available after `MMNotificationRegistrationUpdated` event.
public internal(set) var pushRegistrationId: String?
public internal(set) var appVersion: String?
public internal(set) var deviceManufacturer: String?
public internal(set) var deviceModel: String?
public internal(set) var deviceName: String?
public internal(set) var deviceSecure: Bool
public internal(set) var deviceTimeZone: String?
public internal(set) var geoEnabled: Bool
public internal(set) var language: String?
public internal(set) var notificationsEnabled: Bool?
public internal(set) var os: String?
public internal(set) var osVersion: String?
public internal(set) var pushServiceToken: String?
public internal(set) var pushServiceType: String?
public internal(set) var sdkVersion: String?
// more properties needed? ok but look at the code below first.
required public init?(coder aDecoder: NSCoder) {
applicationUserId = aDecoder.decodeObject(forKey: "applicationUserId") as? String
customAttributes = (aDecoder.decodeObject(forKey: "customAttributes") as? [String: MMAttributeType]) ?? [:]
isPrimaryDevice = aDecoder.decodeBool(forKey: "isPrimary")
isPushRegistrationEnabled = aDecoder.decodeBool(forKey: "regEnabled")
pushRegistrationId = aDecoder.decodeObject(forKey: "pushRegId") as? String
appVersion = aDecoder.decodeObject(forKey: "appVersion") as? String
deviceManufacturer = aDecoder.decodeObject(forKey: "deviceManufacturer") as? String
deviceModel = aDecoder.decodeObject(forKey: "deviceModel") as? String
deviceName = aDecoder.decodeObject(forKey: "deviceName") as? String
deviceSecure = aDecoder.decodeBool(forKey: "deviceSecure")
deviceTimeZone = aDecoder.decodeObject(forKey: "deviceTimeZone") as? String
geoEnabled = aDecoder.decodeBool(forKey: "geoEnabled")
language = aDecoder.decodeObject(forKey: "language") as? String
notificationsEnabled = aDecoder.decodeObject(forKey: "notificationsEnabled") as? Bool
os = aDecoder.decodeObject(forKey: "os") as? String
osVersion = aDecoder.decodeObject(forKey: "osVersion") as? String
pushServiceToken = aDecoder.decodeObject(forKey: "pushServiceToken") as? String
pushServiceType = aDecoder.decodeObject(forKey: "pushServiceType") as? String
sdkVersion = aDecoder.decodeObject(forKey: "sdkVersion") as? String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(applicationUserId, forKey: "applicationUserId")
aCoder.encode(customAttributes, forKey: "customAttributes")
aCoder.encode(isPrimaryDevice, forKey: "isPrimary")
aCoder.encode(isPushRegistrationEnabled, forKey: "regEnabled")
aCoder.encode(pushRegistrationId, forKey: "pushRegId")
aCoder.encode(appVersion, forKey: "appVersion")
aCoder.encode(deviceManufacturer, forKey: "deviceManufacturer")
aCoder.encode(deviceModel, forKey: "deviceModel")
aCoder.encode(deviceName, forKey: "deviceName")
aCoder.encode(deviceSecure, forKey: "deviceSecure")
aCoder.encode(deviceTimeZone, forKey: "deviceTimeZone")
aCoder.encode(geoEnabled, forKey: "geoEnabled")
aCoder.encode(language, forKey: "language")
aCoder.encode(nil, forKey: "notificationsEnabled")
aCoder.encode(os, forKey: "os")
aCoder.encode(osVersion, forKey: "osVersion")
aCoder.encode(pushServiceToken, forKey: "pushServiceToken")
aCoder.encode(pushServiceType, forKey: "pushServiceType")
aCoder.encode(sdkVersion, forKey: "sdkVersion")
}
convenience init?(json: JSON) {
guard let pushRegId = json[Attributes.pushRegistrationId.rawValue].string else // a valid server response must contain pushregid
{
return nil
}
self.init(
applicationUserId: json[Attributes.applicationUserId.rawValue].string,
appVersion: json[Consts.SystemDataKeys.appVer].string,
customAttributes: (json[Attributes.customAttributes.rawValue].dictionary ?? [:]).decodeCustomAttributesJSON,
deviceManufacturer: json[Consts.SystemDataKeys.deviceManufacturer].string,
deviceModel: json[Consts.SystemDataKeys.deviceModel].string,
deviceName: json[Consts.SystemDataKeys.deviceName].string,
deviceSecure: json[Consts.SystemDataKeys.deviceSecure].bool ?? false,
deviceTimeZone: json[Consts.SystemDataKeys.deviceTimeZone].string,
geoEnabled: json[Consts.SystemDataKeys.geofencingServiceEnabled].bool ?? false,
isPrimaryDevice: json[Attributes.isPrimaryDevice.rawValue].bool ?? false,
isPushRegistrationEnabled: json[Attributes.registrationEnabled.rawValue].bool ?? true,
language: json[Consts.SystemDataKeys.language].string,
notificationsEnabled: json[Consts.SystemDataKeys.notificationsEnabled].bool ?? true,
os: json[Consts.SystemDataKeys.OS].string,
osVersion: json[Consts.SystemDataKeys.osVer].string,
pushRegistrationId: pushRegId,
pushServiceToken: json[Attributes.pushServiceToken.rawValue].string,
pushServiceType: json[Consts.SystemDataKeys.pushServiceType].string,
sdkVersion: json[Consts.SystemDataKeys.sdkVersion].string
)
}
init(applicationUserId: String?,
appVersion: String?,
customAttributes: [String: MMAttributeType],
deviceManufacturer: String?,
deviceModel: String?,
deviceName: String?,
deviceSecure: Bool,
deviceTimeZone: String?,
geoEnabled: Bool,
isPrimaryDevice: Bool,
isPushRegistrationEnabled: Bool,
language: String?,
notificationsEnabled: Bool?,
os: String?,
osVersion: String?,
pushRegistrationId: String?,
pushServiceToken: String?,
pushServiceType: String?,
sdkVersion: String?)
{
self.applicationUserId = applicationUserId
self.appVersion = appVersion
self.customAttributes = customAttributes
self.deviceManufacturer = deviceManufacturer
self.deviceModel = deviceModel
self.deviceName = deviceName
self.deviceSecure = deviceSecure
self.deviceTimeZone = deviceTimeZone
self.geoEnabled = geoEnabled
self.isPrimaryDevice = isPrimaryDevice
self.isPushRegistrationEnabled = isPushRegistrationEnabled
self.language = language
self.notificationsEnabled = notificationsEnabled
self.os = os
self.osVersion = osVersion
self.pushRegistrationId = pushRegistrationId
self.pushServiceToken = pushServiceToken?.lowercased()
self.pushServiceType = pushServiceType
self.sdkVersion = sdkVersion
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? MMInstallation else {
return false
}
return self.applicationUserId == object.applicationUserId &&
self.appVersion == object.appVersion &&
self.customAttributes == object.customAttributes &&
self.deviceManufacturer == object.deviceManufacturer &&
self.deviceModel == object.deviceModel &&
self.deviceName == object.deviceName &&
self.deviceSecure == object.deviceSecure &&
self.deviceTimeZone == object.deviceTimeZone &&
self.geoEnabled == object.geoEnabled &&
self.isPrimaryDevice == object.isPrimaryDevice &&
self.isPushRegistrationEnabled == object.isPushRegistrationEnabled &&
self.language == object.language &&
self.notificationsEnabled == object.notificationsEnabled &&
self.os == object.os &&
self.osVersion == object.osVersion &&
self.pushRegistrationId == object.pushRegistrationId &&
self.pushServiceToken == object.pushServiceToken &&
self.pushServiceType == object.pushServiceType &&
self.sdkVersion == object.sdkVersion
}
// must be extracted to cordova plugin srcs
public convenience init?(dictRepresentation dict: DictionaryRepresentation) {
self.init(
applicationUserId: dict["applicationUserId"] as? String,
appVersion: dict["appVersion"] as? String,
customAttributes: (dict["customAttributes"] as? [String: MMAttributeType]) ?? [:],
deviceManufacturer: dict["deviceManufacturer"] as? String,
deviceModel: dict["deviceModel"] as? String,
deviceName: dict["deviceName"] as? String,
deviceSecure: dict["deviceSecure"] as? Bool ?? false,
deviceTimeZone: dict["deviceTimezoneOffset"] as? String,
geoEnabled: dict["geoEnabled"] as? Bool ?? false,
isPrimaryDevice: dict["isPrimaryDevice"] as? Bool ?? false,
isPushRegistrationEnabled: dict["isPushRegistrationEnabled"] as? Bool ?? true,
language: dict["language"] as? String,
notificationsEnabled: dict["notificationsEnabled"] as? Bool,
os: dict["os"] as? String,
osVersion: dict["osVersion"] as? String,
pushRegistrationId: dict["pushRegistrationId"] as? String,
pushServiceToken: dict["pushServiceToken"] as? String,
pushServiceType: dict["pushServiceType"] as? String,
sdkVersion: dict["sdkVersion"] as? String
)
}
public var dictionaryRepresentation: DictionaryRepresentation {
var dict = DictionaryRepresentation()
dict["applicationUserId"] = applicationUserId
dict["appVersion"] = appVersion
dict["customAttributes"] = UserDataMapper.makeCustomAttributesPayload(customAttributes)
dict["deviceManufacturer"] = deviceManufacturer
dict["deviceModel"] = deviceModel
dict["deviceName"] = deviceName
dict["deviceSecure"] = deviceSecure
dict["deviceTimezoneOffset"] = deviceTimeZone
dict["geoEnabled"] = geoEnabled
dict["isPrimaryDevice"] = isPrimaryDevice
dict["isPushRegistrationEnabled"] = isPushRegistrationEnabled
dict["language"] = language
dict["notificationsEnabled"] = notificationsEnabled
dict["os"] = os
dict["osVersion"] = osVersion
dict["pushRegistrationId"] = pushRegistrationId
dict["pushServiceToken"] = pushServiceToken
dict["pushServiceType"] = pushServiceType
dict["sdkVersion"] = sdkVersion
return dict
}
public func copy(with zone: NSZone? = nil) -> Any {
let copy = MMInstallation(applicationUserId: applicationUserId, appVersion: appVersion, customAttributes: customAttributes, deviceManufacturer: deviceManufacturer, deviceModel: deviceModel, deviceName: deviceName, deviceSecure: deviceSecure, deviceTimeZone: deviceTimeZone, geoEnabled: geoEnabled, isPrimaryDevice: isPrimaryDevice, isPushRegistrationEnabled: isPushRegistrationEnabled, language: language, notificationsEnabled: notificationsEnabled, os: os, osVersion: osVersion, pushRegistrationId: pushRegistrationId, pushServiceToken: pushServiceToken, pushServiceType: pushServiceType, sdkVersion: sdkVersion)
return copy
}
}
| apache-2.0 | f08a086113fd93bc01e484a0b8255b1a | 50.08427 | 652 | 0.786209 | 4.880837 | false | false | false | false |
KevinYangGit/DYTV | DYZB/DYZB/Classes/Home/ViewModel/RecommendViewModel.swift | 1 | 3700 | //
// RecommendViewModel.swift
// DYZB
//
// Created by boxfishedu on 2016/10/17.
// Copyright © 2016年 杨琦. All rights reserved.
//
import UIKit
class RecommendViewModel : BaseViewModel {
lazy var cycleModels : [CycleModel] = [CycleModel]()
fileprivate lazy var bigDataGroup : AnchorGroup = AnchorGroup()
fileprivate lazy var prettyGroup : AnchorGroup = AnchorGroup()
}
extension RecommendViewModel {
//请求数据
func requestData(finishCallback : @escaping () -> ()) {
//定义参数
let parameters = ["limit" : "4", "offset" : "0", "time" : Date.getCurrentTime()]
//创建Group
let dGroup = DispatchGroup()
//请求推荐数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: ["time" : Date.getCurrentTime()]) { (result) in
//将result转换成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
//根据data该key,获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
//遍历字典,并转成模型对象
self.bigDataGroup.tag_name = "热门"
self.bigDataGroup.icon_name = "home_header_hot"
// 获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict : dict)
self.bigDataGroup.anchors.append(anchor)
}
dGroup.leave()
}
//请求颜值数据
dGroup.enter()
NetworkTools.requestData(.get, URLString: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters) { (result) in
//将result转成字典类型
guard let resultDict = result as? [String : NSObject] else { return }
//获取数组
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
//遍历字典,取出模型
//设置组的属性
self.prettyGroup.tag_name = "颜值"
self.prettyGroup.icon_name = "home_header_phone"
//获取主播数据
for dict in dataArray {
let anchor = AnchorModel(dict: dict)
self.prettyGroup.anchors.append(anchor)
}
dGroup.leave()
}
//请求2-12部分游戏数据
dGroup.enter()
loadAnchorData(isGroupData: true, URLString: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters) {
dGroup.leave()
}
//等所有的数据都得到时,排序
dGroup.notify(queue: DispatchQueue.main) {
self.anchorGroups.insert(self.prettyGroup, at: 0)
self.anchorGroups.insert(self.bigDataGroup, at: 0)
finishCallback()
}
}
//请求无线轮播的数据
func requestCycleData(_ finishCallback : @escaping () -> ()) {
NetworkTools.requestData(.get, URLString: "http://www.douyutv.com/api/v1/slide/6", parameters: ["version" : "2.300"]) { (result) in
guard let resultDict = result as? [String : NSObject] else { return }
guard let dataArray = resultDict["data"] as? [[String : NSObject]] else { return }
for dict in dataArray {
self.cycleModels.append(CycleModel(dict: dict))
}
finishCallback()
}
}
}
| mit | a77d617a6e6fbb6bc33f13e1e95e6826 | 32.153846 | 158 | 0.540023 | 4.769018 | false | false | false | false |
nbkey/DouYuTV | DouYu/DouYu/Classes/Main/Model/AnchorGroup.swift | 1 | 2453 | //
// AnchorGroup.swift
// DouYu
//
// Created by 吉冠坤 on 2017/7/25.
// Copyright © 2017年 吉冠坤. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
var room_list : [[String: NSObject]]? {
//属性监听
didSet {
guard let roomList = room_list else {return}
for dict in roomList {
let anchor = AnchorModel(dict: dict)
anchors.append(anchor)
}
}
}
var small_icon_url : String = ""
var icon_url : String = ""
var tag_name : String = ""
var tag_id : Int = 0
var anchors:[AnchorModel] = [AnchorModel]()
// MARK:-处理颜值特有的属性
var cateInfo : [String: NSObject]? {
//监听
didSet {
guard let level = cateInfo?["level"] as? Int else {return}
guard let name = cateInfo?["cate\(level)_name"] as? String else {return}
guard let url = cateInfo?["icon_url"] as? String else {return}
self.tag_name = name
self.icon_url = url
self.small_icon_url = url
}
}
var list : [[String: NSObject]]? {
//属性监听
didSet {
guard let roomList = list else {return}
self.room_list = roomList
}
}
// MARK:-构造函数
init(dict:[String: NSObject]) {
super.init()
setValuesForKeys(dict)
}
override init() {
super.init()
}
override func setValue(_ value: Any?, forKey key: String) {
super.setValue(value, forKey: key)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
//将我们的roomList内的元素转化成AnchorModel对象
// override func setValue(_ value: Any?, forKey key: String) {
// if key == "room_list" {
// guard let dataArray = value as? [[String: NSObject]] else {return}
// for dict in dataArray {
// let anchor = AnchorModel(dict: dict)
// anchors.append(anchor)
// }
// }
// override func setValue(_ value: Any?, forKey key: String) {
// if key == "small_icon_url" {
// print("走啊啊走\(value)")
// }
// }
}
/*
room_list: [[String: NSObject]] 房间信息
icon_url: String游戏图标
small_icon_url: String 左上角小图标
tag_name: String 游戏名称
tag_id: Int 游戏ID
*/
| mit | 4df3f607a1bf58c3ee618e102a95f120 | 25.044944 | 84 | 0.528473 | 3.825083 | false | false | false | false |
hulinSun/Better | better/better/Classes/Vendors/Source/ConstraintMaker.swift | 6 | 7371 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMaker {
public var left: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.left)
}
public var top: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.top)
}
public var bottom: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottom)
}
public var right: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.right)
}
public var leading: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leading)
}
public var trailing: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailing)
}
public var width: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.width)
}
public var height: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.height)
}
public var centerX: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerX)
}
public var centerY: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerY)
}
@available(*, deprecated:3.0, message:"Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
public var lastBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.firstBaseline)
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leftMargin)
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.rightMargin)
}
@available(iOS 8.0, *)
public var topMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.topMargin)
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottomMargin)
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leadingMargin)
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailingMargin)
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerXWithinMargins)
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerYWithinMargins)
}
public var edges: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.edges)
}
public var size: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.size)
}
public var center: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.center)
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.margins)
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerWithinMargins)
}
private let item: LayoutConstraintItem
private var descriptions = [ConstraintDescription]()
internal init(item: LayoutConstraintItem) {
self.item = item
self.item.prepare()
}
internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable {
let description = ConstraintDescription(item: self.item, attributes: attributes)
self.descriptions.append(description)
return ConstraintMakerExtendable(description)
}
internal static func prepareConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
let maker = ConstraintMaker(item: item)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
return constraints
}
internal static func makeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
let maker = ConstraintMaker(item: item)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: false)
}
}
internal static func remakeConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
self.removeConstraints(item: item)
self.makeConstraints(item: item, closure: closure)
}
internal static func updateConstraints(item: LayoutConstraintItem, closure: (_ make: ConstraintMaker) -> Void) {
guard item.constraints.count > 0 else {
self.makeConstraints(item: item, closure: closure)
return
}
let maker = ConstraintMaker(item: item)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: true)
}
}
internal static func removeConstraints(item: LayoutConstraintItem) {
let constraints = item.constraints
for constraint in constraints {
constraint.deactivateIfNeeded()
}
}
}
| mit | 35142c69b71352734b2809b00c2aa766 | 33.933649 | 133 | 0.681726 | 5.558824 | false | false | false | false |
jpsim/Yams | Sources/Yams/Parser.swift | 1 | 15162 | //
// Parser.swift
// Yams
//
// Created by Norio Nomura on 12/15/16.
// Copyright (c) 2016 Yams. All rights reserved.
//
#if SWIFT_PACKAGE
@_implementationOnly import CYaml
#endif
import Foundation
/// Parse all YAML documents in a String
/// and produce corresponding Swift objects.
///
/// - parameter yaml: String
/// - parameter resolver: Resolver
/// - parameter constructor: Constructor
/// - parameter encoding: Parser.Encoding
///
/// - returns: YamlSequence<Any>
///
/// - throws: YamlError
public func load_all(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default,
_ encoding: Parser.Encoding = .default) throws -> YamlSequence<Any> {
let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor, encoding: encoding)
return YamlSequence { try parser.nextRoot()?.any }
}
/// Parse the first YAML document in a String
/// and produce the corresponding Swift object.
///
/// - parameter yaml: String
/// - parameter resolver: Resolver
/// - parameter constructor: Constructor
/// - parameter encoding: Parser.Encoding
///
/// - returns: Any?
///
/// - throws: YamlError
public func load(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default,
_ encoding: Parser.Encoding = .default) throws -> Any? {
return try Parser(yaml: yaml, resolver: resolver, constructor: constructor, encoding: encoding).singleRoot()?.any
}
/// Parse all YAML documents in a String
/// and produce corresponding representation trees.
///
/// - parameter yaml: String
/// - parameter resolver: Resolver
/// - parameter constructor: Constructor
/// - parameter encoding: Parser.Encoding
///
/// - returns: YamlSequence<Node>
///
/// - throws: YamlError
public func compose_all(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default,
_ encoding: Parser.Encoding = .default) throws -> YamlSequence<Node> {
let parser = try Parser(yaml: yaml, resolver: resolver, constructor: constructor, encoding: encoding)
return YamlSequence(parser.nextRoot)
}
/// Parse the first YAML document in a String
/// and produce the corresponding representation tree.
///
/// - parameter yaml: String
/// - parameter resolver: Resolver
/// - parameter constructor: Constructor
/// - parameter encoding: Parser.Encoding
///
/// - returns: Node?
///
/// - throws: YamlError
public func compose(yaml: String,
_ resolver: Resolver = .default,
_ constructor: Constructor = .default,
_ encoding: Parser.Encoding = .default) throws -> Node? {
return try Parser(yaml: yaml, resolver: resolver, constructor: constructor, encoding: encoding).singleRoot()
}
/// Sequence that holds an error.
public struct YamlSequence<T>: Sequence, IteratorProtocol {
/// This sequence's error, if any.
public private(set) var error: Swift.Error?
/// `Swift.Sequence.next()`.
public mutating func next() -> T? {
do {
return try closure()
} catch {
self.error = error
return nil
}
}
fileprivate init(_ closure: @escaping () throws -> T?) {
self.closure = closure
}
private let closure: () throws -> T?
}
/// Parses YAML strings.
public final class Parser {
/// YAML string.
public let yaml: String
/// Resolver.
public let resolver: Resolver
/// Constructor.
public let constructor: Constructor
/// Encoding
public enum Encoding: String {
/// Use `YAML_UTF8_ENCODING`
case utf8
/// Use `YAML_UTF16(BE|LE)_ENCODING`
case utf16
/// The default encoding, determined at run time based on the String type's native encoding.
/// This can be overridden by setting `YAMS_DEFAULT_ENCODING` to either `UTF8` or `UTF16`.
/// This value is case insensitive.
public static var `default`: Encoding = {
let key = "YAMS_DEFAULT_ENCODING"
if let yamsEncoding = ProcessInfo.processInfo.environment[key],
let encoding = Encoding(rawValue: yamsEncoding.lowercased()) {
print("""
`Parser.Encoding.default` was set to `\(encoding)` by the `\(key)` environment variable.
""")
return encoding
}
return key.utf8.withContiguousStorageIfAvailable({ _ in true }) != nil ? .utf8 : .utf16
}()
/// The equivalent `Swift.Encoding` value for `self`.
internal var swiftStringEncoding: String.Encoding {
switch self {
case .utf8:
return .utf8
case .utf16:
return .utf16
}
}
}
/// Encoding
public let encoding: Encoding
/// Set up a `Parser` with a `String` value as input.
///
/// - parameter string: YAML string.
/// - parameter resolver: Resolver, `.default` if omitted.
/// - parameter constructor: Constructor, `.default` if omitted.
/// - parameter encoding: Encoding, `.default` if omitted.
///
/// - throws: `YamlError`.
public init(yaml string: String,
resolver: Resolver = .default,
constructor: Constructor = .default,
encoding: Encoding = .default) throws {
yaml = string
self.resolver = resolver
self.constructor = constructor
self.encoding = encoding
yaml_parser_initialize(&parser)
switch encoding {
case .utf8:
yaml_parser_set_encoding(&parser, YAML_UTF8_ENCODING)
let utf8View = yaml.utf8
buffer = .utf8View(utf8View)
if try utf8View.withContiguousStorageIfAvailable(startParse(with:)) != nil {
// Attempt to parse with underlying UTF8 String encoding was successful, nothing further to do
} else {
// Fall back to using UTF8 slice
let utf8Slice = string.utf8CString.dropLast()
buffer = .utf8Slice(utf8Slice)
try utf8Slice.withUnsafeBytes(startParse(with:))
}
case .utf16:
// use native endianness
let isLittleEndian = 1 == 1.littleEndian
yaml_parser_set_encoding(&parser, isLittleEndian ? YAML_UTF16LE_ENCODING : YAML_UTF16BE_ENCODING)
let encoding: String.Encoding = isLittleEndian ? .utf16LittleEndian : .utf16BigEndian
let data = yaml.data(using: encoding)!
buffer = .utf16(data)
try data.withUnsafeBytes(startParse(with:))
}
}
/// Set up a `Parser` with a `Data` value as input.
///
/// - parameter string: YAML Data encoded using the `encoding` encoding.
/// - parameter resolver: Resolver, `.default` if omitted.
/// - parameter constructor: Constructor, `.default` if omitted.
/// - parameter encoding: Encoding, `.default` if omitted.
///
/// - throws: `YamlError`.
public convenience init(yaml data: Data,
resolver: Resolver = .default,
constructor: Constructor = .default,
encoding: Encoding = .default) throws {
guard let yamlString = String(data: data, encoding: encoding.swiftStringEncoding) else {
throw YamlError.dataCouldNotBeDecoded(encoding: encoding.swiftStringEncoding)
}
try self.init(
yaml: yamlString,
resolver: resolver,
constructor: constructor,
encoding: encoding
)
}
deinit {
yaml_parser_delete(&parser)
}
/// Parse next document and return root Node.
///
/// - returns: next Node.
///
/// - throws: `YamlError`.
public func nextRoot() throws -> Node? {
guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil }
return try loadDocument()
}
/// Parses the document expecting a single root Node and returns it.
///
/// - returns: Single root Node.
///
/// - throws: `YamlError`.
public func singleRoot() throws -> Node? {
guard !streamEndProduced, try parse().type != YAML_STREAM_END_EVENT else { return nil }
let node = try loadDocument()
let event = try parse()
if event.type != YAML_STREAM_END_EVENT {
throw YamlError.composer(
context: YamlError.Context(text: "expected a single document in the stream",
mark: Mark(line: 1, column: 1)),
problem: "but found another document", event.startMark,
yaml: yaml
)
}
return node
}
// MARK: - Private Members
private var anchors = [String: Node]()
private var parser = yaml_parser_t()
private enum Buffer {
case utf8View(String.UTF8View)
case utf8Slice(ArraySlice<CChar>)
case utf16(Data)
}
private var buffer: Buffer
}
// MARK: Implementation Details
private extension Parser {
var streamEndProduced: Bool {
return parser.stream_end_produced != 0
}
func loadDocument() throws -> Node {
let node = try loadNode(from: parse())
try parse() // Drop YAML_DOCUMENT_END_EVENT
return node
}
func loadNode(from event: Event) throws -> Node {
switch event.type {
case YAML_ALIAS_EVENT:
return try loadAlias(from: event)
case YAML_SCALAR_EVENT:
return try loadScalar(from: event)
case YAML_SEQUENCE_START_EVENT:
return try loadSequence(from: event)
case YAML_MAPPING_START_EVENT:
return try loadMapping(from: event)
default:
fatalError("unreachable")
}
}
func startParse(with buffer: UnsafeRawBufferPointer) throws {
yaml_parser_set_input_string(&parser, buffer.baseAddress?.assumingMemoryBound(to: UInt8.self), buffer.count)
try parse() // Drop YAML_STREAM_START_EVENT
}
func startParse(with buffer: UnsafeBufferPointer<UInt8>) throws {
yaml_parser_set_input_string(&parser, buffer.baseAddress, buffer.count)
try parse() // Drop YAML_STREAM_START_EVENT
}
@discardableResult
func parse() throws -> Event {
let event = Event()
guard yaml_parser_parse(&parser, &event.event) == 1 else {
throw YamlError(from: parser, with: yaml)
}
return event
}
func loadAlias(from event: Event) throws -> Node {
guard let alias = event.aliasAnchor else {
fatalError("unreachable")
}
guard let node = anchors[alias] else {
throw YamlError.composer(context: nil,
problem: "found undefined alias", event.startMark,
yaml: yaml)
}
return node
}
func loadScalar(from event: Event) throws -> Node {
let node = Node.scalar(.init(event.scalarValue, tag(event.scalarTag), event.scalarStyle, event.startMark))
if let anchor = event.scalarAnchor {
anchors[anchor] = node
}
return node
}
func loadSequence(from firstEvent: Event) throws -> Node {
var array = [Node]()
var event = try parse()
while event.type != YAML_SEQUENCE_END_EVENT {
array.append(try loadNode(from: event))
event = try parse()
}
let node = Node.sequence(.init(array, tag(firstEvent.sequenceTag), event.sequenceStyle, firstEvent.startMark))
if let anchor = firstEvent.sequenceAnchor {
anchors[anchor] = node
}
return node
}
func loadMapping(from firstEvent: Event) throws -> Node {
var pairs = [(Node, Node)]()
var event = try parse()
while event.type != YAML_MAPPING_END_EVENT {
let key = try loadNode(from: event)
event = try parse()
let value = try loadNode(from: event)
pairs.append((key, value))
event = try parse()
}
let node = Node.mapping(.init(pairs, tag(firstEvent.mappingTag), event.mappingStyle, firstEvent.startMark))
if let anchor = firstEvent.mappingAnchor {
anchors[anchor] = node
}
return node
}
func tag(_ string: String?) -> Tag {
let tagName = string.map(Tag.Name.init(rawValue:)) ?? .implicit
return Tag(tagName, resolver, constructor)
}
}
/// Representation of `yaml_event_t`
private class Event {
var event = yaml_event_t()
deinit { yaml_event_delete(&event) }
var type: yaml_event_type_t {
return event.type
}
// alias
var aliasAnchor: String? {
return string(from: event.data.alias.anchor)
}
// scalar
var scalarAnchor: String? {
return string(from: event.data.scalar.anchor)
}
var scalarStyle: Node.Scalar.Style {
// swiftlint:disable:next force_unwrapping
return Node.Scalar.Style(rawValue: numericCast(event.data.scalar.style.rawValue))!
}
var scalarTag: String? {
if event.data.scalar.quoted_implicit == 1 {
return Tag.Name.str.rawValue
}
return string(from: event.data.scalar.tag)
}
var scalarValue: String {
// scalar may contain NULL characters
let buffer = UnsafeBufferPointer(start: event.data.scalar.value,
count: event.data.scalar.length)
// libYAML converts scalar characters into UTF8 if input is other than YAML_UTF8_ENCODING
return String(bytes: buffer, encoding: .utf8)!
}
// sequence
var sequenceAnchor: String? {
return string(from: event.data.sequence_start.anchor)
}
var sequenceStyle: Node.Sequence.Style {
// swiftlint:disable:next force_unwrapping
return Node.Sequence.Style(rawValue: numericCast(event.data.sequence_start.style.rawValue))!
}
var sequenceTag: String? {
return event.data.sequence_start.implicit != 0
? nil : string(from: event.data.sequence_start.tag)
}
// mapping
var mappingAnchor: String? {
return string(from: event.data.scalar.anchor)
}
var mappingStyle: Node.Mapping.Style {
// swiftlint:disable:next force_unwrapping
return Node.Mapping.Style(rawValue: numericCast(event.data.mapping_start.style.rawValue))!
}
var mappingTag: String? {
return event.data.mapping_start.implicit != 0
? nil : string(from: event.data.sequence_start.tag)
}
// start_mark
var startMark: Mark {
return Mark(line: event.start_mark.line + 1, column: event.start_mark.column + 1)
}
}
private func string(from pointer: UnsafePointer<UInt8>!) -> String? {
return String.decodeCString(pointer, as: UTF8.self, repairingInvalidCodeUnits: true)?.result
}
| mit | 955bc6312a80f46be5a35068663ed8b4 | 33.537585 | 118 | 0.60058 | 4.492444 | false | false | false | false |
Loveswift/BookReview | BookReview/BookReview/MeViewController.swift | 1 | 2591 | //
// MeViewController.swift
// BookReview
//
// Created by xjc on 16/4/30.
// Copyright © 2016年 xjc. All rights reserved.
//
import UIKit
class MeViewController: UIViewController {
var headerView:HeaderView!
var pageMenu:CAPSPageMenu!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.navigationController?.navigationBarHidden = true
//头视图
self.headerView = HeaderView(frame: CGRectMake(0,0,SCREEN_WIDTH,180))
self.view.addSubview(self.headerView)
var controllerArray:[UIViewController] = []
let bookReviewVC = MyBookReviewController()
bookReviewVC.title = "我的书评"
controllerArray.append(bookReviewVC)
let commentVC = MyCommentController()
commentVC.title = "我的评论"
controllerArray.append(commentVC)
let collectionVC = MyCollectionController()
collectionVC.title = "我的收藏"
controllerArray.append(collectionVC)
let parameters: [CAPSPageMenuOption] = [
.ScrollMenuBackgroundColor(UIColor(red: 87.0/255, green: 113.0/255, blue: 100.0/255, alpha: 1)),
.ViewBackgroundColor(UIColor.grayColor()),
.SelectionIndicatorColor(UIColor.orangeColor()),
.SelectedMenuItemLabelColor(UIColor(red: 0.0/255, green: 175.0/255, blue: 193.0/255, alpha: 1)),
.UnselectedMenuItemLabelColor(UIColor.whiteColor()),
.BottomMenuHairlineColor(UIColor(red: 70.0/255.0, green: 70.0/255.0, blue: 80.0/255.0, alpha: 1.0)),
.UseMenuLikeSegmentedControl(true),
.MenuItemFont(UIFont.boldSystemFontOfSize(16)),
.MenuHeight(30.0),
.MenuItemSeparatorWidth(1), //
.MenuItemSeparatorColor(UIColor.whiteColor()), //
.MenuItemWidth(SCREEN_WIDTH/3),
.CenterMenuItems(true)
]
self.pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 180.0, self.view.frame.width, self.view.frame.height-20), pageMenuOptions: parameters)
//self.addChildViewController(self.pageMenu!) //注释后使其不出现SrcollView
self.view.addSubview(self.pageMenu!.view)
self.pageMenu?.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | ae41e065af26a9a2bd294a24df44f252 | 34.802817 | 180 | 0.636113 | 4.638686 | false | false | false | false |
velvetroom/columbus | Source/View/Create/VCreateStatusReadyBarTravelHeader.swift | 1 | 787 | import UIKit
final class VCreateStatusReadyBarTravelHeader:UICollectionReusableView
{
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
isUserInteractionEnabled = false
let imageView:UIImageView = UIImageView()
imageView.isUserInteractionEnabled = false
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.image = #imageLiteral(resourceName: "assetMapOrigin")
addSubview(imageView)
NSLayoutConstraint.equals(
view:imageView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| mit | 49767a0a939c82b5a7af7149b72d716a | 26.137931 | 71 | 0.651842 | 6.007634 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Pods/SimpleImageViewer/ImageViewer/AnimatableImageView.swift | 1 | 3236 | import UIKit
final class AnimatableImageView: UIView {
fileprivate let imageView = UIImageView()
override var contentMode: UIViewContentMode {
didSet { update() }
}
override var frame: CGRect {
didSet { update() }
}
var image: UIImage? {
didSet {
imageView.image = image
update()
}
}
init() {
super.init(frame: .zero)
clipsToBounds = true
addSubview(imageView)
imageView.contentMode = .scaleToFill
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension AnimatableImageView {
func update() {
guard let image = image else { return }
switch contentMode {
case .scaleToFill:
imageView.bounds = Utilities.rect(forSize: bounds.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFit:
imageView.bounds = Utilities.aspectFitRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .scaleAspectFill:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .redraw:
imageView.bounds = Utilities.aspectFillRect(forSize: image.size, insideRect: bounds)
imageView.center = Utilities.center(forSize: bounds.size)
case .center:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.center(forSize: bounds.size)
case .top:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerTop(forSize: image.size, insideSize: bounds.size)
case .bottom:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerBottom(forSize: image.size, insideSize: bounds.size)
case .left:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerLeft(forSize: image.size, insideSize: bounds.size)
case .right:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.centerRight(forSize: image.size, insideSize: bounds.size)
case .topLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topLeft(forSize: image.size, insideSize: bounds.size)
case .topRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.topRight(forSize: image.size, insideSize: bounds.size)
case .bottomLeft:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomLeft(forSize: image.size, insideSize: bounds.size)
case .bottomRight:
imageView.bounds = Utilities.rect(forSize: image.size)
imageView.center = Utilities.bottomRight(forSize: image.size, insideSize: bounds.size)
}
}
}
| mit | c6306d6cad9d2950945d426f9b637e5c | 39.962025 | 99 | 0.637515 | 4.744868 | false | false | false | false |
zhubofei/IGListKit | Examples/Examples-iOS/IGListKitExamples/Views/EmbeddedCollectionViewCell.swift | 4 | 1308 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import IGListKit
import UIKit
final class EmbeddedCollectionViewCell: UICollectionViewCell {
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
let view = UICollectionView(frame: .zero, collectionViewLayout: layout)
view.backgroundColor = .clear
view.alwaysBounceVertical = false
view.alwaysBounceHorizontal = true
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = contentView.frame
}
}
| mit | da7bb22cc8a8f6f1158d5989cc93018f | 35.333333 | 80 | 0.74159 | 5.317073 | false | false | false | false |
webim/webim-client-sdk-ios | Example/Tests/WebimTests.swift | 1 | 4767 | //
// WebimTests.swift
// WebimClientLibrary_Tests
//
// Created by Nikita Lazarev-Zubov on 15.02.18.
// Copyright © 2018 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import WebimClientLibrary
import XCTest
class WebimTests: XCTestCase {
// MARK: - Constants
private static let WEBIM_REMOTE_NOTIFICATION_JSON_STRING = """
{
"aps" : {
"alert" : {
"loc-key" : "P.OM",
"loc-args" : ["Имя Оператора", "Сообщение"]
},
"sound" : "default",
},
"webim": 1
}
"""
private static let NOT_WEBIM_REMOTE_NOTIFICATION_JSON_STRING = """
{
"aps" : {
"alert" : {
"loc-key" : "P.OM",
"loc-args" : ["Имя Оператора", "Сообщение"]
},
"sound" : "default",
}
}
"""
private static let INCORRECT_REMOTE_NOTIFICATION_JSON_STRING = """
{
"alert" : {
"loc-key" : "P.OM",
"loc-args" : ["Имя Оператора", "Сообщение"]
},
"sound" : "default",
}
"""
private static let REMOTE_NOTIFICATION_WITH_SPECIAL_FIELDS = """
{
"aps": {
"alert": {
"loc-key": "P.OM",
"loc-args": [
"Имя Оператора",
"Сообщение"
]
},
"sound": "default"
},
"webim": 1,
"unread_by_visitor_msg_cnt": 1,
"location": "mobile"
}
"""
// MARK: - Properties
let webimRemoteNotification = try! JSONSerialization.jsonObject(with: WebimTests.WEBIM_REMOTE_NOTIFICATION_JSON_STRING.data(using: .utf8)!,
options: []) as! [AnyHashable : Any]
let notWebimRemoteNotification = try! JSONSerialization.jsonObject(with: WebimTests.NOT_WEBIM_REMOTE_NOTIFICATION_JSON_STRING.data(using: .utf8)!,
options: []) as! [AnyHashable : Any]
let incorrectRemoteNotification = try! JSONSerialization.jsonObject(with: WebimTests.INCORRECT_REMOTE_NOTIFICATION_JSON_STRING.data(using: .utf8)!,
options: []) as! [AnyHashable : Any]
let webimRemoteNotificationWithSpecialFields = try! JSONSerialization.jsonObject(with: WebimTests.REMOTE_NOTIFICATION_WITH_SPECIAL_FIELDS.data(using: .utf8)!,
options: []) as! [AnyHashable : Any]
// MARK: - Tests
func testParseRemoteNotification() {
let webimRemoteNotification = Webim.parse(remoteNotification: self.webimRemoteNotification)!
XCTAssertNil(webimRemoteNotification.getEvent())
XCTAssertEqual(webimRemoteNotification.getParameters(), ["Имя Оператора",
"Сообщение"])
XCTAssertEqual(webimRemoteNotification.getType(),
NotificationType.operatorMessage)
XCTAssertNil(Webim.parse(remoteNotification: self.incorrectRemoteNotification))
}
func testIsWebimRemoteNotification() {
XCTAssertTrue(Webim.isWebim(remoteNotification: webimRemoteNotification))
XCTAssertFalse(Webim.isWebim(remoteNotification: notWebimRemoteNotification))
}
func testRemoteNotificationWithSpecialFields() {
let webimRemoteNotification = Webim.parse(remoteNotification: self.webimRemoteNotificationWithSpecialFields)
XCTAssertEqual(webimRemoteNotification?.getUnreadByVisitorMessagesCount(), 1)
XCTAssertEqual(webimRemoteNotification?.getLocation(), "mobile")
}
}
| mit | a14dbaba40ada2f4e8f879cc0e339358 | 38.168067 | 162 | 0.62626 | 4.624008 | false | true | false | false |
kevinhankens/runalysis | Runalysis/SummaryCell.swift | 1 | 6756 | //
// SummaryCell.swift
// Runalysis
//
// Created by Kevin Hankens on 7/23/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
class SummaryCell: UIView {
// The date this week begins with.
var beginDate: NSDate = NSDate()
// The date this week ends with.
var endDate: NSDate = NSDate()
// The label containing the date.
var dateLabel: UILabel?
// The total planned mileage for the week.
var totalPlanned = 0.0
// The total actual mileage for the week.
var totalActual = 0.0
// The label that contains the planned mileage.
var plannedLabel: UILabel?
// The label that contains the actual mileage.
var actualLabel: UILabel?
// A list of the RockerCell objects for summary.
var cells: [RockerCell]?
/*!
* Factory method to create a SummaryCell.
*
* @param CGFloat cellHeight
* @param CGFloat cellWidth
* @param CGFloat cellY
* @param NSDate beginDate
* @param NSDate endDate
*
* @return SummaryCell
*/
class func createCell(cellHeight: CGFloat, cellWidth:
CGFloat, cellY: CGFloat, beginDate: NSDate, endDate: NSDate)->SummaryCell {
// @todo this needs more dynamic boundaries.
let container = SummaryCell(frame: CGRectMake(0, cellY, cellWidth, cellHeight))
let mpos = container.frame.minY - container.frame.height/4
let planned = UILabel(frame: CGRect(x: 0, y: mpos, width: 50.00, height: container.bounds.height))
planned.textColor = UIColor.whiteColor()
planned.textAlignment = NSTextAlignment.Center
container.plannedLabel = planned
container.addSubview(planned)
let actual = UILabel(frame: CGRect(x: cellWidth - 50, y: mpos, width: 50.00, height: container.bounds.height))
actual.textColor = UIColor.whiteColor()
actual.textAlignment = NSTextAlignment.Center
container.actualLabel = actual
container.addSubview(actual)
let headerDate = UILabel(frame: CGRect(x: 0, y: 0, width: container.bounds.width, height: 50.0))
headerDate.textAlignment = NSTextAlignment.Center
headerDate.textColor = UIColor.whiteColor()
container.dateLabel = headerDate
container.updateDate(beginDate, endDate: endDate)
container.addSubview(headerDate)
return container
}
/*!
* Updates the values according to the latest list of RockerCell objects.
*
* @return void
*/
func updateValues() {
// @todo this should mark setNeedsDisplay().
self.totalPlanned = 0.0
self.totalActual = 0.0
let mileageCells = self.cells!
for cell in mileageCells {
var l = cell.leftControl! as RockerStepper
var r = cell.rightControl! as RockerStepper
self.totalPlanned += l.value
self.totalActual += r.value
}
let p = self.plannedLabel! as UILabel
let a = self.actualLabel! as UILabel
p.text = "\(RockerStepper.getLabel(Double(self.totalPlanned)))"
a.text = "\(RockerStepper.getLabel(Double(self.totalActual)))"
}
/*!
* Overrides drawRect.
*
* Creates the mileage graph for the week.
*
* @param CGRect rect
*
* @return void
*/
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, GlobalTheme.getBackgroundColor().CGColor);
CGContextFillRect(context, self.bounds)
// The max mileage.
var vmax = 0.0
// The vertical scale.
var vscale:CGFloat = 0
// The vertical boundary.
let vbounds = CGFloat(40.0)
// Tracks the mileage for each day of the week.
var mileage = [[0.0,0.0,0.0,0.0,0.0,0.0,0.0],[0.0,0.0,0.0,0.0,0.0,0.0,0.0]]
let mileageCells = self.cells!
// Locate the maximum value to determine graph scale.
var i = 0
for cell in mileageCells {
var l = cell.leftControl! as RockerStepper
var r = cell.rightControl! as RockerStepper
mileage[0][i] = l.value
mileage[1][i] = r.value
if l.value > vmax && l.value > r.value {
vmax = l.value
}
else if r.value > vmax {
vmax = r.value
}
i++
}
// Determine the vertical scale for each point.
vscale = CGFloat(self.frame.height - vbounds)/CGFloat(vmax)
// Clear the context to start over.
CGContextFillRect(context, self.bounds)
CGContextSetLineWidth(context, 2.0)
var start = true
let increment = (self.frame.width - 100) / 6
// Iterate over planned/actual and chart the mileage.
var type = 0
for color in [GlobalTheme.getPlannedColor(), GlobalTheme.getActualColor()] {
CGContextSetStrokeColorWithColor(context, color.CGColor)
var xval = CGFloat(50.0)
var yval = CGFloat(0.0)
for i in 0...6 {
yval = CGFloat(mileage[type][i]) * vscale
if (isnan(yval)) {
yval = CGFloat(0.0)
}
yval = yval == CGFloat(0.0) ? CGFloat(1.0) : yval
if start {
CGContextMoveToPoint(context, xval, self.frame.height - yval)
start = false
}
else {
CGContextAddLineToPoint(context, xval, self.frame.height - yval)
}
xval += increment
}
start = true
CGContextStrokePath(context)
type++
}
}
/*!
* Updates the header to contain a new begin and end date.
*
* This also updates the label accordingly.
*
* @param NSDate beginDate
* @param NSDate endDate
*
* @return void
*/
func updateDate(beginDate: NSDate, endDate: NSDate) {
self.beginDate = beginDate
self.endDate = endDate
self.updateLabel()
}
/*!
* Updates the label containing the dates.
*
* @return void
*/
func updateLabel() {
let v = self.dateLabel!
let format = NSDateFormatter()
format.dateFormat = "MMM d"
v.text = "< \(format.stringFromDate(self.beginDate)) - \(format.stringFromDate(self.endDate)) >"
}
}
| mit | 4815cef3237dcf1c07c96028079fc32e | 30.133641 | 118 | 0.566311 | 4.546433 | false | false | false | false |
adrfer/swift | stdlib/public/core/AssertCommon.swift | 1 | 7109 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
// Implementation Note: this file intentionally uses very LOW-LEVEL
// CONSTRUCTS, so that assert and fatal may be used liberally in
// building library abstractions without fear of infinite recursion.
//
// FIXME: We could go farther with this simplification, e.g. avoiding
// UnsafeMutablePointer
@_transparent
@warn_unused_result
public // @testable
func _isDebugAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 0
}
@_transparent
@warn_unused_result
internal func _isReleaseAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 1
}
@_transparent
@warn_unused_result
public // @testable
func _isFastAssertConfiguration() -> Bool {
// The values for the assert_configuration call are:
// 0: Debug
// 1: Release
// 2: Fast
return Int32(Builtin.assert_configuration()) == 2
}
@_transparent
@warn_unused_result
public // @testable
func _isStdlibInternalChecksEnabled() -> Bool {
#if INTERNAL_CHECKS_ENABLED
return true
#else
return false
#endif
}
@_silgen_name("_swift_stdlib_reportFatalErrorInFile")
func _reportFatalErrorInFile(
prefix: UnsafePointer<UInt8>, _ prefixLength: UInt,
_ message: UnsafePointer<UInt8>, _ messageLength: UInt,
_ file: UnsafePointer<UInt8>, _ fileLength: UInt,
_ line: UInt)
@_silgen_name("_swift_stdlib_reportFatalError")
func _reportFatalError(
prefix: UnsafePointer<UInt8>, _ prefixLength: UInt,
_ message: UnsafePointer<UInt8>, _ messageLength: UInt)
@_silgen_name("_swift_stdlib_reportUnimplementedInitializerInFile")
func _reportUnimplementedInitializerInFile(
className: UnsafePointer<UInt8>, _ classNameLength: UInt,
_ initName: UnsafePointer<UInt8>, _ initNameLength: UInt,
_ file: UnsafePointer<UInt8>, _ fileLength: UInt,
_ line: UInt, _ column: UInt)
@_silgen_name("_swift_stdlib_reportUnimplementedInitializer")
func _reportUnimplementedInitializer(
className: UnsafePointer<UInt8>, _ classNameLength: UInt,
_ initName: UnsafePointer<UInt8>, _ initNameLength: UInt)
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
func _assertionFailed(
prefix: StaticString, _ message: StaticString,
_ file: StaticString, _ line: UInt
) {
prefix.withUTF8Buffer {
(prefix) -> Void in
message.withUTF8Buffer {
(message) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_reportFatalErrorInFile(
prefix.baseAddress, UInt(prefix.count),
message.baseAddress, UInt(message.count),
file.baseAddress, UInt(file.count), line)
Builtin.int_trap()
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of user-level
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
func _assertionFailed(
prefix: StaticString, _ message: String,
_ file: StaticString, _ line: UInt
) {
prefix.withUTF8Buffer {
(prefix) -> Void in
let messageUTF8 = message.nulTerminatedUTF8
messageUTF8.withUnsafeBufferPointer {
(messageUTF8) -> Void in
file.withUTF8Buffer {
(file) -> Void in
_reportFatalErrorInFile(
prefix.baseAddress, UInt(prefix.count),
messageUTF8.baseAddress, UInt(messageUTF8.count),
file.baseAddress, UInt(file.count), line)
}
}
}
Builtin.int_trap()
}
/// This function should be used only in the implementation of stdlib
/// assertions.
///
/// This function should not be inlined because it is cold and it inlining just
/// bloats code.
@noreturn @inline(never)
@_semantics("stdlib_binary_only")
@_semantics("arc.programtermination_point")
func _fatalErrorMessage(prefix: StaticString, _ message: StaticString,
_ file: StaticString, _ line: UInt) {
#if INTERNAL_CHECKS_ENABLED
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
file.withUTF8Buffer {
(file) in
_reportFatalErrorInFile(
prefix.baseAddress, UInt(prefix.count),
message.baseAddress, UInt(message.count),
file.baseAddress, UInt(file.count), line)
}
}
}
#else
prefix.withUTF8Buffer {
(prefix) in
message.withUTF8Buffer {
(message) in
_reportFatalError(
prefix.baseAddress, UInt(prefix.count),
message.baseAddress, UInt(message.count))
}
}
#endif
Builtin.int_trap()
}
/// Prints a fatal error message when an unimplemented initializer gets
/// called by the Objective-C runtime.
@_transparent @noreturn
public // COMPILER_INTRINSIC
func _unimplemented_initializer(className: StaticString,
initName: StaticString = __FUNCTION__,
file: StaticString = __FILE__,
line: UInt = __LINE__,
column: UInt = __COLUMN__) {
// This function is marked @_transparent so that it is inlined into the caller
// (the initializer stub), and, depending on the build configuration,
// redundant parameter values (__FILE__ etc.) are eliminated, and don't leak
// information about the user's source.
if _isDebugAssertConfiguration() {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
file.withUTF8Buffer {
(file) in
_reportUnimplementedInitializerInFile(
className.baseAddress, UInt(className.count),
initName.baseAddress, UInt(initName.count),
file.baseAddress, UInt(file.count), line, column)
}
}
}
} else {
className.withUTF8Buffer {
(className) in
initName.withUTF8Buffer {
(initName) in
_reportUnimplementedInitializer(
className.baseAddress, UInt(className.count),
initName.baseAddress, UInt(initName.count))
}
}
}
Builtin.int_trap()
}
@noreturn
public // COMPILER_INTRINSIC
func _undefined<T>(
@autoclosure message: () -> String = String(),
file: StaticString = __FILE__, line: UInt = __LINE__
) -> T {
_assertionFailed("fatal error", message(), file, line)
}
| apache-2.0 | 87f9f74fa1e83c5507b6398af22ecb61 | 29.51073 | 80 | 0.659586 | 4.3427 | false | false | false | false |
ephread/Instructions | Examples/Example/Sources/Core/View Controllers/Basic Examples/OnlyHintsViewController.swift | 1 | 3181 | // Copyright (c) 2015-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
import Instructions
// That's the default controller, using every defaults made available by Instructions.
// It can't get any simpler.
internal class OnlyHintViewController: ProfileViewController {
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.coachMarksController.dataSource = self
self.emailLabel?.layer.cornerRadius = 4.0
self.postsLabel?.layer.cornerRadius = 4.0
self.reputationLabel?.layer.cornerRadius = 4.0
let skipView = CoachMarkSkipDefaultView()
skipView.setTitle("Skip", for: .normal)
self.coachMarksController.skipView = skipView
}
override func startInstructions() {
coachMarksController.start(in: .window(over: self))
}
}
// MARK: - Protocol Conformance | CoachMarksControllerDataSource
extension OnlyHintViewController: CoachMarksControllerDataSource {
func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int {
return 5
}
func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkAt index: Int) -> CoachMark {
switch index {
case 0:
return coachMarksController.helper.makeCoachMark(
for: self.navigationController?.navigationBar,
cutoutPathMaker: { (frame: CGRect) -> UIBezierPath in
// This will make a cutoutPath matching the shape of
// the component (no padding, no rounded corners).
return UIBezierPath(rect: frame)
}
)
case 1:
return coachMarksController.helper.makeCoachMark(for: self.handleLabel)
case 2:
return coachMarksController.helper.makeCoachMark(for: self.emailLabel)
case 3:
return coachMarksController.helper.makeCoachMark(for: self.postsLabel)
case 4:
return coachMarksController.helper.makeCoachMark(for: self.reputationLabel)
default:
return coachMarksController.helper.makeCoachMark()
}
}
func coachMarksController(
_ coachMarksController: CoachMarksController,
coachMarkViewsAt index: Int,
madeFrom coachMark: CoachMark
) -> (bodyView: (UIView & CoachMarkBodyView), arrowView: (UIView & CoachMarkArrowView)?) {
var hintText = ""
switch index {
case 0:
hintText = self.profileSectionText
case 1:
hintText = self.handleText
case 2:
hintText = self.emailText
case 3:
hintText = self.postsText
case 4:
hintText = self.reputationText
default: break
}
let coachViews = coachMarksController.helper.makeDefaultCoachViews(
withArrow: true,
arrowOrientation: coachMark.arrowOrientation,
hintText: hintText,
nextText: nil
)
return (bodyView: coachViews.bodyView, arrowView: coachViews.arrowView)
}
}
| mit | 88af16f106654880f545d47180db877d | 33.554348 | 114 | 0.647059 | 5.490501 | false | false | false | false |
Workpop/meteor-ios | Examples/Todos/Todos/PlaceholderView.swift | 1 | 5026 | // Copyright (c) 2014-2015 Martijn Walraven
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class PlaceholderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
convenience override init() {
self.init(frame: CGRectZero)
}
required init(coder: NSCoder) {
super.init(coder: coder)
}
override func awakeFromNib() {
super.awakeFromNib()
setUp()
}
private var loadingIndicatorView: UIActivityIndicatorView!
private var contentView: UIView!
private var titleLabel: UILabel!
private var messageLabel: UILabel!
func setUp() {
let textColor = UIColor(white: 172/255.0, alpha:1)
loadingIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge)
loadingIndicatorView.setTranslatesAutoresizingMaskIntoConstraints(false)
loadingIndicatorView.color = UIColor.lightGrayColor()
addSubview(loadingIndicatorView)
contentView = UIView(frame: CGRectZero)
contentView.setTranslatesAutoresizingMaskIntoConstraints(false)
addSubview(contentView)
titleLabel = UILabel(frame: CGRectZero)
titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
titleLabel.textAlignment = .Center
titleLabel.backgroundColor = nil
titleLabel.opaque = false
titleLabel.font = UIFont.systemFontOfSize(22)
titleLabel.numberOfLines = 0_
titleLabel.textColor = textColor
contentView.addSubview(titleLabel)
messageLabel = UILabel(frame: CGRectZero)
messageLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
messageLabel.textAlignment = .Center
messageLabel.backgroundColor = nil
messageLabel.opaque = false
messageLabel.font = UIFont.systemFontOfSize(14)
messageLabel.numberOfLines = 0_
messageLabel.textColor = textColor
contentView.addSubview(messageLabel)
addConstraint(NSLayoutConstraint(item: loadingIndicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: loadingIndicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: contentView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0))
addConstraint(NSLayoutConstraint(item: contentView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0))
let views = ["contentView": contentView, "titleLabel": titleLabel, "messageLabel": messageLabel]
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-(>=30)-[contentView(<=418)]-(>=30)-|", options: nil, metrics: nil, views: views))
} else {
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-30-[contentView]-30-|", options: nil, metrics: nil, views: views))
}
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[titleLabel]|", options: nil, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[messageLabel]|", options: nil, metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[titleLabel]-15-[messageLabel]|", options: nil, metrics: nil, views: views))
}
private var title: String? {
didSet {
titleLabel.text = title
}
}
private var message: String? {
didSet {
messageLabel.text = message
}
}
func showLoadingIndicator() {
contentView.hidden = true
loadingIndicatorView.startAnimating()
}
func hideLoadingIndicator() {
contentView.hidden = false
loadingIndicatorView.stopAnimating()
}
func showTitle(title: String?, message: String?) {
hideLoadingIndicator()
self.title = title
self.message = message
}
}
| mit | 13deec4f71ea99910b7937e01cd2d455 | 39.208 | 172 | 0.736371 | 5.005976 | false | false | false | false |
changjiashuai/AudioKit | Tests/Tests/AKInterpolatedRandomNumberPulse.swift | 14 | 932 | //
// main.swift
// AudioKit
//
// Created by Nick Arner and Aurelius Prochazka on 12/21/14.
// Copyright (c) 2014 Aurelius Prochazka. All rights reserved.
//
import Foundation
let testDuration: NSTimeInterval = 10.0
class Instrument : AKInstrument {
override init() {
super.init()
let interpolatedRandomNumberPulse = AKInterpolatedRandomNumberPulse()
interpolatedRandomNumberPulse.frequency = 3.ak
let oscillator = AKOscillator()
oscillator.frequency = interpolatedRandomNumberPulse.scaledBy(4000.ak)
enableParameterLog(
"Frequency = ",
parameter: oscillator.frequency,
timeInterval:0.1
)
setAudioOutput(oscillator)
}
}
AKOrchestra.testForDuration(testDuration)
let instrument = Instrument()
AKOrchestra.addInstrument(instrument)
instrument.play()
NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
| mit | b8ab36a454f5b905eae0dc865a87974a | 22.3 | 78 | 0.701717 | 4.879581 | false | true | false | false |
Alberto-Vega/SwiftCodeChallenges | BinaryTrees.playground/Sources/Queue.swift | 1 | 926 | import Foundation
public struct Queue<T> {
fileprivate var array = [T?]()
fileprivate var head = 0
public init() {
}
public var isEmpty: Bool {
return count == 0
}
public var count: Int {
return array.count - head
}
public mutating func enqueue(_ element: T) {
array.append(element)
}
public mutating func dequeue() -> T? {
guard head < array.count, let element = array[head] else { return nil }
array[head] = nil
head += 1
let percentage = Double(head)/Double(array.count)
if array.count > 50 && percentage > 0.25 {
array.removeFirst(head)
head = 0
}
return element
}
public func peek() -> T? {
if isEmpty {
return nil
} else {
return array[head]
}
}
}
| mit | 14e071603352ad13c43f40416f4a7180 | 20.045455 | 79 | 0.489201 | 4.584158 | false | false | false | false |
inamiy/RxProperty | Sources/RxProperty/RxProperty.swift | 1 | 2804 | //
// Property.swift
// RxProperty
//
// Created by Yasuhiro Inami on 2017-03-11.
// Copyright © 2017 Yasuhiro Inami. All rights reserved.
//
import RxSwift
import RxRelay
/// A get-only `BehaviorRelay` that works similar to ReactiveSwift's `Property`.
///
/// - Note:
/// From ver 0.3.0, this class will no longer send `.completed` when deallocated.
///
/// - SeeAlso:
/// https://github.com/ReactiveCocoa/ReactiveSwift/blob/1.1.0/Sources/Property.swift
/// https://github.com/ReactiveX/RxSwift/pull/1118 (unmerged)
public final class Property<Element> {
public typealias E = Element
private let _behaviorRelay: BehaviorRelay<E>
/// Gets current value.
public var value: E {
get {
return _behaviorRelay.value
}
}
/// Initializes with initial value.
public init(_ value: E) {
_behaviorRelay = BehaviorRelay(value: value)
}
/// Initializes with `BehaviorRelay`.
public init(_ behaviorRelay: BehaviorRelay<E>) {
_behaviorRelay = behaviorRelay
}
/// Initializes with `Observable` that must send at least one value synchronously.
///
/// - Warning:
/// If `unsafeObservable` fails sending at least one value synchronously,
/// a fatal error would be raised.
///
/// - Warning:
/// If `unsafeObservable` sends multiple values synchronously,
/// the last value will be treated as initial value of `Property`.
public convenience init(unsafeObservable: Observable<E>) {
let observable = unsafeObservable.share(replay: 1, scope: .whileConnected)
var initial: E? = nil
let initialDisposable = observable
.subscribe(onNext: { initial = $0 })
guard let initial_ = initial else {
fatalError("An unsafeObservable promised to send at least one value. Received none.")
}
self.init(initial: initial_, then: observable)
initialDisposable.dispose()
}
/// Initializes with `initial` element and then `observable`.
public init(initial: E, then observable: Observable<E>) {
_behaviorRelay = BehaviorRelay(value: initial)
_ = observable
.bind(to: _behaviorRelay)
// .disposed(by: disposeBag) // Comment-Out: Don't dispose when `property` is deallocated
}
/// Observable that synchronously sends current element and then changed elements.
/// This is same as `ReactiveSwift.Property<T>.producer`.
public func asObservable() -> Observable<E> {
return _behaviorRelay.asObservable()
}
/// Observable that only sends changed elements, ignoring current element.
/// This is same as `ReactiveSwift.Property<T>.signal`.
public var changed: Observable<E> {
return asObservable().skip(1)
}
}
| mit | 2fccae3bbc53d48bc9ac45b44e48d52a | 30.494382 | 104 | 0.650375 | 4.506431 | false | false | false | false |
danielgindi/Charts | Source/Charts/Renderers/Scatter/TriangleShapeRenderer.swift | 2 | 2559 | //
// TriangleShapeRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
open class TriangleShapeRenderer : NSObject, ShapeRenderer
{
open func renderShape(
context: CGContext,
dataSet: ScatterChartDataSetProtocol,
viewPortHandler: ViewPortHandler,
point: CGPoint,
color: NSUIColor)
{
let shapeSize = dataSet.scatterShapeSize
let shapeHalf = shapeSize / 2.0
let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius
let shapeHoleSize = shapeHoleSizeHalf * 2.0
let shapeHoleColor = dataSet.scatterShapeHoleColor
let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0
context.setFillColor(color.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf))
context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf))
if shapeHoleSize > 0.0
{
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf))
context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
}
context.closePath()
context.fillPath()
if shapeHoleSize > 0.0 && shapeHoleColor != nil
{
context.setFillColor(shapeHoleColor!.cgColor)
// create a triangle path
context.beginPath()
context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize))
context.closePath()
context.fillPath()
}
}
}
| apache-2.0 | ad7012d24c47d69e52b25cb9ee42c1a4 | 37.772727 | 124 | 0.622509 | 4.644283 | false | false | false | false |
WeirdMath/TimetableSDK | Sources/Science.swift | 1 | 5662 | //
// Science.swift
// TimetableSDK
//
// Created by Sergej Jaskiewicz on 04.12.2016.
//
//
import Foundation
import SwiftyJSON
/// The information about various scientific events taking place in the Univeristy.
public final class Science : JSONRepresentable, TimetableEntity {
/// The Timetable this entity was fetched from. `nil` if it was initialized from a custom JSON object.
public weak var timetable: Timetable? {
didSet {
eventGroupings.forEach { $0.timetable = timetable }
}
}
internal static let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = .posix
return dateFormatter
}()
public let alias: String
public let chosenMonthDisplayText: String
public let eventGroupings: [EventGrouping]
public let hasEventsToShow: Bool
public let isCurrentMonthReferenceAvailable: Bool
public let nextMonth: Date
public let nextMonthDisplayText: String
public let previousMonth: Date
public let previousMonthDisplayText: String
public let showGroupingCaptions: Bool
public let title: String
public let viewName: String
internal init(alias: String,
chosenMonthDisplayText: String,
eventGroupings: [EventGrouping],
hasEventsToShow: Bool,
isCurrentMonthReferenceAvailable: Bool,
nextMonth: Date,
nextMonthDisplayText: String,
previousMonth: Date,
previousMonthDisplayText: String,
showGroupingCaptions: Bool,
title: String,
viewName: String) {
self.alias = alias
self.chosenMonthDisplayText = chosenMonthDisplayText
self.eventGroupings = eventGroupings
self.hasEventsToShow = hasEventsToShow
self.isCurrentMonthReferenceAvailable = isCurrentMonthReferenceAvailable
self.nextMonth = nextMonth
self.nextMonthDisplayText = nextMonthDisplayText
self.previousMonth = previousMonth
self.previousMonthDisplayText = previousMonthDisplayText
self.showGroupingCaptions = showGroupingCaptions
self.title = title
self.viewName = viewName
}
/// Creates a new entity from its JSON representation.
///
/// - Parameter json: The JSON representation of the entity.
/// - Throws: `TimetableError.incorrectJSONFormat`
public init(from json: JSON) throws {
do {
alias = try map(json["Alias"])
chosenMonthDisplayText = try map(json["ChosenMonthDisplayText"])
eventGroupings = try map(json["EventGroupings"])
hasEventsToShow = try map(json["HasEventsToShow"])
isCurrentMonthReferenceAvailable = try map(json["IsCurrentMonthReferenceAvailable"])
nextMonth = try map(json["NextMonthDate"],
transformation: Science.dateFormatter.date(from:))
nextMonthDisplayText = try map(json["NextMonthDisplayText"])
previousMonth = try map(json["PreviousMonthDate"],
transformation: Science.dateFormatter.date(from:))
previousMonthDisplayText = try map(json["PreviousMonthDisplayText"])
showGroupingCaptions = try map(json["ShowGroupingCaptions"])
title = try map(json["Title"])
viewName = try map(json["ViewName"])
} catch {
throw TimetableError.incorrectJSON(json, whenConverting: Science.self)
}
}
}
extension Science : Equatable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
public static func ==(lhs: Science, rhs: Science) -> Bool {
return
lhs.alias == rhs.alias &&
lhs.chosenMonthDisplayText == rhs.chosenMonthDisplayText &&
lhs.eventGroupings == rhs.eventGroupings &&
lhs.hasEventsToShow == rhs.hasEventsToShow &&
lhs.isCurrentMonthReferenceAvailable == rhs.isCurrentMonthReferenceAvailable &&
lhs.nextMonth == rhs.nextMonth &&
lhs.nextMonthDisplayText == rhs.nextMonthDisplayText &&
lhs.previousMonth == rhs.previousMonth &&
lhs.previousMonthDisplayText == rhs.previousMonthDisplayText &&
lhs.showGroupingCaptions == rhs.showGroupingCaptions &&
lhs.title == rhs.title &&
lhs.viewName == rhs.viewName
}
}
| mit | dadedac33a6e6d1e6b6e9e0274c547e4 | 46.579832 | 106 | 0.542388 | 6.174482 | false | false | false | false |
kevin00223/iOS-demo | PromiseKitDemo/PromiseKitDemo/ViewController.swift | 1 | 3036 | //
// ViewController.swift
// PromiseKitDemo
//
// Created by 李凯 on 2019/5/7.
// Copyright © 2019 LK. All rights reserved.
//
import UIKit
import PromiseKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
_ = cook()
.then{ data -> Promise<String> in
return self.eat(data: data)
}.then{ data -> Promise<String> in
return self.wash(data: data)
}.done{ data in
print(data)
}.catch{ error in
print(error.localizedDescription + "没法吃!")
}.finally {
print("出门上班")
}
//开始监听通知
beginObserve()
}
// MARK: Notification
func beginObserve() {
NotificationCenter.default.observe(once: UIApplication.didEnterBackgroundNotification).done { notification in
print("程序进入后台")
//通知相应后 PromiseKit会自动将通知取消 因此想继续监听 需要再次调用
self.beginObserve()
}
}
// MARK: Async
func cook() -> Promise<String> {
print("开始做饭")
let promise = Promise<String> { resolver in
//延迟操作
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
print("做饭完毕")
//fulfil为满足/完成状态, 进入then函数
resolver.fulfill("鸡蛋炒饭")
})
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
// print("做饭失败")
// let error = NSError(domain: "PromiseKitDemo", code: 0, userInfo: [NSLocalizedDescriptionKey : "烧焦的米饭"])
// //reject为拒绝状态, 进入catch函数
// resolver.reject(error)
// })
}
return promise
}
func eat(data: String) -> Promise<String> {
print("开始吃饭:" + data)
let promise = Promise<String> { resolver in
//延迟操作
after(seconds: 1).done{
print("吃饭完毕")
resolver.fulfill("一双筷子一个碗")
}
// DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
// print("吃饭完毕")
// resolver.fulfill("一双筷子一个碗")
// })
}
return promise
}
func wash(data: String) -> Promise<String> {
print("开始洗碗:" + data)
let promise = Promise<String> { resolver in
//延迟操作
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
print("洗碗完毕")
resolver.fulfill("干净的碗筷")
})
}
return promise
}
}
| mit | 60c194e6dff538cf7483e16832eced2e | 28.021053 | 121 | 0.507073 | 4.25463 | false | false | false | false |
kyouko-taiga/anzen | Sources/Sema/Dispatcher.swift | 1 | 8315 | import AST
import Utils
/// A visitor that annotates expressions with their reified type (as inferred by the type solver),
/// and associates identifiers with their corresponding symbol.
///
/// The main purpose of this pass is to resolve identifiers' symbols, so as to know which variable,
/// function or type they refer to. The choice is based on the identifier's inferred type, which is
/// why this pass also reifies all types.
///
/// Dispatching may fail if the pass is unable to unambiguously resolve an identifier's symbol,
/// which may happen in the presence of function declarations whose normalized (and specialized)
/// signature are found identical.
public final class Dispatcher: ASTTransformer {
/// The AST context.
public let context: ASTContext
/// The substitution map obtained after inference.
public let solution: SubstitutionTable
/// The nominal types already reified.
private var visited: [NominalType] = []
public init(context: ASTContext) {
self.context = context
self.solution = [:]
}
public init(context: ASTContext, solution: SubstitutionTable) {
self.context = context
self.solution = solution
}
public func transform(_ node: ModuleDecl) throws -> Node {
visitScopeDelimiter(node)
return try defaultTransform(node)
}
public func transform(_ node: Block) throws -> Node {
visitScopeDelimiter(node)
return try defaultTransform(node)
}
public func transform(_ node: FunDecl) throws -> Node {
visitScopeDelimiter(node)
return try defaultTransform(node)
}
public func transform(_ node: TypeIdent) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: IfExpr) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: LambdaExpr) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: BinExpr) throws -> Node {
node.type = reify(type: node.type)
let lhs = try transform(node.left) as! Expr
let rhs = try transform(node.right) as! Expr
// Optimization opportunity:
// Rather than transforming all overloadable operators into function calls, we could keep
// built-in operators as binary expressions and emit decicated AIR instructions, just like it's
// done for reference identity checks.
if (node.op == .refeq) || (node.op == .refne) {
// As reference identity operators cannot be overloaded, there is no need to look for the
// symbol to which the operator corresponds.
node.left = lhs
node.right = rhs
return node
} else {
// Transform the binary expression into a function application of the form `lhs.op(rhs)`.
let opIdent = Ident(name: node.op.rawValue, module: node.module, range: node.range)
opIdent.scope = (lhs.type as! NominalType).memberScope
opIdent.type = reify(type: node.operatorType)
let callee = SelectExpr(
owner: lhs,
ownee: try transform(opIdent) as! Ident,
module: node.module,
range: node.range)
callee.type = opIdent.type
let arg = CallArg(value: rhs, module: node.module, range: node.range)
arg.type = rhs.type
let call = CallExpr(callee: callee, arguments: [arg], module: node.module, range: node.range)
call.type = node.type
return call
}
}
public func transform(_ node: UnExpr) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: CallExpr) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: CallArg) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: SubscriptExpr) throws -> Node {
node.type = reify(type: node.type)
return try defaultTransform(node)
}
public func transform(_ node: SelectExpr) throws -> Node {
node.type = reify(type: node.type)
node.owner = try node.owner.map { try transform($0) as! Expr }
let ownerTy = node.owner != nil
? node.owner!.type!
: node.type!
// Once the owner's type's been inferred, we can determine the scope of the ownee. We can
// expect the owner to be either a nominal type or the metatype of a nominal type, as other
// types don't have members.
switch ownerTy {
case let nominal as NominalType:
node.ownee.scope = nominal.memberScope
case let bound as BoundGenericType:
node.ownee.scope = (bound.unboundType as! NominalType).memberScope
case let meta as Metatype where meta.type is NominalType:
node.ownee.scope = (meta.type as! NominalType).memberScope!.parent
case let meta as Metatype where meta.type is BoundGenericType:
let unbound = (meta.type as! BoundGenericType).unboundType
node.ownee.scope = (unbound as! NominalType).memberScope!.parent
default:
unreachable()
}
// Dispatch the symbol of the ownee, now that its scope's been determined.
node.ownee = try transform(node.ownee) as! Ident
return node
}
public func transform(_ node: Ident) throws -> Node {
node.type = node.type.map { solution.reify(type: $0, in: context, skipping: &visited) }
node.specializations = try Dictionary(
uniqueKeysWithValues: node.specializations.map({
try ($0, transform($1) as! QualTypeSign)
}))
assert(node.scope != nil)
assert(node.scope!.symbols[node.name] != nil)
var choices = node.scope!.symbols[node.name]!
assert(!choices.isEmpty)
if node.type is FunctionType {
// There are various situations to consider if the identifier has a function type.
// * The identifier might refer to a functional property, in which case the only solution
// is to dispatch to that property's symbol.
// * The identifier might refer to a function constructor, in which case we may dispatch to
// any constructor symbol in the member scope of the type it refers to.
// * The identifier might refer directly to a function declaration, in which case we may
// dispatch to any overloaded symbol in the accessible scope.
if !(choices[0].isOverloadable || choices[0].type is Metatype) {
// First case: the identifier refers to a property.
assert(choices.count == 1)
node.symbol = choices[0]
} else if let ty = (choices[0].type as? Metatype)?.type as? NominalType {
// Second case: the identifier refers to a constructor.
choices = ty.memberScope!.symbols["new"]!
node.symbol = inferSymbol(type: node.type!, choices: choices)
} else {
// Thid case: the identifier refers to a function.
var scope = node.scope
while let parent = scope?.parent {
if let symbols = parent.symbols[node.name] {
guard symbols.first!.isOverloadable
else { break }
choices += symbols
}
scope = parent
}
node.symbol = inferSymbol(type: node.type!, choices: choices)
}
} else {
assert(choices.count == 1)
node.symbol = choices[0]
}
return node
}
private func visitScopeDelimiter(_ node: ScopeDelimiter) {
if let scope = node.innerScope {
for symbol in scope.symbols.values.joined() {
symbol.type = symbol.type.map { solution.reify(type: $0, in: context, skipping: &visited) }
}
}
}
private func reify(type: TypeBase?) -> TypeBase? {
return type.map { solution.reify(type: $0, in: context, skipping: &visited) }
}
private func inferSymbol(type: TypeBase, choices: [Symbol]) -> Symbol {
// Filter out incompatible symbols.
let compatible = choices.filter { symbol in
let ty = symbol.isMethod && !symbol.isStatic
? (symbol.type as! FunctionType).codomain
: symbol.type!
var bindings: [PlaceholderType: TypeBase] = [:]
return specializes(lhs: type, rhs: ty, in: context, bindings: &bindings)
}
// FIXME: Disambiguise when there are several choices.
assert(compatible.count > 0)
return compatible[0]
}
}
| apache-2.0 | f62bf826874f173679d3567901158015 | 34.686695 | 99 | 0.669874 | 4.182596 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | Buy/Generated/Storefront/Brand.swift | 1 | 7321 | //
// Brand.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension Storefront {
/// The store's branding configuration.
open class BrandQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = Brand
/// The colors of the store's brand.
@discardableResult
open func colors(alias: String? = nil, _ subfields: (BrandColorsQuery) -> Void) -> BrandQuery {
let subquery = BrandColorsQuery()
subfields(subquery)
addField(field: "colors", aliasSuffix: alias, subfields: subquery)
return self
}
/// The store's cover image.
@discardableResult
open func coverImage(alias: String? = nil, _ subfields: (MediaImageQuery) -> Void) -> BrandQuery {
let subquery = MediaImageQuery()
subfields(subquery)
addField(field: "coverImage", aliasSuffix: alias, subfields: subquery)
return self
}
/// The store's default logo.
@discardableResult
open func logo(alias: String? = nil, _ subfields: (MediaImageQuery) -> Void) -> BrandQuery {
let subquery = MediaImageQuery()
subfields(subquery)
addField(field: "logo", aliasSuffix: alias, subfields: subquery)
return self
}
/// The store's short description.
@discardableResult
open func shortDescription(alias: String? = nil) -> BrandQuery {
addField(field: "shortDescription", aliasSuffix: alias)
return self
}
/// The store's slogan.
@discardableResult
open func slogan(alias: String? = nil) -> BrandQuery {
addField(field: "slogan", aliasSuffix: alias)
return self
}
/// The store's preferred logo for square UI elements.
@discardableResult
open func squareLogo(alias: String? = nil, _ subfields: (MediaImageQuery) -> Void) -> BrandQuery {
let subquery = MediaImageQuery()
subfields(subquery)
addField(field: "squareLogo", aliasSuffix: alias, subfields: subquery)
return self
}
}
/// The store's branding configuration.
open class Brand: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = BrandQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "colors":
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return try BrandColors(fields: value)
case "coverImage":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return try MediaImage(fields: value)
case "logo":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return try MediaImage(fields: value)
case "shortDescription":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return value
case "slogan":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return value
case "squareLogo":
if value is NSNull { return nil }
guard let value = value as? [String: Any] else {
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
return try MediaImage(fields: value)
default:
throw SchemaViolationError(type: Brand.self, field: fieldName, value: fieldValue)
}
}
/// The colors of the store's brand.
open var colors: Storefront.BrandColors {
return internalGetColors()
}
func internalGetColors(alias: String? = nil) -> Storefront.BrandColors {
return field(field: "colors", aliasSuffix: alias) as! Storefront.BrandColors
}
/// The store's cover image.
open var coverImage: Storefront.MediaImage? {
return internalGetCoverImage()
}
func internalGetCoverImage(alias: String? = nil) -> Storefront.MediaImage? {
return field(field: "coverImage", aliasSuffix: alias) as! Storefront.MediaImage?
}
/// The store's default logo.
open var logo: Storefront.MediaImage? {
return internalGetLogo()
}
func internalGetLogo(alias: String? = nil) -> Storefront.MediaImage? {
return field(field: "logo", aliasSuffix: alias) as! Storefront.MediaImage?
}
/// The store's short description.
open var shortDescription: String? {
return internalGetShortDescription()
}
func internalGetShortDescription(alias: String? = nil) -> String? {
return field(field: "shortDescription", aliasSuffix: alias) as! String?
}
/// The store's slogan.
open var slogan: String? {
return internalGetSlogan()
}
func internalGetSlogan(alias: String? = nil) -> String? {
return field(field: "slogan", aliasSuffix: alias) as! String?
}
/// The store's preferred logo for square UI elements.
open var squareLogo: Storefront.MediaImage? {
return internalGetSquareLogo()
}
func internalGetSquareLogo(alias: String? = nil) -> Storefront.MediaImage? {
return field(field: "squareLogo", aliasSuffix: alias) as! Storefront.MediaImage?
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
var response: [GraphQL.AbstractResponse] = []
objectMap.keys.forEach {
switch($0) {
case "colors":
response.append(internalGetColors())
response.append(contentsOf: internalGetColors().childResponseObjectMap())
case "coverImage":
if let value = internalGetCoverImage() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "logo":
if let value = internalGetLogo() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
case "squareLogo":
if let value = internalGetSquareLogo() {
response.append(value)
response.append(contentsOf: value.childResponseObjectMap())
}
default:
break
}
}
return response
}
}
}
| mit | 82dd34a895d6636c4cbfc68eaae4062f | 30.969432 | 100 | 0.700997 | 4.015908 | false | false | false | false |
whiteshadow-gr/HatForIOS | HAT/Objects/Phatav2/HATProfileOnline.swift | 1 | 4237 | /**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
import SwiftyJSON
// MARK: Struct
public struct HATProfileOnline: HATObject, HatApiType {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `blog` in JSON is `blog`
* `google` in JSON is `google`
* `twitter` in JSON is `twitter`
* `website` in JSON is `website`
* `youtube` in JSON is `youtube`
* `facebook` in JSON is `facebook`
* `linkedin` in JSON is `linkedin`
*/
private enum CodingKeys: String, CodingKey {
case blog
case google
case twitter
case website
case youtube
case facebook
case linkedin
}
// MARK: - Variables
/// The user's blog address
public var blog: String = ""
/// The user's google address
public var google: String = ""
/// The user's twitter address
public var twitter: String = ""
/// The user's website address
public var website: String = ""
/// The user's youtube address
public var youtube: String = ""
/// The user's facebook address
public var facebook: String = ""
/// The user's linkedin address
public var linkedin: String = ""
// MARK: - Initialisers
/**
The default initialiser. Initialises everything to default values.
*/
public init() {
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public init(dict: Dictionary<String, JSON>) {
self.init()
self.initialize(dict: dict)
}
/**
It initialises everything from the received JSON file from the HAT
- dict: The JSON file received from the HAT
*/
public mutating func initialize(dict: Dictionary<String, JSON>) {
if let tempBlog: String = (dict[CodingKeys.blog.rawValue]?.stringValue) {
blog = tempBlog
}
if let tempGoogle: String = (dict[CodingKeys.google.rawValue]?.stringValue) {
google = tempGoogle
}
if let tempTwitter: String = (dict[CodingKeys.twitter.rawValue]?.stringValue) {
twitter = tempTwitter
}
if let tempWebsite: String = (dict[CodingKeys.website.rawValue]?.stringValue) {
website = tempWebsite
}
if let tempYoutube: String = (dict[CodingKeys.youtube.rawValue]?.stringValue) {
youtube = tempYoutube
}
if let tempFacebook: String = (dict[CodingKeys.facebook.rawValue]?.stringValue) {
facebook = tempFacebook
}
if let tempLinkedin: String = (dict[CodingKeys.linkedin.rawValue]?.stringValue) {
linkedin = tempLinkedin
}
}
// MARK: - HatApiType protocol
/**
Returns the object as Dictionary, JSON
- returns: Dictionary<String, String>
*/
public func toJSON() -> Dictionary<String, Any> {
return [
CodingKeys.blog.rawValue: self.blog,
CodingKeys.google.rawValue: self.google,
CodingKeys.twitter.rawValue: self.twitter,
CodingKeys.website.rawValue: self.website,
CodingKeys.youtube.rawValue: self.youtube,
CodingKeys.facebook.rawValue: self.facebook,
CodingKeys.linkedin.rawValue: self.linkedin
]
}
/**
It initialises everything from the received Dictionary file from the cache
- fromCache: The dictionary file received from the cache
*/
public mutating func initialize(fromCache: Dictionary<String, Any>) {
let json: JSON = JSON(fromCache)
self.initialize(dict: json.dictionaryValue)
}
}
| mpl-2.0 | 079b2598b8fcd96b4bacc19ba1590d29 | 27.436242 | 89 | 0.586972 | 4.809308 | false | false | false | false |
GimVic-app/gimvic-ios | GimVic/SuplenceViewController.swift | 2 | 4052 | //
// ViewController.swift
// GimVic
//
// Created by Vid Drobnič on 9/18/16.
// Copyright © 2016 Vid Drobnič. All rights reserved.
//
import UIKit
import GimVicData
class SuplenceViewController: UIViewController, UITableViewDataSource, TimetableDataDelegate {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var snackLabel: UILabel!
@IBOutlet weak var lunchLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var index = 0
let refreshControl = UIRefreshControl()
var profesor = false
var data: TimetableEntry?
override func viewDidLoad() {
super.viewDidLoad()
dateLabel.text = Weekdays(index: index)!.rawValue
TimetableData.sharedInstance.delegates[TimetableData.DelegateID(rawValue: index)!] = self
data = TimetableData.sharedInstance.timetableEntryFor(TimetableData.Weekday(rawValue: index)!)
setJedilnik()
profesor = UserDefaults().bool(forKey: UserSettings.profesorFilter.rawValue)
tableView.register(UINib(nibName: "SuplenceCell", bundle: nil), forCellReuseIdentifier: "SuplenceCell")
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
refreshControl.addTarget(self, action: #selector(refresh(sender:)), for: .valueChanged)
refreshControl.tintColor = UIColor.white
refreshControl.tintColor = UIColor.white
refreshControl.tintColorDidChange()
tableView.addSubview(refreshControl)
}
func setJedilnik() {
snackLabel.text = data?.snack ?? ""
lunchLabel.text = data?.lunch ?? ""
}
func refresh(sender: AnyObject) {
let viewControllers = RootViewController.sharedInstance?.suplenceViewControllers ?? []
for viewController in viewControllers {
if viewController.index == index {
continue
}
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
viewController.tableView.contentOffset.y = -viewController.refreshControl.frame.size.height
}, completion: {finished in
viewController.refreshControl.beginRefreshing()
})
}
TimetableData.sharedInstance.update()
}
// MARK: - Table View Data Source
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data?.lessons.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SuplenceCell", for: indexPath) as! SuplenceCell
let lesson = data!.lessons[indexPath.row]
cell.hourLabel.text = String(lesson.hour)
cell.lessonLabel.text = lesson.subjects.first
cell.classroomLabel.text = lesson.classrooms.first
if profesor {
cell.teacherLabel.text = lesson.classes.first
} else {
cell.teacherLabel.text = lesson.teachers.first
}
cell.setNote(lesson.note)
cell.isSubstitution(lesson.substitution)
return cell
}
// MARK: - Timetable Data Delegate
func timetableDataDidUpdateWithStatus(_ status: DataGetterStatus) {
UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: {
self.tableView.contentOffset.y = 0
}, completion: {finished in
self.refreshControl.endRefreshing()
})
if status == .success {
data = TimetableData.sharedInstance.timetableEntryFor(TimetableData.Weekday(rawValue: index)!)
tableView.reloadData()
setJedilnik()
profesor = UserDefaults().bool(forKey: UserSettings.profesorFilter.rawValue)
}
}
}
| gpl-3.0 | a78f7f0263dbdf825498ad2b00c5f1dd | 35.477477 | 113 | 0.646826 | 5.093082 | false | false | false | false |
kcome/SwiftIB | SwiftIB/Order.swift | 1 | 14798 | //
// Order.swift
// SwiftIB
//
// Created by Hanfei Li on 1/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
open class Order: Equatable {
let CUSTOMER: Int = 0
let FIRM: Int = 1
let OPT_UNKNOWN: Character = "?"
let OPT_BROKER_DEALER: Character = "b"
let OPT_CUSTOMER: Character = "c"
let OPT_FIRM: Character = "f"
let OPT_ISEMM: Character = "m"
let OPT_FARMM: Character = "n"
let OPT_SPECIALIST: Character = "y"
let AUCTION_MATCH: Int = 1
let AUCTION_IMPROVEMENT: Int = 2
let AUCTION_TRANSPARENT: Int = 3
let EMPTY_STR: String = ""
// main order fields
var orderId: Int
var clientId: Int
var permId: Int
var action: String
var totalQuantity: Int
var orderType: String
var lmtPrice: Double
var auxPrice: Double
// extended order fields
var tif: String // "Time in Force" - DAY, GTC, etc.
var activeStartTime: String // GTC orders
var activeStopTime: String // GTC orders
var ocaGroup: String // one cancels all group name
var ocaType: Int = 0 // 1 = CANCEL_WITH_BLOCK, 2 = REDUCE_WITH_BLOCK, 3 = REDUCE_NON_BLOCK
var orderRef: String
var transmit: Bool // if false, order will be created but not transmited
var parentId: Int = 0 // Parent order Id, to associate Auto STP or TRAIL orders with the original order.
var blockOrder: Bool = false
var sweepToFill: Bool = false
var displaySize: Int = 0
var triggerMethod: Int = 0 // 0=Default, 1=Double_Bid_Ask, 2=Last, 3=Double_Last, 4=Bid_Ask, 7=Last_or_Bid_Ask, 8=Mid-point
var outsideRth: Bool
var hidden: Bool = false
var goodAfterTime: String // FORMAT: 20060505 08:00:00 {time zone}
var goodTillDate: String // FORMAT: 20060505 08:00:00 {time zone}
var overridePercentageConstraints: Bool = false
var rule80A: String // Individual = 'I', Agency = 'A', AgentOtherMember = 'W', IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M', IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
var allOrNone: Bool = false
var minQty: Int
var percentOffset: Double // REL orders only. specify the decimal, e.g. .04 not 4
var trailStopPrice: Double // for TRAILLIMIT orders only
var trailingPercent: Double // specify the percentage, e.g. 3, not .03
// Financial advisors only
var faGroup: String
var faProfile: String
var faMethod: String
var faPercentage: String
// Institutional orders only
var openClose: String // O=Open, C=Close
var origin: Int // 0=Customer, 1=Firm
var shortSaleSlot: Int = 0 // 1 if you hold the shares, 2 if they will be delivered from elsewhere. Only for Action="SSHORT
var designatedLocation: String // set when slot=2 only.
var exemptCode: Int
// SMART routing only
var discretionaryAmt: Double = 0
var eTradeOnly: Bool = false
var firmQuoteOnly: Bool = false
var nbboPriceCap: Double
var optOutSmartRouting: Bool
// BOX or VOL ORDERS ONLY
var auctionStrategy: Int = 0 // 1=AUCTION_MATCH, 2=AUCTION_IMPROVEMENT, 3=AUCTION_TRANSPARENT
// BOX ORDERS ONLY
var startingPrice: Double
var stockRefPrice: Double
var delta: Double
// pegged to stock or VOL orders
var stockRangeLower: Double
var stockRangeUpper: Double
// VOLATILITY ORDERS ONLY
var volatility: Double // enter percentage not decimal, e.g. 2 not .02
var volatilityType: Int // 1=daily, 2=annual
var continuousUpdate: Int = 0
var referencePriceType: Int // 1=Bid/Ask midpoint, 2 = BidOrAsk
var deltaNeutralOrderType: String
var deltaNeutralAuxPrice: Double
var deltaNeutralConId: Int
var deltaNeutralSettlingFirm: String
var deltaNeutralClearingAccount: String
var deltaNeutralClearingIntent: String
var deltaNeutralOpenClose: String
var deltaNeutralShortSale: Bool
var deltaNeutralShortSaleSlot: Int
var deltaNeutralDesignatedLocation: String
// COMBO ORDERS ONLY
var basisPoints: Double // EFP orders only, download only
var basisPointsType: Int // EFP orders only, download only
// SCALE ORDERS ONLY
var scaleInitLevelSize: Int
var scaleSubsLevelSize: Int
var scalePriceIncrement: Double
var scalePriceAdjustValue: Double
var scalePriceAdjustInterval: Int
var scaleProfitOffset: Double
var scaleAutoReset: Bool
var scaleInitPosition: Int
var scaleInitFillQty: Int
var scaleRandomPercent: Bool
var scaleTable: String
// HEDGE ORDERS ONLY
var hedgeType: String // 'D' - delta, 'B' - beta, 'F' - FX, 'P' - pair
var hedgeParam: String // beta value for beta hedge (in range 0-1), ratio for pair hedge
// Clearing info
var account: String // IB account
var settlingFirm: String
var clearingAccount: String // True beneficiary of the order
var clearingIntent: String // "" (Default), "IB", "Away", "PTA" (PostTrade)
// ALGO ORDERS ONLY
var algoStrategy: String
var algoParams: [TagValue] = [TagValue]()
// What-if
var whatIf: Bool
// Not Held
var notHeld: Bool
// Smart combo routing params
var smartComboRoutingParams: [TagValue] = [TagValue]()
// order combo legs
var orderComboLegs: [OrderComboLeg] = [OrderComboLeg]()
// order misc options
var orderMiscOptions: [TagValue] = [TagValue]()
init() {
activeStartTime = EMPTY_STR
activeStopTime = EMPTY_STR
designatedLocation = EMPTY_STR
deltaNeutralOrderType = EMPTY_STR
deltaNeutralSettlingFirm = EMPTY_STR
deltaNeutralClearingAccount = EMPTY_STR
deltaNeutralClearingIntent = EMPTY_STR
deltaNeutralOpenClose = EMPTY_STR
deltaNeutralDesignatedLocation = EMPTY_STR
scaleTable = EMPTY_STR
openClose = "O"
origin = CUSTOMER
transmit = true
exemptCode = -1
deltaNeutralConId = 0
deltaNeutralShortSaleSlot = 0
lmtPrice = Double.nan
auxPrice = Double.nan
percentOffset = Double.nan
nbboPriceCap = Double.nan
startingPrice = Double.nan
stockRefPrice = Double.nan
delta = Double.nan
stockRangeLower = Double.nan
stockRangeUpper = Double.nan
volatility = Double.nan
deltaNeutralAuxPrice = Double.nan
trailStopPrice = Double.nan
trailingPercent = Double.nan
basisPoints = Double.nan
scalePriceIncrement = Double.nan
scalePriceAdjustValue = Double.nan
scaleProfitOffset = Double.nan
minQty = Int.max
volatilityType = Int.max
referencePriceType = Int.max
basisPointsType = Int.max
scaleInitLevelSize = Int.max
scaleSubsLevelSize = Int.max
scalePriceAdjustInterval = Int.max
scaleInitPosition = Int.max
scaleInitFillQty = Int.max
outsideRth = false
optOutSmartRouting = false
deltaNeutralShortSale = false
scaleAutoReset = false
scaleRandomPercent = false
whatIf = false
notHeld = false
orderId = 0
clientId = 0
permId = 0
action = EMPTY_STR
totalQuantity = 0
orderType = EMPTY_STR
tif = EMPTY_STR
ocaGroup = EMPTY_STR
orderRef = EMPTY_STR
goodAfterTime = EMPTY_STR
goodTillDate = EMPTY_STR
rule80A = EMPTY_STR
faGroup = EMPTY_STR
faProfile = EMPTY_STR
faMethod = EMPTY_STR
faPercentage = EMPTY_STR
hedgeType = EMPTY_STR
hedgeParam = EMPTY_STR
account = EMPTY_STR
settlingFirm = EMPTY_STR
clearingAccount = EMPTY_STR
clearingIntent = EMPTY_STR
algoStrategy = EMPTY_STR
}
}
public func == (lhs: Order, rhs: Order) -> Bool {
if lhs === rhs {
return true
}
if lhs.permId == rhs.permId {
return true
}
if lhs.orderId != rhs.orderId {return false}
if lhs.clientId != rhs.clientId {return false}
if lhs.totalQuantity != rhs.totalQuantity {return false}
if lhs.lmtPrice != rhs.lmtPrice {return false}
if lhs.auxPrice != rhs.auxPrice {return false}
if lhs.ocaType != rhs.ocaType {return false}
if lhs.transmit != rhs.transmit {return false}
if lhs.parentId != rhs.parentId {return false}
if lhs.blockOrder != rhs.blockOrder {return false}
if lhs.sweepToFill != rhs.sweepToFill {return false}
if lhs.displaySize != rhs.displaySize {return false}
if lhs.triggerMethod != rhs.triggerMethod {return false}
if lhs.outsideRth != rhs.outsideRth {return false}
if lhs.hidden != rhs.hidden {return false}
if lhs.overridePercentageConstraints != rhs.overridePercentageConstraints {return false}
if lhs.allOrNone != rhs.allOrNone {return false}
if lhs.minQty != rhs.minQty {return false}
if lhs.percentOffset != rhs.percentOffset {return false}
if lhs.trailStopPrice != rhs.trailStopPrice {return false}
if lhs.trailingPercent != rhs.trailingPercent {return false}
if lhs.origin != rhs.origin {return false}
if lhs.shortSaleSlot != rhs.shortSaleSlot {return false}
if lhs.discretionaryAmt != rhs.discretionaryAmt {return false}
if lhs.eTradeOnly != rhs.eTradeOnly {return false}
if lhs.firmQuoteOnly != rhs.firmQuoteOnly {return false}
if lhs.nbboPriceCap != rhs.nbboPriceCap {return false}
if lhs.optOutSmartRouting != rhs.optOutSmartRouting {return false}
if lhs.auctionStrategy != rhs.auctionStrategy {return false}
if lhs.startingPrice != rhs.startingPrice {return false}
if lhs.stockRefPrice != rhs.stockRefPrice {return false}
if lhs.delta != rhs.delta {return false}
if lhs.stockRangeLower != rhs.stockRangeLower {return false}
if lhs.stockRangeUpper != rhs.stockRangeUpper {return false}
if lhs.volatility != rhs.volatility {return false}
if lhs.volatilityType != rhs.volatilityType {return false}
if lhs.continuousUpdate != rhs.continuousUpdate {return false}
if lhs.referencePriceType != rhs.referencePriceType {return false}
if lhs.deltaNeutralAuxPrice != rhs.deltaNeutralAuxPrice {return false}
if lhs.deltaNeutralConId != rhs.deltaNeutralConId {return false}
if lhs.deltaNeutralShortSale != rhs.deltaNeutralShortSale {return false}
if lhs.deltaNeutralShortSaleSlot != rhs.deltaNeutralShortSaleSlot {return false}
if lhs.basisPoints != rhs.basisPoints {return false}
if lhs.basisPointsType != rhs.basisPointsType {return false}
if lhs.scaleInitLevelSize != rhs.scaleInitLevelSize {return false}
if lhs.scaleSubsLevelSize != rhs.scaleSubsLevelSize {return false}
if lhs.scalePriceIncrement != rhs.scalePriceIncrement {return false}
if lhs.scalePriceAdjustValue != rhs.scalePriceAdjustValue {return false}
if lhs.scalePriceAdjustInterval != rhs.scalePriceAdjustInterval {return false}
if lhs.scaleProfitOffset != rhs.scaleProfitOffset {return false}
if lhs.scaleAutoReset != rhs.scaleAutoReset {return false}
if lhs.scaleInitPosition != rhs.scaleInitPosition {return false}
if lhs.scaleInitFillQty != rhs.scaleInitFillQty {return false}
if lhs.scaleRandomPercent != rhs.scaleRandomPercent {return false}
if lhs.whatIf != rhs.whatIf {return false}
if lhs.notHeld != rhs.notHeld {return false}
if lhs.exemptCode != rhs.exemptCode {return false}
if lhs.action != rhs.action {return false}
if lhs.orderType != rhs.orderType {return false}
if lhs.tif != rhs.tif {return false}
if lhs.activeStartTime != rhs.activeStartTime {return false}
if lhs.activeStopTime != rhs.activeStopTime {return false}
if lhs.ocaGroup != rhs.ocaGroup {return false}
if lhs.orderRef != rhs.orderRef {return false}
if lhs.goodAfterTime != rhs.goodAfterTime {return false}
if lhs.goodTillDate != rhs.goodTillDate {return false}
if lhs.rule80A != rhs.rule80A {return false}
if lhs.faGroup != rhs.faGroup {return false}
if lhs.faProfile != rhs.faProfile {return false}
if lhs.faMethod != rhs.faMethod {return false}
if lhs.faPercentage != rhs.faPercentage {return false}
if lhs.openClose != rhs.openClose {return false}
if lhs.designatedLocation != rhs.designatedLocation {return false}
if lhs.deltaNeutralOrderType != rhs.deltaNeutralOrderType {return false}
if lhs.deltaNeutralSettlingFirm != rhs.deltaNeutralSettlingFirm {return false}
if lhs.deltaNeutralClearingAccount != rhs.deltaNeutralClearingAccount {return false}
if lhs.deltaNeutralClearingIntent != rhs.deltaNeutralClearingIntent {return false}
if lhs.deltaNeutralOpenClose != rhs.deltaNeutralOpenClose {return false}
if lhs.deltaNeutralDesignatedLocation != rhs.deltaNeutralDesignatedLocation {return false}
if lhs.hedgeType != rhs.hedgeType {return false}
if lhs.hedgeParam != rhs.hedgeParam {return false}
if lhs.account != rhs.account {return false}
if lhs.settlingFirm != rhs.settlingFirm {return false}
if lhs.clearingAccount != rhs.clearingAccount {return false}
if lhs.clearingIntent != rhs.clearingIntent {return false}
if lhs.algoStrategy != rhs.algoStrategy {return false}
if lhs.scaleTable != rhs.scaleTable {return false}
if !arrayEqualUnordered(lhs.algoParams, rhs.algoParams) {return false}
if !arrayEqualUnordered(lhs.smartComboRoutingParams, rhs.smartComboRoutingParams) {return false}
if !arrayEqualUnordered(lhs.orderComboLegs, rhs.orderComboLegs) {return false}
return true
}
| mit | 6c2d2745897d230e0393b198ebd7387f | 40.335196 | 212 | 0.68908 | 4.088975 | false | false | false | false |
haijianhuo/TopStore | Pods/JSQCoreDataKit/Source/Utils.swift | 2 | 1631 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/// Describes a child managed object context.
public typealias ChildContext = NSManagedObjectContext
/// Describes the initialization options for a persistent store.
public typealias PersistentStoreOptions = [AnyHashable : AnyObject]
/// Describes default persistent store options.
public let defaultStoreOptions: PersistentStoreOptions = [
NSMigratePersistentStoresAutomaticallyOption: true as AnyObject,
NSInferMappingModelAutomaticallyOption: true as AnyObject
]
/// The default directory used to initialize a `CoreDataModel`.
/// On tvOS, this is the caches directory. All other platforms use the document directory.
public func defaultDirectoryURL() -> URL {
do {
#if os(tvOS)
let searchPathDirectory = FileManager.SearchPathDirectory.cachesDirectory
#else
let searchPathDirectory = FileManager.SearchPathDirectory.documentDirectory
#endif
return try FileManager.default.url(for: searchPathDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)
}
catch {
fatalError("*** Error finding default directory: \(error)")
}
}
| mit | af0055f28d6da17837f7d437940b208b | 28.636364 | 90 | 0.674847 | 5.433333 | false | false | false | false |
hikelee/hotel | Sources/Video/Models/Category.swift | 1 | 2050 | import Vapor
import Fluent
import HTTP
import Common
final class Category: HotelBasedModel {
static var entity: String {
return "hotel_category"
}
var id: Node?
var channelId: Node?
var hotelId: Node?
var title: String?
var imgUrl:String?
//items
var exists: Bool = false //used in fluent
init(node: Node) throws {
id = try? node.extract("id")
channelId = try? node.extract("channel_id")
hotelId = try? node.extract("hotel_id")
imgUrl = try node.extract("img_url")
title = try node.extract("title")
}
convenience init(node: Node, in context: Context) throws {
try self.init(node:node)
}
func makeNode() throws->Node {
return try Node(
node:[
"id": id,
"channel_id":channelId,
"hotel_id": hotelId,
"img_url": imgUrl,
"title": title,
])
}
func validate(isCreate: Bool) throws -> [String:String] {
var result:[String:String]=[:]
if (hotelId?.int ?? 0) == 0 {
result["hotel_id"] = "必选项";
}else if try (Hotel.query().filter("id", .equals, hotelId!).first()) == nil {
result["hotel_id"] = "找不到所选的酒店"
}
if title?.isEmpty ?? true{result["title"]="必填项"}
if imgUrl?.isEmpty ?? true{result["img_url"]="必填项"}
return result
}
}
extension Category {
static func find(hostId:Int) throws ->[Category] {
let query = " where t1.id=t2.category_id and t2.id=t3.video_id and t3.host_id=$1 order by t1.hot desc"
let sql = "select distinct t1.* from \(Category.entity) t1,\(Video.entity) t2,hotel_video_hosts t3 \(query)"
var result:[Category] = []
let params = [Node(hostId)]
if let rows = try database?.driver.raw(sql,params),let array = rows.nodeArray {
try array.forEach{
try result.append(Category(node:$0))
}
}
return result
}
}
| mit | 5d8130629aef8e1cec93e7539ee9d4e4 | 29.089552 | 116 | 0.556548 | 3.768224 | false | false | false | false |
JohnnyHao/ForeignChat | ForeignChat/TabVCs/UserCenter/LoginViewController.swift | 1 | 1914 | //
// LoginViewController.swift
// ForeignChat
//
// Created by Tonny Hao on 2/22/15.
// Copyright (c) 2015 Tonny Hao. All rights reserved.
//
import UIKit
class LoginViewController: UITableViewController {
@IBOutlet var emailField: UITextField!
@IBOutlet var passwordField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "dismissKeyboard"))
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.emailField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func dismissKeyboard() {
self.view.endEditing(true)
}
@IBAction func loginButtonPressed(sender: UIButton) {
// regist and login all use lowercase string.
let userName = emailField.text.lowercaseString
let password = passwordField.text
if countElements(userName) == 0 {
ProgressHUD.showError("Email field is empty.")
return
} else {
ProgressHUD.showError("Password field is empty.")
}
ProgressHUD.show("Signing in...", interaction: true)
PFUser.logInWithUsernameInBackground(userName, password: password) { (user: PFUser!, error: NSError!) -> Void in
if user != nil {
PushNotication.parsePushUserAssign()
ProgressHUD.showSuccess("Welcome back, \(user[PF_USER_FULLNAME])!")
self.dismissViewControllerAnimated(true, completion: nil)
} else {
if let info = error.userInfo {
ProgressHUD.showError(info["error"] as String)
}
}
}
}
}
| apache-2.0 | 7199bca34869c1211b350c979452fbca | 30.377049 | 120 | 0.611808 | 5.301939 | false | false | false | false |
practicalswift/swift | stdlib/public/core/LifetimeManager.swift | 26 | 7369 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: () throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body()
}
/// Evaluates a closure while ensuring that the given instance is not destroyed
/// before the closure returns.
///
/// - Parameters:
/// - x: An instance to preserve until the execution of `body` is completed.
/// - body: A closure to execute that depends on the lifetime of `x` being
/// extended. If `body` has a return value, that value is also used as the
/// return value for the `withExtendedLifetime(_:_:)` method.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable
public func withExtendedLifetime<T, Result>(
_ x: T, _ body: (T) throws -> Result
) rethrows -> Result {
defer { _fixLifetime(x) }
return try body(x)
}
// Fix the lifetime of the given instruction so that the ARC optimizer does not
// shorten the lifetime of x to be before this point.
@_transparent
public func _fixLifetime<T>(_ x: T) {
Builtin.fixLifetime(x)
}
/// Calls the given closure with a mutable pointer to the given argument.
///
/// The `withUnsafeMutablePointer(to:_:)` function is useful for calling
/// Objective-C APIs that take in/out parameters (and default-constructible
/// out parameters) by pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafeMutablePointer(to:_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer. Note that the `inout`
/// exclusivity rules mean that, like any other `inout` argument, `value`
/// cannot be directly accessed by other code for the duration of `body`.
/// Access must only occur through the pointer argument to `body` until
/// `body` returns.
/// - body: A closure that takes a mutable pointer to `value` as its sole
/// argument. If the closure has a return value, that value is also used
/// as the return value of the `withUnsafeMutablePointer(to:_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafeMutablePointer<T, Result>(
to value: inout T,
_ body: (UnsafeMutablePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafeMutablePointer<T>(Builtin.addressof(&value)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in parameters by const pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer.
/// - body: A closure that takes a pointer to `value` as its sole argument. If
/// the closure has a return value, that value is also used as the return
/// value of the `withUnsafePointer(to:_:)` function. The pointer argument
/// is valid only for the duration of the function's execution.
/// It is undefined behavior to try to mutate through the pointer argument
/// by converting it to `UnsafeMutablePointer` or any other mutable pointer
/// type. If you need to mutate the argument through the pointer, use
/// `withUnsafeMutablePointer(to:_:)` instead.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafePointer<T, Result>(
to value: T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressOfBorrow(value)))
}
/// Invokes the given closure with a pointer to the given argument.
///
/// The `withUnsafePointer(to:_:)` function is useful for calling Objective-C
/// APIs that take in parameters by const pointer.
///
/// The pointer argument to `body` is valid only during the execution of
/// `withUnsafePointer(to:_:)`. Do not store or return the pointer for later
/// use.
///
/// - Parameters:
/// - value: An instance to temporarily use via pointer. Note that the `inout`
/// exclusivity rules mean that, like any other `inout` argument, `value`
/// cannot be directly accessed by other code for the duration of `body`.
/// Access must only occur through the pointer argument to `body` until
/// `body` returns.
/// - body: A closure that takes a pointer to `value` as its sole argument. If
/// the closure has a return value, that value is also used as the return
/// value of the `withUnsafePointer(to:_:)` function. The pointer argument
/// is valid only for the duration of the function's execution.
/// It is undefined behavior to try to mutate through the pointer argument
/// by converting it to `UnsafeMutablePointer` or any other mutable pointer
/// type. If you need to mutate the argument through the pointer, use
/// `withUnsafeMutablePointer(to:_:)` instead.
/// - Returns: The return value, if any, of the `body` closure.
@inlinable
public func withUnsafePointer<T, Result>(
to value: inout T,
_ body: (UnsafePointer<T>) throws -> Result
) rethrows -> Result
{
return try body(UnsafePointer<T>(Builtin.addressof(&value)))
}
extension String {
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // fast-path: already C-string compatible
public func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
return try _guts.withCString(body)
}
}
| apache-2.0 | 2a83d1df06abb734f4c29faa340d1370 | 42.60355 | 80 | 0.683268 | 4.266937 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletPairing/Login/LoginService.swift | 1 | 2388 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import WalletPayloadKit
public final class LoginService: LoginServiceAPI {
// MARK: - Properties
public let authenticator: AnyPublisher<WalletAuthenticatorType, Never>
private let payloadService: WalletPayloadServiceAPI
private let twoFAPayloadService: TwoFAWalletServiceAPI
private let guidRepository: GuidRepositoryAPI
/// Keeps authenticator type. Defaults to `.none` unless
/// `func login() -> AnyPublisher<Void, LoginServiceError>` sets it to a different value
private let authenticatorSubject: CurrentValueSubject<WalletAuthenticatorType, Never>
// MARK: - Setup
public init(
payloadService: WalletPayloadServiceAPI,
twoFAPayloadService: TwoFAWalletServiceAPI,
repository: GuidRepositoryAPI
) {
self.payloadService = payloadService
self.twoFAPayloadService = twoFAPayloadService
guidRepository = repository
authenticatorSubject = CurrentValueSubject(WalletAuthenticatorType.standard)
authenticator = authenticatorSubject.eraseToAnyPublisher()
}
// MARK: - API
public func login(walletIdentifier: String) -> AnyPublisher<Void, LoginServiceError> {
guidRepository
.set(guid: walletIdentifier)
.first()
.flatMap { [payloadService] _ -> AnyPublisher<WalletAuthenticatorType, WalletPayloadServiceError> in
payloadService.requestUsingSessionToken()
}
.mapError(LoginServiceError.walletPayloadServiceError)
.handleEvents(receiveOutput: { [authenticatorSubject] type in
authenticatorSubject.send(type)
})
.flatMap { type -> AnyPublisher<Void, LoginServiceError> in
switch type {
case .standard:
return .just(())
case .google, .yubiKey, .email, .yubikeyMtGox, .sms:
return .failure(.twoFactorOTPRequired(type))
}
}
.eraseToAnyPublisher()
}
public func login(walletIdentifier: String, code: String) -> AnyPublisher<Void, LoginServiceError> {
twoFAPayloadService
.send(code: code)
.mapError(LoginServiceError.twoFAWalletServiceError)
.eraseToAnyPublisher()
}
}
| lgpl-3.0 | d0311f3b93f707d8096fc648e20df2c5 | 35.723077 | 112 | 0.664013 | 5.474771 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Services/UserWallet/UserWalletURLRequest.swift | 1 | 1442 | //
// Copyright © 2020 Ingresse. All rights reserved.
//
import Alamofire
struct UserWalletURLRequest {
struct GetWallet: NetworkURLRequest {
private let userId: Int
private let apiKey: String
private let request: WalletRequest
private let environment: Environment
private let userAgent: String
private let authToken: String
init(userId: Int,
apiKey: String,
request: WalletRequest,
environment: Environment,
userAgent: String,
authToken: String) {
self.userId = userId
self.apiKey = apiKey
self.request = request
self.environment = environment
self.userAgent = userAgent
self.authToken = authToken
}
var body: Encodable? { nil }
var baseURL: URL? { environment.walletBaseURL }
var path: String { "user/\(userId)/wallet" }
var method: HTTPMethod { .get }
var authenticationType: AuthenticationType? { nil}
var headers: [HeaderType]? {
[.userAgent(header: userAgent, authorization: authToken)]
}
var parameters: Encodable? {
KeyedRequest(request: request, apikey: apiKey)
}
}
}
private extension Environment {
var walletBaseURL: URL? {
URL(string: "https://\(self.rawValue)\(Host.api.rawValue)")
}
}
| mit | 1b72679b495d51a6ad6a85af2524833a | 27.254902 | 69 | 0.58501 | 5.146429 | false | false | false | false |
huonw/swift | benchmark/single-source/DictionaryGroup.swift | 1 | 1636 | //===--- DictionaryGroup.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let DictionaryGroup = [
BenchmarkInfo(name: "DictionaryGroup", runFunction: run_DictionaryGroup, tags: [.validation, .api, .Dictionary]),
BenchmarkInfo(name: "DictionaryGroupOfObjects", runFunction: run_DictionaryGroupOfObjects, tags: [.validation, .api, .Dictionary]),
]
let count = 10_000
let result = count / 10
@inline(never)
public func run_DictionaryGroup(_ N: Int) {
for _ in 1...N {
let dict = Dictionary(grouping: 0..<count, by: { $0 % 10 })
CheckResults(dict.count == 10)
CheckResults(dict[0]!.count == result)
}
}
class Box<T : Hashable> : Hashable {
var value: T
init(_ v: T) {
value = v
}
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
static func ==(lhs: Box, rhs: Box) -> Bool {
return lhs.value == rhs.value
}
}
@inline(never)
public func run_DictionaryGroupOfObjects(_ N: Int) {
let objects = (0..<count).map { Box($0) }
for _ in 1...N {
let dict = Dictionary(grouping: objects, by: { Box($0.value % 10) })
CheckResults(dict.count == 10)
CheckResults(dict[Box(0)]!.count == result)
}
}
| apache-2.0 | 2f8397546b5aa1586d2db78005a0d202 | 28.214286 | 133 | 0.616137 | 3.913876 | false | false | false | false |
ludoded/ReceiptBot | ReceiptBot/Networking/Router/Router.swift | 1 | 5647 | //
// Router.swift
// ReceiptBot
//
// Created by Haik Ampardjian on 4/4/17.
// Copyright © 2017 receiptbot. All rights reserved.
//
import Foundation
import Alamofire
protocol BaseRouter: URLRequestConvertible {
static var baseURLString: String? { get }
}
enum SessionRouter: BaseRouter {
static var baseURLString: String?
case signUpFirst(Parameters)
case signUpSecond(Parameters)
case signIn(Parameters)
case external(email: String)
case forgotPassword(email: String)
var method: Alamofire.HTTPMethod {
switch self {
case .signUpFirst, .signUpSecond, .signIn:
return .post
case .forgotPassword, .external:
return .get
}
}
var path: String {
switch self {
case .signUpFirst:
return "/AccountService.svc/RegisterUser"
case .signUpSecond:
return "/AccountService.svc/SignUpOrgInfo"
case .signIn:
return "/AccountService.svc/Login"
case .external(let email):
return "/AccountService.svc/ExternalLogin/\(email)"
case .forgotPassword(let email):
return "/AccountService.svc/ForgotPassword/\(email)"
}
}
func asURLRequest() throws -> URLRequest {
let url = Foundation.URL(string: SessionRouter.baseURLString!)!
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
let encoder = JSONEncoding.default
switch self {
case .signUpFirst(let params):
return try encoder.encode(urlRequest, with: params)
case .signUpSecond(let params):
return try encoder.encode(urlRequest, with: params)
case .signIn(let params):
return try encoder.encode(urlRequest, with: params)
case .forgotPassword, .external:
return try encoder.encode(urlRequest, with: nil)
}
}
}
enum Router: BaseRouter {
static var baseURLString: String?
static var OAuthToken: String?
case syncData(entityId: Int)
case pieChart(entityId: Int)
case lineChart(entityId: Int)
case convertedInvoice(originalInvoiceId: Int)
case paymentMethod(entityId: Int)
case allExpense(softwareId: String, entityId: Int)
case taxPercentage(softwareId: String, entityId: Int)
case fileUpload(params: Parameters)
case xeroCategories
case qbCategories
case updateConvertedInvoice(params: Parameters)
case suppliers(softwareId: String, entityId: Int)
case reject(params: Parameters)
var method: Alamofire.HTTPMethod {
switch self {
case .syncData,
.pieChart,
.lineChart,
.convertedInvoice,
.paymentMethod,
.allExpense,
.taxPercentage,
.xeroCategories,
.qbCategories,
.suppliers:
return .get
case .fileUpload,
.updateConvertedInvoice,
.reject:
return .post
}
}
var path: String {
switch self {
case .syncData(let entityId):
return "/DataCorrectionService.svc/SyncConvertedInvoicesMobile/\(entityId)"
case .pieChart(let entityId):
return "/CommonService.svc/InvoiceStatusToShow/\(entityId)"
case .lineChart(let entityId):
return "/CommonService.svc/linechartMobile/\(entityId)/6"
case .convertedInvoice(let originalInvoiceId):
return "/DataCorrectionService.svc/GetConvertedInvoicesMobile/\(originalInvoiceId)"
case .paymentMethod(let entityId):
return "/CommonService.svc/GetPaymentsModesMobile/\(entityId)"
case .allExpense(let softwareId, let entityId):
return "/CommonService.svc/GetCategories/\(softwareId)/\(entityId)"
case .taxPercentage(let softwareId, let entityId):
return "/CommonService.svc/GetTaxPercentageMobile/\(softwareId)/\(entityId)"
case .fileUpload:
return "/FileService.svc/FileUploadMobile"
case .xeroCategories:
return "/CommonService.svc/GetAllXeroExpenseCategories"
case .qbCategories:
return "/CommonService.svc/GetAllQBExpenseCategories"
case .updateConvertedInvoice:
return "/DataCorrectionService.svc/UpdateConvertedInvoiceMobile"
case .suppliers(let softwareId, let entityId):
return "/DataCorrectionService.svc/GetSuppliers/\(softwareId)/\(entityId)"
case .reject:
return "/DataCorrectionService.svc/AddInvoiceCommentMobile"
}
}
func asURLRequest() throws -> URLRequest {
let url = Foundation.URL(string: Router.baseURLString!)!
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
let urlEncoder = URLEncoding.default
let jsonEncoder = JSONEncoding.default
switch self {
case .syncData,
.pieChart,
.lineChart,
.convertedInvoice,
.paymentMethod,
.allExpense,
.taxPercentage,
.xeroCategories,
.qbCategories,
.suppliers:
return try urlEncoder.encode(urlRequest, with: nil)
case .fileUpload(let params),
.updateConvertedInvoice(let params),
.reject(let params):
return try jsonEncoder.encode(urlRequest, with: params)
}
}
}
| lgpl-3.0 | ce4a1945120a8bd01d8b22f6231382f8 | 33.012048 | 95 | 0.620971 | 5.027605 | false | false | false | false |
andreabondi/sdktester | SDKtester/NativeXOUIWebViewController.swift | 1 | 1653 | //
// NativeXOUIWebViewController.swift
// SDK Tester
//
// Created by Bondi, Andrea on 20/04/2017.
// Copyright © 2017 Bondi, Andrea. All rights reserved.
//
import Foundation
import UIKit
import WebKit
class NativeXOUIWebViewController: UIViewController {
var storeUrl: String = ""
var nativeSheet: Bool = true
var instance: PYPLCheckout!
@IBOutlet weak var storeWebView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false;
// Generate the request and quickly check for scheme.
// If no scheme, add https:// to the url
var url = URL (string: storeUrl)
if (url?.scheme) == nil {
storeUrl = "https://" + storeUrl
url = URL (string: storeUrl)
}
let requestObj = URLRequest(url: url!)
// Retrieve the shared instance of NativeXO and setup the right WebView.
// NativeXO supports UIWebView
instance = PYPLCheckout.sharedInstance() as! PYPLCheckout
if(nativeSheet) {
instance.webBrowserOnlyMode = false
} else {
instance.webBrowserOnlyMode = true
}
instance.interceptWebView(storeWebView)
storeWebView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
storeWebView.load(requestObj)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destinationVC = segue.destination as? ViewController
destinationVC?.selectedSdk = 0
destinationVC?.url = storeUrl
}
}
| mit | 9afc4cc219f6cdc39cfaeb33cbe397dd | 29.036364 | 93 | 0.635593 | 4.844575 | false | false | false | false |
brentvatne/react-native-video | ios/Video/Features/RCTVideoErrorHandling.swift | 1 | 4125 | enum RCTVideoError : Int {
case fromJSPart
case noLicenseServerURL
case licenseRequestNotOk
case noDataFromLicenseRequest
case noSPC
case noDataRequest
case noCertificateData
case noCertificateURL
case noFairplayDRM
case noDRMData
case invalidContentId
}
enum RCTVideoErrorHandler {
static let noDRMData = NSError(
domain: "RCTVideo",
code: RCTVideoError.noDRMData.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM license.",
NSLocalizedFailureReasonErrorKey: "No drm object found.",
NSLocalizedRecoverySuggestionErrorKey: "Have you specified the 'drm' prop?"
])
static let noCertificateURL = NSError(
domain: "RCTVideo",
code: RCTVideoError.noCertificateURL.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM License.",
NSLocalizedFailureReasonErrorKey: "No certificate URL has been found.",
NSLocalizedRecoverySuggestionErrorKey: "Did you specified the prop certificateUrl?"
])
static let noCertificateData = NSError(
domain: "RCTVideo",
code: RCTVideoError.noCertificateData.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM license.",
NSLocalizedFailureReasonErrorKey: "No certificate data obtained from the specificied url.",
NSLocalizedRecoverySuggestionErrorKey: "Have you specified a valid 'certificateUrl'?"
])
static let noSPC = NSError(
domain: "RCTVideo",
code: RCTVideoError.noSPC.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining license.",
NSLocalizedFailureReasonErrorKey: "No spc received.",
NSLocalizedRecoverySuggestionErrorKey: "Check your DRM config."
])
static let noLicenseServerURL = NSError(
domain: "RCTVideo",
code: RCTVideoError.noLicenseServerURL.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM License.",
NSLocalizedFailureReasonErrorKey: "No license server URL has been found.",
NSLocalizedRecoverySuggestionErrorKey: "Did you specified the prop licenseServer?"
])
static let noDataFromLicenseRequest = NSError(
domain: "RCTVideo",
code: RCTVideoError.noDataFromLicenseRequest.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM license.",
NSLocalizedFailureReasonErrorKey: "No data received from the license server.",
NSLocalizedRecoverySuggestionErrorKey: "Is the licenseServer ok?"
])
static func licenseRequestNotOk(_ statusCode: Int) -> NSError {
return NSError(
domain: "RCTVideo",
code: RCTVideoError.licenseRequestNotOk.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining license.",
NSLocalizedFailureReasonErrorKey: String(
format:"License server responded with status code %li",
(statusCode)
),
NSLocalizedRecoverySuggestionErrorKey: "Did you send the correct data to the license Server? Is the server ok?"
])
}
static func fromJSPart(_ error: String) -> NSError {
return NSError(domain: "RCTVideo",
code: RCTVideoError.fromJSPart.rawValue,
userInfo: [
NSLocalizedDescriptionKey: error,
NSLocalizedFailureReasonErrorKey: error,
NSLocalizedRecoverySuggestionErrorKey: error
])
}
static let invalidContentId = NSError(
domain: "RCTVideo",
code: RCTVideoError.invalidContentId.rawValue,
userInfo: [
NSLocalizedDescriptionKey: "Error obtaining DRM license.",
NSLocalizedFailureReasonErrorKey: "No valide content Id received",
NSLocalizedRecoverySuggestionErrorKey: "Is the contentId and url ok?"
])
}
| mit | 06faf5e0ca9ae417160ae16626342d0a | 39.048544 | 127 | 0.650182 | 6.193694 | false | false | false | false |
binarylevel/Tinylog-iOS | Tinylog/Core Data/TLICoreDataTableViewController.swift | 1 | 6596 | //
// TLICoreDataTableViewController.swift
// Tinylog
//
// Created by Spiros Gerokostas on 17/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
import CoreData
class TLICoreDataTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {
var tableView:UITableView?
var frc:NSFetchedResultsController?
var debug:Bool? = true
var ignoreNextUpdates:Bool = false
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
tableView = UITableView(frame: CGRectZero, style: UITableViewStyle.Plain)
tableView?.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
tableView?.dataSource = self
tableView?.delegate = self
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
deinit {
tableView?.dataSource = nil
tableView?.delegate = nil
}
override func loadView() {
super.loadView()
tableView?.frame = self.view.bounds
self.view.addSubview(tableView!)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView?.flashScrollIndicators()
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
tableView?.setEditing(editing, animated: animated)
}
class func classString() -> String {
return NSStringFromClass(self)
}
func performFetch() {
if debug! {
print("Running \(NSStringFromClass(TLICoreDataTableViewController)) \(NSStringFromSelector(#function))")
}
if self.frc != nil {
self.frc?.managedObjectContext.performBlock({ () -> Void in
do {
try self.frc!.performFetch()
self.tableView?.reloadData()
} catch let error as NSError {
print("Failed to perform fetch \(error)")
}
})
} else {
print("Failed to fetch the NSFetchedResultsController controller is nil")
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MyTestCell")
return cell
}
// MARK: - UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.frc?.sections?.count ?? 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = frc!.sections![section] as NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
/*func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return self.frc?.sections![section].name
}*/
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
}
func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int {
return self.frc!.sectionForSectionIndexTitle(title, atIndex: index)
}
func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? {
return self.frc?.sectionIndexTitles
}
// MARK: - NSFetchedResultsControllerDelegate
func controllerWillChangeContent(controller: NSFetchedResultsController) {
if ignoreNextUpdates {
return
}
self.tableView?.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
if ignoreNextUpdates {
return
}
switch type {
case NSFetchedResultsChangeType.Insert:
self.tableView?.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
break;
case NSFetchedResultsChangeType.Delete:
self.tableView?.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
break;
default:
return
}
}
func controller(controller: NSFetchedResultsController,
didChangeObject anObject: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?) {
if ignoreNextUpdates {
return
}
switch(type) {
case .Insert:
if let newIndexPath = newIndexPath {
tableView?.insertRowsAtIndexPaths([newIndexPath],
withRowAnimation:UITableViewRowAnimation.Fade)
}
case .Delete:
if let indexPath = indexPath {
tableView?.deleteRowsAtIndexPaths([indexPath],
withRowAnimation: UITableViewRowAnimation.Fade)
}
case .Update:
if let indexPath = indexPath {
if let cell = tableView!.cellForRowAtIndexPath(indexPath) {
self.configureCell(cell, atIndexPath: indexPath)
}
}
case .Move:
if let indexPath = indexPath {
if let newIndexPath = newIndexPath {
tableView?.deleteRowsAtIndexPaths([indexPath],
withRowAnimation: UITableViewRowAnimation.Fade)
tableView?.insertRowsAtIndexPaths([newIndexPath],
withRowAnimation: UITableViewRowAnimation.Fade)
}
}
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
if ignoreNextUpdates {
ignoreNextUpdates = false
} else {
self.tableView?.endUpdates()
}
}
}
| mit | e668a36d5c961542f71fb86747255dbd | 32.647959 | 195 | 0.601971 | 6.409135 | false | false | false | false |
ATFinke-Productions/Steppy-2 | SwiftSteppy/View Controllers/Modal/STPYAboutViewController.swift | 1 | 3180 | //
// STPYAboutViewController.swift
// SwiftSteppy
//
// Created by Andrew Finke on 1/12/15.
// Copyright (c) 2015 Andrew Finke. All rights reserved.
//
import UIKit
class STPYAboutViewController: STPYModalViewController {
//MARK: Outlets
@IBOutlet weak var gameCenterButton, sourceCodeButton, websiteButton, visitWebsite: UIButton!
@IBOutlet weak var versionLabel: UILabel!
//MARK: Loading
override func viewDidLoad() {
super.viewDidLoad()
configureButtons([gameCenterButton,sourceCodeButton,websiteButton])
loadMenuBarButtonItem()
loadLocalization()
loadVersionLabel()
// Do any additional setup after loading the view.
}
/**
Loads the localized strings for the labels
*/
func loadLocalization() {
self.navigationItem.title = NSLocalizedString("About Title", comment: "")
sourceCodeButton.setTitle(NSLocalizedString("Source Code Button", comment: ""), forState: .Normal)
websiteButton.setTitle(NSLocalizedString("Website Button", comment: ""), forState: .Normal)
loadGameCenterButton()
}
/**
Loads the version label with the build infomation
*/
func loadVersionLabel() {
let build: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"]
let version: AnyObject? = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]
versionLabel.text = "\(version!) (\(build!))"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Game Center
/**
Loads the Game Center button based on user preference
*/
func loadGameCenterButton() {
if STPYDataHelper.key("GKEnabled") {
gameCenterButton.setTitle(NSLocalizedString("Game Center Disable", comment: "")
, forState: UIControlState.Normal)
}
else {
gameCenterButton.setTitle(NSLocalizedString("Setup GC Title", comment: "")
, forState: UIControlState.Normal)
}
}
/**
Called when the user presses the Game Center button
*/
@IBAction func toggleGameCenter(sender: AnyObject) {
let enabled = STPYDataHelper.key("GKEnabled")
STPYDataHelper.keyIs(!enabled, key: "GKEnabled")
if !enabled {
STPYHKManager.sharedInstance.gkHelper.authenticate(self, completion: { (authenticated) -> Void in
})
}
self.loadGameCenterButton()
}
//MARK: Websites
/**
Called when the user presses the source code button
*/
@IBAction func viewSourceCode(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://atfinke-productions.github.io/Steppy-2/?utm_source=App&utm_medium=About&utm_campaign=App")!)
}
/**
Called when the user presses the website button
*/
@IBAction func visitWebsite(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://www.atfinkeproductions.com")!)
}
}
| mit | 19c1e36271ceab0b8f75bd1153b423c1 | 31.44898 | 164 | 0.647484 | 4.984326 | false | false | false | false |
kesun421/firefox-ios | Client/Frontend/Widgets/HistoryBackButton.swift | 10 | 2490 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import SnapKit
import Shared
private struct HistoryBackButtonUX {
static let HistoryHistoryBackButtonHeaderChevronInset: CGFloat = 10
static let HistoryHistoryBackButtonHeaderChevronSize: CGFloat = 20
static let HistoryHistoryBackButtonHeaderChevronLineWidth: CGFloat = 3.0
}
class HistoryBackButton: UIButton {
lazy var title: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
label.text = Strings.HistoryBackButtonTitle
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronLineWidth
return chevron
}()
lazy var topBorder: UIView = self.createBorderView()
lazy var bottomBorder: UIView = self.createBorderView()
override init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = true
addSubview(topBorder)
addSubview(chevron)
addSubview(title)
backgroundColor = UIColor.white
chevron.snp.makeConstraints { make in
make.leading.equalTo(self).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
make.size.equalTo(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronSize)
}
title.snp.makeConstraints { make in
make.leading.equalTo(chevron.snp.trailing).offset(HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.trailing.greaterThanOrEqualTo(self).offset(-HistoryBackButtonUX.HistoryHistoryBackButtonHeaderChevronInset)
make.centerY.equalTo(self)
}
topBorder.snp.makeConstraints { make in
make.leading.trailing.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
}
fileprivate func createBorderView() -> UIView {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | 92a664a00554fd1789ebde9e01205b77 | 34.571429 | 125 | 0.698394 | 5.220126 | false | false | false | false |
janukobytsch/cardiola | Pods/Swinject/Swinject/iOS-tvOS/SwinjectStoryboard.swift | 2 | 4915 | //
// SwinjectStoryboard.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/31/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import UIKit
/// The `SwinjectStoryboard` provides the features defined by its super class `UIStoryboard`,
/// with dependencies of view controllers injected.
///
/// To specify a registration name of a view controller registered to the `Container` as a service type,
/// add a user defined runtime attribute with the following settings:
///
/// - Key Path: `swinjectRegistrationName`
/// - Type: String
/// - Value: Registration name to the `Container`
///
/// in User Defined Runtime Attributes section on Indentity Inspector pane.
/// If no name is supplied to the registration, no runtime attribute should be specified.
public class SwinjectStoryboard: _SwinjectStoryboardBase, SwinjectStoryboardType {
/// A shared container used by SwinjectStoryboard instances that are instantiated without specific containers.
///
/// Typical usecases of this property are:
/// - Implicit instantiation of UIWindow and its root view controller from "Main" storyboard.
/// - Storyboard references to transit from a storyboard to another.
public static var defaultContainer = Container()
// Boxing to workaround a runtime error [Xcode 7.1.1 and Xcode 7.2 beta 4]
// If container property is Resolvable type and a Resolvable instance is assigned to the property,
// the program crashes by EXC_BAD_ACCESS, which looks a bug of Swift.
private var container: Box<Resolvable>!
/// Do NOT call this method explicitly. It is designed to be called by the runtime.
public override class func initialize() {
struct Static {
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
if SwinjectStoryboard.respondsToSelector("setup") {
SwinjectStoryboard.performSelector("setup")
}
}
}
private override init() {
super.init()
}
/// Creates the new instance of `SwinjectStoryboard`. This method is used instead of an initializer.
///
/// - Parameters:
/// - name: The name of the storyboard resource file without the filename extension.
/// - bundle: The bundle containing the storyboard file and its resources. Specify nil to use the main bundle.
/// - container: The container with registrations of the view controllers in the storyboard and their dependencies.
/// The shared singleton container `SwinjectStoryboard.defaultContainer` is used if no container is passed.
///
/// - Returns: The new instance of `SwinjectStoryboard`.
public class func create(
name name: String,
bundle storyboardBundleOrNil: NSBundle?,
container: Resolvable = SwinjectStoryboard.defaultContainer) -> SwinjectStoryboard
{
// Use this factory method to create an instance because the initializer of UIStoryboard is "not inherited".
let storyboard = SwinjectStoryboard._create(name, bundle: storyboardBundleOrNil)
storyboard.container = Box(container)
return storyboard
}
/// Instantiates the view controller with the specified identifier.
/// The view controller and its child controllers have their dependencies injected
/// as specified in the `Container` passed to the initializer of the `SwinjectStoryboard`.
///
/// - Parameter identifier: The identifier set in the storyboard file.
///
/// - Returns: The instantiated view controller with its dependencies injected.
public override func instantiateViewControllerWithIdentifier(identifier: String) -> UIViewController {
let viewController = super.instantiateViewControllerWithIdentifier(identifier)
injectDependency(viewController)
return viewController
}
private func injectDependency(viewController: UIViewController) {
let registrationName = viewController.swinjectRegistrationName
// Xcode 7.1 workaround for Issue #10. This workaround is not necessary with Xcode 7.
// The actual controller type is distinguished by the dynamic type name in `nameWithActualType`.
//
// If a future update of Xcode fixes the problem, replace the resolution with the following code and fix registerForStoryboard too:
// container.resolve(viewController.dynamicType, argument: viewController as Container.Controller, name: registrationName)
let nameWithActualType = String(reflecting: viewController.dynamicType) + ":" + (registrationName ?? "")
container.value.resolve(Container.Controller.self, name: nameWithActualType, argument: viewController as Container.Controller)
for child in viewController.childViewControllers {
injectDependency(child)
}
}
}
| mit | 864b5e264fd72890b14e0e054c8eb5a1 | 48.14 | 139 | 0.706553 | 5.4 | false | false | false | false |
hollance/swift-algorithm-club | Palindromes/Palindromes.playground/Sources/Palindrome.swift | 3 | 1328 | import Foundation
/**
Validate that a string is a plaindrome
- parameter str: The string to validate
- returns: `true` if string is plaindrome, `false` if string is not
*/
public func isPalindrome(_ str: String) -> Bool {
let strippedString = str.replacingOccurrences(of: "\\W", with: "", options: .regularExpression, range: nil)
let length = strippedString.count
if length > 1 {
return palindrome(strippedString.lowercased(), left: 0, right: length - 1)
}
return false
}
/**
Compares a strings left side character against right side character following
- parameter str: The string to compare characters of
- parameter left: Index of left side to compare, must be less than or equal to right
- parameter right: Index of right side to compare, must be greater than or equal to left
- returns: `true` if left side and right side have all been compared and they all match, `false` if a left and right aren't equal
*/
private func palindrome(_ str: String, left: Int, right: Int) -> Bool {
if left >= right {
return true
}
let lhs = str[str.index(str.startIndex, offsetBy: left)]
let rhs = str[str.index(str.startIndex, offsetBy: right)]
if lhs != rhs {
return false
}
return palindrome(str, left: left + 1, right: right - 1)
}
| mit | a1d45f95f2c3c5779bb12c63a6968917 | 33.947368 | 130 | 0.677711 | 4.137072 | false | false | false | false |
kdw9/TIY-Assignments | In_Due_Time/In_Due_Time/CounterTableViewController.swift | 1 | 5179 | //
// CounterTableViewController.swift
// In_Due_Time
//
// Created by Keron Williams on 10/20/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
class CounterTableViewController: UITableViewController, UITextFieldDelegate
{
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var todoList = Array<TheList>()
let checkImg = UIImage (contentsOfFile: "checkbutton.png")
let unCheckImg = UIImage (contentsOfFile: "unchecked.png")
override func viewDidLoad() {
super.viewDidLoad()
title = "To Do List"
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// #warning Incomplete implementation, return the number of rows
return todoList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TodoCell", forIndexPath: indexPath) as! TodoCell
// Configure the cell...
let aListItem = todoList[indexPath.row]
if aListItem.title == nil
{
cell.listTitleTextField.becomeFirstResponder()
}
else
{
cell.listTitleTextField.text = aListItem.title; resignFirstResponder()
}
// I need to put a for in loop here to make the button work.
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
// MARK: UITextField Delegate
func textFieldShouldReturn(textField: UITextField) -> Bool
{
var rc = false
if textField.text != ""
{
rc = true
let contentView = textField.superview
let cell = contentView?.superview as! TodoCell
let indexPath = tableView.indexPathForCell(cell)
let aListItem = todoList[indexPath!.row]
aListItem.title = textField.text
textField.resignFirstResponder()
saveContext()
}
return rc
}
// MARK: - Action Handlers
@IBAction func addToList(sender: UIBarButtonItem)
{
let aListItem = NSEntityDescription.insertNewObjectForEntityForName("TheList", inManagedObjectContext: managedObjectContext) as! TheList
todoList.append(aListItem)
tableView.reloadData()
}
// MARK: - Private
func saveContext()
{
do{
try managedObjectContext.save()
}
catch{
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
| cc0-1.0 | b626a51a0295ebf4c9dc22266a8d41b0 | 31.566038 | 157 | 0.653148 | 5.579741 | false | false | false | false |
Parallels-MIPT/Coconut-Kit | CoconutKit/CoconutKit/ConflictSolutionManager.swift | 1 | 1675 | //
// ConflictSolutionManager.swift
// ICDocumentsSync-IOS
//
// Created by Alexander Malyshev on 26.08.15.
// Copyright (c) 2015 SecurityQQ. All rights reserved.
//
import Foundation
@objc public class ConflictSolutionManager: NSObject {
public let conflictSolutionClosure: NSURL -> Void
public static let defaultManager: ConflictSolutionManager = {
let defaultConflictSolution: (NSURL) -> Void = { (url) in
if let versions = NSFileVersion.unresolvedConflictVersionsOfItemAtURL(url) {
let lastVersion = versions.reduce(versions[0]) { ($0.modificationDate?.compare($1.modificationDate!) == .OrderedAscending) ? $1 : $0 }
do {
try lastVersion.replaceItemAtURL(url, options: NSFileVersionReplacingOptions.ByMoving)
} catch {
}
for version : NSFileVersion in versions {
if (version != lastVersion) {
do {
try version.remove()
} catch {
}
}
}
}
}
let manager = ConflictSolutionManager(conflictSolutionClosure: defaultConflictSolution)
return manager
}()
public init(conflictSolutionClosure: (NSURL -> Void)) {
self.conflictSolutionClosure = conflictSolutionClosure
}
public func solveConflictAtURL(itemURL: NSURL) {
conflictSolutionClosure(itemURL)
}
} | apache-2.0 | 7da2cd1328d5a1ecba51813d77129fcc | 33.204082 | 154 | 0.532537 | 5.697279 | false | false | false | false |
makeandbuild/watchkit-activity-builder | ActivityBuilder/ActivityDetailController.swift | 1 | 4510 | //
// ActivityDetailController.swift
// ActivityBuilder
//
// Created by Lindsay Thurmond on 2/26/15.
// Copyright (c) 2015 Make and Build. All rights reserved.
//
import UIKit
import WatchCoreDataProxy
/**
* Used for creating and editing activities
*/
class ActivityDetailController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let stepCellIdentifier = "StepCell"
var activity:Activity?
var steps:[Step] = [Step]()
@IBOutlet weak var nameField: UITextField!
@IBOutlet weak var addStepButton: UIButton!
@IBOutlet weak var table: UITableView!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.title = activity == nil ? "Add Activity" : "Edit Activity"
nameField.text = activity?.name ?? ""
enableAddStepIfNecessary()
if activity?.steps != nil {
// steps = activity!.steps.allObjects as! [Step]
steps = activity!.stepsSortedByNumber()
} else {
steps = [Step]()
}
self.table.reloadData()
}
@IBAction func doneButtonTapped(sender: AnyObject) {
println("Done button tapped")
saveActivity()
self.navigationController?.popToRootViewControllerAnimated(true)
}
func saveActivity() {
if activity == nil {
// create a new activity
activity = ActivityManager.createActivity(nameField.text, category: "", details: "", steps: nil)
} else {
// update existing activity
activity?.name = nameField.text
DataManager.saveManagedContext()
}
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
// view.endEditing(true)
// auto-save activity
if (!nameField.text.isEmpty) {
saveActivity()
}
enableAddStepIfNecessary()
super.touchesBegan(touches, withEvent: event)
}
func enableAddStepIfNecessary() {
var addStepsEnabled = !nameField.text.isEmpty
addStepButton.enabled = addStepsEnabled
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return steps.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(stepCellIdentifier, forIndexPath: indexPath) as! UITableViewCell
let row = indexPath.row
var step = steps[row]
cell.textLabel?.text = step.name
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
var deletedStep = steps.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
StepManager.deleteStep(deletedStep)
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var stepDetailController:StepDetailController = segue.destinationViewController as! StepDetailController
if (segue.identifier == "addStep") {
if (activity == nil) {
saveActivity()
}
stepDetailController.activity = activity
} else if (segue.identifier == "stepDetail") {
var selectedIndexPath:NSIndexPath = self.table.indexPathForSelectedRow()!
stepDetailController.step = steps[selectedIndexPath.row]
}
}
func showValidationError() {
let alertController = UIAlertController(title: "Validation Error", message:
"Activity Name is Required", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| apache-2.0 | a934987a752865c89c054a9aab1aa5cf | 29.268456 | 148 | 0.621064 | 5.616438 | false | false | false | false |
rodrigoruiz/SwiftUtilities | SwiftUtilities/Cocoa/PageViewController.swift | 1 | 2083 | //
// PageViewController.swift
// SwiftUtilities
//
// Created by Rodrigo Ruiz on 5/3/17.
// Copyright © 2017 Rodrigo Ruiz. All rights reserved.
//
open class PageViewController: UIPageViewController, UIPageViewControllerDataSource {
public var orderedViewControllers = [UIViewController]() {
didSet {
if orderedViewControllers.count == 0 {
return
}
setViewControllers(
[orderedViewControllers[0]],
direction: .forward,
animated: true,
completion: nil
)
}
}
open override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
}
// MARK: - UIPageViewControllerDataSource
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return nil
}
return orderedViewControllers[previousIndex]
}
public func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = orderedViewControllers.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard nextIndex < orderedViewControllers.count else {
return nil
}
return orderedViewControllers[nextIndex]
}
public func presentationCount(for pageViewController: UIPageViewController) -> Int {
return orderedViewControllers.count
}
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return 0
}
}
| mit | b0d86575547dc9cdf35f80ba082477e2 | 28.742857 | 156 | 0.617675 | 6.82623 | false | false | false | false |
iCrany/iOSExample | iOSExample/Module/CoreTextExample/VC/ICLabelBenchmarkVC.swift | 1 | 2132 | //
// ICLabelBenchmarkVC.swift
// iOSExample
//
// Created by iCrany on 2018/10/11.
// Copyright © 2018 iCrany. All rights reserved.
//
import Foundation
//swiftlint:disable force_cast
class ICLabelBenchmarkVC: UIViewController {
private lazy var dataList: [String] = {
var list: [String] = []
for i in 0..<1000 {
list.append("\(i)-new-😁😁😁😁😁😁😀😀😀😀😀🧀🧀🧀🧀🥔🥔🥔🥔🥔🥔🥔🥔🥔🥔🥔🍑🍑🍑🍎🍎🍎🍎🍎🍏🍏🍏🍏🍏( ̄︶ ̄)↗( ̄︶ ̄)↗( ̄︶ ̄)↗( ̄︶ ̄)↗[]~( ̄▽ ̄)~*")
}
return list
}()
private lazy var tableView: UITableView = {
let v = UITableView(frame: .zero, style: .plain)
v.delegate = self
v.dataSource = self
v.register(ICBenchMarkCell.self, forCellReuseIdentifier: "ICBenchMarkCell")
return v
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init() {
super.init(nibName: nil, bundle: nil)
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { (maker) in
maker.top.equalToSuperview().offset(84)
maker.left.right.bottom.equalToSuperview()
}
}
}
extension ICLabelBenchmarkVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let str = self.dataList[indexPath.row]
let cell: ICBenchMarkCell = tableView.dequeueReusableCell(withIdentifier: "ICBenchMarkCell") as! ICBenchMarkCell
cell.update(str: str)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let str = self.dataList[indexPath.row]
return ICBenchMarkCell.getCellSize(str: str).height
}
}
| mit | 34c9c46e6f703ca9d693296061d1536e | 29.625 | 120 | 0.622959 | 3.828125 | false | false | false | false |
temchik2004/tapper | tapper-extreme/ViewController.swift | 1 | 1592 | //
// ViewController.swift
// tapper-extreme
//
// Created by Admin on 28.12.15.
// Copyright © 2015 Admin. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var maxTaps: UInt = 0
var currentTaps: UInt = 0
@IBOutlet weak var logoImg: UIImageView!
@IBOutlet weak var howManyTapsTXT: UITextField!
@IBOutlet weak var playBtn: UIButton!
@IBOutlet weak var tapBtn: UIButton!
@IBOutlet weak var tapsLbl: UILabel!
@IBAction func onPlayBtnPressed(sender: UIButton!) {
if howManyTapsTXT.text != nil && howManyTapsTXT.text != "" {
logoImg.hidden = true
playBtn.hidden = true
howManyTapsTXT.hidden = true
tapBtn.hidden = false
tapsLbl.hidden = false
maxTaps = UInt(howManyTapsTXT.text!)!
currentTaps = 0
updateTabsLbl()
}
}
@IBAction func onCoinTapped(sender: UIButton!){
++currentTaps
updateTabsLbl()
if isGameOver(){
restartGame()
}
}
func isGameOver() -> Bool {
return currentTaps >= maxTaps
}
func updateTabsLbl() {
tapsLbl.text = "\(currentTaps) Taps"
}
func restartGame() {
maxTaps = 0
howManyTapsTXT.text = ""
logoImg.hidden = false
playBtn.hidden = false
howManyTapsTXT.hidden = false
tapBtn.hidden = true
tapsLbl.hidden = true
}
}
| apache-2.0 | 91071048bb96254af84bff55f40103af | 20.794521 | 68 | 0.543683 | 5.03481 | false | false | false | false |
hooman/swift | stdlib/private/StdlibUnittest/RaceTest.swift | 5 | 21381 | //===--- RaceTest.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// This file implements support for race tests.
///
/// Race test harness executes the given operation in multiple threads over a
/// set of shared data, trying to ensure that executions overlap in time.
///
/// The name "race test" does not imply that the race actually happens in the
/// harness or in the operation being tested. The harness contains all the
/// necessary synchronization for its own data, and for publishing test data to
/// threads. But if the operation under test is, in fact, racy, it should be
/// easier to discover the bug in this environment.
///
/// Every execution of a race test is called a trial. During a single trial
/// the operation under test is executed multiple times in each thread over
/// different data items (`RaceData` instances). Different threads process
/// data in different order. Choosing an appropriate balance between the
/// number of threads and data items, the harness uses the birthday paradox to
/// increase the probability of "collisions" between threads.
///
/// After performing the operation under test, the thread should observe the
/// data in a test-dependent way to detect if presence of other concurrent
/// actions disturbed the result. The observation should be as short as
/// possible, and the results should be returned as `Observation`. Evaluation
/// (cross-checking) of observations is deferred until the end of the trial.
///
//===----------------------------------------------------------------------===//
import SwiftPrivate
import SwiftPrivateLibcExtras
import SwiftPrivateThreadExtras
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
import WinSDK
#endif
#if _runtime(_ObjC)
import ObjectiveC
#else
func autoreleasepool(invoking code: () -> Void) {
// Native runtime does not have autorelease pools. Execute the code
// directly.
code()
}
#endif
/// Race tests that need a fresh set of data for every trial should implement
/// this protocol.
///
/// All racing threads execute the same operation, `thread1`.
///
/// Types conforming to this protocol should be structs. (The type
/// should be a struct to reduce unnecessary reference counting during
/// the test.) The types should be stateless.
public protocol RaceTestWithPerTrialData {
/// Input for threads.
///
/// This type should be a class. (The harness will not pass struct instances
/// between threads correctly.)
associatedtype RaceData : AnyObject
/// Type of thread-local data.
///
/// Thread-local data is newly created for every trial.
associatedtype ThreadLocalData
/// Results of the observation made after performing an operation.
associatedtype Observation
init()
/// Creates a fresh instance of `RaceData`.
func makeRaceData() -> RaceData
/// Creates a fresh instance of `ThreadLocalData`.
func makeThreadLocalData() -> ThreadLocalData
/// Performs the operation under test and makes an observation.
func thread1(
_ raceData: RaceData, _ threadLocalData: inout ThreadLocalData) -> Observation
/// Evaluates the observations made by all threads for a particular instance
/// of `RaceData`.
func evaluateObservations(
_ observations: [Observation],
_ sink: (RaceTestObservationEvaluation) -> Void)
}
/// The result of evaluating observations.
///
/// Case payloads can carry test-specific data. Results will be grouped
/// according to it.
public enum RaceTestObservationEvaluation : Equatable, CustomStringConvertible {
/// Normal 'pass'.
case pass
/// An unusual 'pass'.
case passInteresting(String)
/// A failure.
case failure
case failureInteresting(String)
public var description: String {
switch self {
case .pass:
return "Pass"
case .passInteresting(let s):
return "Pass(\(s))"
case .failure:
return "Failure"
case .failureInteresting(let s):
return "Failure(\(s))"
}
}
}
public func == (
lhs: RaceTestObservationEvaluation, rhs: RaceTestObservationEvaluation
) -> Bool {
switch (lhs, rhs) {
case (.pass, .pass),
(.failure, .failure):
return true
case (.passInteresting(let s1), .passInteresting(let s2)):
return s1 == s2
default:
return false
}
}
/// An observation result that consists of one `UInt`.
public struct Observation1UInt : Equatable, CustomStringConvertible {
public var data1: UInt
public init(_ data1: UInt) {
self.data1 = data1
}
public var description: String {
return "(\(data1))"
}
}
public func == (lhs: Observation1UInt, rhs: Observation1UInt) -> Bool {
return lhs.data1 == rhs.data1
}
/// An observation result that consists of four `UInt`s.
public struct Observation4UInt : Equatable, CustomStringConvertible {
public var data1: UInt
public var data2: UInt
public var data3: UInt
public var data4: UInt
public init(_ data1: UInt, _ data2: UInt, _ data3: UInt, _ data4: UInt) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4))"
}
}
public func == (lhs: Observation4UInt, rhs: Observation4UInt) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4
}
/// An observation result that consists of three `Int`s.
public struct Observation3Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public init(_ data1: Int, _ data2: Int, _ data3: Int) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
}
public var description: String {
return "(\(data1), \(data2), \(data3))"
}
}
public func == (lhs: Observation3Int, rhs: Observation3Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3
}
/// An observation result that consists of four `Int`s.
public struct Observation4Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public init(_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4))"
}
}
public func == (lhs: Observation4Int, rhs: Observation4Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4
}
/// An observation result that consists of five `Int`s.
public struct Observation5Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public var data5: Int
public init(
_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int, _ data5: Int
) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
self.data5 = data5
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4), \(data5))"
}
}
public func == (lhs: Observation5Int, rhs: Observation5Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4 &&
lhs.data5 == rhs.data5
}
/// An observation result that consists of nine `Int`s.
public struct Observation9Int : Equatable, CustomStringConvertible {
public var data1: Int
public var data2: Int
public var data3: Int
public var data4: Int
public var data5: Int
public var data6: Int
public var data7: Int
public var data8: Int
public var data9: Int
public init(
_ data1: Int, _ data2: Int, _ data3: Int, _ data4: Int,
_ data5: Int, _ data6: Int, _ data7: Int, _ data8: Int,
_ data9: Int
) {
self.data1 = data1
self.data2 = data2
self.data3 = data3
self.data4 = data4
self.data5 = data5
self.data6 = data6
self.data7 = data7
self.data8 = data8
self.data9 = data9
}
public var description: String {
return "(\(data1), \(data2), \(data3), \(data4), \(data5), \(data6), \(data7), \(data8), \(data9))"
}
}
public func == (lhs: Observation9Int, rhs: Observation9Int) -> Bool {
return
lhs.data1 == rhs.data1 &&
lhs.data2 == rhs.data2 &&
lhs.data3 == rhs.data3 &&
lhs.data4 == rhs.data4 &&
lhs.data5 == rhs.data5 &&
lhs.data6 == rhs.data6 &&
lhs.data7 == rhs.data7 &&
lhs.data8 == rhs.data8 &&
lhs.data9 == rhs.data9
}
/// A helper that is useful to implement
/// `RaceTestWithPerTrialData.evaluateObservations()` in race tests.
public func evaluateObservationsAllEqual<T : Equatable>(_ observations: [T])
-> RaceTestObservationEvaluation {
let first = observations.first!
for x in observations {
if x != first {
return .failure
}
}
return .pass
}
struct _RaceTestAggregatedEvaluations : CustomStringConvertible {
var passCount: Int = 0
var passInterestingCount = [String: Int]()
var failureCount: Int = 0
var failureInterestingCount = [String: Int]()
init() {}
mutating func addEvaluation(_ evaluation: RaceTestObservationEvaluation) {
switch evaluation {
case .pass:
passCount += 1
case .passInteresting(let s):
if passInterestingCount[s] == nil {
passInterestingCount[s] = 0
}
passInterestingCount[s] = passInterestingCount[s]! + 1
case .failure:
failureCount += 1
case .failureInteresting(let s):
if failureInterestingCount[s] == nil {
failureInterestingCount[s] = 0
}
failureInterestingCount[s] = failureInterestingCount[s]! + 1
}
}
var isFailed: Bool {
return failureCount != 0 || !failureInterestingCount.isEmpty
}
var description: String {
var result = ""
result += "Pass: \(passCount) times\n"
for desc in passInterestingCount.keys.sorted() {
let count = passInterestingCount[desc]!
result += "Pass \(desc): \(count) times\n"
}
result += "Failure: \(failureCount) times\n"
for desc in failureInterestingCount.keys.sorted() {
let count = failureInterestingCount[desc]!
result += "Failure \(desc): \(count) times\n"
}
return result
}
}
// FIXME: protect this class against false sharing.
class _RaceTestWorkerState<RT : RaceTestWithPerTrialData> {
// FIXME: protect every element of 'raceData' against false sharing.
var raceData: [RT.RaceData] = []
var raceDataShuffle: [Int] = []
var observations: [RT.Observation] = []
}
class _RaceTestSharedState<RT : RaceTestWithPerTrialData> {
var racingThreadCount: Int
var stopNow = _stdlib_AtomicInt(0)
var trialBarrier: _stdlib_Barrier
var trialSpinBarrier = _stdlib_AtomicInt()
var raceData: [RT.RaceData] = []
var workerStates: [_RaceTestWorkerState<RT>] = []
var aggregatedEvaluations: _RaceTestAggregatedEvaluations =
_RaceTestAggregatedEvaluations()
init(racingThreadCount: Int) {
self.racingThreadCount = racingThreadCount
self.trialBarrier = _stdlib_Barrier(threadCount: racingThreadCount + 1)
self.workerStates.reserveCapacity(racingThreadCount)
for _ in 0..<racingThreadCount {
self.workerStates.append(_RaceTestWorkerState<RT>())
}
}
}
func _masterThreadStopWorkers<RT>( _ sharedState: _RaceTestSharedState<RT>) {
// Workers are proceeding to the first barrier in _workerThreadOneTrial.
sharedState.stopNow.store(1)
// Allow workers to proceed past that first barrier. They will then see
// stopNow==true and stop.
sharedState.trialBarrier.wait()
}
func _masterThreadOneTrial<RT>(_ sharedState: _RaceTestSharedState<RT>) {
let racingThreadCount = sharedState.racingThreadCount
let raceDataCount = racingThreadCount * racingThreadCount
let rt = RT()
sharedState.raceData.removeAll(keepingCapacity: true)
sharedState.raceData.append(contentsOf: (0..<raceDataCount).lazy.map { _ in
rt.makeRaceData()
})
let identityShuffle = Array(0..<sharedState.raceData.count)
sharedState.workerStates.removeAll(keepingCapacity: true)
sharedState.workerStates.append(contentsOf: (0..<racingThreadCount).lazy.map {
_ in
let workerState = _RaceTestWorkerState<RT>()
// Shuffle the data so that threads process it in different order.
let shuffle = identityShuffle.shuffled()
workerState.raceData = scatter(sharedState.raceData, shuffle)
workerState.raceDataShuffle = shuffle
workerState.observations = []
workerState.observations.reserveCapacity(sharedState.raceData.count)
return workerState
})
sharedState.trialSpinBarrier.store(0)
sharedState.trialBarrier.wait()
// Race happens.
sharedState.trialBarrier.wait()
// Collect and compare results.
for i in 0..<racingThreadCount {
let shuffle = sharedState.workerStates[i].raceDataShuffle
sharedState.workerStates[i].raceData =
gather(sharedState.workerStates[i].raceData, shuffle)
sharedState.workerStates[i].observations =
gather(sharedState.workerStates[i].observations, shuffle)
}
if true {
// FIXME: why doesn't the bracket syntax work?
// <rdar://problem/18305718> Array sugar syntax does not work when used
// with associated types
var observations: [RT.Observation] = []
observations.reserveCapacity(racingThreadCount)
for i in 0..<raceDataCount {
for j in 0..<racingThreadCount {
observations.append(sharedState.workerStates[j].observations[i])
}
let sink = { sharedState.aggregatedEvaluations.addEvaluation($0) }
rt.evaluateObservations(observations, sink)
observations.removeAll(keepingCapacity: true)
}
}
}
func _workerThreadOneTrial<RT>(
_ tid: Int, _ sharedState: _RaceTestSharedState<RT>
) -> Bool {
sharedState.trialBarrier.wait()
if sharedState.stopNow.load() == 1 {
return true
}
let racingThreadCount = sharedState.racingThreadCount
let workerState = sharedState.workerStates[tid]
let rt = RT()
var threadLocalData = rt.makeThreadLocalData()
do {
let trialSpinBarrier = sharedState.trialSpinBarrier
_ = trialSpinBarrier.fetchAndAdd(1)
while trialSpinBarrier.load() < racingThreadCount {}
}
// Perform racy operations.
// Warning: do not add any synchronization in this loop, including
// any implicit reference counting of shared data.
for raceData in workerState.raceData {
workerState.observations.append(rt.thread1(raceData, &threadLocalData))
}
sharedState.trialBarrier.wait()
return false
}
/// One-shot sleep in one thread, allowing interrupt by another.
#if os(Windows)
class _InterruptibleSleep {
let event: HANDLE?
var completed: Bool = false
init() {
self.event = CreateEventW(nil, true, false, nil)
precondition(self.event != nil)
}
deinit {
CloseHandle(self.event)
}
func sleep(durationInSeconds duration: Int) {
guard completed == false else { return }
let result: DWORD = WaitForSingleObject(event, DWORD(duration * 1000))
precondition(result == WAIT_OBJECT_0)
completed = true
}
func wake() {
guard completed == false else { return }
let result: Bool = SetEvent(self.event)
precondition(result == true)
}
}
#else
class _InterruptibleSleep {
let writeEnd: CInt
let readEnd: CInt
var completed = false
init() {
(readEnd: readEnd, writeEnd: writeEnd, _) = _stdlib_pipe()
}
deinit {
close(readEnd)
close(writeEnd)
}
/// Sleep for durationInSeconds or until another
/// thread calls wake(), whichever comes first.
func sleep(durationInSeconds duration: Int) {
if completed {
return
}
// WebAssembly/WASI on wasm32 is the only 32-bit platform with Int64 time_t,
// needs an explicit conversion to `time_t` because of this.
var timeout = timeval(tv_sec: time_t(duration), tv_usec: 0)
var readFDs = _stdlib_fd_set()
var writeFDs = _stdlib_fd_set()
var errorFDs = _stdlib_fd_set()
readFDs.set(readEnd)
let ret = _stdlib_select(&readFDs, &writeFDs, &errorFDs, &timeout)
precondition(ret >= 0)
completed = true
}
/// Wake the thread in sleep().
func wake() {
if completed { return }
let buffer: [UInt8] = [1]
let ret = write(writeEnd, buffer, 1)
precondition(ret >= 0)
}
}
#endif
#if os(Windows)
typealias ThreadHandle = HANDLE
#else
typealias ThreadHandle = pthread_t
#endif
public func runRaceTest<RT : RaceTestWithPerTrialData>(
_: RT.Type,
trials: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil
) {
let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency())
let sharedState = _RaceTestSharedState<RT>(racingThreadCount: racingThreadCount)
// Alarm thread sets timeoutReached.
// Master thread sees timeoutReached and tells worker threads to stop.
let timeoutReached = _stdlib_AtomicInt(0)
let alarmTimer = _InterruptibleSleep()
let masterThreadBody = {
() -> Void in
for t in 0..<trials {
// Check for timeout.
// _masterThreadStopWorkers must run BEFORE the last _masterThreadOneTrial
// to make the thread coordination barriers work
// but we do want to run at least one trial even if the timeout occurs.
if timeoutReached.load() == 1 && t > 0 {
_masterThreadStopWorkers(sharedState)
break
}
autoreleasepool {
_masterThreadOneTrial(sharedState)
}
}
}
let racingThreadBody = {
(tid: Int) -> Void in
for _ in 0..<trials {
let stopNow = _workerThreadOneTrial(tid, sharedState)
if stopNow { break }
}
}
let alarmThreadBody = {
() -> Void in
guard let timeoutInSeconds = timeoutInSeconds
else { return }
alarmTimer.sleep(durationInSeconds: timeoutInSeconds)
_ = timeoutReached.fetchAndAdd(1)
}
var testTids = [ThreadHandle]()
var alarmTid: ThreadHandle
// Create the master thread.
do {
let (ret, tid) = _stdlib_thread_create_block(masterThreadBody, ())
expectEqual(0, ret)
testTids.append(tid!)
}
// Create racing threads.
for i in 0..<racingThreadCount {
let (ret, tid) = _stdlib_thread_create_block(racingThreadBody, i)
expectEqual(0, ret)
testTids.append(tid!)
}
// Create the alarm thread that enforces the timeout.
do {
let (ret, tid) = _stdlib_thread_create_block(alarmThreadBody, ())
expectEqual(0, ret)
alarmTid = tid!
}
// Join all testing threads.
for tid in testTids {
let (ret, _) = _stdlib_thread_join(tid, Void.self)
expectEqual(0, ret)
}
// Tell the alarm thread to stop if it hasn't already, then join it.
do {
alarmTimer.wake()
let (ret, _) = _stdlib_thread_join(alarmTid, Void.self)
expectEqual(0, ret)
}
let aggregatedEvaluations = sharedState.aggregatedEvaluations
expectFalse(aggregatedEvaluations.isFailed)
print(aggregatedEvaluations)
}
internal func _divideRoundUp(_ lhs: Int, _ rhs: Int) -> Int {
return (lhs + rhs) / rhs
}
public func runRaceTest<RT : RaceTestWithPerTrialData>(
_ test: RT.Type,
operations: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil
) {
let racingThreadCount = threads ?? max(2, _stdlib_getHardwareConcurrency())
// Each trial runs threads^2 operations.
let operationsPerTrial = racingThreadCount * racingThreadCount
let trials = _divideRoundUp(operations, operationsPerTrial)
runRaceTest(test, trials: trials, timeoutInSeconds: timeoutInSeconds,
threads: threads)
}
public func consumeCPU(units amountOfWork: Int) {
for _ in 0..<amountOfWork {
let scale = 16
for _ in 0..<scale {
_blackHole(42)
}
}
}
internal struct ClosureBasedRaceTest : RaceTestWithPerTrialData {
static var thread: () -> Void = {}
class RaceData {}
typealias ThreadLocalData = Void
typealias Observation = Void
func makeRaceData() -> RaceData { return RaceData() }
func makeThreadLocalData() -> Void { return Void() }
func thread1(
_ raceData: RaceData, _ threadLocalData: inout ThreadLocalData
) {
ClosureBasedRaceTest.thread()
}
func evaluateObservations(
_ observations: [Observation],
_ sink: (RaceTestObservationEvaluation) -> Void
) {}
}
public func runRaceTest(
trials: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil,
invoking body: @escaping () -> Void
) {
ClosureBasedRaceTest.thread = body
runRaceTest(ClosureBasedRaceTest.self, trials: trials,
timeoutInSeconds: timeoutInSeconds, threads: threads)
}
public func runRaceTest(
operations: Int,
timeoutInSeconds: Int? = nil,
threads: Int? = nil,
invoking body: @escaping () -> Void
) {
ClosureBasedRaceTest.thread = body
runRaceTest(ClosureBasedRaceTest.self, operations: operations,
timeoutInSeconds: timeoutInSeconds, threads: threads)
}
| apache-2.0 | e30c8d5dea1d980de769767f92266514 | 27.207124 | 103 | 0.681072 | 4.160537 | false | true | false | false |
crossroadlabs/Swirl | Sources/Swirl/Column.swift | 1 | 1542 | //===--- Column.swift ------------------------------------------------------===//
//Copyright (c) 2017 Crossroad Labs s.r.o.
//
//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 Boilerplate
public enum Columns {
case list([String])
case all
}
public protocol Column : Named, ErasedRep {
var table:Table {get}
}
public struct ErasedColumn : Column, Rep {
public typealias Value = Any
public let name:String
public let table:Table
init(name: String, in table: Table) {
self.name = name
self.table = table
}
}
public extension ErasedColumn {
public func bind<T>(_ type:T.Type) -> TypedColumn<T> {
return TypedColumn(name: name, in: table)
}
}
public struct TypedColumn<T> : Column, Rep {
public typealias Value = T
public let name:String
public let table:Table
init(name: String, in table: Table) {
self.name = name
self.table = table
}
}
| apache-2.0 | 4af4bd6ded1062ad21b0b1d0719c0a67 | 26.535714 | 81 | 0.614137 | 4.259669 | false | false | false | false |
dreamsxin/swift | validation-test/compiler_crashers_fixed/27771-swift-typebase-isequal.swift | 11 | 736 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 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
// RUN: not %target-swift-frontend %s -parse
let a{let f=[{func a{class b{struct a{let e=A{a T{class a{class b{class B{let:{{let A{let a{func b{class B{let:{class b{func d{{func a(){let a<A{var b<T{class b{let:{{{}struct d{class b{func a{let f{struct B{class b{struct S{let a{let a=[{let d{var d{{{{{{}}}}}class b{struct d{struct c{{{}}struct c{struct a{{}struct B{class B{let f{let e=a=c
| apache-2.0 | 6582f0fd6642cd345f6239002dcb2947 | 80.777778 | 343 | 0.70788 | 3.105485 | false | false | false | false |
benlangmuir/swift | test/SILOptimizer/default-cmo.swift | 2 | 3882 |
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -O -wmo -Xfrontend -enable-default-cmo -parse-as-library -emit-module -emit-module-path=%t/Submodule.swiftmodule -module-name=Submodule %S/Inputs/cross-module/default-submodule.swift -c -o %t/submodule.o
// RUN: %target-build-swift -O -wmo -Xfrontend -enable-default-cmo -parse-as-library -emit-module -emit-module-path=%t/Module.swiftmodule -module-name=Module -I%t -I%S/Inputs/cross-module %S/Inputs/cross-module/default-module.swift -c -o %t/module.o
// RUN: %target-build-swift -O -wmo -Xfrontend -enable-default-cmo -parse-as-library -emit-tbd -emit-tbd-path %t/ModuleTBD.tbd -emit-module -emit-module-path=%t/ModuleTBD.swiftmodule -module-name=ModuleTBD -I%t -I%S/Inputs/cross-module %S/Inputs/cross-module/default-module.swift -c -o %t/moduletbd.o
// RUN: %target-build-swift -O -wmo -module-name=Main -I%t %s -emit-sil | %FileCheck %s
import Module
import ModuleTBD
// CHECK-LABEL: sil_global public_external [serialized] @$s6Module0A6StructV21publicFunctionPointeryS2icvpZ : $@callee_guaranteed (Int) -> Int = {
// CHECK: %0 = function_ref @$s6Module16incrementByThreeyS2iF
// CHECK-LABEL: sil_global public_external @$s6Module0A6StructV22privateFunctionPointeryS2icvpZ : $@callee_guaranteed (Int) -> Int{{$}}
public func callPublicFunctionPointer(_ x: Int) -> Int {
return Module.ModuleStruct.publicFunctionPointer(x)
}
public func callPrivateFunctionPointer(_ x: Int) -> Int {
return Module.ModuleStruct.privateFunctionPointer(x)
}
// CHECK-LABEL: sil @$s4Main11doIncrementyS2iF
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: } // end sil function '$s4Main11doIncrementyS2iF'
public func doIncrement(_ x: Int) -> Int {
return Module.incrementByThree(x)
}
// CHECK-LABEL: sil @$s4Main19doIncrementWithCallyS2iF
// CHECK: function_ref @$s9Submodule19incrementByOneNoCMOyS2iF
// CHECK: } // end sil function '$s4Main19doIncrementWithCallyS2iF'
public func doIncrementWithCall(_ x: Int) -> Int {
return Module.incrementByThreeWithCall(x)
}
// CHECK-LABEL: sil @$s4Main14doIncrementTBDyS2iF
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: } // end sil function '$s4Main14doIncrementTBDyS2iF'
public func doIncrementTBD(_ x: Int) -> Int {
return ModuleTBD.incrementByThree(x)
}
// CHECK-LABEL: sil @$s4Main22doIncrementTBDWithCallyS2iF
// CHECK: function_ref @$s9ModuleTBD24incrementByThreeWithCallyS2iF
// CHECK: } // end sil function '$s4Main22doIncrementTBDWithCallyS2iF'
public func doIncrementTBDWithCall(_ x: Int) -> Int {
return ModuleTBD.incrementByThreeWithCall(x)
}
// CHECK-LABEL: sil @$s4Main23getSubmoduleKlassMemberSiyF
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: } // end sil function '$s4Main23getSubmoduleKlassMemberSiyF'
public func getSubmoduleKlassMember() -> Int {
return Module.submoduleKlassMember()
}
// CHECK-LABEL: sil @$s4Main26getSubmoduleKlassMemberTBDSiyF
// CHECK: [[F:%[0-9]+]] = function_ref @$s9ModuleTBD20submoduleKlassMemberSiyF
// CHECK: [[I:%[0-9]+]] = apply [[F]]
// CHECK: return [[I]]
// CHECK: } // end sil function '$s4Main26getSubmoduleKlassMemberTBDSiyF'
public func getSubmoduleKlassMemberTBD() -> Int {
return ModuleTBD.submoduleKlassMember()
}
// CHECK-LABEL: sil @$s4Main20getModuleKlassMemberSiyF
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: } // end sil function '$s4Main20getModuleKlassMemberSiyF'
public func getModuleKlassMember() -> Int {
return Module.moduleKlassMember()
}
// CHECK-LABEL: sil @$s4Main23getModuleKlassMemberTBDSiyF
// CHECK-NOT: function_ref
// CHECK-NOT: apply
// CHECK: } // end sil function '$s4Main23getModuleKlassMemberTBDSiyF'
public func getModuleKlassMemberTBD() -> Int {
return ModuleTBD.moduleKlassMember()
}
| apache-2.0 | d68b0455ef043c1b8636459300e24a61 | 42.617978 | 300 | 0.723338 | 3.363951 | false | false | false | false |
loisie123/Cuisine-Project | Cuisine/FavoriteViewController.swift | 1 | 3563 | //
// FavoriteViewController.swift
//
//
// Created by Lois van Vliet on 20-01-17.
// ViewController that shows the favorite meals
//
import UIKit
import Firebase
class FavoriteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var ref: FIRDatabaseReference?
var databaseHandle: FIRDatabaseHandle?
let types = ["Soup", "Sandwich", "Hot dish", "Standard Assortment"]
var listAllNamesFavorites = [[String]]()
var listCategorynameFavorites = [String]()
var listOfMealsFavorites = [meals]()
@IBOutlet weak var FavoriteTableImage: UITableView!
override func viewDidLoad() {
getMealsFavorites()
super.viewDidLoad()
// Define identifier
let reloadTableView = Notification.Name("reloadTableView")
// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(FavoriteViewController.reloadTableView), name: reloadTableView, object: nil)
ref = FIRDatabase.database().reference()
self.FavoriteTableImage.reloadData()
}
//MARK:- Reload tableview
func reloadTableView() {
getMealsFavorites()
FavoriteTableImage.reloadData()
}
//MARK:- Get information from Firebase
func getMealsFavorites(){
let currentUser = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference()
ref.child("users").child(currentUser!).child("likes").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
(self.listAllNamesFavorites, self.listOfMealsFavorites) = self.getMealInformation(snapshot: snapshot, categories: self.types, kindOfCategorie: "type")
self.FavoriteTableImage.reloadData()
})
}
//MARK:- Make tableview with sections
func numberOfSections(in tableView: UITableView) -> Int {
return listAllNamesFavorites.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listAllNamesFavorites[section].count-1
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return listAllNamesFavorites[section][0]
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var returnedView = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 25))
returnedView = makeSectionHeader(returnedView: returnedView, section: section, listAllNames: self.listAllNamesFavorites)
return returnedView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "favoriteCell", for: indexPath) as! FavoriteTableViewCell
for meal in listOfMealsFavorites{
if meal.name == listAllNamesFavorites[indexPath.section][indexPath.row+1] {
cell.nameMeal.text = meal.name
cell.priceFavoriteMeal.text = "\(meal.price!)"
cell.likesFavoriteMeal.text = "\(meal.likes!) likes"
cell.day = meal.day
}
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
| mit | 9c27a1f5e2bb17b55a05103bc278c35e | 32.933333 | 162 | 0.640191 | 5.325859 | false | false | false | false |
coreymason/LAHacks2017 | ios/DreamWell/DreamWell/RecordingViewController.swift | 1 | 4879 | //
// RecordingViewController.swift
// DreamWell
//
// Created by Rohin Bhushan on 4/1/17.
// Copyright © 2017 rohin. All rights reserved.
//
import UIKit
import HCSStarRatingView
import Speech
class RecordingViewController: UIViewController, SFSpeechRecognizerDelegate {
@IBOutlet weak var startRecordingButton: UIButton!
@IBOutlet weak var starView: HCSStarRatingView!
@IBOutlet weak var bottomConstraint: NSLayoutConstraint!
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewHeightConstraint: NSLayoutConstraint!
private let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US"))!
private var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
private var recognitionTask: SFSpeechRecognitionTask?
private let audioEngine = AVAudioEngine()
private var recordedLines = 0
override func viewDidLoad() {
super.viewDidLoad()
//Services.postSleepLogs(text: "hello wassup it worked maddafacka")
// Do any additional setup after loading the view.
speechRecognizer.delegate = self //3
SFSpeechRecognizer.requestAuthorization { (authStatus) in
print(authStatus)
}
startRecordingButton.layer.cornerRadius = 4.0
textView.layoutManager.allowsNonContiguousLayout = false
}
func textViewDidChange(_ textView: UITextView) {
let lines = numberOfLines(textView: textView)
recordedLines = lines
moveTextViewUp()
}
func moveTextViewUp() {
textViewHeightConstraint.constant = CGFloat(30 * recordedLines) + 40.0
let stringLength:Int = self.textView.text.characters.count
self.textView.scrollRangeToVisible(NSMakeRange(stringLength-1, 0))
UIView.animate(withDuration: 0.3) {
self.view.layoutIfNeeded()
}
}
// get number of lines
func numberOfLines(textView: UITextView) -> Int {
let layoutManager = textView.layoutManager
let numberOfGlyphs = layoutManager.numberOfGlyphs
var lineRange: NSRange = NSMakeRange(0, 1)
var index = 0
var numberOfLines = 0
while index < numberOfGlyphs {
layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
index = NSMaxRange(lineRange)
numberOfLines += 1
}
return numberOfLines
}
func showStars() {
self.bottomConstraint.constant += 70
startRecordingButton.isEnabled = false
UIView.animate(withDuration: 1.0) {
self.starView.alpha = 1.0
self.view.layoutIfNeeded()
}
}
@IBAction func starsSet(_ sender: Any) {
if (sender as! UIView).alpha == 1.0 {
startRecordingButton.setTitle("Start Recording", for: UIControlState())
sendText()
textView.text = "Dream Uploaded! Expect results in a few seconds.\n\n"
hideStars()
}
}
func hideStars() {
self.bottomConstraint.constant -= 70
startRecordingButton.isEnabled = true
UIView.animate(withDuration: 1.0, animations: {
self.starView.alpha = 0.0
self.view.layoutIfNeeded()
}) { (succ) in
self.starView.value = 0.0
}
}
@IBAction func startRecording(_ sender: Any) { //button press
if recognitionTask != nil { // stop
recognitionTask?.cancel()
recognitionTask = nil
showStars()
return
}
startRecordingButton.setTitle("Stop Recording", for: UIControlState())
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(AVAudioSessionCategoryRecord)
try audioSession.setMode(AVAudioSessionModeMeasurement)
try audioSession.setActive(true, with: .notifyOthersOnDeactivation)
} catch {
print("audioSession properties weren't set because of an error.")
}
recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let inputNode = audioEngine.inputNode else {
fatalError("Audio engine has no input node")
}
guard let recognitionRequest = recognitionRequest else {
fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object")
}
recognitionRequest.shouldReportPartialResults = true
recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
var isFinal = false
if result != nil {
self.textView.text = result?.bestTranscription.formattedString
self.textViewDidChange(self.textView)
isFinal = (result?.isFinal)!
}
if error != nil || isFinal {
self.audioEngine.stop()
inputNode.removeTap(onBus: 0)
self.recognitionRequest = nil
self.recognitionTask = nil
}
})
let recordingFormat = inputNode.outputFormat(forBus: 0)
inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in
self.recognitionRequest?.append(buffer)
}
audioEngine.prepare()
do {
try audioEngine.start()
} catch {
print("audioEngine couldn't start because of an error.")
}
}
func sendText() {
Services.postSleepLogs(text: textView.text, stars: Int(starView.value * 2.0))
}
}
| mit | e3f311225358a449e5dad50f633cbcd7 | 26.559322 | 114 | 0.732062 | 4.155026 | false | false | false | false |
KevinCoble/AIToolbox | AIToolbox/DeepNetworkOperator.swift | 1 | 3254 | //
// DeepNetworkOperator.swift
// AIToolbox
//
// Created by Kevin Coble on 6/26/16.
// Copyright © 2016 Kevin Coble. All rights reserved.
//
import Foundation
public enum DeepNetworkOperatorType : Int
{
case convolution2DOperation = 0
case poolingOperation
case feedForwardNetOperation
case nonLinearityOperation
public func getString() ->String
{
switch self {
case .convolution2DOperation:
return "2D Convolution"
case .poolingOperation:
return "Pooling"
case .feedForwardNetOperation:
return "FeedForward NN"
case .nonLinearityOperation:
return "NonLinearity"
}
}
public static func getAllTypes() -> [(name: String, type: DeepNetworkOperatorType)]
{
var raw = 0
var results : [(name: String, type: DeepNetworkOperatorType)] = []
while let type = DeepNetworkOperatorType(rawValue: raw) {
results.append((name: type.getString(), type: type))
raw += 1
}
return results
}
public static func getDeepNetworkOperatorFromDict(_ sourceDictionary: [String: AnyObject]) -> DeepNetworkOperator?
{
if let type = sourceDictionary["operatorType"] as? NSInteger {
if let opType = DeepNetworkOperatorType(rawValue: type) {
if let opDefinition = sourceDictionary["operatorDefinition"] as? [String: AnyObject] {
switch opType {
case .convolution2DOperation:
return Convolution2D(fromDictionary: opDefinition)
case .poolingOperation:
return Pooling(fromDictionary: opDefinition)
case .feedForwardNetOperation:
return DeepNeuralNetwork(fromDictionary: opDefinition)
case .nonLinearityOperation:
return DeepNonLinearity(fromDictionary: opDefinition)
}
}
}
}
return nil
}
}
public protocol DeepNetworkOperator : MLPersistence {
func getType() -> DeepNetworkOperatorType
func getDetails() -> String
func getResultingSize(_ inputSize: DeepChannelSize) -> DeepChannelSize
func initializeParameters()
func feedForward(_ inputs: [Float], inputSize: DeepChannelSize) -> [Float]
func getResults() -> [Float]
func getResultSize() -> DeepChannelSize
func getResultRange() ->(minimum: Float, maximum: Float)
func startBatch()
func backPropogateGradient(_ upStreamGradient: [Float]) -> [Float]
func updateWeights(_ trainingRate : Float, weightDecay: Float)
func gradientCheck(ε: Float, Δ: Float, network: DeepNetwork) -> Bool
}
extension DeepNetworkOperator {
public func getOperationPersistenceDictionary() -> [String : AnyObject] {
var resultDictionary : [String: AnyObject] = [:]
// Set the operator type
resultDictionary["operatorType"] = getType().rawValue as AnyObject?
// Set the definition
resultDictionary["operatorDefinition"] = getPersistenceDictionary() as AnyObject?
return resultDictionary
}
}
| apache-2.0 | 9419cb1249bd29c7905c359bbd614b44 | 32.864583 | 118 | 0.622885 | 5.294788 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Requests/Messages/GetMessagesRequest.swift | 1 | 678 | //
// GetMessagesRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/24/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
import Alamofire
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451691
public struct GetMessagesRequest: Request {
public let endpoint: ApiEndpoint = .GetMessages
public var parameters: [String : AnyObject] = [:]
public let account: Account
public let httpMethod: Alamofire.Method = .POST
public init(withAccount account: Account, folder: Mailbox, page: Int) {
self.account = account
self.parameters["folder"] = folder.rawValue
self.parameters["page"] = page
}
}
| mit | 0581fb1d08629c9b46a698098532765e | 25.038462 | 75 | 0.685377 | 4.029762 | false | false | false | false |
byu-osl/city-issue-tracker-ios | City Issue Tracker/City Issue Tracker/Mediator.swift | 1 | 1238 | //
// Mediator.swift
// City Issue Tracker
//
// Created by Joshua Cockrell on 4/8/15.
// Copyright (c) 2015 BYU Open Source Lab. All rights reserved.
//
import Foundation
class Mediator: NSObject
{
var dataModel: DataModel!
var trackerAPI: TrackerAPI!
var subscribers: [Subscriber]!
override init()
{
self.subscribers = []
super.init()
// create the model and api
self.trackerAPI = TrackerAPI(newMediator: self)
self.dataModel = DataModel(newMediator: self)
var event: Event = ReloadServiceRequestsFromServerEvent()
self.postEvent(event)
// start the refresh timer
var refreshTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector:"refreshTimerCalled", userInfo: nil, repeats: true)
}
func registerSubscriber(newSubscriber: Subscriber)
{
subscribers.append(newSubscriber)
}
func refreshTimerCalled()
{
// var event: Event = ReloadServiceRequestsFromServerEvent()
// self.postEvent(event)
}
func postEvent(event: Event)
{
for s in subscribers
{
s.notify(event)
}
}
} | gpl-2.0 | f06efddd3177ba0bc7a3a2ea70440456 | 22.377358 | 144 | 0.61147 | 4.469314 | false | false | false | false |
hydrixos/cloudstatus | Source/Model/TransferStatus.swift | 1 | 546 | //
// TransferStatus.swift
// CloudStatus
//
// Created by Friedrich Gräter on 31/01/16.
// Copyright © 2016 Friedrich Gräter. All rights reserved.
//
enum TransferStatus {
case UpToDate, Uploading, Downloading, Bidirectional, Unknown
func combineWithTransferStatus(transferStatus: TransferStatus) -> TransferStatus {
if (transferStatus == self) {
return self
}
else if (transferStatus == .UpToDate) {
return self
}
else if (self == .UpToDate) {
return transferStatus
}
else {
return .Bidirectional
}
}
}
| bsd-2-clause | 79ec5267b21c90217e77b18afa322398 | 19.884615 | 83 | 0.694291 | 3.525974 | false | false | false | false |
6ag/WeiboSwift-mvvm | WeiboSwift/Classes/View/Main/MainViewController.swift | 1 | 6291 | //
// MainViewController.swift
// WeiboSwift
//
// Created by 周剑峰 on 2017/1/16.
// Copyright © 2017年 周剑峰. All rights reserved.
//
import UIKit
class MainViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
setupChildViewControllers()
setupComposeButton()
delegate = self
// 监听需要用户登录通知
NotificationCenter.default.addObserver(self, selector: #selector(showUserLogin), name: NSNotification.Name(NEED_USER_LOGIN_NOTIFICATION), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// 弹出用户登录界面
@objc private func showUserLogin() {
let nav = UINavigationController(rootViewController: OAuthViewController())
present(nav, animated: true, completion: nil)
}
/// 让所有子控制器只支持竖屏 这个方法是UIViewController中的,会让当前控制器和他所有子控制器都能被限制方向
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
/// 发布微博按钮点击
@objc fileprivate func composeStatus() {
if NetworkManager.shared.isLogin {
let composeTypeView = ComposeTypeView()
composeTypeView.show()
} else {
// 发出请求登录的通知
NotificationCenter.default.post(name: NSNotification.Name(NEED_USER_LOGIN_NOTIFICATION), object: nil)
}
}
/// 发布按钮
fileprivate lazy var composeButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}
// MARK: - 添加子控制器
extension MainViewController {
/// 设置发布按钮
fileprivate func setupComposeButton() {
tabBar.addSubview(composeButton)
let width = tabBar.bounds.width / CGFloat(childViewControllers.count)
composeButton.frame = tabBar.bounds.insetBy(dx: width * 2, dy: 0)
composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
}
/// 设置所有子控制器
fileprivate func setupChildViewControllers() {
let array = [
["clsName" : "HomeViewController",
"title" : "首页",
"imageName" : "home",
"visitorInfo" : [
"imageName" : "",
"message" : "关注一些人,回来看看有什么惊喜"
]
],
["clsName" : "MessageViewController",
"title" : "消息",
"imageName" : "message_center",
"visitorInfo" : [
"imageName" : "visitordiscover_image_message",
"message" : "登录后,别人评论你的微博,发给你的信息,都会在这里收到通知"
]
],
["clsName" : "UIViewController"],
["clsName" : "DiscoverViewController",
"title" : "发现",
"imageName" : "discover",
"visitorInfo" : [
"imageName" : "visitordiscover_image_message",
"message" : "登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过"
]
],
["clsName" : "ProfileViewController",
"title" : "我的",
"imageName" : "profile",
"visitorInfo" : [
"imageName" : "visitordiscover_image_profile",
"message" : "登录后,你的微博、相册、个人资料会显示在这里,展示给别人"
]
]
]
var arrayM = [UIViewController]()
for dict in array {
arrayM.append(controller(dict: dict as [String : AnyObject]))
}
viewControllers = arrayM
}
/// 使用字典创建一个子控制器
///
/// - Parameter dict: 信息字典[clsName, title, imageName]
/// - Returns: 子控制器
private func controller(dict: [String: AnyObject]) -> UIViewController {
guard let clsName = dict["clsName"] as? String,
let title = dict["title"] as? String,
let imageName = dict["imageName"] as? String,
let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type,
let visitorInfo = dict["visitorInfo"] as? [String : String]
else {
return UIViewController()
}
let vc = cls.init()
if let baseVc = vc as? BaseViewController {
baseVc.visitorInfo = visitorInfo
}
vc.title = title
vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)?.withRenderingMode(.alwaysOriginal)
vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
let nav = NavigationController(rootViewController: vc)
return nav
}
}
// MARK: - UITabBarControllerDelegate
extension MainViewController: UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
let currendIndex: Int = childViewControllers.index(of: viewController) ?? 0
let lastIndex = selectedIndex
if currendIndex == 0 && currendIndex == lastIndex {
print("刷新数据")
let nav = childViewControllers[0] as! NavigationController
let homeVc = nav.childViewControllers[0] as! HomeViewController
homeVc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .bottom, animated: true)
// 延迟刷新数据,让列表先滚动等顶部
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.25, execute: {
homeVc.refreshControl?.beginRefreshing()
})
}
return !viewController.isMember(of: UIViewController.classForCoder())
}
}
| mit | e78018a2c01a741d7f4c9cfd870df8ae | 33.392857 | 158 | 0.583766 | 4.99395 | false | false | false | false |
tapglue/snaasSdk-iOS | Sources/Internal/Network.swift | 2 | 18952 | //
// Network.swift
// Tapglue
//
// Created by John Nilsen on 7/5/16.
// Copyright © 2016 Tapglue. All rights reserved.
//
import RxSwift
class Network {
let http = Http()
init() {
}
func loginUser(_ username: String, password:String) -> Observable<User> {
let payload = ["user_name": username, "password": password]
return http.execute(Router.post("/me/login", payload: payload as [String : AnyObject]))
.map { (user:User) in
Router.sessionToken = user.sessionToken ?? ""
return user
}
}
func loginUserWithEmail(_ email: String, password: String) -> Observable<User> {
let payload = ["email": email, "password": password]
return http.execute(Router.post("/me/login", payload: payload as [String : AnyObject]))
.map { (user:User) in
Router.sessionToken = user.sessionToken ?? ""
return user
}
}
func createUser(_ user: User, inviteConnections: String? = nil) -> Observable<User> {
var path = "/users"
if let inviteConnections = inviteConnections {
path = path.appending("?invite-connections=\(inviteConnections)")
}
return http.execute(Router.post(path, payload: user.toJSON() as [String : AnyObject]))
}
func refreshCurrentUser() -> Observable<User> {
return http.execute(Router.get("/me"))
}
func updateCurrentUser(_ user: User) -> Observable<User> {
return http.execute(Router.put("/me", payload: user.toJSON() as [String : AnyObject]))
}
func createInvite(_ key: String, _ value: String) -> Observable<Void> {
let payload = ["key": key, "value": value]
return http.execute(Router.post("/me/invites", payload: payload as [String : AnyObject]))
}
func logout() -> Observable<Void> {
return http.execute(Router.delete("/me/logout"))
}
func deleteCurrentUser() -> Observable<Void> {
return http.execute(Router.delete("/me"))
}
func retrieveUser(_ id: String) -> Observable<User> {
return http.execute(Router.get("/users/" + id))
}
func createConnection(_ connection: Connection) -> Observable<Connection> {
return http.execute(Router.put("/me/connections", payload: connection.toJSON() as [String : AnyObject]))
}
func deleteConnection(toUserId userId: String, type: ConnectionType) -> Observable<Void> {
return http.execute(Router.delete("/me/connections/" + type.rawValue + "/" + userId))
}
func createSocialConnections(_ socialConnections: SocialConnections) -> Observable<[User]> {
return http.execute(Router.post("/me/connections/social",
payload: socialConnections.toJSON() as [String : AnyObject])).map { (feed: UserFeed) in
return feed.users!
}
}
func searchUsers(forSearchTerm term: String) -> Observable<[User]> {
return http.execute(Router.get("/users/search?q=" +
term.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlHostAllowed)!)).map { (feed:UserFeed) in
return feed.users!
}
}
func searchEmails(_ emails: [String]) -> Observable<[User]> {
let payload = ["emails": emails]
return http.execute(Router.post("/users/search/emails", payload: payload as [String : AnyObject])).map { (feed:UserFeed) in
return feed.users!
}
}
func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<[User]> {
let payload = ["ids":ids]
return http.execute(Router.post("/users/search/" + platform, payload: payload as [String : AnyObject])).map {
(feed: UserFeed) in
return feed.users!
}
}
func retrieveFollowers() -> Observable<[User]> {
return http.execute(Router.get("/me/followers")).map { (userFeed:UserFeed) in
return userFeed.users ?? [User]()
}
}
func retrieveFollowings() -> Observable<[User]> {
return http.execute(Router.get("/me/follows")).map { (userFeed:UserFeed) in
return userFeed.users ?? [User]()
}
}
func retrieveFollowersForUserId(_ id: String) -> Observable<[User]> {
return http.execute(Router.get("/users/" + id + "/followers")).map { (userFeed: UserFeed) in
return userFeed.users ?? [User]()
}
}
func retrieveFollowingsForUserId(_ id: String) -> Observable<[User]> {
return http.execute(Router.get("/users/" + id + "/follows")).map { (userFeed:UserFeed) in
return userFeed.users ?? [User]()
}
}
func retrieveFriends() -> Observable<[User]> {
return http.execute(Router.get("/me/friends")).map { (feed: UserFeed) in
return feed.users ?? [User]()
}
}
func retrieveFriendsForUserId(_ id: String) -> Observable<[User]> {
return http.execute(Router.get("/users/" + id + "/friends")).map { (feed: UserFeed) in
return feed.users ?? [User]()
}
}
func retrievePendingConnections() -> Observable<Connections> {
return http.execute(Router.get("/me/connections/pending")).map {
self.convertToConnections($0)
}
}
func retrieveRejectedConnections() -> Observable<Connections> {
return http.execute(Router.get("/me/connections/rejected")).map {
self.convertToConnections($0)
}
}
func createPost(_ post: Post) -> Observable<Post> {
return http.execute(Router.post("/posts", payload: post.toJSON() as [String : AnyObject]))
}
func retrievePost(_ id: String) -> Observable<Post> {
return http.execute(Router.get("/posts/" + id))
}
func updatePost(_ id: String, post: Post) -> Observable<Post> {
return http.execute(Router.put("/posts/" + id, payload: post.toJSON() as [String : AnyObject]))
}
func deletePost(_ id: String) -> Observable<Void> {
return http.execute(Router.delete("/posts/" + id))
}
func retrievePostsByUser(_ userId: String) -> Observable<[Post]> {
return http.execute(Router.get("/users/" + userId + "/posts")).map {
self.mapUserToPost($0)
}
}
func retrieveAllPosts() -> Observable<[Post]> {
return http.execute(Router.get("/posts")).map {
self.mapUserToPost($0)
}
}
func filterPostsByTags(_ tags: [String]) -> Observable<[Post]> {
let tagsObject = PostTagFilter(tags: tags)
let json = "{\"post\":\(tagsObject.toJSONString() ?? "")}"
let query = json.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlHostAllowed) ?? ""
return http.execute(Router.get("/posts?where=" + query)).map {
self.mapUserToPost($0)
}
}
func createComment(_ comment: Comment) -> Observable<Comment> {
return http.execute(Router.post("/posts/" + comment.postId! + "/comments", payload: comment.toJSON() as [String : AnyObject]))
}
func retrieveComments(_ postId: String) -> Observable<[Comment]> {
return http.execute(Router.get("/posts/" + postId + "/comments")).map { (commentFeed:CommentFeed) in
let comments = commentFeed.comments?.map { comment -> Comment in
comment.user = commentFeed.users?[comment.userId ?? ""]
return comment
}
return comments ?? [Comment]()
}
}
func updateComment(_ postId: String, commentId: String, comment: Comment) -> Observable<Comment> {
return http.execute(Router.put("/posts/" + postId + "/comments/" + commentId, payload: comment.toJSON() as [String : AnyObject]))
}
func deleteComment(_ postId: String, commentId: String) -> Observable<Void> {
return http.execute(Router.delete("/posts/" + postId + "/comments/" + commentId))
}
func createLike(forPostId postId: String) -> Observable<Like> {
let like = Like(postId: postId)
return http.execute(Router.post("/posts/" + postId + "/likes", payload: like.toJSON() as [String : AnyObject]))
}
func createReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return http.execute(Router.post("/posts/" + postId + "/reactions/" + reaction.rawValue, payload: [:]))
}
func deleteReaction(_ reaction: Reaction, forPostId postId: String) -> Observable<Void> {
return http.execute(Router.delete("/posts/" + postId + "/reactions/" + reaction.rawValue))
}
func retrieveLikes(_ postId: String) -> Observable<[Like]> {
return http.execute(Router.get("/posts/" + postId + "/likes")).map { (likeFeed:LikeFeed) in
let likes = likeFeed.likes?.map { like -> Like in
like.user = likeFeed.users?[like.userId ?? ""]
return like
}
return likes ?? [Like]()
}
}
func deleteLike(forPostId postId: String) -> Observable<Void> {
return http.execute(Router.delete("/posts/" + postId + "/likes"))
}
func retrieveLikesByUser(_ userId: String) -> Observable<[Like]> {
return http.execute(Router.get("/users/" + userId + "/likes")).map {(likeFeed: LikeFeed) in
let likes = likeFeed.likes?.map { like -> Like in
like.user = likeFeed.users?[like.userId ?? ""]
like.post = likeFeed.posts?[like.postId ?? ""]
return like
}
return likes ?? [Like]()
}
}
func retrieveActivitiesByUser(_ userId: String) -> Observable<[Activity]> {
return retrieveActivitiesOn("/users/" + userId + "/events")
}
func retrievePostFeed() -> Observable<[Post]> {
return http.execute(Router.get("/me/feed/posts")).map {
self.mapUserToPost($0)
}
}
func retrieveActivityFeed() -> Observable<[Activity]> {
return retrieveActivitiesOn("/me/feed/events")
}
func retrieveNewsFeed() -> Observable<NewsFeed> {
return http.execute(Router.get("/me/feed")).map { (feed: NewsFeedEndpoint) in
let newsFeed = NewsFeed()
newsFeed.posts = feed.posts?.map { post -> Post in
post.user = feed.users?[post.userId ?? ""]
return post
}
newsFeed.activities = feed.activities?.map { activity -> Activity in
activity.user = feed.users?[activity.userId ?? ""]
activity.post = feed.postMap?[activity.postId ?? ""]
activity.post?.user = feed.users?[activity.post?.userId ?? ""]
if activity.target?.type == "tg_user" {
activity.targetUser = feed.users?[activity.target!.id ?? ""]
}
return activity
}
return newsFeed
}
}
func retrieveMeFeed() -> Observable<[Activity]> {
return retrieveActivitiesOn("/me/feed/notifications/self")
}
func searchUsers(forSearchTerm term: String) -> Observable<RxPage<User>> {
return http.execute(Router.get("/users/search?q=" +
term.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlHostAllowed)!)).map { (feed:UserFeed) in
return feed.rxPage()
}
}
func searchEmails(_ emails: [String]) -> Observable<RxPage<User>> {
let payload = ["emails": emails]
return http.execute(Router.post("/users/search/emails", payload: payload as [String : AnyObject])).map { (feed:UserFeed) in
return feed.rxPage()
}
}
func searchSocialIds(_ ids: [String], onPlatform platform: String) ->
Observable<RxPage<User>> {
let payload = ["ids":ids]
return http.execute(Router.post("/users/search/" + platform, payload: payload as [String : AnyObject])).map {
(feed: UserFeed) in
return feed.rxPage()
}
}
func createSocialConnections(_ socialConnections: SocialConnections) -> Observable<RxPage<User>>{
return http.execute(Router.post("/me/connections/social",
payload: socialConnections.toJSON() as [String : AnyObject])).map { (feed: UserFeed) in
return feed.rxPage(socialConnections.toJSON() as [String : AnyObject])
}
}
func retrieveFollowers() -> Observable<RxPage<User>> {
return http.execute(Router.get("/me/followers")).map { (feed:UserFeed) in
return feed.rxPage()
}
}
func retrieveFollowings() -> Observable<RxPage<User>> {
return http.execute(Router.get("/me/follows")).map { (feed:UserFeed) in
return feed.rxPage()
}
}
func retrieveFollowersForUserId(_ id: String) -> Observable<RxPage<User>> {
return http.execute(Router.get("/users/" + id + "/followers")).map { (feed:UserFeed) in
return feed.rxPage()
}
}
func retrieveFollowingsForUserId(_ id: String) -> Observable<RxPage<User>> {
return http.execute(Router.get("/users/" + id + "/follows")).map { (feed: UserFeed) in
return feed.rxPage()
}
}
func retrieveFriends() -> Observable<RxPage<User>> {
return http.execute(Router.get("/me/friends")).map { (feed: UserFeed) in
return feed.rxPage()
}
}
func retrieveFriendsForUserId(_ id: String) -> Observable<RxPage<User>> {
return http.execute(Router.get("/users/" + id + "/friends")).map { (feed: UserFeed) in
return feed.rxPage()
}
}
func retrievePendingConnections() -> Observable<RxCompositePage<Connections>> {
return http.execute(Router.get("/me/connections/pending")).map { (feed:ConnectionsFeed) in
return feed.rxPage()
}
}
func retrieveRejectedConnections() -> Observable<RxCompositePage<Connections>> {
return http.execute(Router.get("/me/connections/rejected")).map { (feed:ConnectionsFeed) in
return feed.rxPage()
}
}
func retrievePostsByUser(_ userId: String) -> Observable<RxPage<Post>> {
return http.execute(Router.get("/users/" + userId + "/posts")).map { (feed:PostFeed) in
return feed.rxPage()
}
}
func retrieveAllPosts() -> Observable<RxPage<Post>> {
return http.execute(Router.get("/posts")).map { (feed:PostFeed) in
return feed.rxPage()
}
}
func filterPostsByTags(_ tags: [String]) -> Observable<RxPage<Post>> {
let tagsObject = PostTagFilter(tags: tags)
let json = "{\"post\":\(tagsObject.toJSONString() ?? "")}"
let query = json.addingPercentEncoding(
withAllowedCharacters: CharacterSet.urlHostAllowed) ?? ""
return http.execute(Router.get("/posts?where=" + query)).map { (feed:PostFeed) in
return feed.rxPage()
}
}
func retrieveComments(_ postId: String) -> Observable<RxPage<Comment>> {
return http.execute(Router.get("/posts/" + postId + "/comments")).map { (feed:CommentFeed) in
return feed.rxPage()
}
}
func retrieveLikes(_ postId: String) -> Observable<RxPage<Like>> {
return http.execute(Router.get("/posts/" + postId + "/likes")).map { (feed:LikeFeed) in
return feed.rxPage()
}
}
func retrieveLikesByUser(_ userId: String) -> Observable<RxPage<Like>> {
return http.execute(Router.get("/users/" + userId + "/likes")).map {(feed: LikeFeed) in
return feed.rxPage()
}
}
func retrieveActivitiesByUser(_ userId: String) -> Observable<RxPage<Activity>> {
return retrieveActivitiesOn("/users/" + userId + "/events")
}
func retrievePostFeed() -> Observable<RxPage<Post>> {
return http.execute(Router.get("/me/feed/posts")).map { (feed:PostFeed) in
return feed.rxPage()
}
}
func retrieveActivityFeed() -> Observable<RxPage<Activity>> {
return retrieveActivitiesOn("/me/feed/events")
}
func retrieveMeFeed() -> Observable<RxPage<Activity>> {
return retrieveActivitiesOn("/me/feed/notifications/self")
}
func retrieveNewsFeed() -> Observable<RxCompositePage<NewsFeed>> {
return http.execute(Router.get("/me/feed")).map { (feed: NewsFeedEndpoint) in
return feed.rxPage()
}
}
func updateCount(_ newCount: Int, _ nameSpace: String) -> Observable<Void> {
let payload = ["value": newCount] as [String: AnyObject]
return http.execute(Router.put("/me/counters/" +
nameSpace.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!, payload: payload))
}
func getCount(_ nameSpace: String) -> Observable<Count> {
return http.execute(Router.get("/counters/" +
nameSpace.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)!))
}
fileprivate func retrieveActivitiesOn(_ path: String) -> Observable<[Activity]> {
return http.execute(Router.get(path)).map { (feed: ActivityFeed) in
let activities = feed.activities?.map {activity -> Activity in
activity.user = feed.users?[activity.userId ?? ""]
activity.post = feed.posts?[activity.postId ?? ""]
activity.post?.user = feed.users?[activity.post?.userId ?? ""]
if activity.target?.type == "tg_user" {
activity.targetUser = feed.users?[activity.target!.id ?? ""]
}
return activity
}
return activities!
}
}
fileprivate func retrieveActivitiesOn(_ path: String) -> Observable<RxPage<Activity>> {
return http.execute(Router.get(path)).map { (feed: ActivityFeed) in
return feed.rxPage()
}
}
fileprivate func convertToConnections(_ feed: ConnectionsFeed) -> Connections {
let connections = Connections()
connections.incoming = feed.incoming?.map { connection -> Connection in
connection.userFrom = feed.users?.filter { user -> Bool in
user.id == connection.userFromId
}.first
return connection
}
connections.outgoing = feed.outgoing?.map { connection -> Connection in
connection.userTo = feed.users?.filter { user -> Bool in
user.id == connection.userToId
}.first
return connection
}
return connections
}
fileprivate func mapUserToPost(_ feed: PostFeed) -> [Post] {
let posts = feed.posts?.map { post -> Post in
post.user = feed.users?[post.userId ?? ""]
return post
}
return posts!
}
}
| apache-2.0 | a7d03ddb73d2c94242ade8a22d88709a | 37.596741 | 137 | 0.59142 | 4.469575 | false | false | false | false |
slightair/SwiftGraphics | Playgrounds/Images.playground/Contents.swift | 2 | 6478 | //: Playground - noun: a place where people can play
import Cocoa
import CoreGraphics
import CoreImage
import SwiftGraphics
public extension NSImage {
var CGImage: Cocoa.CGImage? {
return CGImageForProposedRect(nil, context: nil, hints: nil)
}
}
public extension CGImage {
var size: CGSize {
return CGSize(width: CGImageGetWidth(self), height: CGImageGetHeight(self))
}
}
public extension CGImage {
func toNSImage() -> NSImage {
return NSImage(CGImage: self, size: self.size)
}
}
public extension CGImage {
func resized(size: CGSize, keepAspectRatio: Bool = false) -> CGImage {
let rect: CGRect
if keepAspectRatio == true {
rect = scaleAndAlignRectToRect(source: self.size.toRect(), destination: size.toRect(), scaling: .proportionally, alignment: .center)
}
else {
rect = size.toRect()
}
let context = CGContext.bitmapContext(size)
context.with() {
CGContextDrawImage(context, rect, self)
}
return context.image
}
}
public extension CGImage {
func cropped(rect: CGRect) -> CGImage {
let context = CGContext.bitmapContext(rect.size)
context.with() {
CGContextDrawImage(context, rect, self)
}
return context.image
}
func cropped(size: CGSize, scaling: SwiftGraphics.Scaling = .none, alignment: SwiftGraphics.Alignment) -> CGImage {
let rect = scaleAndAlignRectToRect(source: self.size.toRect(), destination: size.toRect(), scaling: scaling, alignment: alignment)
let context = CGContext.bitmapContext(size)
context.with() {
CGContextDrawImage(context, rect, self)
}
return context.image
}
}
public extension CGImage {
func clipped(path: CGPath) -> CGImage {
let context = CGContext.bitmapContext(size)
context.with() {
CGContextAddPath(context, path)
CGContextClip(context)
CGContextDrawImage(context, CGRect(size: size), self)
}
return context.image
}
func clipped(pathable: CGPathable) -> CGImage {
return clipped(pathable.cgpath)
}
}
extension CGImage: Drawable {
public func drawInContext(context: CGContextRef) {
CGContextDrawImage(context, size.toRect(), self)
}
}
extension CGImage {
func composite(other: CGImage, blendMode: CGBlendMode? = nil, alpha: CGFloat = 1.0) -> CGImage {
let context = CGContext.bitmapContext(size)
context.with() {
context.draw(self)
if let blendMode = blendMode {
context.blendMode = blendMode
}
context.alpha = alpha
context.draw(other)
}
return context.image
}
}
extension CGImage {
static func with(size: CGSize, contextDraw: CGContext -> Void) -> CGImage {
let context = CGContext.bitmapContext(size)
context.with() {
contextDraw(context)
}
return context.image
}
func with(size: CGSize? = nil, contextDraw: CGContext -> Void) -> CGImage {
let size = size ?? self.size
let context = CGContext.bitmapContext(size)
context.with() {
drawInContext(context)
contextDraw(context)
}
return context.image
}
}
func composite(imageables: [Imageable], size: CGSize, blendMode: CGBlendMode? = nil, alpha: CGFloat = 1.0) -> CGImage {
let images = imageables.map() { return $0.toCGImage(size) }
guard let firstImage = images.first else {
preconditionFailure()
}
let context = CGContext.bitmapContext(size)
context.with() {
context.draw(firstImage)
if let blendMode = blendMode {
context.blendMode = blendMode
}
context.alpha = alpha
for image in images[1...(images.count - 1)] {
if image === firstImage {
continue
}
context.draw(image)
}
}
return context.image
}
protocol Imageable {
func toCGImage() -> CGImage
func toCGImage(size: CGSize) -> CGImage
}
extension Imageable {
func toCIImage() -> CIImage {
let cgImage = toCGImage()
let ciImage = CIImage(CGImage: cgImage)
return ciImage
}
func toCIImage(size: CGSize) -> CIImage {
let cgImage = toCGImage(size)
let ciImage = CIImage(CGImage: cgImage)
return ciImage
}
}
extension CGColor: Imageable {
func toCGImage() -> CGImage {
return toCGImage(CGSize(w: 1, h: 1))
}
func toCGImage(size: CGSize = CGSize(width: 1, height: 1)) -> CGImage {
let context = CGContext.bitmapContext(size)
context.with() {
context.fillColor = self
CGContextFillRect(context, size.toRect())
}
return context.image
}
}
extension CGImage: Imageable {
func toCGImage() -> CGImage {
return self
}
func toCGImage(size: CGSize) -> CGImage {
assert(size == self.size)
return self
}
}
extension CIImage: Imageable {
func toCGImage() -> CGImage {
let c = CIContext()
return c.createCGImage(self, fromRect: self.extent)
}
func toCGImage(size: CGSize) -> CGImage {
let c = CIContext()
return c.createCGImage(self, fromRect: self.extent)
}
}
extension Circle {
func circleWithRadius(radius: CGFloat) -> Circle {
return Circle(center: center, radius: radius)
}
func inset(delta: CGFloat) -> Circle {
return circleWithRadius(radius + delta)
}
}
var image = NSImage(named: "albert-einstein-tongue")!.CGImage!
image = image.cropped(CGSize(w: image.size.min, h: image.size.min), alignment: .center)
image = image.resized(CGSize(w: 800, h: 800), keepAspectRatio: true)
image = composite([image, CGColor.greenColor()], size: image.size, blendMode: .Normal, alpha: 0.15)
let r = image.size.min * 0.5
let circle = Circle(center: CGPoint(x: r, y: r), radius: r - 10)
image = image.clipped(circle.inset(-20))
image = image.with() {
$0.lineWidth = 20
$0.strokeColor = CGColor.greenColor().withAlpha(0.75)
circle.drawInContext($0)
}
let circleImage = circle.toCGImage(circle.frame.insetBy(dx: -10, dy: -10).size, style: nil)
circleImage.toNSImage()
let f1 = Crystallize(inputImage: image.toCIImage())
image = f1.outputImage!.toCGImage()
image.toNSImage()
| bsd-2-clause | 06e931195183552211c0be254b147d1b | 26.333333 | 144 | 0.619944 | 4.253447 | false | false | false | false |
TalntsApp/media-picker-ios | MediaPicker/TitleView/MediaListTitleView.swift | 1 | 1943 | import UIKit
class MediaListTitleView: UICollectionReusableView, RegisterableReusableView {
static let defaultIdentifier: String = "MediaListTitleView"
static let nibName: String? = "MediaListTitleView"
@IBOutlet var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.titleLabel.text = nil
}
override func prepareForReuse() {
super.prepareForReuse()
self.titleLabel.text = nil
}
}
protocol RegisterableReusableView: class {
static var defaultIdentifier: String { get }
static var nibName: String? { get }
static func registerAtCollectionView(collectionView: UICollectionView, kind: ReusableViewKind, identifier: String)
}
extension RegisterableReusableView {
static func registerAtCollectionView(collectionView: UICollectionView, kind: ReusableViewKind, identifier: String = Self.defaultIdentifier) {
if let nibName = Self.nibName {
let bundle = NSBundle(forClass: Self.self)
let nib = UINib(nibName: nibName, bundle: bundle)
collectionView.registerNib(nib, forSupplementaryViewOfKind: kind.rawValue, withReuseIdentifier: identifier)
} else {
collectionView.registerClass(Self.self, forSupplementaryViewOfKind: kind.rawValue, withReuseIdentifier: identifier)
}
}
}
enum ReusableViewKind {
case Header
case Footer
init?(rawValue: String) {
switch rawValue {
case UICollectionElementKindSectionHeader:
self = .Header
case UICollectionElementKindSectionFooter:
self = .Footer
default:
return nil
}
}
var rawValue: String {
switch self {
case .Header:
return UICollectionElementKindSectionHeader
case .Footer:
return UICollectionElementKindSectionFooter
}
}
} | mit | c1228432b9e0bca00bde934af7aa6ec6 | 28.907692 | 145 | 0.66598 | 5.731563 | false | false | false | false |
MJSR-Developer/Rush | Rush/Classes/Reachability.swift | 2 | 10009 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import SystemConfiguration
import Foundation
public enum ReachabilityError: Error {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification")
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
guard let info = info else { return }
let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue()
DispatchQueue.main.async {
reachability.reachabilityChanged()
}
}
public class Reachability {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUnreachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case notReachable, reachableViaWiFi, reachableViaWWAN
public var description: String {
switch self {
case .reachableViaWWAN: return "Cellular"
case .reachableViaWiFi: return "WiFi"
case .notReachable: return "No Connection"
}
}
}
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
// The notification center on which "reachability changed" events are being posted
public var notificationCenter: NotificationCenter = NotificationCenter.default
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
public var currentReachabilityStatus: NetworkStatus {
guard isReachable else { return .notReachable }
if isReachableViaWiFi {
return .reachableViaWiFi
}
if isRunningOnDevice {
return .reachableViaWWAN
}
return .notReachable
}
fileprivate var previousFlags: SCNetworkReachabilityFlags?
fileprivate var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
fileprivate var notifierRunning = false
fileprivate var reachabilityRef: SCNetworkReachability?
fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability")
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil }
self.init(reachabilityRef: ref)
}
public convenience init?() {
var zeroAddress = sockaddr()
zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size)
zeroAddress.sa_family = sa_family_t(AF_INET)
guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { return nil }
self.init(reachabilityRef: ref)
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
public extension Reachability {
// MARK: - *** Notifier methods ***
func startNotifier() throws {
guard let reachabilityRef = reachabilityRef, !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an initial check
reachabilitySerialQueue.async {
self.reachabilityChanged()
}
notifierRunning = true
}
func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
var isReachable: Bool {
guard isReachableFlagSet else { return false }
if isConnectionRequiredAndTransientFlagSet {
return false
}
if isRunningOnDevice {
if isOnWWANFlagSet && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
var isReachableViaWWAN: Bool {
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet
}
var isReachableViaWiFi: Bool {
// Check we're reachable
guard isReachableFlagSet else { return false }
// If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi
guard isRunningOnDevice else { return true }
// Check we're NOT on WWAN
return !isOnWWANFlagSet
}
var description: String {
let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X"
let R = isReachableFlagSet ? "R" : "-"
let c = isConnectionRequiredFlagSet ? "c" : "-"
let t = isTransientConnectionFlagSet ? "t" : "-"
let i = isInterventionRequiredFlagSet ? "i" : "-"
let C = isConnectionOnTrafficFlagSet ? "C" : "-"
let D = isConnectionOnDemandFlagSet ? "D" : "-"
let l = isLocalAddressFlagSet ? "l" : "-"
let d = isDirectFlagSet ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
}
fileprivate extension Reachability {
func reachabilityChanged() {
let flags = reachabilityFlags
guard previousFlags != flags else { return }
let block = isReachable ? whenReachable : whenUnreachable
block?(self)
self.notificationCenter.post(name: ReachabilityChangedNotification, object:self)
previousFlags = flags
}
var isOnWWANFlagSet: Bool {
#if os(iOS)
return reachabilityFlags.contains(.isWWAN)
#else
return false
#endif
}
var isReachableFlagSet: Bool {
return reachabilityFlags.contains(.reachable)
}
var isConnectionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.connectionRequired)
}
var isInterventionRequiredFlagSet: Bool {
return reachabilityFlags.contains(.interventionRequired)
}
var isConnectionOnTrafficFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnTraffic)
}
var isConnectionOnDemandFlagSet: Bool {
return reachabilityFlags.contains(.connectionOnDemand)
}
var isConnectionOnTrafficOrDemandFlagSet: Bool {
return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty
}
var isTransientConnectionFlagSet: Bool {
return reachabilityFlags.contains(.transientConnection)
}
var isLocalAddressFlagSet: Bool {
return reachabilityFlags.contains(.isLocalAddress)
}
var isDirectFlagSet: Bool {
return reachabilityFlags.contains(.isDirect)
}
var isConnectionRequiredAndTransientFlagSet: Bool {
return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]
}
var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(to: &flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
}
| mit | c15c049578415cf0ab0318adf3323ce3 | 32.587248 | 137 | 0.662604 | 6.029518 | false | false | false | false |
avito-tech/Marshroute | MarshrouteTests/Sources/Routers/RouterFocusableTests/RouterFocusableTests.swift | 1 | 13563 | import XCTest
@testable import Marshroute
final class RouterFocusableTests: XCTestCase
{
var transitionId: TransitionId!
var transitionIdGenerator: TransitionIdGenerator!
var transitionsCoordinator: TransitionsCoordinatorImpl!
var masterAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy!
var detailAnimatingTransitionsHandlerSpy: AnimatingTransitionsHandlerSpy!
var masterContainingTransitionsHandlerSpy: ContainingTransitionsHandlerSpy!
var detailContainingTransitionsHandlerSpy: ContainingTransitionsHandlerSpy!
var dummyPresentingTransitionsHandler: DummyAnimatingTransitionsHandler!
override func setUp() {
super.setUp()
transitionIdGenerator = TransitionIdGeneratorImpl()
transitionId = transitionIdGenerator.generateNewTransitionId()
let peekAndPopTransitionsCoordinator = PeekAndPopUtilityImpl()
transitionsCoordinator = TransitionsCoordinatorImpl(
stackClientProvider: TransitionContextsStackClientProviderImpl(),
peekAndPopTransitionsCoordinator: peekAndPopTransitionsCoordinator
)
masterAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy(
transitionsCoordinator: transitionsCoordinator
)
detailAnimatingTransitionsHandlerSpy = AnimatingTransitionsHandlerSpy(
transitionsCoordinator: transitionsCoordinator
)
masterContainingTransitionsHandlerSpy = ContainingTransitionsHandlerSpy(
transitionsCoordinator: transitionsCoordinator
)
detailContainingTransitionsHandlerSpy = ContainingTransitionsHandlerSpy(
transitionsCoordinator: transitionsCoordinator
)
dummyPresentingTransitionsHandler = DummyAnimatingTransitionsHandler()
}
// MARK: - BaseRouter
func testThatNotRootRouterCallsItsTransitionsHandlerOn_FocusOnCurrentModule_IfItsTransitionHandlerIsAnimating() {
// Given
let router = BaseRouter( // Base Router
routerSeed: RouterSeed(
transitionsHandlerBox: .init(
animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy // Animating Transitions Handler
),
transitionId: transitionId,
presentingTransitionsHandler: dummyPresentingTransitionsHandler, // Not Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
router.focusOnCurrentModule()
// Then
XCTAssert(router.transitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy)
XCTAssert(router.presentingTransitionsHandler === dummyPresentingTransitionsHandler)
XCTAssert(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
}
func testThatNotRootRouterCallsItsTransitionsHandlerOn_FocusOnCurrentModule_IfItsTransitionHandlerIsContaining() {
// Given
let router = BaseRouter( // Base Router
routerSeed: RouterSeed(
transitionsHandlerBox: .init(
containingTransitionsHandler: masterContainingTransitionsHandlerSpy // Containing Transitions Handler
),
transitionId: transitionId,
presentingTransitionsHandler: dummyPresentingTransitionsHandler, // Not Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
router.focusOnCurrentModule()
// Then
XCTAssert(router.transitionsHandlerBox.unbox() === masterContainingTransitionsHandlerSpy)
XCTAssert(router.presentingTransitionsHandler === dummyPresentingTransitionsHandler)
XCTAssert(masterContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterContainingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
}
func testThatRootRouterCallsItsTransitionsHandlerOn_FocusOnCurrentModule_IfItsTransitionHandlerIsAnimating() {
// Given
let router = BaseRouter( // Router
routerSeed: RouterSeed(
transitionsHandlerBox: .init(
animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy // Animating Transitions Handler
),
transitionId: transitionId,
presentingTransitionsHandler: nil, // Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
router.focusOnCurrentModule()
// Then
XCTAssert(router.transitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy)
XCTAssertNil(router.presentingTransitionsHandler)
XCTAssert(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
}
func testThatRootRouterDoesNotCallItsTransitionsHandlerOn_FocusOnCurrentModule_IfItsTransitionHandlerIsContaining() {
// Given
let router = BaseRouter( // Router
routerSeed: RouterSeed(
transitionsHandlerBox: .init(
containingTransitionsHandler: masterContainingTransitionsHandlerSpy // Containing Transitions Handler
),
transitionId: transitionId,
presentingTransitionsHandler: nil, // Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
router.focusOnCurrentModule()
// Then
XCTAssert(router.transitionsHandlerBox.unbox() === masterContainingTransitionsHandlerSpy)
XCTAssertNil(router.presentingTransitionsHandler)
XCTAssertFalse(masterContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
}
// MARK: - BaseMasterDetailRouter
func testThatNotRootMasterDetailRouterCallsItsMasterTransitionsHandlerOn_FocusOnCurrentModule_IfItsMasterTransitionHandlerIsAnimating() {
// Given
let masterDetailRouter = BaseMasterDetailRouter( // MasterDetail Router
routerSeed: MasterDetailRouterSeed(
masterTransitionsHandlerBox: .init(
animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy // Animating Master Transitions Handler
),
detailTransitionsHandlerBox: .init(
animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy
),
transitionId: transitionId,
presentingTransitionsHandler: dummyPresentingTransitionsHandler, // Not Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
masterDetailRouter.focusOnCurrentModule()
// Then
XCTAssert(masterDetailRouter.masterTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.detailTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.presentingTransitionsHandler === dummyPresentingTransitionsHandler)
XCTAssert(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
XCTAssertFalse(detailAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
}
func testThatNotRootMasterDetailRouterCallsItsMasterTransitionsHandlerOn_FocusOnCurrentModule_IfItsMasterTransitionHandlerIsContaining() {
// Given
let masterDetailRouter = BaseMasterDetailRouter( // MasterDetail Router
routerSeed: MasterDetailRouterSeed(
masterTransitionsHandlerBox: .init(
containingTransitionsHandler: masterContainingTransitionsHandlerSpy // Containing Master Transitions Handler
),
detailTransitionsHandlerBox: .init(
containingTransitionsHandler: detailContainingTransitionsHandlerSpy
),
transitionId: transitionId,
presentingTransitionsHandler: dummyPresentingTransitionsHandler, // Not Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
masterDetailRouter.focusOnCurrentModule()
// Then
XCTAssert(masterDetailRouter.masterTransitionsHandlerBox.unbox() === masterContainingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.detailTransitionsHandlerBox.unbox() === detailContainingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.presentingTransitionsHandler === dummyPresentingTransitionsHandler)
XCTAssert(masterContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterContainingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
XCTAssertFalse(detailContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
}
func testThatRootMasterDetailRouterCallsItsMasterTransitionsHandlerOn_FocusOnCurrentModule_IfItsMasterTransitionHandlerIsAnimating() {
// Given
let masterDetailRouter = BaseMasterDetailRouter( // MasterDetail Router
routerSeed: MasterDetailRouterSeed(
masterTransitionsHandlerBox: .init(
animatingTransitionsHandler: masterAnimatingTransitionsHandlerSpy // Animating Master Transitions Handler
),
detailTransitionsHandlerBox: .init(
animatingTransitionsHandler: detailAnimatingTransitionsHandlerSpy
),
transitionId: transitionId,
presentingTransitionsHandler: nil, // Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
masterDetailRouter.focusOnCurrentModule()
// Then
XCTAssert(masterDetailRouter.masterTransitionsHandlerBox.unbox() === masterAnimatingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.detailTransitionsHandlerBox.unbox() === detailAnimatingTransitionsHandlerSpy)
XCTAssertNil(masterDetailRouter.presentingTransitionsHandler)
XCTAssert(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertEqual(masterAnimatingTransitionsHandlerSpy.undoTransitionsAfterTransitionIdParameter, transitionId)
XCTAssertFalse(detailAnimatingTransitionsHandlerSpy.undoTransitionsAfterCalled)
}
func testThatRootMasterDetailRouterDoesNotCallItsMasterTransitionsHandlerOn_FocusOnCurrentModule_IfItsMasterTransitionHandlerIsContaining() {
// Given
let masterDetailRouter = BaseMasterDetailRouter( // MasterDetail Router
routerSeed: MasterDetailRouterSeed(
masterTransitionsHandlerBox: .init(
containingTransitionsHandler: masterContainingTransitionsHandlerSpy // Containing Master Transitions Handler
),
detailTransitionsHandlerBox: .init(
containingTransitionsHandler: detailContainingTransitionsHandlerSpy
),
transitionId: transitionId,
presentingTransitionsHandler: nil, // Root Router
transitionsHandlersProvider: transitionsCoordinator,
transitionIdGenerator: transitionIdGenerator,
controllersProvider: RouterControllersProviderImpl()
)
)
// When
masterDetailRouter.focusOnCurrentModule()
// Then
XCTAssert(masterDetailRouter.masterTransitionsHandlerBox.unbox() === masterContainingTransitionsHandlerSpy)
XCTAssert(masterDetailRouter.detailTransitionsHandlerBox.unbox() === detailContainingTransitionsHandlerSpy)
XCTAssertNil(masterDetailRouter.presentingTransitionsHandler)
XCTAssertFalse(masterContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
XCTAssertFalse(detailContainingTransitionsHandlerSpy.undoTransitionsAfterCalled)
}
}
| mit | 6523cdb0e8c00869a4884583d3387cff | 47.78777 | 145 | 0.70508 | 9.680942 | false | false | false | false |
fitpay/fitpay-ios-sdk | FitpaySDKTests/Rest/Models/CreditCard/CreditCardTests.swift | 1 | 17639 | import XCTest
import Nimble
@testable import FitpaySDK
class CreditCardTests: XCTestCase {
private let mockModels = MockModels()
private let mockRestRequest = MockRestRequest()
private var session: RestSession?
private var client: RestClient?
override func setUp() {
session = RestSession(sessionData: nil, restRequest: mockRestRequest)
session!.accessToken = "authorized"
client = RestClient(session: session!, restRequest: mockRestRequest)
}
func testCreditCardParsing() {
let creditCard = mockModels.getCreditCard()
expect(creditCard?.creditCardId).to(equal(mockModels.someId))
expect(creditCard?.userId).to(equal(mockModels.someId))
expect(creditCard?.created).to(equal(mockModels.someDate))
expect(creditCard?.createdEpoch).to(equal(NSTimeIntervalTypeTransform().transform(mockModels.timeEpoch)))
expect(creditCard?.state).to(equal(TokenizationState.notEligible))
expect(creditCard?.cardType).to(equal(mockModels.someType))
expect(creditCard?.termsAssetId).to(equal(mockModels.someId))
expect(creditCard?.eligibilityExpiration).to(equal(mockModels.someDate))
expect(creditCard?.encryptedData).to(equal(mockModels.someEncryptionData))
expect(creditCard?.targetDeviceId).to(equal(mockModels.someId))
expect(creditCard?.targetDeviceType).to(equal(mockModels.someType))
expect(creditCard?.externalTokenReference).to(equal("someToken"))
expect(creditCard?.links).toNot(beNil())
expect(creditCard?.links?.count).to(equal(10))
expect(creditCard?.cardMetaData).toNot(beNil())
expect(creditCard?.termsAssetReferences).toNot(beNil())
expect(creditCard?.verificationMethods).toNot(beNil())
expect(creditCard?.topOfWalletAPDUCommands).toNot(beNil())
expect(creditCard?.topOfWalletAPDUCommands?.count).to(equal(1))
let json = creditCard?.toJSON()
expect(json?["creditCardId"] as? String).to(equal(mockModels.someId))
expect(json?["createdTs"] as? String).to(equal(mockModels.someDate))
expect(json?["createdTsEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["state"] as? String).to(equal("NOT_ELIGIBLE"))
expect(json?["cardType"] as? String).to(equal(mockModels.someType))
expect(json?["termsAssetId"] as? String).to(equal(mockModels.someId))
expect(json?["eligibilityExpiration"] as? String).to(equal(mockModels.someDate))
expect(json?["eligibilityExpirationEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["encryptedData"] as? String).to(equal(mockModels.someEncryptionData))
expect(json?["targetDeviceId"] as? String).to(equal(mockModels.someId))
expect(json?["targetDeviceType"] as? String).to(equal(mockModels.someType))
expect(json?["externalTokenReference"] as? String).to(equal("someToken"))
expect(json?["_links"]).toNot(beNil())
expect(json?["cardMetaData"]).toNot(beNil())
expect(json?["termsAssetReferences"]).toNot(beNil())
expect(json?["verificationMethods"]).toNot(beNil())
}
func testCreditCardCommitParsing() {
let creditCard = mockModels.getCreditCardCommit()
expect(creditCard?.creditCardId).to(equal(mockModels.someId))
expect(creditCard?.userId).to(equal(mockModels.someId))
expect(creditCard?.created).to(equal(mockModels.someDate))
expect(creditCard?.createdEpoch).to(equal(NSTimeIntervalTypeTransform().transform(mockModels.timeEpoch)))
expect(creditCard?.state).to(equal(TokenizationState.notEligible))
expect(creditCard?.cardType).to(equal(mockModels.someType))
expect(creditCard?.termsAssetId).to(equal(mockModels.someId))
expect(creditCard?.eligibilityExpiration).to(equal(mockModels.someDate))
expect(creditCard?.encryptedData).to(equal(mockModels.someEncryptionData))
expect(creditCard?.targetDeviceId).to(equal(mockModels.someId))
expect(creditCard?.targetDeviceType).to(equal(mockModels.someType))
expect(creditCard?.externalTokenReference).to(equal("someToken"))
expect(creditCard?.provisioningFailedReason).to(equal(ProvisioningFailedReason.provisioningLimitReached))
expect(creditCard?.termsAssetReferences).toNot(beNil())
expect(creditCard?.info?.name).to(equal("Bob"))
expect(creditCard?.info?.pan).to(equal("############1134"))
expect(creditCard?.info?.cvv).to(equal("###"))
expect(creditCard?.info?.expMonth).to(equal(11))
expect(creditCard?.info?.expYear).to(equal(2022))
let json = creditCard?.toJSON()
expect(json?["creditCardId"] as? String).to(equal(mockModels.someId))
expect(json?["createdTs"] as? String).to(equal(mockModels.someDate))
expect(json?["createdTsEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["state"] as? String).to(equal("NOT_ELIGIBLE"))
expect(json?["cardType"] as? String).to(equal(mockModels.someType))
expect(json?["termsAssetId"] as? String).to(equal(mockModels.someId))
expect(json?["eligibilityExpiration"] as? String).to(equal(mockModels.someDate))
expect(json?["eligibilityExpirationEpoch"] as? Int64).to(equal(mockModels.timeEpoch))
expect(json?["encryptedData"] as? String).to(equal(mockModels.someEncryptionData))
expect(json?["targetDeviceId"] as? String).to(equal(mockModels.someId))
expect(json?["targetDeviceType"] as? String).to(equal(mockModels.someType))
expect(json?["externalTokenReference"] as? String).to(equal("someToken"))
expect(json?["termsAssetReferences"]).toNot(beNil())
}
func testAvailable() {
let creditCard = mockModels.getCreditCard()
expect(creditCard?.acceptTermsAvailable).to(beTrue())
expect(creditCard?.declineTermsAvailable).to(beTrue())
expect(creditCard?.deactivateAvailable).to(beTrue())
expect(creditCard?.reactivateAvailable).to(beTrue())
expect(creditCard?.makeDefaultAvailable).to(beTrue())
expect(creditCard?.listTransactionsAvailable).to(beTrue())
expect(creditCard?.verificationMethodsAvailable).to(beTrue())
expect(creditCard?.selectedVerificationMethodAvailable).to(beTrue())
}
func testNotAvailable() {
let creditCard = mockModels.getCreditCard()
creditCard?.links = nil
expect(creditCard?.acceptTermsAvailable).to(beFalse())
expect(creditCard?.declineTermsAvailable).to(beFalse())
expect(creditCard?.deactivateAvailable).to(beFalse())
expect(creditCard?.reactivateAvailable).to(beFalse())
expect(creditCard?.makeDefaultAvailable).to(beFalse())
expect(creditCard?.listTransactionsAvailable).to(beFalse())
expect(creditCard?.verificationMethodsAvailable).to(beFalse())
expect(creditCard?.selectedVerificationMethodAvailable).to(beFalse())
}
func testwebappCardLink() {
let creditCard = mockModels.getCreditCard()
expect(creditCard?.webappCardLink?.templated).to(beTrue())
expect(creditCard?.webappCardLink?.href).to(equal("https://fit-pay.com/users/9469bfe0-3fa1-4465-9abf-f78cacc740b2/creditcards/57717bdb6d213e810137ee21adb7e883fe0904e9/config={config}"))
creditCard?.links = nil
expect(creditCard?.webappCardLink).to(beNil())
}
func testGetAcceptTermsURL() {
let creditCard = mockModels.getCreditCard()
expect(creditCard?.getAcceptTermsUrl()).to(contain("acceptTerms"))
}
func testSetAcceptTermsUrl() {
let creditCard = mockModels.getCreditCard()
creditCard?.setAcceptTermsUrl(acceptTermsUrl: "newUrl")
expect(creditCard?.getAcceptTermsUrl()).to(equal("newUrl"))
creditCard?.links = nil
creditCard?.setAcceptTermsUrl(acceptTermsUrl: "newNewUrl")
expect(creditCard?.getAcceptTermsUrl()).to(beNil())
}
func testGetCardNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.getCard { (_, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testGetCard() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.getCard { (card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
done()
}
}
}
func testDeleteCardNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.deleteCard { error in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testDeleteCard() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.deleteCard { error in
expect(error).to(beNil())
done()
}
}
}
func testUpdateCardNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
let address = Address(street1: "123 Lane", street2: "2", street3: "3", city: "Boulder", state: "Colorado", postalCode: "80401", countryCode: "US")
creditCard?.updateCard(name: "John Wick", address: address) { (_, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testUpdateCard() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
let address = Address(street1: "123 Lane", street2: "2", street3: "3", city: "Boulder", state: "Colorado", postalCode: "80401", countryCode: "US")
creditCard?.updateCard(name: "John Wick", address: address) { (card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
done()
}
}
}
func testAcceptTermsNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.acceptTerms { (_, _, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testAcceptTerms() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.acceptTerms { (pending, card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
done()
}
}
}
func testDeclineTermsNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.declineTerms { (_, _, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testDeclineTerms() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.declineTerms { (pending, card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
done()
}
}
}
func testDeactivateNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.deactivate(causedBy: .cardholder, reason: "none") { (_, _, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testDeactivate() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.deactivate(causedBy: .cardholder, reason: "none") { (pending, card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
done()
}
}
}
func testReactivateNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.reactivate(causedBy: .cardholder, reason: "none") { (_, _, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testReactivate() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.reactivate(causedBy: .cardholder, reason: "none") { (pending, card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
done()
}
}
}
func testMakeDefaultNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.makeDefault { (_, _, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testMakeDefault() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.makeDefault { (pending, card, error) in
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
done()
}
}
}
func testMakeDefaultWithDeviceId() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.makeDefault(deviceId: "123") { (pending, card, error) in
let urlString = try! self.mockRestRequest.lastUrl?.asURL().absoluteString
expect(error).to(beNil())
expect(card).toNot(beNil())
expect(pending).to(beFalse())
expect(urlString).to(contain("deviceId=123"))
done()
}
}
}
func testListTransactionsNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.listTransactions(limit: 10, offset: 0) { (_, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testListTransactions() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.listTransactions(limit: 10, offset: 0) { (transactionResults, error) in
expect(error).to(beNil())
expect(transactionResults).toNot(beNil())
expect(transactionResults?.results?.count).to(equal(10))
done()
}
}
}
func testGetVerificationMethodsNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.getVerificationMethods { (_, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testGetVerificationMethods() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.getVerificationMethods { (verificationResults, error) in
expect(error).to(beNil())
expect(verificationResults).toNot(beNil())
expect(verificationResults?.results?.count).to(equal(1))
done()
}
}
}
func testGetSelectedVerificationMethodNoClient() {
let creditCard = mockModels.getCreditCard()
waitUntil { done in
creditCard?.getSelectedVerification { (_, error) in
expect(error).toNot(beNil())
expect(error?.localizedDescription).to(equal("RestClient is not set."))
done()
}
}
}
func testGetSelectedVerificationMethod() {
let creditCard = mockModels.getCreditCard()
creditCard?.client = client
waitUntil { done in
creditCard?.getSelectedVerification { (verification, error) in
expect(error).to(beNil())
expect(verification).toNot(beNil())
done()
}
}
}
}
| mit | 57ca538b2cb5cba0862901d631f75ed2 | 39.271689 | 193 | 0.600317 | 4.971533 | false | true | false | false |
CYZZ/Sinaweibo | SinaWeb(Swift)/Classes/Main/MainVC.swift | 1 | 6007 | //
// MainVC.swift
// SinaWeb(Swift)
//
// Created by cyz on 16/10/29.
// Copyright © 2016年 yuze. All rights reserved.
//
import UIKit
class MainVC: UITabBarController {
var callBack:((String)->())?
override func viewDidLoad() {
super.viewDidLoad()
// iOS7以后只需要设置tinColor,那么图片你和文字都会按照tintColor渲染
tabBar.tintColor = UIColor.orange
// 添加自控制器
addChildViewControllers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBar.addSubview(composeButton)
}
// MARK: - 内部控制方法
/// 添加所有子控制器
private func addChildViewControllers() {
// 1. 根据JSON文件创建控制器
// 1.1读取JSON数据
guard let filePath = Bundle.main.path(forResource: "MainVCSettings.json", ofType: nil) else {
BLLog("JSON文件不存在")
return
}
guard let data = NSData(contentsOfFile:filePath) else {
BLLog("加载二进制数据失败")
return
}
// 1.2将JSON数据转换为对象(数组字典)
do {
let obj = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String:AnyObject]] // 声明解析出来的数据是数组,数组中存储着字典
for dic in obj{
let title = dic["title"] as? String
let vcName = dic["vcName"] as? String
let imageName = dic["imageName"] as? String
addChildViewController(childControllerName: vcName, title: title, imageName: imageName)
}
} catch {
// 只要try对应的方法发生了异常,就会执行catch{}中的代码
addChildViewController(childControllerName: "HomeVC", title: "首页", imageName: "tabbar_home")
addChildViewController(childControllerName: "MessageVC", title: "消息", imageName:"tabbar_message_center")
addChildViewController(childControllerName: "NULLVC", title: "", imageName: " ")
addChildViewController(childControllerName: "DiscoverVC", title: "发现", imageName: "tabbar_discover")
addChildViewController(childControllerName: "ProfileVC", title: "我", imageName: "tabbar_Profile")
}
}
private func addChildViewController(childControllerName: String?, title: String?, imageName:String?) {
// 1. 动态获取命名空间
guard let name = Bundle.main.infoDictionary!["CFBundleExecutable"]as? String else {
BLLog("获取命名空间失败")
return
}
// 2. 根据字符串获取Class
var cls:AnyClass? = nil
if let vcName = childControllerName {
cls = NSClassFromString(name + "." + vcName)
}
// 3. 通过Class创建对象
// Swift中如果想通过一个CLass来创建一个对象,必须告诉系统这个Class的确切类型
guard let typeCls = cls as? UIViewController.Type else {
BLLog("cls不能当做UITabelVIewController")
return
}
// 通过Class创建对象
let childController = typeCls.init()
// 1.2设置子控制器的相关属性
childController.title = title
if let ivName = imageName {
childController.tabBarItem.image = UIImage(named: ivName)
childController.tabBarItem.selectedImage = UIImage(named:ivName + "_highlighted")
}
// 1.3 包装一个导航控制器
let nav = UINavigationController(rootViewController: childController)
// 1.4 将子控制器添加到UITabController中
addChildViewController(nav) // 这个方法是UITabbarController自带的方法
}
// MARK: - 懒加载
lazy var composeButton: UIButton = {
()->UIButton in
// 1. 创建按钮
let btn = UIButton()
// 2. 设置前景图片
// UIImage.init(named: "tabbar_compose_icon_add") 等同于#imageLiteral(resourceName: "tabbar_compose_icon_add")
btn.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: UIControlState.normal)
btn.setImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
// 3. 设置背景颜色
btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: UIControlState.normal)
btn.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
// UIButton.init(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_background_icon_add", state: .normal)
// 4. 监听按钮点击
btn.addTarget(self, action: #selector(compseBtnCLick(btn:)), for: UIControlEvents.touchUpInside)
btn.sizeToFit() // 按钮大小自适应
return btn
}()
/*
如果给按钮的锦亭方法加上private就会报错,报错原因是因为监听事件是有运行循环触发的,而如果该方法是私有的只能在当前类中访问
而相同的情况下OC中是没有问题的,因为OC是动态派发的
而Swift不一样,Swift中所有的东西都是编译时确定的
如果想让Swift中你的方法也支持动态派发可以在方法前面加上@objc
加上@objc就告诉系统需要动态派发
*/
@objc private func compseBtnCLick(btn:UIButton) -> Void {
BLLog("点击了按钮")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | fc00c31a8305538dfb9e80b58d267f95 | 34.210884 | 186 | 0.612249 | 4.54833 | false | false | false | false |
Tantalum73/XJodel | XJodel/XJodel/MainSplitViewController.swift | 1 | 1160 | //
// MainSplitViewController.swift
// XJodel
//
// Created by Andreas Neusüß on 09.03.16.
// Copyright © 2016 Cocoawah. All rights reserved.
//
import Cocoa
class MainSplitViewController: NSSplitViewController {
weak var sidebar: SidebarViewController?
weak var main: JodelTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
if let sidebar = childViewControllers.first as? SidebarViewController {
self.sidebar = sidebar
sidebar.delegate = self
}
if let main = childViewControllers[1] as? JodelTableViewController {
self.main = main
}
}
}
extension MainSplitViewController: SidebarProtocol {
func buttonPressed(button: SidebarButtons) {
switch button {
case .timeline:
main?.showTimeline()
case .pinned:
main?.showPinnedJodels()
case .own:
main?.showOwnJodels(nil)
case .best:
main?.showBestJodels()
case .mostComments:
main?.showMostCommentedJodels()
}
}
}
| mit | 5afa897625c754dd4157b24aa9421cf6 | 23.104167 | 79 | 0.605877 | 4.944444 | false | false | false | false |
Takanu/Pelican | Sources/Pelican/Session/Modules/API Request/Sync/Sync+Stickers.swift | 1 | 3283 | //
// MethodRequest+Stickers.swift
// Pelican
//
// Created by Takanu Kyriako on 17/12/2017.
//
import Foundation
/**
This extension handles any kinds of operations involving stickers (including setting group sticker packs).
*/
extension MethodRequestSync {
/**
Returns a StickerSet type for the name of the sticker set given, if successful.
*/
public func getStickerSet(_ name: String) -> StickerSet? {
let request = TelegramRequest.getStickerSet(name: name)
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response)
}
/**
Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet
methods (can be used multiple times).
*/
public func uploadStickerFile(_ sticker: Sticker, userID: String) -> FileDownload? {
guard let request = TelegramRequest.uploadStickerFile(userID: userID, sticker: sticker) else {
PLog.error("Can't create uploadStickerFile request.")
return nil
}
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response)
}
/**
Use this method to create new sticker set owned by a user. The bot will be able to edit the created sticker set.
*/
@discardableResult
public func createNewStickerSet(userID: String,
name: String,
title: String,
sticker: Sticker,
emojis: String,
containsMasks: Bool? = nil,
maskPosition: MaskPosition? = nil) -> Bool {
let request = TelegramRequest.createNewStickerSet(userID: userID,
name: name,
title: title,
sticker: sticker,
emojis: emojis,
containsMasks: containsMasks,
maskPosition: maskPosition)
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response) ?? false
}
/**
Adds a sticker to a sticker set created by the bot.
*/
@discardableResult
public func addStickerToSet(userID: String,
name: String,
pngSticker: Sticker,
emojis: String,
maskPosition: MaskPosition? = nil) -> Bool {
let request = TelegramRequest.addStickerToSet(userID: userID, name: name, pngSticker: pngSticker, emojis: emojis, maskPosition: maskPosition)
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response) ?? false
}
/**
Use this method to move a sticker in a set created by the bot to a specific position.
*/
@discardableResult
public func setStickerPositionInSet(stickerID: String, newPosition: Int) -> Bool {
let request = TelegramRequest.setStickerPositionInSet(stickerID: stickerID, position: newPosition)
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response) ?? false
}
/**
Use this method to delete a sticker from a set created by the bot.
*/
@discardableResult
public func deleteStickerFromSet(stickerID: String) -> Bool {
let request = TelegramRequest.deleteStickerFromSet(stickerID: stickerID)
let response = tag.sendSyncRequest(request)
return MethodRequest.decodeResponse(response) ?? false
}
}
| mit | fde43aa89129e37eb2d551c552ac97e8 | 32.161616 | 143 | 0.681084 | 4.331135 | false | false | false | false |
TBXark/Ruler | Ruler/Modules/Ruler/Views/CylinderLine.swift | 1 | 1547 | //
// CylinderLine.swift
// Ruler
//
// Created by Tbxark on 22/09/2017.
// Copyright © 2017 Tbxark. All rights reserved.
//
import SceneKit
class CylinderLine: SCNNode {
init( parent: SCNNode, v1: SCNVector3, v2: SCNVector3, radius: CGFloat, radSegmentCount: Int, color: UIColor)
{
super.init()
let height = v1.distance(receiver: v2)
position = v1
let nodeV2 = SCNNode()
nodeV2.position = v2
parent.addChildNode(nodeV2)
let zAlign = SCNNode()
zAlign.eulerAngles.x = Float(CGFloat.pi / 2)
let cyl = SCNCylinder(radius: radius, height: CGFloat(height))
cyl.radialSegmentCount = radSegmentCount
cyl.firstMaterial?.diffuse.contents = color
let nodeCyl = SCNNode(geometry: cyl )
nodeCyl.position.y = -height/2
zAlign.addChildNode(nodeCyl)
addChildNode(zAlign)
constraints = [SCNLookAtConstraint(target: nodeV2)]
}
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
private extension SCNVector3{
func distance(receiver:SCNVector3) -> Float{
let xd = receiver.x - self.x
let yd = receiver.y - self.y
let zd = receiver.z - self.z
let distance = Float(sqrt(xd * xd + yd * yd + zd * zd))
if (distance < 0){
return (distance * -1)
} else {
return (distance)
}
}
}
| mit | 02168f92239d9bc25deeb345b5142d7b | 25.20339 | 113 | 0.571151 | 3.817284 | false | false | false | false |
vbudhram/firefox-ios | Storage/SQL/SQLiteLogins.swift | 2 | 39089 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
open class SQLiteLogins: BrowserLogins {
fileprivate let db: BrowserDB
fileprivate static let MainColumns: String = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
fileprivate static let MainWithLastUsedColumns: String = MainColumns + ", timeLastUsed, timesUsed"
fileprivate static let LoginColumns: String = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
}
fileprivate class func populateLogin(_ login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
fileprivate class func constructLogin<T: Login>(_ row: SDRow, c: T.Type) -> T {
let credential = URLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: .none)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = URLProtectionSpace(host: host,
port: port,
protocol: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(_ row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified") ?? 0
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(_ row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
fileprivate class func LoginFactory(_ row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
fileprivate class func LoginDataFactory(_ row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
fileprivate class func LoginUsageDataFactory(_ row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
NotificationCenter.default.post(name: .DataLoginDidChange, object: nil)
}
open func getUsageDataForLoginByGUID(_ guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
open func getLoginDataForGUID(_ guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login with username: \(username ?? "nil"), first arg: \(args[0] ?? "nil")")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
open func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
open func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query, !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append("username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ?")
}
let whereSearchClause = searchClauses.count > 0 ? "AND (" + searchClauses.joined(separator: "OR") + ") " : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
open func addLogin(_ login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.new.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
fileprivate func cloneMirrorToOverlay(whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
fileprivate func ensureLocalOverlayExistsForGUID(_ guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { _ in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
fileprivate func cloneMirrorToOverlay(_ guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
fileprivate func markMirrorAsOverridden(_ guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
open func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
open func addUseOfLoginByGUID(_ guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [nowMicro, nowMilli, guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
open func removeLoginByGUID(_ guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
fileprivate func getDeletionStatementsForGUIDs(_ guids: ArraySlice<GUID>, nowMillis: Timestamp) -> [(sql: String, args: Args?)] {
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.new.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 }
return [ (delete, args), (update, args), (markMirrorAsOverridden, args), (insert, args)]
}
open func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success {
let timestamp = Date.now()
return db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap {
self.getDeletionStatementsForGUIDs($0, nowMillis: timestamp)
}) >>> effect(self.notifyLoginDidChange)
}
open func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.new.rawValue)"
let nowMillis = Date.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(_ guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(_ guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
fileprivate func storeReconciledLogin(_ login: Login) -> Success {
let dateMilli = Date.now()
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timeLastUsed,
login.timePasswordChanged,
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(_ upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
fileprivate func applyChangedLogin(_ upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
fileprivate func mirrorArgs(_ login: ServerLogin) -> Args {
let args: Args = [
login.serverModified,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
login.timeLastUsed,
login.timePasswordChanged,
login.timeCreated,
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
fileprivate func updateMirrorToLogin(_ login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
fileprivate func insertNewMirror(_ login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
fileprivate func findLocalRecordByContent(_ login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch cursor.count {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
fileprivate func resolveConflictBetween(local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
fileprivate func resolveConflictWithoutParentBetween(local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized<T: Collection>(_ guids: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> where T.Iterator.Element == GUID {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return [(delMirror, args),
(insMirror, args),
(delLocal, args)]
}
return self.db.run(queries)
>>> always(modified)
}
public func markAsDeleted<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let inClause = BrowserDB.varlist(args.count)
return [("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", args),
("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", args)]
}
return self.db.run(queries)
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.new.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.new.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
| mpl-2.0 | 6c9e6ec9b15a7e93088594789baf964e | 42.723714 | 204 | 0.60856 | 4.850956 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/Document+ScriptingSupport.swift | 1 | 18309 | //
// Document+ScriptingSupport.swift
//
// CotEditor
// https://coteditor.com
//
// Created by nakamuxu on 2005-03-12.
//
// ---------------------------------------------------------------------------
//
// © 2004-2007 nakamuxu
// © 2014-2022 1024jp
//
// 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
//
// https://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 Cocoa
private enum OSALineEnding: FourCharCode {
case lf = "leLF"
case cr = "leCR"
case crlf = "leCL"
case nel = "leNL"
case ls = "leLS"
case ps = "lePS"
var lineEnding: LineEnding {
switch self {
case .lf:
return .lf
case .cr:
return .cr
case .crlf:
return .crlf
case .nel:
return .nel
case .ls:
return .lineSeparator
case .ps:
return .paragraphSeparator
}
}
init?(lineEnding: LineEnding) {
switch lineEnding {
case .lf:
self = .lf
case .cr:
self = .cr
case .crlf:
self = .crlf
case .nel:
self = .nel
case .lineSeparator:
self = .ls
case .paragraphSeparator:
self = .ps
}
}
}
extension Document {
// MARK: AppleScript Accessors
/// whole document string (text (NSTextStorage))
@objc var scriptTextStorage: Any {
get {
let textStorage = NSTextStorage(string: self.string)
textStorage.observeDirectEditing { [weak self] (editedString) in
self?.insert(string: editedString, at: .replaceAll)
}
return textStorage
}
set {
switch newValue {
case let textStorage as NSTextStorage:
self.insert(string: textStorage.string, at: .replaceAll)
case let string as String:
self.insert(string: string, at: .replaceAll)
default:
assertionFailure()
}
}
}
/// document string (text (NSTextStorage))
@objc var contents: Any {
get {
return self.scriptTextStorage
}
set {
self.scriptTextStorage = newValue
}
}
/// selection-object (TextSelection)
@objc var selectionObject: Any {
get {
return self.selection
}
set {
guard let string = newValue as? String else { return }
self.selection.contents = string
}
}
/// length of document (integer)
@objc var length: Int {
return (self.string as NSString).length
}
/// new line code (enum type)
@objc var lineEndingChar: FourCharCode {
get {
return (OSALineEnding(lineEnding: self.lineEnding) ?? .lf).rawValue
}
set {
let lineEnding = OSALineEnding(rawValue: newValue)?.lineEnding
self.changeLineEnding(to: lineEnding ?? .lf)
}
}
/// encoding name (Unicode text)
@objc var encodingName: String {
return String.localizedName(of: self.fileEncoding.encoding)
}
/// encoding in IANA CharSet name (Unicode text)
@objc var IANACharSetName: String {
return self.fileEncoding.encoding.ianaCharSetName ?? ""
}
@objc var hasBOM: Bool {
self.fileEncoding.withUTF8BOM ||
self.fileEncoding.encoding == .utf16 ||
self.fileEncoding.encoding == .utf32
}
/// syntax style name (Unicode text)
@objc var coloringStyle: String {
get {
return self.syntaxParser.style.name
}
set {
self.setSyntaxStyle(name: newValue)
}
}
/// state of text wrapping (bool)
@objc var wrapsLines: Bool {
get {
return self.viewController?.wrapsLines ?? false
}
set {
self.setViewControllerValue(newValue, for: \.wrapsLines)
}
}
/// tab width (integer)
@objc var tabWidth: Int {
get {
return self.viewController?.tabWidth ?? 0
}
set {
self.setViewControllerValue(newValue, for: \.tabWidth)
}
}
/// whether replace tab with spaces
@objc var expandsTab: Bool {
get {
return self.viewController?.isAutoTabExpandEnabled ?? false
}
set {
self.setViewControllerValue(newValue, for: \.isAutoTabExpandEnabled)
}
}
// MARK: AppleScript Handler
/// handle the Convert AppleScript by changing the text encoding and converting the text
@objc func handleConvert(_ command: NSScriptCommand) -> NSNumber {
guard
let arguments = command.evaluatedArguments,
let encodingName = arguments["newEncoding"] as? String,
let encoding = EncodingManager.shared.encoding(name: encodingName) ?? EncodingManager.shared.encoding(ianaCharSetName: encodingName)
else {
command.scriptErrorNumber = OSAParameterMismatch
command.scriptErrorString = "Invalid encoding name."
return false
}
let withBOM = arguments["BOM"] as? Bool ?? false
let fileEncoding = FileEncoding(encoding: encoding, withUTF8BOM: withBOM)
if fileEncoding == self.fileEncoding {
return true
}
let lossy = (arguments["lossy"] as? Bool) ?? false
do {
try self.changeEncoding(to: fileEncoding, lossy: lossy)
} catch {
command.scriptErrorNumber = errOSAGeneralError
command.scriptErrorString = error.localizedDescription
return false
}
return true
}
/// handle the Convert AppleScript by changing the text encoding and reinterpreting the text
@objc func handleReinterpret(_ command: NSScriptCommand) -> NSNumber {
guard
let arguments = command.evaluatedArguments,
let encodingName = arguments["newEncoding"] as? String,
let encoding = EncodingManager.shared.encoding(name: encodingName) ?? EncodingManager.shared.encoding(ianaCharSetName: encodingName)
else {
command.scriptErrorNumber = OSAParameterMismatch
command.scriptErrorString = "Invalid encoding name."
return false
}
do {
try self.reinterpret(encoding: encoding)
} catch {
command.scriptErrorNumber = errOSAGeneralError
command.scriptErrorString = error.localizedDescription
return false
}
return true
}
/// handle the Find AppleScript command
@objc func handleFind(_ command: NSScriptCommand) -> NSNumber {
guard
let arguments = command.evaluatedArguments,
let searchString = arguments["targetString"] as? String, !searchString.isEmpty
else { return false }
let options = NSString.CompareOptions(scriptingArguments: arguments)
let isWrapSearch = (arguments["wrapSearch"] as? Bool) ?? false
// perform find
let string = self.string as NSString
guard let foundRange = string.range(of: searchString, selectedRange: self.selectedRange,
options: options, isWrapSearch: isWrapSearch)
else { return false }
self.selectedRange = foundRange
return true
}
/// handle the Replace AppleScript command
@objc func handleReplace(_ command: NSScriptCommand) -> NSNumber {
guard
let arguments = command.evaluatedArguments,
let searchString = arguments["targetString"] as? String, !searchString.isEmpty,
let replacementString = arguments["newString"] as? String
else { return 0 }
let options = NSString.CompareOptions(scriptingArguments: arguments)
let isWrapSearch = (arguments["wrapSearch"] as? Bool) ?? false
let isAll = (arguments["all"] as? Bool) ?? false
let string = self.string
guard !string.isEmpty else { return 0 }
// perform replacement
if isAll {
let mutableString = NSMutableString(string: string)
let count: Int
if options.contains(.regularExpression) {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? [.caseInsensitive] : []
guard let regex = try? NSRegularExpression(pattern: searchString, options: regexOptions.union(.anchorsMatchLines)) else {
command.scriptErrorNumber = errOSAGeneralError
command.scriptErrorString = "Invalid regular expression."
return 0
}
count = regex.replaceMatches(in: mutableString, range: string.nsRange, withTemplate: replacementString)
} else {
count = mutableString.replaceOccurrences(of: searchString, with: replacementString, options: options, range: string.nsRange)
}
guard count > 0 else { return 0 }
self.insert(string: mutableString as String, at: .replaceAll)
self.selectedRange = NSRange()
return count as NSNumber
} else {
guard let foundRange = (string as NSString).range(of: searchString, selectedRange: self.selectedRange,
options: options, isWrapSearch: isWrapSearch)
else { return 0 }
let replacedString: String
if options.contains(.regularExpression) {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
guard let regex = try? NSRegularExpression(pattern: searchString, options: regexOptions.union(.anchorsMatchLines)) else {
command.scriptErrorNumber = errOSAGeneralError
command.scriptErrorString = "Invalid regular expression."
return 0
}
guard let match = regex.firstMatch(in: string, options: .withoutAnchoringBounds, range: foundRange) else { return 0 }
replacedString = regex.replacementString(for: match, in: string, offset: 0, template: replacementString)
} else {
replacedString = replacementString
}
self.selectedRange = foundRange
self.insert(string: replacedString, at: .replaceSelection)
return 1
}
}
/// handle the Scroll AppleScript command by scrolling the text tiew to make selection visible
@objc func handleScroll(_ command: NSScriptCommand) {
self.textView?.centerSelectionInVisibleArea(nil)
}
/// handle the Jump AppleScript command by moving the cursor to the specified line and scrolling the text view to make it visible
@objc func handleJump(_ command: NSScriptCommand) {
guard
let arguments = command.evaluatedArguments,
let line = arguments["line"] as? Int
else {
command.scriptErrorNumber = OSAMissingParameter
return
}
let column = arguments["column"] as? Int ?? 0
guard let textView = self.textView else { return assertionFailure() }
let location: Int
do {
location = try textView.string.fuzzyLocation(line: line, column: column)
} catch {
command.scriptErrorNumber = OSAParameterMismatch
command.scriptErrorString = "Invalid parameter. " + error.localizedDescription
return
}
textView.selectedRange = NSRange(location: location, length: 0)
textView.centerSelectionInVisibleArea(nil)
}
/// return sting in the specified range
@objc func handleString(_ command: NSScriptCommand) -> String? {
guard
let arguments = command.evaluatedArguments,
let rangeArray = arguments["range"] as? [Int], rangeArray.count == 2
else {
command.scriptErrorNumber = OSAParameterMismatch
command.scriptErrorString = "The range paramator must be a list of {location, length}."
return nil
}
let fuzzyRange = FuzzyRange(location: rangeArray[0], length: max(rangeArray[1], 1))
guard let range = self.string.range(in: fuzzyRange) else {
command.scriptErrorNumber = OSAParameterMismatch
command.scriptErrorString = "Out of the range."
return nil
}
return (self.string as NSString).substring(with: range)
}
// MARK: Private Methods
/// Set the value to DocumentViewController but lazily by waiting the DocumentViewController is attached if it is not available yet.
///
/// When document's properties are set in the document creation phase like in the following code,
/// those setters are invoked while `self.viewController` is still `nil`.
/// Therefore, to avoid ignoring initialization, this method asynchronously waits for the DocumentViewController is available, and then sets the value.
///
/// tell application "CotEditor"
/// make new document with properties { name: "Untitled.txt", tab width: 16 }
/// end tell
///
/// - Parameters:
/// - value: The value to set.
/// - keyPath: The keyPath of the DocumentViewController to set the value.
private func setViewControllerValue<Value>(_ value: Value, for keyPath: ReferenceWritableKeyPath<DocumentViewController, Value>) {
if let viewController = self.viewController {
viewController[keyPath: keyPath] = value
return
}
weak var observer: NSObjectProtocol?
observer = NotificationCenter.default.addObserver(forName: EditorTextView.didBecomeFirstResponderNotification, object: nil, queue: .main) { [weak self] _ in
guard let viewController = self?.viewController else { return }
if let observer = observer {
NotificationCenter.default.removeObserver(observer)
}
viewController[keyPath: keyPath] = value
}
}
}
// MARK: -
private extension NSString.CompareOptions {
init(scriptingArguments arguments: [String: Any]) {
let isRegex = (arguments["regularExpression"] as? Bool) ?? false
let ignoresCase = (arguments["ignoreCase"] as? Bool) ?? false
let isBackwards = (arguments["backwardsSearch"] as? Bool) ?? false
self.init()
if isRegex {
self.formUnion(.regularExpression)
}
if ignoresCase {
self.formUnion(.caseInsensitive)
}
if isBackwards {
self.formUnion(.backwards)
}
}
}
private extension NSString {
/// Find the range of the first occurrence starting from the given selectedRange.
///
/// - Parameters:
/// - searchString: The string to search for.
/// - selectedRange: The range to search in.
/// - options: The search option.
/// - isWrapSearch: Whether the search should wrap.
/// - Returns: The range of found or `nil` if not found.
func range(of searchString: String, selectedRange: NSRange, options: NSString.CompareOptions, isWrapSearch: Bool) -> NSRange? {
guard self.length > 0 else { return nil }
let targetRange = (options.contains(.backwards) && !options.contains(.regularExpression))
? NSRange(..<selectedRange.lowerBound)
: NSRange(selectedRange.upperBound..<self.length)
var foundRange: NSRange = .notFound
if options.contains(.regularExpression) {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
guard let regex = try? NSRegularExpression(pattern: searchString, options: regexOptions.union(.anchorsMatchLines)) else { return nil }
foundRange = regex.rangeOfFirstMatch(in: self as String, options: .withoutAnchoringBounds, range: targetRange)
if foundRange == .notFound, isWrapSearch {
foundRange = regex.rangeOfFirstMatch(in: self as String, options: .withoutAnchoringBounds, range: self.range)
}
} else {
foundRange = self.range(of: searchString, options: options, range: targetRange)
if foundRange == .notFound, isWrapSearch {
foundRange = self.range(of: searchString, options: options)
}
}
guard foundRange.location != NSNotFound else { return nil }
return foundRange
}
}
| apache-2.0 | 4652941625a3dd445ad15ee950a147dc | 31.985586 | 164 | 0.569673 | 5.504209 | false | false | false | false |
jshin47/swift-reactive-viper-example | swift-reactive-viper-sample/swift-reactive-viper-sample/PuppyListView.swift | 1 | 1410 | //
// PuppyListView.swift
// swift-reactive-viper-sample
//
// Created by Justin Shin on 8/18/15.
// Copyright © 2015 EmergingMed. All rights reserved.
//
import Foundation
import UIKit
import ReactiveCocoa
class PuppyListView : ProgrammaticViewController, IPuppyListView {
private let uiSubviewNoResultsView = UILabel()
private let uiSubviewTable = UITableView()
private var container:IDependencies
private var presenter:IPuppyListPresenter {
get {
return self.container.puppyListPresenter
}
}
init(container:IDependencies) {
self.container = container
super.init()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func actionDisplayItems(items: PuppyListViewModel) {
print("Displaying \(items) items")
}
func actionToggleNoItemsMessageVisibility(visible: Bool) {
if (visible) {
print("SHOULD display NO ITEMS")
} else {
print("should NOT DISPLAY because there ARE ITEMS")
}
}
// MARK - overrides
override func createInitialView() -> UIView {
let v = super.createInitialView()
v.backgroundColor = UIColor.purpleColor()
return v
}
override func setupViewConstraints() {
}
} | mit | 8f6fb18f0bac6019548492747cd54d8d | 22.114754 | 66 | 0.619588 | 4.808874 | false | false | false | false |
frankrausch/Typographizer | Sources/String+Typographizer.swift | 1 | 538 | //
// String+Typographizer.swift
// Typographizer
//
// Created by Frank Rausch on 2017-02-04.
// Copyright © 2017 Frank Rausch.
//
import Foundation
extension String {
public func typographized(language: String, isHTML: Bool = false, debug: Bool = false, measurePerformance: Bool = false) -> String {
var t = Typographizer(language: language, text: self)
t.isHTML = isHTML
t.isDebugModeEnabled = debug
t.isMeasurePerformanceEnabled = measurePerformance
return t.typographize()
}
}
| mit | a89ed78010e6ece690657a959c639391 | 25.85 | 136 | 0.67784 | 3.653061 | false | false | false | false |
MaTriXy/androidtool-mac | AndroidTool/MasterViewController.swift | 1 | 4402 | //
// MasterViewController.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/22/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
class MasterViewController: NSViewController, DeviceDiscovererDelegate, NSTableViewDelegate, NSTableViewDataSource {
var discoverer = DeviceDiscoverer()
var devices : [Device]!
var deviceVCs = [DeviceViewController]()
var window : NSWindow!
var previousSig:Double = 0
@IBOutlet var emptyStateView: NSImageView!
@IBOutlet weak var devicesTable: NSTableView!
override func awakeFromNib() {
discoverer.delegate = self
devices = [Device]()
discoverer.start()
}
func installApk(apkPath:String){
showDevicePicker(apkPath)
}
func showDevicePicker(apkPath:String){
let devicePickerVC = DevicePickerViewController(nibName: "DevicePickerViewController", bundle: nil)
devicePickerVC?.devices = devices
devicePickerVC?.apkPath = apkPath
if #available(OSX 10.10, *) {
self.presentViewControllerAsSheet(devicePickerVC!)
} else {
// Fallback on earlier versions
}
}
func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return false
}
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
// println("asked number of rows")
if devices == nil { return 0 }
return devices.count
}
func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? {
let deviceVC = DeviceViewController(device: devices[row])
deviceVCs.append(deviceVC!) // save it from deallocation
return deviceVC?.view
}
func removeDevice(device:Device){
}
func fingerPrintForDeviceList(deviceList:[Device]) -> Double {
var total:Double = 0
for d in deviceList {
total += d.firstBoot!
}
total = total/Double(deviceList.count)
return total
}
func deviceListSignature(deviceList:[Device]) -> Double {
var total:Double = 0
for device in deviceList {
if let firstboot = device.firstBoot {
total += firstboot
}
}
let signa = total/Double(deviceList.count)
return signa
}
func showEmptyState(){
// resize window
if !emptyStateView.isDescendantOf(view) {
emptyStateView.frame.origin.y = -15
emptyStateView.frame.origin.x = 45
view.addSubview(emptyStateView)
}
}
func removeEmptyState(){
emptyStateView.removeFromSuperview()
}
func devicesUpdated(deviceList: [Device]) {
let newSig = deviceListSignature(deviceList)
if deviceList.count == 0 {
previousSig=0
devicesTable.reloadData()
showEmptyState()
} else {
removeEmptyState()
}
devices = deviceList
devices.sortInPlace({$0.model < $1.model})
// refresh each device with updated data like current activity
// for deviceVC in deviceVCs {
// for device in devices {
// if deviceVC.device.adbIdentifier == device.adbIdentifier {
// deviceVC.device = device
// deviceVC.setStatusToCurrentActivity()
// }
// }
// }
// make sure we don't refresh the tableview when it's not necessary
if newSig != previousSig {
devicesTable.reloadData()
var newHeight=Util().deviceHeight
// adjust window height accordingly
if devices.count != 0 {
newHeight = CGFloat(devices.count) * (Util().deviceHeight) + 20
} else {
newHeight = 171 // emptystate height
}
Util().changeWindowHeight(window, view: self.view, newHeight: newHeight)
previousSig = newSig
}
}
override func viewDidLoad() {
if #available(OSX 10.10, *) {
super.viewDidLoad()
} else {
// Fallback on earlier versions
}
}
}
| apache-2.0 | a4c377a6ec54d9c9ee576ceca386f01c | 27.217949 | 117 | 0.574739 | 5.166667 | false | false | false | false |
hellogaojun/Swift-coding | 06-字符和字符串/06-字符和字符串/main.swift | 1 | 4781 | //
// main.swift
// 06-字符和字符串
//
// Created by gaojun on 16/4/2.
// Copyright © 2016年 高军. All rights reserved.
//
import Foundation
print("Hello, World!")
//——————————————————————字符和字符串基本------------------------
/*
Swift和OC字符不一样
1.Swift是用双引号
2.Swift中的字符类型和OC中的也不一样, OC中的字符占一个字节,因为它只包含ASCII表中的字符, 而Swift中的字符除了可以存储ASCII表中的字符还可以存储unicode字符,
例如中文:
OC:char charValue = '李'; // 错误
Swift: var charValue2:Character = "李" // 正确
OC的字符是遵守ASCII标准的,Swift的字符是遵守unicode标准的, 所以可以存放世界上所有国家语言的字符(大部分)
*/
/*
注意: 双引号中只能放一个字符, 如下是错误写法
var charValue3:Character = "ab"
*/
//字符
var charValue : Character = "a"
print("charValue:",charValue)
var charValue1 : Character = "高"
print("charValue1:",charValue1)
/*
字符串:
字符是单个字符的集合, 字符串是多个字符的集合, 想要存放多个字符需要使用字符串
C:
char *stringValue = "ab";
char stringArr = "ab";
OC:
NSString *stringValue = "ab";
*/
//字符串
var charValue2 = "ab"
print("charValue2:",charValue2)
var charValue3 = "高军"
print("charValue3:",charValue3)
/*
C语言中的字符串是以\0结尾的, 例如:
char *stringValue = "abc\0bcd";
printf("%s", stringValue);
打印结果为abc
OC语言中的字符串也是以\0结尾的, 例如:
NSString *stringValue = @"abc\0bcd";
NSLog(@"%@", stringValue);
打印结果为abc
*/
var charValue4 = "abc\0dre"//swift中\0不是字符串的结束标志
print("charValue4:",charValue4)
// 打印结果为abcbcd
// 从此可以看出Swift中的字符串和C语言/OC语言中的字符串是不一样的
//--------------------字符和字符串构造------------------------
//计算字符串长度
var stringValue = "a"
print("stringValue长度:",stringValue.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
var stringValue1 = "abc高"//一个汉字占3个字节(8位时)
print("stringValue1长度:",stringValue1.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
/*
计算字符串长度:
C:
char *stringValue = "abc李";
printf("%tu", strlen(stringValue));
打印结果6
OC:
NSString *stringValue = @"abc李";
NSLog(@"%tu", stringValue.length);
打印结果4, 以UTF16计算
*/
//字符串拼接
var str1 = "abc"
var str2 = "Gj"
var str = str1 + str2
print("str:",str)
/*
字符串拼接
C:
char str1[] = "abc";
char *str2 = "bcd";
char *str = strcat(str1, str2);
OC:
NSMutableString *str1 = [NSMutableString stringWithString:@"abc"];
NSString *str2 = @"bcd";
[str1 appendString:str2];
NSLog(@"%@", str1);
*/
//格式化字符串
var index = 1
var str3 = "http://www.baidu.com/\(index).jpg"
print("str3:",str3)//http://www.baidu.com/1.jpg
/*
格式化字符串
C: 相当麻烦, 指针, 下标等方式
OC:
NSInteger index = 1;
NSString *str1 = [NSMutableString stringWithFormat:@"http://ios.itcast.cn/pic/%tu.png", index];
NSLog(@"%@", str1);
*/
//字符串比较
var str4 = "abc"
var str5 = "abc"
var str6 = "abd"
if str4 == str5 {
print("str4等于str5")
}
if str4 >= str6 {
print("str4大于等于str6")
}else {
print("str4小于str6")
}
/*
字符串比较:
OC:
NSString *str1 = @"abc";
NSString *str2 = @"abc";
if ([str1 compare:str2] == NSOrderedSame)
{
NSLog(@"相等");
}else
{
NSLog(@"不相等");
}
if ([str1 isEqualToString:str2])
{
NSLog(@"相等");
}else
{
NSLog(@"不相等");
}
Swift:(== / != / >= / <=), 和C语言的strcmp一样是逐个比较
*/
//判断前后缀
var str7 = "http://www.baidu.com"
if str7 .hasPrefix("http") {
print("str7是url")
}
if str7 .hasSuffix("com") {
print("str7是顶级域名")
}
/*
判断前后缀
OC:
NSString *str = @"http://ios.itcast.cn";
if ([str hasPrefix:@"http"]) {
NSLog(@"是url");
}
if ([str hasSuffix:@".cn"]) {
NSLog(@"是天朝顶级域名");
}
*/
//大小写转化
var str8 = "abc.txt"
print("小写转大写:",str8.uppercaseString)
print("大写转小写:",str8.uppercaseString.lowercaseString)
/*
大小写转换
OC:
NSString *str = @"abc.txt";
NSLog(@"%@", [str uppercaseString]);
NSLog(@"%@", [str lowercaseString]);
*/
//转换为基本数据类型(注意拆装包,好好研究)
var str9 = "123"
// 如果str不能转换为整数, 那么可选类型返回nil
// str = "250sb" 不能转换所以可能为nil
var number : Int? = Int(str9)
if number != nil {
// 以前的版本println会自动拆包, 现在的不会
print("number:",number!)
}
/*
转换为基本数据类型
OC:
NSString *str = @"250";
NSInteger number = [str integerValue];
NSLog(@"%tu", number);
*/
| apache-2.0 | d667b5ecc598c798829ad5122beb3e35 | 14.770213 | 95 | 0.651916 | 2.641483 | false | false | false | false |
tidepool-org/nutshell-ios | Nutshell/ViewControllers/EventGroupTableViewController.swift | 1 | 10654 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
import CoreData
class EventGroupTableViewController: BaseUITableViewController {
var eventGroup: NutEvent?
@IBOutlet weak var tableHeaderTitle: NutshellUILabel!
@IBOutlet weak var tableHeaderLocation: NutshellUILabel!
@IBOutlet weak var headerView: NutshellUIView!
@IBOutlet weak var headerViewLocIcon: UIImageView!
@IBOutlet weak var innerHeaderView: UIView!
@IBOutlet weak var eatAgainButton: UIButton!
@IBOutlet weak var eatAgainLabel: NutshellUILabel!
@IBOutlet weak var eatAgainLargeHitArea: UIButton!
fileprivate var isWorkout: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem?.imageInsets = UIEdgeInsetsMake(0.0, -8.0, -1.0, 0.0)
}
override func viewWillAppear(_ animated: Bool) {
NSLog("Event group viewWillAppear")
super.viewWillAppear(animated)
APIConnector.connector().trackMetric("Viewed Similar Meals Screen (Similar Meals Screen)")
if let eventGroup = eventGroup {
if eventGroup.itemArray.count >= 1 {
configureGroupView()
eventGroup.sortEvents()
tableView.reloadData()
return
}
}
// empty group!
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
}
override func viewDidLayoutSubviews() {
// Workaround: iOS currently doesn't resize table headers dynamically
if let headerView = headerView {
let height = ceil(innerHeaderView.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height)
var frame = headerView.frame
if frame.size.height != height {
NSLog("adjusting header height from \(frame.size.height) to \(height)")
frame.size.height = height
headerView.frame = frame
// set it back so table will adjust as well...
tableView.tableHeaderView = headerView
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
fileprivate func configureGroupView() {
title = ""
if let eventGroup = eventGroup {
isWorkout = eventGroup.isWorkout
eatAgainButton.isHidden = isWorkout
eatAgainLabel.isHidden = isWorkout
eatAgainLargeHitArea.isHidden = isWorkout
tableHeaderTitle.text = eventGroup.title
tableHeaderLocation.text = eventGroup.location
headerViewLocIcon.isHidden = (tableHeaderLocation.text?.isEmpty)!
}
}
//
// MARK: - Button handling
//
@IBAction func disclosureTouchDownHandler(_ sender: AnyObject) {
}
@IBAction func backButtonHandler(_ sender: AnyObject) {
APIConnector.connector().trackMetric("Clicked Back to All Events (Similar Meals Screen)")
self.performSegue(withIdentifier: "unwindSegueToDone", sender: self)
}
//
// MARK: - Navigation
//
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
super.prepare(for: segue, sender: sender)
if segue.identifier == EventViewStoryboard.SegueIdentifiers.EventItemDetailSegue {
let eventItemVC = segue.destination as! EventDetailViewController
eventItemVC.eventGroup = eventGroup
eventItemVC.title = self.title
if let cell = sender as? EventGroupTableViewCell {
eventItemVC.eventItem = cell.eventItem
} else if let collectCell = sender as? EventGroupRowCollectionCell {
eventItemVC.eventItem = collectCell.eventItem
}
APIConnector.connector().trackMetric("Clicked a Meal Instance (Similar Meals Screen)")
} else if segue.identifier == EventViewStoryboard.SegueIdentifiers.EventItemAddSegue {
let eventItemVC = segue.destination as! EventAddOrEditViewController
// no existing item to pass along...
eventItemVC.eventGroup = eventGroup
APIConnector.connector().trackMetric("Clicked Eat Again (Similar Meals Screen)")
} else {
NSLog("Unknown segue from eventGroup \(segue.identifier)")
}
}
@IBAction func done(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventGroup done")
doneCommon(segue)
}
@IBAction func doneItemDeleted(_ segue: UIStoryboardSegue) {
NSLog("unwind segue to eventGroup doneItemDeleted")
doneCommon(segue)
}
fileprivate func doneCommon(_ segue: UIStoryboardSegue) {
// update group in case it has changed!
if let eventDetailVC = segue.source as? EventDetailViewController {
self.eventGroup = eventDetailVC.eventGroup
} else if let eventAddOrEditVC = segue.source as? EventAddOrEditViewController {
self.eventGroup = eventAddOrEditVC.eventGroup
}
}
@IBAction func cancel(_ segue: UIStoryboardSegue) {
print("unwind segue to eventGroup cancel")
}
}
//
// MARK: - Table view delegate
//
extension EventGroupTableViewController {
fileprivate func itemAtIndexPathHasPhoto(_ indexPath: IndexPath) -> Bool {
if indexPath.item < eventGroup!.itemArray.count {
let eventItem = eventGroup!.itemArray[indexPath.item]
if let mealItem = eventItem as? NutMeal {
let photoUrl = mealItem.firstPictureUrl()
return !photoUrl.isEmpty
}
}
return false
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return itemAtIndexPathHasPhoto(indexPath) ? 164.0 : 80.0
}
}
//
// MARK: - Table view data source
//
extension EventGroupTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return eventGroup!.itemArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "eventItemCell", for: indexPath) as! EventGroupTableViewCell
//NSLog("Event group cellForRowAtIndexPath: \(indexPath)")
// Configure the cell...
if indexPath.item < eventGroup!.itemArray.count {
let eventItem = eventGroup!.itemArray[indexPath.item]
cell.configureCell(eventItem)
if eventItem.nutCracked {
APIConnector.connector().trackMetric("Cracked Nut Badge Appears (Similar Meals Screen)")
}
}
return cell
}
override func tableView(_ tableView: UITableView,
editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let rowAction = UITableViewRowAction(style: UITableViewRowActionStyle.normal, title: "delete") {_,indexPath in
// use dialog to confirm delete with user!
let alert = UIAlertController(title: NSLocalizedString("deleteMealAlertTitle", comment:"Are you sure?"), message: NSLocalizedString("deleteMealAlertMessage", comment:"If you delete this meal, it will be gone forever."), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertCancel", comment:"Cancel"), style: .cancel, handler: { Void in
return
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("deleteAlertOkay", comment:"Delete"), style: .default, handler: { Void in
// Delete the row from the data source
let eventItem = self.eventGroup!.itemArray[indexPath.item]
if eventItem.deleteItem() {
// Delete the row...
tableView.deleteRows(at: [indexPath], with: .fade)
self.eventGroup!.itemArray.remove(at: indexPath.item)
if self.eventGroup!.itemArray.count == 0 {
self.performSegue(withIdentifier: "unwindSegueToHome", sender: self)
}
}
return
}))
self.present(alert, animated: true, completion: nil)
}
rowAction.backgroundColor = Styles.peachDeleteColor
return [rowAction]
}
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Remove support for delete at this point...
return false
}
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
print("commitEditingStyle forRowAtIndexPath")
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
}
| bsd-2-clause | 9ecfbfad8d7f66bef0148c940f8b167e | 38.313653 | 259 | 0.648677 | 5.610321 | false | false | false | false |
PGSSoft/AutoMate | AutoMateExample/AutoMateExample/ReminderViewModel.swift | 1 | 1448 | //
// ReminderViewModel.swift
// AutoMateExample
//
// Created by Joanna Bednarz on 10/03/2017.
// Copyright © 2017 PGS Software. All rights reserved.
//
import EventKit
// MARK: - ReminderViewModel
struct ReminderViewModel {
// MARK: Properties
let title: String
let startDate: Date?
let completionDate: Date?
let calendar: String
let notes: String?
var startDateString: String? {
guard let date = startDate else { return nil }
return DateFormatter.fullDate.string(from: date)
}
var completionDateString: String? {
guard let date = completionDate else { return nil }
return DateFormatter.fullDate.string(from: date)
}
fileprivate let reminderIdentifier: String
// MARK: Initialization
init(reminder: EKReminder) {
reminderIdentifier = reminder.calendarItemIdentifier
title = reminder.title
startDate = reminder.startDateComponents?.date
completionDate = reminder.completionDate
calendar = reminder.calendar.title
notes = reminder.notes
}
}
func < (lhs: ReminderViewModel, rhs: ReminderViewModel) -> Bool {
if let lhsStartDate = lhs.startDate, let rhsStartDate = rhs.startDate, lhsStartDate != rhsStartDate {
return lhsStartDate < rhsStartDate
} else if lhs.title != rhs.title {
return lhs.title < rhs.title
}
return lhs.reminderIdentifier < rhs.reminderIdentifier
}
| mit | 1caf76ea02ae8ca2e9dd021aa48c1523 | 27.372549 | 105 | 0.683483 | 4.521875 | false | false | false | false |
stormhouse/SnapDemo | SnapDemo/SemiCircleMenu.swift | 1 | 9519 | //
// SemiCircleMenu.swift
// SnapDemo
//
// Created by stormhouse on 4/1/15.
// Copyright (c) 2015 stormhouse. All rights reserved.
//
import UIKit
let radius = 120.0
let side = 50.0
protocol SemiCircleMenuDelegate{
func didTapMenuItem(index: Int)
}
class MenuItemButton: UIButton {
var index: Int!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
init(index: Int){
super.init()
self.index = index
}
}
class SemiCircleMenu: UIView {
var delegate: SemiCircleMenuDelegate!
var navImage1: UIImage? = UIImage(named:"nav-click.png")
var navImage2: UIImage? = UIImage(named:"nav-clicked.png")
let mainButton: UIButton!
let buttonItems: Array<MenuItemButton>!
var mainButtonRecognizer: UIPanGestureRecognizer!
var expand: Bool = false
var left: Bool = true
var x: CGFloat = 16
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
init(buttonItems btnItems: Array<Dictionary<String, String>>) {
super.init()
self.clipsToBounds = false
self.mainButton = UIButton()
self.buttonItems = Array<MenuItemButton>()
for (index, item) in enumerate(btnItems) {
var img1: UIImage? = UIImage(named: item["img1"]!)
var img2: UIImage? = UIImage(named: item["img2"]!)
var btn = MenuItemButton(index: index)
btn.hidden = true
btn.setBackgroundImage(img1, forState: UIControlState.Normal)
// btn.setBackgroundImage(img2, forState: UIControlState.Highlighted)
btn.addTarget(self, action: "itemTapHandler:", forControlEvents: .TouchUpInside)
self.buttonItems.append(btn)
self.addSubview(btn)
}
mainButtonRecognizer = UIPanGestureRecognizer(target: self, action: "mainButtonHandle:")
mainButtonRecognizer.minimumNumberOfTouches = 1
mainButtonRecognizer.maximumNumberOfTouches = 1
mainButton.addGestureRecognizer(mainButtonRecognizer)
createMenu()
updateMenuConstraints()
}
func createMenu(){
//self 添加约束(自己不能决定自己的定义,在它的父级view中添加它的 约束)
mainButton.setBackgroundImage(navImage1, forState:UIControlState.Normal)
mainButton.setBackgroundImage(navImage2, forState: UIControlState.Highlighted)
mainButton.addTarget(self, action: "buttonIsTapped:", forControlEvents: .TouchUpInside)
addSubview(mainButton)
}
func itemTapHandler(sender: MenuItemButton){
updateMenu()
delegate.didTapMenuItem(sender.index!)
}
func buttonIsTapped(sender: UIButton){
updateMenu()
}
func mainButtonHandle(sender: UIPanGestureRecognizer){
if self.expand {
return
}
if sender.state == .Began{
self.x = sender.locationInView(sender.view!.superview!).x
}
if sender.state == .Ended {
let location = sender.locationInView(sender.view!.superview!)
if location.x > self.x {
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: { _ in
self.mainButton.transform = CGAffineTransformMakeTranslation(UIScreen.mainScreen().bounds.width-50-32, 0)
}, completion: { _ in
self.left = false
self.updateMenuConstraints()
})
}else{
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: { _ in
self.mainButton.transform = CGAffineTransformMakeTranslation(50+32-UIScreen.mainScreen().bounds.width, 0)
}, completion: { _ in
self.left = true
self.updateMenuConstraints()
})
}
}
}
func updateMenuConstraints(){
//mainButton snap约束
// mainButton.snp_makeConstraints { make in
// make.center.equalTo(self.snp_center)
// make.height.equalTo(side)
// make.width.equalTo(side)
// make.bottom.equalTo(-16)
// make.left.equalTo(16)
// }
//mainButton 约束
// mainButton.setTranslatesAutoresizingMaskIntoConstraints(false)
// mainButton.addConstraint(NSLayoutConstraint(
// item: mainButton,
// attribute: NSLayoutAttribute.Height,
// relatedBy: NSLayoutRelation.Equal,
// toItem: nil,
// attribute: NSLayoutAttribute.NotAnAttribute,
// multiplier: 1,
// constant: 50
// ))
// mainButton.addConstraint(NSLayoutConstraint(
// item: mainButton,
// attribute: NSLayoutAttribute.Width,
// relatedBy: NSLayoutRelation.Equal,
// toItem: nil,
// attribute: NSLayoutAttribute.NotAnAttribute,
// multiplier: 1,
// constant: 50
// ))
// self.addConstraint(NSLayoutConstraint(
// item: mainButton,
// attribute: NSLayoutAttribute.Left,
// relatedBy: NSLayoutRelation.Equal,
// toItem: self,
// attribute: NSLayoutAttribute.Left,
// multiplier: 1,
// constant: 16
// ))
// self.addConstraint(NSLayoutConstraint(
// item: mainButton,
// attribute: NSLayoutAttribute.Bottom,
// relatedBy: NSLayoutRelation.Equal,
// toItem: self,
// attribute: NSLayoutAttribute.Bottom,
// multiplier: 1,
// constant: -16
// ))
mainButton.transform = CGAffineTransformIdentity
if self.left {
for button in buttonItems{
button.snp_remakeConstraints { make in
make.width.equalTo(side)
make.height.equalTo(side)
make.bottom.equalTo(-16)
make.left.equalTo(16)
}
}
mainButton.snp_remakeConstraints { make in
// make.center.equalTo(self.snp_center)
make.height.equalTo(side)
make.width.equalTo(side)
make.bottom.equalTo(-16)
make.left.equalTo(16)
}
}else{
for button in buttonItems{
button.snp_remakeConstraints { make in
make.width.equalTo(side)
make.height.equalTo(side)
make.bottom.equalTo(-16)
make.right.equalTo(-16)
}
}
mainButton.snp_remakeConstraints { make in
// make.center.equalTo(self.snp_center)
make.height.equalTo(side)
make.width.equalTo(side)
make.bottom.equalTo(-16)
make.right.equalTo(-16)
}
}
}
func updateMenu(){
if self.expand {
mainButton.setBackgroundImage(navImage1, forState:UIControlState.Normal)
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: { _ in
for item in self.buttonItems{
item.transform = CGAffineTransformIdentity
}
}, completion: { _ in
self.expand = false
for item in self.buttonItems{
item.hidden = true
}
})
}else{
mainButton.setBackgroundImage(navImage2, forState:UIControlState.Normal)
for item in self.buttonItems{
item.hidden = false
}
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: nil, animations: { _ in
let num = self.buttonItems.count
let degree: Double = 90.0 / Double(num-1)
for (index, item) in enumerate(self.buttonItems) {
let radian = degree * Double(index) * M_PI / 180.0
var x = CGFloat(Int((sin(radian) * radius)*100))/100
var y = -CGFloat(Int((cos(radian) * radius)*100))/100
if !self.left{
x = -x
}
// println("x:\(x)----y:\(y)")
var t = CGAffineTransformMakeTranslation(x, y)
var s = CGAffineTransformMakeScale(1.1, 1.1)
item.transform = CGAffineTransformConcat(s, t)
}
}, completion: { _ in
self.expand = true
})
}
}
override func updateConstraints() {
super.updateConstraints()
}
}
| apache-2.0 | 09d48710964bd231c460e326850379c7 | 33.257246 | 149 | 0.538128 | 5.026582 | false | false | false | false |
JakeLin/IBAnimatable | Sources/Enums/GradientStartPoint.swift | 2 | 2478 | //
// Created by Jake Lin on 12/2/15.
// Copyright © 2015 IBAnimatable. All rights reserved.
//
import UIKit
public enum GradientStartPoint: IBEnum {
case top
case topRight
case right
case bottomRight
case bottom
case bottomLeft
case left
case topLeft
case custom(start: CGPoint, end: CGPoint)
case none
}
extension GradientStartPoint {
public init(string: String?) {
guard let string = string else {
self = .none
return
}
guard let (name, params) = string.extractNameAndParams() else {
self = .none
return
}
switch name {
case "top":
self = .top
case "topright":
self = .topRight
case "right":
self = .right
case "bottomright":
self = .bottomRight
case "bottom":
self = .bottom
case "bottomleft":
self = .bottomLeft
case "left":
self = .left
case "topleft":
self = .topLeft
case "custom":
self = .custom(start: CGPoint(x: params.toDouble(0) ?? 0,
y: params.toDouble(1) ?? 0),
end: CGPoint(x: params.toDouble(2) ?? 0,
y: params.toDouble(3) ?? 0))
default:
self = .none
}
}
}
extension GradientStartPoint {
var startPoint: CGPoint {
switch self {
case .top:
return CGPoint(x: 0.5, y: 0)
case .topRight:
return CGPoint(x: 1, y: 0)
case .right:
return CGPoint(x: 1, y: 0.5)
case .bottomRight:
return CGPoint(x: 1, y: 1)
case .bottom:
return CGPoint(x: 0.5, y: 1)
case .bottomLeft:
return CGPoint(x: 0, y: 1)
case .left:
return CGPoint(x: 0, y: 0.5)
case .topLeft:
return CGPoint(x: 0, y: 0)
case let .custom(start, _):
return start
case .none:
return .zero
}
}
var endPoint: CGPoint {
switch self {
case .top:
return CGPoint(x: 0.5, y: 1)
case .topRight:
return CGPoint(x: 0, y: 1)
case .right:
return CGPoint(x: 0, y: 0.5)
case .bottomRight:
return CGPoint(x: 0, y: 0)
case .bottom:
return CGPoint(x: 0.5, y: 0)
case .bottomLeft:
return CGPoint(x: 1, y: 0)
case .left:
return CGPoint(x: 1, y: 0.5)
case .topLeft:
return CGPoint(x: 1, y: 1)
case let .custom(_, end):
return end
case .none:
return .zero
}
}
var points: (CGPoint, CGPoint) {
return (startPoint, endPoint)
}
}
| mit | 284b1033fbedd276633c5c4a3aa71769 | 20.53913 | 67 | 0.551474 | 3.574315 | false | false | false | false |
russbishop/swift | test/Interpreter/SDK/FoundationDiagnostics.swift | 1 | 631 | // RUN: %target-swift-frontend %s -parse -verify
// REQUIRES: objc_interop
import Foundation
func useUnavailable() {
var a = NSSimpleCString() // expected-error {{'NSSimpleCString' is unavailable}}
var b = NSConstantString() // expected-error {{'NSConstantString' is unavailable}}
}
func encode(_ string: String) {
_ = string.cString(using: NSUTF8StringEncoding) // expected-error {{'NSUTF8StringEncoding' has been renamed to 'String.Encoding.utf8'}} {{29-49=String.Encoding.utf8}}
let _: NSStringEncoding? = nil // expected-error {{'NSStringEncoding' has been renamed to 'String.Encoding'}} {{10-26=String.Encoding}}
} | apache-2.0 | 08cf5e1c45293f5e8e9cbd03922fa0fe | 41.133333 | 168 | 0.724247 | 3.824242 | false | false | false | false |
archagon/tasty-imitation-keyboard | Keyboard/KeyboardViewController.swift | 1 | 33984 | //
// KeyboardViewController.swift
// Keyboard
//
// Created by Alexei Baboulevitch on 6/9/14.
// Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved.
//
import UIKit
import AudioToolbox
let metrics: [String:Double] = [
"topBanner": 30
]
func metric(_ name: String) -> CGFloat { return CGFloat(metrics[name]!) }
// TODO: move this somewhere else and localize
let kAutoCapitalization = "kAutoCapitalization"
let kPeriodShortcut = "kPeriodShortcut"
let kKeyboardClicks = "kKeyboardClicks"
let kSmallLowercase = "kSmallLowercase"
class KeyboardViewController: UIInputViewController {
let backspaceDelay: TimeInterval = 0.5
let backspaceRepeat: TimeInterval = 0.07
var keyboard: Keyboard!
var forwardingView: ForwardingView!
var layout: KeyboardLayout?
var heightConstraint: NSLayoutConstraint?
var bannerView: ExtraView?
var settingsView: ExtraView?
var currentMode: Int {
didSet {
if oldValue != currentMode {
setMode(currentMode)
}
}
}
var backspaceActive: Bool {
get {
return (backspaceDelayTimer != nil) || (backspaceRepeatTimer != nil)
}
}
var backspaceDelayTimer: Timer?
var backspaceRepeatTimer: Timer?
enum AutoPeriodState {
case noSpace
case firstSpace
}
var autoPeriodState: AutoPeriodState = .noSpace
var lastCharCountInBeforeContext: Int = 0
var shiftState: ShiftState {
didSet {
switch shiftState {
case .disabled:
self.updateKeyCaps(false)
case .enabled:
self.updateKeyCaps(true)
case .locked:
self.updateKeyCaps(true)
}
}
}
// state tracking during shift tap
var shiftWasMultitapped: Bool = false
var shiftStartingState: ShiftState?
var keyboardHeight: CGFloat {
get {
if let constraint = self.heightConstraint {
return constraint.constant
}
else {
return 0
}
}
set {
self.setHeight(newValue)
}
}
// TODO: why does the app crash if this isn't here?
convenience init() {
self.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
UserDefaults.standard.register(defaults: [
kAutoCapitalization: true,
kPeriodShortcut: true,
kKeyboardClicks: false,
kSmallLowercase: false
])
self.keyboard = defaultKeyboard()
self.shiftState = .disabled
self.currentMode = 0
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.forwardingView = ForwardingView(frame: CGRect.zero)
self.view.addSubview(self.forwardingView)
NotificationCenter.default.addObserver(self, selector: #selector(KeyboardViewController.defaultsChanged(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
required init?(coder: NSCoder) {
fatalError("NSCoding not supported")
}
deinit {
backspaceDelayTimer?.invalidate()
backspaceRepeatTimer?.invalidate()
NotificationCenter.default.removeObserver(self)
}
func defaultsChanged(_ notification: Notification) {
//let defaults = notification.object as? NSUserDefaults
self.updateKeyCaps(self.shiftState.uppercase())
}
// without this here kludge, the height constraint for the keyboard does not work for some reason
var kludge: UIView?
func setupKludge() {
if self.kludge == nil {
let kludge = UIView()
self.view.addSubview(kludge)
kludge.translatesAutoresizingMaskIntoConstraints = false
kludge.isHidden = true
let a = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.left, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let b = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.right, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.left, multiplier: 1, constant: 0)
let c = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
let d = NSLayoutConstraint(item: kludge, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)
self.view.addConstraints([a, b, c, d])
self.kludge = kludge
}
}
/*
BUG NOTE
For some strange reason, a layout pass of the entire keyboard is triggered
whenever a popup shows up, if one of the following is done:
a) The forwarding view uses an autoresizing mask.
b) The forwarding view has constraints set anywhere other than init.
On the other hand, setting (non-autoresizing) constraints or just setting the
frame in layoutSubviews works perfectly fine.
I don't really know what to make of this. Am I doing Autolayout wrong, is it
a bug, or is it expected behavior? Perhaps this has to do with the fact that
the view's frame is only ever explicitly modified when set directly in layoutSubviews,
and not implicitly modified by various Autolayout constraints
(even though it should really not be changing).
*/
var constraintsAdded: Bool = false
func setupLayout() {
if !constraintsAdded {
self.layout = type(of: self).layoutClass.init(model: self.keyboard, superview: self.forwardingView, layoutConstants: type(of: self).layoutConstants, globalColors: type(of: self).globalColors, darkMode: self.darkMode(), solidColorMode: self.solidColorMode())
self.layout?.initialize()
self.setMode(0)
self.setupKludge()
self.updateKeyCaps(self.shiftState.uppercase())
self.updateCapsIfNeeded()
self.updateAppearances(self.darkMode())
self.addInputTraitsObservers()
self.constraintsAdded = true
}
}
// only available after frame becomes non-zero
func darkMode() -> Bool {
let darkMode = { () -> Bool in
let proxy = self.textDocumentProxy
return proxy.keyboardAppearance == UIKeyboardAppearance.dark
}()
return darkMode
}
func solidColorMode() -> Bool {
return UIAccessibilityIsReduceTransparencyEnabled()
}
var lastLayoutBounds: CGRect?
override func viewDidLayoutSubviews() {
if view.bounds == CGRect.zero {
return
}
self.setupLayout()
let orientationSavvyBounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.height(forOrientation: self.interfaceOrientation, withTopBanner: false))
if (lastLayoutBounds != nil && lastLayoutBounds == orientationSavvyBounds) {
// do nothing
}
else {
let uppercase = self.shiftState.uppercase()
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
self.forwardingView.frame = orientationSavvyBounds
self.layout?.layoutKeys(self.currentMode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.lastLayoutBounds = orientationSavvyBounds
self.setupKeys()
}
self.bannerView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: metric("topBanner"))
let newOrigin = CGPoint(x: 0, y: self.view.bounds.height - self.forwardingView.bounds.height)
self.forwardingView.frame.origin = newOrigin
}
override func loadView() {
super.loadView()
if let aBanner = self.createBanner() {
aBanner.isHidden = true
self.view.insertSubview(aBanner, belowSubview: self.forwardingView)
self.bannerView = aBanner
}
}
override func viewWillAppear(_ animated: Bool) {
self.bannerView?.isHidden = false
self.keyboardHeight = self.height(forOrientation: self.interfaceOrientation, withTopBanner: true)
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
// optimization: ensures smooth animation
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = true
}
}
self.keyboardHeight = self.height(forOrientation: toInterfaceOrientation, withTopBanner: true)
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
// optimization: ensures quick mode and shift transitions
if let keyPool = self.layout?.keyPool {
for view in keyPool {
view.shouldRasterize = false
}
}
}
func height(forOrientation orientation: UIInterfaceOrientation, withTopBanner: Bool) -> CGFloat {
let isPad = UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
// AB: consider re-enabling this when interfaceOrientation actually breaks
//// HACK: Detecting orientation manually
//let screenSize: CGSize = UIScreen.main.bounds.size
//let orientation: UIInterfaceOrientation = screenSize.width < screenSize.height ? .portrait : .landscapeLeft
//TODO: hardcoded stuff
let actualScreenWidth = (UIScreen.main.nativeBounds.size.width / UIScreen.main.nativeScale)
let canonicalPortraitHeight: CGFloat
let canonicalLandscapeHeight: CGFloat
if isPad {
canonicalPortraitHeight = 264
canonicalLandscapeHeight = 352
}
else {
canonicalPortraitHeight = orientation.isPortrait && actualScreenWidth >= 400 ? 226 : 216
canonicalLandscapeHeight = 162
}
let topBannerHeight = (withTopBanner ? metric("topBanner") : 0)
return CGFloat(orientation.isPortrait ? canonicalPortraitHeight + topBannerHeight : canonicalLandscapeHeight + topBannerHeight)
}
/*
BUG NOTE
None of the UIContentContainer methods are called for this controller.
*/
//override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
// super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
//}
func setupKeys() {
if self.layout == nil {
return
}
for page in keyboard.pages {
for rowKeys in page.rows { // TODO: quick hack
for key in rowKeys {
if let keyView = self.layout?.viewForKey(key) {
keyView.removeTarget(nil, action: nil, for: UIControlEvents.allEvents)
switch key.type {
case Key.KeyType.keyboardChange:
keyView.addTarget(self,
action: #selector(KeyboardViewController.advanceTapped(_:)),
for: .touchUpInside)
case Key.KeyType.backspace:
let cancelEvents: UIControlEvents = [UIControlEvents.touchUpInside, UIControlEvents.touchUpInside, UIControlEvents.touchDragExit, UIControlEvents.touchUpOutside, UIControlEvents.touchCancel, UIControlEvents.touchDragOutside]
keyView.addTarget(self,
action: #selector(KeyboardViewController.backspaceDown(_:)),
for: .touchDown)
keyView.addTarget(self,
action: #selector(KeyboardViewController.backspaceUp(_:)),
for: cancelEvents)
case Key.KeyType.shift:
keyView.addTarget(self,
action: #selector(KeyboardViewController.shiftDown(_:)),
for: .touchDown)
keyView.addTarget(self,
action: #selector(KeyboardViewController.shiftUp(_:)),
for: .touchUpInside)
keyView.addTarget(self,
action: #selector(KeyboardViewController.shiftDoubleTapped(_:)),
for: .touchDownRepeat)
case Key.KeyType.modeChange:
keyView.addTarget(self,
action: #selector(KeyboardViewController.modeChangeTapped(_:)),
for: .touchDown)
case Key.KeyType.settings:
keyView.addTarget(self,
action: #selector(KeyboardViewController.toggleSettings),
for: .touchUpInside)
default:
break
}
if key.isCharacter {
if UIDevice.current.userInterfaceIdiom != UIUserInterfaceIdiom.pad {
keyView.addTarget(self,
action: #selector(KeyboardViewController.showPopup(_:)),
for: [.touchDown, .touchDragInside, .touchDragEnter])
keyView.addTarget(keyView,
action: #selector(KeyboardKey.hidePopup),
for: [.touchDragExit, .touchCancel])
keyView.addTarget(self,
action: #selector(KeyboardViewController.hidePopupDelay(_:)),
for: [.touchUpInside, .touchUpOutside, .touchDragOutside])
}
}
if key.hasOutput {
keyView.addTarget(self,
action: #selector(KeyboardViewController.keyPressedHelper(_:)),
for: .touchUpInside)
}
if key.type != Key.KeyType.shift && key.type != Key.KeyType.modeChange {
keyView.addTarget(self,
action: #selector(KeyboardViewController.highlightKey(_:)),
for: [.touchDown, .touchDragInside, .touchDragEnter])
keyView.addTarget(self,
action: #selector(KeyboardViewController.unHighlightKey(_:)),
for: [.touchUpInside, .touchUpOutside, .touchDragOutside, .touchDragExit, .touchCancel])
}
keyView.addTarget(self,
action: #selector(KeyboardViewController.playKeySound),
for: .touchDown)
}
}
}
}
}
/////////////////
// POPUP DELAY //
/////////////////
var keyWithDelayedPopup: KeyboardKey?
var popupDelayTimer: Timer?
func showPopup(_ sender: KeyboardKey) {
if sender == self.keyWithDelayedPopup {
self.popupDelayTimer?.invalidate()
}
sender.showPopup()
}
func hidePopupDelay(_ sender: KeyboardKey) {
self.popupDelayTimer?.invalidate()
if sender != self.keyWithDelayedPopup {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = sender
}
if sender.popup != nil {
self.popupDelayTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(KeyboardViewController.hidePopupCallback), userInfo: nil, repeats: false)
}
}
func hidePopupCallback() {
self.keyWithDelayedPopup?.hidePopup()
self.keyWithDelayedPopup = nil
self.popupDelayTimer = nil
}
/////////////////////
// POPUP DELAY END //
/////////////////////
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated
}
// TODO: this is currently not working as intended; only called when selection changed -- iOS bug
override func textDidChange(_ textInput: UITextInput?) {
self.contextChanged()
}
func contextChanged() {
self.updateCapsIfNeeded()
self.autoPeriodState = .noSpace
}
func setHeight(_ height: CGFloat) {
if self.heightConstraint == nil {
self.heightConstraint = NSLayoutConstraint(
item:self.view,
attribute:NSLayoutAttribute.height,
relatedBy:NSLayoutRelation.equal,
toItem:nil,
attribute:NSLayoutAttribute.notAnAttribute,
multiplier:0,
constant:height)
self.heightConstraint!.priority = 1000
self.view.addConstraint(self.heightConstraint!) // TODO: what if view already has constraint added?
}
else {
self.heightConstraint?.constant = height
}
}
func updateAppearances(_ appearanceIsDark: Bool) {
self.layout?.solidColorMode = self.solidColorMode()
self.layout?.darkMode = appearanceIsDark
self.layout?.updateKeyAppearance()
self.bannerView?.darkMode = appearanceIsDark
self.settingsView?.darkMode = appearanceIsDark
}
func highlightKey(_ sender: KeyboardKey) {
sender.isHighlighted = true
}
func unHighlightKey(_ sender: KeyboardKey) {
sender.isHighlighted = false
}
func keyPressedHelper(_ sender: KeyboardKey) {
if let model = self.layout?.keyForView(sender) {
self.keyPressed(model)
// auto exit from special char subkeyboard
if model.type == Key.KeyType.space || model.type == Key.KeyType.return {
self.currentMode = 0
}
else if model.lowercaseOutput == "'" {
self.currentMode = 0
}
else if model.type == Key.KeyType.character {
self.currentMode = 0
}
// auto period on double space
// TODO: timeout
self.handleAutoPeriod(model)
// TODO: reset context
}
self.updateCapsIfNeeded()
}
func handleAutoPeriod(_ key: Key) {
if !UserDefaults.standard.bool(forKey: kPeriodShortcut) {
return
}
if self.autoPeriodState == .firstSpace {
if key.type != Key.KeyType.space {
self.autoPeriodState = .noSpace
return
}
let charactersAreInCorrectState = { () -> Bool in
let previousContext = self.textDocumentProxy.documentContextBeforeInput
if previousContext == nil || (previousContext!).characters.count < 3 {
return false
}
var index = previousContext!.endIndex
index = previousContext!.index(before: index)
if previousContext![index] != " " {
return false
}
index = previousContext!.index(before: index)
if previousContext![index] != " " {
return false
}
index = previousContext!.index(before: index)
let char = previousContext![index]
if self.characterIsWhitespace(char) || self.characterIsPunctuation(char) || char == "," {
return false
}
return true
}()
if charactersAreInCorrectState {
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.deleteBackward()
self.textDocumentProxy.insertText(".")
self.textDocumentProxy.insertText(" ")
}
self.autoPeriodState = .noSpace
}
else {
if key.type == Key.KeyType.space {
self.autoPeriodState = .firstSpace
}
}
}
func cancelBackspaceTimers() {
self.backspaceDelayTimer?.invalidate()
self.backspaceRepeatTimer?.invalidate()
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = nil
}
func backspaceDown(_ sender: KeyboardKey) {
self.cancelBackspaceTimers()
self.textDocumentProxy.deleteBackward()
self.updateCapsIfNeeded()
// trigger for subsequent deletes
self.backspaceDelayTimer = Timer.scheduledTimer(timeInterval: backspaceDelay - backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceDelayCallback), userInfo: nil, repeats: false)
}
func backspaceUp(_ sender: KeyboardKey) {
self.cancelBackspaceTimers()
}
func backspaceDelayCallback() {
self.backspaceDelayTimer = nil
self.backspaceRepeatTimer = Timer.scheduledTimer(timeInterval: backspaceRepeat, target: self, selector: #selector(KeyboardViewController.backspaceRepeatCallback), userInfo: nil, repeats: true)
}
func backspaceRepeatCallback() {
self.playKeySound()
self.textDocumentProxy.deleteBackward()
self.updateCapsIfNeeded()
}
func shiftDown(_ sender: KeyboardKey) {
self.shiftStartingState = self.shiftState
if let shiftStartingState = self.shiftStartingState {
if shiftStartingState.uppercase() {
// handled by shiftUp
return
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
func shiftUp(_ sender: KeyboardKey) {
if self.shiftWasMultitapped {
// do nothing
}
else {
if let shiftStartingState = self.shiftStartingState {
if !shiftStartingState.uppercase() {
// handled by shiftDown
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .disabled
}
(sender.shape as? ShiftShape)?.withLock = false
}
}
}
self.shiftStartingState = nil
self.shiftWasMultitapped = false
}
func shiftDoubleTapped(_ sender: KeyboardKey) {
self.shiftWasMultitapped = true
switch self.shiftState {
case .disabled:
self.shiftState = .locked
case .enabled:
self.shiftState = .locked
case .locked:
self.shiftState = .disabled
}
}
func updateKeyCaps(_ uppercase: Bool) {
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
self.layout?.updateKeyCaps(false, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
}
func modeChangeTapped(_ sender: KeyboardKey) {
if let toMode = self.layout?.viewToModel[sender]?.toMode {
self.currentMode = toMode
}
}
func setMode(_ mode: Int) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
let uppercase = self.shiftState.uppercase()
let characterUppercase = (UserDefaults.standard.bool(forKey: kSmallLowercase) ? uppercase : true)
self.layout?.layoutKeys(mode, uppercase: uppercase, characterUppercase: characterUppercase, shiftState: self.shiftState)
self.setupKeys()
}
func advanceTapped(_ sender: KeyboardKey) {
self.forwardingView.resetTrackedViews()
self.shiftStartingState = nil
self.shiftWasMultitapped = false
self.advanceToNextInputMode()
}
@IBAction func toggleSettings() {
// lazy load settings
if self.settingsView == nil {
if let aSettings = self.createSettings() {
aSettings.darkMode = self.darkMode()
aSettings.isHidden = true
self.view.addSubview(aSettings)
self.settingsView = aSettings
aSettings.translatesAutoresizingMaskIntoConstraints = false
let widthConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.width, multiplier: 1, constant: 0)
let heightConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.height, multiplier: 1, constant: 0)
let centerXConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
let centerYConstraint = NSLayoutConstraint(item: aSettings, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
self.view.addConstraint(widthConstraint)
self.view.addConstraint(heightConstraint)
self.view.addConstraint(centerXConstraint)
self.view.addConstraint(centerYConstraint)
}
}
if let settings = self.settingsView {
let hidden = settings.isHidden
settings.isHidden = !hidden
self.forwardingView.isHidden = hidden
self.forwardingView.isUserInteractionEnabled = !hidden
self.bannerView?.isHidden = hidden
}
}
func updateCapsIfNeeded() {
if self.shouldAutoCapitalize() {
switch self.shiftState {
case .disabled:
self.shiftState = .enabled
case .enabled:
self.shiftState = .enabled
case .locked:
self.shiftState = .locked
}
}
else {
switch self.shiftState {
case .disabled:
self.shiftState = .disabled
case .enabled:
self.shiftState = .disabled
case .locked:
self.shiftState = .locked
}
}
}
func characterIsPunctuation(_ character: Character) -> Bool {
return (character == ".") || (character == "!") || (character == "?")
}
func characterIsNewline(_ character: Character) -> Bool {
return (character == "\n") || (character == "\r")
}
func characterIsWhitespace(_ character: Character) -> Bool {
// there are others, but who cares
return (character == " ") || (character == "\n") || (character == "\r") || (character == "\t")
}
func stringIsWhitespace(_ string: String?) -> Bool {
if string != nil {
for char in (string!).characters {
if !characterIsWhitespace(char) {
return false
}
}
}
return true
}
func shouldAutoCapitalize() -> Bool {
if !UserDefaults.standard.bool(forKey: kAutoCapitalization) {
return false
}
let traits = self.textDocumentProxy
if let autocapitalization = traits.autocapitalizationType {
let documentProxy = self.textDocumentProxy
//var beforeContext = documentProxy.documentContextBeforeInput
switch autocapitalization {
case .none:
return false
case .words:
if let beforeContext = documentProxy.documentContextBeforeInput {
let previousCharacter = beforeContext[beforeContext.characters.index(before: beforeContext.endIndex)]
return self.characterIsWhitespace(previousCharacter)
}
else {
return true
}
case .sentences:
if let beforeContext = documentProxy.documentContextBeforeInput {
let offset = min(3, beforeContext.characters.count)
var index = beforeContext.endIndex
for i in 0 ..< offset {
index = beforeContext.index(before: index)
let char = beforeContext[index]
if characterIsPunctuation(char) {
if i == 0 {
return false //not enough spaces after punctuation
}
else {
return true //punctuation with at least one space after it
}
}
else {
if !characterIsWhitespace(char) {
return false //hit a foreign character before getting to 3 spaces
}
else if characterIsNewline(char) {
return true //hit start of line
}
}
}
return true //either got 3 spaces or hit start of line
}
else {
return true
}
case .allCharacters:
return true
}
}
else {
return false
}
}
// this only works if full access is enabled
func playKeySound() {
if !UserDefaults.standard.bool(forKey: kKeyboardClicks) {
return
}
DispatchQueue.global(qos: .default).async(execute: {
AudioServicesPlaySystemSound(1104)
})
}
//////////////////////////////////////
// MOST COMMONLY EXTENDABLE METHODS //
//////////////////////////////////////
class var layoutClass: KeyboardLayout.Type { get { return KeyboardLayout.self }}
class var layoutConstants: LayoutConstants.Type { get { return LayoutConstants.self }}
class var globalColors: GlobalColors.Type { get { return GlobalColors.self }}
func keyPressed(_ key: Key) {
self.textDocumentProxy.insertText(key.outputForCase(self.shiftState.uppercase()))
}
// a banner that sits in the empty space on top of the keyboard
func createBanner() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
//return ExtraView(globalColors: self.dynamicType.globalColors, darkMode: false, solidColorMode: self.solidColorMode())
return nil
}
// a settings view that replaces the keyboard when the settings button is pressed
func createSettings() -> ExtraView? {
// note that dark mode is not yet valid here, so we just put false for clarity
let settingsView = DefaultSettings(globalColors: type(of: self).globalColors, darkMode: false, solidColorMode: self.solidColorMode())
settingsView.backButton?.addTarget(self, action: #selector(KeyboardViewController.toggleSettings), for: UIControlEvents.touchUpInside)
return settingsView
}
}
| bsd-3-clause | c27c84508cc7fba11c57209a97b9a5f4 | 38.062069 | 269 | 0.554702 | 6.288675 | false | false | false | false |
blighli/iPhone2015 | 21551047黄鑫/FinalAssignment/The Ending/ComposeBeginningView.swift | 1 | 1322 | //
// ComposeBeginningView.swift
// The Ending
//
// Created by Xin on 24/12/2015.
// Copyright © 2015 Huang Xin. All rights reserved.
//
import UIKit
class ComposeBeginningView: UIView {
private struct Constants {
static let EdgeInset: CGFloat = 10//字体左右间距
static let StartFontColor: UIColor = UIColor(red: 0.6824, green: 0.6824, blue: 0.6824, alpha: 1)//字体颜色
}
var contentView: StoryCardView!
override func awakeFromNib() {
contentView = NSBundle.mainBundle().loadNibNamed("StoryCardView", owner: self, options: nil).last as! StoryCardView
addSubview(contentView)
contentView.frame = self.bounds
contentView.story.selectable = true
contentView.story.textContainerInset = UIEdgeInsets(top: Constants.EdgeInset, left: Constants.EdgeInset, bottom: 0, right: Constants.EdgeInset)
contentView.story.attributedText = AppUtils.attributedString("\n 请发起一段开头吧!", attributes: [NSForegroundColorAttributeName, NSFontAttributeName], values: [Constants.StartFontColor, UIFont(name: "PingFang SC", size: 15.0)!], inRange: [NSMakeRange(0, 13), NSMakeRange(0, 13)])
contentView.eyeView.layer.opacity = 0
}
override func setNeedsDisplay() {
super.setNeedsDisplay()
}
}
| mit | bc85bf97c6473efcbf0d4e8fd4e54da3 | 37.939394 | 282 | 0.696498 | 4.312081 | false | false | false | false |
cnoon/CollectionViewAnimations | Source/Sticky Headers/Layout.swift | 1 | 9623 | //
// ExpandCollapseLayout.swift
// Sticky Headers
//
// Created by Christian Noon on 10/29/15.
// Copyright © 2015 Noondev. All rights reserved.
//
import UIKit
class Layout: UICollectionViewLayout {
// MARK: - Helper Types
struct SectionLimit {
let top: CGFloat
let bottom: CGFloat
}
// MARK: - Properties
var previousAttributes: [[UICollectionViewLayoutAttributes]] = []
var currentAttributes: [[UICollectionViewLayoutAttributes]] = []
var previousSectionAttributes: [UICollectionViewLayoutAttributes] = []
var currentSectionAttributes: [UICollectionViewLayoutAttributes] = []
var currentSectionLimits: [SectionLimit] = []
let sectionHeaderHeight: CGFloat = 40
var contentSize = CGSizeZero
var selectedCellIndexPath: NSIndexPath?
// MARK: - Preparation
override func prepareLayout() {
super.prepareLayout()
prepareContentCellAttributes()
prepareSectionHeaderAttributes()
}
private func prepareContentCellAttributes() {
guard let collectionView = collectionView else { return }
//================== Reset Content Cell Attributes ================
previousAttributes = currentAttributes
contentSize = CGSizeZero
currentAttributes = []
currentSectionLimits = []
//================== Calculate New Content Cell Attributes ==================
let width = collectionView.bounds.size.width
var y: CGFloat = 0
for sectionIndex in 0..<collectionView.numberOfSections() {
let itemCount = collectionView.numberOfItemsInSection(sectionIndex)
let sectionTop = y
y += sectionHeaderHeight
var attributesList: [UICollectionViewLayoutAttributes] = []
for itemIndex in 0..<itemCount {
let indexPath = NSIndexPath(forItem: itemIndex, inSection: sectionIndex)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
let size = CGSize(
width: width,
height: indexPath == selectedCellIndexPath ? 300.0 : 100.0
)
attributes.frame = CGRectMake(0, y, width, size.height)
attributesList.append(attributes)
y += size.height
}
let sectionBottom = y
currentSectionLimits.append(SectionLimit(top: sectionTop, bottom: sectionBottom))
currentAttributes.append(attributesList)
}
contentSize = CGSizeMake(width, y)
}
private func prepareSectionHeaderAttributes() {
guard let collectionView = collectionView else { return }
//================== Reset Section Attributes ====================
previousSectionAttributes = currentSectionAttributes
currentSectionAttributes = []
//==================== Calculate New Section Attributes ===================
let width = collectionView.bounds.size.width
let collectionViewTop = collectionView.contentOffset.y
let aboveCollectionViewTop = collectionViewTop - sectionHeaderHeight
for sectionIndex in 0..<collectionView.numberOfSections() {
let sectionLimit = currentSectionLimits[sectionIndex]
//================= Add Section Header Attributes =================
let indexPath = NSIndexPath(forItem: 0, inSection: sectionIndex)
let attributes = UICollectionViewLayoutAttributes(
forSupplementaryViewOfKind: SectionHeaderCell.kind,
withIndexPath: indexPath
)
attributes.zIndex = 1
attributes.frame = CGRectMake(0, sectionLimit.top, width, sectionHeaderHeight)
//================== Set the y-position ==================
let sectionTop = sectionLimit.top
let sectionBottom = sectionLimit.bottom - sectionHeaderHeight
attributes.frame.origin.y = min(
max(sectionTop, collectionViewTop),
max(sectionBottom, aboveCollectionViewTop)
)
currentSectionAttributes.append(attributes)
}
}
// MARK: - Layout Attributes - Content Cell
override func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return previousAttributes[itemIndexPath.section][itemIndexPath.item]
}
override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return currentAttributes[indexPath.section][indexPath.item]
}
override func finalLayoutAttributesForDisappearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? {
return layoutAttributesForItemAtIndexPath(itemIndexPath)
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attributes: [UICollectionViewLayoutAttributes] = []
for sectionIndex in 0..<(collectionView?.numberOfSections() ?? 0) {
let sectionAttributes = currentSectionAttributes[sectionIndex]
if CGRectIntersectsRect(rect, sectionAttributes.frame) {
attributes.append(sectionAttributes)
}
for item in currentAttributes[sectionIndex] where CGRectIntersectsRect(rect, item.frame) {
attributes.append(item)
}
}
return attributes
}
// MARK: - Layout Attributes - Section Header Cell
override func initialLayoutAttributesForAppearingSupplementaryElementOfKind(
elementKind: String,
atIndexPath elementIndexPath: NSIndexPath)
-> UICollectionViewLayoutAttributes?
{
return previousSectionAttributes[elementIndexPath.section]
}
override func layoutAttributesForSupplementaryViewOfKind(
elementKind: String,
atIndexPath indexPath: NSIndexPath)
-> UICollectionViewLayoutAttributes?
{
return currentSectionAttributes[indexPath.section]
}
override func finalLayoutAttributesForDisappearingSupplementaryElementOfKind(
elementKind: String,
atIndexPath elementIndexPath: NSIndexPath)
-> UICollectionViewLayoutAttributes?
{
return layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: elementIndexPath)
}
// MARK: - Invalidation
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
override class func invalidationContextClass() -> AnyClass {
return InvalidationContext.self
}
override func invalidationContextForBoundsChange(newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let invalidationContext = super.invalidationContextForBoundsChange(newBounds) as! InvalidationContext
guard let oldBounds = collectionView?.bounds else { return invalidationContext }
guard oldBounds != newBounds else { return invalidationContext }
let originChanged = !CGPointEqualToPoint(oldBounds.origin, newBounds.origin)
let sizeChanged = !CGSizeEqualToSize(oldBounds.size, newBounds.size)
if sizeChanged {
invalidationContext.shouldInvalidateEverything = true
} else {
invalidationContext.shouldInvalidateEverything = false
}
if originChanged {
invalidationContext.invalidateSectionHeaders = true
}
return invalidationContext
}
override func invalidateLayoutWithContext(context: UICollectionViewLayoutInvalidationContext) {
let invalidationContext = context as! InvalidationContext
if invalidationContext.invalidateSectionHeaders {
prepareSectionHeaderAttributes()
var sectionHeaderIndexPaths: [NSIndexPath] = []
for sectionIndex in 0..<currentSectionAttributes.count {
sectionHeaderIndexPaths.append(NSIndexPath(forItem: 0, inSection: sectionIndex))
}
invalidationContext.invalidateSupplementaryElementsOfKind(
SectionHeaderCell.kind,
atIndexPaths: sectionHeaderIndexPaths
)
}
super.invalidateLayoutWithContext(invalidationContext)
}
// MARK: - Collection View Info
override func collectionViewContentSize() -> CGSize {
return contentSize
}
override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint) -> CGPoint {
guard let selectedCellIndexPath = selectedCellIndexPath else { return proposedContentOffset }
var finalContentOffset = proposedContentOffset
if let frame = layoutAttributesForItemAtIndexPath(selectedCellIndexPath)?.frame {
let collectionViewHeight = collectionView?.bounds.size.height ?? 0
let collectionViewTop = proposedContentOffset.y
let collectionViewBottom = collectionViewTop + collectionViewHeight
let cellTop = frame.origin.y
let cellBottom = cellTop + frame.size.height
if cellBottom > collectionViewBottom {
finalContentOffset = CGPointMake(0.0, collectionViewTop + (cellBottom - collectionViewBottom))
} else if cellTop < collectionViewTop + sectionHeaderHeight {
finalContentOffset = CGPointMake(0.0, collectionViewTop - (collectionViewTop - cellTop) - sectionHeaderHeight)
}
}
return finalContentOffset
}
}
| mit | af5a048e364c7928c07e336e08c4a6a0 | 33.862319 | 136 | 0.666078 | 6.677307 | false | false | false | false |
matrix-org/matrix-ios-sdk | MatrixSDK/Data/Store/MXStoreService.swift | 1 | 5472 | //
// Copyright 2021 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
/// A class to help coordinate the session's main store with any secondary
/// stores that it relies upon such as aggregations. It will ensure that actions
/// which need synchronisation (such as deleting all data) are handled properly.
@objcMembers
public class MXStoreService: NSObject {
// MARK: - Constants
private enum Constants {
// Namespace to avoid conflict with any defaults set in the app.
static let storesToResetKey = "MatrixSDK:storesToReset"
}
private enum StoreType: String {
case aggregations
}
// MARK: - Properties
let credentials: MXCredentials
public let mainStore: MXStore
public var aggregations: MXAggregations? {
didSet {
if shouldResetStore(.aggregations) {
aggregations?.resetData()
removeStoreToReset(.aggregations)
}
}
}
// MARK: - Setup
public init(store: MXStore, credentials: MXCredentials) {
self.credentials = credentials
self.mainStore = store
super.init()
mainStore.storeService = self
}
// MARK: - Public
/// Reset any secondary stores in the service. This should be called by the main
/// store if it is permanent, in order to keep all of the data in sync across stores.
/// - Parameter sender: The file store that is about to delete its data.
public func resetSecondaryStores(sender: MXFileStore) {
guard sender == mainStore as? MXFileStore else {
MXLog.error("[MXStoreService] resetSecondaryStores called by the wrong store.")
return
}
MXLog.debug("[MXStoreService] Reset secondary stores")
if let aggregations = aggregations {
aggregations.resetData()
} else {
// It is possible that aggregations doesn't exist (for example in MXBackgroundStore),
// In this instance, remember to reset the aggregations store when it is set.
addStoreToReset(.aggregations)
MXLog.debug("[MXStoreService] Aggregations will be reset when added to the service.")
}
}
/// Close all stores in the service.
public func closeStores() {
mainStore.close?()
// MXAggregations doesn't require closing.
}
// MARK: - Stores with credentials
/// Whether or not the specified store type needs to be reset for the current user ID.
private func shouldResetStore(_ storeType: StoreType) -> Bool {
guard let userId = credentials.userId else { return false }
return storesToReset(for: userId).contains(storeType)
}
/// Add a store that should be reset later for the current user ID.
private func addStoreToReset(_ storeType: StoreType) {
guard let userId = credentials.userId else { return }
var storeTypes = storesToReset(for: userId)
storeTypes.append(storeType)
updateStoresToReset(storeTypes, for: userId)
}
/// Marks a store as having been reset for the current user ID.
/// This only needs to be called if `shouldResetStore` was true.
private func removeStoreToReset(_ storeType: StoreType) {
guard let userId = credentials.userId else { return }
var storeTypes = storesToReset(for: userId)
storeTypes.removeAll { $0 == storeType }
updateStoresToReset(storeTypes, for: userId)
}
// MARK: - All Stores
private var defaults: UserDefaults {
UserDefaults(suiteName: MXSDKOptions.sharedInstance().applicationGroupIdentifier) ?? UserDefaults.standard
}
/// All store types that should be reset when loaded for the specified user ID
/// - Parameter userId: The user ID to check with.
/// - Returns: An array of store types.
private func storesToReset(for userId: String) -> [StoreType] {
let allStoresToReset = defaults.object(forKey: Constants.storesToResetKey) as? [String: [String]] ?? [:]
let userStoreTypes = allStoresToReset[userId] ?? []
return userStoreTypes.compactMap { StoreType(rawValue: $0) }
}
/// Update the store types that need to be reset when loaded for the specified user ID.
/// - Parameters:
/// - storeTypes: The store types that should be reset.
/// - userId: The user ID to store the types for.
private func updateStoresToReset(_ storeTypes: [StoreType], for userId: String) {
var allStoresToReset = defaults.object(forKey: Constants.storesToResetKey) as? [String: [String]] ?? [:]
allStoresToReset[userId] = storeTypes.map { $0.rawValue }
defaults.setValue(allStoresToReset, forKey: Constants.storesToResetKey)
}
}
| apache-2.0 | 57b6cea5bcfc08c71edcaab0c80c46d8 | 36.479452 | 114 | 0.65223 | 4.947559 | false | false | false | false |
BennyKJohnson/OpenCloudKit | Sources/CKUserIdentity.swift | 1 | 2541 | //
// CKUserIdentity.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 14/07/2016.
//
//
import Foundation
public class CKUserIdentity : NSObject {
// This is the lookupInfo you passed in to CKDiscoverUserIdentitiesOperation or CKFetchShareParticipantsOperation
public let lookupInfo: CKUserIdentityLookupInfo?
public let nameComponents: CKPersonNameComponentsType?
public let userRecordID: CKRecordID?
public let hasiCloudAccount: Bool
var firstName: String?
var lastName: String?
public init(userRecordID: CKRecordID) {
self.userRecordID = userRecordID
self.lookupInfo = nil
hasiCloudAccount = false
nameComponents = nil
super.init()
}
init?(dictionary: [String: Any]) {
if let lookUpInfoDictionary = dictionary["lookupInfo"] as? [String: Any],let lookupInfo = CKUserIdentityLookupInfo(dictionary: lookUpInfoDictionary) {
self.lookupInfo = lookupInfo
} else {
self.lookupInfo = nil
}
if let userRecordName = dictionary["userRecordName"] as? String {
self.userRecordID = CKRecordID(recordName: userRecordName)
} else {
self.userRecordID = nil
}
if let nameComponentsDictionary = dictionary["nameComponents"] as? [String: Any] {
if #available(OSX 10.11, *) {
self.nameComponents = CKPersonNameComponents(dictionary: nameComponentsDictionary)
} else {
// Fallback on earlier versions
self.nameComponents = CKPersonNameComponents(dictionary: nameComponentsDictionary)
}
// self.firstName = nameComponents?.givenName
// self.lastName = nameComponents?.familyName
} else {
self.nameComponents = nil
}
self.hasiCloudAccount = false
super.init()
}
}
/*
extension PersonNameComponents {
init?(dictionary: [String: Any]) {
self.init()
namePrefix = dictionary["namePrefix"] as? String
givenName = dictionary["givenName"] as? String
familyName = dictionary["familyName"] as? String
nickname = dictionary["nickname"] as? String
nameSuffix = dictionary["nameSuffix"] as? String
middleName = dictionary["middleName"] as? String
// phoneticRepresentation
}
}
*/
| mit | bf60f2e0da831372baaa78bfcb722762 | 27.233333 | 159 | 0.603699 | 5.464516 | false | false | false | false |
benlangmuir/swift | test/Sema/call_as_function_generic.swift | 22 | 1520 | // RUN: %target-typecheck-verify-swift
protocol P0 {
func callAsFunction(x: Self)
}
struct ConcreteType {
func callAsFunction<T, U>(_ x: T, _ y: U) -> (T, U) {
return (x, y)
}
func callAsFunction<T, U>(_ fn: @escaping (T) -> U) -> (T) -> U {
return fn
}
}
let concrete = ConcreteType()
_ = concrete(1, 3.0)
_ = concrete(concrete, concrete.callAsFunction as ([Int], Float) -> ([Int], Float))
func generic<T, U>(_ x: T, _ y: U) {
_ = concrete(x, x)
_ = concrete(x, y)
}
struct GenericType<T : Collection> {
let collection: T
func callAsFunction<U>(_ x: U) -> Bool where U == T.Element, U : Equatable {
return collection.contains(x)
}
}
// Test conditional conformance.
extension GenericType where T.Element : Numeric {
func callAsFunction(initialValue: T.Element) -> T.Element {
return collection.reduce(initialValue, +)
}
}
let genericString = GenericType<[String]>(collection: ["Hello", "world", "!"])
_ = genericString("Hello")
let genericInt = GenericType<Set<Int>>(collection: [1, 2, 3])
_ = genericInt(initialValue: 1)
// SR-11386
class C<T> {}
protocol P1 {}
extension C where T : P1 { // expected-note {{where 'T' = 'Int'}}
func callAsFunction(t: T) {}
}
struct S0 : P1 {}
func testCallAsFunctionWithWhereClause(_ c1: C<Int>, _ c2: C<S0>, _ s0: S0) {
c1(42) // expected-error {{referencing instance method 'callAsFunction(t:)' on 'C' requires that 'Int' conform to 'P1'}}
// expected-error@-1 {{missing argument label 't:' in call}}
c2(t: s0) // Okay.
}
| apache-2.0 | 85959e01475043a989ef53464098f572 | 24.762712 | 122 | 0.633553 | 3.102041 | false | false | false | false |
haawa799/WaniKani-iOS | WaniKani/ViewControllers/GameCenterViewController.swift | 1 | 1239 | //
// GameCenterViewController.swift
// WaniKani
//
// Created by Andriy K. on 10/26/15.
// Copyright © 2015 Andriy K. All rights reserved.
//
import UIKit
import GameKit
class GameCenterViewController: UIViewController {
private(set) var gameCenterViewController: GKGameCenterViewController = {
let vc = GKGameCenterViewController()
vc.viewState = GKGameCenterViewControllerState.Leaderboards
vc.leaderboardIdentifier = "wanikani.score.leaderboard.0"
return vc
}()
override func viewDidLoad() {
super.viewDidLoad()
gameCenterViewController.gameCenterDelegate = self
}
override func viewDidAppear(animated: Bool) {
super.viewWillAppear(animated)
presentViewController(gameCenterViewController, animated: false, completion: nil)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
gameCenterViewController.dismissViewControllerAnimated(false, completion: nil)
}
}
extension GameCenterViewController: GKGameCenterControllerDelegate {
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
| gpl-3.0 | e4d3ebbb9872874b890235055149a569 | 26.511111 | 96 | 0.768174 | 5.09465 | false | false | false | false |
fakerabbit/LucasBot | LucasBot/ViewController.swift | 1 | 2965 | //
// ViewController.swift
// LucasBot
//
// Created by Mirko Justiniano on 1/8/17.
// Copyright © 2017 LB. All rights reserved.
//
import UIKit
import SafariServices
class ViewController: BotViewController {
lazy var chatView:ChatView! = {
let frame = UIScreen.main.bounds
let v = ChatView(frame: frame)
return v
}()
override func loadView() {
super.loadView()
BotMgr.sharedInstance.currentView = self.chatView
self.view = self.chatView
chatView.chatInput?.onMessage = { message in
if message != nil {
BotMgr.sharedInstance.sendMessage(msg: message!)
}
}
chatView.onButton = { [weak self] button in
if button != nil {
if button?.payload != nil {
BotMgr.sharedInstance.sendPayload(button: button!)
}
else if button?.url != nil {
//UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
if let requestUrl = NSURL(string: button!.url!) {
let svc = SFSafariViewController(url: requestUrl as URL)
self?.present(svc, animated: true, completion: nil)
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
chatView.chatInput?.nav = self.nav
BotMgr.sharedInstance.initBot()
chatView.animateView()
BotMgr.sharedInstance.onMessage = { [weak self] message in
//debugPrint("bot manager received message...")
if message.typing == true || message.type == "user" {
self?.chatView.newMessage = message
}
else {
self?.chatView.newBotMessage = message
}
self?.chatView.animateTyping(anim: message.typing)
}
chatView.chatInput?.pop.onCell = { [weak self] button in
if button != nil {
if button?.payload != nil {
BotMgr.sharedInstance.sendPayload(button: button!)
}
else if button?.url != nil {
//UIApplication.shared.open(URL(string: "http://www.stackoverflow.com")!, options: [:], completionHandler: nil)
if let requestUrl = NSURL(string: button!.url!) {
let svc = SFSafariViewController(url: requestUrl as URL)
self?.present(svc, animated: true, completion: nil)
}
}
}
self?.chatView.chatInput?.hideMenu()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 074c39502f5c9ed262b2c84d4fd7936b | 34.285714 | 131 | 0.538799 | 5.136915 | false | false | false | false |
zmeyc/telegram-bot-swift | Sources/TelegramBotSDK/Types/FileInfo.swift | 1 | 1245 | //
// FileInfo.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//
import Foundation
public enum FileInfo: Codable {
case inputFile(InputFile)
case string(String)
case unknown
public init(from decoder: Decoder) throws {
if let inputFile = try? decoder.singleValueContainer().decode(InputFile.self) {
self = .inputFile(inputFile)
return
}
if let string = try? decoder.singleValueContainer().decode(String.self) {
self = .string(string)
return
}
self = .unknown
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case let .string(string):
try container.encode(string)
case let .inputFile(inputFile):
try container.encode(inputFile)
default:
fatalError("Unknown should not be used")
}
}
}
| apache-2.0 | 4f57349435bbfbdc0a95ce189d1f8513 | 26.666667 | 87 | 0.6249 | 4.645522 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.