repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
KaiCode2/swift-corelibs-foundation | refs/heads/master | TestFoundation/TestNSString.swift | apache-2.0 | 1 | // 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
//
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
import Foundation
import XCTest
#else
import SwiftFoundation
import SwiftXCTest
#endif
import CoreFoundation
#if os(OSX) || os(iOS)
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
#endif
class TestNSString : XCTestCase {
static var allTests: [(String, (TestNSString) -> () throws -> Void)] {
return [
("test_boolValue", test_boolValue ),
("test_BridgeConstruction", test_BridgeConstruction ),
("test_integerValue", test_integerValue ),
("test_intValue", test_intValue ),
("test_isEqualToStringWithSwiftString", test_isEqualToStringWithSwiftString ),
("test_isEqualToObjectWithNSString", test_isEqualToObjectWithNSString ),
("test_isNotEqualToObjectWithNSNumber", test_isNotEqualToObjectWithNSNumber ),
("test_FromASCIIData", test_FromASCIIData ),
("test_FromUTF8Data", test_FromUTF8Data ),
// Swift3 updates broke the expectations of this test. disabling for now
// ("test_FromMalformedUTF8Data", test_FromMalformedUTF8Data ),
("test_FromASCIINSData", test_FromASCIINSData ),
("test_FromUTF8NSData", test_FromUTF8NSData ),
// Swift3 updates broke the expectations of this test. disabling for now
// ("test_FromMalformedUTF8NSData", test_FromMalformedUTF8NSData ),
("test_FromNullTerminatedCStringInASCII", test_FromNullTerminatedCStringInASCII ),
("test_FromNullTerminatedCStringInUTF8", test_FromNullTerminatedCStringInUTF8 ),
// Swift3 updates broke the expectations of this test. disabling for now
// ("test_FromMalformedNullTerminatedCStringInUTF8", test_FromMalformedNullTerminatedCStringInUTF8 ),
("test_uppercaseString", test_uppercaseString ),
("test_lowercaseString", test_lowercaseString ),
("test_capitalizedString", test_capitalizedString ),
("test_longLongValue", test_longLongValue ),
("test_rangeOfCharacterFromSet", test_rangeOfCharacterFromSet ),
("test_CFStringCreateMutableCopy", test_CFStringCreateMutableCopy),
("test_FromContentsOfURL",test_FromContentsOfURL),
("test_FromContentOfFile",test_FromContentOfFile),
("test_swiftStringUTF16", test_swiftStringUTF16),
// This test takes forever on build servers; it has been seen up to 1852.084 seconds
// ("test_completePathIntoString", test_completePathIntoString),
("test_stringByTrimmingCharactersInSet", test_stringByTrimmingCharactersInSet),
("test_initializeWithFormat", test_initializeWithFormat),
("test_initializeWithFormat2", test_initializeWithFormat2),
("test_initializeWithFormat3", test_initializeWithFormat3),
("test_stringByDeletingLastPathComponent", test_stringByDeletingLastPathComponent),
("test_getCString_simple", test_getCString_simple),
("test_getCString_nonASCII_withASCIIAccessor", test_getCString_nonASCII_withASCIIAccessor),
("test_NSHomeDirectoryForUser", test_NSHomeDirectoryForUser),
("test_stringByResolvingSymlinksInPath", test_stringByResolvingSymlinksInPath),
("test_stringByExpandingTildeInPath", test_stringByExpandingTildeInPath),
("test_stringByStandardizingPath", test_stringByStandardizingPath),
("test_stringByRemovingPercentEncoding", test_stringByRemovingPercentEncoding),
("test_stringByAppendingPathExtension", test_stringByAppendingPathExtension),
("test_stringByDeletingPathExtension", test_stringByDeletingPathExtension),
("test_ExternalRepresentation", test_ExternalRepresentation),
("test_mutableStringConstructor", test_mutableStringConstructor),
("test_PrefixSuffix", test_PrefixSuffix),
("test_reflection", { _ in test_reflection }),
]
}
func test_boolValue() {
let trueStrings: [NSString] = ["t", "true", "TRUE", "tRuE", "yes", "YES", "1", "+000009"]
for string in trueStrings {
XCTAssert(string.boolValue)
}
let falseStrings: [NSString] = ["false", "FALSE", "fAlSe", "no", "NO", "0", "<true>", "_true", "-00000"]
for string in falseStrings {
XCTAssertFalse(string.boolValue)
}
}
func test_BridgeConstruction() {
let literalConversion: NSString = "literal"
XCTAssertEqual(literalConversion.length, 7)
let nonLiteralConversion: NSString = "test\(self)".bridge()
XCTAssertTrue(nonLiteralConversion.length > 4)
let nonLiteral2: NSString = String(4).bridge()
let t = nonLiteral2.character(at: 0)
XCTAssertTrue(t == 52)
let externalString: NSString = String.localizedNameOfStringEncoding(String.defaultCStringEncoding()).bridge()
XCTAssertTrue(externalString.length >= 4)
let cluster: NSString = "✌🏾"
XCTAssertEqual(cluster.length, 3)
}
func test_integerValue() {
let string1: NSString = "123"
XCTAssertEqual(string1.integerValue, 123)
let string2: NSString = "123a"
XCTAssertEqual(string2.integerValue, 123)
let string3: NSString = "-123a"
XCTAssertEqual(string3.integerValue, -123)
let string4: NSString = "a123"
XCTAssertEqual(string4.integerValue, 0)
let string5: NSString = "+123"
XCTAssertEqual(string5.integerValue, 123)
let string6: NSString = "++123"
XCTAssertEqual(string6.integerValue, 0)
let string7: NSString = "-123"
XCTAssertEqual(string7.integerValue, -123)
let string8: NSString = "--123"
XCTAssertEqual(string8.integerValue, 0)
let string9: NSString = "999999999999999999999999999999"
XCTAssertEqual(string9.integerValue, Int.max)
let string10: NSString = "-999999999999999999999999999999"
XCTAssertEqual(string10.integerValue, Int.min)
}
func test_intValue() {
let string1: NSString = "123"
XCTAssertEqual(string1.intValue, 123)
let string2: NSString = "123a"
XCTAssertEqual(string2.intValue, 123)
let string3: NSString = "-123a"
XCTAssertEqual(string3.intValue, -123)
let string4: NSString = "a123"
XCTAssertEqual(string4.intValue, 0)
let string5: NSString = "+123"
XCTAssertEqual(string5.intValue, 123)
let string6: NSString = "++123"
XCTAssertEqual(string6.intValue, 0)
let string7: NSString = "-123"
XCTAssertEqual(string7.intValue, -123)
let string8: NSString = "--123"
XCTAssertEqual(string8.intValue, 0)
let string9: NSString = "999999999999999999999999999999"
XCTAssertEqual(string9.intValue, Int32.max)
let string10: NSString = "-999999999999999999999999999999"
XCTAssertEqual(string10.intValue, Int32.min)
}
func test_isEqualToStringWithSwiftString() {
let string: NSString = "literal"
let swiftString = "literal"
XCTAssertTrue(string.isEqual(to: swiftString))
}
func test_isEqualToObjectWithNSString() {
let string1: NSString = "literal"
let string2: NSString = "literal"
XCTAssertTrue(string1.isEqual(string2))
}
func test_isNotEqualToObjectWithNSNumber() {
let string: NSString = "5"
let number: NSNumber = 5
XCTAssertFalse(string.isEqual(number))
}
internal let mockASCIIStringBytes: [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x20, 0x53, 0x77, 0x69, 0x66, 0x74, 0x21]
internal let mockASCIIString = "Hello Swift!"
internal let mockUTF8StringBytes: [UInt8] = [0x49, 0x20, 0xE2, 0x9D, 0xA4, 0xEF, 0xB8, 0x8F, 0x20, 0x53, 0x77, 0x69, 0x66, 0x74]
internal let mockUTF8String = "I ❤️ Swift"
internal let mockMalformedUTF8StringBytes: [UInt8] = [0xFF]
func test_FromASCIIData() {
let bytes = mockASCIIStringBytes
let string = NSString(bytes: bytes, length: bytes.count, encoding: NSASCIIStringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockASCIIString) ?? false)
}
func test_FromUTF8Data() {
let bytes = mockUTF8StringBytes
let string = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockUTF8String) ?? false)
}
func test_FromMalformedUTF8Data() {
let bytes = mockMalformedUTF8StringBytes
let string = NSString(bytes: bytes, length: bytes.count, encoding: NSUTF8StringEncoding)
XCTAssertNil(string)
}
func test_FromASCIINSData() {
let bytes = mockASCIIStringBytes
let data = NSData(bytes: bytes, length: bytes.count)
let string = NSString(data: data, encoding: NSASCIIStringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockASCIIString) ?? false)
}
func test_FromUTF8NSData() {
let bytes = mockUTF8StringBytes
let data = NSData(bytes: bytes, length: bytes.count)
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockUTF8String) ?? false)
}
func test_FromMalformedUTF8NSData() {
let bytes = mockMalformedUTF8StringBytes
let data = NSData(bytes: bytes, length: bytes.count)
let string = NSString(data: data, encoding: NSUTF8StringEncoding)
XCTAssertNil(string)
}
func test_FromNullTerminatedCStringInASCII() {
let bytes = mockASCIIStringBytes + [0x00]
let string = NSString(CString: bytes.map { Int8(bitPattern: $0) }, encoding: NSASCIIStringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockASCIIString) ?? false)
}
func test_FromNullTerminatedCStringInUTF8() {
let bytes = mockUTF8StringBytes + [0x00]
let string = NSString(CString: bytes.map { Int8(bitPattern: $0) }, encoding: NSUTF8StringEncoding)
XCTAssertNotNil(string)
XCTAssertTrue(string?.isEqual(to: mockUTF8String) ?? false)
}
func test_FromMalformedNullTerminatedCStringInUTF8() {
let bytes = mockMalformedUTF8StringBytes + [0x00]
let string = NSString(CString: bytes.map { Int8(bitPattern: $0) }, encoding: NSUTF8StringEncoding)
XCTAssertNil(string)
}
func test_FromContentsOfURL() {
guard let testFileURL = testBundle().URLForResource("NSStringTestData", withExtension: "txt") else {
XCTFail("URL for NSStringTestData.txt is nil")
return
}
do {
let string = try NSString(contentsOf: testFileURL, encoding: NSUTF8StringEncoding)
XCTAssertEqual(string, "swift-corelibs-foundation")
} catch {
XCTFail("Unable to init NSString from contentsOf:encoding:")
}
do {
let string = try NSString(contentsOf: testFileURL, encoding: NSUTF16StringEncoding)
XCTAssertNotEqual(string, "swift-corelibs-foundation", "Wrong result when reading UTF-8 file with UTF-16 encoding in contentsOf:encoding")
} catch {
XCTFail("Unable to init NSString from contentsOf:encoding:")
}
}
func test_FromContentOfFile() {
let testFilePath = testBundle().pathForResource("NSStringTestData", ofType: "txt")
XCTAssertNotNil(testFilePath)
do {
let str = try NSString(contentsOfFile: testFilePath!, encoding: NSUTF8StringEncoding)
XCTAssertEqual(str, "swift-corelibs-foundation")
} catch {
XCTFail("Unable to init NSString from contentsOfFile:encoding:")
}
}
func test_uppercaseString() {
XCTAssertEqual(NSString(stringLiteral: "abcd").uppercased, "ABCD")
XCTAssertEqual(NSString(stringLiteral: "abcd").uppercased, "ABCD") // full-width
XCTAssertEqual(NSString(stringLiteral: "абВГ").uppercased, "АБВГ")
XCTAssertEqual(NSString(stringLiteral: "たちつてと").uppercased, "たちつてと")
// Special casing (see swift/validation-tests/stdlib/NSStringAPI.swift)
XCTAssertEqual(NSString(stringLiteral: "\u{0069}").uppercased(with: NSLocale(localeIdentifier: "en")), "\u{0049}")
// Currently fails; likely there are locale loading issues that are preventing this from functioning correctly
// XCTAssertEqual(NSString(stringLiteral: "\u{0069}").uppercased(with: NSLocale(localeIdentifier: "tr")), "\u{0130}")
XCTAssertEqual(NSString(stringLiteral: "\u{00df}").uppercased, "\u{0053}\u{0053}")
XCTAssertEqual(NSString(stringLiteral: "\u{fb01}").uppercased, "\u{0046}\u{0049}")
}
func test_lowercaseString() {
XCTAssertEqual(NSString(stringLiteral: "abCD").lowercased, "abcd")
XCTAssertEqual(NSString(stringLiteral: "ABCD").lowercased, "abcd") // full-width
XCTAssertEqual(NSString(stringLiteral: "aБВГ").lowercased, "aбвг")
XCTAssertEqual(NSString(stringLiteral: "たちつてと").lowercased, "たちつてと")
// Special casing (see swift/validation-tests/stdlib/NSStringAPI.swift)
XCTAssertEqual(NSString(stringLiteral: "\u{0130}").lowercased(with: NSLocale(localeIdentifier: "en")), "\u{0069}\u{0307}")
// Currently fails; likely there are locale loading issues that are preventing this from functioning correctly
// XCTAssertEqual(NSString(stringLiteral: "\u{0130}").lowercased(with: NSLocale(localeIdentifier: "tr")), "\u{0069}")
XCTAssertEqual(NSString(stringLiteral: "\u{0049}\u{0307}").lowercased(with: NSLocale(localeIdentifier: "en")), "\u{0069}\u{0307}")
// Currently fails; likely there are locale loading issues that are preventing this from functioning correctly
// XCTAssertEqual(NSString(stringLiteral: "\u{0049}\u{0307}").lowercaseStringWithLocale(NSLocale(localeIdentifier: "tr")), "\u{0069}")
}
func test_capitalizedString() {
XCTAssertEqual(NSString(stringLiteral: "foo Foo fOO FOO").capitalized, "Foo Foo Foo Foo")
XCTAssertEqual(NSString(stringLiteral: "жжж").capitalized, "Жжж")
}
func test_longLongValue() {
let string1: NSString = "123"
XCTAssertEqual(string1.longLongValue, 123)
let string2: NSString = "123a"
XCTAssertEqual(string2.longLongValue, 123)
let string3: NSString = "-123a"
XCTAssertEqual(string3.longLongValue, -123)
let string4: NSString = "a123"
XCTAssertEqual(string4.longLongValue, 0)
let string5: NSString = "+123"
XCTAssertEqual(string5.longLongValue, 123)
let string6: NSString = "++123"
XCTAssertEqual(string6.longLongValue, 0)
let string7: NSString = "-123"
XCTAssertEqual(string7.longLongValue, -123)
let string8: NSString = "--123"
XCTAssertEqual(string8.longLongValue, 0)
let string9: NSString = "999999999999999999999999999999"
XCTAssertEqual(string9.longLongValue, Int64.max)
let string10: NSString = "-999999999999999999999999999999"
XCTAssertEqual(string10.longLongValue, Int64.min)
}
func test_rangeOfCharacterFromSet() {
let string: NSString = "0Az"
let letters = NSCharacterSet.letters()
let decimalDigits = NSCharacterSet.decimalDigits()
XCTAssertEqual(string.rangeOfCharacter(from: letters).location, 1)
XCTAssertEqual(string.rangeOfCharacter(from: decimalDigits).location, 0)
XCTAssertEqual(string.rangeOfCharacter(from: letters, options: [.backwardsSearch]).location, 2)
XCTAssertEqual(string.rangeOfCharacter(from: letters, options: [], range: NSMakeRange(2, 1)).location, 2)
}
func test_CFStringCreateMutableCopy() {
let nsstring: NSString = "абВГ"
let mCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, unsafeBitCast(nsstring, to: CFString.self))
let str = unsafeBitCast(mCopy, to: NSString.self).bridge()
XCTAssertEqual(nsstring.bridge(), str)
}
// This test verifies that CFStringGetBytes with a UTF16 encoding works on an NSString backed by a Swift string
func test_swiftStringUTF16() {
#if os(OSX) || os(iOS)
let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
#endif
let testString = "hello world"
let string = NSString(string: testString)
let cfString = unsafeBitCast(string, to: CFString.self)
// Get the bytes as UTF16
let reservedLength = 50
var buf : [UInt8] = []
buf.reserveCapacity(reservedLength)
var usedLen : CFIndex = 0
buf.withUnsafeMutableBufferPointer { p in
CFStringGetBytes(cfString, CFRangeMake(0, CFStringGetLength(cfString)), CFStringEncoding(kCFStringEncodingUTF16), 0, false, p.baseAddress, reservedLength, &usedLen)
}
// Make a new string out of it
let newCFString = CFStringCreateWithBytes(nil, buf, usedLen, CFStringEncoding(kCFStringEncodingUTF16), false)
let newString = unsafeBitCast(newCFString, to: NSString.self)
XCTAssertTrue(newString.isEqual(to: testString))
}
func test_completePathIntoString() {
let fileNames = [
"/tmp/Test_completePathIntoString_01",
"/tmp/test_completePathIntoString_02",
"/tmp/test_completePathIntoString_01.txt",
"/tmp/test_completePathIntoString_01.dat",
"/tmp/test_completePathIntoString_03.DAT"
]
guard ensureFiles(fileNames) else {
XCTAssert(false, "Could not create temp files for testing.")
return
}
let tmpPath = { (path: String) -> NSString in
return "/tmp/\(path)".bridge()
}
do {
let path: NSString = tmpPath("")
var outName: NSString?
var matches: [NSString] = []
_ = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
_ = try NSFileManager.defaultManager().contentsOfDirectory(at: NSURL(string: path.bridge())!, includingPropertiesForKeys: nil, options: [])
XCTAssert(outName == "/", "If NSString is valid path to directory which has '/' suffix then outName is '/'.")
// This assert fails on CI; https://bugs.swift.org/browse/SR-389
// XCTAssert(matches.count == content.count && matches.count == count, "If NSString is valid path to directory then matches contain all content of directory. expected \(content) but got \(matches)")
} catch {
XCTAssert(false, "Could not finish test due to error")
}
do {
let path: NSString = "/tmp"
var outName: NSString?
var matches: [NSString] = []
_ = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
let urlToTmp = NSURL(fileURLWithPath: "/private/tmp/").URLByStandardizingPath!
_ = try NSFileManager.defaultManager().contentsOfDirectory(at: urlToTmp, includingPropertiesForKeys: nil, options: [])
XCTAssert(outName == "/tmp/", "If path could be completed to existing directory then outName is a string itself plus '/'.")
// This assert fails on CI; https://bugs.swift.org/browse/SR-389
// XCTAssert(matches.count == content.count && matches.count == count, "If NSString is valid path to directory then matches contain all content of directory. expected \(content) but got \(matches)")
} catch {
XCTAssert(false, "Could not finish test due to error")
}
let fileNames2 = [
"/tmp/ABC/",
"/tmp/ABCD/",
"/tmp/abcde"
]
guard ensureFiles(fileNames2) else {
XCTAssert(false, "Could not create temp files for testing.")
return
}
do {
let path: NSString = tmpPath("ABC")
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(stringsAreCaseInsensitivelyEqual(outName!, path), "If NSString is valid path to directory then outName is string itself.")
XCTAssert(matches.count == count && count == fileNames2.count, "")
}
do {
let path: NSString = tmpPath("Test_completePathIntoString_01")
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: true, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(outName == path, "If NSString is valid path to file and search is case sensitive then outName is string itself.")
XCTAssert(matches.count == 1 && count == 1 && stringsAreCaseInsensitivelyEqual(matches[0], path), "If NSString is valid path to file and search is case sensitive then matches contain that file path only")
}
do {
let path: NSString = tmpPath("Test_completePathIntoString_01")
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(stringsAreCaseInsensitivelyEqual(outName!, path), "If NSString is valid path to file and search is case insensitive then outName is string equal to self.")
XCTAssert(matches.count == 3 && count == 3, "Matches contain all files with similar name.")
}
do {
let path = tmpPath(NSUUID().UUIDString)
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(outName == nil, "If no matches found then outName is nil.")
XCTAssert(matches.count == 0 && count == 0, "If no matches found then return 0 and matches is empty.")
}
do {
let path: NSString = ""
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(outName == nil, "If no matches found then outName is nil.")
XCTAssert(matches.count == 0 && count == 0, "If no matches found then return 0 and matches is empty.")
}
do {
let path: NSString = tmpPath("test_c")
var outName: NSString?
var matches: [NSString] = []
// case insensetive
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(stringsAreCaseInsensitivelyEqual(outName!, tmpPath("Test_completePathIntoString_0")), "If there are matches then outName should be longest common prefix of all matches.")
XCTAssert(matches.count == fileNames.count && count == fileNames.count, "If there are matches then matches array contains them.")
}
do {
let path: NSString = tmpPath("test_c")
var outName: NSString?
var matches: [NSString] = []
// case sensetive
let count = path.completePathIntoString(&outName, caseSensitive: true, matchesIntoArray: &matches, filterTypes: nil)
XCTAssert(outName == tmpPath("test_completePathIntoString_0"), "If there are matches then outName should be longest common prefix of all matches.")
XCTAssert(matches.count == 4 && count == 4, "Supports case sensetive search")
}
do {
let path: NSString = tmpPath("test_c")
var outName: NSString?
var matches: [NSString] = []
// case sensetive
let count = path.completePathIntoString(&outName, caseSensitive: true, matchesIntoArray: &matches, filterTypes: ["DAT"])
XCTAssert(outName == tmpPath("test_completePathIntoString_03.DAT"), "If there are matches then outName should be longest common prefix of all matches.")
XCTAssert(matches.count == 1 && count == 1, "Supports case sensetive search by extensions")
}
do {
let path: NSString = tmpPath("test_c")
var outName: NSString?
var matches: [NSString] = []
// type by filter
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: ["txt", "dat"])
XCTAssert(stringsAreCaseInsensitivelyEqual(outName!, tmpPath("test_completePathIntoString_0")), "If there are matches then outName should be longest common prefix of all matches.")
XCTAssert(matches.count == 3 && count == 3, "Supports filtration by type")
}
do {
// will be resolved against current working directory that is directory there results of build process are stored
let path: NSString = "TestFoundation"
var outName: NSString?
var matches: [NSString] = []
let count = path.completePathIntoString(&outName, caseSensitive: false, matchesIntoArray: &matches, filterTypes: nil)
// Build directory at least contains executable itself and *.swiftmodule directory
XCTAssert(matches.count == count && count >= 2, "Supports relative paths.")
XCTAssert(startWith(path.bridge(), strings: matches), "For relative paths matches are relative too.")
}
// Next check has no sense on Linux due to case sensitive file system.
#if os(OSX)
guard ensureFiles(["/tmp/ABC/temp.txt"]) else {
XCTAssert(false, "Could not create temp files for testing.")
return
}
do {
let path: NSString = tmpPath("aBc/t")
var outName: NSString?
var matches: [NSString] = []
// type by filter
let count = path.completePathIntoString(&outName, caseSensitive: true, matchesIntoArray: &matches, filterTypes: ["txt", "dat"])
XCTAssert(outName == tmpPath("aBc/temp.txt"), "outName starts with receiver.")
XCTAssert(matches.count >= 1 && count >= 1, "There are matches")
}
#endif
}
private func startWith(_ prefix: String, strings: [NSString]) -> Bool {
for item in strings {
guard item.hasPrefix(prefix) else {
return false
}
}
return true
}
private func stringsAreCaseInsensitivelyEqual(_ lhs: NSString, _ rhs: NSString) -> Bool {
return lhs.compare(rhs.bridge(), options: .caseInsensitiveSearch) == .orderedSame
}
func test_stringByTrimmingCharactersInSet() {
let characterSet = NSCharacterSet.whitespaces()
let string: NSString = " abc "
XCTAssertEqual(string.trimmingCharacters(in: characterSet), "abc")
}
func test_initializeWithFormat() {
let argument: [CVarArg] = [42, 42.0]
withVaList(argument) {
pointer in
let string = NSString(format: "Value is %d (%.1f)", arguments: pointer)
XCTAssertEqual(string, "Value is 42 (42.0)")
}
}
func test_initializeWithFormat2() {
let argument: UInt8 = 75
let string = NSString(format: "%02X", argument)
XCTAssertEqual(string, "4B")
}
func test_initializeWithFormat3() {
let argument: [CVarArg] = [1000, 42.0]
withVaList(argument) {
pointer in
let string = NSString(format: "Default value is %d (%.1f)", locale: nil, arguments: pointer)
XCTAssertEqual(string, "Default value is 1000 (42.0)")
}
withVaList(argument) {
pointer in
let string = NSString(format: "en_GB value is %d (%.1f)", locale: NSLocale.init(localeIdentifier: "en_GB"), arguments: pointer)
XCTAssertEqual(string, "en_GB value is 1000 (42.0)")
}
withVaList(argument) {
pointer in
let string = NSString(format: "de_DE value is %d (%.1f)", locale: NSLocale.init(localeIdentifier: "de_DE"), arguments: pointer)
XCTAssertEqual(string, "de_DE value is 1000 (42,0)")
}
withVaList(argument) {
pointer in
let loc: NSDictionary = ["NSDecimalSeparator" as NSString : "&" as NSString]
let string = NSString(format: "NSDictionary value is %d (%.1f)", locale: loc, arguments: pointer)
XCTAssertEqual(string, "NSDictionary value is 1000 (42&0)")
}
}
func test_stringByDeletingLastPathComponent() {
do {
let path: NSString = "/tmp/scratch.tiff"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "/tmp")
}
do {
let path: NSString = "/tmp/lock/"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "/tmp")
}
do {
let path: NSString = "/tmp/"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "/")
}
do {
let path: NSString = "/tmp"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "/")
}
do {
let path: NSString = "/"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "/")
}
do {
let path: NSString = "scratch.tiff"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "")
}
do {
let path: NSString = "foo/bar"
let result = path.stringByDeletingLastPathComponent
XCTAssertEqual(result, "foo", "Relative path stays relative.")
}
}
func test_stringByResolvingSymlinksInPath() {
do {
let path: NSString = "foo/bar"
let result = path.stringByResolvingSymlinksInPath
XCTAssertEqual(result, "foo/bar", "For relative paths, symbolic links that can’t be resolved are left unresolved in the returned string.")
}
do {
let path: NSString = "/tmp/.."
let result = path.stringByResolvingSymlinksInPath
#if os(OSX)
let expected = "/private"
#else
let expected = "/"
#endif
XCTAssertEqual(result, expected, "For absolute paths, all symbolic links are guaranteed to be removed.")
}
do {
let path: NSString = "tmp/.."
let result = path.stringByResolvingSymlinksInPath
XCTAssertEqual(result, "tmp/..", "Parent links could be resolved for absolute paths only.")
}
do {
let path: NSString = "/tmp/"
let result = path.stringByResolvingSymlinksInPath
XCTAssertEqual(result, "/tmp", "Result doesn't contain trailing slash.")
}
do {
let path: NSString = "http://google.com/search/.."
let result = path.stringByResolvingSymlinksInPath
XCTAssertEqual(result, "http:/google.com/search/..", "stringByResolvingSymlinksInPath treats receiver as file path always")
}
do {
let path: NSString = "file:///tmp/.."
let result = path.stringByResolvingSymlinksInPath
XCTAssertEqual(result, "file:/tmp/..", "stringByResolvingSymlinksInPath treats receiver as file path always")
}
}
func test_getCString_simple() {
let str: NSString = "foo"
var chars = [Int8](repeating:0xF, count:4)
let count = chars.count
let expected: [Int8] = [102, 111, 111, 0]
var res: Bool = false
chars.withUnsafeMutableBufferPointer() {
let ptr = $0.baseAddress!
res = str.getCString(ptr, maxLength: count, encoding: NSASCIIStringEncoding)
}
XCTAssertTrue(res, "getCString should work on simple strings with ascii string encoding")
XCTAssertEqual(chars, expected, "getCString on \(str) should have resulted in \(expected) but got \(chars)")
}
func test_getCString_nonASCII_withASCIIAccessor() {
let str: NSString = "ƒoo"
var chars = [Int8](repeating:0xF, count:5)
let expected: [Int8] = [-58, -110, 111, 111, 0]
let count = chars.count
var res: Bool = false
chars.withUnsafeMutableBufferPointer() {
let ptr = $0.baseAddress!
res = str.getCString(ptr, maxLength: count, encoding: NSASCIIStringEncoding)
}
XCTAssertFalse(res, "getCString should not work on non ascii strings accessing as ascii string encoding")
chars.withUnsafeMutableBufferPointer() {
let ptr = $0.baseAddress!
res = str.getCString(ptr, maxLength: count, encoding: NSUTF8StringEncoding)
}
XCTAssertTrue(res, "getCString should work on UTF8 encoding")
XCTAssertEqual(chars, expected, "getCString on \(str) should have resulted in \(expected) but got \(chars)")
}
func test_NSHomeDirectoryForUser() {
let homeDir = NSHomeDirectoryForUser(nil)
let userName = NSUserName()
let homeDir2 = NSHomeDirectoryForUser(userName)
let homeDir3 = NSHomeDirectory()
XCTAssert(homeDir != nil && homeDir == homeDir2 && homeDir == homeDir3, "Could get user' home directory")
}
func test_stringByExpandingTildeInPath() {
do {
let path: NSString = "~"
let result = path.stringByExpandingTildeInPath
XCTAssert(result == NSHomeDirectory(), "Could resolve home directory for current user")
XCTAssertFalse(result.hasSuffix("/"), "Result have no trailing path separator")
}
do {
let path: NSString = "~/"
let result = path.stringByExpandingTildeInPath
XCTAssert(result == NSHomeDirectory(), "Could resolve home directory for current user")
XCTAssertFalse(result.hasSuffix("/"), "Result have no trailing path separator")
}
do {
let path = NSString(string: "~\(NSUserName())")
let result = path.stringByExpandingTildeInPath
XCTAssert(result == NSHomeDirectory(), "Could resolve home directory for specific user")
XCTAssertFalse(result.hasSuffix("/"), "Result have no trailing path separator")
}
do {
let userName = NSUUID().UUIDString
let path = NSString(string: "~\(userName)/")
let result = path.stringByExpandingTildeInPath
// next assert fails in VirtualBox because home directory for unknown user resolved to /var/run/vboxadd
XCTAssert(result == "~\(userName)", "Return copy of reciver if home directory could no be resolved.")
}
}
func test_stringByStandardizingPath() {
// tmp is special because it is symlinked to /private/tmp and this /private prefix should be dropped,
// so tmp is tmp. On Linux tmp is not symlinked so it would be the same.
do {
let path: NSString = "/.//tmp/ABC/.."
let result = path.stringByStandardizingPath
XCTAssertEqual(result, "/tmp", "stringByStandardizingPath removes extraneous path components and resolve symlinks.")
}
do {
let path: NSString = "~"
let result = path.stringByStandardizingPath
let expected = NSHomeDirectory()
XCTAssertEqual(result, expected, "stringByStandardizingPath expanding initial tilde.")
}
do {
let path: NSString = "~/foo/bar/"
let result = path.stringByStandardizingPath
let expected = NSHomeDirectory() + "/foo/bar"
XCTAssertEqual(result, expected, "stringByStandardizingPath expanding initial tilde.")
}
// relative file paths depend on file path standardizing that is not yet implemented
do {
let path: NSString = "foo/bar"
let result = path.stringByStandardizingPath
XCTAssertEqual(result, path.bridge(), "stringByStandardizingPath doesn't resolve relative paths")
}
// tmp is symlinked on OS X only
#if os(OSX)
do {
let path: NSString = "/tmp/.."
let result = path.stringByStandardizingPath
XCTAssertEqual(result, "/private")
}
#endif
do {
let path: NSString = "/tmp/ABC/.."
let result = path.stringByStandardizingPath
XCTAssertEqual(result, "/tmp", "parent links could be resolved for absolute paths")
}
do {
let path: NSString = "tmp/ABC/.."
let result = path.stringByStandardizingPath
XCTAssertEqual(result, path.bridge(), "parent links could not be resolved for relative paths")
}
}
func test_stringByRemovingPercentEncoding() {
let s1 = "a%20b".stringByRemovingPercentEncoding
XCTAssertEqual(s1, "a b")
let s2 = "a%1 b".stringByRemovingPercentEncoding
XCTAssertNil(s2, "returns nil for a string with an invalid percent encoding")
}
func test_stringByAppendingPathExtension() {
let values : Dictionary = [
NSString(string: "/tmp/scratch.old") : "/tmp/scratch.old.tiff",
NSString(string: "/tmp/scratch.") : "/tmp/scratch..tiff",
NSString(string: "/tmp/") : "/tmp.tiff",
NSString(string: "/scratch") : "/scratch.tiff",
NSString(string: "/~scratch") : "/~scratch.tiff",
NSString(string: "scratch") : "scratch.tiff",
]
for (fileName, expectedResult) in values {
let result = fileName.stringByAppendingPathExtension("tiff")
XCTAssertEqual(result, expectedResult, "expected \(expectedResult) for \(fileName) but got \(result)")
}
}
func test_stringByDeletingPathExtension() {
let values : Dictionary = [
NSString(string: "/tmp/scratch.tiff") : "/tmp/scratch",
NSString(string: "/tmp/") : "/tmp",
NSString(string: "scratch.bundle") : "scratch",
NSString(string: "scratch..tiff") : "scratch.",
NSString(string: ".tiff") : ".tiff",
NSString(string: "/") : "/",
]
for (fileName, expectedResult) in values {
let result = fileName.stringByDeletingPathExtension
XCTAssertEqual(result, expectedResult, "expected \(expectedResult) for \(fileName) but got \(result)")
}
}
func test_ExternalRepresentation() {
// Ensure NSString can be used to create an external data representation
let UTF8Encoding = CFStringEncoding(kCFStringEncodingUTF8)
let UTF16Encoding = CFStringEncoding(kCFStringEncodingUTF16)
let ISOLatin1Encoding = CFStringEncoding(kCFStringEncodingISOLatin1)
do {
let string = unsafeBitCast(NSString(string: "this is an external string that should be representable by data"), to: CFString.self)
let UTF8Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, UTF8Encoding, 0)
let UTF8Length = CFDataGetLength(UTF8Data)
XCTAssertEqual(UTF8Length, 63, "NSString should successfully produce an external UTF8 representation with a length of 63 but got \(UTF8Length) bytes")
let UTF16Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, UTF16Encoding, 0)
let UTF16Length = CFDataGetLength(UTF16Data)
XCTAssertEqual(UTF16Length, 128, "NSString should successfully produce an external UTF16 representation with a length of 128 but got \(UTF16Length) bytes")
let ISOLatin1Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, ISOLatin1Encoding, 0)
let ISOLatin1Length = CFDataGetLength(ISOLatin1Data)
XCTAssertEqual(ISOLatin1Length, 63, "NSString should successfully produce an external ISOLatin1 representation with a length of 63 but got \(ISOLatin1Length) bytes")
}
do {
let string = unsafeBitCast(NSString(string: "🐢 encoding all the way down. 🐢🐢🐢"), to: CFString.self)
let UTF8Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, UTF8Encoding, 0)
let UTF8Length = CFDataGetLength(UTF8Data)
XCTAssertEqual(UTF8Length, 44, "NSString should successfully produce an external UTF8 representation with a length of 44 but got \(UTF8Length) bytes")
let UTF16Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, UTF16Encoding, 0)
let UTF16Length = CFDataGetLength(UTF16Data)
XCTAssertEqual(UTF16Length, 74, "NSString should successfully produce an external UTF16 representation with a length of 74 but got \(UTF16Length) bytes")
let ISOLatin1Data = CFStringCreateExternalRepresentation(kCFAllocatorDefault, string, ISOLatin1Encoding, 0)
XCTAssertNil(ISOLatin1Data)
}
}
func test_mutableStringConstructor() {
let mutableString = NSMutableString(string: "Test")
XCTAssertEqual(mutableString, "Test")
}
}
struct ComparisonTest {
let lhs: String
let rhs: String
let loc: UInt
let reason: String
var xfail: Bool {
return !reason.isEmpty
}
init(
_ lhs: String, _ rhs: String,
reason: String = "", line: UInt = #line
) {
self.lhs = lhs
self.rhs = rhs
self.reason = reason
self.loc = line
}
}
let comparisonTests = [
ComparisonTest("", ""),
ComparisonTest("", "a"),
// ASCII cases
ComparisonTest("t", "tt"),
ComparisonTest("t", "Tt"),
ComparisonTest("\u{0}", ""),
ComparisonTest("\u{0}", "\u{0}",
reason: "https://bugs.swift.org/browse/SR-332"),
ComparisonTest("\r\n", "t"),
ComparisonTest("\r\n", "\n",
reason: "blocked on rdar://problem/19036555"),
ComparisonTest("\u{0}", "\u{0}\u{0}",
reason: "rdar://problem/19034601"),
// Whitespace
// U+000A LINE FEED (LF)
// U+000B LINE TABULATION
// U+000C FORM FEED (FF)
// U+0085 NEXT LINE (NEL)
// U+2028 LINE SEPARATOR
// U+2029 PARAGRAPH SEPARATOR
ComparisonTest("\u{0085}", "\n"),
ComparisonTest("\u{000b}", "\n"),
ComparisonTest("\u{000c}", "\n"),
ComparisonTest("\u{2028}", "\n"),
ComparisonTest("\u{2029}", "\n"),
ComparisonTest("\r\n\r\n", "\r\n"),
// U+0301 COMBINING ACUTE ACCENT
// U+00E1 LATIN SMALL LETTER A WITH ACUTE
ComparisonTest("a\u{301}", "\u{e1}"),
ComparisonTest("a", "a\u{301}"),
ComparisonTest("a", "\u{e1}"),
// U+304B HIRAGANA LETTER KA
// U+304C HIRAGANA LETTER GA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
ComparisonTest("\u{304b}", "\u{304b}"),
ComparisonTest("\u{304c}", "\u{304c}"),
ComparisonTest("\u{304b}", "\u{304c}"),
ComparisonTest("\u{304b}", "\u{304c}\u{3099}"),
ComparisonTest("\u{304c}", "\u{304b}\u{3099}"),
ComparisonTest("\u{304c}", "\u{304c}\u{3099}"),
// U+212B ANGSTROM SIGN
// U+030A COMBINING RING ABOVE
// U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE
ComparisonTest("\u{212b}", "A\u{30a}"),
ComparisonTest("\u{212b}", "\u{c5}"),
ComparisonTest("A\u{30a}", "\u{c5}"),
ComparisonTest("A\u{30a}", "a"),
ComparisonTest("A", "A\u{30a}"),
// U+2126 OHM SIGN
// U+03A9 GREEK CAPITAL LETTER OMEGA
ComparisonTest("\u{2126}", "\u{03a9}"),
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
// U+1E69 LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
ComparisonTest("\u{1e69}", "s\u{323}\u{307}"),
ComparisonTest("\u{1e69}", "s\u{307}\u{323}"),
ComparisonTest("\u{1e69}", "\u{1e63}\u{307}"),
ComparisonTest("\u{1e63}", "s\u{323}"),
ComparisonTest("\u{1e63}\u{307}", "s\u{323}\u{307}"),
ComparisonTest("\u{1e63}\u{307}", "s\u{307}\u{323}"),
ComparisonTest("s\u{323}", "\u{1e69}"),
// U+FB01 LATIN SMALL LIGATURE FI
ComparisonTest("\u{fb01}", "\u{fb01}"),
ComparisonTest("fi", "\u{fb01}"),
// U+1F1E7 REGIONAL INDICATOR SYMBOL LETTER B
// \u{1F1E7}\u{1F1E7} Flag of Barbados
ComparisonTest("\u{1F1E7}", "\u{1F1E7}\u{1F1E7}",
reason: "https://bugs.swift.org/browse/SR-367"),
// Test that Unicode collation is performed in deterministic mode.
//
// U+0301 COMBINING ACUTE ACCENT
// U+0341 COMBINING ACUTE TONE MARK
// U+0954 DEVANAGARI ACUTE ACCENT
//
// Collation elements from DUCET:
// 0301 ; [.0000.0024.0002] # COMBINING ACUTE ACCENT
// 0341 ; [.0000.0024.0002] # COMBINING ACUTE TONE MARK
// 0954 ; [.0000.0024.0002] # DEVANAGARI ACUTE ACCENT
//
// U+0301 and U+0954 don't decompose in the canonical decomposition mapping.
// U+0341 has a canonical decomposition mapping of U+0301.
ComparisonTest("\u{0301}", "\u{0341}",
reason: "https://bugs.swift.org/browse/SR-243"),
ComparisonTest("\u{0301}", "\u{0954}"),
ComparisonTest("\u{0341}", "\u{0954}"),
]
enum Stack: ErrorProtocol {
case Stack([UInt])
}
func checkHasPrefixHasSuffix(_ lhs: String, _ rhs: String, _ stack: [UInt]) -> Int {
if lhs == "" {
var failures = 0
failures += lhs.hasPrefix(rhs) ? 1 : 0
failures += lhs.hasSuffix(rhs) ? 1 : 0
return failures
}
if rhs == "" {
var failures = 0
failures += lhs.hasPrefix(rhs) ? 1 : 0
failures += lhs.hasSuffix(rhs) ? 1 : 0
return failures
}
// To determine the expected results, compare grapheme clusters,
// scalar-to-scalar, of the NFD form of the strings.
let lhsNFDGraphemeClusters =
lhs.decomposedStringWithCanonicalMapping.characters.map {
Array(String($0).unicodeScalars)
}
let rhsNFDGraphemeClusters =
rhs.decomposedStringWithCanonicalMapping.characters.map {
Array(String($0).unicodeScalars)
}
let expectHasPrefix = lhsNFDGraphemeClusters.starts(
with: rhsNFDGraphemeClusters, isEquivalent: (==))
let expectHasSuffix =
lhsNFDGraphemeClusters.lazy.reversed().starts(
with: rhsNFDGraphemeClusters.lazy.reversed(), isEquivalent: (==))
func testFailure(_ lhs: Bool, _ rhs: Bool, _ stack: [UInt]) -> Int {
guard lhs == rhs else {
// print(stack)
return 1
}
return 0
}
var failures = 0
failures += testFailure(expectHasPrefix, lhs.hasPrefix(rhs), stack + [#line])
failures += testFailure(expectHasSuffix, lhs.hasSuffix(rhs), stack + [#line])
return failures
}
extension TestNSString {
func test_PrefixSuffix() {
#if !_runtime(_ObjC)
for test in comparisonTests {
var failures = 0
failures += checkHasPrefixHasSuffix(test.lhs, test.rhs, [test.loc, #line])
failures += checkHasPrefixHasSuffix(test.rhs, test.lhs, [test.loc, #line])
let fragment = "abc"
let combiner = "\u{0301}"
failures += checkHasPrefixHasSuffix(test.lhs + fragment, test.rhs, [test.loc, #line])
failures += checkHasPrefixHasSuffix(fragment + test.lhs, test.rhs, [test.loc, #line])
failures += checkHasPrefixHasSuffix(test.lhs + combiner, test.rhs, [test.loc, #line])
failures += checkHasPrefixHasSuffix(combiner + test.lhs, test.rhs, [test.loc, #line])
let fail = (failures > 0)
if fail {
// print("Prefix/Suffix case \(test.loc): \(failures) failures")
// print("Failures were\(test.xfail ? "" : " not") expected")
}
XCTAssert(test.xfail == fail, "Unexpected \(test.xfail ?"success":"failure"): \(test.loc)")
}
#endif
}
}
func test_reflection() {
let testString: NSString = "some text here"
let ql = PlaygroundQuickLook(reflecting: testString)
switch ql {
case .text(let str): XCTAssertEqual(testString.bridge(), str)
default: XCTAssertTrue(false, "mismatched quicklook")
}
}
| 59a30e3624b9e6209bf8049e88ac0502 | 43.232578 | 221 | 0.632702 | false | true | false | false |
Allow2CEO/browser-ios | refs/heads/master | Client/Frontend/Reader/ReaderMode.swift | mpl-2.0 | 1 | /* 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 WebKit
import SwiftyJSON
let ReaderModeProfileKeyStyle = "readermode.style"
enum ReaderModeMessageType: String {
case StateChange = "ReaderModeStateChange"
case PageEvent = "ReaderPageEvent"
}
enum ReaderPageEvent: String {
case PageShow = "PageShow"
}
enum ReaderModeState: String {
case Available = "Available"
case Unavailable = "Unavailable"
case Active = "Active"
}
enum ReaderModeTheme: String {
case Light = "light"
case Dark = "dark"
case Sepia = "sepia"
}
enum ReaderModeFontType: String {
case Serif = "serif"
case SansSerif = "sans-serif"
}
enum ReaderModeFontSize: Int {
case size1 = 1
case size2 = 2
case size3 = 3
case size4 = 4
case size5 = 5
case size6 = 6
case size7 = 7
case size8 = 8
case size9 = 9
case size10 = 10
case size11 = 11
case size12 = 12
case size13 = 13
func isSmallest() -> Bool {
return self == ReaderModeFontSize.size1
}
func smaller() -> ReaderModeFontSize {
if isSmallest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue - 1)!
}
}
func isLargest() -> Bool {
return self == ReaderModeFontSize.size13
}
static var defaultSize: ReaderModeFontSize {
switch UIApplication.shared.preferredContentSizeCategory {
case UIContentSizeCategory.extraSmall:
return .size1
case UIContentSizeCategory.small:
return .size3
case UIContentSizeCategory.medium:
return .size5
case UIContentSizeCategory.large:
return .size7
case UIContentSizeCategory.extraLarge:
return .size9
case UIContentSizeCategory.extraExtraLarge:
return .size11
case UIContentSizeCategory.extraExtraExtraLarge:
return .size13
default:
return .size5
}
}
func bigger() -> ReaderModeFontSize {
if isLargest() {
return self
} else {
return ReaderModeFontSize(rawValue: self.rawValue + 1)!
}
}
}
struct ReaderModeStyle {
var theme: ReaderModeTheme
var fontType: ReaderModeFontType
var fontSize: ReaderModeFontSize
/// Encode the style to a JSON dictionary that can be passed to ReaderMode.js
func encode() -> String {
return JSON(["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]).rawString() ?? ""
}
/// Encode the style to a dictionary that can be stored in the profile
func encode() -> [String:Any] {
return ["theme": theme.rawValue, "fontType": fontType.rawValue, "fontSize": fontSize.rawValue]
}
init(theme: ReaderModeTheme, fontType: ReaderModeFontType, fontSize: ReaderModeFontSize) {
self.theme = theme
self.fontType = fontType
self.fontSize = fontSize
}
/// Initialize the style from a dictionary, taken from the profile. Returns nil if the object cannot be decoded.
init?(dict: [String:Any]) {
let themeRawValue = dict["theme"] as? String
let fontTypeRawValue = dict["fontType"] as? String
let fontSizeRawValue = dict["fontSize"] as? Int
if themeRawValue == nil || fontTypeRawValue == nil || fontSizeRawValue == nil {
return nil
}
let theme = ReaderModeTheme(rawValue: themeRawValue!)
let fontType = ReaderModeFontType(rawValue: fontTypeRawValue!)
let fontSize = ReaderModeFontSize(rawValue: fontSizeRawValue!)
if theme == nil || fontType == nil || fontSize == nil {
return nil
}
self.theme = theme!
self.fontType = fontType!
self.fontSize = fontSize!
}
}
let DefaultReaderModeStyle = ReaderModeStyle(theme: .Light, fontType: .SansSerif, fontSize: ReaderModeFontSize.defaultSize)
/// This struct captures the response from the Readability.js code.
struct ReadabilityResult {
var domain = ""
var url = ""
var content = ""
var title = ""
var credits = ""
init?(object: AnyObject?) {
if let dict = object as? NSDictionary {
if let uri = dict["uri"] as? NSDictionary {
if let url = uri["spec"] as? String {
self.url = url
}
if let host = uri["host"] as? String {
self.domain = host
}
}
if let content = dict["content"] as? String {
self.content = content
}
if let title = dict["title"] as? String {
self.title = title
}
if let credits = dict["byline"] as? String {
self.credits = credits
}
} else {
return nil
}
}
/// Initialize from a JSON encoded string
init?(string: String) {
let object = JSON(parseJSON: string)
let domain = object["domain"].string
let url = object["url"].string
let content = object["content"].string
let title = object["title"].string
let credits = object["credits"].string
if domain == nil || url == nil || content == nil || title == nil || credits == nil {
return nil
}
self.domain = domain!
self.url = url!
self.content = content!
self.title = title!
self.credits = credits!
}
/// Encode to a dictionary, which can then for example be json encoded
func encode() -> [String:Any] {
return ["domain": domain, "url": url, "content": content, "title": title, "credits": credits]
}
/// Encode to a JSON encoded string
func encode() -> String {
let dict: [String: Any] = self.encode()
return JSON(object: dict).rawString()!
}
}
/// Delegate that contains callbacks that we have added on top of the built-in WKWebViewDelegate
protocol ReaderModeDelegate {
func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forBrowser browser: Browser)
func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForBrowser browser: Browser)
}
let ReaderModeNamespace = "_firefox_ReaderMode"
class ReaderMode: BrowserHelper {
var delegate: ReaderModeDelegate?
fileprivate weak var browser: Browser?
var state: ReaderModeState = ReaderModeState.Unavailable
fileprivate var originalURL: URL?
required init(browser: Browser) {
self.browser = browser
// This is a WKUserScript at the moment because webView.evaluateJavaScript() fails with an unspecified error. Possibly script size related.
if let path = Bundle.main.path(forResource: "Readability", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
browser.webView?.configuration.userContentController.addUserScript(userScript)
}
}
// This is executed after a page has been loaded. It executes Readability and then fires a script message to let us know if the page is compatible with reader mode.
if let path = Bundle.main.path(forResource: "ReaderMode", ofType: "js") {
if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String {
let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
browser.webView?.configuration.userContentController.addUserScript(userScript)
}
}
if let dict = getApp().profile?.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let _style = ReaderModeStyle(dict: dict as [String : AnyObject]) {
// Force didSet to get called to ensure style is updated on the page
style = _style
}
}
}
class func scriptMessageHandlerName() -> String? {
return "readerModeMessageHandler"
}
fileprivate func handleReaderPageEvent(_ readerPageEvent: ReaderPageEvent) {
switch readerPageEvent {
case .PageShow:
if let browser = browser {
delegate?.readerMode(self, didDisplayReaderizedContentForBrowser: browser)
}
}
}
fileprivate func handleReaderModeStateChange(_ state: ReaderModeState) {
self.state = state
if let browser = browser {
delegate?.readerMode(self, didChangeReaderModeState: state, forBrowser: browser)
if state == .Active {
(style = style)
}
}
}
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let msg = message.body as? Dictionary<String, String> {
if let messageType = ReaderModeMessageType(rawValue: msg["Type"] ?? "") {
switch messageType {
case .PageEvent:
if let readerPageEvent = ReaderPageEvent(rawValue: msg["Value"] ?? "Invalid") {
handleReaderPageEvent(readerPageEvent)
}
break
case .StateChange:
if let readerModeState = ReaderModeState(rawValue: msg["Value"] ?? "Invalid") {
handleReaderModeStateChange(readerModeState)
}
break
}
}
}
}
var style: ReaderModeStyle = DefaultReaderModeStyle {
didSet {
if state == ReaderModeState.Active {
browser?.webView?.evaluateJavaScript("\(ReaderModeNamespace).setStyle(\(style.encode() as String))", completionHandler: { (object, error) -> Void in
return
})
}
}
}
}
| f2886105306a37cd32a19101e67f8f71 | 33.410596 | 172 | 0.609796 | false | false | false | false |
dutchcoders/stacktray | refs/heads/v2 | StackTray/Models/Account.swift | mit | 1 | //
// Account.swift
// stacktray
//
// Created by Ruben Cagnie on 3/4/15.
// Copyright (c) 2015 dutchcoders. All rights reserved.
//
import Cocoa
public enum AccountType : Int, Printable {
case AWS, DUMMY, Unknown
/** Name of the thumbnail that should be show */
public var imageName: String {
switch self{
case .AWS: return "AWS"
case .DUMMY: return "DUMMY"
case .Unknown: return "UNKNOWN"
}
}
/** Description */
public var description: String {
switch self{
case .AWS: return "Amazon Web Service"
case .DUMMY: return "DUMMY Web Service"
case .Unknown: return "Unknown Web Service"
}
}
}
public protocol AccountDelegate {
func didAddAccountInstance(account: Account, instanceIndex: Int)
func didUpdateAccountInstance(account: Account, instanceIndex: Int)
func didDeleteAccountInstance(account: Account, instanceIndex: Int)
func instanceDidStart(account: Account, instanceIndex: Int)
func instanceDidStop(account: Account, instanceIndex: Int)
}
/**
An account object represents the connection to a web service
*/
public class Account : NSObject, NSCoding {
/** Meta Data */
public var name: String = ""
/** Account Type */
public var accountType: AccountType = .Unknown
/** Delegate */
public var delegate : AccountDelegate?
func sortOnName(this:Instance, that:Instance) -> Bool {
return this.name > that.name
}
/** Instances */
public var instances : [Instance] = [] {
didSet{
if let d = delegate {
let oldInstanceIds = oldValue.map{ $0.instanceId }
let newInstanceIds = instances.map{ $0.instanceId }
for instance in instances {
if contains(oldInstanceIds, instance.instanceId) && contains(newInstanceIds, instance.instanceId) {
d.didUpdateAccountInstance(self, instanceIndex: find(instances, instance)!)
} else if contains(oldInstanceIds, instance.instanceId){
d.didDeleteAccountInstance(self, instanceIndex: find(instances, instance)!)
} else if contains(newInstanceIds, instance.instanceId){
d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!)
}
}
}
}
}
/** Init an Account Object */
public init(name: String, accountType: AccountType){
self.name = name
self.accountType = accountType
super.init()
}
required public init(coder aDecoder: NSCoder) {
if let name = aDecoder.decodeObjectForKey("name") as? String {
self.name = name
}
if let accountTypeNumber = aDecoder.decodeObjectForKey("accountType") as? NSNumber {
if let accountType = AccountType(rawValue: accountTypeNumber.integerValue){
self.accountType = accountType
}
}
if let data = aDecoder.decodeObjectForKey("instances") as? NSData {
if let instances = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Instance] {
self.instances = instances
}
}
super.init()
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(NSNumber(integer: accountType.rawValue), forKey: "accountType")
aCoder.encodeObject(NSKeyedArchiver.archivedDataWithRootObject(instances), forKey: "instances")
}
public func addInstance(instance: Instance){
instances.append(instance)
if let d = delegate {
d.didAddAccountInstance(self, instanceIndex: find(instances, instance)!)
}
}
public func updateInstanceAtIndex(index: Int, instance: Instance){
let existingInstance = instances[index]
let beforeState = existingInstance.state
existingInstance.mergeInstance(instance)
if let d = delegate {
d.didUpdateAccountInstance(self, instanceIndex: index)
if instance.lastUpdate != nil && instance.state != beforeState {
if instance.state == .Running {
d.instanceDidStart(self, instanceIndex: index)
} else if instance.state == .Stopped {
d.instanceDidStop(self, instanceIndex: index)
}
}
}
}
public func removeInstances(instanceIds: [String]){
var toRemove = instances.filter { (instance) -> Bool in
return contains(instanceIds, instance.instanceId)
}
for instance in toRemove {
if let index = find(instances, instance){
instances.removeAtIndex(index)
if let d = delegate {
d.didDeleteAccountInstance(self, instanceIndex: index)
}
}
}
}
}
public class AWSAccount : Account {
/** AWS Specific Keys */
public var accessKey: String = ""
public var secretKey: String = ""
public var region: String = ""
/** Init an AWS Account Object */
public init(name: String, accessKey: String, secretKey: String, region: String){
self.accessKey = accessKey
self.secretKey = secretKey
self.region = region
super.init(name: name, accountType: .AWS)
}
required public init(coder aDecoder: NSCoder) {
if let accessKey = aDecoder.decodeObjectForKey("accessKey") as? String {
self.accessKey = accessKey
}
if let secretKey = aDecoder.decodeObjectForKey("secretKey") as? String {
self.secretKey = secretKey
}
if let region = aDecoder.decodeObjectForKey("region") as? String{
self.region = region
}
super.init(coder: aDecoder)
}
public override func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(accessKey, forKey: "accessKey")
aCoder.encodeObject(secretKey, forKey: "secretKey")
aCoder.encodeObject(region, forKey: "region")
super.encodeWithCoder(aCoder)
}
}
| e01d6949642f32784d3abed440b363df | 32.282723 | 119 | 0.596665 | false | false | false | false |
tiagobsbraga/HotmartTest | refs/heads/master | HotmartTest/MessageCollectionViewCell.swift | mit | 1 | //
// MessageCollectionViewCell.swift
// HotmartTest
//
// Created by Tiago Braga on 08/02/17.
// Copyright © 2017 Tiago Braga. All rights reserved.
//
import UIKit
class MessageCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var firstCharNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.firstCharNameLabel.isHidden = true
}
// Public Methods
func populateMessage(_ message: Message) {
self.photoImageView.image = UIImage()
self.photoImageView.cicleMask(message.photo, withBackgroundColor: Style.randomColor())
self.nameLabel.text = message.name
self.firstCharNameLabel.text = String(message.firstChar())
self.firstCharNameLabel.isHidden = !(message.photo == nil)
}
}
| f7954cea358080acbbfaadda4ae4a0b5 | 28 | 94 | 0.696329 | false | false | false | false |
innominds-mobility/swift-custom-ui-elements | refs/heads/master | swift-custom-ui/InnoUI/InnoProgressViewCircle.swift | gpl-3.0 | 1 | //
// InnoProgressView.swift
// swift-custom-ui
//
// Created by Deepthi Muramshetty on 09/05/17.
// Copyright © 2017 Innominds Mobility. All rights reserved.
//
import UIKit
/// The purpose of this class is to provide custom view for showing progress in a circle.
/// The `InnoProgressViewCircle` class is a subclass of the `UIView`.
@IBDesignable public class InnoProgressViewCircle: UIView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
/// IBInspectable for Progress color of InnoProgressViewCircle.
@IBInspectable public var progressColor: UIColor = UIColor.orange {
didSet {
setNeedsDisplay()
}
}
/// IBInspectable for Progress default color of InnoProgressViewCircle.
@IBInspectable public var progressDefaultColor: UIColor = UIColor.lightGray {
didSet {
setNeedsDisplay()
}
}
/// IBInspectable for Progress width of InnoProgressViewCircle.
@IBInspectable public var progressWidth: CGFloat = 0.0
/// IBInspectable for Progress value of InnoProgressViewCircle.
@IBInspectable public var progress: CGFloat = 0.0 {
didSet {
self.drawProgressCircleViewLayer(progressVal:progress, strokeColor: self.progressColor)
}
}
/// IBInspectable for show title bool of InnoProgressViewCircle
@IBInspectable public var showTitle: Bool = false
/// IBInspectable for progress title of InnoProgressViewCircle
@IBInspectable public var progressTitle: NSString = "Progress"
/// Performing custom drawing for progress circle.
///
/// - Parameter rect: The portion of the view’s bounds that needs to be updated.
override public func draw(_ rect: CGRect) {
// Add ARCs
self.drawDefaultCircleLayer()
self.drawProgressCircleViewLayer(progressVal: self.progress, strokeColor: self.progressColor)
}
/// Shape layer for default circle.
var defaultCircleLayer: CAShapeLayer = CAShapeLayer()
/// Shape layer for progress circle.
let progressCircleLayer: CAShapeLayer = CAShapeLayer()
// MARK: Drawing default circle layer method
/// This method draws default circle layer on a bezier path and adds a stroke color to it.
func drawDefaultCircleLayer() {
/// Center point of circle.
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
/// Radius of arc.
let radius: CGFloat = max(bounds.width, bounds.height)
/// Arc width.
let arcWidth: CGFloat = self.progressWidth
/// Start angle.
let startAngle: CGFloat = 3 * 3.14/2// 3* π / 4
/// End angle.
let endAngle: CGFloat = startAngle + CGFloat(2 * 3.14 * 1.0)//π / 4
/// Path for default circle.
let defaultPath = UIBezierPath(arcCenter: center,
radius: radius/2 - arcWidth/2,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
defaultPath.lineWidth = arcWidth
self.progressDefaultColor.setStroke()
defaultPath.stroke()
defaultPath.close()
defaultCircleLayer.path = defaultPath.cgPath
defaultCircleLayer.fillColor = UIColor.clear.cgColor
defaultCircleLayer.strokeEnd = 0
self.layer.addSublayer(defaultCircleLayer)
}
// MARK: Drawing Progress circle layer Method
/// This method draws/redraws progress circle layer on bezier path and adds a stroke color to it.
/// This layer is added as a sublayer for 'defaultCircleLayer'.
/// For every change in progress value, this method is called.
///
/// - Parameters:
/// - progressVal: Progress value for circle.
/// - strokeColor: color of circle.
func drawProgressCircleViewLayer(progressVal: CGFloat, strokeColor: UIColor) {
progressCircleLayer.removeFromSuperlayer()
/// Center point of arc.
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
/// Radius of arc.
let radius: CGFloat = max(bounds.width, bounds.height)
/// Arc width.
let arcWidth: CGFloat = self.progressWidth
/// Start angle.
let startAngle: CGFloat = 3 * 3.14/2// 3* π / 4
/// End angle.
let endAngle: CGFloat = startAngle + CGFloat(2 * 3.14 * progressVal)//π / 4
/// Path for progress circle
let pCirclePath = UIBezierPath(arcCenter: center,
radius: radius/2 - arcWidth/2, startAngle: startAngle,
endAngle: endAngle, clockwise: true)
pCirclePath.lineWidth = arcWidth
strokeColor.setStroke()
pCirclePath.stroke()
pCirclePath.close()
progressCircleLayer.path = pCirclePath.cgPath
progressCircleLayer.fillColor = UIColor.clear.cgColor
defaultCircleLayer.addSublayer(progressCircleLayer)
for subview in self.subviews { subview.removeFromSuperview() }
if showTitle {
/// Title view
let datailsView = UIView()
datailsView.frame = CGRect(x: self.bounds.origin.x+10,
y: self.bounds.height/2-30,
width: self.bounds.width-20, height: 60)
/// Title label
let nameLabel = UILabel()
nameLabel.font = UIFont(name: "Helvetica-Bold", size: 20)
nameLabel.frame = CGRect(x: 0, y: 0,
width: datailsView.frame.size.width, height: 30)
nameLabel.text = progressTitle as String
nameLabel.textAlignment = NSTextAlignment.center
nameLabel.textColor = strokeColor
datailsView.addSubview(nameLabel)
/// Progress value label
let valLabel = UILabel()
valLabel.font = UIFont(name: "Helvetica-Bold", size: 30)
valLabel.frame = CGRect(x: 5,
y: nameLabel.frame.origin.y+nameLabel.frame.size.height+5,
width: datailsView.frame.size.width-10, height: 30)
valLabel.text = "\(Int(progressVal*100))%"
valLabel.textAlignment = NSTextAlignment.center
valLabel.textColor = strokeColor
datailsView.addSubview(valLabel)
self.addSubview(datailsView) }
}
}
| 1058c7d8a73c50855c6edee04723c1c4 | 43.763514 | 101 | 0.618868 | false | false | false | false |
IvanVorobei/Sparrow | refs/heads/master | sparrow/ui/controls/buttons/SPSystemIconButton.swift | mit | 1 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPSystemIconButton: UIButton {
let iconView = SPSystemIconView.init()
var widthIconFactor: CGFloat = 1
var heightIconFactor: CGFloat = 1
var type: SPSystemIconType {
didSet {
self.iconView.type = self.type
}
}
var color = SPNativeStyleKit.Colors.blue {
didSet {
self.iconView.color = self.color
}
}
override var isHighlighted: Bool {
didSet {
if isHighlighted {
self.iconView.color = self.color.withAlphaComponent(0.7)
} else {
self.iconView.color = self.color.withAlphaComponent(1)
}
}
}
init() {
self.type = .share
super.init(frame: CGRect.zero)
self.commonInit()
}
init(type: SPSystemIconType) {
self.type = type
super.init(frame: CGRect.zero)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func commonInit() {
self.iconView.isUserInteractionEnabled = false
self.addSubview(self.iconView)
}
override func layoutSubviews() {
super.layoutSubviews()
self.iconView.setEqualsFrameFromBounds(self, withWidthFactor: self.widthIconFactor, withHeightFactor: self.heightIconFactor, withCentering: true)
}
}
| f722378c360969c303f01cf55f67b6a6 | 32.487179 | 153 | 0.665391 | false | false | false | false |
whereuat/whereuat-ios | refs/heads/master | whereuat-ios/Database/ContactRequestTable.swift | apache-2.0 | 1 | //
// ContactRequestTable.swift
// whereuat
//
// Created by Raymond Jacobson on 5/16/16.
// Copyright © 2016 whereuat. All rights reserved.
//
import Foundation
import SQLite
/*
* ContactRequestTable is the SQLite database tables for pending requests that have
* not been added as contacts
*/
class ContactRequestTable: Table {
static let sharedInstance = ContactRequestTable(databaseFilePath: "database.sqlite")
private var databaseFilePath: String!
var contactRequests: SQLite.Table
var db: SQLite.Connection?
var idColumn: SQLite.Expression<Int64>
var firstNameColumn: SQLite.Expression<String>
var lastNameColumn: SQLite.Expression<String>
var phoneNumberColumn: SQLite.Expression<String>
/*
* Init sets up the SQLite connection and constructs the schema
*/
init(databaseFilePath: String) {
self.databaseFilePath = databaseFilePath
if let dirs: [NSString] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainsMask, true) as [NSString] {
let dir = dirs[0]
self.databaseFilePath = dir.stringByAppendingPathComponent(self.databaseFilePath);
}
do {
self.db = try SQLite.Connection(self.databaseFilePath)
} catch {
print("Unable to connect to the Database")
}
self.contactRequests = SQLite.Table("contactRequests")
self.idColumn = SQLite.Expression<Int64>("id")
self.firstNameColumn = SQLite.Expression<String>("firstName")
self.lastNameColumn = SQLite.Expression<String>("lastName")
self.phoneNumberColumn = SQLite.Expression<String>("phoneNumber")
}
/*
* setUpTable instantiates the schema
*/
func setUpTable() {
do {
try (self.db!).run(self.contactRequests.create(ifNotExists: true) { t in
t.column(self.idColumn, primaryKey: true)
t.column(self.firstNameColumn)
t.column(self.lastNameColumn)
t.column(self.phoneNumberColumn, unique: true)
})
} catch {
print("Unable to set up Database")
}
}
/*
* dropTable drops the database table
*/
func dropTable() {
// Clean the database
do {
try (self.db)!.run(self.contactRequests.drop())
} catch {
print ("Unable to drop the database")
}
}
/*
* generateMockData fills the table with 5 mock contacts
*/
func generateMockData() {
let contact1 = Contact(firstName: "Damian",
lastName: "Mastylo",
phoneNumber: "+19133700735",
autoShare: true,
requestedCount: 0,
color: ColorWheel.randomColor())
let contact2 = Contact(firstName: "Yingjie",
lastName: "Shu",
phoneNumber: "+12029552443",
autoShare: false,
requestedCount: 0,
color: ColorWheel.randomColor())
let contact3 = Contact(firstName: "",
lastName: "",
phoneNumber: "+12077348728",
autoShare: false,
requestedCount: 0,
color: ColorWheel.randomColor())
// Insert mock data
insert(contact1)
insert(contact2)
insert(contact3)
}
/*
* insert inserts a row into the database
* @param - contact to insert
*/
func insert(contact: Model) {
let c = contact as! Contact
let insert = self.contactRequests.insert(self.firstNameColumn <- c.firstName,
self.lastNameColumn <- c.lastName,
self.phoneNumberColumn <- c.phoneNumber)
do {
try (self.db!).run(insert)
} catch {
print("Unable to insert contact")
}
}
/*
* getAll returns all of the rows in the table, a SELECT * FROM
* @return - Array of Model type
*/
func getAll() -> Array<Model> {
var contactRequestArray = Array<Contact>()
do {
for contact in (try (self.db!).prepare(self.contactRequests)) {
contactRequestArray.append(Contact(firstName: contact[self.firstNameColumn],
lastName: contact[self.lastNameColumn],
phoneNumber: contact[self.phoneNumberColumn]))
}
} catch {
print("Unable to get pending requests")
return Array<Contact>()
}
return contactRequestArray
}
/*
* dropContactRequest retrieves a particular pending request by phone number and removes
* it from the table.
* @param - phoneNumber is the phone number for the pending request lookup
*/
func dropContactRequest(phoneNumber: String) {
let query = contactRequests.filter(phoneNumberColumn == phoneNumber)
do {
try db!.run(query.delete())
} catch {
print("Unable to delete contactRequest")
}
}
/*
* getContactRequest retrives a particular pending request by phone number.
* @param - phoneNumber is the phone number for the pending request lookup
* @return the contact found
*/
func getContactRequest(phoneNumber: String) -> Contact? {
do {
let query = contactRequests.filter(phoneNumberColumn == phoneNumber)
let c = try (db!).prepare(query)
for contact in c {
return Contact(firstName: contact[self.firstNameColumn],
lastName: contact[self.lastNameColumn],
phoneNumber: contact[self.phoneNumberColumn])
}
return nil
} catch {
print("Unable to get contact")
return nil
}
}
} | a6a865eda5e5fd5063c929974d9cd9f0 | 34.664804 | 130 | 0.545198 | false | false | false | false |
igandhi/Trax | refs/heads/master | SwiftyExpandingCells/Libs/FontAwesome/FontAwesome.swift | mit | 1 | // FontAwesome.swift
//
// Copyright (c) 2014-2015 Thi Doan
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreText
private class FontLoader {
class func loadFont(name: String) {
let bundle = NSBundle(forClass: FontLoader.self)
var fontURL = NSURL()
let identifier = bundle.bundleIdentifier
if identifier?.hasPrefix("org.cocoapods") == true {
// If this framework is added using CocoaPods, resources is placed under a subdirectory
fontURL = bundle.URLForResource(name, withExtension: "otf", subdirectory: "FontAwesome.swift.bundle")!
} else {
fontURL = bundle.URLForResource(name, withExtension: "otf")!
}
let data = NSData(contentsOfURL: fontURL)!
let provider = CGDataProviderCreateWithCFData(data)
let font = CGFontCreateWithDataProvider(provider)!
var error: Unmanaged<CFError>?
if !CTFontManagerRegisterGraphicsFont(font, &error) {
let errorDescription: CFStringRef = CFErrorCopyDescription(error!.takeUnretainedValue())
let nsError = error!.takeUnretainedValue() as AnyObject as! NSError
NSException(name: NSInternalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise()
}
}
}
public extension UIFont {
public class func fontAwesomeOfSize(fontSize: CGFloat) -> UIFont {
struct Static {
static var onceToken : dispatch_once_t = 0
}
let name = "FontAwesome"
if (UIFont.fontNamesForFamilyName(name).count == 0) {
dispatch_once(&Static.onceToken) {
FontLoader.loadFont(name)
}
}
return UIFont(name: name, size: fontSize)!
}
}
public extension String {
public static func fontAwesomeIconWithName(name: FontAwesome) -> String {
return name.rawValue.substringToIndex(name.rawValue.startIndex.advancedBy(1))
}
}
public extension UIImage {
public static func fontAwesomeIconWithName(name: FontAwesome, textColor: UIColor, size: CGSize) -> UIImage {
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = NSLineBreakMode.ByWordWrapping
paragraph.alignment = .Center
let attributedString = NSAttributedString(string: String.fontAwesomeIconWithName(name) as String, attributes: [NSFontAttributeName: UIFont.fontAwesomeOfSize(max(size.width, size.height)), NSForegroundColorAttributeName: textColor, NSParagraphStyleAttributeName:paragraph])
let size = sizeOfAttributeString(attributedString, maxWidth: size.width)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
attributedString.drawInRect(CGRectMake(0, 0, size.width, size.height))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
func sizeOfAttributeString(str: NSAttributedString, maxWidth: CGFloat) -> CGSize {
let size = str.boundingRectWithSize(CGSizeMake(maxWidth, 1000), options:(NSStringDrawingOptions.UsesLineFragmentOrigin), context:nil).size
return size
}
| 880bdf0411a6848512c7f73adb24c9e7 | 43.670213 | 280 | 0.717075 | false | false | false | false |
wilfreddekok/Antidote | refs/heads/master | Antidote/ProfileDetailsController.swift | mpl-2.0 | 1 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import LocalAuthentication
protocol ProfileDetailsControllerDelegate: class {
func profileDetailsControllerSetPin(controller: ProfileDetailsController)
func profileDetailsControllerChangeLockTimeout(controller: ProfileDetailsController)
func profileDetailsControllerChangePassword(controller: ProfileDetailsController)
func profileDetailsControllerDeleteProfile(controller: ProfileDetailsController)
}
class ProfileDetailsController: StaticTableController {
weak var delegate: ProfileDetailsControllerDelegate?
private weak var toxManager: OCTManager!
private let pinEnabledModel = StaticTableSwitchCellModel()
private let lockTimeoutModel = StaticTableInfoCellModel()
private let touchIdEnabledModel = StaticTableSwitchCellModel()
private let changePasswordModel = StaticTableButtonCellModel()
private let exportProfileModel = StaticTableButtonCellModel()
private let deleteProfileModel = StaticTableButtonCellModel()
private var documentInteractionController: UIDocumentInteractionController?
init(theme: Theme, toxManager: OCTManager) {
self.toxManager = toxManager
var model = [[StaticTableBaseCellModel]]()
var footers = [String?]()
model.append([pinEnabledModel, lockTimeoutModel])
footers.append(String(localized: "pin_description"))
if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
model.append([touchIdEnabledModel])
footers.append(String(localized: "pin_touch_id_description"))
}
model.append([changePasswordModel])
footers.append(nil)
model.append([exportProfileModel, deleteProfileModel])
footers.append(nil)
super.init(theme: theme, style: .Grouped, model: model, footers: footers)
updateModel()
title = String(localized: "profile_details")
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateModel()
reloadTableView()
}
}
extension ProfileDetailsController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController) -> UIView? {
return view
}
func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController) -> CGRect {
return view.frame
}
}
private extension ProfileDetailsController {
func updateModel() {
let settings = toxManager.objects.getProfileSettings()
let isPinEnabled = settings.unlockPinCode != nil
pinEnabledModel.title = String(localized: "pin_enabled")
pinEnabledModel.on = isPinEnabled
pinEnabledModel.valueChangedHandler = pinEnabledValueChanged
lockTimeoutModel.title = String(localized: "pin_lock_timeout")
lockTimeoutModel.showArrow = true
lockTimeoutModel.didSelectHandler = changeLockTimeout
switch settings.lockTimeout {
case .Immediately:
lockTimeoutModel.value = String(localized: "pin_lock_immediately")
case .Seconds30:
lockTimeoutModel.value = String(localized: "pin_lock_30_seconds")
case .Minute1:
lockTimeoutModel.value = String(localized: "pin_lock_1_minute")
case .Minute2:
lockTimeoutModel.value = String(localized: "pin_lock_2_minutes")
case .Minute5:
lockTimeoutModel.value = String(localized: "pin_lock_5_minutes")
}
touchIdEnabledModel.enabled = isPinEnabled
touchIdEnabledModel.title = String(localized: "pin_touch_id_enabled")
touchIdEnabledModel.on = settings.useTouchID
touchIdEnabledModel.valueChangedHandler = touchIdEnabledValueChanged
changePasswordModel.title = String(localized: "change_password")
changePasswordModel.didSelectHandler = changePassword
exportProfileModel.title = String(localized: "export_profile")
exportProfileModel.didSelectHandler = exportProfile
deleteProfileModel.title = String(localized: "delete_profile")
deleteProfileModel.didSelectHandler = deleteProfile
}
func pinEnabledValueChanged(on: Bool) {
if on {
delegate?.profileDetailsControllerSetPin(self)
}
else {
let settings = toxManager.objects.getProfileSettings()
settings.unlockPinCode = nil
toxManager.objects.saveProfileSettings(settings)
}
updateModel()
reloadTableView()
}
func changeLockTimeout(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangeLockTimeout(self)
}
func touchIdEnabledValueChanged(on: Bool) {
let settings = toxManager.objects.getProfileSettings()
settings.useTouchID = on
toxManager.objects.saveProfileSettings(settings)
}
func changePassword(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangePassword(self)
}
func exportProfile(_: StaticTableBaseCell) {
do {
let path = try toxManager.exportToxSaveFile()
let name = UserDefaultsManager().lastActiveProfile ?? "profile"
documentInteractionController = UIDocumentInteractionController(URL: NSURL.fileURLWithPath(path))
documentInteractionController!.delegate = self
documentInteractionController!.name = "\(name).tox"
documentInteractionController!.presentOptionsMenuFromRect(view.frame, inView:view, animated: true)
}
catch let error as NSError {
handleErrorWithType(.ExportProfile, error: error)
}
}
func deleteProfile(cell: StaticTableBaseCell) {
let title1 = String(localized: "delete_profile_confirmation_title_1")
let title2 = String(localized: "delete_profile_confirmation_title_2")
let message = String(localized: "delete_profile_confirmation_message")
let yes = String(localized: "alert_delete")
let cancel = String(localized: "alert_cancel")
let alert1 = UIAlertController(title: title1, message: message, preferredStyle: .ActionSheet)
alert1.popoverPresentationController?.sourceView = cell
alert1.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert1.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
let alert2 = UIAlertController(title: title2, message: nil, preferredStyle: .ActionSheet)
alert2.popoverPresentationController?.sourceView = cell
alert2.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert2.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
self.reallyDeleteProfile()
})
alert2.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
})
alert1.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
presentViewController(alert1, animated: true, completion: nil)
}
func reallyDeleteProfile() {
delegate?.profileDetailsControllerDeleteProfile(self)
}
}
| 937c571bba5ddde6a9681764fcf21802 | 38.895 | 155 | 0.702218 | false | false | false | false |
mxcl/PromiseKit | refs/heads/v6 | Tests/JS-A+/JSPromise.swift | mit | 1 | //
// JSPromise.swift
// PMKJSA+Tests
//
// Created by Lois Di Qual on 3/1/18.
//
import Foundation
import XCTest
import PromiseKit
import JavaScriptCore
@objc protocol JSPromiseProtocol: JSExport {
func then(_: JSValue, _: JSValue) -> JSPromise
}
class JSPromise: NSObject, JSPromiseProtocol {
let promise: Promise<JSValue>
init(promise: Promise<JSValue>) {
self.promise = promise
}
func then(_ onFulfilled: JSValue, _ onRejected: JSValue) -> JSPromise {
// Keep a reference to the returned promise so we can comply to 2.3.1
var returnedPromiseRef: Promise<JSValue>?
let afterFulfill = promise.then { value -> Promise<JSValue> in
// 2.2.1: ignored if not a function
guard JSUtils.isFunction(value: onFulfilled) else {
return .value(value)
}
// Call `onFulfilled`
// 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value)
guard let returnValue = try JSUtils.call(function: onFulfilled, arguments: [JSUtils.undefined, value]) else {
return .value(value)
}
// Extract JSPromise.promise if available, or use plain return value
if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise {
// 2.3.1: if returned value is the promise that `then` returned, throw TypeError
if jsPromise.promise === returnedPromiseRef {
throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self"))
}
return jsPromise.promise
} else {
return .value(returnValue)
}
}
let afterReject = promise.recover { error -> Promise<JSValue> in
// 2.2.1: ignored if not a function
guard let jsError = error as? JSUtils.JSError, JSUtils.isFunction(value: onRejected) else {
throw error
}
// Call `onRejected`
// 2.2.5: onFulfilled/onRejected must be called as functions (with no `this` value)
guard let returnValue = try JSUtils.call(function: onRejected, arguments: [JSUtils.undefined, jsError.reason]) else {
throw error
}
// Extract JSPromise.promise if available, or use plain return value
if let jsPromise = returnValue.toObjectOf(JSPromise.self) as? JSPromise {
// 2.3.1: if returned value is the promise that `then` returned, throw TypeError
if jsPromise.promise === returnedPromiseRef {
throw JSUtils.JSError(reason: JSUtils.typeError(message: "Returned self"))
}
return jsPromise.promise
} else {
return .value(returnValue)
}
}
let newPromise = Promise<Result<JSValue>> { resolver in
_ = promise.tap(resolver.fulfill)
}.then(on: nil) { result -> Promise<JSValue> in
switch result {
case .fulfilled: return afterFulfill
case .rejected: return afterReject
}
}
returnedPromiseRef = newPromise
return JSPromise(promise: newPromise)
}
}
| 1b7a6c72a59ea374be42d7ef6ef44a1f | 35.585106 | 129 | 0.562954 | false | false | false | false |
SahilDhawan/On-The-Map | refs/heads/master | OnTheMap/AddLocationViewController.swift | mit | 1 | //
// AddLocationViewController.swift
// OnTheMap
//
// Created by Sahil Dhawan on 05/04/17.
// Copyright © 2017 Sahil Dhawan. All rights reserved.
//
import UIKit
import CoreLocation
class AddLocationViewController: UIViewController {
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var websiteTextField: UITextField!
//Current User Details
static var mapString : String = ""
static var webURL : String = ""
static var studentLocation : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0)
override func viewDidLoad() {
super.viewDidLoad()
locationTextField.delegate = self
websiteTextField.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
Alert().activityView(false, self.view)
}
@IBAction func FindLocationPressed(_ sender: Any) {
guard locationTextField.text == nil, websiteTextField.text == nil else
{
//ActivityIndicatorView
Alert().activityView(true, self.view)
let geocoder = CLGeocoder()
let text = websiteTextField.text!
if(text.contains("https://www.") || (text.contains("http://www.")) && (text.contains(".com")))
{
AddLocationViewController.webURL = websiteTextField.text!
geocoder.geocodeAddressString(locationTextField.text!, completionHandler: { (placemark, error) in
if error != nil
{
Alert().showAlert("Invalid Location",self)
Alert().activityView(false, self.view)
}
else
{
if let place = placemark, (placemark?.count)! > 0
{
var location : CLLocation?
location = place.first?.location
AddLocationViewController.studentLocation = location!.coordinate
AddLocationViewController.mapString = self.locationTextField.text!
Alert().activityView(false, self.view)
self.performSegue(withIdentifier: "UserCoordinate", sender: location)
}
}
})
}
else
{
Alert().showAlert("website link is not valid",self)
Alert().activityView(false, self.view)
return
}
return
}
}
@IBAction func cancelButtonPressed(_ sender: Any) {
let controller = storyboard?.instantiateViewController(withIdentifier: "tabController")
self.present(controller!, animated: true, completion: nil)
}
}
extension AddLocationViewController:UITextFieldDelegate
{
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
| a15a00714332def04a981b8bae486ff7 | 32.795918 | 113 | 0.57035 | false | false | false | false |
nerdishbynature/RequestKit | refs/heads/main | Tests/RequestKitTests/RequestKitURLTestSession.swift | mit | 1 | import RequestKit
import XCTest
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
class MockURLSessionDataTask: URLSessionDataTaskProtocol {
fileprivate(set) var resumeWasCalled = false
func resume() {
resumeWasCalled = true
}
}
class RequestKitURLTestSession: RequestKitURLSession {
var wasCalled: Bool = false
let expectedURL: String
let expectedHTTPMethod: String
let responseString: String?
let statusCode: Int
init(expectedURL: String, expectedHTTPMethod: String, response: String?, statusCode: Int) {
self.expectedURL = expectedURL
self.expectedHTTPMethod = expectedHTTPMethod
responseString = response
self.statusCode = statusCode
}
init(expectedURL: String, expectedHTTPMethod: String, jsonFile: String?, statusCode: Int) {
self.expectedURL = expectedURL
self.expectedHTTPMethod = expectedHTTPMethod
if let jsonFile = jsonFile {
responseString = Helper.stringFromFile(jsonFile)
} else {
responseString = nil
}
self.statusCode = statusCode
}
func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void) -> URLSessionDataTaskProtocol {
XCTAssertEqual(request.url?.absoluteString, expectedURL)
XCTAssertEqual(request.httpMethod, expectedHTTPMethod)
let data = responseString?.data(using: String.Encoding.utf8)
let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "http/1.1", headerFields: ["Content-Type": "application/json"])
completionHandler(data, response, nil)
wasCalled = true
return MockURLSessionDataTask()
}
func uploadTask(with request: URLRequest, fromData _: Data?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTaskProtocol {
XCTAssertEqual(request.url?.absoluteString, expectedURL)
XCTAssertEqual(request.httpMethod, expectedHTTPMethod)
let data = responseString?.data(using: String.Encoding.utf8)
let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "http/1.1", headerFields: ["Content-Type": "application/json"])
completionHandler(data, response, nil)
wasCalled = true
return MockURLSessionDataTask()
}
#if compiler(>=5.5.2) && canImport(_Concurrency)
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
func upload(for request: URLRequest, from _: Data, delegate _: URLSessionTaskDelegate?) async throws -> (Data, URLResponse) {
XCTAssertEqual(request.url?.absoluteString, expectedURL)
XCTAssertEqual(request.httpMethod, expectedHTTPMethod)
let data = responseString?.data(using: String.Encoding.utf8)
let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "http/1.1", headerFields: ["Content-Type": "application/json"])
wasCalled = true
return (data!, response!)
}
@available(macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0, *)
func data(for request: URLRequest, delegate _: URLSessionTaskDelegate?) async throws -> (Data, URLResponse) {
XCTAssertEqual(request.url?.absoluteString, expectedURL)
XCTAssertEqual(request.httpMethod, expectedHTTPMethod)
let data = responseString?.data(using: String.Encoding.utf8)
let response = HTTPURLResponse(url: request.url!, statusCode: statusCode, httpVersion: "http/1.1", headerFields: ["Content-Type": "application/json"])
wasCalled = true
return (data!, response!)
}
#endif
}
| b77992d19556241d1b0ac98549737975 | 44.45679 | 164 | 0.698533 | false | true | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/LockerRental/model/LockerRentalAgreement.swift | apache-2.0 | 2 | //
// LockerRentalAgreement.swift
// byuSuite
//
// Created by Erik Brady on 7/18/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
private let dateFormat = DateFormatter.defaultDateFormat("MMM dd, yyyy")
class LockerRentalAgreement: NSObject, Comparable {
var personId: String?
var lockerId: Int?
var agreementDateTime: Date?
var expirationDate: Date?
var agreedToTerms: Bool
var fee: Int?
var dateCharged: Date?
var locker: LockerRentalLocker?
init(dict: [String: Any]) {
personId = dict["personId"] as? String
lockerId = dict["lockerId"] as? Int
agreementDateTime = dateFormat.date(from: dict["agreementDateTime"] as? String)
expirationDate = dateFormat.date(from: dict["expirationDate"] as? String)
agreedToTerms = dict["agreedToTerms"] as? Bool ?? false
fee = dict["fee"] as? Int
dateCharged = dateFormat.date(from: dict["dateCharged"] as? String)
}
func expirationDateString() -> String {
if let expirationDate = expirationDate {
return dateFormat.string(from: expirationDate)
} else {
return ""
}
}
//MARK: Comparable Methods
static func <(lhs: LockerRentalAgreement, rhs: LockerRentalAgreement) -> Bool {
return lhs.expirationDate ?? Date() < rhs.expirationDate ?? Date()
}
static func ==(lhs: LockerRentalAgreement, rhs: LockerRentalAgreement) -> Bool {
return lhs.expirationDate == rhs.expirationDate
}
}
| ebd9525b4af8f254f7fed7facebd46ea | 30.979592 | 87 | 0.644544 | false | false | false | false |
huangboju/QMUI.swift | refs/heads/master | QMUI.swift/Demo/Modules/Demos/Components/QDSingleImagePickerPreviewViewController.swift | mit | 1 | //
// QDSingleImagePickerPreviewViewController.swift
// QMUI.swift
//
// Created by qd-hxt on 2018/5/14.
// Copyright © 2018年 伯驹 黄. All rights reserved.
//
import UIKit
protocol QDSingleImagePickerPreviewViewControllerDelegate: QMUIImagePickerPreviewViewControllerDelegate {
func imagePickerPreviewViewController(_ imagePickerPreviewViewController: QDSingleImagePickerPreviewViewController, didSelectImageWithImagesAsset imagesAsset: QMUIAsset)
}
class QDSingleImagePickerPreviewViewController: QMUIImagePickerPreviewViewController {
weak var singleDelegate: QDSingleImagePickerPreviewViewControllerDelegate? {
get {
return delegate as? QDSingleImagePickerPreviewViewControllerDelegate
}
set {
delegate = newValue
}
}
var assetsGroup: QMUIAssetsGroup?
private var confirmButton: QMUIButton!
override func initSubviews() {
super.initSubviews()
confirmButton = QMUIButton()
confirmButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6)
confirmButton.setTitle("使用", for: .normal)
confirmButton.setTitleColor(toolBarTintColor, for: .normal)
confirmButton.sizeToFit()
confirmButton.addTarget(self, action: #selector(handleUserAvatarButtonClick(_:)), for: .touchUpInside)
topToolBarView.addSubview(confirmButton)
}
override var downloadStatus: QMUIAssetDownloadStatus {
didSet {
switch downloadStatus {
case .succeed:
confirmButton.isHidden = false
case .downloading:
confirmButton.isHidden = true
case .canceled:
confirmButton.isHidden = false
case .failed:
confirmButton.isHidden = true
}
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
confirmButton.frame = confirmButton.frame.setXY(topToolBarView.frame.width - confirmButton.frame.width - 10, backButton.frame.minY + backButton.frame.height.center(confirmButton.frame.height))
}
@objc private func handleUserAvatarButtonClick(_ sender: Any) {
navigationController?.dismiss(animated: true, completion: {
if let imagePreviewView = self.imagePreviewView {
let imageAsset = self.imagesAssetArray[imagePreviewView.currentImageIndex]
self.singleDelegate?.imagePickerPreviewViewController(self, didSelectImageWithImagesAsset: imageAsset)
}
})
}
}
| b6bf613894647d38ab33730036d1211b | 34.821918 | 200 | 0.677247 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Classes/Issues/Comments/IssueCollapsedBodies.swift | mit | 1 | //
// IssueCollapsedBodies.swift
// Freetime
//
// Created by Ryan Nystrom on 6/1/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
private func bodyIsCollapsible(body: Any) -> Bool {
if body is IssueCommentHrModel,
body is IssueCommentHtmlModel {
return false
} else {
return true
}
}
func IssueCollapsedBodies(bodies: [AnyObject], width: CGFloat) -> (AnyObject, CGFloat)? {
let cap: CGFloat = 300
// minimum height to collapse so expanding shows significant amount of content
let minDelta = IssueCommentBaseCell.collapseCellMinHeight * 3
var totalHeight: CGFloat = 0
for body in bodies {
let height = BodyHeightForComment(
viewModel: body,
width: width,
webviewCache: nil,
imageCache: nil
)
totalHeight += height
if bodyIsCollapsible(body: body),
totalHeight > cap,
totalHeight - cap > minDelta {
let collapsedBodyHeight = max(cap - (totalHeight - height), IssueCommentBaseCell.collapseCellMinHeight)
return (body, collapsedBodyHeight)
}
}
return nil
}
| c801019cbe47d1987e4ba44525e056e6 | 27.285714 | 115 | 0.632155 | false | false | false | false |
GalinaCode/Nutriction-Cal | refs/heads/master | NutritionCal/Nutrition Cal/NDBConvenience.swift | apache-2.0 | 1 | //
// NDBConvenience.swift
// Nutrition Cal
//
// Created by Galina Petrova on 03/25/16.
// Copyright © 2015 Galina Petrova. All rights reserved.
//
// United States Department of Agriculture
// Agricultural Research Service
// National Nutrient Database for Standard Reference Release 28
// visit to: http://ndb.nal.usda.gov/ndb/doc/index for documentation and help
import Foundation
import CoreData
extension NDBClient {
func NDBItemsFromString(searchString: String, type: NDBSearchType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) {
let escapedSearchString = searchString.stringByReplacingOccurrencesOfString(" ", withString: "+").stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!.lowercaseString
var searchType: String {
switch type {
case .ByFoodName: return "n"
case .ByRelevance: return "r"
}
}
let params: [String : AnyObject] = [
NDBParameterKeys.format : NDBParameterValues.json,
NDBParameterKeys.searchTerm : escapedSearchString,
NDBParameterKeys.sort : searchType,
NDBParameterKeys.limit : NDBConstants.resultsLimit,
NDBParameterKeys.offset : 0,
NDBParameterKeys.apiKey : NDBConstants.apiKey
]
let urlString = NDBConstants.baseURL + NDBMethods.search + NDBClient.escapedParameters(params)
let request = NSURLRequest(URL: NSURL(string: urlString)!)
print(request.URL!)
let session = NSURLSession.sharedSession()
sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
var parsedResults: AnyObject?
NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("Error parsing JSON: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
parsedResults = result
})
if let errors = parsedResults?.valueForKey("errors") {
if let error = errors.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message.firstObject as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
}
if let error = parsedResults!.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
guard let list = parsedResults?.valueForKey("list") as? [String: AnyObject] else {
print("Couldn't find list in: \(parsedResults)")
completionHandler(success: false, result: nil, errorString: "Couldn't find list in parsedResults")
return
}
guard let items = list["item"] as? NSArray else {
print("Couldn't find item in: \(list)")
completionHandler(success: false, result: nil, errorString: "Couldn't find item in list")
return
}
completionHandler(success: true, result: items, errorString: nil)
}
sharedTask!.resume()
}
func NDBReportForItem(ndbNo: String, type: NDBReportType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) {
var reportType: String {
switch type {
case .Basic: return "b"
case .Full: return "f"
}
}
let params: [String : AnyObject] = [
NDBParameterKeys.format : NDBParameterValues.json,
NDBParameterKeys.NDBNo : ndbNo,
NDBParameterKeys.reportType : reportType,
NDBParameterKeys.apiKey : NDBConstants.apiKey
]
let urlString = NDBConstants.baseURL + NDBMethods.reports + NDBClient.escapedParameters(params)
let request = NSURLRequest(URL: NSURL(string: urlString)!)
print(request.URL!)
let session = NSURLSession.sharedSession()
sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
var parsedResults: AnyObject?
NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("Error parsing JSON: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
parsedResults = result
})
if let errors = parsedResults?.valueForKey("errors") {
if let error = errors.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message.firstObject as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
completionHandler(success: false, result: nil, errorString: nil)
return
}
if let error = parsedResults?.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
guard let report = parsedResults?.valueForKey("report") as? [String: AnyObject] else {
print("Error finding report")
completionHandler(success: false, result: nil, errorString: "Error finding report")
return
}
guard let food = report["food"] as? [String: AnyObject] else {
print("Error finding food")
completionHandler(success: false, result: nil, errorString: "Error finding food")
return
}
guard let nutrients = food["nutrients"] as? NSArray else {
print("Error finding nutrients")
completionHandler(success: false, result: nil, errorString: "Error finding nutrients")
return
}
completionHandler(success: true, result: nutrients, errorString: nil)
}
sharedTask!.resume()
}
}
| 9e94b2bb22026270057e087114031b38 | 30.950739 | 213 | 0.689485 | false | false | false | false |
Codigami/CFAlertViewController | refs/heads/master | CFAlertViewController/Transitions/Popup/CFAlertPopupTransition.swift | mit | 1 | //
// CFAlertPopupTransition.swift
// CFAlertViewControllerDemo
//
// Created by Shivam Bhalla on 1/20/17.
// Copyright © 2017 Codigami Inc. All rights reserved.
//
import UIKit
class CFAlertPopupTransition: NSObject {
// MARK: - Declarations
@objc public enum CFAlertPopupTransitionType : Int {
case present = 0
case dismiss
}
// MARK: - Variables
// MARK: Public
public var transitionType = CFAlertPopupTransitionType(rawValue: 0)
// MARK: - Initialisation Methods
public override init() {
super.init()
// Default Transition Type
transitionType = CFAlertPopupTransitionType(rawValue: 0)
}
}
// MARK: - UIViewControllerTransitioningDelegate
extension CFAlertPopupTransition: UIViewControllerTransitioningDelegate {
public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitionType = .present
return self
}
public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
transitionType = .dismiss
return self
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension CFAlertPopupTransition: UIViewControllerAnimatedTransitioning {
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.4
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
// Get context vars
let duration: TimeInterval = transitionDuration(using: transitionContext)
let containerView: UIView? = transitionContext.containerView
let fromViewController: UIViewController? = transitionContext.viewController(forKey: .from)
let toViewController: UIViewController? = transitionContext.viewController(forKey: .to)
// Call Will System Methods
fromViewController?.beginAppearanceTransition(false, animated: true)
toViewController?.beginAppearanceTransition(true, animated: true)
if transitionType == .present {
/** SHOW ANIMATION **/
if let alertViewController = toViewController as? CFAlertViewController, let containerView = containerView {
alertViewController.containerView?.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
alertViewController.view?.frame = containerView.frame
alertViewController.view?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
alertViewController.view?.translatesAutoresizingMaskIntoConstraints = true
containerView.addSubview(alertViewController.view)
alertViewController.view?.layoutIfNeeded()
// Hide Container View
alertViewController.containerView?.alpha = 0.0
// Background
if alertViewController.backgroundStyle == .blur {
alertViewController.backgroundBlurView?.alpha = 0.0
}
alertViewController.backgroundColorView?.alpha = 0.0
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .allowUserInteraction, .beginFromCurrentState], animations: {() -> Void in
// Background
if alertViewController.backgroundStyle == .blur {
alertViewController.backgroundBlurView?.alpha = 1.0
}
alertViewController.backgroundColorView?.alpha = 1.0
}, completion: nil)
// Animate height changes
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 14.0, options: [.curveEaseIn, .allowUserInteraction, .beginFromCurrentState], animations: {() -> Void in
alertViewController.containerView?.transform = CGAffineTransform.identity
alertViewController.containerView?.alpha = 1.0
}, completion: {(_ finished: Bool) -> Void in
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
else {
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
else if transitionType == .dismiss {
/** HIDE ANIMATION **/
let alertViewController: CFAlertViewController? = (fromViewController as? CFAlertViewController)
// Animate height changes
UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseOut, .beginFromCurrentState], animations: {() -> Void in
alertViewController?.containerView?.transform = CGAffineTransform(scaleX: 0.94, y: 0.94)
alertViewController?.containerView?.alpha = 0.0
// Background
if alertViewController?.backgroundStyle == .blur {
alertViewController?.backgroundBlurView?.alpha = 0.0
}
alertViewController?.backgroundColorView?.alpha = 0.0
}, completion: {(_ finished: Bool) -> Void in
// Call Did System Methods
toViewController?.endAppearanceTransition()
fromViewController?.endAppearanceTransition()
// Declare Animation Finished
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
})
}
}
}
| fad02bbb9b82dce382bc4bad1e21a967 | 42.045455 | 223 | 0.609896 | false | false | false | false |
KitmanLabs/XLForm | refs/heads/master | Examples/Swift/Examples/CustomRows/Weekdays/XLFormWeekDaysCell.swift | mit | 14 | // XLFormWeekDaysCell.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
let XLFormRowDescriptorTypeWeekDays = "XLFormRowDescriptorTypeWeekDays"
class XLFormWeekDaysCell : XLFormBaseCell {
enum kWeekDay: Int {
case
Sunday = 1,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
func description() -> String {
switch self {
case .Sunday:
return "Sunday"
case .Monday:
return "Monday"
case .Tuesday:
return "Tuesday"
case .Wednesday:
return "Wednesday"
case .Thursday:
return "Thursday"
case .Friday:
return "Friday"
case .Saturday:
return "Saturday"
}
}
//Add Custom Functions
//Allows for iteration as needed (for in ...)
static let allValues = [Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday]
}
@IBOutlet weak var sundayButton: UIButton!
@IBOutlet weak var mondayButton: UIButton!
@IBOutlet weak var tuesdayButton: UIButton!
@IBOutlet weak var wednesdayButton: UIButton!
@IBOutlet weak var thursdayButton: UIButton!
@IBOutlet weak var fridayButton: UIButton!
@IBOutlet weak var saturdayButton: UIButton!
//MARK: - XLFormDescriptorCell
override func configure() {
super.configure()
selectionStyle = .None
configureButtons()
}
override func update() {
super.update()
updateButtons()
}
override static func formDescriptorCellHeightForRowDescriptor(rowDescriptor: XLFormRowDescriptor!) -> CGFloat {
return 60
}
//MARK: - Action
@IBAction func dayTapped(sender: UIButton) {
let day = getDayFormButton(sender)
sender.selected = !sender.selected
var newValue = rowDescriptor!.value as! Dictionary<String, Bool>
newValue[day] = sender.selected
rowDescriptor!.value = newValue
}
//MARK: - Helpers
func configureButtons() {
for subview in contentView.subviews {
if let button = subview as? UIButton {
button.setImage(UIImage(named: "uncheckedDay"), forState: .Normal)
button.setImage(UIImage(named: "checkedDay"), forState: .Selected)
button.adjustsImageWhenHighlighted = false
imageTopTitleBottom(button)
}
}
}
func updateButtons() {
var value = rowDescriptor!.value as! Dictionary<String, Bool>
sundayButton.selected = value[kWeekDay.Sunday.description()]!
mondayButton.selected = value[kWeekDay.Monday.description()]!
tuesdayButton.selected = value[kWeekDay.Tuesday.description()]!
wednesdayButton.selected = value[kWeekDay.Wednesday.description()]!
thursdayButton.selected = value[kWeekDay.Thursday.description()]!
fridayButton.selected = value[kWeekDay.Friday.description()]!
saturdayButton.selected = value[kWeekDay.Saturday.description()]!
sundayButton.alpha = rowDescriptor!.isDisabled() ? 0.6 : 1
mondayButton.alpha = mondayButton.alpha
tuesdayButton.alpha = mondayButton.alpha
wednesdayButton.alpha = mondayButton.alpha
thursdayButton.alpha = mondayButton.alpha
fridayButton.alpha = mondayButton.alpha
saturdayButton.alpha = mondayButton.alpha
}
func imageTopTitleBottom(button: UIButton) {
// the space between the image and text
let spacing : CGFloat = 3.0
// lower the text and push it left so it appears centered
// below the image
let imageSize : CGSize = button.imageView!.image!.size
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: -imageSize.width, bottom: -(imageSize.height + spacing), right: 0.0)
// raise the image and push it right so it appears centered
// above the text
let titleSize : CGSize = (button.titleLabel!.text! as NSString).sizeWithAttributes([NSFontAttributeName: button.titleLabel!.font])
button.imageEdgeInsets = UIEdgeInsetsMake(-(titleSize.height + spacing), 0.0, 0.0, -titleSize.width)
}
func getDayFormButton(button: UIButton) -> String {
switch button {
case sundayButton:
return kWeekDay.Sunday.description()
case mondayButton:
return kWeekDay.Monday.description()
case tuesdayButton:
return kWeekDay.Tuesday.description()
case wednesdayButton:
return kWeekDay.Wednesday.description()
case thursdayButton:
return kWeekDay.Thursday.description()
case fridayButton:
return kWeekDay.Friday.description()
default:
return kWeekDay.Saturday.description()
}
}
}
| 203d388aa7ad97e035370acdaceaed6d | 34.960452 | 138 | 0.621838 | false | false | false | false |
EdenShapiro/tip-calculator-with-yelp-review | refs/heads/master | SuperCoolTipCalculator/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// SuperCoolTipCalculator
//
// Created by Eden on 2/3/17.
// Copyright © 2017 Eden Shapiro. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
@IBOutlet weak var picker1: UIPickerView!
@IBOutlet weak var picker2: UIPickerView!
@IBOutlet weak var picker3: UIPickerView!
var pickerData = [Int]()
let defaults = UserDefaults.standard
var tipPercentages: [Double]!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
tipPercentages = defaults.object(forKey: "tipPercentages") as! [Double]
pickerData += 1...100
picker1.dataSource = self
picker1.delegate = self
picker1.tag = 1
picker2.dataSource = self
picker2.delegate = self
picker2.tag = 2
picker3.dataSource = self
picker3.delegate = self
picker3.tag = 3
picker1.selectRow(Int(tipPercentages[0]*100)-1, inComponent: 0, animated: true)
picker2.selectRow(Int(tipPercentages[1]*100)-1, inComponent: 0, animated: true)
picker3.selectRow(Int(tipPercentages[2]*100)-1, inComponent: 0, animated: true)
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return pickerData.count
}
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let attributedString = NSAttributedString(string: String(pickerData[row]), attributes: [NSForegroundColorAttributeName : UIColor.lightGray])
return attributedString
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
tipPercentages[pickerView.tag - 1] = Double(pickerData[row])/100.0
defaults.set(tipPercentages, forKey: "tipPercentages")
defaults.synchronize()
}
}
| 05137c898c8364ee969ef35c9c0647eb | 33.238095 | 148 | 0.672694 | false | false | false | false |
frograin/FluidValidator | refs/heads/master | Example/Tests/ValidationTests.swift | mit | 1 | //
// TestValidatorTests.swift
// TestValidatorTests
//
// Created by FrogRain on 05/02/16.
// Copyright © 2016 FrogRain. All rights reserved.
//
import XCTest
import FluidValidator
class ValidationTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testValidation() {
let validation = Validation(name: "isTrue") { (context:Example) -> (Any?) in
return context.isTrue
}
let rule = BeNotNil()
validation.addRule(rule)
let example = Example()
let result = validation.runValidation(example)
let failMessage = validation.allErrors
XCTAssertFalse(result)
XCTAssertTrue(failMessage.errors.count > 0)
}
func testConditionalValidation() {
let validation = Validation(name: "test") { (context:Example) -> (Any?) in
return context.testProperty
}
validation.when { (context) -> (Bool) in
return context.number == 0
}
validation.addRule(BeNotEmpty())
let example = Example()
example.number = 5
example.testProperty = "" // It's empty!
let result = validation.runValidation(example)
XCTAssertTrue(result)
}
}
| eafbfd7e4ea8e42fa28928ca85aeda50 | 26.016667 | 111 | 0.586058 | false | true | false | false |
num42/RxUserDefaults | refs/heads/master | Examples/Sources/ViewController.swift | apache-2.0 | 1 | import UIKit
import RxUserDefaults
import RxSwift
class ViewController: UIViewController {
let settings: RxSettings
let reactiveSetting: Setting<String>
var disposeBag = DisposeBag()
lazy var valueLabel: UILabel = {
let valueLabel = UILabel()
valueLabel.textColor = .blue
return valueLabel
}()
lazy var textField: UITextField = {
let textField = UITextField()
textField.backgroundColor = .white
textField.borderStyle = .line
textField.text = "Enter new value here"
textField.textColor = .black
return textField
}()
lazy var saveButton: UIButton = {
let saveButton = UIButton()
saveButton.setTitle("Save", for: .normal)
saveButton.setTitleColor(.blue, for: .normal)
saveButton.setTitleColor(.lightGray, for: .highlighted)
return saveButton
}()
init() {
settings = RxSettings(userDefaults: UserDefaults.standard)
reactiveSetting = settings.setting(key: "the_settings_key", defaultValue: "The Default Value")
super.init(nibName: nil, bundle: nil)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
fatalError("init(nibNameOrNil:nibBundleOrNil:) has not been implemented")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupView()
setupRxSettingsBinding()
}
private func setupView() {
view.backgroundColor = .white
let stackView = UIStackView()
stackView.axis = .vertical
stackView.addArrangedSubview(textField)
stackView.addArrangedSubview(saveButton)
stackView.addArrangedSubview(UIView())
stackView.addArrangedSubview(valueLabel)
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
stackView.widthAnchor.constraint(equalToConstant: 250).isActive = true
stackView.heightAnchor.constraint(equalToConstant: 250).isActive = true
}
private func setupRxSettingsBinding(){
// Setup Saving to Settings
saveButton.rx.tap
.subscribe(onNext:
{ [weak self] _ in
guard let text = self?.textField.text else {
self?.reactiveSetting.remove()
return
}
self?.reactiveSetting.value = text
}
)
.disposed(by: disposeBag)
// Setup Displaying value when settings change
reactiveSetting.asObservable()
.asDriver(onErrorJustReturn: "Error")
.drive(valueLabel.rx.text)
.disposed(by: disposeBag)
}
}
| 48c6e7a3b74b6e810d7c01dd9a4ec3ab | 31.247423 | 102 | 0.611573 | false | false | false | false |
el-hoshino/NotAutoLayout | refs/heads/master | Playground.playground/Contents.swift | apache-2.0 | 1 | //: Playground - noun: a place where people can play
import PlaygroundSupport
import NotAutoLayout
let controller = IPhoneXScreenController()
controller.rotate(to: .portrait)
PlaygroundPage.current.liveView = controller.view
let appView = LayoutInfoStoredView()
appView.backgroundColor = .white
controller.view.addSubview(appView)
controller.view.nal.layout(appView) { $0
.stickOnParent()
}
let padding: NotAutoLayout.Float = 10
let summaryView = ProfileSummaryView()
let contentsView = ContentsView()
let replyView = ReplyView()
summaryView.avatar = #imageLiteral(resourceName: "avatar.png")
summaryView.mainTitle = "星野恵瑠@今日も1日フレンズ㌠"
summaryView.subTitle = "@lovee"
contentsView.contents = """
Hello, NotAutoLayout!
The new NotAutoLayout 3.0 now has even better syntax which is:
- Easy to write (thanks to method-chain structures)
- Easy to read (thanks to more natural English-like statements)
- Capable with dynamic view sizes (with commands like `fitSize()`)
- Even better closure support to help you set various kinds of layouts with various kinds of properties!
- And one more thing: an experienmental sequencial layout engine!
"""
contentsView.timeStamp = Date()
appView.nal.setupSubview(summaryView) { $0
.setDefaultLayout { $0
.setLeft(by: { $0.layoutMarginsGuide.left })
.setRight(by: { $0.layoutMarginsGuide.right })
.setTop(by: { $0.layoutMarginsGuide.top })
.setHeight(to: 50)
}
.addToParent()
}
appView.nal.setupSubview(contentsView) { $0
.setDefaultLayout({ $0
.setLeft(by: { $0.layoutMarginsGuide.left })
.setRight(by: { $0.layoutMarginsGuide.right })
.pinTop(to: summaryView, with: { $0.bottom + padding })
.fitHeight()
})
.setDefaultOrder(to: 1)
.addToParent()
}
appView.nal.setupSubview(replyView) { $0
.setDefaultLayout({ $0
.setBottomLeft(by: { $0.layoutMarginsGuide.bottomLeft })
.setRight(by: { $0.layoutMarginsGuide.right })
.setHeight(to: 30)
})
.addToParent()
}
let imageViews = (0 ..< 3).map { (_) -> UIImageView in
let image = #imageLiteral(resourceName: "avatar.png")
let view = UIImageView(image: image)
appView.addSubview(view)
return view
}
appView.nal.layout(imageViews) { $0
.setMiddle(by: { $0.vertical(at: 0.7) })
.fitSize()
.setHorizontalInsetsEqualingToMargin()
}
| 3a475339e7833a968f34d790499c3db7 | 28.723684 | 105 | 0.736609 | false | false | false | false |
pabloroca/PR2StudioSwift | refs/heads/master | Source/Networking/AuthorizationJWT.swift | mit | 1 | //
// AuthorizationJWT.swift
// PR2StudioSwift
//
// Created by Pablo Roca on 28/02/2019.
// Copyright © 2019 PR2Studio. All rights reserved.
//
import Foundation
public final class AuthorizationJWT: Authorization {
public private(set) var authEndPoint: String
public private(set) var parameters: [String: String]
public init(authEndPoint: String, parameters: [String: String]) {
self.authEndPoint = authEndPoint
self.parameters = parameters
}
public func loadCredentials() -> String {
return KeyChainService.load(withKey: "jwt") ?? ""
}
public func authorize(completionHandler: @escaping (Result<Any, AnyError>) -> Void) {
let requestOptional = URLRequest(authEndPoint, method: .post, parameters: parameters, encoding: .json)
guard let request = requestOptional else {
completionHandler(.failure(AnyError(
NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed))))
return
}
NetworkSession.shared.dataTask(request, parserType: .data, toType: String.self, authorization: nil) { (result) in
if case let .success(value) = result {
guard let token = value as? String else {
completionHandler(.failure(AnyError(
NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed))))
return
}
if !KeyChainService.save(token, forKey: "jwt") {
completionHandler(.failure(AnyError(
NetworkingError.authorizationError(underlyingError: .authorizationHandlingFailed))))
} else {
completionHandler(result)
}
} else {
completionHandler(result)
}
}
}
}
| 83d72a6c8477f3921ccec73a23d82cdc | 35.269231 | 121 | 0.613998 | false | false | false | false |
FelixMLians/NVActivityIndicatorView | refs/heads/master | NVActivityIndicatorView/NVActivityIndicatorView.swift | mit | 22 | //
// NVActivityIndicatorView.swift
// NVActivityIndicatorViewDemo
//
// Created by Nguyen Vinh on 7/21/15.
// Copyright (c) 2015 Nguyen Vinh. All rights reserved.
//
import UIKit
enum NVActivityIndicatorType {
case Blank
case BallPulse
case BallGridPulse
case BallClipRotate
case SquareSpin
case BallClipRotatePulse
case BallClipRotateMultiple
case BallPulseRise
case BallRotate
case CubeTransition
case BallZigZag
case BallZigZagDeflect
case BallTrianglePath
case BallScale
case LineScale
case LineScaleParty
case BallScaleMultiple
case BallPulseSync
case BallBeat
case LineScalePulseOut
case LineScalePulseOutRapid
case BallScaleRipple
case BallScaleRippleMultiple
case BallSpinFadeLoader
case LineSpinFadeLoader
case TriangleSkewSpin
case Pacman
case BallGridBeat
case SemiCircleSpin
}
class NVActivityIndicatorView: UIView {
private let DEFAULT_TYPE: NVActivityIndicatorType = .Blank
private let DEFAULT_COLOR = UIColor.whiteColor()
private let DEFAULT_SIZE: CGSize = CGSize(width: 40, height: 40)
private var type: NVActivityIndicatorType
private var color: UIColor
private var size: CGSize
var animating: Bool = false
required init(coder aDecoder: NSCoder) {
self.type = DEFAULT_TYPE
self.color = DEFAULT_COLOR
self.size = DEFAULT_SIZE
super.init(coder: aDecoder);
}
init(frame: CGRect, type: NVActivityIndicatorType, color: UIColor?, size: CGSize?) {
self.type = type
self.color = DEFAULT_COLOR
self.size = DEFAULT_SIZE
super.init(frame: frame)
if let _color = color {
self.color = _color
}
if let _size = size {
self.size = _size
}
}
convenience init(frame: CGRect, type: NVActivityIndicatorType, color: UIColor?) {
self.init(frame: frame, type: type, color: color, size: nil)
}
convenience init(frame: CGRect, type: NVActivityIndicatorType) {
self.init(frame: frame, type: type, color: nil)
}
func startAnimation() {
if (self.layer.sublayers == nil) {
setUpAnimation()
}
self.layer.speed = 1
self.animating = true
}
func stopAnimation() {
self.layer.speed = 0
self.animating = false
}
private func setUpAnimation() {
let animation: protocol<NVActivityIndicatorAnimationDelegate> = animationOfType(self.type)
self.layer.sublayers = nil
animation.setUpAnimationInLayer(self.layer, size: self.size, color: self.color)
}
private func animationOfType(type: NVActivityIndicatorType) -> protocol<NVActivityIndicatorAnimationDelegate> {
switch type {
case .Blank:
return NVActivityIndicatorAnimationBlank()
case .BallPulse:
return NVActivityIndicatorAnimationBallPulse()
case .BallGridPulse:
return NVActivityIndicatorAnimationBallGridPulse()
case .BallClipRotate:
return NVActivityIndicatorAnimationBallClipRotate()
case .SquareSpin:
return NVActivityIndicatorAnimationSquareSpin()
case .BallClipRotatePulse:
return NVActivityIndicatorAnimationBallClipRotatePulse()
case .BallClipRotateMultiple:
return NVActivityIndicatorAnimationBallClipRotateMultiple()
case .BallPulseRise:
return NVActivityIndicatorAnimationBallPulseRise()
case .BallRotate:
return NVActivityIndicatorAnimationBallRotate()
case .CubeTransition:
return NVActivityIndicatorAnimationCubeTransition()
case .BallZigZag:
return NVActivityIndicatorAnimationBallZigZag()
case .BallZigZagDeflect:
return NVActivityIndicatorAnimationBallZigZagDeflect()
case .BallTrianglePath:
return NVActivityIndicatorAnimationBallTrianglePath()
case .BallScale:
return NVActivityIndicatorAnimationBallScale()
case .LineScale:
return NVActivityIndicatorAnimationLineScale()
case .LineScaleParty:
return NVActivityIndicatorAnimationLineScaleParty()
case .BallScaleMultiple:
return NVActivityIndicatorAnimationBallScaleMultiple()
case .BallPulseSync:
return NVActivityIndicatorAnimationBallPulseSync()
case .BallBeat:
return NVActivityIndicatorAnimationBallBeat()
case .LineScalePulseOut:
return NVActivityIndicatorAnimationLineScalePulseOut()
case .LineScalePulseOutRapid:
return NVActivityIndicatorAnimationLineScalePulseOutRapid()
case .BallScaleRipple:
return NVActivityIndicatorAnimationBallScaleRipple()
case .BallScaleRippleMultiple:
return NVActivityIndicatorAnimationBallScaleRippleMultiple()
case .BallSpinFadeLoader:
return NVActivityIndicatorAnimationBallSpinFadeLoader()
case .LineSpinFadeLoader:
return NVActivityIndicatorAnimationLineSpinFadeLoader()
case .TriangleSkewSpin:
return NVActivityIndicatorAnimationTriangleSkewSpin()
case .Pacman:
return NVActivityIndicatorAnimationPacman()
case .BallGridBeat:
return NVActivityIndicatorAnimationBallGridBeat()
case .SemiCircleSpin:
return NVActivityIndicatorAnimationSemiCircleSpin()
}
}
}
| 4e4e0fc876c762e50370ab3b8f40e63d | 32.927273 | 115 | 0.67667 | false | false | false | false |
mseemann/D2Layers | refs/heads/master | Example/D2Layers/ViewController.swift | mit | 1 | //
// ViewController.swift
// TestGraphics
//
// Created by Michael Seemann on 04.11.15.
// Copyright © 2015 Michael Seemann. All rights reserved.
//
import UIKit
import D2Layers
class D2LayerView: UIView {
var root: Graph?
override init(frame: CGRect) {
super.init(frame: frame)
rootInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
rootInit()
}
func rootInit() {
root = Graph(layer: self.layer, parent: nil)
// self.layer.shadowRadius = 10.0
// self.layer.shadowOffset = CGSize(width: 0, height: 0)
// self.layer.shadowColor = UIColor.grayColor().CGColor
// self.layer.masksToBounds = false
// self.layer.shadowOpacity = 1.0
}
override func layoutSubviews() {
root?.needsLayout()
}
}
class ViewController: UIViewController {
@IBOutlet weak var vPieChart: D2LayerView!
var switcher = false
var pieLayout:PieLayout?
var normalizedValues : [Double] = []
let colorScale = OrdinalScale<Int, UIColor>.category20c()
var count = 5
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let root = vPieChart.root {
let circle = root.circle{
(parentGraph: Graph) in
let parentSize = parentGraph.layer.bounds.size
let at = CGPoint(x: parentSize.width/2, y: parentSize.height/2)
let r = min(parentSize.width, parentSize.height)/CGFloat(2.0)
return (at:at, r:r)
}.fillColor(UIColor.grayColor().brighter())
pieLayout = circle.pieLayout{
(parentGraph: Graph) in
let outerRadius = (min(parentGraph.layer.bounds.width, parentGraph.layer.bounds.height)/2) - 1
return (innerRadius:outerRadius*0.75, outerRadius:outerRadius, startAngle:CGFloat(0), endAngle:CGFloat(2*M_PI))
}
.data(updateSlices()){
(pieSlice:PieSlice, normalizedValue:Double, index:Int) in
pieSlice.fillColor(self.colorScale.scale(index)!.brighter())
pieSlice.strokeColor(UIColor(white: 0.25, alpha: 1.0))
pieSlice.strokeWidth(0.25)
}
}
}
@IBAction func doit(sender: AnyObject) {
if let pieLayout = pieLayout {
pieLayout.data(updateSlices())
let scale = (1.0 - CGFloat(arc4random_uniform(128))/255.0)
let selection = pieLayout.selectAll(PieSlice.self)
for g in selection.all() {
g.innerRadius(scale * g.outerRadius())
}
}
}
internal func updateSlices() -> [Double]{
var sliceValues:[Double] = []
for(var i=0; i < count; i++) {
sliceValues.append(Double(arc4random_uniform(100)))
}
return sliceValues
}
}
| a3d6f0ee7787232d956ff325671a8d5e | 26.627119 | 131 | 0.528221 | false | false | false | false |
lingostar/PilotPlant | refs/heads/master | PilotPlant/CHViews.swift | agpl-3.0 | 1 | //
// CHViews.swift
// PilotPlantCatalog
//
// Created by Lingostar on 2017. 5. 2..
// Copyright © 2017년 LingoStar. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class AnimationImageView:UIImageView {
@IBInspectable open var imageBaseName:String = ""
@IBInspectable open var duration:Double = 1.0
@IBInspectable open var repeatCount:Int = 0
open override func awakeFromNib() {
super.awakeFromNib()
var images = [UIImage]()
for i in 1 ..< 32000
{
let imageFileName = self.imageBaseName + "_\(i)"
if let image = UIImage(named: imageFileName) {
images.append(image)
} else { break }
}
self.animationImages = images
self.contentMode = .scaleAspectFit
self.animationRepeatCount = self.repeatCount
self.animationDuration = duration
self.image = images.first
self.startAnimating()
}
}
| 42cf198edb938cd7c63c5d50d0bfca18 | 25.421053 | 60 | 0.60757 | false | false | false | false |
taqun/HBR | refs/heads/master | HBR/Classes/ViewController/FeedTableViewController.swift | mit | 1 | //
// FeedTableViewController.swift
// HBR
//
// Created by taqun on 2014/09/12.
// Copyright (c) 2014年 envoixapp. All rights reserved.
//
import UIKit
import CoreData
class FeedTableViewController: SegmentedDisplayTableViewController, NSFetchedResultsControllerDelegate {
var channel: Channel!
private var fetchedResultController: NSFetchedResultsController!
/*
* Initialize
*/
convenience init(channel: Channel) {
self.init(style: UITableViewStyle.Plain)
self.channel = channel
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(style: UITableViewStyle) {
super.init(style: style)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
// navigation bar
let backBtn = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.backBarButtonItem = backBtn
let checkBtn = UIBarButtonItem(image: UIImage(named: "IconCheckmark"), style: UIBarButtonItemStyle.Plain, target: self, action: Selector("didCheckmark"))
self.navigationItem.rightBarButtonItem = checkBtn
// tableview
self.clearsSelectionOnViewWillAppear = true
self.tableView.separatorInset = UIEdgeInsetsZero
self.tableView.registerNib(UINib(nibName: "FeedTableViewCell", bundle: nil), forCellReuseIdentifier: "FeedCell")
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: Selector("didRefreshControlChanged"), forControlEvents: UIControlEvents.ValueChanged)
NSFetchedResultsController.deleteCacheWithName(self.channel.title + "Cache")
self.initFetchedResultsController()
var error:NSError?
if !self.fetchedResultController.performFetch(&error) {
println(error)
}
}
/*
* Private Method
*/
private func initFetchedResultsController() {
if self.fetchedResultController != nil{
return
}
var fetchRequest = Item.requestAllSortBy("date", ascending: false)
fetchRequest.predicate = NSPredicate(format: "ANY channels = %@", self.channel)
let context = CoreDataManager.sharedInstance.managedObjectContext!
self.fetchedResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: self.channel.title + "Cache")
self.fetchedResultController.delegate = self
}
@objc private func feedLoaded(notification: NSNotification){
if let userInfo = notification.userInfo {
if let channelID = userInfo["channelID"] as? NSManagedObjectID {
if self.channel.objectID != channelID {
return
}
}
}
allItemNum = channel.items.count
self.tableView.reloadData()
self.updateTitle()
self.refreshControl?.endRefreshing()
}
@objc private func didRefreshControlChanged() {
FeedController.sharedInstance.loadFeed(channel.objectID)
}
@objc private func didCheckmark() {
channel.markAsReadAllItems()
self.updateTitle()
self.updateVisibleCells()
}
private func updateVisibleCells() {
var cells = self.tableView.visibleCells() as! [FeedTableViewCell]
for cell: FeedTableViewCell in cells {
cell.updateView()
}
}
private func updateTitle() {
let unreadCount = channel.unreadItemCount
if unreadCount == 0 {
self.title = channel.title
} else {
self.title = channel.title + " (" + String(unreadCount) + ")"
}
}
/*
* UIViewController Method
*/
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// navigationbar
self.updateTitle()
// toolbar
self.navigationController?.toolbarHidden = true
if let indexPath = self.tableView?.indexPathForSelectedRow() {
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// tableView
self.updateVisibleCells()
allItemNum = channel.items.count
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("feedLoaded:"), name: Notification.FEED_LOADED, object: nil)
Logger.sharedInstance.trackFeedList(self.channel)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/*
* UITableViewDataSoruce Protocol
*/
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("FeedCell") as! FeedTableViewCell!
if cell == nil {
cell = FeedTableViewCell()
}
let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item
cell.setFeedItem(item)
return cell
}
/*
* UITableViewDelegate Protocol
*/
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let item = self.fetchedResultController.objectAtIndexPath(indexPath) as! Item
let webViewController = WebViewController(item: item)
self.navigationController?.pushViewController(webViewController, animated: true)
}
/*
* NSFetchedResultsControllerDelegate Protocol
*/
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
| 48939b8ad0d4135636b97778439945cd | 30.203791 | 190 | 0.640644 | false | false | false | false |
imfree-jdcastro/Evrythng-iOS-SDK | refs/heads/master | Evrythng-iOS/EvrythngNetworkService.swift | apache-2.0 | 1 | //
// EvrythngNetworkService.swift
// EvrythngiOS
//
// Created by JD Castro on 26/04/2017.
// Copyright © 2017 ImFree. All rights reserved.
//
import Foundation
import Moya
import MoyaSugar
public enum EvrythngNetworkService {
case url(String)
// User
case createUser(user: User?, isAnonymous: Bool)
case deleteUser(operatorApiKey: String, userId: String)
case authenticateUser(credentials: Credentials)
case validateUser(userId: String, activationCode: String)
case logout(apiKey: String)
case editIssue(owner: String, repo: String, number: Int, title: String?, body: String?)
// Thng
case readThng(thngId: String)
// Scan
case identify(scanType: EvrythngScanTypes, scanMethod: EvrythngScanMethods, value: String)
}
extension EvrythngNetworkService: EvrythngNetworkTargetType {
public var sampleResponseClosure: (() -> EndpointSampleResponse) {
return {
return EndpointSampleResponse.networkResponse(200, self.sampleData)
}
}
public var baseURL: URL { return URL(string: "https://api.evrythng.com")! }
//public var baseURL: URL { return URL(string: "https://www.jsonblob.com/api")! }
/// method + path
public var route: Route {
switch self {
case .url(let urlString):
return .get(urlString)
case .createUser:
return .post("/auth/evrythng/users")
case .deleteUser(_, let userId):
return .delete("/users/\(userId)")
case .authenticateUser:
return .post("/auth/evrythng")
case .validateUser(let userId, _):
return .post("/users/\(userId)/validate")
case .logout:
return .post("/auth/all/logout")
case .editIssue(let owner, let repo, let number, _, _):
return .patch("/repos/\(owner)/\(repo)/issues/\(number)")
case .readThng(let thngId):
return .get("/thngs/\(thngId)")
case .identify:
return .get("/scan/identifications")
}
}
// override default url building behavior
public var url: URL {
switch self {
case .url(let urlString):
return URL(string: urlString)!
default:
return self.defaultURL
}
}
/// encoding + parameters
public var params: Parameters? {
switch self {
case .createUser(let user, let anonymous):
if(anonymous == true) {
var params:[String: Any] = [:]
params[EvrythngNetworkServiceConstants.REQUEST_URL_PARAMETER_KEY] = ["anonymous": "true"]
params[EvrythngNetworkServiceConstants.REQUEST_BODY_PARAMETER_KEY] = [:]
return CompositeEncoding() => params
} else {
return JSONEncoding() => user!.jsonData!.dictionaryObject!
}
/*
[
"firstName": "Test First1", "lastName": "Test Last1", "email": "[email protected]", "password": "testPassword1"
]
*/
case .validateUser(_, let activationCode):
return JSONEncoding() => ["activationCode": activationCode]
case .authenticateUser(let credentials):
return JSONEncoding() => ["email": credentials.email!, "password": credentials.password!]
case .logout:
return JSONEncoding() => [:]
case .identify(let scanType, let scanMethod, let value):
let urlEncodedFilter = "type=\(scanType.rawValue)&value=\(value)"
let encoding = URLEncoding() => ["filter": urlEncodedFilter]
print("Encoding: \(encoding.values.description)")
return encoding
case .editIssue(_, _, _, let title, let body):
// Use `URLEncoding()` as default when not specified
return [
"title": title,
"body": body,
]
default:
return JSONEncoding() => [:]
}
}
public var sampleData: Data {
switch self {
case .editIssue(_, let owner, _, _, _):
return "{\"id\": 100, \"owner\": \"\(owner)}".utf8Encoded
default:
return "{}".utf8Encoded
}
}
public var httpHeaderFields: [String: String]? {
var headers: [String:String] = [:]
headers[EvrythngNetworkServiceConstants.HTTP_HEADER_ACCEPTS] = "application/json"
headers[EvrythngNetworkServiceConstants.HTTP_HEADER_CONTENT_TYPE] = "application/json"
var authorization: String?
switch(self) {
case .deleteUser(let operatorApiKey, _):
// Operator API Key
//authorization = "hohzaKH7VbVp659Pnr5m3xg2DpKBivg9rFh6PttT5AnBtEn3s17B8OPAOpBjNTWdoRlosLTxJmUrpjTi"
authorization = operatorApiKey
case .logout(let apiKey):
authorization = apiKey
default:
authorization = UserDefaultsUtils.get(key: "pref_key_authorization") as? String
if let authorization = UserDefaultsUtils.get(key: "pref_key_authorization") as? String{
headers[EvrythngNetworkServiceConstants.HTTP_HEADER_AUTHORIZATION] = authorization
}
}
if let auth = authorization {
if(!auth.isEmpty) {
headers[EvrythngNetworkServiceConstants.HTTP_HEADER_AUTHORIZATION] = auth
}
}
print("Headers: \(headers)")
return headers
}
public var task: Task {
switch self {
case .editIssue, .createUser, .url:
fallthrough
default:
return .request
}
}
}
internal struct EvrythngNetworkServiceConstants {
static let AppToken = "evrythng_app_token"
static let EVRYTHNG_OPERATOR_API_KEY = "evrythng_operator_api_key"
static let EVRYTHNG_APP_API_KEY = "evrythng_app_api_key"
static let EVRYTHNG_APP_USER_API_KEY = "evrythng_app_user_api_key"
static let HTTP_HEADER_AUTHORIZATION = "Authorization"
static let HTTP_HEADER_ACCEPTS = "Accept"
static let HTTP_HEADER_CONTENT_TYPE = "Content-Type"
static let REQUEST_URL_PARAMETER_KEY = "query"
static let REQUEST_BODY_PARAMETER_KEY = "body"
}
// MARK: - Helpers
private extension String {
var urlEscaped: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var utf8Encoded: Data {
return self.data(using: .utf8)!
}
}
| e910340b83c9121db1e9897614290d43 | 32.851282 | 131 | 0.589759 | false | false | false | false |
tgu/HAP | refs/heads/master | Sources/HAP/Endpoints/root().swift | mit | 1 | import func Evergreen.getLogger
fileprivate let logger = getLogger("hap.endpoints")
typealias Route = (path: String, application: Application)
func root(device: Device) -> Application {
return logger(router([
// Unauthenticated endpoints
("/", { _, _ in Response(status: .ok,
text: "Nothing to see here. Pair this Homekit" +
"Accessory with an iOS device.") }),
("/pair-setup", pairSetup(device: device)),
("/pair-verify", pairVerify(device: device)),
// Authenticated endpoints
("/identify", protect(identify(device: device))),
("/accessories", protect(accessories(device: device))),
("/characteristics", protect(characteristics(device: device))),
("/pairings", protect(pairings(device: device)))
]))
}
func logger(_ application: @escaping Application) -> Application {
return { connection, request in
let response = application(connection, request)
// swiftlint:disable:next line_length
logger.info("\(connection.socket?.remoteHostname ?? "-") \(request.method) \(request.urlURL.path) \(request.urlURL.query ?? "-") \(response.status.rawValue) \(response.body?.count ?? 0)")
logger.debug("- Response Messagea: \(String(data: response.serialized(), encoding: .utf8) ?? "-")")
return response
}
}
func router(_ routes: [Route]) -> Application {
return { connection, request in
guard let route = routes.first(where: { $0.path == request.urlURL.path }) else {
return Response(status: .notFound)
}
return route.application(connection, request)
}
}
func protect(_ application: @escaping Application) -> Application {
return { connection, request in
guard connection.isAuthenticated else {
logger.warning("Unauthorized request to \(request.urlURL.path)")
return .forbidden
}
return application(connection, request)
}
}
| 17cc9f314bf031e145d10742fb110c2c | 40.265306 | 195 | 0.619683 | false | false | false | false |
ixx1232/swift-Tour | refs/heads/master | swiftTour/swiftTour/tour.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
/**
本页内容包括:
简单值(Simple Value)
控制流(control Flow)
函数和闭包(Functions and Closures)
对象和类(Objects and classes)
枚举和结构体(Enumerations and Structures)
协议和扩展(Protocols and Extensions)
错误处理(Error Handling)
泛型(Generics)
*/
print("Hello, world!")
/*
简单值
*/
var myVariable = 42
myVariable = 50
let myConstant = 42
let implicitInteger = 70
let implcitDouble = 70.0
let explictiDoublt: Double = 70
// EXPERIMENT: Create a constant with an explicit type of float and a value of 4
let explicitDouble: Double = 4
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
// EXPERIMENT: Try removing the conversion to string from the last line. What error do you get?
// binary operator '+' cannot be applied to operands of type 'String' and 'Int'
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
// EXPERMENT: Use \() to include a float-point calculation in a string and to include someone's name in a greeting.
let revenue: Float = 160.0
let cost: Float = 70.0
let profit: String = "Today my lemonade stand made \(revenue-cost)"
let personName: String = "Josh"
let greetJosh = "Hi \(personName)"
var shoppingList = ["catfish", "water", "tulips","blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm":"Captain",
"Kaylee":"Mechanic",
]
occupations["Jayne"] = "Public Relations"
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
shoppingList = []
occupations = [:]
/**
控制流
*/
let individualScore = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScore {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalString {
greeting = "Hello, \(name)"
}
// EXPERMENT: Change optional to nil. What greeting do you get? Add an else clause that sets a different greeting if optionalName is nil
optionalName = nil
if let name = optionalName {
greeting = "Hello, \(name)"
} else {
greeting = "Hello stranger"
}
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
let vegetable = "red repper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber","watercress":
print("That would make a good tea sandwich")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
// EXPERIMENT: Try removing the default case. What error do you get?
// switch must be exhaustive, consider adding a default clause
let interestingNumbers = [
"prime":[2, 3, 5, 7, 11, 13],
"Fibonacci":[1, 1, 2, 3, 5, 8],
"Square":[1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
// EXPERIMENT: Add another variable to keep track o which kind of number was the largest, as well as what that largest number was.
let interestingNumber1 = [
"prime":[2, 3, 5, 7, 11, 13],
"Fibonacci":[1, 1, 2, 3, 5, 8],
"Square":[1, 4, 9, 16, 25],
]
var largest1 = 0
var largestKind: String = ""
for (kind, numbers) in interestingNumber1 {
for number in numbers {
if number > largest1 {
largest1 = number
largestKind = kind
}
}
}
print(largest1)
print(largestKind)
var n = 2
while n < 100 {
n = n * 2
}
print(n)
var m = 2
repeat {
m = m * 2
}while m < 100
print(m)
var total = 0
for i in 0..<4 {
total += i
}
print(total)
/**
Functions and Closures
*/
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
// EXPERIMENT: Remove the day parameter. Add a parameter to include today's lunch special in the greeting.
func greet(name: String, tadaysLunch: String) -> String {
return "Hello \(name), today's lunch is \(tadaysLunch)"
}
greet(name: "Bob", tadaysLunch: "Turkey Sandwich")
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.min)
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(numbers: 42, 597, 12)
// EXPERIMENT: Write a function that calculates the average of its arguments
func average(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum/numbers.count
}
average(numbers: 2, 10)
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(list: numbers, condition: lessThanTen)
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
// EXPERIMENT: Rewrite the closure to return zero for all odd numbers.
var number1 = [20 , 19, 7, 12]
number1.map({
(number : Int) -> Int in
if number % 2 == 0 {
return number
} else {
return 0
}
})
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
let sortedNumbers = numbers.sorted{ $0 > $1 }
print(sortedNumbers)
/**
Objects and Classes
*/
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
// EXPERIMENT: Add a constant property with let, and add another method that takes an argument.
class Shape1 {
var numberOfSides = 0
let dimension = "2d"
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides"
}
func notSoSimpleDescription() -> String {
return "That is a \(dimension) shape."
}
}
let myShape1 = Shape1()
myShape1.notSoSimpleDescription()
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
class NameShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square: NameShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)"
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
// EXPERIMENT: Make another subclass of NameShape called Circle that takes a radius and a name as arguments to its initializer.
class NameShape1 {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Circle: NameShape1 {
var radius: Double
init(name: String, radius: Double) {
self.radius = radius
super.init(name: name)
self.name = name
}
override func simpleDescription() -> String {
return "A circle with a radius of \(radius)"
}
func area() -> Double {
return 3.14159265 * radius * radius
}
}
let myCircle = Circle(name: "Example circle", radius: 6.0)
myCircle.name
myCircle.area()
myCircle.simpleDescription()
class EquilateralTriangle: NameShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimter)
triangle.perimter = 9.9
print(triangle.sideLength)
class TriangleAndSquare {
var triangle: EquilateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "large square")
print(triangleAndSquare.triangle.sideLength)
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
/**
Enumerations and Structrures
*/
enum Rank: Int {
case ace = 1
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.ace
let aceRawValue = ace.rawValue
// EXPERIMENT: Write a function that compares two Rank values by comparing their raw values.
enum Rank2: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ac = Rank2.Ace
let two = Rank2.Two
let aceRawValu = ace.rawValue
func compare(rank11: Rank2, rank12: Rank2) -> String {
var higher: Rank2 = rank11
if rank12.rawValue > rank11.rawValue {
var higher = rank12
}
return "The higher of the two is \(higher.simpleDescription())"
}
compare(rank11: ac, rank12: two)
if let convertedRank = Rank(rawValue: 3) {
let threeDescription = convertedRank.simpleDescription()
}
enum Suit {
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
}
let hearts = Suit.hearts
let heartsDescription = hearts.simpleDescription()
// EXPERIMENT: Add a color() method to Suit that returns "black" for spades and clubs, and returns "red" for hearts and diamonds.
enum Suit1: Int {
case Spades = 1
case Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
func color() -> String {
switch self {
case .Spades, .Clubs:
return "black"
case .Hearts, .Diamonds:
return "red"
}
}
}
let heartsDescription1 = Suit1.Hearts.simpleDescription()
let heartsColor = Suit1.Hearts.color()
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result(" 6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
}
// EXPERRMENT: Add a third case to ServerResponse and to the switch.
enum ServerResponse1 {
case Result(String, String)
case Error(String)
case ThirdCase(String)
}
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
// EXPERIMENT: Add a method to Card that creates a full deck of cards,with one card of each combination of rank and suit
//class Card12 {
// var rank: Rank
// var suit: Suit
//
// init(cardRank: Rank, cardSuit: Suit) {
// self.rank = cardRank
// self.suit = cardSuit
// }
//
// func simpleDescription() -> String {
// return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
// }
//
// func Deck() -> String {
// var stringTogether = ""
// for i in 0..<14 {
// if let convertedRank = Rank.init(rawValue: i) {
// self.rank = convertedRank
//
// for y in 0..<14 {
// if let convertedSuit = Suit.init(rawValue: y) {
// self.suit = convertedSuit
// stringTogether = "\(stringTogether) \(self.simpleDescription())"
// }
// }
// }
// }
// return stringTogether
// }
//}
/**
Protocols and Extensions
*/
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
// EXPERIMENT: Write an enumeration that conforms to this protocol.
protocol ExampleProtocol22 {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass22: ExampleProtocol22 {
var simpleDescription: String = "A VERY simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += "Now 100% adjusted."
}
}
class ConformingClass: ExampleProtocol22 {
var simpleDescription: String = "A very simple class."
var carModel: String = "The toyota corolla"
func adjust() {
carModel += " is the best car ever"
}
}
let conformingClass = ConformingClass()
conformingClass.adjust()
let whichCarIsBest = conformingClass.carModel
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
// EXPERIMENT: Write an extension for the Double type that adds an absoluteValue property.
extension Double {
var absoluteValue: Double {
return abs(self)
}
}
let exampleDouble: Double = -40.0
let exampleAbsoluteValue = exampleDouble.absoluteValue
let protocolValue: ExampleProtocol = a
protocolValue.simpleDescription
/**
Error Handing
*/
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}
do {
let printerResponse = try send(job: 1040, toPrinter: "Bi Sheng")
print(printerResponse)
} catch {
print(error)
}
// EXPERIMENT: Change the printer name to "Never Has Toner", so that the send(job: toPrinter:)function throws an error.
do {
let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
print(printerResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError)")
} catch {
print(error)
}
// EXPERMENT: Add code to throw an error inside the do block. What kind of error do you need to throw so that the error is handled by the first catch block? What about the second and third blocks?
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]
func fridgeContains(_ food: String) -> Bool {
fridgeIsOpen = true
defer {
fridgeIsOpen = false
}
let result = fridgeContent.contains(food)
return result
}
fridgeContains("banana")
print(fridgeIsOpen)
/**
Generics
*/
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
makeArray(repeating: "knock", numberOfTimes: 4)
enum OptionalValue<Wrapped> {
case none
case some(Wrapped)
}
var possibleInteger: Optional<Int> = .none
possibleInteger = .some(100)
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
// EXPERIMENT: Modify the anyCommonElements(_:_:)function to make a function that returns an array of the elements that any two sequences have in common
// 练习: 修改 anyCommonElements 函数来创建一个函数, 返回一个数组, 内容是两个序列的共有元素.
//func anyCommonElements1<T: Sequence, U:Sequence>(_ lhs: T, _ rhs: U) -> Bool where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element
//{
// for lhsItem in lhs {
// for rhsItem in rhs {
// if lhsItem == rhsItem {
// return true
// }
// }
// }
// return false
//}
//anyCommonElements1([1, 2, 3], [3])
//
//
//func whichCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element:Equatable, T.GeneratorType.Element == U.GeneratorType.Element>(lhs: T, rhs: U) -> Array<T.GeneratorType.Element>
//{
// var toReturn = Array<T.GeneratorType.Element>()
//
// for lhsItem in lhs {
// for rhsItem in rhs {
// if lhsItem == rhsItem {
// toReturn.append(lhsItem)
// }
// }
// }
// return toReturn
//}
//whichCommonElements(lhs: [1, 2, 3], rhs: [3, 2])
// Write<T: Equatable> is the same as writing<T>...where T:Equatable>.
| 9578a16fcb6a68cb80f3210e403c9493 | 23.32494 | 201 | 0.628678 | false | false | false | false |
lemberg/obd2-swift-lib | refs/heads/master | OBD2-Swift/Classes/Classes/SensorList.swift | mit | 1 | //
// SensorList.swift
// OBD2Swift
//
// Created by Max Vitruk on 27/04/2017.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
/**
Supported OBD2 sensors list
For detailed information read https://en.wikipedia.org/wiki/OBD-II_PIDs
*/
enum OBD2Sensor : UInt8 {
case Supported01_20 = 0x00
case MonitorStatusSinceDTCsCleared = 0x01
case FreezeFrameStatus = 0x02
case FuelSystemStatus = 0x03
case CalculatedEngineLoadValue = 0x04
case EngineCoolantTemperature = 0x05
case ShorttermfueltrimBank1 = 0x06
case LongtermfueltrimBank1 = 0x07
case ShorttermfueltrimBank2 = 0x08
case LongtermfueltrimBank2 = 0x09
case FuelPressure = 0x0A
case IntakeManifoldPressure = 0x0B
case EngineRPM = 0x0C
case VehicleSpeed = 0x0D
case TimingAdvance = 0x0E
case IntakeAirTemperature = 0x0F
case MassAirFlow = 0x10
case ThrottlePosition = 0x11
case SecondaryAirStatus = 0x12
case OxygenSensorsPresent = 0x13
case OxygenVoltageBank1Sensor1 = 0x14
case OxygenVoltageBank1Sensor2 = 0x15
case OxygenVoltageBank1Sensor3 = 0x16
case OxygenVoltageBank1Sensor4 = 0x17
case OxygenVoltageBank2Sensor1 = 0x18
case OxygenVoltageBank2Sensor2 = 0x19
case OxygenVoltageBank2Sensor3 = 0x1A
case OxygenVoltageBank2Sensor4 = 0x1B
case OBDStandardsThisVehicleConforms = 0x1C
case OxygenSensorsPresent2 = 0x1D
case AuxiliaryInputStatus = 0x1E
case RunTimeSinceEngineStart = 0x1F
case PIDsSupported21_40 = 0x20
case DistanceTraveledWithMalfunctionIndicatorLampOn = 0x21
case FuelRailPressureManifoldVacuum = 0x22
case FuelRailPressureDiesel = 0x23
case EquivalenceRatioVoltageO2S1 = 0x24
case EquivalenceRatioVoltageO2S2 = 0x25
case EquivalenceRatioVoltageO2S3 = 0x26
case EquivalenceRatioVoltageO2S4 = 0x27
case EquivalenceRatioVoltageO2S5 = 0x28
case EquivalenceRatioVoltageO2S6 = 0x29
case EquivalenceRatioVoltageO2S7 = 0x2A
case EquivalenceRatioVoltageO2S8 = 0x2B
case CommandedEGR = 0x2C
case EGRError = 0x2D
case CommandedEvaporativePurge = 0x2E
case FuelLevelInput = 0x2F
case NumberofWarmUpsSinceCodesCleared = 0x30
case DistanceTraveledSinceCodesCleared = 0x31
case EvaporativeSystemVaporPressure = 0x32
case BarometricPressure = 0x33
case EquivalenceRatioCurrentO2S1 = 0x34
case EquivalenceRatioCurrentO2S2 = 0x35
case EquivalenceRatioCurrentO2S3 = 0x36
case EquivalenceRatioCurrentO2S4 = 0x37
case EquivalenceRatioCurrentO2S5 = 0x38
case EquivalenceRatioCurrentO2S6 = 0x39
case EquivalenceRatioCurrentO2S7 = 0x3A
case EquivalenceRatioCurrentO2S8 = 0x3B
case CatalystTemperatureBank1Sensor1 = 0x3C
case CatalystTemperatureBank2Sensor1 = 0x3D
case CatalystTemperatureBank1Sensor2 = 0x3E
case CatalystTemperatureBank2Sensor2 = 0x3F
case PIDsSupported41_60 = 0x40
case MonitorStatusThisDriveCycle = 0x41
case ControlModuleVoltage = 0x42
case AbsoluteLoadValue = 0x43
case CommandEquivalenceRatio = 0x44
case RelativeThrottlePosition = 0x45
case AmbientAirTemperature = 0x46
case AbsoluteThrottlePositionB = 0x47
case AbsoluteThrottlePositionC = 0x48
case AcceleratorPedalPositionD = 0x49
case AcceleratorPedalPositionE = 0x4A
case AcceleratorPedalPositionF = 0x4B
case CommandedThrottleActuator = 0x4C
case TimeRunWithMILOn = 0x4D
case TimeSinceTroubleCodesCleared = 0x4E
// From this point sensors don't have full support yet
case MaxValueForER_OSV_OSC_IMAP = 0x4F /* Maximum value for equivalence ratio, oxygen sensor voltage,
oxygen sensor current and intake manifold absolute pressure
*/
case MaxValueForAirFlowRateFromMAFSensor = 0x50
case FuelType = 0x51
case EthanolFuelRatio = 0x52
case AbsoluteEvapSystemVaporPressure = 0x53
case EvapSystemVaporPressure = 0x54
case ShortTermSecondaryOxygenSensorTrimBank_1_3 = 0x55
case LongTermSecondaryOxygenSensorTrimBank_1_3 = 0x56
case ShortTermSecondaryOxygenSensorTrimBank_2_4 = 0x57
case LongTermSecondaryOxygenSensorTrimBank_2_4 = 0x58
case FuelRailPressure_Absolute = 0x59
case RelativeAcceleratorPedalPosition = 0x5A
case HybridBatteryPackRemainingLife = 0x5B
case EngineOilTemperature = 0x5C
//OBD2SensorsVIN = 0x123,
// OBD2Sensor = 0x,
// Sensors should be added at this point for supporting count and last.
}
| 1eb596c058d5a14cc4f963826dd1d786 | 34.92437 | 106 | 0.80117 | false | false | false | false |
jacobjiggler/FoodMate | refs/heads/master | src/iOS/FoodMate/FoodMate/ScanItemViewController.swift | mit | 1 | //
// ScanItemViewController.swift
// FoodMate
//
// Created by Jordan Horwich on 9/13/14.
// Copyright (c) 2014 FoodMate. All rights reserved.
//
import UIKit
import AVFoundation
class ScanItemViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var _session:AVCaptureSession!
var _device:AVCaptureDevice!
var _input:AVCaptureDeviceInput!
var _output:AVCaptureMetadataOutput!
var _prevLayer:AVCaptureVideoPreviewLayer!
@IBOutlet weak var scanView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
_session = AVCaptureSession()
_device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error: NSError? = nil
_input = AVCaptureDeviceInput.deviceInputWithDevice(_device, error: &error) as AVCaptureDeviceInput
if ((_input) != nil) {
_session.addInput(_input)
} else {
print("Error: \(error)")
}
_output = AVCaptureMetadataOutput()
_output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
_session.addOutput(_output)
_output.metadataObjectTypes = _output.availableMetadataObjectTypes
_prevLayer = AVCaptureVideoPreviewLayer.layerWithSession(_session) as AVCaptureVideoPreviewLayer
_prevLayer.frame = scanView.bounds
_prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
scanView.layer.addSublayer(_prevLayer)
}
override func viewDidAppear(animated: Bool) {
_session.startRunning()
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var highlightViewRect:CGRect = CGRectZero
var barCodeObject:AVMetadataMachineReadableCodeObject
var detectionString = ""
var barCodeTypes = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode]
for metadata in metadataObjects {
for type in barCodeTypes {
if metadata.type == type {
barCodeObject = _prevLayer.transformedMetadataObjectForMetadataObject(metadata as AVMetadataObject) as AVMetadataMachineReadableCodeObject
highlightViewRect = barCodeObject.bounds
detectionString = metadata.stringValue
break
}
}
if detectionString != "" {
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let vc = storyboard.instantiateViewControllerWithIdentifier("manualItem") as ManualItemViewController
vc.initwithBarcode(detectionString)
self.presentViewController(vc, animated: true, completion: nil)
_session.stopRunning()
break
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
/////////////////////
// Button Bar Actions
/////////////////////
@IBAction func doneButtonClicked(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
}
| 1ef168a2849d357c4c48f1a431a502f6 | 37.307692 | 162 | 0.664408 | false | false | false | false |
petrone/PetroneAPI_swift | refs/heads/master | PetroneAPI/PetroneStructs.swift | mit | 1 | //
// PetroneStructs.swift
// Petrone
//
// Created by Byrobot on 2017. 7. 31..
// Copyright © 2017년 Byrobot. All rights reserved.
//
import Foundation
public struct PetroneScanData {
public var name: String?
public var uuid: String?
public var rssi: NSNumber = 0
public var fpv: Bool = false
public init( name: String, uuid: String, rssi: NSNumber ) {
self.name = name
self.uuid = uuid
self.rssi = rssi
}
}
public struct PetroneStatus {
public var mode: PetroneMode = PetroneMode.None
public var modeSystem: PetroneModeSystem = PetroneModeSystem.None
public var modeFlight: PetroneModeFlight = PetroneModeFlight.None
public var modeDrive: PetroneModeDrive = PetroneModeDrive.None
public var sensorOrientation: PetroneSensorOrientation = PetroneSensorOrientation.None
public var coordinate: PetroneCoordinate = PetroneCoordinate.None
public var battery: UInt8 = 0
public mutating func parse(_ data:Data) {
self.mode = PetroneMode(rawValue: data[1])!
self.modeSystem = PetroneModeSystem(rawValue: data[2])!
self.modeFlight = PetroneModeFlight(rawValue: data[3])!
self.modeDrive = PetroneModeDrive(rawValue: data[4])!
self.sensorOrientation = PetroneSensorOrientation(rawValue: data[5])!
self.coordinate = PetroneCoordinate(rawValue: data[6])!
self.battery = data[7]
}
}
public struct PetroneTrimFlight {
public var throttle: Int16 = 0
public var yaw: Int16 = 0
public var roll: Int16 = 0
public var pitch: Int16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.throttle = Petrone.getInt16(data, start:&index)
self.yaw = Petrone.getInt16(data, start:&index)
self.roll = Petrone.getInt16(data, start:&index)
self.pitch = Petrone.getInt16(data, start:&index)
}
}
public struct PetroneTrimDrive {
public var wheel: Int16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.wheel = Petrone.getInt16(data, start:&index)
}
}
public struct PetroneTrim {
public var flight: PetroneTrimFlight = PetroneTrimFlight()
public var drive: PetroneTrimDrive = PetroneTrimDrive()
public mutating func parse(_ data:Data) {
var index:Int = 1
self.flight.throttle = Petrone.getInt16(data, start:&index)
self.flight.yaw = Petrone.getInt16(data, start:&index)
self.flight.roll = Petrone.getInt16(data, start:&index)
self.flight.pitch = Petrone.getInt16(data, start:&index)
self.drive.wheel = Petrone.getInt16(data, start:&index)
}
}
public struct PetroneAttitude {
public var roll:Int16 = 0
public var pitch:Int16 = 0
public var yaw:Int16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.roll = Petrone.getInt16(data, start: &index)
self.pitch = Petrone.getInt16(data, start: &index)
self.yaw = Petrone.getInt16(data, start: &index)
}
}
public struct PetroneGyroBias {
public var roll:Int16 = 0
public var pitch:Int16 = 0
public var yaw:Int16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.roll = Petrone.getInt16(data, start: &index)
self.pitch = Petrone.getInt16(data, start: &index)
self.yaw = Petrone.getInt16(data, start: &index)
}
}
public struct PetroneCountFlight {
public var time:UInt64 = 0
public var takeOff:UInt16 = 0
public var landing:UInt16 = 0
public var accident:UInt16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.time = Petrone.getUInt64(data, start: &index)
self.takeOff = Petrone.getUInt16(data, start: &index)
self.landing = Petrone.getUInt16(data, start: &index)
self.accident = Petrone.getUInt16(data, start: &index)
}
}
public struct PetroneCountDrive {
public var time:UInt64 = 0
public var accident:UInt16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.time = Petrone.getUInt64(data, start: &index)
self.accident = Petrone.getUInt16(data, start: &index)
}
}
public struct PetroneImuRawAndAngle {
public var accX:Int16 = 0
public var accY:Int16 = 0
public var accZ:Int16 = 0
public var gyroRoll:Int16 = 0
public var gyroPitch:Int16 = 0
public var gyroYaw:Int16 = 0
public var angleRoll:Int16 = 0
public var anglePitch:Int16 = 0
public var angleYaw:Int16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.accX = Petrone.getInt16(data, start: &index)
self.accY = Petrone.getInt16(data, start: &index)
self.accZ = Petrone.getInt16(data, start: &index)
self.gyroRoll = Petrone.getInt16(data, start: &index)
self.gyroPitch = Petrone.getInt16(data, start: &index)
self.gyroYaw = Petrone.getInt16(data, start: &index)
self.angleRoll = Petrone.getInt16(data, start: &index)
self.anglePitch = Petrone.getInt16(data, start: &index)
self.angleYaw = Petrone.getInt16(data, start: &index)
}
}
public struct PetronePressure {
public var d1:Int32 = 0
public var d2:Int32 = 0
public var temperature:Int32 = 0
public var pressure:Int32 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.d1 = Petrone.getInt32(data, start: &index)
self.d2 = Petrone.getInt32(data, start: &index)
self.temperature = Petrone.getInt32(data, start: &index)
self.pressure = Petrone.getInt32(data, start: &index)
}
}
public struct PetroneImageFlow {
public var fVelocitySumX:Int32 = 0
public var fVelocitySumY:Int32 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.fVelocitySumX = Petrone.getInt32(data, start: &index)
self.fVelocitySumY = Petrone.getInt32(data, start: &index)
}
}
public struct PetroneBattery {
public var percent:UInt8 = 0
public mutating func parse(_ data:Data) {
self.percent = data[1]
}
}
public struct PetroneMotorBase {
public var forward:Int16 = 0
public var reverse:Int16 = 0
public mutating func parse(_ data:Data, start:inout Int) {
self.forward = Petrone.getInt16(data, start: &start)
self.reverse = Petrone.getInt16(data, start: &start)
}
}
public struct PetroneMotor {
public var motor:[PetroneMotorBase] = [PetroneMotorBase(), PetroneMotorBase(), PetroneMotorBase(), PetroneMotorBase()]
public mutating func parse(_ data:Data) {
var index:Int = 1
motor[0].parse(data, start: &index)
motor[1].parse(data, start: &index)
motor[2].parse(data, start: &index)
motor[3].parse(data, start: &index)
}
}
public struct PetroneTemperature {
public var temperature:Int32 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.temperature = Petrone.getInt32(data, start: &index)
}
}
public struct PetroneRange {
public var left:UInt16 = 0
public var front:UInt16 = 0
public var right:UInt16 = 0
public var rear:UInt16 = 0
public var top:UInt16 = 0
public var bottom:UInt16 = 0
public mutating func parse(_ data:Data) {
var index:Int = 1
self.left = Petrone.getUInt16(data, start: &index)
self.front = Petrone.getUInt16(data, start: &index)
self.right = Petrone.getUInt16(data, start: &index)
self.rear = Petrone.getUInt16(data, start: &index)
self.top = Petrone.getUInt16(data, start: &index)
self.bottom = Petrone.getUInt16(data, start: &index)
}
}
public struct PetroneLedModeBase {
public var mode:UInt8 = PetroneLigthMode.None.rawValue
public var color:UInt8 = 0
public var interval:UInt8 = 0
}
public struct PetroneLedBase {
public var mode:UInt8 = PetroneLigthMode.None.rawValue
public var red:UInt8 = 0
public var green:UInt8 = 0
public var blue:UInt8 = 0
public var interval:UInt8 = 0
}
| 750cfe63e3c8194cbe50d280b1804b82 | 31.64 | 122 | 0.655515 | false | false | false | false |
CodaFi/swift | refs/heads/main | stdlib/public/core/SequenceAlgorithms.swift | apache-2.0 | 12 | //===--- SequenceAlgorithms.swift -----------------------------*- 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
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// enumerated()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a sequence of pairs (*n*, *x*), where *n* represents a
/// consecutive integer starting at zero and *x* represents an element of
/// the sequence.
///
/// This example enumerates the characters of the string "Swift" and prints
/// each character along with its place in the string.
///
/// for (n, c) in "Swift".enumerated() {
/// print("\(n): '\(c)'")
/// }
/// // Prints "0: 'S'"
/// // Prints "1: 'w'"
/// // Prints "2: 'i'"
/// // Prints "3: 'f'"
/// // Prints "4: 't'"
///
/// When you enumerate a collection, the integer part of each pair is a counter
/// for the enumeration, but is not necessarily the index of the paired value.
/// These counters can be used as indices only in instances of zero-based,
/// integer-indexed collections, such as `Array` and `ContiguousArray`. For
/// other collections the counters may be out of range or of the wrong type
/// to use as an index. To iterate over the elements of a collection with its
/// indices, use the `zip(_:_:)` function.
///
/// This example iterates over the indices and elements of a set, building a
/// list consisting of indices of names with five or fewer letters.
///
/// let names: Set = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// var shorterIndices: [Set<String>.Index] = []
/// for (i, name) in zip(names.indices, names) {
/// if name.count <= 5 {
/// shorterIndices.append(i)
/// }
/// }
///
/// Now that the `shorterIndices` array holds the indices of the shorter
/// names in the `names` set, you can use those indices to access elements in
/// the set.
///
/// for i in shorterIndices {
/// print(names[i])
/// }
/// // Prints "Sofia"
/// // Prints "Mateo"
///
/// - Returns: A sequence of pairs enumerating the sequence.
///
/// - Complexity: O(1)
@inlinable // protocol-only
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
}
//===----------------------------------------------------------------------===//
// min(), max()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the minimum element in the sequence, using the given predicate as
/// the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `min(by:)` method on a
/// dictionary to find the key-value pair with the lowest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let leastHue = hues.min { a, b in a.value < b.value }
/// print(leastHue)
/// // Prints "Optional((key: "Coral", value: 16))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true`
/// if its first argument should be ordered before its second
/// argument; otherwise, `false`.
/// - Returns: The sequence's minimum element, according to
/// `areInIncreasingOrder`. If the sequence has no elements, returns
/// `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func min(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(e, result) { result = e }
}
return result
}
/// Returns the maximum element in the sequence, using the given predicate
/// as the comparison between elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// This example shows how to use the `max(by:)` method on a
/// dictionary to find the key-value pair with the highest value.
///
/// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156]
/// let greatestHue = hues.max { a, b in a.value < b.value }
/// print(greatestHue)
/// // Prints "Optional((key: "Heliotrope", value: 296))"
///
/// - Parameter areInIncreasingOrder: A predicate that returns `true` if its
/// first argument should be ordered before its second argument;
/// otherwise, `false`.
/// - Returns: The sequence's maximum element if the sequence is not empty;
/// otherwise, `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable // protocol-only
@warn_unqualified_access
public func max(
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Element? {
var it = makeIterator()
guard var result = it.next() else { return nil }
while let e = it.next() {
if try areInIncreasingOrder(result, e) { result = e }
}
return result
}
}
extension Sequence where Element: Comparable {
/// Returns the minimum element in the sequence.
///
/// This example finds the smallest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let lowestHeight = heights.min()
/// print(lowestHeight)
/// // Prints "Optional(58.5)"
///
/// - Returns: The sequence's minimum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func min() -> Element? {
return self.min(by: <)
}
/// Returns the maximum element in the sequence.
///
/// This example finds the largest value in an array of height measurements.
///
/// let heights = [67.5, 65.7, 64.3, 61.1, 58.5, 60.3, 64.9]
/// let greatestHeight = heights.max()
/// print(greatestHeight)
/// // Prints "Optional(67.5)"
///
/// - Returns: The sequence's maximum element. If the sequence has no
/// elements, returns `nil`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
@warn_unqualified_access
public func max() -> Element? {
return self.max(by: <)
}
}
//===----------------------------------------------------------------------===//
// starts(with:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are equivalent to the elements in another sequence, using
/// the given predicate as the equivalence test.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - possiblePrefix: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if the initial elements of the sequence are equivalent
/// to the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix,
by areEquivalent: (Element, PossiblePrefix.Element) throws -> Bool
) rethrows -> Bool {
var possiblePrefixIterator = possiblePrefix.makeIterator()
for e0 in self {
if let e1 = possiblePrefixIterator.next() {
if try !areEquivalent(e0, e1) {
return false
}
}
else {
return true
}
}
return possiblePrefixIterator.next() == nil
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the initial elements of the
/// sequence are the same as the elements in another sequence.
///
/// This example tests whether one countable range begins with the elements
/// of another countable range.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(b.starts(with: a))
/// // Prints "true"
///
/// Passing a sequence with no elements or an empty collection as
/// `possiblePrefix` always results in `true`.
///
/// print(b.starts(with: []))
/// // Prints "true"
///
/// - Parameter possiblePrefix: A sequence to compare to this sequence.
/// - Returns: `true` if the initial elements of the sequence are the same as
/// the elements of `possiblePrefix`; otherwise, `false`. If
/// `possiblePrefix` has no elements, the return value is `true`.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `possiblePrefix`.
@inlinable
public func starts<PossiblePrefix: Sequence>(
with possiblePrefix: PossiblePrefix
) -> Bool where PossiblePrefix.Element == Element {
return self.starts(with: possiblePrefix, by: ==)
}
}
//===----------------------------------------------------------------------===//
// elementsEqual()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain equivalent elements in the same order, using the given
/// predicate as the equivalence test.
///
/// At least one of the sequences must be finite.
///
/// The predicate must be a *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this sequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence,
by areEquivalent: (Element, OtherSequence.Element) throws -> Bool
) rethrows -> Bool {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
switch (iter1.next(), iter2.next()) {
case let (e1?, e2?):
if try !areEquivalent(e1, e2) {
return false
}
case (_?, nil), (nil, _?): return false
case (nil, nil): return true
}
}
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether this sequence and another
/// sequence contain the same elements in the same order.
///
/// At least one of the sequences must be finite.
///
/// This example tests whether one countable range shares the same elements
/// as another countable range and an array.
///
/// let a = 1...3
/// let b = 1...10
///
/// print(a.elementsEqual(b))
/// // Prints "false"
/// print(a.elementsEqual([1, 2, 3]))
/// // Prints "true"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence and `other` contain the same elements
/// in the same order.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func elementsEqual<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.elementsEqual(other, by: ==)
}
}
//===----------------------------------------------------------------------===//
// lexicographicallyPrecedes()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the given
/// predicate to compare elements.
///
/// The predicate must be a *strict weak ordering* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity)
/// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are
/// both `true`, then `areInIncreasingOrder(a, c)` is also
/// `true`. (Transitive comparability)
/// - Two elements are *incomparable* if neither is ordered before the other
/// according to the predicate. If `a` and `b` are incomparable, and `b`
/// and `c` are incomparable, then `a` and `c` are also incomparable.
/// (Transitive incomparability)
///
/// - Parameters:
/// - other: A sequence to compare to this sequence.
/// - areInIncreasingOrder: A predicate that returns `true` if its first
/// argument should be ordered before its second argument; otherwise,
/// `false`.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering as ordered by `areInIncreasingOrder`; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that perform
/// localized comparison instead.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence,
by areInIncreasingOrder: (Element, Element) throws -> Bool
) rethrows -> Bool
where OtherSequence.Element == Element {
var iter1 = self.makeIterator()
var iter2 = other.makeIterator()
while true {
if let e1 = iter1.next() {
if let e2 = iter2.next() {
if try areInIncreasingOrder(e1, e2) {
return true
}
if try areInIncreasingOrder(e2, e1) {
return false
}
continue // Equivalent
}
return false
}
return iter2.next() != nil
}
}
}
extension Sequence where Element: Comparable {
/// Returns a Boolean value indicating whether the sequence precedes another
/// sequence in a lexicographical (dictionary) ordering, using the
/// less-than operator (`<`) to compare elements.
///
/// This example uses the `lexicographicallyPrecedes` method to test which
/// array of integers comes first in a lexicographical ordering.
///
/// let a = [1, 2, 2, 2]
/// let b = [1, 2, 3, 4]
///
/// print(a.lexicographicallyPrecedes(b))
/// // Prints "true"
/// print(b.lexicographicallyPrecedes(b))
/// // Prints "false"
///
/// - Parameter other: A sequence to compare to this sequence.
/// - Returns: `true` if this sequence precedes `other` in a dictionary
/// ordering; otherwise, `false`.
///
/// - Note: This method implements the mathematical notion of lexicographical
/// ordering, which has no connection to Unicode. If you are sorting
/// strings to present to the end user, use `String` APIs that
/// perform localized comparison.
///
/// - Complexity: O(*m*), where *m* is the lesser of the length of the
/// sequence and the length of `other`.
@inlinable
public func lexicographicallyPrecedes<OtherSequence: Sequence>(
_ other: OtherSequence
) -> Bool where OtherSequence.Element == Element {
return self.lexicographicallyPrecedes(other, by: <)
}
}
//===----------------------------------------------------------------------===//
// contains()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns a Boolean value indicating whether the sequence contains an
/// element that satisfies the given predicate.
///
/// You can use the predicate to check for an element of a type that
/// doesn't conform to the `Equatable` protocol, such as the
/// `HTTPResponse` enumeration in this example.
///
/// enum HTTPResponse {
/// case ok
/// case error(Int)
/// }
///
/// let lastThreeResponses: [HTTPResponse] = [.ok, .ok, .error(404)]
/// let hadError = lastThreeResponses.contains { element in
/// if case .error = element {
/// return true
/// } else {
/// return false
/// }
/// }
/// // 'hadError' == true
///
/// Alternatively, a predicate can be satisfied by a range of `Equatable`
/// elements or a general condition. This example shows how you can check an
/// array for an expense greater than $100.
///
/// let expenses = [21.37, 55.21, 9.32, 10.18, 388.77, 11.41]
/// let hasBigPurchase = expenses.contains { $0 > 100 }
/// // 'hasBigPurchase' == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element represents a match.
/// - Returns: `true` if the sequence contains an element that satisfies
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(
where predicate: (Element) throws -> Bool
) rethrows -> Bool {
for e in self {
if try predicate(e) {
return true
}
}
return false
}
/// Returns a Boolean value indicating whether every element of a sequence
/// satisfies a given predicate.
///
/// The following code uses this method to test whether all the names in an
/// array have at least five characters:
///
/// let names = ["Sofia", "Camilla", "Martina", "Mateo", "Nicolás"]
/// let allHaveAtLeastFive = names.allSatisfy({ $0.count >= 5 })
/// // allHaveAtLeastFive == true
///
/// - Parameter predicate: A closure that takes an element of the sequence
/// as its argument and returns a Boolean value that indicates whether
/// the passed element satisfies a condition.
/// - Returns: `true` if the sequence contains only elements that satisfy
/// `predicate`; otherwise, `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func allSatisfy(
_ predicate: (Element) throws -> Bool
) rethrows -> Bool {
return try !contains { try !predicate($0) }
}
}
extension Sequence where Element: Equatable {
/// Returns a Boolean value indicating whether the sequence contains the
/// given element.
///
/// This example checks to see whether a favorite actor is in an array
/// storing a movie's cast.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// print(cast.contains("Marlon"))
/// // Prints "true"
/// print(cast.contains("James"))
/// // Prints "false"
///
/// - Parameter element: The element to find in the sequence.
/// - Returns: `true` if the element was found in the sequence; otherwise,
/// `false`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func contains(_ element: Element) -> Bool {
if let result = _customContainsEquatableElement(element) {
return result
} else {
return self.contains { $0 == element }
}
}
}
//===----------------------------------------------------------------------===//
// reduce()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(_:_:)` method to produce a single value from the elements
/// of an entire sequence. For example, you can use this method on an array
/// of numbers to find their sum or product.
///
/// The `nextPartialResult` closure is called sequentially with an
/// accumulating value initialized to `initialResult` and each element of
/// the sequence. This example shows how to find the sum of an array of
/// numbers.
///
/// let numbers = [1, 2, 3, 4]
/// let numberSum = numbers.reduce(0, { x, y in
/// x + y
/// })
/// // numberSum == 10
///
/// When `numbers.reduce(_:_:)` is called, the following steps occur:
///
/// 1. The `nextPartialResult` closure is called with `initialResult`---`0`
/// in this case---and the first element of `numbers`, returning the sum:
/// `1`.
/// 2. The closure is called again repeatedly with the previous call's return
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the last value returned from the
/// closure is returned to the caller.
///
/// If the sequence has no elements, `nextPartialResult` is never executed
/// and `initialResult` is the result of the call to `reduce(_:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// `initialResult` is passed to `nextPartialResult` the first time the
/// closure is executed.
/// - nextPartialResult: A closure that combines an accumulating value and
/// an element of the sequence into a new accumulating value, to be used
/// in the next call of the `nextPartialResult` closure or returned to
/// the caller.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
_ initialResult: Result,
_ nextPartialResult:
(_ partialResult: Result, Element) throws -> Result
) rethrows -> Result {
var accumulator = initialResult
for element in self {
accumulator = try nextPartialResult(accumulator, element)
}
return accumulator
}
/// Returns the result of combining the elements of the sequence using the
/// given closure.
///
/// Use the `reduce(into:_:)` method to produce a single value from the
/// elements of an entire sequence. For example, you can use this method on an
/// array of integers to filter adjacent equal entries or count frequencies.
///
/// This method is preferred over `reduce(_:_:)` for efficiency when the
/// result is a copy-on-write type, for example an Array or a Dictionary.
///
/// The `updateAccumulatingResult` closure is called sequentially with a
/// mutable accumulating value initialized to `initialResult` and each element
/// of the sequence. This example shows how to build a dictionary of letter
/// frequencies of a string.
///
/// let letters = "abracadabra"
/// let letterCount = letters.reduce(into: [:]) { counts, letter in
/// counts[letter, default: 0] += 1
/// }
/// // letterCount == ["a": 5, "b": 2, "r": 2, "c": 1, "d": 1]
///
/// When `letters.reduce(into:_:)` is called, the following steps occur:
///
/// 1. The `updateAccumulatingResult` closure is called with the initial
/// accumulating value---`[:]` in this case---and the first character of
/// `letters`, modifying the accumulating value by setting `1` for the key
/// `"a"`.
/// 2. The closure is called again repeatedly with the updated accumulating
/// value and each element of the sequence.
/// 3. When the sequence is exhausted, the accumulating value is returned to
/// the caller.
///
/// If the sequence has no elements, `updateAccumulatingResult` is never
/// executed and `initialResult` is the result of the call to
/// `reduce(into:_:)`.
///
/// - Parameters:
/// - initialResult: The value to use as the initial accumulating value.
/// - updateAccumulatingResult: A closure that updates the accumulating
/// value with an element of the sequence.
/// - Returns: The final accumulated value. If the sequence has no elements,
/// the result is `initialResult`.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func reduce<Result>(
into initialResult: __owned Result,
_ updateAccumulatingResult:
(_ partialResult: inout Result, Element) throws -> ()
) rethrows -> Result {
var accumulator = initialResult
for element in self {
try updateAccumulatingResult(&accumulator, element)
}
return accumulator
}
}
//===----------------------------------------------------------------------===//
// reversed()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the elements of this sequence in reverse
/// order.
///
/// The sequence must be finite.
///
/// - Returns: An array containing the elements of this sequence in
/// reverse order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public __consuming func reversed() -> [Element] {
// FIXME(performance): optimize to 1 pass? But Array(self) can be
// optimized to a memcpy() sometimes. Those cases are usually collections,
// though.
var result = Array(self)
let count = result.count
for i in 0..<count/2 {
result.swapAt(i, count - ((i + 1) as Int))
}
return result
}
}
//===----------------------------------------------------------------------===//
// flatMap()
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns an array containing the concatenated results of calling the
/// given transformation with each element of this sequence.
///
/// Use this method to receive a single-level collection when your
/// transformation produces a sequence or collection for each element.
///
/// In this example, note the difference in the result of using `map` and
/// `flatMap` with a transformation that returns an array.
///
/// let numbers = [1, 2, 3, 4]
///
/// let mapped = numbers.map { Array(repeating: $0, count: $0) }
/// // [[1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
///
/// let flatMapped = numbers.flatMap { Array(repeating: $0, count: $0) }
/// // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
///
/// In fact, `s.flatMap(transform)` is equivalent to
/// `Array(s.map(transform).joined())`.
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns a sequence or collection.
/// - Returns: The resulting flattened array.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable
public func flatMap<SegmentOfResult: Sequence>(
_ transform: (Element) throws -> SegmentOfResult
) rethrows -> [SegmentOfResult.Element] {
var result: [SegmentOfResult.Element] = []
for element in self {
result.append(contentsOf: try transform(element))
}
return result
}
}
extension Sequence {
/// Returns an array containing the non-`nil` results of calling the given
/// transformation with each element of this sequence.
///
/// Use this method to receive an array of non-optional values when your
/// transformation produces an optional value.
///
/// In this example, note the difference in the result of using `map` and
/// `compactMap` with a transformation that returns an optional `Int` value.
///
/// let possibleNumbers = ["1", "2", "three", "///4///", "5"]
///
/// let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
/// // [1, 2, nil, nil, 5]
///
/// let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
/// // [1, 2, 5]
///
/// - Parameter transform: A closure that accepts an element of this
/// sequence as its argument and returns an optional value.
/// - Returns: An array of the non-`nil` results of calling `transform`
/// with each element of the sequence.
///
/// - Complexity: O(*m* + *n*), where *n* is the length of this sequence
/// and *m* is the length of the result.
@inlinable // protocol-only
public func compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
return try _compactMap(transform)
}
// The implementation of compactMap accepting a closure with an optional result.
// Factored out into a separate function in order to be used in multiple
// overloads.
@inlinable // protocol-only
@inline(__always)
public func _compactMap<ElementOfResult>(
_ transform: (Element) throws -> ElementOfResult?
) rethrows -> [ElementOfResult] {
var result: [ElementOfResult] = []
for element in self {
if let newElement = try transform(element) {
result.append(newElement)
}
}
return result
}
}
| 8649f865ce8d575b2338b2315f0ed527 | 38.00861 | 83 | 0.60292 | false | false | false | false |
nessBautista/iOSBackup | refs/heads/master | iOSNotebook/Pods/Outlaw/Sources/Outlaw/Dictionary.swift | cc0-1.0 | 1 | //
// Dictionary.swift
// Outlaw
//
// Created by Brian Mullen on 11/18/16.
// Copyright © 2016 Molbie LLC. All rights reserved.
//
import Foundation
public extension Dictionary {
public static func value(from object: Any) throws -> [Key: Value] {
guard let value = object as? [Key: Value] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return value
}
public static func value(from object: Any) throws -> [Key: Value?] {
guard let anyDictionary = object as? [Key: Any?] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return anyDictionary.map { (key, anyValue) in
return (key, anyValue as? Value)
}
}
}
// MARK: -
// MARK: Transforms
public extension Dictionary {
public static func value<T>(from object: Any, with transform:(Value) throws -> T) throws -> [Key: T] {
guard let anyDictionary = object as? [Key: Value] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return try anyDictionary.map { (key, anyValue) in
return (key, try transform(anyValue))
}
}
public static func value<T>(from object: Any, with transform:(Value?) throws -> T) throws -> [Key: T] {
guard let anyDictionary = object as? [Key: Value?] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return try anyDictionary.map { (key, anyValue) in
return (key, try transform(anyValue))
}
}
public static func value<T>(from object: Any, with transform:(Value) -> T?) throws -> [Key: T?] {
guard let anyDictionary = object as? [Key: Value?] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return anyDictionary.map { (key, anyValue) in
guard let rawValue = anyValue else { return (key, nil) }
return (key, transform(rawValue))
}
}
public static func value<T>(from object: Any, with transform:(Value?) -> T?) throws -> [Key: T?] {
guard let anyDictionary = object as? [Key: Value?] else {
throw OutlawError.typeMismatch(expected: self, actual: type(of: object))
}
return anyDictionary.map { (key, anyValue) in
return (key, transform(anyValue))
}
}
}
| 41202600f175310047e7126a91358806 | 32.394737 | 107 | 0.5855 | false | false | false | false |
Eonil/EditorLegacy | refs/heads/trial1 | Modules/Editor/Sources/ProtoUIComponents/ScrollViewController1.swift | mit | 1 | //
// ScrollViewController1.swift
// RFC Formaliser
//
// Created by Hoon H. on 10/27/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Foundation
import Cocoa
/// `translatesAutoresizingMaskIntoConstraints` set to `false` implicitly.
@availability(*,deprecated=0)
class ScrollViewController1: NSViewController {
override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
final var documentViewController:NSViewController? = nil {
willSet {
if let dc1 = documentViewController {
scrollView.documentView = nil
self.removeChildViewController(dc1)
}
}
didSet {
if let dc1 = documentViewController {
scrollView.documentView = dc1.view
self.addChildViewController(dc1)
}
}
}
final var scrollView:NSScrollView {
get {
return super.view as! NSScrollView
}
set(v) {
super.view = v
}
}
override var view:NSView {
willSet {
fatalError("You cannot replace view of this object.")
}
}
override func loadView() {
// super.loadView()
super.view = NSScrollView()
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = true
scrollView.translatesAutoresizingMaskIntoConstraints = false /// This shall benefit everyone in the universe...
}
}
| 14671548dc835622841f70dc675582ed | 19.852941 | 114 | 0.708039 | false | false | false | false |
ddaguro/clintonconcord | refs/heads/master | OIMApp/Controls/ADVAnimatedButton/ADVAnimatedButton.swift | mit | 1 | //
// ADVAnimatedButton.swift
// Mega
//
// Created by Tope Abayomi on 10/12/2014.
// Copyright (c) 2014 App Design Vault. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable class ADVAnimatedButton: UIButton {
var refreshImageView = UIImageView(frame: CGRectZero)
var animating : Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupView()
}
@IBInspectable var imageToShow : UIImage = UIImage(named: "sync")! {
didSet {
refreshImageView.image = imageToShow.imageWithRenderingMode(.AlwaysTemplate)
}
}
func setupView(){
refreshImageView.image = UIImage(named: "sync")?.imageWithRenderingMode(.AlwaysTemplate)
refreshImageView.tintColor = UIColor(white: 1.0, alpha: 0.5)
refreshImageView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(refreshImageView)
}
override func layoutSubviews() {
super.layoutSubviews()
let heightConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Height, relatedBy: .Equal, toItem: titleLabel, attribute: .Height, multiplier: 1.0, constant: 0.0)
let aspectRatioConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Height, relatedBy: .Equal, toItem: refreshImageView, attribute: .Width, multiplier: 1.0, constant: 0.0)
let horizontalSpacingConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Right, relatedBy: .Equal, toItem: titleLabel, attribute: .Left, multiplier: 1.0, constant: -10.0)
let topConstraint = NSLayoutConstraint(item: refreshImageView, attribute: .Top, relatedBy: .Equal, toItem: titleLabel, attribute: .Top, multiplier: 1.0, constant: 0.0)
refreshImageView.addConstraint(aspectRatioConstraint)
addConstraints([heightConstraint, horizontalSpacingConstraint, topConstraint])
let horizontalCenterConstraint = NSLayoutConstraint(item: titleLabel!, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0.0)
let verticalCenterConstraint = NSLayoutConstraint(item: titleLabel!, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0.0)
addConstraints([horizontalCenterConstraint, verticalCenterConstraint])
}
func startAnimating(){
if !animating {
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
animation.toValue = M_PI * 2.0
animation.cumulative = true
animation.duration = 1.0
animation.repeatCount = 10000
refreshImageView.layer.addAnimation(animation, forKey: "rotationAnimation")
animating = true
}
}
func stopAnimating(){
CATransaction.begin()
refreshImageView.layer.removeAllAnimations()
CATransaction.commit()
animating = false
}
}
| b889e028b98ab6858f2daa15bd9941f5 | 34.11828 | 194 | 0.647275 | false | false | false | false |
groue/GRDB.swift | refs/heads/master | Tests/GRDBTests/AssociationHasManyThroughOrderingTests.swift | mit | 1 | import XCTest
import GRDB
// Ordered hasManyThrough
private struct Team: Codable, FetchableRecord, PersistableRecord, Equatable {
static let playerRoles = hasMany(PlayerRole.self).order(Column("position"))
static let players = hasMany(Player.self, through: playerRoles, using: PlayerRole.player)
var id: Int64
var name: String
}
private struct PlayerRole: Codable, FetchableRecord, PersistableRecord {
static let player = belongsTo(Player.self)
var teamId: Int64
var playerId: Int64
var position: Int
}
private struct Player: Codable, FetchableRecord, PersistableRecord, Equatable {
var id: Int64
var name: String
}
private struct TeamInfo: Decodable, FetchableRecord, Equatable {
var team: Team
var players: [Player]
}
/// A usage test for ordered hasManyThrough association
class AssociationHasManyThroughOrderingTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
try dbWriter.write { db in
try db.create(table: "team") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull()
}
try db.create(table: "player") { t in
t.column("id", .integer).primaryKey()
t.column("name", .text).notNull()
}
try db.create(table: "playerRole") { t in
t.column("teamId", .integer).notNull().references("team")
t.column("playerId", .integer).notNull().references("player")
t.column("position", .integer).notNull()
t.primaryKey(["teamId", "playerId"])
}
try Team(id: 1, name: "Red").insert(db)
try Team(id: 2, name: "Blue").insert(db)
try Player(id: 1, name: "Arthur").insert(db)
try Player(id: 2, name: "Barbara").insert(db)
try Player(id: 3, name: "Craig").insert(db)
try Player(id: 4, name: "Diane").insert(db)
try PlayerRole(teamId: 1, playerId: 1, position: 1).insert(db)
try PlayerRole(teamId: 1, playerId: 2, position: 2).insert(db)
try PlayerRole(teamId: 1, playerId: 3, position: 3).insert(db)
try PlayerRole(teamId: 2, playerId: 2, position: 3).insert(db)
try PlayerRole(teamId: 2, playerId: 3, position: 2).insert(db)
try PlayerRole(teamId: 2, playerId: 4, position: 1).insert(db)
}
}
func testRequestFor() throws {
try makeDatabaseQueue().read { db in
let team = try Team.fetchOne(db, key: 2)!
let players = try team.request(for: Team.players).fetchAll(db)
XCTAssertEqual(lastSQLQuery, """
SELECT "player".* \
FROM "player" \
JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" = 2) \
ORDER BY "playerRole"."position"
""")
XCTAssertEqual(players, [
Player(id: 4, name: "Diane"),
Player(id: 3, name: "Craig"),
Player(id: 2, name: "Barbara"),
])
}
}
func testReorderedRequestFor() throws {
try makeDatabaseQueue().read { db in
let team = try Team.fetchOne(db, key: 2)!
let players = try team.request(for: Team.players).order(Column("name")).fetchAll(db)
XCTAssertEqual(lastSQLQuery, """
SELECT "player".* \
FROM "player" \
JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" = 2) \
ORDER BY "player"."name", "playerRole"."position"
""")
XCTAssertEqual(players, [
Player(id: 2, name: "Barbara"),
Player(id: 3, name: "Craig"),
Player(id: 4, name: "Diane"),
])
}
}
func testIncludingAll() throws {
try makeDatabaseQueue().read { db in
let teamInfos = try Team
.orderByPrimaryKey()
.including(all: Team.players)
.asRequest(of: TeamInfo.self)
.fetchAll(db)
XCTAssertTrue(sqlQueries.contains("""
SELECT * FROM "team" ORDER BY "id"
"""))
XCTAssertTrue(sqlQueries.contains("""
SELECT "player".*, "playerRole"."teamId" AS "grdb_teamId" \
FROM "player" \
JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" IN (1, 2)) \
ORDER BY "playerRole"."position"
"""))
XCTAssertEqual(teamInfos, [
TeamInfo(
team: Team(id: 1, name: "Red"),
players: [
Player(id: 1, name: "Arthur"),
Player(id: 2, name: "Barbara"),
Player(id: 3, name: "Craig"),
]),
TeamInfo(
team: Team(id: 2, name: "Blue"),
players: [
Player(id: 4, name: "Diane"),
Player(id: 3, name: "Craig"),
Player(id: 2, name: "Barbara"),
])])
}
}
func testReorderedIncludingAll() throws {
try makeDatabaseQueue().read { db in
let teamInfos = try Team
.orderByPrimaryKey()
.including(all: Team.players.order(Column("name")))
.asRequest(of: TeamInfo.self)
.fetchAll(db)
XCTAssertTrue(sqlQueries.contains("""
SELECT * FROM "team" ORDER BY "id"
"""))
XCTAssertTrue(sqlQueries.contains("""
SELECT "player".*, "playerRole"."teamId" AS "grdb_teamId" \
FROM "player" \
JOIN "playerRole" ON ("playerRole"."playerId" = "player"."id") AND ("playerRole"."teamId" IN (1, 2)) \
ORDER BY "player"."name", "playerRole"."position"
"""))
XCTAssertEqual(teamInfos, [
TeamInfo(
team: Team(id: 1, name: "Red"),
players: [
Player(id: 1, name: "Arthur"),
Player(id: 2, name: "Barbara"),
Player(id: 3, name: "Craig"),
]),
TeamInfo(
team: Team(id: 2, name: "Blue"),
players: [
Player(id: 2, name: "Barbara"),
Player(id: 3, name: "Craig"),
Player(id: 4, name: "Diane"),
])])
}
}
}
| 44f9c4974a2564b58819d0481039c4b7 | 39.676647 | 118 | 0.500221 | false | false | false | false |
clayellis/StringScanner | refs/heads/master | Sources/StringScanner/CharacterSet.swift | mit | 1 | //
// CharactersSet.swift
// StringScanner
//
// Created by Omar Abdelhafith on 26/10/2016.
//
//
/// Range Set
public enum CharactersSet: Containable {
/// All english letters set
case allLetters
/// Small english letters set
case smallLetters
/// Capital english letters set
case capitalLetters
/// Numbers set
case numbers
/// Spaces set
case space
/// Alpha Numeric set
case alphaNumeric
/// Characters in the string
case string(String)
/// Containable Array
case containables([Containable])
/// Range (and closed range)
case range(Containable)
/// Join with another containable
public func join(characterSet: CharactersSet) -> CharactersSet {
let array = [characterSet.containable, self.containable]
return .containables(array)
}
public func contains(character element: Character) -> Bool {
return self.containable.contains(character: element)
}
var containable: Containable {
switch self {
case .smallLetters:
return RangeContainable(ranges: "a"..."z")
case .capitalLetters:
return RangeContainable(ranges: "A"..."Z")
case .allLetters:
return RangeContainable(
ranges: CharactersSet.smallLetters.containable, CharactersSet.capitalLetters.containable)
case .numbers:
return RangeContainable(ranges: "0"..."9")
case .space:
return RangeContainable(ranges: " "..." ")
case .alphaNumeric:
return RangeContainable(ranges:
CharactersSet.allLetters.containable, CharactersSet.numbers.containable)
case .string(let string):
return ContainableString(stringOfCharacters: string)
case .containables(let array):
return RangeContainable(array: array)
case .range(let range):
return RangeContainable(ranges: range)
}
}
}
private struct ContainableString: Containable {
let stringOfCharacters: String
func contains(character element: Character) -> Bool {
return stringOfCharacters.find(string: String(element)) != nil
}
}
private struct RangeContainable: Containable {
let ranges: [Containable]
init(ranges: Containable...) {
self.ranges = ranges
}
init(array: [Containable]) {
self.ranges = array
}
func contains(character element: Character) -> Bool {
let filtered = ranges.filter { $0.contains(character: element) }
return filtered.count > 0
}
}
| ee5961e70fb6cb1b38bfced3e31770fd | 22.930693 | 97 | 0.683906 | false | false | false | false |
zskyfly/yelp | refs/heads/master | Yelp/FiltersViewController.swift | apache-2.0 | 1 | //
// FiltersViewController.swift
// Yelp
//
// Created by Zachary Matthews on 2/18/16.
// Copyright © 2016 Timothy Lee. All rights reserved.
//
import UIKit
protocol FiltersViewControllerDelegate {
func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [SearchFilter])
}
class FiltersViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var searchFilters: [SearchFilter]!
var delegate: FiltersViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.allowsSelection = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCancelButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func onSearchButton(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
delegate?.filtersViewController(self, didUpdateFilters: self.searchFilters)
}
/*
// 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.
}
*/
}
extension FiltersViewController: UITableViewDataSource {
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let searchFilter = self.searchFilters[section]
return searchFilter.sectionName
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let searchFilter = self.searchFilters[section]
switch searchFilter.cellIdentifier {
case "SwitchCell":
return searchFilter.values.count
case "SegmentedCell":
return 1
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell
let section = indexPath.section
let index = indexPath.row
let searchFilter = self.searchFilters[section]
let searchFilterValues = searchFilter.values
let selectedIndex = searchFilter.selectedIndex
let searchFilterValue = searchFilterValues[index]
let searchFilterState = searchFilter.states[index]
switch searchFilter.cellIdentifier {
case "SwitchCell":
let switchCell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchCell
switchCell.delegate = self
switchCell.filterState = searchFilterState
switchCell.filterValue = searchFilterValue
cell = switchCell
break
case "SegmentedCell":
let segmentedCell = tableView.dequeueReusableCellWithIdentifier("SegmentedCell", forIndexPath: indexPath) as! SegmentedCell
segmentedCell.delegate = self
segmentedCell.selectedIndex = selectedIndex
segmentedCell.segmentNames = searchFilterValues
cell = segmentedCell
break
default:
cell = UITableViewCell()
}
return cell
}
}
extension FiltersViewController: UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.searchFilters.count
}
}
extension FiltersViewController: SwitchCellDelegate {
func switchCell(switchCell: SwitchCell, didChangeValue value: Bool) {
let indexPath = tableView.indexPathForCell(switchCell)!
let section = indexPath.section
let row = indexPath.row
self.searchFilters[section].states[row] = value
}
}
extension FiltersViewController: SegmentedCellDelegate {
func segmentedCell(segmentedCell: SegmentedCell, didChangeValue value: Int) {
let indexPath = tableView.indexPathForCell(segmentedCell)!
let section = indexPath.section
self.searchFilters[section].selectedIndex = value
}
}
| 06968f06afc1ee998390c81cc2efc3da | 29.809859 | 135 | 0.693257 | false | false | false | false |
brightdigit/speculid | refs/heads/master | frameworks/speculid/Controllers/VersionMenuItem.swift | mit | 1 | import Cocoa
import SwiftVer
extension Version {
public var buildHexidecimal: String {
String(format: "%05x", build)
}
}
public class VersionMenuItem: NSMenuItem {
public static func buildNumbers(fromResource resource: String?, withExtension extension: String?) -> Set<Int>? {
if let url = Application.bundle.url(forResource: resource, withExtension: `extension`) {
if let text = try? String(contentsOf: url) {
return Set(text.components(separatedBy: CharacterSet.newlines).compactMap { Int($0.trimmingCharacters(in: .whitespacesAndNewlines)) })
}
}
return nil
}
public init() {
let title: String
if let version = Application.current.version, Application.vcs != nil {
title = version.developmentDescription
} else {
title = "\(String(describing: Application.bundle.infoDictionary?["CFBundleShortVersionString"])) (\(String(describing: Application.bundle.infoDictionary?["CFBundleVersion"])))"
}
super.init(title: title, action: nil, keyEquivalent: "")
}
public required init(coder decoder: NSCoder) {
super.init(coder: decoder)
}
}
| 46250b4d0e313d63d57f50fc50f27536 | 32.088235 | 182 | 0.702222 | false | false | false | false |
isaced/fir-mac | refs/heads/master | fir-mac/Tools/Util.swift | gpl-3.0 | 1 | //
// Util.swift
// fir-mac
//
// Created by isaced on 2017/5/8.
//
//
import Foundation
import Cocoa
enum UploadAppIOSReleaseType: String {
case adhoc = "Adhoc"
case inHouse = "Inhouse"
}
struct ParsedAppInfo: CustomStringConvertible {
var appName: String?
var bundleID: String?
var version: String?
var build: String?
var type: UploadAppType?
var iosReleaseType: UploadAppIOSReleaseType?
var iconImage: NSImage?
var sourceFileURL: URL?
var description: String {
return "--- App Info --- \nApp Name: \((appName ?? "")) \nBundle ID: \((bundleID ?? "")) \nVersion: \((version ?? "")) \nBuild: \((build ?? ""))\nType: \(type?.rawValue ?? "")\nIcon: \(iconImage != nil ? "YES":"NO") \n--- App Info ---"
}
}
class Util {
//MARK: Constants
fileprivate static let mktempPath = "/usr/bin/mktemp"
fileprivate static let unzipPath = "/usr/bin/unzip"
fileprivate static let defaultsPath = "/usr/bin/defaults"
static func parseAppInfo(sourceFile: URL, callback:((_ : ParsedAppInfo?)->Void)) {
if sourceFile.pathExtension.lowercased() == "ipa" {
// Create temp folder
if let tempFolder = makeTempFolder() {
print("--- makeTempFolder : \(tempFolder)")
// unzip
unzip(sourceFile.path, outputPath: tempFolder.path)
print("--- unzip...")
// Payload Path
let payloadPath = tempFolder.appendingPathComponent("Payload")
if payloadPath.isExists() {
// Loop payload directory
do {
let files = try FileManager.default.contentsOfDirectory(atPath: payloadPath.path)
for file in files {
let filePath = payloadPath.appendingPathComponent(file)
if !filePath.isExists(dir: true) { continue }
if filePath.pathExtension.lowercased() != "app" { continue}
// Got info.plist
let infoPlistPath = filePath.appendingPathComponent("Info.plist")
if let data = try? Data(contentsOf: infoPlistPath) {
if let plist = (try? PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil)) as? [String: Any] {
var info = ParsedAppInfo()
info.bundleID = plist["CFBundleIdentifier"] as? String
info.version = plist["CFBundleShortVersionString"] as? String
info.build = plist["CFBundleVersion"] as? String
info.appName = plist["CFBundleDisplayName"] as? String
info.type = .ios
info.sourceFileURL = sourceFile
// icon
let iconNames = ["[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"]
for iconName in iconNames {
let iconFile = filePath.appendingPathComponent(iconName, isDirectory: false)
if iconFile.isExists() {
info.iconImage = NSImage(contentsOfFile: iconFile.path)
break
}
}
callback(info)
}
}
// clean
cleanTempDir(path: tempFolder)
return
}
} catch {
print("loop file error...")
}
}else{
print("can't find payload...")
}
// clean
cleanTempDir(path: tempFolder)
}else{
print("make temp dir error...")
}
}else{
print("pathExtension error...")
}
callback(nil)
}
static func cleanTempDir(path: URL) {
try! FileManager.default.removeItem(atPath: path.path)
print("--- clean temp dir...")
}
static func makeTempFolder() -> URL? {
let tempTask = Process().execute(mktempPath, workingDirectory: nil, arguments: ["-d"])
let url = URL(fileURLWithPath: tempTask.output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), isDirectory: true)
return url
}
static func unzip(_ inputFile: String, outputPath: String) {
_ = Process().execute(unzipPath, workingDirectory: nil, arguments: ["-q", "-o", inputFile,"-d",outputPath])
}
static func defaultsRead(item: String, plistFilePath: String) -> String {
let output = Process().execute(defaultsPath, workingDirectory: nil, arguments: ["read", plistFilePath, item]).output
return output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
static func generateQRCode(from string: String) -> NSImage? {
let data = string.data(using: String.Encoding.ascii)
if let filter = CIFilter(name: "CIQRCodeGenerator") {
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 3, y: 3)
if let output = filter.outputImage?.applying(transform) {
let rep = NSCIImageRep(ciImage: output)
let nsImage = NSImage(size: rep.size)
nsImage.addRepresentation(rep)
return nsImage
}
}
return nil
}
}
extension URL {
func isExists(dir: Bool = false) -> Bool {
if dir {
var isDirectory: ObjCBool = true
return FileManager.default.fileExists(atPath: self.path, isDirectory: &isDirectory)
}else{
return FileManager.default.fileExists(atPath: self.path)
}
}
}
| 80ac9dc2594ffe1ace03a7bb6f1d89ae | 39.952096 | 243 | 0.474777 | false | false | false | false |
thewells1024/TipICal | refs/heads/master | TipICal/TipCalculatorBrain.swift | mit | 1 | //
// TipCalculatorBrain.swift
// TipICal
//
// Created by Kent Kawahara on 5/9/17.
// Copyright © 2017 Kent Kawahara. All rights reserved.
//
import Foundation
class TipCalculatorBrain {
public enum TipPercentage: Double {
case Fifteen = 0.15
case Twenty = 0.20
case TwentyFive = 0.25
}
init() {
self.tipPercentage = nil
}
init(tipPercentage: TipPercentage) {
self.tipPercentage = tipPercentage
}
private var tipPercentageValue: Double?
public var tipPercentage: TipPercentage? {
get {
if let rawValue = tipPercentageValue {
return TipPercentage.init(rawValue: rawValue)
}
return nil
}
set {
tipPercentageValue = newValue?.rawValue
}
}
public func calculateTip(dollarAmount: Double) -> Double {
let percentage = tipPercentageValue ?? 0
return percentage * dollarAmount
}
}
| 1ee9afeaf06fef801c80837305e60cea | 20.522727 | 61 | 0.621964 | false | false | false | false |
LearningSwift2/LearningApps | refs/heads/master | SimpleRealm/SimpleRealm/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// SimpleRealm
//
// Created by Phil Wright on 3/5/16.
// Copyright © 2016 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
class ViewController: UIViewController {
let realm = try! Realm()
override func viewDidLoad() {
super.viewDidLoad()
let luke = Person()
luke.name = "Luke Skywalker"
luke.createdAt = NSDate()
let starship = Starship()
starship.name = "X-wing"
starship.createdAt = NSDate()
let starship2 = Starship()
starship2.name = "Millennium Falcon"
starship2.createdAt = NSDate()
luke.starships.append(starship)
luke.starships.append(starship2)
do {
try realm.write() { () -> Void in
realm.add(luke)
}
} catch {
print("An error occurred writing luke")
}
let persons = realm.objects(Person)
for p in persons {
print(p.name)
print(p.createdAt)
for s in p.starships {
print(s.name)
print(s.createdAt)
}
}
}
}
| 1ead325cd67c6ea77b8104bedd273b34 | 19.171875 | 56 | 0.487219 | false | false | false | false |
ruddfawcett/Notepad | refs/heads/master | Notepad/Notepad-iOS.swift | mit | 1 | //
// Notepad.swift
// Notepad
//
// Created by Rudd Fawcett on 10/14/16.
// Copyright © 2016 Rudd Fawcett. All rights reserved.
//
#if os(iOS)
import UIKit
public class Notepad: UITextView {
var storage: Storage = Storage()
/// Creates a new Notepad.
///
/// - parameter frame: The frame of the text editor.
/// - parameter themeFile: The name of the theme file to use.
///
/// - returns: A new Notepad.
convenience public init(frame: CGRect, themeFile: String) {
self.init(frame: frame, textContainer: nil)
let theme = Theme(themeFile)
self.storage.theme = theme
self.backgroundColor = theme.backgroundColor
self.tintColor = theme.tintColor
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
convenience public init(frame: CGRect, theme: Theme.BuiltIn) {
self.init(frame: frame, themeFile: theme.rawValue)
}
convenience public init(frame: CGRect, theme: Theme) {
self.init(frame: frame, textContainer: nil)
self.storage.theme = theme
self.backgroundColor = theme.backgroundColor
self.tintColor = theme.tintColor
self.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
let layoutManager = NSLayoutManager()
let containerSize = CGSize(width: frame.size.width, height: CGFloat.greatestFiniteMagnitude)
let container = NSTextContainer(size: containerSize)
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
storage.addLayoutManager(layoutManager)
super.init(frame: frame, textContainer: container)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let layoutManager = NSLayoutManager()
let containerSize = CGSize(width: frame.size.width, height: CGFloat.greatestFiniteMagnitude)
let container = NSTextContainer(size: containerSize)
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
storage.addLayoutManager(layoutManager)
}
}
#endif
| f4d16f0d4b7394f35050bf084a76cebf | 31.746269 | 100 | 0.67639 | false | false | false | false |
luinily/hOme | refs/heads/master | hOme/Model/FlicManager.swift | mit | 1 | //
// FlicManager.swift
// hOme
//
// Created by Coldefy Yoann on 2016/03/06.
// Copyright © 2016年 YoannColdefy. All rights reserved.
//
import Foundation
import CloudKit
class FlicManager: NSObject, SCLFlicManagerDelegate {
private let _appKey = "6f90a672-3a48-4d43-9070-d7f06ecd1704"
private let _appSecret = "cfd3a24d-091f-414f-8f0e-978ee49e1712"
private var _manager: SCLFlicManager?
private var _onButtonGrabbed: ((_ button: Button) -> Void)?
override init() {
super.init()
_manager = SCLFlicManager.configure(with: self, defaultButtonDelegate: nil, appID: _appKey, appSecret: _appSecret, backgroundExecution: false)
print("known buttons: " + String(describing: _manager?.knownButtons().count))
}
func deleteButton(_ button: FlicButton) {
if let flic = button.button {
_manager?.forget(flic)
}
}
func setOnButtonGrabbed(_ onButtonGrabbed: @escaping (_ button: Button) -> Void) {
_onButtonGrabbed = onButtonGrabbed
}
func getButton(identifier: UUID) -> SCLFlicButton? {
return _manager?.knownButtons()[identifier]
}
func grabButton() {
_manager?.grabFlicFromFlicApp(withCallbackUrlScheme: "hOme://button")
}
func flicManagerDidRestoreState(_ manager: SCLFlicManager) {
print("known buttons after restoration: " + String(describing: _manager?.knownButtons().count))
}
func flicManager(_ manager: SCLFlicManager, didChange state: SCLFlicManagerBluetoothState) {
NSLog("FlicManager did change state..")
}
func flicManager(_ manager: SCLFlicManager, didGrab button: SCLFlicButton?, withError error: Error?) {
let button = FlicButton(button: button)
_onButtonGrabbed?(button)
}
}
| 9f9ce508ad2cad70df935027da2579e7 | 29.5 | 144 | 0.73224 | false | false | false | false |
iOSreverse/DWWB | refs/heads/master | DWWB/DWWB/Classes/Tools(工具)/Categoy/NSDate-Extension.swift | apache-2.0 | 1 | //
// NSDate-Extension.swift
// DWWB
//
// Created by xmg on 16/4/9.
// Copyright © 2016年 NewDee. All rights reserved.
//
import Foundation
extension NSDate {
class func createDateString(createAtStr : String) -> String {
// 1.创建时间格式化对象
let fmt = NSDateFormatter()
fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy" // 星期 月份 日 小时:分钟:秒 时区 年份
// 2.将字符串时间,转成NSDate类型
guard let createDate = fmt.dateFromString(createAtStr) else {
return ""
}
// 3.创建当前时间
let nowDate = NSDate()
// 4.计算创建时间和当前时间的时间差
let interval = Int(nowDate.timeIntervalSinceDate(createDate))
// 5.对时间间隔处理
// 5.1 显示刚刚
if interval < 60 {
return "刚刚"
}
// 5.2 59分钟前
if interval < 60 * 60 {
return "\(interval / 60)分钟前"
}
// 5.3 11小时前
if interval < 60 * 60 * 24 {
return "\(interval / (60 * 60))小时前"
}
// 5.4 创建日历对象
let calendar = NSCalendar.currentCalendar()
// 5.5 处理昨天数据: 昨天 12:23
if calendar.isDateInYesterday(createDate) {
fmt.dateFormat = "昨天 HH:mm"
let timerStr = fmt.stringFromDate(createDate)
return timerStr
}
// 5.6 处理一年之内 02-22 12:22
let cmps = calendar.components(.Year, fromDate: createDate, toDate: nowDate, options: [])
if cmps.year < 1 {
fmt.dateFormat = "MM-dd HH:mm"
let timeStr = fmt.stringFromDate(createDate)
return timeStr
}
// 5.7 超过一年 2014-02-12 13:22
fmt.dateFormat = "yyyy-MM-dd HH:mm"
let timeStr = fmt.stringFromDate(createDate)
return timeStr
}
} | 5e3a052652503ec804c338defe6734e4 | 24.955224 | 97 | 0.540852 | false | false | false | false |
cotkjaer/Silverback | refs/heads/master | Silverback/ArcView.swift | mit | 1 | //
// ArcView.swift
// Silverback
//
// Created by Christian Otkjær on 09/12/15.
// Copyright © 2015 Christian Otkjær. All rights reserved.
//
import UIKit
@IBDesignable
public class ArcView: UIView
{
@IBInspectable
public var width : CGFloat
{
set { arcLayer.arcWidth = newValue }
get { return arcLayer.arcWidth }
}
@IBInspectable
public var startDegrees: CGFloat
{
set { startAngle = degrees2radians(newValue) }
get { return radians2degrees(startAngle) }
}
public var startAngle: CGFloat
{
set { if clockwise { arcLayer.arcStartAngle = newValue } else { arcLayer.arcEndAngle = newValue } }
get { return clockwise ? arcLayer.arcStartAngle : arcLayer.arcEndAngle }
}
@IBInspectable
public var endDegrees: CGFloat
{
set { endAngle = degrees2radians(newValue) }
get { return radians2degrees(endAngle) }
}
public var endAngle: CGFloat
{
set { if !clockwise { arcLayer.arcStartAngle = newValue } else { arcLayer.arcEndAngle = newValue } }
get { return !clockwise ? arcLayer.arcStartAngle : arcLayer.arcEndAngle }
}
@IBInspectable
public var clockwise: Bool = true
{
didSet
{
if clockwise != oldValue
{
swap(&arcLayer.arcStartAngle, &arcLayer.arcEndAngle)
}
}
}
@IBInspectable
public var color: UIColor = UIColor.blackColor()
{
didSet { arcLayer.arcColor = color.CGColor }
}
// MARK: - Layout
public override func layoutSubviews()
{
super.layoutSubviews()
updateArc()
}
public override func layoutSublayersOfLayer(layer: CALayer)
{
super.layoutSublayersOfLayer(layer)
if layer == self.layer
{
updateArc()
}
}
// MARK: - Init
override public init(frame: CGRect)
{
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
func setup()
{
layer.addSublayer(arcLayer)
arcLayer.arcColor = color.CGColor
updateArc()
}
override public var bounds : CGRect { didSet { updateArc() } }
override public var frame : CGRect { didSet { updateArc() } }
// MARK: - Arc
private let arcLayer = ArcLayer()
func updateArc()
{
arcLayer.frame = bounds
}
}
// MARK: - CustomDebugStringConvertible
extension ArcView : CustomDebugStringConvertible
{
override public var debugDescription : String { return super.debugDescription + "<startDegrees = \(startDegrees), endDegrees = \(endDegrees), clockwise = \(clockwise), width = \(width)>" }
}
| 144a3ed1ba4fd84f174d05f36dd66f45 | 22.306452 | 192 | 0.586851 | false | false | false | false |
rwbutler/TypographyKit | refs/heads/master | TypographyKit/Classes/ParsingService.swift | mit | 1 | //
// ParsingService.swift
// TypographyKit
//
// Created by Ross Butler on 7/15/17.
//
//
import Foundation
import UIKit
typealias ConfigurationParsingResult = Result<ConfigurationModel, ConfigurationParsingError>
protocol ConfigurationParsingService {
func parse(_ data: Data) -> ConfigurationParsingResult
}
private enum CodingKeys {
static let buttons = "buttons"
static let colorsEntry = "typography-colors"
static let labels = "labels"
static let minimumPointSize = "minimum-point-size"
static let maximumPointSize = "maximum-point-size"
static let pointStepMultiplier = "point-step-multiplier"
static let pointStepSize = "point-step-size"
static let scalingMode = "scaling-mode"
static let stylesEntry = "ui-font-text-styles"
static let umbrellaEntry = "typography-kit"
}
typealias FontTextStyleEntries = [String: [String: Any]]
typealias ColorEntries = [String: Any]
extension ConfigurationParsingService {
// MARK: - Type definitions
fileprivate typealias ExtendedTypographyStyleEntry = (existingStyleName: String, newStyle: Typography)
func parse(_ configEntries: [String: Any]) -> ConfigurationParsingResult {
let configuration: ConfigurationSettings
if let typographyKitConfig = configEntries[CodingKeys.umbrellaEntry] as? [String: Any],
let stepSize = typographyKitConfig[CodingKeys.pointStepSize] as? Float,
let stepMultiplier = typographyKitConfig[CodingKeys.pointStepMultiplier] as? Float {
let buttonsConfig = typographyKitConfig[CodingKeys.buttons] as? [String: String]
let labelsConfig = typographyKitConfig[CodingKeys.labels] as? [String: String]
let buttonSettings = self.buttonSettings(buttonsConfig)
let labelSettings = self.labelSettings(labelsConfig)
let minimumPointSize = typographyKitConfig[CodingKeys.minimumPointSize] as? Float
let maximumPointSize = typographyKitConfig[CodingKeys.maximumPointSize] as? Float
let scalingMode = typographyKitConfig[CodingKeys.scalingMode] as? String
configuration = ConfigurationSettings(
buttons: buttonSettings,
labels: labelSettings,
minPointSize: minimumPointSize,
maxPointSize: maximumPointSize,
pointStepSize: stepSize,
pointStepMultiplier: stepMultiplier,
scalingMode: scalingMode
)
} else {
configuration = ConfigurationSettings(buttons: ButtonSettings(), labels: LabelSettings())
}
// Colors
let colorEntries = configEntries[CodingKeys.colorsEntry] as? ColorEntries ?? [:]
var colorParser = ColorParser(colors: colorEntries)
let typographyColors = colorParser.parseColors()
let uiColors = typographyColors.mapValues { $0.uiColor }
// Fonts
let fontTextStyles = configEntries[CodingKeys.stylesEntry] as? FontTextStyleEntries ?? [:]
var fontParser = FontTextStyleParser(textStyles: fontTextStyles, colorEntries: typographyColors)
let typographyStyles = fontParser.parseFonts()
return .success(ConfigurationModel(settings: configuration, colors: uiColors,
styles: typographyStyles))
}
/// Translates a dictionary of configuration settings into a `ButtonSettings` model object.
private func buttonSettings(_ config: [String: String]?) -> ButtonSettings {
guard let config = config, let lineBreakConfig = config["title-color-apply"],
let applyMode = UIButton.TitleColorApplyMode(string: lineBreakConfig) else {
return ButtonSettings()
}
return ButtonSettings(titleColorApplyMode: applyMode)
}
/// Translates a dictionary of configuration settings into a `LabelSettings` model object.
private func labelSettings(_ config: [String: String]?) -> LabelSettings {
guard let config = config, let lineBreakConfig = config["line-break"],
let lineBreak = NSLineBreakMode(string: lineBreakConfig) else {
return LabelSettings()
}
return LabelSettings(lineBreak: lineBreak)
}
}
| 8fc9c5b7f0f6b0773360a28f12560fa6 | 43.635417 | 106 | 0.685414 | false | true | false | false |
crossroadlabs/Express | refs/heads/master | Express/Headers.swift | gpl-3.0 | 1 | //===--- Headers.swift ----------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Swift Express.
//
//Swift Express is free software: you can redistribute it and/or modify
//it under the terms of the GNU Lesser General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//Swift Express is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import Foundation
import Future
public enum HttpHeader : String {
case ContentType = "Content-Type"
case ContentLength = "Content-Length"
func header(headers:Dictionary<String,String>) -> String? {
return headers[self.rawValue]
}
func headerInt(headers:Dictionary<String,String>) -> Int? {
return header(headers: headers).flatMap { str in Int(str) }
}
}
public protocol HttpHeadType {
var headers:Dictionary<String, String> {get}
}
public class HttpHead : HttpHeadType {
public let headers:Dictionary<String, String>
init(head:HttpHeadType) {
headers = head.headers
}
init(headers:Dictionary<String, String>) {
self.headers = headers
}
}
public protocol HttpResponseHeadType : HttpHeadType {
var status:UInt16 {get}
}
public class HttpResponseHead : HttpHead, HttpResponseHeadType, FlushableType {
public let status:UInt16
init(status:UInt16, head:HttpHeadType) {
self.status = status
super.init(head: head)
}
init(status:UInt16, headers:Dictionary<String, String>) {
self.status = status
super.init(headers: headers)
}
//all the code below should be moved to Streams+Headers and made as an extension
//unfortunately swift does not allow to override functions introduced in extensions yet
//should be moved as soon as the feature is implemented in swift
public func flushTo(out:DataConsumerType) -> Future<Void> {
if let headOut = out as? ResponseHeadDataConsumerType {
return headOut.consume(head: self)
} else {
return out.consume(data: serializeHead())
}
}
func serializeHead() -> Array<UInt8> {
//TODO: move to real serializer
var r = "HTTP/1.1 " + status.description + " OK\n"
for header in headers {
r += header.0 + ": " + header.1 + "\n"
}
r += "\n"
return Array(r.utf8)
}
}
| 0418b8e3cda18f212a97f2c72d4053d1 | 31.120879 | 91 | 0.633938 | false | false | false | false |
devpunk/cartesian | refs/heads/master | cartesian/View/DrawProject/Menu/VDrawProjectMenu.swift | mit | 1 | import UIKit
class VDrawProjectMenu:UIView
{
weak var layoutBottom:NSLayoutConstraint!
private weak var controller:CDrawProject!
private(set) weak var viewBar:VDrawProjectMenuBar!
private(set) weak var viewSettings:VDrawProjectMenuSettings!
private(set) weak var viewNodes:VDrawProjectMenuNodes!
private(set) weak var viewLabels:VDrawProjectMenuLabels!
private(set) weak var viewEdit:VDrawProjectMenuEdit!
private(set) weak var viewText:VDrawProjectMenuText!
private let kBarHeight:CGFloat = 51
private let kKeyboardAnimationDuration:TimeInterval = 0.3
init(controller:CDrawProject)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let viewBar:VDrawProjectMenuBar = VDrawProjectMenuBar(controller:controller)
self.viewBar = viewBar
let viewSettings:VDrawProjectMenuSettings = VDrawProjectMenuSettings(
controller:controller)
viewSettings.isHidden = true
self.viewSettings = viewSettings
let viewNodes:VDrawProjectMenuNodes = VDrawProjectMenuNodes(
controller:controller)
viewNodes.isHidden = true
self.viewNodes = viewNodes
let viewEdit:VDrawProjectMenuEdit = VDrawProjectMenuEdit(
controller:controller)
viewEdit.isHidden = true
self.viewEdit = viewEdit
let viewLabels:VDrawProjectMenuLabels = VDrawProjectMenuLabels(
controller:controller)
viewLabels.isHidden = true
self.viewLabels = viewLabels
let viewText:VDrawProjectMenuText = VDrawProjectMenuText(
controller:controller)
viewText.isHidden = true
self.viewText = viewText
let background:UIView = UIView()
background.isUserInteractionEnabled = false
background.backgroundColor = UIColor.white
background.translatesAutoresizingMaskIntoConstraints = false
addSubview(background)
addSubview(viewBar)
addSubview(viewSettings)
addSubview(viewNodes)
addSubview(viewLabels)
addSubview(viewEdit)
addSubview(viewText)
NSLayoutConstraint.topToTop(
view:viewBar,
toView:self)
NSLayoutConstraint.height(
view:viewBar,
constant:kBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:self)
layoutView(view:background)
layoutView(view:viewSettings)
layoutView(view:viewNodes)
layoutView(view:viewLabels)
layoutView(view:viewEdit)
layoutView(view:viewText)
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedKeyboardChanged(sender:)),
name:NSNotification.Name.UIKeyboardWillChangeFrame,
object:nil)
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
//MARK: notifications
func notifiedKeyboardChanged(sender notification:Notification)
{
guard
let userInfo:[AnyHashable:Any] = notification.userInfo,
let keyboardFrameValue:NSValue = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue,
let menuBottom:CGFloat = controller.modelMenuState.current?.bottom
else
{
return
}
let keyRect:CGRect = keyboardFrameValue.cgRectValue
let yOrigin = keyRect.origin.y
let height:CGFloat = UIScreen.main.bounds.maxY
let keyboardHeight:CGFloat
if yOrigin < height
{
keyboardHeight = -height + yOrigin + menuBottom
}
else
{
keyboardHeight = menuBottom
}
layoutBottom.constant = keyboardHeight
UIView.animate(withDuration:kKeyboardAnimationDuration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
//MARK: private
private func layoutView(view:UIView)
{
NSLayoutConstraint.topToBottom(
view:view,
toView:viewBar)
NSLayoutConstraint.bottomToBottom(
view:view,
toView:self)
NSLayoutConstraint.equalsHorizontal(
view:view,
toView:self)
}
//MARK: public
func displayNothing()
{
viewSettings.isHidden = true
viewNodes.isHidden = true
viewLabels.isHidden = true
viewEdit.isHidden = true
viewText.isHidden = true
viewBar.selectNothing()
}
func displayNode(model:DNode)
{
viewSettings.isHidden = true
viewNodes.isHidden = true
viewLabels.isHidden = true
viewEdit.isHidden = false
viewText.isHidden = true
viewEdit.loadNode(model:model)
viewBar.modeEdit()
}
func displaySettings()
{
viewSettings.isHidden = false
viewNodes.isHidden = true
viewLabels.isHidden = true
viewEdit.isHidden = true
viewText.isHidden = true
}
func displayNodes()
{
viewSettings.isHidden = true
viewNodes.isHidden = false
viewLabels.isHidden = true
viewEdit.isHidden = true
viewText.isHidden = true
}
func displayLabels()
{
viewSettings.isHidden = true
viewNodes.isHidden = true
viewLabels.isHidden = false
viewEdit.isHidden = true
viewText.isHidden = true
}
func displayText(model:DLabel)
{
viewSettings.isHidden = true
viewNodes.isHidden = true
viewLabels.isHidden = true
viewEdit.isHidden = true
viewText.isHidden = false
viewText.loadLabel(model:model)
}
}
| 8f2e9a620c44717e60b22a165a72aa0a | 27.686916 | 97 | 0.61541 | false | false | false | false |
alvinvarghese/GNTickerButton | refs/heads/master | Pod/Classes/GNTickerButton.swift | mit | 2 | //
// GNTickerButton.swift
// Letters
//
// Created by Gonzalo Nunez on 5/11/15.
// Copyright (c) 2015 Gonzalo Nunez. All rights reserved.
//
import UIKit
@objc public protocol GNTickerButtonRotationDelegate {
func tickerButtonTickerRotated(tickerButton button:GNTickerButton)
}
@IBDesignable public class GNTickerButton : UIButton {
static private let kInnerRingLineWidth:CGFloat = 1
static private let kOuterRingLineWidth:CGFloat = 4
static private let kOutterInnerRingSpacing:CGFloat = 6
static private let kTearDropRadius:CGFloat = 5
static private let kTickerRotationAnimationKey = "transform.rotation"
static private let kRingProgressAnimationKey = "strokeEnd"
static private let kRingProgressAnimationDuration = 0.15
@IBInspectable public var fillColor = UIColor(red: 251/255, green: 77/255, blue: 31/255, alpha: 1) {
didSet {
setNeedsDisplay()
}
}
@IBInspectable public var ringColor = UIColor.whiteColor() {
didSet {
setNeedsDisplay()
}
}
@IBInspectable public var tickerColor = UIColor.whiteColor() {
didSet {
setNeedsDisplay()
}
}
public var shouldShowRingProgress = true {
didSet {
ringLayer.hidden = !shouldShowRingProgress
}
}
private var isPressed : Bool = false {
didSet {
setNeedsDisplay()
}
}
private(set) var tickerIsSpinning = false
private var tickerLayer = CAShapeLayer()
private var ringLayer = CAShapeLayer()
private var desiredRotations:Int?
weak var delegate : GNTickerButtonRotationDelegate?
//MARK: - Initiliazation
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addTargets()
}
override public init(frame: CGRect) {
super.init(frame: frame)
addTargets()
}
//MARK: - Set Up
private func setUpTicker() {
tickerLayer.removeFromSuperlayer()
let centerX = CGRectGetMidX(bounds)
let centerY = CGRectGetMidY(bounds)
let outerRadius = outerRadiusInRect(bounds)
let innerRadius = outerRadius - GNTickerButton.kOutterInnerRingSpacing
let path = CGPathCreateMutable()
let padding = 8 as CGFloat
CGPathAddArc(path, nil, centerX, centerY, GNTickerButton.kTearDropRadius, CGFloat(2*M_PI), CGFloat(M_PI), false)
CGPathAddLineToPoint(path, nil, centerX, centerY - innerRadius + padding)
CGPathAddLineToPoint(path, nil, centerX + GNTickerButton.kTearDropRadius, centerY)
let tearDropHeight = innerRadius - padding
let boundingBox = CGPathGetBoundingBox(path)
let height = CGRectGetHeight(boundingBox)
let anchorY = 1 - (height - tearDropHeight)/height
tickerLayer.anchorPoint = CGPoint(x: 0.5, y: anchorY)
tickerLayer.position = CGPoint(x: CGRectGetMidX(layer.bounds), y: CGRectGetMidY(layer.bounds))
tickerLayer.bounds = boundingBox
tickerLayer.path = path
tickerLayer.fillColor = tickerColor.CGColor
tickerLayer.strokeColor = tickerColor.CGColor
layer.addSublayer(tickerLayer)
}
private func setUpRing() {
ringLayer.removeFromSuperlayer()
let rect = layer.bounds
let outerRadius = outerRadiusInRect(rect)
let centerX = CGRectGetMidX(rect)
let centerY = CGRectGetMidY(rect)
let ringPath = CGPathCreateMutable()
CGPathAddArc(ringPath, nil, centerX, centerY, outerRadius, CGFloat(-M_PI_2), CGFloat(M_PI_2*3), false)
ringLayer.path = ringPath
ringLayer.position = CGPoint(x: CGRectGetMidX(layer.bounds), y: CGRectGetMidY(layer.bounds))
ringLayer.bounds = CGPathGetBoundingBox(ringPath)
ringLayer.fillColor = UIColor.clearColor().CGColor
ringLayer.strokeColor = ringColor.CGColor
ringLayer.lineWidth = GNTickerButton.kOuterRingLineWidth
ringLayer.strokeEnd = 0
layer.addSublayer(ringLayer)
}
private func addTargets() {
addTarget(self, action: "touchDown", forControlEvents: .TouchDown)
addTarget(self, action: "touchUpInside", forControlEvents: .TouchUpInside)
addTarget(self, action: "touchUpOutside", forControlEvents: .TouchUpOutside)
}
@objc private func touchDown() {
isPressed = true
}
@objc private func touchUpInside() {
isPressed = false
}
@objc private func touchUpOutside() {
isPressed = false
}
//MARK: Public
public func rotateTickerWithDuration(duration:CFTimeInterval, rotations repeatCount:Int = 1, rotationBlock: (Void -> Void)?) {
_rotateTickerWithDuration(duration, rotations: repeatCount, shouldSetDesiredRotationCount: desiredRotations == nil, rotationBlock: rotationBlock)
}
public func stopRotatingTicker() {
tickerLayer.removeAnimationForKey(GNTickerButton.kTickerRotationAnimationKey)
}
public func clearRingProgress() {
CATransaction.begin()
CATransaction.setCompletionBlock() {
CATransaction.begin()
self.ringLayer.strokeStart = 0
self.ringLayer.strokeEnd = 0
CATransaction.commit()
}
ringLayer.strokeStart = 1
CATransaction.commit()
}
//MARK: Private
private func _rotateTickerWithDuration(duration:CFTimeInterval, rotations repeatCount:Int = 1, shouldSetDesiredRotationCount:Bool = true, rotationBlock: (Void -> Void)?) {
tickerIsSpinning = true
if (shouldSetDesiredRotationCount) {
desiredRotations = repeatCount
}
let rotationAnimation = CABasicAnimation(keyPath: GNTickerButton.kTickerRotationAnimationKey)
rotationAnimation.duration = duration
rotationAnimation.fromValue = 0
rotationAnimation.toValue = 2*M_PI
rotationAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
var repeats = repeatCount
CATransaction.begin()
CATransaction.setCompletionBlock() {
dispatch_async(dispatch_get_main_queue()) {
self.updateRingProgress(repeatCount, animated: true)
if (rotationBlock != nil) {
rotationBlock!()
} else {
self.delegate?.tickerButtonTickerRotated(tickerButton: self)
}
if (repeats > 0) {
self.rotateTickerWithDuration(duration, rotations: --repeats, rotationBlock: rotationBlock)
} else {
self.desiredRotations = nil
self.tickerIsSpinning = false
}
}
}
tickerLayer.addAnimation(rotationAnimation, forKey: GNTickerButton.kTickerRotationAnimationKey)
CATransaction.commit()
}
private func updateRingProgress(rotationsLeft:Int, animated:Bool) {
var strokeEnd = 0 as CGFloat
if (desiredRotations != nil) {
strokeEnd = CGFloat((desiredRotations! - rotationsLeft)) / CGFloat(desiredRotations!)
}
let fillAnimation = CABasicAnimation(keyPath: GNTickerButton.kRingProgressAnimationKey)
fillAnimation.duration = animated ? GNTickerButton.kRingProgressAnimationDuration : 0
fillAnimation.fromValue = ringLayer.strokeEnd
fillAnimation.toValue = strokeEnd
fillAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
ringLayer.strokeEnd = strokeEnd
CATransaction.begin()
ringLayer.addAnimation(fillAnimation, forKey: GNTickerButton.kRingProgressAnimationKey)
CATransaction.commit()
}
//MARK: - Drawing
override public func drawRect(rect: CGRect) {
super.drawRect(rect)
func addCircleInContext(context:CGContextRef, centerX:CGFloat, centerY:CGFloat, radius:CGFloat) {
CGContextAddArc(context, centerX, centerY, radius, CGFloat(0), CGFloat(2*M_PI), 0)
}
let context = UIGraphicsGetCurrentContext()
let color = isPressed ? fillColor.colorWithAlphaComponent(0.5) : fillColor
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextSetStrokeColorWithColor(context, ringColor.CGColor)
let outerRadius = outerRadiusInRect(rect)
let innerRadius = outerRadius - GNTickerButton.kOutterInnerRingSpacing
let centerX = CGRectGetMidX(rect)
let centerY = CGRectGetMidY(rect)
// Inner Circle
addCircleInContext(context, centerX, centerY, innerRadius)
CGContextFillPath(context)
// Inner Ring
CGContextSetLineWidth(context, GNTickerButton.kInnerRingLineWidth)
addCircleInContext(context, centerX, centerY, innerRadius)
CGContextStrokePath(context)
}
override public func drawLayer(layer: CALayer!, inContext ctx: CGContext!) {
super.drawLayer(layer, inContext: ctx)
setUpTicker()
setUpRing()
}
//MARK - Helpers
private func outerRadiusInRect(rect:CGRect) -> CGFloat {
return rect.width/2 - 2
}
} | dcfb60025e4c91cf216b80f20f1e9db2 | 33.588448 | 175 | 0.643528 | false | false | false | false |
vapor/vapor | refs/heads/main | Sources/Vapor/Concurrency/Request+Concurrency.swift | mit | 1 | #if compiler(>=5.7) && canImport(_Concurrency)
import NIOCore
import NIOConcurrencyHelpers
// MARK: - Request.Body.AsyncSequenceDelegate
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
extension Request.Body {
/// `Request.Body.AsyncSequenceDelegate` bridges between EventLoop
/// and AsyncSequence. Crucially, this type handles backpressure
/// by synchronizing bytes on the `EventLoop`
///
/// `AsyncSequenceDelegate` can be created and **must be retained**
/// in `Request.Body/makeAsyncIterator()` method.
fileprivate final class AsyncSequenceDelegate: @unchecked Sendable, NIOAsyncSequenceProducerDelegate {
private enum State {
case noSignalReceived
case waitingForSignalFromConsumer(EventLoopPromise<Void>)
}
private var _state: State = .noSignalReceived
private let eventLoop: any EventLoop
init(eventLoop: any EventLoop) {
self.eventLoop = eventLoop
}
private func produceMore0() {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
preconditionFailure()
case .waitingForSignalFromConsumer(let promise):
self._state = .noSignalReceived
promise.succeed(())
}
}
private func didTerminate0() {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
// we will inform the producer, since the next write will fail.
break
case .waitingForSignalFromConsumer(let promise):
self._state = .noSignalReceived
promise.fail(CancellationError())
}
}
func registerBackpressurePromise(_ promise: EventLoopPromise<Void>) {
self.eventLoop.preconditionInEventLoop()
switch self._state {
case .noSignalReceived:
self._state = .waitingForSignalFromConsumer(promise)
case .waitingForSignalFromConsumer:
preconditionFailure()
}
}
func didTerminate() {
self.eventLoop.execute { self.didTerminate0() }
}
func produceMore() {
self.eventLoop.execute { self.produceMore0() }
}
}
}
// MARK: - Request.Body.AsyncSequence
@available(macOS 12, iOS 15, watchOS 8, tvOS 15, *)
extension Request.Body: AsyncSequence {
public typealias Element = ByteBuffer
/// This wrapper generalizes our implementation.
/// `RequestBody.AsyncIterator` is the override point for
/// using another implementation
public struct AsyncIterator: AsyncIteratorProtocol {
public typealias Element = ByteBuffer
fileprivate typealias Underlying = NIOThrowingAsyncSequenceProducer<ByteBuffer, any Error, NIOAsyncSequenceProducerBackPressureStrategies.HighLowWatermark, Request.Body.AsyncSequenceDelegate>.AsyncIterator
private var underlying: Underlying
fileprivate init(underlying: Underlying) {
self.underlying = underlying
}
public mutating func next() async throws -> ByteBuffer? {
return try await self.underlying.next()
}
}
/// Checks that the request has a body suitable for an AsyncSequence
///
/// AsyncSequence streaming should use a body of type .stream().
/// Using `.collected(_)` will load the entire request into memory
/// which should be avoided for large file uploads.
///
/// Example: app.on(.POST, "/upload", body: .stream) { ... }
private func checkBodyStorage() {
switch request.bodyStorage {
case .stream(_):
break
case .collected(_):
break
default:
preconditionFailure("""
AsyncSequence streaming should use a body of type .stream()
Example: app.on(.POST, "/upload", body: .stream) { ... }
""")
}
}
/// Generates an `AsyncIterator` to stream the body’s content as
/// `ByteBuffer` sequences. This implementation supports backpressure using
/// `NIOAsyncSequenceProducerBackPressureStrategies`
/// - Returns: `AsyncIterator` containing the `Requeset.Body` as a
/// `ByteBuffer` sequence
public func makeAsyncIterator() -> AsyncIterator {
let delegate = AsyncSequenceDelegate(eventLoop: request.eventLoop)
let producer = NIOThrowingAsyncSequenceProducer.makeSequence(
elementType: ByteBuffer.self,
failureType: Error.self,
backPressureStrategy: NIOAsyncSequenceProducerBackPressureStrategies
.HighLowWatermark(lowWatermark: 5, highWatermark: 20),
delegate: delegate
)
let source = producer.source
self.drain { streamResult in
switch streamResult {
case .buffer(let buffer):
// Send the buffer to the async sequence
let result = source.yield(buffer)
// Inspect the source view and handle outcomes
switch result {
case .dropped:
// The consumer dropped the sequence.
// Inform the producer that we don't want more data
// by returning an error in the future.
return request.eventLoop.makeFailedFuture(CancellationError())
case .stopProducing:
// The consumer is too slow.
// We need to create a promise that we succeed later.
let promise = request.eventLoop.makePromise(of: Void.self)
// We pass the promise to the delegate so that we can succeed it,
// once we get a call to `delegate.produceMore()`.
delegate.registerBackpressurePromise(promise)
// return the future that we will fulfill eventually.
return promise.futureResult
case .produceMore:
// We can produce more immidately. Return a succeeded future.
return request.eventLoop.makeSucceededVoidFuture()
}
case .error(let error):
source.finish(error)
return request.eventLoop.makeSucceededVoidFuture()
case .end:
source.finish()
return request.eventLoop.makeSucceededVoidFuture()
}
}
return AsyncIterator(underlying: producer.sequence.makeAsyncIterator())
}
}
#endif
| 2337d2dd6f6a5ec1fc0fb22f7c882974 | 38.216374 | 213 | 0.605279 | false | false | false | false |
WaterReporter/WaterReporter-iOS | refs/heads/master | WaterReporter/WaterReporter/NewReportTableViewController.swift | agpl-3.0 | 1 | //
// NewReportTableViewController.swift
// WaterReporter
//
// Created by Viable Industries on 7/24/16.
// Copyright © 2016 Viable Industries, L.L.C. All rights reserved.
//
import Alamofire
import CoreLocation
import Mapbox
import OpenGraph
import SwiftyJSON
import UIKit
class NewReportTableViewController: UITableViewController, UIImagePickerControllerDelegate, UITextViewDelegate, UINavigationControllerDelegate, CLLocationManagerDelegate, MGLMapViewDelegate, NewReportLocationSelectorDelegate {
//
// MARK: @IBOutlets
//
@IBOutlet weak var navigationBarButtonSave: UIBarButtonItem!
@IBOutlet var indicatorLoadingView: UIView!
//
// MARK: @IBActions
//
@IBAction func launchNewReportLocationSelector(sender: UIButton) {
self.performSegueWithIdentifier("setLocationForNewReport", sender: sender)
}
@IBAction func attemptOpenPhotoTypeSelector(sender: AnyObject) {
let thisActionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let cameraAction = UIAlertAction(title: "Camera", style: .Default, handler:self.cameraActionHandler)
thisActionSheet.addAction(cameraAction)
let photoLibraryAction = UIAlertAction(title: "Photo Library", style: .Default, handler:self.photoLibraryActionHandler)
thisActionSheet.addAction(photoLibraryAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
thisActionSheet.addAction(cancelAction)
presentViewController(thisActionSheet, animated: true, completion: nil)
}
@IBAction func buttonSaveNewReportTableViewController(sender: UIBarButtonItem) {
let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken")
let headers = [
"Authorization": "Bearer " + (accessToken! as! String)
]
self.attemptNewReportSave(headers)
}
@IBAction func selectGroup(sender: UISwitch) {
if sender.on {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups.append(_organization_id_number)
print("addGroup::finished::tempGroups \(self.tempGroups)")
} else {
let _organization_id_number: String! = "\(self.groups!["features"][sender.tag]["properties"]["organization_id"])"
self.tempGroups = self.tempGroups.filter() {$0 != _organization_id_number}
print("removeGroup::finished::tempGroups \(self.tempGroups)")
}
}
//
// MARK: Variables
//
var loadingView: UIView!
var userSelectedCoorindates: CLLocationCoordinate2D!
var imageReportImagePreviewIsSet:Bool = false
var thisLocationManager: CLLocationManager = CLLocationManager()
var tempGroups: [String] = [String]()
var groups: JSON?
var reportImage: UIImage!
var reportDescription: String = "Write a few words about the photo or paste a link..."
var hashtagAutocomplete: [String] = [String]()
var hashtagSearchEnabled: Bool = false
var dataSource: HashtagTableView = HashtagTableView()
var hashtagSearchTimer: NSTimer = NSTimer()
var og_paste: String!
var og_active: Bool = false
var og_title: String!
var og_description: String!
var og_sitename: String!
var og_type: String!
var og_image: String!
var og_url: String!
//
// MARK: Overrides
//
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
//
// Load default list of groups into the form
//
self.attemptLoadUserGroups()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(true)
if self.tabBarController?.selectedIndex != 2 {
//
// When navigating away from this tab the Commons team wants this
// form to clear out.
//
// Reset all fields
self.imageReportImagePreviewIsSet = false
self.reportDescription = "Write a few words about the photo or paste a link..."
self.reportImage = nil
self.og_paste = ""
self.og_active = false
self.og_title = ""
self.og_description = ""
self.og_sitename = ""
self.og_type = ""
self.og_image = ""
self.og_url = ""
self.tempGroups = [String]()
self.tableView.reloadData()
self.userSelectedCoorindates = nil
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
}
override func viewDidLoad() {
super.viewDidLoad()
//
// Make sure we are getting 'auto layout' specific sizes
// otherwise any math we do will be messed up
//
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
self.navigationItem.title = "New Report"
self.tableView.backgroundColor = UIColor.colorBackground(1.00)
self.dataSource.parent = self
//
// Setup Navigation Bar
//
navigationBarButtonSave.target = self
navigationBarButtonSave.action = #selector(buttonSaveNewReportTableViewController(_:))
}
//
// MARK: Advanced TextView Interactions
//
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
// [text isEqualToString:[UIPasteboard generalPasteboard].string]
let _pasteboard = UIPasteboard.generalPasteboard().string
if (text == _pasteboard) {
//
// Step 1: Get the information being pasted
//
print("Pasting text", _pasteboard)
// _pasteboard = _pasteboard!.stringByRemovingPercentEncoding!.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
if let checkedUrl = NSURL(string: _pasteboard!) {
//
// Step 2: Check to see if the text being pasted is a link
//
OpenGraph.fetch(checkedUrl) { og, error in
print("Open Graph \(og)")
self.og_paste = "\(checkedUrl)"
if og?[.title] != nil {
let _og_title = og?[.title]!.stringByDecodingHTMLEntities
self.og_title = "\(_og_title!)"
}
else {
self.og_title = ""
}
if og?[.description] != nil {
let _og_description_encoded = og?[.description]!
let _og_description = _og_description_encoded?.stringByDecodingHTMLEntities
self.og_description = "\(_og_description!)"
self.reportDescription = "\(_og_description!)"
}
else {
self.og_description = ""
}
if og?[.type] != nil {
let _og_type = og?[.type]!
self.og_type = "\(_og_type!)"
}
else {
self.og_type = ""
}
if og?[.image] != nil {
let _ogImage = og?[.image]!
print("_ogImage \(_ogImage!)")
if let imageURL = NSURL(string: _ogImage!) {
self.og_image = "\(imageURL)"
}
else {
let _tmpImage = "\(_ogImage!)"
let _image = _tmpImage.characters.split{$0 == " "}.map(String.init)
if _image.count >= 1 {
var _imageUrl = _image[0]
if let imageURLRange = _imageUrl.rangeOfString("?") {
_imageUrl.removeRange(imageURLRange.startIndex..<_imageUrl.endIndex)
self.og_image = "\(_imageUrl)"
}
}
}
}
else {
self.og_image = ""
}
if og?[.url] != nil {
let _og_url = og?[.url]!
self.og_url = "\(_og_url!)"
}
else {
self.og_url = ""
}
if self.og_url != "" && self.og_image != "" {
self.og_active = true
}
// We need to wait for all other tasks to finish before
// executing the table reload
//
NSOperationQueue.mainQueue().addOperationWithBlock {
self.tableView.reloadData()
}
}
}
return true
}
return false
}
func textViewDidBeginEditing(textView: UITextView) {
if textView.text == "Write a few words about the photo or paste a link..." {
textView.text = ""
}
}
func textViewDidChange(textView: UITextView) {
let _text: String = "\(textView.text)"
// let _index = NSIndexPath.init(forRow: 0, inSection: 0)
// Always make sure we are constantly copying what is entered into the
// remote text field into this controller so that we can pass it along
// to the report save methods.
//
self.reportDescription = _text
// if _text != "" && _text.characters.last! == "#" {
// self.hashtagSearchEnabled = true
//
// print("Hashtag Search: Found start of hashtag")
// }
// else if _text != "" && self.hashtagSearchEnabled == true && _text.characters.last! == " " {
// self.hashtagSearchEnabled = false
// self.dataSource.results = [String]()
//
//// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None)
//
// print("Hashtag Search: Disabling search because space was entered")
// print("Hashtag Search: Timer reset to zero due to search termination (space entered)")
// self.hashtagSearchTimer.invalidate()
//
// }
// else if _text != "" && self.hashtagSearchEnabled == true {
//
// self.dataSource.results = [String]()
//
//// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None)
//
// // Identify hashtag search
// //
// let _hashtag_identifier = _text.rangeOfString("#", options:NSStringCompareOptions.BackwardsSearch)
// if ((_hashtag_identifier) != nil) {
// let _hashtag_search: String! = _text.substringFromIndex((_hashtag_identifier?.endIndex)!)
//
// // Add what the user is typing to the top of the list
// //
// print("Hashtag Search: Performing search for \(_hashtag_search)")
//
// dataSource.results = ["\(_hashtag_search)"]
// dataSource.search = "\(_hashtag_search)"
//
// dataSource.numberOfRowsInSection(dataSource.results.count)
//
//// self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None)
//
// // Execute the serverside search BUT wait a few milliseconds between
// // each character so we aren't returning inconsistent results to
// // the user
// //
// print("Hashtag Search: Timer reset to zero")
// self.hashtagSearchTimer.invalidate()
//
// print("Hashtag Search: Send this to search methods \(_hashtag_search) after delay expires")
//// self.hashtagSearchTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: #selector(self.searchHashtags(_:)), userInfo: _hashtag_search, repeats: false)
//
// }
//
// }
}
//
// MARK: Custom TextView Functionality
//
func focusTextView() {
}
//
// MARK: Table Overrides
//
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView:UITableView, numberOfRowsInSection section: Int) -> Int {
var numberOfRows: Int = 2
if section == 0 {
numberOfRows = 2
// if self.dataSource.results != nil {
// let numberOfHashtags: Int = (self.dataSource.results.count)
// numberOfRows = numberOfHashtags
// }
} else if section == 1 {
if self.groups != nil {
let numberOfGroups: Int = (self.groups?["features"].count)!
numberOfRows = (numberOfGroups)
}
}
return numberOfRows
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCellWithIdentifier("newReportContentTableViewCell", forIndexPath: indexPath) as! NewReportContentTableViewCell
// Report Image
//
cell.buttonReportAddImage.addTarget(self, action: #selector(NewReportTableViewController.attemptOpenPhotoTypeSelector(_:)), forControlEvents: .TouchUpInside)
if (self.reportImage != nil) {
cell.imageReportImage.image = self.reportImage
}
else {
cell.imageReportImage.image = UIImage(named: "icon--camera")
}
// Report Description
//
if self.reportDescription != "" {
cell.textviewReportDescription.text = self.reportDescription
}
cell.textviewReportDescription.delegate = self
cell.textviewReportDescription.targetForAction(#selector(self.textViewDidChange(_:)), withSender: self)
// Report Description > Hashtag Type Ahead
//
cell.tableViewHashtag.delegate = self.dataSource
cell.tableViewHashtag.dataSource = self.dataSource
if self.hashtagSearchEnabled == true {
cell.tableViewHashtag.hidden = false
cell.typeAheadHeight.constant = 128.0
}
else {
cell.tableViewHashtag.hidden = true
cell.typeAheadHeight.constant = 0.0
}
// Report Description > Open Graph
//
if self.og_active {
cell.ogView.hidden = false
cell.ogViewHeightConstraint.constant = 256.0
// Open Graph > Title
//
cell.ogTitle.text = self.og_title
// Open Graph > Description
//
cell.ogDescription.text = self.og_description
// Open Graph > Image
//
if self.og_image != "" {
let ogImageURL:NSURL = NSURL(string: "\(self.og_image)")!
cell.ogImage.kf_indicatorType = .Activity
cell.ogImage.kf_showIndicatorWhenLoading = true
cell.ogImage.kf_setImageWithURL(ogImageURL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: {
(image, error, cacheType, imageUrl) in
cell.ogImage.image = image
if (self.imageReportImagePreviewIsSet == false) {
self.reportImage = image
self.imageReportImagePreviewIsSet = true
self.tableView.reloadData()
}
})
}
}
else {
cell.ogView.hidden = true
cell.ogViewHeightConstraint.constant = 0.0
}
return cell
}
else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("newReportLocationTableViewCell", forIndexPath: indexPath) as! NewReportLocationTableViewCell
print("Location Row")
// Display location selection map when Confirm Location button is
// tapped/touched
//
cell.buttonChangeLocation.addTarget(self, action: #selector(self.launchNewReportLocationSelector(_:)), forControlEvents: .TouchUpInside)
// Update the text display for the user selected coordinates when
// the self.userSelectedCoorindates variable is not empty
//
print("self.userSelectedCoorindates \(self.userSelectedCoorindates)")
if self.userSelectedCoorindates != nil {
cell.labelLocation.text = String(self.userSelectedCoorindates.longitude) + " " + String(self.userSelectedCoorindates.latitude)
}
else {
cell.labelLocation.text = "Confirm location"
}
return cell
}
}
else if indexPath.section == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier("newReportGroupTableViewCell", forIndexPath: indexPath) as! NewReportGroupTableViewCell
guard (self.groups != nil) else { return cell }
let _index = indexPath.row
let group = self.groups?["features"][_index]
if group != nil {
// Organization Logo
//
cell.imageGroupLogo.tag = _index
cell.imageGroupLogo.tag = indexPath.row
let organizationImageUrl:NSURL = NSURL(string: "\(group!["properties"]["organization"]["properties"]["picture"])")!
cell.imageGroupLogo.kf_indicatorType = .Activity
cell.imageGroupLogo.kf_showIndicatorWhenLoading = true
cell.imageGroupLogo.kf_setImageWithURL(organizationImageUrl, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: {
(image, error, cacheType, imageUrl) in
cell.imageGroupLogo.image = image
cell.imageGroupLogo.layer.cornerRadius = cell.imageGroupLogo.frame.size.width / 2
cell.imageGroupLogo.clipsToBounds = true
})
// Organization Name
//
cell.labelGroupName.text = "\(group!["properties"]["organization"]["properties"]["name"])"
// Organization Switch/Selection
//
cell.switchGroupSelect.tag = _index
if let _organization_id_number = self.groups?["features"][indexPath.row]["properties"]["organization_id"] {
if self.tempGroups.contains("\(_organization_id_number)") {
cell.switchGroupSelect.on = true
}
else {
cell.switchGroupSelect.on = false
}
}
}
return cell
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var rowHeight: CGFloat = 44.0
if indexPath.section == 0 {
// if (indexPath.row == 1 && self.hashtagTypeAhead.hidden == false) {
if (indexPath.row == 0) {
if (self.og_active == false) {
if (self.hashtagSearchEnabled == true) {
rowHeight = 288.0
}
else if (self.hashtagSearchEnabled == false) {
rowHeight = 128.0
}
}
else if (self.og_active == true) {
if (self.hashtagSearchEnabled == true) {
rowHeight = 527.0
}
else if (self.hashtagSearchEnabled == false) {
rowHeight = 384.0
}
}
else {
rowHeight = 128.0
}
}
}
else if indexPath.section == 1 {
rowHeight = 72.0
}
return rowHeight
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let segueId = segue.identifier else { return }
switch segueId {
case "setLocationForNewReport":
let destinationNavigationViewController = segue.destinationViewController as! UINavigationController
let destinationNewReportLocationSelectorViewController = destinationNavigationViewController.topViewController as! NewReportLocationSelector
destinationNewReportLocationSelectorViewController.delegate = self
destinationNewReportLocationSelectorViewController.userSelectedCoordinates = self.userSelectedCoorindates
break
default:
break
}
}
func onSetCoordinatesComplete(isFinished: Bool) { return }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//
// MARK: Custom Statuses
//
func saving() {
//
// Create a view that covers the entire screen
//
self.loadingView = self.indicatorLoadingView
self.loadingView.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.view.addSubview(self.loadingView)
self.view.bringSubviewToFront(self.loadingView)
//
// Make sure that the Done/Save button is disabled
//
self.navigationItem.rightBarButtonItem?.enabled = false
//
// Make sure our view is scrolled to the top
//
self.tableView.setContentOffset(CGPointZero, animated: false)
}
func finishedSaving() {
//
// Create a view that covers the entire screen
//
self.loadingView.removeFromSuperview()
//
// Make sure that the Done/Save button is disabled
//
self.navigationItem.rightBarButtonItem?.enabled = true
//
// Make sure our view is scrolled to the top
//
self.tableView.setContentOffset(CGPointZero, animated: false)
// Reset all fields
self.imageReportImagePreviewIsSet = false
self.reportDescription = "Write a few words about the photo or paste a link..."
self.reportImage = nil
self.og_paste = ""
self.og_active = false
self.og_title = ""
self.og_description = ""
self.og_sitename = ""
self.og_type = ""
self.og_image = ""
self.og_url = ""
self.tempGroups = [String]()
self.tableView.reloadData()
self.userSelectedCoorindates = nil
}
func finishedSavingWithError() {
self.navigationItem.rightBarButtonItem?.enabled = true
}
//
// MARK: Camera Functionality
//
func cameraActionHandler(action:UIAlertAction) -> Void {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func photoLibraryActionHandler(action:UIAlertAction) -> Void {
if (UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = true
self.presentViewController(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
// Change the default camera icon to a preview of the image the user
// has selected to be their report image.
//
self.reportImage = image
self.imageReportImagePreviewIsSet = true
// Refresh the table view to display the updated image data
//
self.dismissViewControllerAnimated(true, completion: {
self.tableView.reloadData()
})
}
//
// MARK: Location Child Delegate
//
func sendCoordinates(coordinates: CLLocationCoordinate2D) {
print("PARENT:sendCoordinates see \(coordinates)")
// Pass off coorindates to the self.userSelectedCoordinates
//
self.userSelectedCoorindates = coordinates
// Update the display of the returned coordinates in the "Confirm
// Location" table view cell label
//
self.tableView.reloadData()
}
//
// MARK: Server Request/Response functionality
//
func displayErrorMessage(title: String, message: String) {
let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
}
func buildRequestHeaders() -> [String: String] {
let accessToken = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountAccessToken")
return [
"Authorization": "Bearer " + (accessToken! as! String)
]
}
func attemptNewReportSave(headers: [String: String]) {
//
// Error Check for Geometry
//
var geometryCollection: [String: AnyObject] = [
"type": "GeometryCollection"
]
if (self.userSelectedCoorindates != nil) {
var geometry: [String: AnyObject] = [
"type": "Point"
]
let coordinates: Array = [
self.userSelectedCoorindates.longitude,
self.userSelectedCoorindates.latitude
]
geometry["coordinates"] = coordinates
let geometries: [AnyObject] = [geometry]
geometryCollection["geometries"] = geometries
}
else {
self.displayErrorMessage("Location Field Empty", message: "Please add a location to your report before saving")
self.finishedSavingWithError()
return
}
//
// Check image value
//
if (!imageReportImagePreviewIsSet) {
self.displayErrorMessage("Image Field Empty", message: "Please add an image to your report before saving")
self.finishedSavingWithError()
return
}
// Before starting the saving process, hide the form
// and show the user the saving indicator
self.saving()
//
// REPORT DATE
//
let dateFormatter = NSDateFormatter()
let date = NSDate()
dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
dateFormatter.timeStyle = NSDateFormatterStyle.NoStyle
let report_date: String = dateFormatter.stringFromDate(date)
print("report_date \(report_date)")
//
// PARAMETERS
//
if self.reportDescription == "Write a few words about the photo or paste a link..." {
self.reportDescription = ""
}
var parameters: [String: AnyObject] = [
"report_description": self.reportDescription,
"report_date": report_date,
"is_public": "true",
"geometry": geometryCollection,
"state": "open"
]
//
// GROUPS
//
var _temporary_groups: [AnyObject] = [AnyObject]()
for _organization_id in tempGroups {
print("group id \(_organization_id)")
let _group = [
"id": "\(_organization_id)",
]
_temporary_groups.append(_group)
}
parameters["groups"] = _temporary_groups
//
// OPEN GRAPH
//
var open_graph: [AnyObject] = [AnyObject]()
if self.og_active {
let _social = [
"og_title": self.og_title,
"og_type": self.og_type,
"og_url": self.og_url,
"og_image_url": self.og_image,
"og_description": self.og_description
]
open_graph.append(_social)
}
parameters["social"] = open_graph
//
// Make request
//
if (self.reportImage != nil) {
Alamofire.upload(.POST, Endpoints.POST_IMAGE, headers: headers, multipartFormData: { multipartFormData in
// import image to request
if let imageData = UIImageJPEGRepresentation(self.reportImage!, 1) {
multipartFormData.appendBodyPart(data: imageData, name: "image", fileName: "ReportImageFromiPhone.jpg", mimeType: "image/jpeg")
}
}, encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON { response in
print("Image uploaded \(response)")
if let value = response.result.value {
let imageResponse = JSON(value)
let image = [
"id": String(imageResponse["id"].rawValue)
]
let images: [AnyObject] = [image]
parameters["images"] = images
print("parameters \(parameters)")
Alamofire.request(.POST, Endpoints.POST_REPORT, parameters: parameters, headers: headers, encoding: .JSON)
.responseJSON { response in
print("Response \(response)")
switch response.result {
case .Success(let value):
print("Response Sucess \(value)")
// Hide the loading indicator
self.finishedSaving()
// Send user to the Activty Feed
self.tabBarController?.selectedIndex = 0
case .Failure(let error):
print("Response Failure \(error)")
break
}
}
}
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
}
func attemptLoadUserGroups() {
// Set headers
let _headers = self.buildRequestHeaders()
if let userId = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountUID") as? NSNumber {
let GET_GROUPS_ENDPOINT = Endpoints.GET_USER_PROFILE + "\(userId)" + "/groups"
Alamofire.request(.GET, GET_GROUPS_ENDPOINT, headers: _headers, encoding: .JSON).responseJSON { response in
print("response.result \(response.result)")
switch response.result {
case .Success(let value):
// print("Request Success for Groups: \(value)")
// Assign response to groups variable
self.groups = JSON(value)
// Refresh the data in the table so the newest items appear
self.tableView.reloadData()
break
case .Failure(let error):
print("Request Failure: \(error)")
break
}
}
} else {
self.attemptRetrieveUserID()
}
}
func attemptRetrieveUserID() {
// Set headers
let _headers = self.buildRequestHeaders()
Alamofire.request(.GET, Endpoints.GET_USER_ME, headers: _headers, encoding: .JSON)
.responseJSON { response in
switch response.result {
case .Success(let value):
let json = JSON(value)
if let data: AnyObject = json.rawValue {
NSUserDefaults.standardUserDefaults().setValue(data["id"], forKeyPath: "currentUserAccountUID")
self.attemptLoadUserGroups()
}
case .Failure(let error):
print(error)
}
}
}
//
// MARK: Hashtag
//
func searchHashtags(timer: NSTimer) {
let queryText: String! = "\(timer.userInfo!)"
print("searchHashtags fired with \(queryText)")
//
// Send a request to the defined endpoint with the given parameters
//
let parameters = [
"q": "{\"filters\": [{\"name\":\"tag\",\"op\":\"like\",\"val\":\"\(queryText)%\"}]}"
]
Alamofire.request(.GET, Endpoints.GET_MANY_HASHTAGS, parameters: parameters)
.responseJSON { response in
switch response.result {
case .Success(let value):
let _results = JSON(value)
// print("self.dataSource >>>> _results \(_results)")
for _result in _results["features"] {
print("_result \(_result.1["properties"]["tag"])")
let _tag = "\(_result.1["properties"]["tag"])"
self.dataSource.results.append(_tag)
}
self.dataSource.numberOfRowsInSection(_results["features"].count)
let _index = NSIndexPath.init(forRow: 0, inSection: 0)
self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None)
case .Failure(let error):
print(error)
break
}
}
}
func selectedValue(value: String, searchText: String) {
let _index = NSIndexPath.init(forRow: 0, inSection: 0)
let _selection = "\(value)"
print("Hashtag Selected, now we need to update the textview with selected \(value) and search text \(searchText) so that it makes sense with \(self.reportDescription)")
let _temporaryCopy = self.reportDescription
let _updatedDescription = _temporaryCopy.stringByReplacingOccurrencesOfString(searchText, withString: _selection, options: NSStringCompareOptions.LiteralSearch, range: nil)
print("Updated Text \(_updatedDescription)")
// Add the hashtag to the text
//
self.reportDescription = "\(_updatedDescription)"
// Reset the search
//
self.hashtagSearchEnabled = false
self.dataSource.results = [String]()
self.tableView.reloadRowsAtIndexPaths([_index], withRowAnimation: UITableViewRowAnimation.None)
print("Hashtag Search: Timer reset to zero due to user selection")
self.hashtagSearchTimer.invalidate()
}
}
| 11d8b44a159ac2c635ad67c42fd70080 | 34.907609 | 226 | 0.50116 | false | false | false | false |
xdliu002/TongjiAppleClubDeviceManagement | refs/heads/master | TAC-DM/SettingEntryViewController.swift | mit | 1 | //
// SettingEntryViewController.swift
// TAC-DM
//
// Created by Harold Liu on 8/21/15.
// Copyright (c) 2015 TAC. All rights reserved.
//
import UIKit
// MARK:- NO NEED TO CHAGNE THIS CONTROLLER
class SettingEntryViewController: UIViewController, DMDelegate {
@IBOutlet var typeButtons: [UIButton]!
var dmModel:DatabaseModel!
var umbrellaInfo:BorrowItem?
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
dmModel = DatabaseModel.getInstance()
dmModel.delegate = self
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
SVProgressHUD.show()
}
//更新雨伞的借出情况
func updateUI() {
if let id = umbrellaId {
dmModel.getDevice(id)
} else {
print("unget umbrella id")
SVProgressHUD.showErrorWithStatus("无法获得雨伞信息,请后退刷新界面")
}
}
func configureUI()
{
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "setting background")?.drawInRect(self.view.bounds)
let image :UIImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
for button:UIButton in typeButtons {
button.layer.cornerRadius = button.frame.height/2
}
}
@IBAction func backAction(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toSettingChangeVC" {
if let nextVC = segue.destinationViewController as? SettingChangeViewController {
if let umbrella = umbrellaInfo {
nextVC.title = "Setting Umbrella"
nextVC.itemId = umbrella.id
nextVC.itemCount = umbrella.count
nextVC.itemLeftCount = umbrella.leftCount
} else {
nextVC.title = "无法获得雨伞信息,请后退刷新界面"
}
}
}
if segue.identifier == "bookSettingTableVC"
{
if let nextVC = segue.destinationViewController as? SettingTableView
{
nextVC.title = "Setting Book"
nextVC.isBook = true
}
}
if segue.identifier == "deviceSettingTableVC"
{
if let nextVC = segue.destinationViewController as? SettingTableView
{
nextVC.title = "Setting Device"
nextVC.isBook = false
}
}
}
func getRequiredInfo(Info: String) {
print("umbrella:\(Info)")
let itemInfo = Info.componentsSeparatedByString(",")
umbrellaInfo = BorrowItem(id: itemInfo[0], name: itemInfo[1], descri: itemInfo[2], type: itemInfo[3], count: itemInfo[4], leftCount: itemInfo[5])
SVProgressHUD.dismiss()
}
}
| 76f8749e62113fc700ed00cc19e2b6ae | 28.622642 | 153 | 0.576115 | false | false | false | false |
ls1intum/sReto | refs/heads/master | Source/sReto/Core/Routing/MulticastConnection.swift | mit | 1 | //
// MulticastConnection.swift
// sReto
//
// Created by Julian Asamer on 18/09/14.
// Copyright (c) 2014 - 2016 Chair for Applied Software Engineering
//
// Licensed under the MIT License
//
// 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
/**
* A MulticastConnection acts like a normal underlying connection, but sends all data written to it using a set of subconnections.
* Data received from any subconnection is reported to the delegate.
*/
class MulticastConnection: UnderlyingConnection, UnderlyingConnectionDelegate {
/** The subconnections used with this connection */
var subconnections: [UnderlyingConnection] = []
/** Stores the number of dataSent calls yet to be received. Once all are received, the delegate's didSendData can be called. */
var dataSentCallbacksToBeReceived: Int = 0
/** The number of data packets that have been sent in total. */
var dataPacketsSent: Int = 0
init() {}
/** Adds a subconnection. */
func addSubconnection(_ connection: UnderlyingConnection) {
self.subconnections.append(connection)
connection.delegate = self
}
// MARK: UnderlyingConnection protocol
var delegate: UnderlyingConnectionDelegate?
var isConnected: Bool { get { return subconnections.map({ $0.isConnected }).reduce(false, { $0 && $1 }) } }
var recommendedPacketSize: Int { get { return subconnections.map { $0.recommendedPacketSize }.min()! } }
func connect() {
for connection in self.subconnections {
connection.connect()
}
}
func close() {
for connection in self.subconnections {
connection.close()
}
}
func writeData(_ data: Data) {
if self.dataSentCallbacksToBeReceived != 0 {
self.dataPacketsSent += 1
} else {
self.dataSentCallbacksToBeReceived = self.subconnections.count
}
for connection in self.subconnections {
connection.writeData(data)
}
}
// MARK: UnderlyingConnectionDelegate protocol
func didConnect(_ connection: UnderlyingConnection) {
if self.isConnected { self.delegate?.didConnect(self) }
}
func didClose(_ closedConnection: UnderlyingConnection, error: AnyObject?) {
for connection in self.subconnections {
if connection !== closedConnection { connection.close() }
}
self.delegate?.didClose(self, error: error )
}
func didReceiveData(_ connection: UnderlyingConnection, data: Data) {
self.delegate?.didReceiveData(self, data: data)
}
func didSendData(_ connection: UnderlyingConnection) {
if self.dataSentCallbacksToBeReceived == 0 {
log(.medium, info: "Received unexpected didSendData call.")
return
}
self.dataSentCallbacksToBeReceived -= 1
if self.dataSentCallbacksToBeReceived == 0 {
if self.dataPacketsSent != 0 {
self.dataPacketsSent -= 1
self.dataSentCallbacksToBeReceived = self.subconnections.count
}
self.delegate?.didSendData(self)
}
}
}
| 0aa9b8f96cacefab318295512f2469cd | 38.794393 | 159 | 0.672851 | false | false | false | false |
TheInfiniteKind/duckduckgo-iOS | refs/heads/develop | DuckDuckGo/AutocompleteParser.swift | apache-2.0 | 1 | //
// AutocompleteParser.swift
// DuckDuckGo
//
// Created by Mia Alexiou on 09/03/2017.
// Copyright © 2017 DuckDuckGo. All rights reserved.
//
import Foundation
import Core
class AutocompleteParser {
enum ParsingError: Error {
case noData
case invalidJson
}
func parse(data: Data?) throws -> [Suggestion] {
guard let data = data else { throw ParsingError.noData }
guard let json = try JSONSerialization.jsonObject(with: data) as? [[String: String]] else { throw ParsingError.invalidJson }
var suggestions = [Suggestion]()
for element in json {
if let type = element.keys.first, let suggestion = element[type] {
suggestions.append(Suggestion(type: type, suggestion: suggestion))
}
}
return suggestions
}
}
| aeaec6e40a3ac2900508f6e5cc110c7d | 25.363636 | 132 | 0.609195 | false | false | false | false |
son11592/STKeyboard | refs/heads/master | Example/Pods/STKeyboard/STKeyboard/Classes/STKeyboardNumber.swift | mit | 2 | //
// STKeyboardMoney.swift
// Bubu
//
// Created by Sơn Thái on 9/27/16.
// Copyright © 2016 LOZI. All rights reserved.
//
import UIKit
open class STKeyboardNumber: STKeyboard {
static let sharedNumber = STKeyboardNumber()
fileprivate var buttons: [STButton] = []
override open func commonInit() {
super.commonInit()
self.backgroundColor = UIColor.commonWhiteSand
let padding: CGFloat = 1.0
let width: CGFloat = (UIScreen.main.bounds.width - padding * 3) * 1/3
let height: CGFloat = (STKeyboard.STKeyboardDefaultHeight - padding * 5) * 0.25
var numberX: CGFloat = 0
var numberY: CGFloat = padding
for i in 0..<9 {
let frame = CGRect(x: numberX, y: numberY, width: width, height: height)
let button = self.createButton(title: "\(i + 1)", tag: i + 1, frame: frame)
self.addSubview(button)
self.buttons.append(button)
numberX += (width + padding)
if (i + 1) % 3 == 0 {
numberX = 0.0
numberY += (height + padding)
}
}
let zeroFrame = CGRect(x: 0, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height)
let zero = self.createButton(title: "0", tag: 0, frame: zeroFrame)
self.addSubview(zero)
self.buttons.append(zero)
let trippleFrame = CGRect(x: width + padding, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height)
let tripplezero = self.createButton(title: "000", tag: 11, frame: trippleFrame, titleSize: 20)
self.addSubview(tripplezero)
self.buttons.append(tripplezero)
let backFrame = CGRect(x: UIScreen.main.bounds.width - width, y: STKeyboard.STKeyboardDefaultHeight - height - padding, width: width, height: height)
let backSpace = self.createButton(title: "\u{232B}", tag: -1, frame: backFrame)
self.addSubview(backSpace)
}
open func numberTD(_ button: UIButton) {
UIDevice.current.playInputClick()
switch button.tag {
case -1:
self.backSpaceTD()
break
case 11:
self.inputText(text: "000")
break
default:
self.inputText(text: "\(button.tag)")
break
}
}
fileprivate func createButton(title: String, tag: Int, frame: CGRect, titleSize: CGFloat = 25) -> STButton {
let button = STButton()
button._normalBackgroundColor = UIColor.white
button._selectedBackgroundColor = UIColor(hex: 0x535353)
button.frame = frame
button.setTitleColor(UIColor.black, for: .normal)
button.setTitleColor(UIColor.white, for: .highlighted)
button.setTitle(title, for: .normal)
button.titleLabel?.font = UIFont(name: "HelveticaNeue", size: titleSize)
button.tag = tag
button.addTarget(self, action: #selector(STKeyboardNumber.numberTD(_:)), for: .touchDown)
button.layer.cornerRadius = 5
return button
}
}
| 6dd12ca1fcc3613ab582532097161db5 | 32.714286 | 153 | 0.670551 | false | false | false | false |
ozgur/AutoLayoutAnimation | refs/heads/master | autolayoutanimation/AlamofireViewController.swift | mit | 1 | //
// AlamofireViewController.swift
// AutoLayoutAnimation
//
// Created by Ozgur Vatansever on 10/19/15.
// Copyright © 2015 Techshed. All rights reserved.
//
import UIKit
import Alamofire
class AlamofireViewController: UIViewController {
convenience init() {
self.init(nibName: "AlamofireViewController", bundle: nil)
}
@IBOutlet fileprivate weak var responseLabel: UILabel!
@IBOutlet fileprivate weak var activityIndicatorView: UIActivityIndicatorView!
fileprivate func url(_ url: String) -> String {
return "http://httpbin.org" + url
}
override func loadView() {
super.loadView()
view.backgroundColor = UIColor.white
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge()
title = "Alamofire GET"
}
@IBAction func IPButtonTapped(_ sender: UIButton) {
responseLabel.text = nil
activityIndicatorView.startAnimating()
Alamofire.request(.GET, url("/ip"), parameters: ["foo": "bar"])
.response { (request, response, data, error) -> Void in
debugPrint(request)
debugPrint(response)
debugPrint("Data: \(data)")
debugPrint(error)
}
.responseData { response -> Void in
debugPrint("ResponseData: \(response.result.value)")
}
.responseJSON(options: []) { response -> Void in
self.activityIndicatorView.stopAnimating()
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print(error.localizedDescription)
}
let result = response.result.value as! [String: String]
self.responseLabel.text = result["origin"]!
}
}
@IBAction func userAgentButtonTapped(_ sender: UIButton) {
responseLabel.text = nil
activityIndicatorView.startAnimating()
Alamofire.Manager.sharedInstance.request(.GET, url("/user-agent")).responseJSON {
response in
self.activityIndicatorView.stopAnimating()
if response.result.isSuccess {
let result = response.result.value as! [String: String]
self.responseLabel.text = result["user-agent"]
}
else {
self.responseLabel.text = response.result.error!.description
}
}
}
@IBAction func cookiesButtonTapped(_ sender: UIButton) {
responseLabel.text = nil
activityIndicatorView.startAnimating()
Alamofire.request(.GET, url("/cookies/set"), parameters: ["foo": "bar", "sessionid": "test"])
.responseJSON { response in
self.activityIndicatorView.stopAnimating()
let result = response.result.value as! [String: [String: String]]
let cookies = result["cookies"]!.map({ (k, v) -> String in
return "\(k) -> \(v)"
})
self.responseLabel.text = cookies.joined(separator: "\n")
}
}
}
| 48b09da7b2182dfee081f9e81cb03394 | 28.111111 | 97 | 0.644691 | false | false | false | false |
Jean-Daniel/PhoneNumberKit | refs/heads/master | PhoneNumberKit/ParseManager.swift | mit | 1 | //
// ParseManager.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 01/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/**
Manager for parsing flow.
*/
final class ParseManager {
weak var metadataManager: MetadataManager?
let parser: PhoneNumberParser
weak var regexManager: RegexManager?
init(metadataManager: MetadataManager, regexManager: RegexManager) {
self.metadataManager = metadataManager
self.parser = PhoneNumberParser(regex: regexManager, metadata: metadataManager)
self.regexManager = regexManager
}
/**
Parse a string into a phone number object with a custom region. Can throw.
- Parameter numberString: String to be parsed to phone number struct.
- Parameter region: ISO 639 compliant region code.
- parameter ignoreType: Avoids number type checking for faster performance.
*/
func parse(_ numberString: String, withRegion region: String, ignoreType: Bool) throws -> PhoneNumber {
guard let metadataManager = metadataManager, let regexManager = regexManager else { throw PhoneNumberError.generalError }
// Make sure region is in uppercase so that it matches metadata (1)
let region = region.uppercased()
// Extract number (2)
var nationalNumber = numberString
let match = try regexManager.phoneDataDetectorMatch(numberString)
let matchedNumber = nationalNumber.substring(with: match.range)
nationalNumber = matchedNumber
// Strip and extract extension (3)
var numberExtension: String?
if let rawExtension = parser.stripExtension(&nationalNumber) {
numberExtension = parser.normalizePhoneNumber(rawExtension)
}
// Country code parse (4)
guard var regionMetadata = metadataManager.territoriesByCountry[region] else {
throw PhoneNumberError.invalidCountryCode
}
var countryCode: UInt64 = 0
do {
countryCode = try parser.extractCountryCode(nationalNumber, nationalNumber: &nationalNumber, metadata: regionMetadata)
} catch {
let plusRemovedNumberString = regexManager.replaceStringByRegex(PhoneNumberPatterns.leadingPlusCharsPattern, string: nationalNumber as String)
countryCode = try parser.extractCountryCode(plusRemovedNumberString, nationalNumber: &nationalNumber, metadata: regionMetadata)
}
if countryCode == 0 {
countryCode = regionMetadata.countryCode
}
// Nomralized number (5)
let normalizedNationalNumber = parser.normalizePhoneNumber(nationalNumber)
nationalNumber = normalizedNationalNumber
// If country code is not default, grab correct metadata (6)
if countryCode != regionMetadata.countryCode, let countryMetadata = metadataManager.mainTerritoryByCode[countryCode] {
regionMetadata = countryMetadata
}
// National Prefix Strip (7)
parser.stripNationalPrefix(&nationalNumber, metadata: regionMetadata)
// Test number against general number description for correct metadata (8)
if let generalNumberDesc = regionMetadata.generalDesc, (regexManager.hasValue(generalNumberDesc.nationalNumberPattern) == false || parser.isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) == false) {
throw PhoneNumberError.notANumber
}
// Finalize remaining parameters and create phone number object (9)
let leadingZero = nationalNumber.hasPrefix("0")
guard let finalNationalNumber = UInt64(nationalNumber) else {
throw PhoneNumberError.notANumber
}
// Check if the number if of a known type (10)
var type: PhoneNumberType = .unknown
if ignoreType == false {
if let regionCode = getRegionCode(of: finalNationalNumber, countryCode: countryCode, leadingZero: leadingZero), let foundMetadata = metadataManager.territoriesByCountry[regionCode] {
regionMetadata = foundMetadata
}
type = parser.checkNumberType(String(nationalNumber), metadata: regionMetadata, leadingZero: leadingZero)
if type == .unknown {
throw PhoneNumberError.unknownType
}
}
let phoneNumber = PhoneNumber(numberString: numberString, countryCode: countryCode, leadingZero: leadingZero, nationalNumber: finalNationalNumber, numberExtension: numberExtension, type: type, regionID: regionMetadata.codeID)
return phoneNumber
}
// Parse task
/**
Fastest way to parse an array of phone numbers. Uses custom region code.
- Parameter numberStrings: An array of raw number strings.
- Parameter region: ISO 639 compliant region code.
- parameter ignoreType: Avoids number type checking for faster performance.
- Returns: An array of valid PhoneNumber objects.
*/
func parseMultiple(_ numberStrings: [String], withRegion region: String, ignoreType: Bool, shouldReturnFailedEmptyNumbers: Bool = false) -> [PhoneNumber] {
var hasError = false
var multiParseArray = [PhoneNumber](repeating: PhoneNumber.notPhoneNumber(), count: numberStrings.count)
DispatchQueue.concurrentPerform(iterations: numberStrings.count) { [unowned self] in
let numberString = numberStrings[$0]
do {
let phoneNumber = try self.parse(numberString, withRegion: region, ignoreType: ignoreType)
multiParseArray[$0] = phoneNumber
} catch {
hasError = true
}
}
if hasError && !shouldReturnFailedEmptyNumbers {
multiParseArray = multiParseArray.filter { $0.type != .notParsed }
}
return multiParseArray
}
/// Get correct ISO 639 compliant region code for a number.
///
/// - Parameters:
/// - nationalNumber: national number.
/// - countryCode: country code.
/// - leadingZero: whether or not the number has a leading zero.
/// - Returns: ISO 639 compliant region code.
func getRegionCode(of nationalNumber: UInt64, countryCode: UInt64, leadingZero: Bool) -> String? {
guard let regexManager = regexManager, let metadataManager = metadataManager, let regions = metadataManager.territoriesByCode[countryCode] else { return nil }
if regions.count == 1 {
return regions[0].codeID
}
let nationalNumberString = String(nationalNumber)
for region in regions {
if let leadingDigits = region.leadingDigits {
if regexManager.matchesAtStart(leadingDigits, string: nationalNumberString) {
return region.codeID
}
}
if leadingZero && parser.checkNumberType("0" + nationalNumberString, metadata: region) != .unknown {
return region.codeID
}
if parser.checkNumberType(nationalNumberString, metadata: region) != .unknown {
return region.codeID
}
}
return nil
}
}
| b6f070c1a98537e91fba8e9731d82bf8 | 44.107595 | 233 | 0.677985 | false | false | false | false |
sdaheng/Biceps | refs/heads/master | BicepsService.swift | mit | 1 | //
// BicepsService.swift
// HomeNAS
//
// Created by SDH on 03/04/2017.
// Copyright © 2017 sdaheng. All rights reserved.
//
import Foundation
// MARK: Service Layer
public protocol BicepsProvidable {
func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps
func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps
}
public extension BicepsProvidable {
func fetch(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps {
throw BicepsError.UnimplementedMethodError.fetch
}
func send(paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?)->Void) throws -> Biceps {
throw BicepsError.UnimplementedMethodError.send
}
}
open class BicepsService {
open class func fetch<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws {
do {
let biceps = try provider.fetch(paramater: paramater, resultBlock: resultBlock)
try add(biceps, to: BicepsOperationQueue.shared.operationQueue)
} catch {
throw BicepsError.UnimplementedMethodError.fetch
}
}
open class func send<T: BicepsProvidable>(by provider: T, paramater: [String:Any]?, resultBlock: @escaping (_ result: Any?) -> Void) throws {
do {
let biceps = try provider.send(paramater: paramater, resultBlock: resultBlock)
try add(biceps, to: BicepsOperationQueue.shared.operationQueue)
} catch {
throw BicepsError.UnimplementedMethodError.send
}
}
class func add(_ biceps: Biceps, to queue: OperationQueue) throws {
let operationQueue = queue
if let combinedRequests = biceps.combinedRequest {
operationQueue.addOperations(combinedRequests.map { (biceps) in
return BicepsOperation(biceps)
}, waitUntilFinished: false)
} else if biceps.hasDependency() {
guard let dependency = biceps.dependency, dependency != biceps else {
throw BicepsError.DependencyError.cycle
}
operationQueue.addOperations(resolveDependencyChain(from: biceps),
waitUntilFinished: false)
} else {
operationQueue.addOperation(BicepsOperation(biceps))
}
}
class func resolveDependencyChain(from head: Biceps) -> [BicepsOperation] {
var dependencyChain = head
var dependencyOperation = BicepsOperation(head)
var dependencyOperations = Set<BicepsOperation>()
while dependencyChain.hasDependency() {
if let depsDependency = dependencyChain.dependency {
let depsDependencyOperation = BicepsOperation(depsDependency)
dependencyOperation.addDependency(depsDependencyOperation)
dependencyOperations.insert(dependencyOperation)
if !depsDependency.hasDependency() {
dependencyOperations.insert(depsDependencyOperation)
}
dependencyOperation = depsDependencyOperation
dependencyChain = depsDependency
}
}
return dependencyOperations.map { return $0 }
}
}
| 925a44a78c444d64d47174a5d62e8465 | 39.117647 | 146 | 0.633138 | false | false | false | false |
LeeShiYoung/LSYWeibo | refs/heads/master | Pods/ALCameraViewController/ALCameraViewController/ViewController/ConfirmViewController.swift | artistic-2.0 | 1 | //
// ALConfirmViewController.swift
// ALCameraViewController
//
// Created by Alex Littlejohn on 2015/06/30.
// Copyright (c) 2015 zero. All rights reserved.
//
import UIKit
import Photos
public enum PhotosMode: Int {
case preview = 0 // 默认预览
case graph // 拍照预览
}
public class ConfirmViewController: UIViewController, UIScrollViewDelegate {
lazy var imageView: UIImageView = {
let img = UIImageView()
return img
}()
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var cropOverlay: CropOverlay!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var confirmButton: UIButton!
@IBOutlet weak var centeringView: UIView!
var graphImage: UIImage?
var allowsCropping: Bool = false
var verticalPadding: CGFloat = 30
var horizontalPadding: CGFloat = 30
var modeType: PhotosMode?
public var onComplete: CameraViewCompletion?
var asset: PHAsset!
public init(asset: PHAsset, allowsCropping: Bool, mode: PhotosMode) {
self.allowsCropping = allowsCropping
self.asset = asset
self.modeType = mode
super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle)
}
//MARK: - 增加初始化方法
public init(image: UIImage?, allowsCropping: Bool, mode: PhotosMode) {
self.allowsCropping = allowsCropping
self.graphImage = image
self.modeType = mode
super.init(nibName: "ConfirmViewController", bundle: CameraGlobals.shared.bundle)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override func prefersStatusBarHidden() -> Bool {
switch modeType! {
case .graph:
return false
case .preview:
return true
}
return true
}
public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
return UIStatusBarAnimation.Slide
}
public override func viewDidLoad() {
super.viewDidLoad()
switch modeType! {
case .graph:
print("拍照初始化")
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一步", style: UIBarButtonItemStyle.Plain, target: self, action: .next)
view.backgroundColor = UIColor.whiteColor()
configureWithImage(graphImage!)
case .preview:
view.backgroundColor = UIColor.blackColor()
imageView.userInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(ConfirmViewController.cancel))
imageView.addGestureRecognizer(tap)
}
cancelButton.hidden = true
cancelButton.enabled = false
confirmButton.hidden = true
confirmButton.enabled = false
scrollView.addSubview(imageView)
scrollView.delegate = self
scrollView.maximumZoomScale = 1
cropOverlay.hidden = true
guard let asset = asset else {
return
}
switch modeType! {
case .graph:
return
case .preview:
let spinner = showSpinner()
disable()
SingleImageFetcher()
.setAsset(asset)
.setTargetSize(largestPhotoSize())
.onSuccess { image in
self.configureWithImage(image)
self.hideSpinner(spinner)
self.enable()
}
.onFailure { error in
self.hideSpinner(spinner)
}
.fetch()
}
}
public override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let scale = calculateMinimumScale(view.frame.size)
let frame = allowsCropping ? cropOverlay.frame : view.bounds
scrollView.contentInset = calculateScrollViewInsets(frame)
scrollView.minimumZoomScale = scale
scrollView.zoomScale = scale
centerScrollViewContents()
centerImageViewOnRotate()
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let scale = calculateMinimumScale(size)
var frame = view.bounds
if allowsCropping {
frame = cropOverlay.frame
let centeringFrame = centeringView.frame
var origin: CGPoint
if size.width > size.height { // landscape
let offset = (size.width - centeringFrame.height)
let expectedX = (centeringFrame.height/2 - frame.height/2) + offset
origin = CGPoint(x: expectedX, y: frame.origin.x)
} else {
let expectedY = (centeringFrame.width/2 - frame.width/2)
origin = CGPoint(x: frame.origin.y, y: expectedY)
}
frame.origin = origin
} else {
frame.size = size
}
coordinator.animateAlongsideTransition({ context in
self.scrollView.contentInset = self.calculateScrollViewInsets(frame)
self.scrollView.minimumZoomScale = scale
self.scrollView.zoomScale = scale
self.centerScrollViewContents()
self.centerImageViewOnRotate()
}, completion: nil)
}
private func configureWithImage(image: UIImage) {
if allowsCropping {
cropOverlay.hidden = false
} else {
cropOverlay.hidden = true
}
buttonActions()
imageView.image = image
imageView.sizeToFit()
view.setNeedsLayout()
}
private func calculateMinimumScale(size: CGSize) -> CGFloat {
var _size = size
if allowsCropping {
_size = cropOverlay.frame.size
}
guard let image = imageView.image else {
return 1
}
let scaleWidth = _size.width / image.size.width
let scaleHeight = _size.height / image.size.height
var scale: CGFloat
if allowsCropping {
scale = max(scaleWidth, scaleHeight)
} else {
scale = min(scaleWidth, scaleHeight)
}
return scale
}
private func calculateScrollViewInsets(frame: CGRect) -> UIEdgeInsets {
let bottom = view.frame.height - (frame.origin.y + frame.height)
let right = view.frame.width - (frame.origin.x + frame.width)
let insets = UIEdgeInsets(top: frame.origin.y, left: frame.origin.x, bottom: bottom, right: right)
return insets
}
private func centerImageViewOnRotate() {
if allowsCropping {
let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size
let scrollInsets = scrollView.contentInset
let imageSize = imageView.frame.size
var contentOffset = CGPoint(x: -scrollInsets.left, y: -scrollInsets.top)
contentOffset.x -= (size.width - imageSize.width) / 2
contentOffset.y -= (size.height - imageSize.height) / 2
scrollView.contentOffset = contentOffset
}
}
private func centerScrollViewContents() {
let size = allowsCropping ? cropOverlay.frame.size : scrollView.frame.size
let imageSize = imageView.frame.size
var imageOrigin = CGPoint.zero
if imageSize.width < size.width {
imageOrigin.x = (size.width - imageSize.width) / 2
}
if imageSize.height < size.height {
imageOrigin.y = (size.height - imageSize.height) / 2
}
imageView.frame.origin = imageOrigin
}
private func buttonActions() {
confirmButton.action = { [weak self] in self?.confirmPhoto() }
cancelButton.action = { [weak self] in self?.cancel() }
}
internal func cancel() {
onComplete?(nil, nil)
}
internal func confirmPhoto() {
disable()
imageView.hidden = true
if graphImage != nil {
self.onComplete?(graphImage, nil)
return
}
let spinner = showSpinner()
let fetcher = SingleImageFetcher()
.onSuccess { image in
switch self.modeType! {
case .preview:
print("默认")
case .graph:
print("拍照")
self.onComplete?(self.graphImage, self.asset)
}
self.hideSpinner(spinner)
self.enable()
}
.onFailure { error in
self.hideSpinner(spinner)
self.showNoImageScreen(error)
}
.setAsset(asset)
if allowsCropping {
var cropRect = cropOverlay.frame
cropRect.origin.x += scrollView.contentOffset.x
cropRect.origin.y += scrollView.contentOffset.y
let normalizedX = cropRect.origin.x / imageView.frame.width
let normalizedY = cropRect.origin.y / imageView.frame.height
let normalizedWidth = cropRect.width / imageView.frame.width
let normalizedHeight = cropRect.height / imageView.frame.height
let rect = normalizedRect(CGRect(x: normalizedX, y: normalizedY, width: normalizedWidth, height: normalizedHeight), orientation: imageView.image!.imageOrientation)
fetcher.setCropRect(rect)
}
fetcher.fetch()
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return imageView
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
centerScrollViewContents()
}
func showSpinner() -> UIActivityIndicatorView {
let spinner = UIActivityIndicatorView()
spinner.activityIndicatorViewStyle = .White
spinner.center = view.center
spinner.startAnimating()
view.addSubview(spinner)
view.bringSubviewToFront(spinner)
return spinner
}
func hideSpinner(spinner: UIActivityIndicatorView) {
spinner.stopAnimating()
spinner.removeFromSuperview()
}
func disable() {
confirmButton.enabled = false
}
func enable() {
confirmButton.enabled = true
}
func showNoImageScreen(error: NSError) {
let permissionsView = PermissionsView(frame: view.bounds)
let desc = localizedString("error.cant-fetch-photo.description")
permissionsView.configureInView(view, title: error.localizedDescription, descriptiom: desc, completion: cancel)
}
deinit
{
print("ConfirmViewController 死")
}
}
private extension Selector
{
static let next = #selector(ConfirmViewController.confirmPhoto)
} | e2c1bc61a99a1aa8931985f6c5a4729d | 30.189041 | 175 | 0.58192 | false | false | false | false |
zisko/swift | refs/heads/master | test/SILGen/nested_generics.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-silgen -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -parse-as-library %s > /dev/null
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-sil -O -parse-as-library %s > /dev/null
// RUN: %target-swift-frontend -enable-sil-ownership -Xllvm -sil-full-demangle -emit-ir -parse-as-library %s > /dev/null
// TODO:
// - test generated SIL -- mostly we're just testing mangling here
// - class_method calls
// - witness_method calls
// - inner generic parameters on protocol requirements
// - generic parameter list on method in nested type
// - types nested inside unconstrained extensions of generic types
protocol Pizza : class {
associatedtype Topping
}
protocol HotDog {
associatedtype Condiment
}
protocol CuredMeat {}
// Generic nested inside generic
struct Lunch<T : Pizza> where T.Topping : CuredMeat {
struct Dinner<U : HotDog> where U.Condiment == Deli<Pepper>.Mustard {
let firstCourse: T
let secondCourse: U?
var leftovers: T
var transformation: (T) -> U
func coolCombination(t: T.Topping, u: U.Condiment) {
func nestedGeneric<X, Y>(x: X, y: Y) -> (X, Y) {
return (x, y)
}
_ = nestedGeneric(x: t, y: u)
}
}
}
// CHECK-LABEL: // nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@in T.Topping, Deli<Pepper>.Mustard, @in_guaranteed Lunch<T>.Dinner<U>) -> ()
// CHECK-LABEL: // nestedGeneric #1 <A><A1><A2, B2 where A: nested_generics.Pizza, A1: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, A1.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(x: A2, y: B2) -> (A2, B2) in nested_generics.Lunch.Dinner.coolCombination(t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil private @$S15nested_generics5LunchV6DinnerV15coolCombination1t1uy7ToppingQz_AA4DeliC7MustardOyAA6PepperV_GtF0A7GenericL_1x1yqd0___qd0_0_tqd0___qd0_0_tAA5PizzaRzAA6HotDogRd__AA9CuredMeatAJRQAQ9CondimentRtd__r__0_lF : $@convention(thin) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard><X, Y> (@in X, @in Y) -> (@out X, @out Y)
// CHECK-LABEL: // nested_generics.Lunch.Dinner.init(firstCourse: A, secondCourse: Swift.Optional<A1>, leftovers: A, transformation: (A) -> A1) -> nested_generics.Lunch<A>.Dinner<A1>
// CHECK-LABEL: sil hidden @$S15nested_generics5LunchV6DinnerV11firstCourse06secondF09leftovers14transformationAEyx_qd__Gx_qd__Sgxqd__xctcfC : $@convention(method) <T where T : Pizza, T.Topping : CuredMeat><U where U : HotDog, U.Condiment == Deli<Pepper>.Mustard> (@owned T, @in Optional<U>, @owned T, @owned @callee_guaranteed (@owned T) -> @out U, @thin Lunch<T>.Dinner<U>.Type) -> @out Lunch<T>.Dinner<U>
// Non-generic nested inside generic
class Deli<Spices> : CuredMeat {
class Pepperoni : CuredMeat {}
struct Sausage : CuredMeat {}
enum Mustard {
case Yellow
case Dijon
case DeliStyle(Spices)
}
}
// CHECK-LABEL: // nested_generics.Deli.Pepperoni.init() -> nested_generics.Deli<A>.Pepperoni
// CHECK-LABEL: sil hidden @$S15nested_generics4DeliC9PepperoniCAEyx_Gycfc : $@convention(method) <Spices> (@owned Deli<Spices>.Pepperoni) -> @owned Deli<Spices>.Pepperoni
// Typealiases referencing outer generic parameters
struct Pizzas<Spices> {
class NewYork : Pizza {
typealias Topping = Deli<Spices>.Pepperoni
}
class DeepDish : Pizza {
typealias Topping = Deli<Spices>.Sausage
}
}
class HotDogs {
struct Bratwurst : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
struct American : HotDog {
typealias Condiment = Deli<Pepper>.Mustard
}
}
// Local type in extension of type in another module
extension String {
func foo() {
// CHECK-LABEL: // init(material: A) -> Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()<A> in Cheese #1 in (extension in nested_generics):Swift.String.foo() -> ()
// CHECK-LABEL: sil private @$SSS15nested_genericsE3fooyyF6CheeseL_V8materialADyxGx_tcfC
struct Cheese<Milk> {
let material: Milk
}
let _ = Cheese(material: "cow")
}
}
// Local type in extension of type in same module
extension HotDogs {
func applyRelish() {
// CHECK-LABEL: // init(material: A) -> Relish #1 in nested_generics.HotDogs.applyRelish() -> ()<A> in Relish #1 in nested_generics.HotDogs.applyRelish() -> ()
// CHECK-LABEL: sil private @$S15nested_generics7HotDogsC11applyRelishyyF0F0L_V8materialAFyxGx_tcfC
struct Relish<Material> {
let material: Material
}
let _ = Relish(material: "pickles")
}
}
struct Pepper {}
struct ChiliFlakes {}
// CHECK-LABEL: // nested_generics.eatDinnerGeneric<A, B where A: nested_generics.Pizza, B: nested_generics.HotDog, A.Topping: nested_generics.CuredMeat, B.Condiment == nested_generics.Deli<nested_generics.Pepper>.Mustard>(d: inout nested_generics.Lunch<A>.Dinner<B>, t: A.Topping, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics16eatDinnerGeneric1d1t1uyAA5LunchV0D0Vyx_q_Gz_7ToppingQzAA4DeliC7MustardOyAA6PepperV_GtAA5PizzaRzAA6HotDogR_AA9CuredMeatALRQAS9CondimentRt_r0_lF : $@convention(thin) <T, U where T : Pizza, U : HotDog, T.Topping : CuredMeat, U.Condiment == Deli<Pepper>.Mustard> (@inout Lunch<T>.Dinner<U>, @in T.Topping, Deli<Pepper>.Mustard) -> ()
func eatDinnerGeneric<T, U>(d: inout Lunch<T>.Dinner<U>, t: T.Topping, u: U.Condiment) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// Overloading concrete function with different bound generic arguments in parent type
// CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.ChiliFlakes>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA11ChiliFlakesV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAA6PepperV_GtF : $@convention(thin) (@inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>, @owned Deli<ChiliFlakes>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<ChiliFlakes>.NewYork>.Dinner<HotDogs.American>,
t: Deli<ChiliFlakes>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.ChiliFlakes>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA11ChiliFlakesV_GAA7HotDogsC8AmericanVIegxr_AhLIegxd_TR : $@convention(thin) (@owned Pizzas<ChiliFlakes>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<ChiliFlakes>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // nested_generics.eatDinnerConcrete(d: inout nested_generics.Lunch<nested_generics.Pizzas<nested_generics.Pepper>.NewYork>.Dinner<nested_generics.HotDogs.American>, t: nested_generics.Deli<nested_generics.Pepper>.Pepperoni, u: nested_generics.Deli<nested_generics.Pepper>.Mustard) -> ()
// CHECK-LABEL: sil hidden @$S15nested_generics17eatDinnerConcrete1d1t1uyAA5LunchV0D0VyAA6PizzasV7NewYorkCyAA6PepperV_G_AA7HotDogsC8AmericanVGz_AA4DeliC9PepperoniCyAO_GAW7MustardOyAO_GtF : $@convention(thin) (@inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>, @owned Deli<Pepper>.Pepperoni, Deli<Pepper>.Mustard) -> ()
func eatDinnerConcrete(d: inout Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>,
t: Deli<Pepper>.Pepperoni,
u: Deli<Pepper>.Mustard) {
// Method call
_ = d.coolCombination(t: t, u: u)
// Read a let, store into var
d.leftovers = d.firstCourse
// Read a var
let _ = d.secondCourse
// Call property of function type
_ = d.transformation(d.leftovers)
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIegxr_AhLIegxd_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<Pepper>.NewYork) -> @out HotDogs.American) -> HotDogs.American
// CHECK-LABEL: // closure #1 (nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> nested_generics.HotDogs.American in nested_generics.calls() -> ()
// CHECK-LABEL: sil private @$S15nested_generics5callsyyFAA7HotDogsC8AmericanVAA6PizzasV7NewYorkCyAA6PepperV_GcfU_ : $@convention(thin) (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American
func calls() {
let firstCourse = Pizzas<Pepper>.NewYork()
let secondCourse = HotDogs.American()
var dinner = Lunch<Pizzas<Pepper>.NewYork>.Dinner<HotDogs.American>(
firstCourse: firstCourse,
secondCourse: secondCourse,
leftovers: firstCourse,
transformation: { _ in HotDogs.American() })
let topping = Deli<Pepper>.Pepperoni()
let condiment1 = Deli<Pepper>.Mustard.Dijon
let condiment2 = Deli<Pepper>.Mustard.DeliStyle(Pepper())
eatDinnerGeneric(d: &dinner, t: topping, u: condiment1)
eatDinnerConcrete(d: &dinner, t: topping, u: condiment2)
}
protocol ProtocolWithGenericRequirement {
associatedtype T
associatedtype U
func method<V>(t: T, u: U, v: V) -> (T, U, V)
}
class OuterRing<T> {
class InnerRing<U> : ProtocolWithGenericRequirement {
func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return (t, u, v)
}
}
}
class SubclassOfInner<T, U> : OuterRing<T>.InnerRing<U> {
override func method<V>(t: T, u: U, v: V) -> (T, U, V) {
return super.method(t: t, u: u, v: v)
}
}
// CHECK-LABEL: // reabstraction thunk helper from @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@unowned nested_generics.HotDogs.American) to @escaping @callee_guaranteed (@owned nested_generics.Pizzas<nested_generics.Pepper>.NewYork) -> (@out nested_generics.HotDogs.American)
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$S15nested_generics6PizzasV7NewYorkCyAA6PepperV_GAA7HotDogsC8AmericanVIegxd_AhLIegxr_TR : $@convention(thin) (@owned Pizzas<Pepper>.NewYork, @guaranteed @callee_guaranteed (@owned Pizzas<Pepper>.NewYork) -> HotDogs.American) -> @out HotDogs.American
// CHECK-LABEL: sil private [transparent] [thunk] @$S15nested_generics9OuterRingC05InnerD0Cyx_qd__GAA30ProtocolWithGenericRequirementA2aGP6method1t1u1v1TQz_1UQzqd__tAN_APqd__tlFTW : $@convention(witness_method: ProtocolWithGenericRequirement) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @in_guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0) {
// CHECK: bb0([[T:%[0-9]+]] : @trivial $*τ_0_0, [[U:%[0-9]+]] : @trivial $*τ_1_0, [[V:%[0-9]+]] : @trivial $*τ_2_0, [[TOut:%[0-9]+]] : @trivial $*τ_0_0, [[UOut:%[0-9]+]] : @trivial $*τ_1_0, [[VOut:%[0-9]+]] : @trivial $*τ_2_0, [[SELF:%[0-9]+]] : @trivial $*OuterRing<τ_0_0>.InnerRing<τ_1_0>):
// CHECK: [[SELF_COPY_VAL:%[0-9]+]] = load_borrow [[SELF]] : $*OuterRing<τ_0_0>.InnerRing<τ_1_0>
// CHECK: [[METHOD:%[0-9]+]] = class_method [[SELF_COPY_VAL]] : $OuterRing<τ_0_0>.InnerRing<τ_1_0>, #OuterRing.InnerRing.method!1 : <T><U><V> (OuterRing<T>.InnerRing<U>) -> (T, U, V) -> (T, U, V), $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: apply [[METHOD]]<τ_0_0, τ_1_0, τ_2_0>([[T]], [[U]], [[V]], [[TOut]], [[UOut]], [[VOut]], [[SELF_COPY_VAL]]) : $@convention(method) <τ_0_0><τ_1_0><τ_2_0> (@in τ_0_0, @in τ_1_0, @in τ_2_0, @guaranteed OuterRing<τ_0_0>.InnerRing<τ_1_0>) -> (@out τ_0_0, @out τ_1_0, @out τ_2_0)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: end_borrow [[SELF_COPY_VAL]] from [[SELF]]
// CHECK: return [[RESULT]] : $()
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Pepperoni: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>.Sausage: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Deli<Spices>: CuredMeat module nested_generics {
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.NewYork: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Pepperoni
// CHECK: }
// CHECK: sil_witness_table hidden <Spices> Pizzas<Spices>.DeepDish: Pizza module nested_generics {
// CHECK: associated_type Topping: Deli<Spices>.Sausage
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.Bratwurst: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
// CHECK: sil_witness_table hidden HotDogs.American: HotDog module nested_generics {
// CHECK: associated_type Condiment: Deli<Pepper>.Mustard
// CHECK: }
| 0234956d950cf60a3115ab52eb4a4f7c | 54.211538 | 407 | 0.711181 | false | false | false | false |
MrSuperJJ/JJMediatorDemo | refs/heads/master | JJMediatorDemo/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// JJMediatorDemo
//
// Created by Mr.JJ on 2017/5/11.
// Copyright © 2017年 Mr.JJ. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = .white
let mainViewController = MainTableViewController()
let navigationController = UINavigationController(rootViewController: mainViewController)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 01e19d99fd8e78db95c152d974cb4284 | 45.981481 | 285 | 0.74931 | false | false | false | false |
txstate-etc/mobile-tracs-ios | refs/heads/master | mobile-tracs-ios/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// mobile-tracs-ios
//
// Created by Nick Wing on 3/17/17.
// Copyright © 2017 Texas State University. All rights reserved.
//
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Clear out cache data between versions in case we change the structure of the object being saved
if let savedversion = Utils.grab("version") as? String {
if let currentversion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
if currentversion != savedversion {
TRACSClient.sitecache.clean()
Utils.save(currentversion, withKey: "version")
}
}
}
// register for push notifications
if #available(iOS 10, *) {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in }
center.delegate = self
} else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
//Set a custom user agent so that UIWebView and URLSession dataTasks will match
UserDefaults.standard.register(defaults: ["UserAgent": Utils.userAgent])
return true
}
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if self.window?.rootViewController?.presentedViewController is LoginViewController {
return UIInterfaceOrientationMask.portrait
} else {
return UIInterfaceOrientationMask.all
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
IntegrationClient.deviceToken = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
Utils.save(IntegrationClient.deviceToken, withKey: "deviceToken")
NSLog("deviceToken: %@", IntegrationClient.deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
IntegrationClient.deviceToken = Utils.randomHexString(length:32)
Utils.save(IntegrationClient.deviceToken, withKey: "deviceToken")
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
Analytics.event(category: "External Launch", action: url.absoluteString, label: sourceApplication ?? "null", value: nil)
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ObservableEvent.PUSH_NOTIFICATION), object: self)
var badge:Int?
if let aps = userInfo["aps"] as? [String:Any] {
badge = aps["badge"] as? Int
}
UIApplication.shared.applicationIconBadgeNumber = badge ?? 0
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let tabController = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController
tabController?.selectedIndex = 1
let navController = tabController?.selectedViewController as? UINavigationController
navController?.popToRootViewController(animated: true)
}
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ObservableEvent.PUSH_NOTIFICATION), object: self)
UIApplication.shared.applicationIconBadgeNumber = notification.request.content.badge?.intValue ?? 0
completionHandler([.alert, .badge])
}
}
| 477ac07cded5773d167eda999a24909e | 53.105263 | 285 | 0.716926 | false | false | false | false |
BasThomas/TimeTable | refs/heads/master | TimeTable/TimeTable/ScheduleTableViewController.swift | mit | 1 | //
// ScheduleTableViewController.swift
// TimeTable
//
// Created by Bas Broek on 21/11/2014.
// Copyright (c) 2014 Bas Broek. All rights reserved.
//
import UIKit
class ScheduleTableViewController: UITableViewController {
var daysAhead: Int
var url: String
required init(coder aDecoder: NSCoder)
{
// Do stuff.
self.daysAhead = 14 // Gets two weeks ahead + startOfWeek.
self.url = "https://apps.fhict.nl/api/v1/Schedule/me?expandTeacher=false&daysAhead=\(daysAhead)&IncludeStartOfWeek=true"
super.init(coder: aDecoder)
}
override func viewDidLoad()
{
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
// Return the number of sections.
return 5
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "HEADER"
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
// Return the number of rows in the section.
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("default", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
// 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: - Actions
@IBAction func logout(sender: AnyObject)
{
println("logging out")
}
}
| 81d8b9b98a220a8ffa2f4bcb4f50ef61 | 27.378049 | 128 | 0.647615 | false | false | false | false |
alessiobrozzi/firefox-ios | refs/heads/master | Client/Frontend/Menu/MenuPresentationAnimator.swift | mpl-2.0 | 2 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class MenuPresentationAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var presenting: Bool = false
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let screens = (from: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)!, to: transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)!)
guard let menuViewController = !self.presenting ? screens.from as? MenuViewController : screens.to as? MenuViewController else {
return
}
var bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController
// don't do anything special if it's a popover presentation
if menuViewController.presentationStyle == .popover {
return
}
if let navController = bottomViewController as? UINavigationController {
bottomViewController = navController.viewControllers.last ?? bottomViewController
}
if bottomViewController.isKind(of: BrowserViewController.self) {
animateWithMenu(menuViewController, browserViewController: bottomViewController as! BrowserViewController, transitionContext: transitionContext)
} else if bottomViewController.isKind(of: TabTrayController.self) {
animateWithMenu(menuViewController, tabTrayController: bottomViewController as! TabTrayController, transitionContext: transitionContext)
}
}
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return presenting ? 0.4 : 0.2
}
}
extension MenuPresentationAnimator: UIViewControllerTransitioningDelegate {
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = true
return self
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self.presenting = false
return self
}
}
extension MenuPresentationAnimator {
fileprivate func animateWithMenu(_ menu: MenuViewController, browserViewController bvc: BrowserViewController, transitionContext: UIViewControllerContextTransitioning) {
let leftViews: [UIView]?
let rightViews: [UIView]?
let sourceView: UIView?
if let toolbar = bvc.toolbar {
leftViews = [toolbar.backButton, toolbar.forwardButton]
rightViews = [toolbar.stopReloadButton, toolbar.shareButton, toolbar.homePageButton]
sourceView = toolbar.menuButton
} else {
sourceView = nil
leftViews = nil
rightViews = nil
}
self.animateWithMenu(menu, baseController: bvc, viewsToAnimateLeft: leftViews, viewsToAnimateRight: rightViews, sourceView: sourceView, withTransitionContext: transitionContext)
}
fileprivate func animateWithMenu(_ menu: MenuViewController, tabTrayController ttc: TabTrayController, transitionContext: UIViewControllerContextTransitioning) {
animateWithMenu(menu, baseController: ttc, viewsToAnimateLeft: ttc.leftToolbarButtons, viewsToAnimateRight: ttc.rightToolbarButtons, sourceView: ttc.toolbar.menuButton, withTransitionContext: transitionContext)
}
fileprivate func animateWithMenu(_ menuController: MenuViewController, baseController: UIViewController, viewsToAnimateLeft: [UIView]?, viewsToAnimateRight: [UIView]?, sourceView: UIView?, withTransitionContext transitionContext: UIViewControllerContextTransitioning) {
let container = transitionContext.containerView
// If we don't have any views abort the animation since there isn't anything to animate.
guard let menuView = menuController.view, let bottomView = baseController.view else {
transitionContext.completeTransition(true)
return
}
menuView.frame = container.bounds
// Insert tab tray below the browser and force a layout so the collection view can get it's frame right
if presenting {
container.insertSubview(menuView, belowSubview: bottomView)
menuView.layoutSubviews()
}
let vanishingPoint: CGPoint
if let sourceView = sourceView {
vanishingPoint = menuView.convert(sourceView.center, from: sourceView.superview)
} else {
vanishingPoint = CGPoint(x: menuView.center.x, y: menuView.frame.size.height)
}
let minimisedFrame = CGRect(origin: vanishingPoint, size: CGSize.zero)
guard let menuViewSnapshot = menuView.snapshotView(afterScreenUpdates: presenting) else {
transitionContext.completeTransition(true)
return
}
if presenting {
menuViewSnapshot.frame = minimisedFrame
menuViewSnapshot.alpha = 0
menuView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.0)
menuView.addSubview(menuViewSnapshot)
} else {
menuViewSnapshot.frame = menuView.frame
container.insertSubview(menuViewSnapshot, aboveSubview: menuView)
menuView.isHidden = true
}
let offstageValue = bottomView.bounds.size.width / 2
let offstageLeft = CGAffineTransform(translationX: -offstageValue, y: 0)
let offstageRight = CGAffineTransform(translationX: offstageValue, y: 0)
if presenting {
menuView.alpha = 0
menuController.menuView.isHidden = true
} else {
// move the buttons to their offstage positions
viewsToAnimateLeft?.forEach { $0.transform = offstageLeft }
viewsToAnimateRight?.forEach { $0.transform = offstageRight }
}
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.5, options: [], animations: {
if self.presenting {
menuViewSnapshot.alpha = 1
menuViewSnapshot.frame = menuView.frame
menuView.backgroundColor = menuView.backgroundColor?.withAlphaComponent(0.4)
menuView.alpha = 1
// animate back and forward buttons off to the left
viewsToAnimateLeft?.forEach { $0.transform = offstageLeft }
// animate reload and share buttons off to the right
viewsToAnimateRight?.forEach { $0.transform = offstageRight }
} else {
// animate back and forward buttons in from the left
viewsToAnimateLeft?.forEach { $0.transform = CGAffineTransform.identity }
// animate reload and share buttons in from the right
viewsToAnimateRight?.forEach { $0.transform = CGAffineTransform.identity }
menuViewSnapshot.frame = minimisedFrame
menuViewSnapshot.alpha = 0
menuView.alpha = 0
}
}, completion: { finished in
menuViewSnapshot.removeFromSuperview()
// tell our transitionContext object that we've finished animating
menuController.menuView.isHidden = !self.presenting
transitionContext.completeTransition(true)
})
}
}
| a763d354fa47ad7263dc0594d2fc324b | 47.732484 | 273 | 0.692197 | false | false | false | false |
vmanot/swift-package-manager | refs/heads/master | Sources/Basic/TerminalController.swift | apache-2.0 | 1 | /*
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 http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import libc
import func POSIX.getenv
/// A class to have better control on tty output streams: standard output and standard error.
/// Allows operations like cursor movement and colored text output on tty.
public final class TerminalController {
/// Terminal color choices.
public enum Color {
case noColor
case red
case green
case yellow
case cyan
case white
case black
case grey
/// Returns the color code which can be prefixed on a string to display it in that color.
fileprivate var string: String {
switch self {
case .noColor: return ""
case .red: return "\u{001B}[31m"
case .green: return "\u{001B}[32m"
case .yellow: return "\u{001B}[33m"
case .cyan: return "\u{001B}[36m"
case .white: return "\u{001B}[37m"
case .black: return "\u{001B}[30m"
case .grey: return "\u{001B}[30;1m"
}
}
}
/// Pointer to output stream to operate on.
private var stream: LocalFileOutputByteStream
/// Width of the terminal.
public let width: Int
/// Code to clear the line on a tty.
private let clearLineString = "\u{001B}[2K"
/// Code to end any currently active wrapping.
private let resetString = "\u{001B}[0m"
/// Code to make string bold.
private let boldString = "\u{001B}[1m"
/// Constructs the instance if the stream is a tty.
public init?(stream: LocalFileOutputByteStream) {
// Make sure this file stream is tty.
guard isatty(fileno(stream.filePointer)) != 0 else {
return nil
}
width = TerminalController.terminalWidth() ?? 80 // Assume default if we are not able to determine.
self.stream = stream
}
/// Tries to get the terminal width first using COLUMNS env variable and
/// if that fails ioctl method testing on stdout stream.
///
/// - Returns: Current width of terminal if it was determinable.
public static func terminalWidth() -> Int? {
// Try to get from environment.
if let columns = POSIX.getenv("COLUMNS"), let width = Int(columns) {
return width
}
// Try determining using ioctl.
var ws = winsize()
if ioctl(1, UInt(TIOCGWINSZ), &ws) == 0 {
return Int(ws.ws_col)
}
return nil
}
/// Flushes the stream.
public func flush() {
stream.flush()
}
/// Clears the current line and moves the cursor to beginning of the line..
public func clearLine() {
stream <<< clearLineString <<< "\r"
flush()
}
/// Moves the cursor y columns up.
public func moveCursor(up: Int) {
stream <<< "\u{001B}[\(up)A"
flush()
}
/// Writes a string to the stream.
public func write(_ string: String, inColor color: Color = .noColor, bold: Bool = false) {
writeWrapped(string, inColor: color, bold: bold, stream: stream)
flush()
}
/// Inserts a new line character into the stream.
public func endLine() {
stream <<< "\n"
flush()
}
/// Wraps the string into the color mentioned.
public func wrap(_ string: String, inColor color: Color, bold: Bool = false) -> String {
let stream = BufferedOutputByteStream()
writeWrapped(string, inColor: color, bold: bold, stream: stream)
guard let string = stream.bytes.asString else {
fatalError("Couldn't get string value from stream.")
}
return string
}
private func writeWrapped(_ string: String, inColor color: Color, bold: Bool = false, stream: OutputByteStream) {
// Don't wrap if string is empty or color is no color.
guard !string.isEmpty && color != .noColor else {
stream <<< string
return
}
stream <<< color.string <<< (bold ? boldString : "") <<< string <<< resetString
}
}
| d16fe896c3699f4b309afde8081f3df5 | 31.176471 | 117 | 0.599634 | false | false | false | false |
waltflanagan/AdventOfCode | refs/heads/master | 2015/AOC6.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
enum Instruction {
case On(CGPoint,CGPoint)
case Off(CGPoint, CGPoint)
case Toggle(CGPoint,CGPoint)
init(string:String) {
let components = string.componentsSeparatedByString(" ")
switch components[0] {
case "toggle":
let points = Instruction.parseArguments(Array(components[1..<components.count]))
self = .Toggle(points.0, points.1)
default:
let points = Instruction.parseArguments(Array(components[2..<components.count]))
switch components[0] + components [1] {
case "turnon": self = .On(points.0, points.1)
case "turnoff": self = .Off(points.0, points.1)
default: self = .Toggle(CGPointMake(0, 0), CGPointMake(0, 0))
}
}
}
static func pointFromString(string: String) -> CGPoint {
let numbers = string.componentsSeparatedByString(",")
return CGPointMake(CGFloat(Int(numbers[0])!), CGFloat(Int(numbers[1])!))
}
static func parseArguments(args: [String]) -> (CGPoint, CGPoint) {
let first = pointFromString(args[0])
let second = pointFromString(args[2])
return (first,second)
}
}
var lights = [[Bool]]()
for _ in 0..<10 {
var row = [Bool]()
for _ in 0..<10 {
row.append(false)
}
lights.append(row)
}
func set(value: Bool, first: CGPoint, second: CGPoint) {
for x in Int(first.x)..<Int(second.x) {
for y in Int(first.y)..<Int(second.y) {
lights[x][y] = value
}
}
}
func toggle(first: CGPoint, second: CGPoint) {
for x in Int(first.x)..<Int(second.x) {
for y in Int(first.y)..<Int(second.y) {
lights[x][y] = !lights[x][y]
}
}
}
let input = ["turn on 3,2 through 8,7"]
let instructions = input.map { Instruction(string: $0) }
for instruction in instructions {
switch instruction {
case .Toggle(let first, let second): toggle(first,second:second)
case .On(let first, let second): set(true, first:first, second:second)
case .Off(let first, let second): set(false, first:first, second:second)
}
}
var count = 0
for row in lights {
for light in row {
if light {
count += 1
}
}
}
count
| c806152c920e2f5665ee09f46cb75dc0 | 21.584906 | 92 | 0.571429 | false | false | false | false |
nalexn/ViewInspector | refs/heads/master | .watchOS/watchOS-Ext/watchOSApp+Testable.swift | mit | 1 | import SwiftUI
import WatchKit
import Combine
#if !(os(watchOS) && DEBUG)
typealias RootView<T> = T
typealias TestViewSubject = Set<Int>
extension View {
@inline(__always)
func testable(_ injector: TestViewSubject) -> Self {
self
}
}
#else
typealias RootView<T> = ModifiedContent<T, TestViewHost>
typealias TestViewSubject = CurrentValueSubject<[(String, AnyView)], Never>
extension View {
func testable(_ injector: TestViewSubject) -> ModifiedContent<Self, TestViewHost> {
modifier(TestViewHost(injector: injector))
}
}
struct TestViewHost: ViewModifier {
@State private var hostedViews: [(String, AnyView)] = []
let injector: TestViewSubject
func body(content: Content) -> some View {
ZStack {
content
ForEach(hostedViews, id: \.0) { $0.1 }
}
.onReceive(injector) { hostedViews = $0 }
}
}
#endif
| 4322018b60ec1adbd3bd60676ca5183a | 20.809524 | 87 | 0.648472 | false | true | false | false |
aschwaighofer/swift | refs/heads/master | test/AutoDiff/Sema/DerivedConformances/derived_differentiable.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -print-ast %s | %FileCheck %s --check-prefix=CHECK-AST
import _Differentiation
struct GenericTangentVectorMember<T: Differentiable>: Differentiable,
AdditiveArithmetic
{
var x: T.TangentVector
}
// CHECK-AST-LABEL: internal struct GenericTangentVectorMember<T> : Differentiable, AdditiveArithmetic where T : Differentiable
// CHECK-AST: internal var x: T.TangentVector
// CHECK-AST: internal init(x: T.TangentVector)
// CHECK-AST: internal typealias TangentVector = GenericTangentVectorMember<T>
// CHECK-AST: internal static var zero: GenericTangentVectorMember<T> { get }
// CHECK-AST: internal static func + (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T>
// CHECK-AST: internal static func - (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T>
// CHECK-AST: @_implements(Equatable, ==(_:_:)) internal static func __derived_struct_equals(_ a: GenericTangentVectorMember<T>, _ b: GenericTangentVectorMember<T>) -> Bool
public struct ConditionallyDifferentiable<T> {
public var x: T
}
extension ConditionallyDifferentiable: Differentiable where T: Differentiable {}
// CHECK-AST-LABEL: public struct ConditionallyDifferentiable<T> {
// CHECK-AST: @differentiable(wrt: self where T : Differentiable)
// CHECK-AST: public var x: T
// CHECK-AST: internal init(x: T)
// CHECK-AST: }
// Verify that `TangentVector` is not synthesized to be `Self` for
// `AdditiveArithmetic`-conforming classes.
final class AdditiveArithmeticClass<T: AdditiveArithmetic & Differentiable>: AdditiveArithmetic,
Differentiable
{
var x, y: T
init(x: T, y: T) {
self.x = x
self.y = y
}
// Dummy `AdditiveArithmetic` requirements.
static func == (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Bool
{
fatalError()
}
static var zero: AdditiveArithmeticClass {
fatalError()
}
static func + (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Self
{
fatalError()
}
static func - (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Self
{
fatalError()
}
}
// CHECK-AST-LABEL: final internal class AdditiveArithmeticClass<T> : AdditiveArithmetic, Differentiable where T : AdditiveArithmetic, T : Differentiable {
// CHECK-AST: final internal var x: T, y: T
// CHECK-AST: internal struct TangentVector : Differentiable, AdditiveArithmetic
// CHECK-AST: }
@frozen
public struct FrozenStruct: Differentiable {}
// CHECK-AST-LABEL: @frozen public struct FrozenStruct : Differentiable {
// CHECK-AST: internal init()
// CHECK-AST: @frozen public struct TangentVector : Differentiable, AdditiveArithmetic {
@usableFromInline
struct UsableFromInlineStruct: Differentiable {}
// CHECK-AST-LABEL: @usableFromInline
// CHECK-AST: struct UsableFromInlineStruct : Differentiable {
// CHECK-AST: internal init()
// CHECK-AST: @usableFromInline
// CHECK-AST: struct TangentVector : Differentiable, AdditiveArithmetic {
| e33696118fc0b796d907f9c8c46dcbeb | 37.02439 | 174 | 0.730597 | false | false | false | false |
OwenLaRosa/MemeMe | refs/heads/master | Meme Me/Meme Me/TextFieldDelegate.swift | gpl-3.0 | 1 | //
// TextFieldDelegate.swift
// Meme Me
//
// Created by Owen LaRosa on 3/23/15.
// Copyright (c) 2015 Owen LaRosa. All rights reserved.
//
import Foundation
import UIKit
class TextFieldDelegate: NSObject, UITextFieldDelegate {
var defaultText: String!
init(defaultText: String) {
self.defaultText = defaultText
}
func textFieldDidBeginEditing(textField: UITextField) {
// clears the text field when the user begins editing
if textField.text == defaultText {
textField.text = ""
}
textField.becomeFirstResponder()
}
func textFieldDidEndEditing(textField: UITextField) {
// reverts to default text if text field is empty
if textField.text == "" {
textField.text = defaultText
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// dismiss the keyboard
textField.resignFirstResponder()
return true
}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
var newText = textField.text! as NSString
newText = newText.stringByReplacingCharactersInRange(range, withString: string)
// ensure all inserted text is capitalized
textField.text = newText.uppercaseString
return false
}
}
| 2a063c64c9e9d1b5c0ba942a00ddea30 | 27.591837 | 132 | 0.652391 | false | false | false | false |
atuooo/notGIF | refs/heads/master | notGIF/Controllers/Compose/AccountTableViewController.swift | mit | 1 | //
// AccountTableViewController.swift
// notGIF
//
// Created by Atuooo on 13/10/2016.
// Copyright © 2016 xyz. All rights reserved.
//
import UIKit
import Accounts
private let cellID = "AccountTableViewCell"
class AccountTableViewController: UITableViewController {
public var composeVC: ComposeViewController!
deinit {
printLog(" deinited")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.backgroundColor = .clear
tableView.tableFooterView = UIView()
tableView.tintColor = .black
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return composeVC.accounts.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let account = composeVC.accounts[indexPath.item]
cell.backgroundColor = .clear
cell.textLabel?.text = account.accountDescription
cell.accessoryType = account == composeVC.selectedAccount ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
composeVC.selectedAccount = composeVC.accounts[indexPath.item]
composeVC.reloadConfigurationItems()
composeVC.popConfigurationViewController()
}
}
| e7b4bacfba63aaadd7f4235460ca7546 | 29.769231 | 109 | 0.693125 | false | false | false | false |
wanliming11/MurlocAlgorithms | refs/heads/master | Last/编程之法/1.2_字符串的包含/1.2 字符串的包含/main.swift | mit | 1 | //
// main.swift
// 1.2 字符串的包含
//
// Created by FlyingPuPu on 20/02/2017.
// Copyright (c) 2017 FPP. All rights reserved.
//
import Foundation
/*
1. "abcd" contains "cba"
"acd" contains "acd"
"ad" not contains "ac"
Thinking: 暴力解法,就是一个一个的遍历
时间复杂度: O(nm)
空间复杂度: O(1)
Thinking: 排序后轮询,先每个字符串排序,A,B
注意排序后的两个元素判断是否包含的步骤,首先因为是判断 A 是否包含 B, 所以拿B
中的字母去A中查询,另外,先要找到B中每一个字符在A中第一次不小于的位置,如果是大于则直接返回,如果是等于
继续往下遍历, 因为这个像梭子一样的比较,每次比较的结果都会导致其中一个元素往前一位,所以最坏是O(n+m)
时间复杂度:按一般的快排算法 O(nlogn) + O(mlogm) + O(n+m)
空间复杂度:O(1)
Thinking: 素数排序法,这个采用的素数的原理:素数指在一个大于1的自然数中,除了1和此整数自身外,
没法被其他自然数整除的数。 也就是说如果一个 String 里面把所有的转换为素数,然后相乘,判断另一个 String
里面的对应素数会不会被整除,如果不能,则会失败。
很显然这个很容易导致平台类型的越界。
时间复杂度: O(n+m)
空间复杂度:产生了一个26个数子的数组, O(26) -> O(1)
Thinking: 位排序,原理就是用一个26位的数来表示,然后利用位运算, | 融合进数字, & 来判断是否被包含
时间复杂度:O(n+m)
空间复杂度: O(1)
2. 如果 "abc" ==> "bca", "acb" 都属于它的兄弟字符串
那么判断一个字典中,某一个字符串的兄弟子串。
如果用通用判断方法,那显然相当复杂,这里用到了"标识",把一个字符串排序,然后转换成例如 a1b1c1
这种模式,然后产生一个 a1b1c1 => ["bca", "acb"] 的映射,对应 key 的值 就是兄弟数组。
时间复杂度: 用一个26的数组来辅助生成 a1b1c1, O(n*m) (m 字符的平均长度)
然后整个数组按key 排序,排序复杂度 O(nlogn), 然后再找出对应的 key 的value
*/
//1.暴力解法
func containsStr1(_ a: String, _ b: String) -> Bool {
let aArray = [Character](a.characters)
let bArray = [Character](b.characters)
for v in bArray {
var match = false
for c in aArray {
if c == v {
match = true
break
}
}
if !match {
return false
}
}
return true
}
//print(containsStr1("abc", "ad"))
//排序后轮询
func containsStr2(_ a: String, _ b: String) -> Bool {
var aArray = [Character](a.characters)
var bArray = [Character](b.characters)
aArray.sort(by: <)
bArray.sort(by: <)
//从 b 中去遍历
var index = 0
for v in bArray {
//找到第一个不比v小的数
while index < aArray.count, aArray[index] < v {
index += 1
}
//如果大于,直接返回
if index >= aArray.count || aArray[index] > v {
return false
}
}
return true
}
//print(containsStr2("abc", "ac"))
//素数排序
func containsStr3(_ a: String, _ b: String) -> Bool {
let nArray = [3, 5, 7, 11, 13, 17, 19, 23, 29, 31,
37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
79, 83, 89, 91, 97, 101]
let aArray = [Character](a.characters)
let bArray = [Character](b.characters)
var calcInt: Int = 1
for v in aArray {
let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value)
calcInt = calcInt * nArray[space]
}
for v in bArray {
let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value)
if calcInt % nArray[space] != 0 {
return false
}
}
return true
}
//print(containsStr3("abc", "ad"))
//位排序
func containsStr4(_ a: String, _ b: String) -> Bool {
var hashInt = 0
let aArray = [Character](a.characters)
let bArray = [Character](b.characters)
for v in aArray {
let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value)
hashInt |= 1 << space
}
for v in bArray {
let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value)
if hashInt & 1 << space == 0 {
return false
}
}
return true
}
//print(containsStr4("abc", "ad"))
//2.
func brotherStrings(_ a: String, _ b: [String]) -> [String] {
//convert "abc" to "a1b1c1"
func convert(_ s: String) -> String {
let cArray = [Character](s.characters)
var sArray = [("a", 0), ("b", 0), ("c", 0), ("d", 0), ("e", 0), ("f", 0), ("g", 0), ("h", 0), ("i", 0),
("j", 0), ("k", 0), ("l", 0), ("m", 0), ("n", 0), ("o", 0), ("p", 0), ("q", 0), ("r", 0),
("s", 0), ("t", 0), ("u", 0), ("v", 0), ("w", 0), ("x", 0), ("y", 0), ("z", 0)]
for v in cArray {
let space = Int(UnicodeScalar(String(v))!.value - UnicodeScalar("a")!.value)
sArray[space].1 += 1
}
var retStr = ""
for s in sArray {
if s.1 != 0 {
retStr += (s.0 + String(s.1))
}
}
return retStr
}
var bDic: [String: [String]] = [String: [String]]()
for s in b {
let key = convert(s)
if let _ = bDic[key] {
}
else {
bDic[key] = [String]()
}
bDic[key]?.append(s)
}
let aKey = convert(a)
if let array = bDic[aKey] {
return array
}
return [String]()
}
print(brotherStrings("abc", ["ab", "cba", "cab"]))
| 7bc612cb00b6f068bfd976d437261e73 | 23.93617 | 111 | 0.526024 | false | false | false | false |
shadanan/mado | refs/heads/master | Antlr4Runtime/Sources/Antlr4/misc/utils/StringBuilder.swift | mit | 3 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
//
// StringBuilder.swift
// antlr.swift
//
// Created by janyou on 15/9/4.
//
import Foundation
public class StringBuilder {
private var stringValue: String
public init(string: String = "") {
self.stringValue = string
}
public func toString() -> String {
return stringValue
}
public var length: Int {
return stringValue.length
}
@discardableResult
public func append(_ string: String) -> StringBuilder {
stringValue += string
return self
}
@discardableResult
public func append<T:CustomStringConvertible>(_ value: T) -> StringBuilder {
stringValue += value.description
return self
}
@discardableResult
public func appendLine(_ string: String) -> StringBuilder {
stringValue += string + "\n"
return self
}
@discardableResult
public func appendLine<T:CustomStringConvertible>(_ value: T) -> StringBuilder {
stringValue += value.description + "\n"
return self
}
@discardableResult
public func clear() -> StringBuilder {
stringValue = ""
return self
}
}
public func +=(lhs: StringBuilder, rhs: String) {
lhs.append(rhs)
}
public func +=<T:CustomStringConvertible>(lhs: StringBuilder, rhs: T) {
lhs.append(rhs.description)
}
public func +(lhs: StringBuilder, rhs: StringBuilder) -> StringBuilder {
return StringBuilder(string: lhs.toString() + rhs.toString())
}
| e63309f64fc3eab0c6ee82a5b8e91661 | 23.970149 | 84 | 0.64734 | false | false | false | false |
hirohisa/RxSwift | refs/heads/master | Preprocessor/Preprocessor/main.swift | mit | 5 | //
// main.swift
// Preprocessor
//
// Created by Krunoslav Zaher on 4/22/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
if Process.argc != 3 {
println("./Preprocessor <source-files-root> <derived-data> ")
exit(-1)
}
let sourceFilesRoot = Process.arguments[1]
let derivedData = Process.arguments[2]
let fileManager = NSFileManager()
func escape(value: String) -> String {
let escapedString = value.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
let escapedString1 = escapedString.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
let escapedString2 = escapedString1.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
return "\"\(escapedString2)\""
}
func processFile(path: String, outputPath: String) -> String {
let rawContent = NSData(contentsOfFile: path)!
let content = NSString(data: rawContent, encoding: NSUTF8StringEncoding)! as String
let components = content.componentsSeparatedByString("<%")
var functionContentComponents: [String] = []
functionContentComponents.append("var components: [String] = [\"// This file is autogenerated.\\n// Take a look at `Preprocessor` target in RxSwift project \\n\"]\n")
functionContentComponents.append("components.append(\(escape(components[0])))\n")
for codePlusSuffix in (components[1 ..< components.count]) {
let codePlusSuffixSeparated = codePlusSuffix.componentsSeparatedByString("%>")
if codePlusSuffixSeparated.count != 2 {
fatalError("Error in \(path) near \(codePlusSuffix)")
}
let code = codePlusSuffixSeparated[0]
let suffix = codePlusSuffixSeparated[1]
if code.hasPrefix("=") {
functionContentComponents.append("components.append(String(\(code.substringFromIndex(code.startIndex.successor()))))\n")
}
else {
functionContentComponents.append("\(code)\n")
}
functionContentComponents.append("components.append(\(escape(suffix)));\n")
}
functionContentComponents.append("\"\".join(components).writeToFile(\"\(outputPath)\", atomically: false, encoding: NSUTF8StringEncoding, error: nil);")
return "".join(functionContentComponents)
}
func runCommand(path: String) {
let pid = NSProcessInfo().processIdentifier
let task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = ["-c", "xcrun swift \"\(path)\""]
task.launch()
task.waitUntilExit()
if task.terminationReason != NSTaskTerminationReason.Exit {
exit(-1)
}
}
let files = fileManager.subpathsAtPath(sourceFilesRoot)
var generateAllFiles = ["// Generated code\n", "import Foundation\n"]
for file in files! {
if (file.pathExtension ?? "") != "tt" {
continue
}
let path = sourceFilesRoot.stringByAppendingPathComponent(file as! String)
let outputPath = path.substringToIndex(path.endIndex.predecessor().predecessor().predecessor()) + ".swift"
generateAllFiles.append("_ = { () -> Void in\n\(processFile(path, outputPath))\n}()\n")
}
let script = "".join(generateAllFiles)
let scriptPath = derivedData.stringByAppendingPathComponent("_preprocessor.sh")
script.writeToFile(scriptPath, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
runCommand(scriptPath) | c93523b4265753c7ccac159c6a6bfd00 | 33.464646 | 170 | 0.6781 | false | false | false | false |
frootloops/swift | refs/heads/master | test/IRGen/generic_vtable.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s --check-prefix=CHECK
// REQUIRES: CPU=x86_64
public class Base {
public func m1() {}
public func m2() {}
}
public class Derived<T> : Base {
public override func m2() {}
public func m3() {}
}
public class Concrete : Derived<Int> {
public override func m3() {}
public func m4() {}
}
//// Nominal type descriptor for 'Base' does not have any method descriptors.
// CHECK-LABEL: @_T014generic_vtable4BaseCMn = {{(protected )?}}constant
// -- nesting depth
// CHECK-SAME: i16 1,
// -- flags: has vtable
// CHECK-SAME: i16 4,
// -- generic parameters at depth 0
// CHECK-SAME: i32 0,
// -- vtable offset
// CHECK-SAME: i32 10,
// -- vtable size
// CHECK-SAME: i32 3
// -- no method descriptors -- class is fully concrete
// CHECK-SAME: section "{{.*}}", align 8
//// Type metadata for 'Base' has a static vtable.
// CHECK-LABEL: @_T014generic_vtable4BaseCMf = internal global
// -- vtable entry for 'm1()'
// CHECK-SAME: void (%T14generic_vtable4BaseC*)* @_T014generic_vtable4BaseC2m1yyF
// -- vtable entry for 'm2()'
// CHECK-SAME: void (%T14generic_vtable4BaseC*)* @_T014generic_vtable4BaseC2m2yyF
// -- vtable entry for 'init()'
// CHECK-SAME: %T14generic_vtable4BaseC* (%T14generic_vtable4BaseC*)* @_T014generic_vtable4BaseCACycfc
// --
// CHECK-SAME: , align 8
//// Nominal type descriptor for 'Derived' has method descriptors.
// CHECK-LABEL: @_T014generic_vtable7DerivedCMn = {{(protected )?}}constant
// -- nesting depth
// CHECK-SAME: i16 1,
// -- flags: has vtable
// CHECK-SAME: i16 4,
// -- generic parameters at depth 0
// CHECK-SAME: i32 1,
// -- vtable offset
// CHECK-SAME: i32 14,
// -- vtable size
// CHECK-SAME: i32 1,
// -- vtable entry for m3()
// CHECK-SAME: void (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedC2m3yyF
// --
// CHECK-SAME: section "{{.*}}", align 8
//// Type metadata pattern for 'Derived' has an empty vtable, filled in at
//// instantiation time.
// CHECK-LABEL: @_T014generic_vtable7DerivedCMP = internal global <{{.*}}> <{
// -- nominal type descriptor
// CHECK-SAME: @_T014generic_vtable7DerivedCMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// --
// CHECK-SAME: }>, align 8
//// Nominal type descriptor for 'Concrete' has method descriptors.
// CHECK-LABEL: @_T014generic_vtable8ConcreteCMn = {{(protected )?}}constant
// -- nesting depth
// CHECK-SAME: i16 1,
// -- flags: has vtable
// CHECK-SAME: i16 4,
// -- generic parameters at depth 0
// CHECK-SAME: i32 0,
// -- vtable offset
// CHECK-SAME: i32 15,
// -- vtable size
// CHECK-SAME: i32 1,
// -- vtable entry for m4()
// CHECK-SAME: void (%T14generic_vtable8ConcreteC*)* @_T014generic_vtable8ConcreteC2m4yyF
// --
// CHECK-SAME: section "{{.*}}", align 8
//// Type metadata for 'Concrete' does not have any vtable entries; the vtable is
//// filled in at initialization time.
// CHECK-LABEL: @_T014generic_vtable8ConcreteCMf = internal global <{{.*}}> <{
// -- nominal type descriptor
// CHECK-SAME: @_T014generic_vtable8ConcreteCMn,
// -- ivar destroyer
// CHECK-SAME: i8* null
// --
// CHECK-SAME: }>, align 8
//// Metadata initialization function for 'Derived' copies superclass vtable
//// and installs overrides for 'm2()' and 'init()'.
// CHECK-LABEL: define private %swift.type* @create_generic_metadata_Derived(%swift.type_pattern*, i8**)
// - 2 immediate members:
// - type metadata for generic parameter T,
// - and vtable entry for 'm3()'
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, {{.*}}, i64 2)
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], i64 0, {{.*}})
// -- method override for 'm2()'
// CHECK: [[WORDS:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[VTABLE0:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 11
// CHECK: store i8* bitcast (void (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedC2m2yyF to i8*), i8** [[VTABLE0]], align 8
// -- method override for 'init()'
// CHECK: [[VTABLE1:%.*]] = getelementptr inbounds i8*, i8** [[WORDS]], i32 12
// CHECK: store i8* bitcast (%T14generic_vtable7DerivedC* (%T14generic_vtable7DerivedC*)* @_T014generic_vtable7DerivedCACyxGycfc to i8*), i8** [[VTABLE1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
//// Metadata initialization function for 'Concrete' copies superclass vtable
//// and installs overrides for 'init()' and 'm3()'.
// CHECK-LABEL: define private void @initialize_metadata_Concrete(i8*)
// CHECK: [[SUPERCLASS:%.*]] = call %swift.type* @_T014generic_vtable7DerivedCySiGMa()
// CHECK: store %swift.type* [[SUPERCLASS]], %swift.type** getelementptr inbounds {{.*}} @_T014generic_vtable8ConcreteCMf
// CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, i64 96, i64 1)
// CHECK: call void @swift_initClassMetadata_UniversalStrategy(%swift.type* [[METADATA]], i64 0, {{.*}})
// -- method override for 'init()'
// CHECK: store i8* bitcast (%T14generic_vtable8ConcreteC* (%T14generic_vtable8ConcreteC*)* @_T014generic_vtable8ConcreteCACycfc to i8*), i8**
// -- method override for 'm3()'
// CHECK: store i8* bitcast (void (%T14generic_vtable8ConcreteC*)* @_T014generic_vtable8ConcreteC2m3yyF to i8*), i8**
// CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @_T014generic_vtable8ConcreteCML release, align 8
// CHECK: ret void
| e23bd52b65bcfc26adb4f07dea7cf34b | 35.133333 | 163 | 0.674539 | false | false | false | false |
sendyhalim/Yomu | refs/heads/master | Yomu/Screens/ChapterPageList/ChapterPageCollectionViewModel.swift | mit | 1 | //
// ChapterPagesViewModel.swift
// Yomu
//
// Created by Sendy Halim on 6/26/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import RxCocoa
import RxMoya
import RxSwift
import Swiftz
/// A data structure that represents zoom scale
struct ZoomScale: CustomStringConvertible {
/// Scale in 1 based, 1 -> 100%
let scale: Double
/// String representation of zoom scale,
/// will automatically multiply the scale by 100
var description: String {
return String(Int(scale * 100))
}
/// Normalize the given scale .
///
/// - parameter scale: Zoom scale, if the scale is greater than 10 then
/// it's considered as 100 based scale (I believe no one wants to zoom in by 1000%)
///
/// - returns: zoom scale with base 1 (1 -> 100%)
static private func normalize(scale: Double) -> Double {
return scale > 10 ? (scale / 100) : scale
}
init(scale: Double) {
self.scale = ZoomScale.normalize(scale: scale)
}
init(scale: String) {
self.init(scale: Double(scale)!)
}
}
struct PageSizeMargin {
let previousSize: CGSize
let currentSize: CGSize
var margin: CGSize {
return CGSize(
width: currentSize.width - previousSize.width,
height: currentSize.height - previousSize.height
)
}
}
struct ScrollOffset {
let marginHeight: CGFloat
let previousItemsCount: Int
var deltaY: CGFloat {
return marginHeight * CGFloat(previousItemsCount)
}
}
struct ChapterPageCollectionViewModel {
// MARK: Public
/// Chapter image
var chapterImage: ImageUrl? {
return _chapterPages.value.isEmpty ? .none : _chapterPages.value.first!.image
}
/// Number of pages in one chapter
var count: Int {
return _chapterPages.value.count
}
/// Chapter page size based on config
var pageSize: CGSize {
return _pageSize.value
}
// MARK: Input
let zoomIn = PublishSubject<Void>()
let zoomOut = PublishSubject<Void>()
// MARK: Output
let reload: Driver<Void>
let chapterPages: Driver<List<ChapterPage>>
let invalidateLayout: Driver<Void>
let zoomScale: Driver<String>
let headerTitle: Driver<String>
let chapterTitle: Driver<String>
let readingProgress: Driver<String>
let pageCount: Driver<String>
let zoomScroll: Driver<ScrollOffset>
let disposeBag = DisposeBag()
// MARK: Private
fileprivate let _chapterPages = Variable(List<ChapterPage>())
fileprivate let _currentPageIndex = Variable(0)
fileprivate let _pageSize = Variable(CGSize(
width: Config.chapterPageSize.width,
height: Config.chapterPageSize.height
))
fileprivate let _zoomScale = Variable(ZoomScale(scale: 1.0))
fileprivate let chapterVM: ChapterViewModel
init(chapterViewModel: ChapterViewModel) {
let _chapterPages = self._chapterPages
let _zoomScale = self._zoomScale
let _pageSize = self._pageSize
let _currentPageIndex = self._currentPageIndex
chapterVM = chapterViewModel
chapterPages = _chapterPages.asDriver()
reload = chapterPages
.asDriver()
.map(void)
readingProgress = _currentPageIndex
.asDriver()
.map { String($0 + 1) }
pageCount = _chapterPages
.asDriver()
.map { "/ \($0.count) pages" }
zoomIn
.map {
ZoomScale(scale: _zoomScale.value.scale + Config.chapterPageSize.zoomScaleStep)
}
.bind(to: _zoomScale) ==> disposeBag
zoomOut
.filter {
(_zoomScale.value.scale - Config.chapterPageSize.zoomScaleStep) > Config.chapterPageSize.minimumZoomScale
}
.map {
ZoomScale(scale: _zoomScale.value.scale - Config.chapterPageSize.zoomScaleStep)
}
.bind(to: _zoomScale) ==> disposeBag
_zoomScale
.asObservable()
.map { zoom in
CGSize(
width: Int(Double(Config.chapterPageSize.width) * zoom.scale),
height: Int(Double(Config.chapterPageSize.height) * zoom.scale)
)
}
.bind(to: _pageSize) ==> disposeBag
zoomScale = _zoomScale
.asDriver()
.map { $0.description }
invalidateLayout = _zoomScale
.asDriver()
.map(void)
let initialMargin = PageSizeMargin(previousSize: CGSize.zero, currentSize: _pageSize.value)
zoomScroll = _pageSize
.asDriver()
.scan(initialMargin) { previousSizeMargin, nextSize in
PageSizeMargin(previousSize: previousSizeMargin.currentSize, currentSize: nextSize)
}
.map {
ScrollOffset(
marginHeight: CGFloat($0.margin.height),
previousItemsCount: _currentPageIndex.value
)
}
headerTitle = chapterVM.number
chapterTitle = chapterVM.title
}
subscript(index: Int) -> ChapterPageViewModel {
let page = _chapterPages.value[UInt(index)]
return ChapterPageViewModel(page: page)
}
func fetch() -> Disposable {
return MangaEden
.request(MangaEdenAPI.chapterPages(chapterVM.chapter.id))
.mapArray(ChapterPage.self, withRootKey: "images")
.subscribe(onSuccess: {
let sortedPages = $0.sorted { x, y in
return x.number < y.number
}
self._chapterPages.value = List<ChapterPage>(fromArray: sortedPages)
})
}
func setCurrentPageIndex(_ index: Int) {
_currentPageIndex.value = index
}
func setZoomScale(_ scale: String) {
_zoomScale.value = ZoomScale(scale: scale)
}
func chapterIndexIsValid(index: Int) -> Bool {
return 0 ... (count - 1) ~= index
}
}
| 54820a85882af8be8dc6f66ffdba7020 | 25.038278 | 113 | 0.666483 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/API/Clients/SpotlightClient.swift | mit | 1 | //
// SpotlightClient.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 3/28/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import RealmSwift
struct SpotlightClient: APIClient {
let api: AnyAPIFetcher
init(api: AnyAPIFetcher) {
self.api = api
}
func search(query: String, realm: Realm? = Realm.current, completion: @escaping RequestCompletion) {
api.fetch(SpotlightRequest(query: query)) { response in
switch response {
case .resource(let resource):
guard resource.success else {
completion(nil, true)
return
}
realm?.execute({ (realm) in
var subscriptions: [Subscription] = []
resource.rooms.forEach { object in
// Important note: On this API "_id" means "rid"
if let roomIdentifier = object["_id"].string {
if let subscription = Subscription.find(rid: roomIdentifier, realm: realm) {
subscription.map(object, realm: realm)
subscription.mapRoom(object, realm: realm)
subscriptions.append(subscription)
} else {
let subscription = Subscription()
subscription.identifier = roomIdentifier
subscription.rid = roomIdentifier
subscription.name = object["name"].string ?? ""
if let typeRaw = object["t"].string, let type = SubscriptionType(rawValue: typeRaw) {
subscription.type = type
}
subscriptions.append(subscription)
}
}
}
resource.users.forEach { object in
let user = User.getOrCreate(realm: realm, values: object, updates: nil)
guard let username = user.username else {
return
}
let subscription = Subscription.find(name: username, subscriptionType: [.directMessage]) ?? Subscription()
if subscription.realm == nil {
subscription.identifier = subscription.identifier ?? user.identifier ?? ""
subscription.otherUserId = user.identifier
subscription.type = .directMessage
subscription.name = user.username ?? ""
subscription.fname = user.name ?? ""
subscriptions.append(subscription)
}
}
realm.add(subscriptions, update: true)
}, completion: {
completion(resource.raw, false)
})
case .error:
completion(nil, true)
}
}
}
}
| da62209f7d0176624df8051b850fc726 | 39.74359 | 130 | 0.461611 | false | false | false | false |
presence-insights/pi-sample-ios-DeviceRegistration | refs/heads/master | pi-sample-ios-DeviceRegistration/ViewController.swift | apache-2.0 | 1 | // © Copyright 2015 IBM Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import PresenceInsightsSDK
class ViewController: UIViewController, UITextFieldDelegate {
//hard coding the tenantID, orgID, username, password, baseURL
//This information can be found in your Presence Insights UI/Dashboard
let tenantID = ""
let orgID = ""
let username = ""
let passwd = ""
let baseURL = ""
override func viewDidLoad() {
super.viewDidLoad()
self.deviceName.delegate = self
self.deviceType.delegate = self
self.unencryptedDataValue.delegate = self
self.unencryptedDataKey.delegate = self
self.datakey.delegate = self
self.datavalue.delegate = self
//creating a PIAdapter object with bm information
piAdapter = PIAdapter(tenant: tenantID,
org: orgID,
baseURL: baseURL,
username: username,
password: passwd)
//piAdapter.enableLogging()
deviceType.userInteractionEnabled = false
//initializing device to see if it's registered when the app is loaded.
//if regsitered switch the registered switch to on.
// note: i do not pull the encrypted data and unecnrypted data in the fields when the device is populated.
device = PIDevice(name: " ")
piAdapter.getDeviceByDescriptor(device.descriptor) { (rdevice, NSError) -> () in
if((rdevice.name?.isEmpty) == nil){
}
else{
//using UI thread to make teh necessary changes.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.RegisterSwitch.setOn(true, animated: true)
self.deviceName.text = rdevice.name
self.deviceType.text = rdevice.type
self.alert("Status", messageInput: "The Device is currently registered. Device Name and Type will popular based on PI information")
})
print("Device is already registered")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//initializing piAdapter object and PIdevice
var piAdapter : PIAdapter!
var device : PIDevice!
@IBOutlet weak var deviceName: UITextField!
@IBOutlet weak var datakey: UITextField!
@IBOutlet weak var datavalue: UITextField!
@IBOutlet weak var unencryptedDataKey: UITextField!
@IBOutlet weak var unencryptedDataValue: UITextField!
@IBOutlet weak var deviceType: UITextField!
//pop up alert and display BM information
@IBAction func bmAction(sender: UIButton) {
alert("BM Information", messageInput: "Username: \(username) \n Password: \(passwd) \n Tenant ID: \(tenantID) \n Org ID: \(orgID)")
}
//UI selection for which device Type exist in the user's PI
@IBAction func DeviceTypeAction() {
//gets org information
piAdapter.getOrg { (org, NSError) -> () in
print(org.registrationTypes);
//grab the different device types
let Types = org.registrationTypes
print("TEST")
print(Types.count)
//need this dispatch to change from backend thread to UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let alert = UIAlertController(title: "Select Device Type", message: "", preferredStyle: UIAlertControllerStyle.Alert)
for Type in Types{
alert.addAction(UIAlertAction(title: "\(Type)", style: UIAlertActionStyle.Default, handler:{ (UIAlertAction) in
self.deviceType.text = Type
print(Type)
}))
}
alert.addAction(UIAlertAction(title: "cancel", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
})
}
}
//Update action
@IBAction func Action(sender: UIButton) {
//adding device name to the device object
device = PIDevice(name: deviceName.text!)
device.type = deviceType.text
//adding device type to the device object.
//NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External"
//method to add encrypted data
// ("VALUE", key: "KEY_NAME")
//checks to see if key or value is empty and throw error as necessary
if( MissingText(datavalue, key: datakey) == false){
device.addToDataObject(datavalue.text!, key: datakey.text!)
}
//checks to see if key or value is empty and throw error as necessary for unencrypted data
if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){
device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!)
}
//when the user flicks the switch to green
//checking to see if the device is registered before updating the device.
if RegisterSwitch.on {
//set device register to true if the light is on
device.registered=true
//device is registered and will update.
piAdapter.updateDevice(device, callback: { (newDevice, NSError) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(NSError == nil){
self.alert("Success", messageInput: "Successfully Updated the Device Information")
}
else{
self.alert("Error", messageInput: "\(NSError)")
}
})
})
}
else {
//if the device is not registered, will alert saying must register device
alert("Error", messageInput: "Must Register Device Before Updating")
}
}
//function to make keyboard disappear when pressing return.
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
@IBOutlet weak var RegisterSwitch: UISwitch!
//Register Switch Action
@IBAction func switchAction(sender: AnyObject) {
//adding device name to the device object
device = PIDevice(name: deviceName.text!)
device.type = deviceType.text
//adding device type to the device object.
//NOTE: the type has to exist in the Presence Insights. Default types are : "Internal" and "External"
//checks to see if key or value is empty
if( MissingText(datavalue, key: datakey) == false){
device.addToDataObject(datavalue.text!, key: datakey.text!)
}
// checks to see if key or value is empty
if( MissingText(unencryptedDataValue, key: unencryptedDataKey) == false){
device.addToUnencryptedDataObject(unencryptedDataValue.text!, key: unencryptedDataKey.text!)
}
if RegisterSwitch.on {
//PI Device Register SDK call
piAdapter.registerDevice(device, callback: { (newDevice, NSError) -> () in
// newDevice is of type PIDevice.
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(NSError == nil){
self.alert("Success", messageInput: "Successfully Registered the Device")
}
else{
self.alert("Error", messageInput: "\(NSError)")
}
})
})
}
else {
//PI Device unregister SDK call
piAdapter.unregisterDevice(device, callback: { (newDevice, NSError) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(NSError == nil){
self.alert("Success", messageInput: "Successfully Unregistered the Device")
}
else{
self.alert("Error", messageInput: "\(NSError)")
}
})
})
}
}
//function to easily create alert messages
func alert(titleInput : String , messageInput : String){
let alert = UIAlertController(title: titleInput, message: messageInput, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//function to check if both or none of the data value and key exist.
func MissingText (value: UITextField, key : UITextField) -> Bool{
if ( (key.text! == "" && value.text! == "")){
print("here")
return true
}
else{
print("test")
return false
}
}
}
| 3f4358adca5e44abec0de4078ac55a13 | 36.310861 | 151 | 0.576691 | false | false | false | false |
ivygulch/SwiftPromises | refs/heads/master | SwiftPromises/source/Synchronizer.swift | mit | 1 | //
// Synchronizer.swift
// SwiftPromises
//
// Created by Douglas Sjoquist on 2/25/15.
// Copyright (c) 2015 Ivy Gulch LLC. All rights reserved.
//
import Foundation
/**
A simple helper class that uses dispatch_sync to emulate Objective-C's @synchronize behavior
in swift classes.
Example usage:
```swift
let synchronizer = Synchronizer()
func functionAToBeSynchronized() {
synchronizer.synchronize {
// this is the code to be synchronized
}
}
func functionBToBeSynchronized() {
synchronizer.synchronize {
// this is the code to be synchronized
}
}
```
*/
open class Synchronizer : NSObject {
private let queue:DispatchQueue
/**
Creates a new synchronizer that uses a newly created, custom queue with a random name
*/
public override init() {
let uuid = UUID().uuidString
self.queue = DispatchQueue(label: "Sync.\(uuid)",attributes: [])
}
/**
Creates a new synchronizer that uses a newly created, custom queue with a given name
*/
public init(queueName:String) {
self.queue = DispatchQueue(label: queueName,attributes: [])
}
/**
Creates a new synchronizer that uses an existing dispatch queue
*/
public init(queue:DispatchQueue) {
self.queue = queue
}
/**
- Parameter closure: the closure to be synchronized
*/
public func synchronize(_ closure:()->Void) {
queue.sync(execute: {
closure()
})
}
}
| 3e3d4f8da64c747b844e95ac1cd3f2bb | 21.402985 | 92 | 0.639574 | false | false | false | false |
svenbacia/TraktKit | refs/heads/master | TraktKit/Sources/Resource/Generic/Resource+Request.swift | mit | 1 | //
// Resource+Request.swift
// TraktKit
//
// Created by Sven Bacia on 29.10.17.
// Copyright © 2017 Sven Bacia. All rights reserved.
//
import Foundation
func buildRequest(base: String, path: String, params: [String: Any]?, method: Method) -> URLRequest {
func body(from params: [String: Any]?, method: Method) -> Data? {
guard let params = params, method.allowsHttpBody else { return nil }
return try? JSONSerialization.data(withJSONObject: params, options: [])
}
return buildRequest(base: base, path: path, params: params, body: body(from: params, method: method), method: method)
}
func buildRequest(base: String, path: String, params: [String: Any]?, body: Data?, method: Method) -> URLRequest {
guard var components = URLComponents(string: base) else { fatalError("unexpected url components") }
components.path = path
if let params = params as? [String: String], method == .get {
components.queryItems = params.map(toQueryItem)
}
guard let url = components.url else { fatalError("could not build url with path: \(path)") }
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
if let body = body, method.allowsHttpBody {
request.httpBody = body
}
return request
}
| 4f4de777f8d388e9834376c95cd3b8d6 | 33.72973 | 121 | 0.675486 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/stdlib/NewStringAppending.swift | apache-2.0 | 2 | // RUN: %target-run-stdlib-swift | %FileCheck %s
// REQUIRES: executable_test
//
// Parts of this test depend on memory allocator specifics. The test
// should be rewritten soon so it doesn't expose legacy components
// like OpaqueString anyway, so we can just disable the failing
// configuration
//
// Memory allocator specifics also vary across platforms.
// REQUIRES: CPU=x86_64, OS=macosx
import Foundation
import Swift
func hexAddrVal<T>(_ x: T) -> String {
return "@0x" + String(UInt64(unsafeBitCast(x, to: Int.self)), radix: 16)
}
func hexAddr(_ x: AnyObject?) -> String {
if let owner = x {
if let y = owner as? _StringBuffer._Storage.Storage {
return ".native\(hexAddrVal(y))"
}
if let y = owner as? NSString {
return ".cocoa\(hexAddrVal(y))"
}
else {
return "?Uknown?\(hexAddrVal(owner))"
}
}
return "nil"
}
func repr(_ x: NSString) -> String {
return "\(NSStringFromClass(object_getClass(x)))\(hexAddr(x)) = \"\(x)\""
}
func repr(_ x: _StringCore) -> String {
if x.hasContiguousStorage {
if let b = x.nativeBuffer {
let offset = x.elementWidth == 2
? b.start - UnsafeMutableRawPointer(x.startUTF16)
: b.start - UnsafeMutableRawPointer(x.startASCII)
return "Contiguous(owner: "
+ "\(hexAddr(x._owner))[\(offset)...\(x.count + offset)]"
+ ", capacity = \(b.capacity))"
}
return "Contiguous(owner: \(hexAddr(x._owner)), count: \(x.count))"
}
else if let b2 = x.cocoaBuffer {
return "Opaque(buffer: \(hexAddr(b2))[0...\(x.count)])"
}
return "?????"
}
func repr(_ x: String) -> String {
return "String(\(repr(x._core))) = \"\(x)\""
}
// ===------- Appending -------===
// CHECK: --- Appending ---
print("--- Appending ---")
var s = "⓪" // start non-empty
// To make this test independent of the memory allocator implementation,
// explicitly request initial capacity.
s.reserveCapacity(8)
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer0:[x0-9a-f]+]][0...2], capacity = 8)) = "⓪1"
s += "1"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer1:[x0-9a-f]+]][0...8], capacity = 8)) = "⓪1234567"
s += "234567"
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2:[x0-9a-f]+]][0...9], capacity = 16)) = "⓪12345678"
// CHECK-NOT: .native@[[buffer1]]
s += "8"
print("\(repr(s))")
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer2]][0...16], capacity = 16)) = "⓪123456789012345"
s += "9012345"
print("\(repr(s))")
// -- expect a reallocation here
// Appending more than the next level of capacity only takes as much
// as required. I'm not sure whether this is a great idea, but the
// point is to prevent huge amounts of fragmentation when a long
// string is appended to a short one. The question, of course, is
// whether more appends are coming, in which case we should give it
// more capacity. It might be better to always grow to a multiple of
// the current capacity when the capacity is exceeded.
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer3:[x0-9a-f]+]][0...48], capacity = 48))
// CHECK-NOT: .native@[[buffer2]]
s += s + s
print("\(repr(s))")
// -- expect a reallocation here
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4:[x0-9a-f]+]][0...49], capacity = 96))
// CHECK-NOT: .native@[[buffer3]]
s += "C"
print("\(repr(s))")
var s1 = s
// CHECK-NEXT: String(Contiguous(owner: .native@[[buffer4]][0...49], capacity = 96))
print("\(repr(s1))")
/// The use of later buffer capacity by another string forces
/// reallocation
// CHECK-NEXT: String{{.*}} = {{.*}}X"
// CHECK-NOT: .native@[[buffer4]]
s1 += "X"
print("\(repr(s1))")
/// Appending to an empty string re-uses the RHS
// CHECK-NEXT: .native@[[buffer4]]
var s2 = String()
s2 += s
print("\(repr(s2))")
| 276b1c87d92679e20a91a202ad43138a | 28.267176 | 108 | 0.632238 | false | false | false | false |
vitortexc/MyAlertController | refs/heads/master | MyAlertController/MyAlertOverlayView.swift | mit | 1 | //
// MyAlertOverlayView.swift
// Pods
//
// Created by Vitor Carrasco on 28/04/17.
// Copyright © 2017 Empresinha. All rights reserved.
//
// 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
final class MyAlertOverlayView: UIView {
// MARK: - Appearance
/// The blur radius of the overlay view
@objc public dynamic var blurRadius: Float {
get { return Float(blurView.blurRadius) }
set { blurView.blurRadius = CGFloat(newValue) }
}
/// Turns the blur of the overlay view on or off
@objc public dynamic var blurEnabled: Bool {
get { return blurView.isBlurEnabled }
set {
blurView.isBlurEnabled = newValue
blurView.alpha = newValue ? 1 : 0
}
}
/// Whether the blur view should allow for
/// dynamic rendering of the background
@objc public dynamic var liveBlur: Bool {
get { return blurView.isDynamic }
set { return blurView.isDynamic = newValue }
}
/// The background color of the overlay view
@objc public dynamic var color: UIColor? {
get { return overlay.backgroundColor }
set { overlay.backgroundColor = newValue }
}
/// The opacity of the overay view
@objc public dynamic var opacity: Float {
get { return Float(overlay.alpha) }
set { overlay.alpha = CGFloat(newValue) }
}
// MARK: - Views
internal lazy var blurView: FXBlurView = {
let blurView = FXBlurView(frame: .zero)
blurView.blurRadius = 8
blurView.isDynamic = false
blurView.tintColor = UIColor.clear
blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
return blurView
}()
internal lazy var overlay: UIView = {
let overlay = UIView(frame: .zero)
overlay.backgroundColor = UIColor.black
overlay.autoresizingMask = [.flexibleHeight, .flexibleWidth]
overlay.alpha = 0.7
return overlay
}()
// MARK: - Inititalizers
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View setup
internal override func setupView() {
// Self appearance
self.autoresizingMask = [.flexibleHeight, .flexibleWidth]
self.backgroundColor = UIColor.clear
self.alpha = 0
// Add subviews
addSubview(blurView)
addSubview(overlay)
}
}
| e84be9ceb22f25a6fbbd7ee52cb9a950 | 27.020833 | 81 | 0.713755 | false | false | false | false |
jdbateman/OnTheMap | refs/heads/master | OnTheMap/LoginViewController.swift | mit | 1 | //
// LoginViewController.swift
// OnTheMap
//
// Created by john bateman on 7/23/15.
// Copyright (c) 2015 John Bateman. All rights reserved.
//
// This file implements the LoginViewController which allows the user to create an account on Udacity, Login to a session on Udacity, or Login to Facebook on the device.
import UIKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
@IBOutlet weak var loginButton: FBSDKLoginButton!
var appDelegate: AppDelegate!
var activityIndicator : UIActivityIndicatorView = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50)) as UIActivityIndicatorView
/* a reference to the studentLocations singleton */
let studentLocations = StudentLocations.sharedInstance()
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// get a reference to the app delegate
appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Setup facebook login...
// Facebook Login
loginButton.delegate = self
// request access to user's facebook profile, email, and friends
self.loginButton.readPermissions = ["public_profile", "email", "user_friends"]
if (FBSDKAccessToken.currentAccessToken() != nil) {
// The user is already logged in to Facebook on this device.
appDelegate.loggedIn == true
// Acquire the user's facebook user id.
getFacebookUserID()
}
// If already logged in to Udacity or Facebook present the Tab Bar conttoller.
if appDelegate.loggedIn == true {
presentMapController()
}
// inset text in edit text fields
var insetView = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
emailTextField.leftViewMode = UITextFieldViewMode.Always
emailTextField.leftView = insetView
var insetViewPwd = UIView(frame:CGRect(x:0, y:0, width:10, height:10))
passwordTextField.leftViewMode = UITextFieldViewMode.Always
passwordTextField.leftView = insetViewPwd
// set placeholder text color to white in edit text fields
emailTextField.attributedPlaceholder = NSAttributedString(string:"Email",
attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
passwordTextField.attributedPlaceholder = NSAttributedString(string:"Password",
attributes:[NSForegroundColorAttributeName: UIColor.whiteColor()])
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.view.setNeedsDisplay()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/* User selected Login button. Attempt to login to Parse. */
@IBAction func onLoginButtonTap(sender: AnyObject) {
startActivityIndicator()
if let username = emailTextField.text, password = passwordTextField.text {
RESTClient.sharedInstance().loginUdacity(username: username, password: password) {result, accountKey, error in
if error == nil {
self.appDelegate.loggedIn = true
// Get the logged in user's data from the Udacity service and store the relevant elements in a studentLocation variable for retrieval later when we post the user's data to Parse.
self.getLoggedInUserData(userAccountKey: accountKey) { success, studentLocation, error in
if error == nil {
// got valid user data back, so save it
self.appDelegate.loggedInUser = studentLocation
} else {
// didn't get valid data back so set to default values
self.appDelegate.loggedInUser = StudentLocation()
}
}
// get student locations from Parse
self.studentLocations.reset()
self.studentLocations.getStudentLocations(0) { success, errorString in
dispatch_async(dispatch_get_main_queue()) {
self.stopActivityIndicator()
}
if success == false {
if let errorString = errorString {
OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: errorString)
} else {
OTMError(viewController:self).displayErrorAlertView("Error retrieving Locations", message: "Unknown error")
}
} else {
// successfully logged in - save the user's account key
self.appDelegate.loggedInUser?.uniqueKey = accountKey
self.presentMapController()
}
}
self.presentMapController()
} else {
self.appDelegate.loggedIn = false
dispatch_async(dispatch_get_main_queue()) {
self.stopActivityIndicator()
self.parseLoginError(error!)
OTMError(viewController:self).displayErrorAlertView("Login Error", message: error!.localizedDescription)
}
}
}
}
}
/*
@brief Get user data for logged in user
@param (in) userAccountKey: The Udacity account key for the user account.
*/
func getLoggedInUserData(#userAccountKey: String, completion: (success: Bool, studentLocation: StudentLocation?, error: NSError?) -> Void) {
RESTClient.sharedInstance().getUdacityUser(userID: userAccountKey) { result, studentLocation, error in
if error == nil {
completion(success: true, studentLocation: studentLocation, error: nil)
}
else {
println("error getUdacityUser()")
completion(success: false, studentLocation: nil, error: error)
}
}
}
/* SignUp button selected. Open Udacity signup page in the Safari web browser. */
@IBAction func onSignUpButtonTap(sender: AnyObject) {
let signupUrl = RESTClient.Constants.udacityBaseURL + RESTClient.Constants.udacitySignupMethod
if let requestUrl = NSURL(string: signupUrl) {
UIApplication.sharedApplication().openURL(requestUrl)
}
}
/* Modally present the MapViewController on the main thread. */
func presentMapController() {
dispatch_async(dispatch_get_main_queue()) {
//self.displayMapViewController()
self.performSegueWithIdentifier("LoginToTabBarSegueID", sender: self)
}
}
/* show activity indicator */
func startActivityIndicator() {
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
}
/* hide acitivity indicator */
func stopActivityIndicator() {
activityIndicator.stopAnimating()
}
// Facebook Delegate Methods
/* The Facebook login button was selected. Get the user's Facebook Id and transition to the Map view controller. */
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
appDelegate.loggedIn = true
if ((error) != nil)
{
// Process the error
}
else if result.isCancelled {
// Handle the cancellation
}
else {
// Acquire the user's facebook user id
getFacebookUserID()
// Verify permissions were granted.
if result.grantedPermissions.contains("email")
{
println("facebook email permission granted")
}
if result.grantedPermissions.contains("public_profile")
{
println("facebook public_profile permission granted")
}
if result.grantedPermissions.contains("user_friends")
{
println("facebook user_friends permission granted")
}
// present the MapViewController
presentMapController()
}
}
/* The user selected the logout facebook button. */
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
appDelegate.loggedIn = false
}
/* Acquire the user's Facebook user id */
func getFacebookUserID() {
//let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
let fbToken = FBSDKAccessToken.currentAccessToken()
self.appDelegate.loggedInUser?.uniqueKey = fbToken.userID
}
/* Identify the UITextView responsible for the error, and shake the appropriate UITextView. */
func parseLoginError(error: NSError) {
let message = error.localizedDescription
// Handle case where the username or password was not supplied
if error.code == 400 {
//if message.lowercaseString.rangeOfString("Error 400") != nil && message.lowercaseString.rangeOfString("Missing parameter") != nil {
if message.lowercaseString.rangeOfString("username") != nil {
self.shake(self.emailTextField)
} else if message.lowercaseString.rangeOfString("password") != nil {
self.shake(self.passwordTextField)
}
}
// Handle case where username or password was incorrect
else if error.code == 403 &&
message.lowercaseString.rangeOfString("Account not found") != nil || message.lowercaseString.rangeOfString("invalid credentials") != nil {
self.shake(self.emailTextField)
self.shake(self.passwordTextField)
}
}
/* Create a shake animation for the specified textField. */
func shake(textField: UITextField) {
let shakeAnimation = CABasicAnimation(keyPath: "position")
shakeAnimation.duration = 0.1
shakeAnimation.repeatCount = 3
shakeAnimation.autoreverses = true
shakeAnimation.fromValue = NSValue(CGPoint: CGPointMake(textField.center.x - 7, textField.center.y - 2))
shakeAnimation.toValue = NSValue(CGPoint: CGPointMake(textField.center.x + 7, textField.center.y + 2))
textField.layer.addAnimation(shakeAnimation, forKey: "position")
}
}
| 86dd0ee50f63a6badedeb6075d37bd60 | 42.042308 | 198 | 0.606023 | false | false | false | false |
twtstudio/WePeiYang-iOS | refs/heads/master | WePeiYang/PartyService/Controller/TwentyCourseScoreViewController.swift | mit | 1 | //
// TwentyCourseScoreViewController.swift
// WePeiYang
//
// Created by JinHongxu on 16/8/14.
// Copyright © 2016年 Qin Yubo. All rights reserved.
//
import Foundation
class TwentyCourseScoreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var scoreList = []
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
Applicant.sharedInstance.get20score({
self.scoreList = Applicant.sharedInstance.scoreOf20Course
self.tableView.reloadData()
})
}
//iOS 8 fucking bug
init(){
super.init(nibName: "TwentyCourseScoreViewController", bundle: nil)
//print("haha")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//print(Applicant.sharedInstance.scoreOf20Course.count)
return scoreList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let dict = scoreList[indexPath.row]
let cell = ScoreTableViewCell(title: dict.objectForKey("course_name") as! String, score: dict.objectForKey("score") as! String, completeTime: dict.objectForKey("complete_time") as! String)
cell.selectionStyle = .None
//cell?.textLabel?.text = Applicant.sharedInstance.scoreOf20Course[indexPath.row].objectForKey("course_name")
return cell
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard section == 0 else {
return nil
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: (UIApplication.sharedApplication().keyWindow?.frame.size.width)!, height: 40))
let titleLabel = UILabel(text: "课程名称")
let scoreLabel = UILabel(text: "成绩")
let timeLabel = UILabel(text: "完成时间")
titleLabel.font = UIFont.boldSystemFontOfSize(13.0)
scoreLabel.font = UIFont.boldSystemFontOfSize(13.0)
timeLabel.font = UIFont.boldSystemFontOfSize(13.0)
view.addSubview(titleLabel)
view.addSubview(scoreLabel)
view.addSubview(timeLabel)
timeLabel.snp_makeConstraints {
make in
make.right.equalTo(view).offset(-8)
make.centerY.equalTo(view)
}
scoreLabel.snp_makeConstraints {
make in
make.right.equalTo(timeLabel.snp_left).offset(-56)
make.centerY.equalTo(view)
}
titleLabel.snp_makeConstraints {
make in
make.left.equalTo(view).offset(8)
make.centerY.equalTo(view)
}
return view
}
} | a93f5b16c95d286c7c4f082113d0297c | 30.101852 | 196 | 0.616438 | false | false | false | false |
zhubinchen/MarkLite | refs/heads/master | MarkLite/Utils/ActivityIndicator.swift | gpl-3.0 | 2 | //
// UIView+Loading.swift
// Markdown
//
// Created by 朱炳程 on 2020/5/13.
// Copyright © 2020 zhubch. All rights reserved.
//
import UIKit
class ActivityIndicator {
var inticators = [UIView]()
var toast: UIView?
static let shared = ActivityIndicator()
class func showError(withStatus: String?) {
showMessage(message: withStatus)
}
class func showSuccess(withStatus: String?) {
showMessage(message: withStatus)
}
class func showMessage(message: String?) {
guard let v = UIApplication.shared.keyWindow else { return }
ActivityIndicator.shared.toast?.removeFromSuperview()
let bg = UIView()
ActivityIndicator.shared.toast = bg
bg.setBackgroundColor(.primary)
bg.cornerRadius = 8
v.addSubview(bg)
bg.snp.makeConstraints { maker in
maker.center.equalToSuperview()
maker.width.lessThanOrEqualToSuperview().multipliedBy(0.8)
maker.height.greaterThanOrEqualTo(30)
}
let label = UILabel()
label.text = message
label.setTextColor(.background)
label.textAlignment = .center
label.font = UIFont.systemFont(ofSize: 16)
bg.addSubview(label)
label.snp.makeConstraints { maker in
maker.top.equalToSuperview().offset(10)
maker.left.equalToSuperview().offset(10)
maker.right.equalToSuperview().offset(-10)
maker.bottom.equalToSuperview().offset(-10)
}
UIView.animate(withDuration: 0.5, delay: 1.0, options: .curveLinear, animations: {
bg.alpha = 0
})
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
ActivityIndicator.shared.toast?.removeFromSuperview()
}
}
class func show(on parent: UIView? = UIApplication.shared.keyWindow) {
guard let v = parent else { return }
let container = UIView()
container.backgroundColor = .clear
container.frame = v.bounds
v.addSubview(container)
container.snp.makeConstraints { maker in
maker.edges.equalToSuperview()
}
let loadingView = UIView()
loadingView.isHidden = true
let size = CGSize(width: 30, height: 30)
container.addSubview(loadingView)
loadingView.snp.makeConstraints { maker in
maker.center.equalToSuperview()
maker.size.equalTo(size)
}
if v == UIApplication.shared.keyWindow {
setUpAnimation(in: loadingView.layer, size: size, color: ColorCenter.shared.secondary.value)
} else {
setUpAnimation(in: loadingView.layer, size: size, color: ColorCenter.shared.secondary.value)
}
ActivityIndicator.shared.inticators.append(container)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
loadingView.isHidden = false
if v == UIApplication.shared.keyWindow {
container.backgroundColor = UIColor(white: 0, alpha: 0.2)
}
}
print("ActivityIndicator add\(ActivityIndicator.shared.inticators.count)")
}
class func dismiss() {
guard let v = UIApplication.shared.keyWindow else { return }
dismissOnView(v)
}
class func dismissOnView(_ view: UIView) {
guard let v = ActivityIndicator.shared.inticators.first(where: { $0.superview == view }) else { return }
v.removeFromSuperview()
ActivityIndicator.shared.inticators = ActivityIndicator.shared.inticators.filter{ $0.window != nil }
print("ActivityIndicator remove\(ActivityIndicator.shared.inticators.count)")
}
class func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let lineSize = size.width / 9
let x = (layer.bounds.size.width - size.width) / 2
let y = (layer.bounds.size.height - size.height) / 2
let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08)
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.scale.y")
animation.keyTimes = [0, 0.5, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.4, 1]
animation.duration = 1
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw lines
for i in 0 ..< 5 {
let line: CAShapeLayer = CAShapeLayer()
var path: UIBezierPath = UIBezierPath()
let size = CGSize(width: lineSize, height: size.height)
path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height),
cornerRadius: size.width / 2)
line.fillColor = color.cgColor
line.backgroundColor = nil
line.path = path.cgPath
line.frame = CGRect(x: x + lineSize * 2 * CGFloat(i), y: y, width: size.width, height: size.height)
animation.beginTime = Double(integerLiteral: Int64(i)) * 0.1 + CACurrentMediaTime()
line.add(animation, forKey: "animation")
layer.addSublayer(line)
}
}
}
| 000fcfa7b75ec5fbab8de6f539a4c0d6 | 36.119718 | 112 | 0.611079 | false | false | false | false |
zhoudengfeng8/EmptyDataSetInfo | refs/heads/master | EmptyDataSetInfo/EmptyInfoTableViewCell.swift | mit | 1 | //
// EmptyInfoTableViewCell.swift
// Kirin-iOS
//
// Created by zhou dengfeng derek on 1/12/16.
//
//
import UIKit
@objc protocol EmptyInfoTableViewCellDelegate: class {
@objc optional func emptyInfoTableViewCellDidTapInfoButton(cell: EmptyInfoTableViewCell)
}
class EmptyInfoTableViewCell: UITableViewCell {
weak var delegate: EmptyInfoTableViewCellDelegate?
@IBOutlet weak var infoLabel: UILabel!
@IBOutlet weak var infoImageView: UIImageView!
@IBOutlet weak var infoButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
setupInfoButton()
}
private func setupInfoButton() {
layoutIfNeeded()
infoButton.layer.cornerRadius = 4.0
infoButton.layer.borderColor = UIColor(red: 0, green: 122/255.0, blue: 1, alpha: 1).cgColor
infoButton.layer.borderWidth = 1.0
infoButton.contentEdgeInsets = UIEdgeInsetsMake(5, 15, 5, 15)
infoButton.addTarget(self, action: #selector(tapInfoButton(_:)), for: .touchUpInside)
}
func tapInfoButton(_ sender: UIButton) {
_ = self.delegate?.emptyInfoTableViewCellDidTapInfoButton?(cell: self)
}
}
| e1e7937d4032eeeaf1046108e14bde65 | 27.47619 | 99 | 0.685619 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/keypath_covariant_override.swift | apache-2.0 | 30 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -enable-library-evolution %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
// RUN: %target-swift-frontend -emit-ir -enable-library-evolution %s
public class C : Hashable {
public static func ==(lhs: C, rhs: C) -> Bool { return lhs === rhs }
public func hash(into: inout Hasher) {}
}
public class Base {
public var int: Int? { fatalError() }
public var ref: C? { fatalError() }
public subscript(x x: Int) -> Int? { fatalError() }
public subscript(y y: C) -> C? { fatalError() }
}
public class Derived : Base {
public override var int: Int { fatalError() }
public override var ref: C { fatalError() }
public override subscript(x x: Int?) -> Int { fatalError() }
public override subscript(y y: C?) -> C { fatalError() }
}
public class Generic<T> {
public var generic: T { fatalError() }
public subscript(x x: T) -> T? { fatalError() }
public subscript(y y: T?) -> T? { fatalError() }
}
public class DerivedGeneric<T> : Generic<T?> {
public override var generic: T? { fatalError() }
public subscript(x x: T) -> T { fatalError() }
public subscript(y y: T) -> T { fatalError() }
}
public class DerivedConcrete : Generic<Int?> {
public override var generic: Int? { fatalError() }
public subscript(x x: Int?) -> Int { fatalError() }
public subscript(y y: Int?) -> Int? { fatalError() }
}
@inlinable public func keyPaths() {
_ = \Derived.int
_ = \Derived.ref
_ = \Derived.[x: nil]
_ = \Derived.[y: nil]
_ = \DerivedGeneric<Int>.generic
_ = \DerivedGeneric<Int>.[x: nil]
_ = \DerivedGeneric<Int>.[y: nil]
_ = \DerivedConcrete.generic
_ = \DerivedConcrete.[x: nil]
_ = \DerivedConcrete.[y: nil]
}
// CHECK: sil_property #C.hashValue ()
// CHECK-NEXT: sil_property #Base.int ()
// CHECK-NEXT: sil_property #Base.ref ()
// CHECK-NEXT: sil_property #Base.subscript ()
// CHECK-NEXT: sil_property #Base.subscript ()
// CHECK-NEXT: sil_property #Derived.int ()
// CHECK-NEXT: sil_property #Derived.subscript ()
// CHECK-NEXT: sil_property #Generic.generic<τ_0_0> ()
// CHECK-NEXT: sil_property #Generic.subscript<τ_0_0> ()
// CHECK-NEXT: sil_property #Generic.subscript<τ_0_0> ()
// CHECK-NEXT: sil_property #DerivedGeneric.subscript<τ_0_0> ()
// CHECK-NEXT: sil_property #DerivedGeneric.subscript<τ_0_0> ()
// CHECK-NEXT: sil_property #DerivedConcrete.subscript ()
// CHECK-NEXT: sil_property #DerivedConcrete.subscript ()
| 303bf00ebe7dec700531a3a10cd62f0e | 31.311688 | 78 | 0.651929 | false | false | false | false |
HeartRateLearning/HRLApp | refs/heads/master | HRLApp/Common/HealthStore/HealthStoreFactory.swift | mit | 1 | //
// HealthStoreFactory.swift
// HRLApp
//
// Created by Enrique de la Torre (dev) on 01/02/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
import Foundation
import HealthKit
// MARK: - Main body
final class HealthStoreFactory {
// MARK: - Private properties
fileprivate var state = State.rejected
}
// MARK: - HealthStoreFactoryProtocol methods
extension HealthStoreFactory: HealthStoreFactoryProtocol {
func setup() {
guard !isRequestingAuthorization() else {
print("Already requesting authorization")
return
}
requestAuthorization()
}
func makeHeartRateReader() -> HeartRateReaderProtocol? {
guard let currentStore = currentHealthStore() else {
return nil
}
return HeartRateReader(store: currentStore)
}
func makeWorkoutWriter() -> WorkoutWriterProtocol? {
guard let currentStore = currentHealthStore() else {
return nil
}
return WorkoutWriter(store: currentStore)
}
}
// MARK: - Private body
private extension HealthStoreFactory {
// MARK: - Type definitions
enum State {
case requesting
case rejected
case authorized(HKHealthStore)
init(isAuthorized: Bool, store: HKHealthStore) {
self = isAuthorized ? .authorized(store) : .rejected
}
}
// MARK: - Constants
enum Constants {
static let typesToShare = Set(arrayLiteral: WorkoutWriter.workoutType)
static let typesToRead = Set(arrayLiteral: HeartRateReader.heartRateType)
}
// MARK: - Private methods
func isRequestingAuthorization() -> Bool {
var isRequesting = false
switch state {
case .requesting:
isRequesting = true
default:
isRequesting = false
}
return isRequesting
}
func requestAuthorization() {
guard HKHealthStore.isHealthDataAvailable() else {
print("Health data is NOT available")
state = .rejected
return
}
state = .requesting
let store = HKHealthStore()
let completion = { [weak self] (success: Bool, error: Error?) in
if !success {
print("Request authorization failed: \(error)")
}
DispatchQueue.main.async {
self?.state = State(isAuthorized: success, store: store)
}
}
store.requestAuthorization(toShare: Constants.typesToShare,
read: Constants.typesToRead,
completion: completion)
}
func currentHealthStore() -> HKHealthStore? {
var currentStore: HKHealthStore?
switch state {
case .authorized(let store):
currentStore = store
default:
currentStore = nil
}
return currentStore
}
}
| 307177004f715646c1b9fb9b9f761ad9 | 22.062016 | 81 | 0.591597 | false | false | false | false |
adamahrens/noisily | refs/heads/master | Noisily/Noisily/NoisePlayManager.swift | mit | 1 | //
// NoisePlayManager.swift
// Noisily
//
// Created by Adam Ahrens on 3/19/15.
// Copyright (c) 2015 Appsbyahrens. All rights reserved.
//
import AVFoundation
class NoisePlayerManager: NSObject, AVAudioPlayerDelegate {
private var players = [Noise : AVAudioPlayer]()
/**
Toggles playing the noise. If currently playing turns it off, otherwise on
- parameter noise: The Noise to toggle on/off
*/
func toggleNoise(noise: Noise) {
let noiseResource = noise.soundFilePath()
var error: NSError?
// Already have a player going for the noise
if let player = players[noise] {
player.stop()
players[noise] = nil
} else {
// Need to start a new player
let player: AVAudioPlayer!
do {
player = try AVAudioPlayer(contentsOfURL: noiseResource)
} catch let error1 as NSError {
error = error1
player = nil
}
player.volume = 0.5
player.numberOfLoops = -1
player.delegate = self
player.prepareToPlay()
player.play()
players[noise] = player
}
if (error != nil) {
print("Error constructing player \(error)")
}
}
/**
Determines if a noise is currently playing
*/
func noiseIsPlaying(noise: Noise) -> Bool {
return players[noise] != nil
}
/**
Adjusts the volume level of a noise if it's currently playing
- parameter noise: The Noise to adjust
- parameter volume: Volume level between 0.0 and 1.0 (inclusive)
*/
func adjustVolumeLevel(noise: Noise, volume: Double) {
if let player = players[noise] {
assert(volume >= 0.0 && volume <= 1.0, "Volume has to been in 0.0 - 1.0 range")
player.volume = Float(volume)
}
}
} | 36084e5868f3bf603a8756c740348a1d | 27.661765 | 91 | 0.560062 | false | false | false | false |
box/box-ios-sdk | refs/heads/main | Sources/Core/Errors/BoxSDKError.swift | apache-2.0 | 1 | //
// BoxSDKError.swift
// BoxSDK-iOS
//
// Created by Sujay Garlanka on 10/14/19.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Box SDK Error
public enum BoxSDKErrorEnum: BoxEnum {
// swiftlint:disable cyclomatic_complexity
/// Box client was destroyed
case clientDestroyed
/// URL is invalid
case invalidURL(urlString: String)
/// The requested resource was not found
case notFound(String)
/// Object needed in closure was deallocated
case instanceDeallocated(String)
/// Could not decode or encode keychain data
case keychainDataConversionError
/// Value not found in Keychain
case keychainNoValue
/// Unhandled keychain error
case keychainUnhandledError(String)
/// Request has hit the maximum number of retries
case rateLimitMaxRetries
/// Value for key is of an unexpected type
case typeMismatch(key: String)
/// Value for key is not one of the accepted values
case valueMismatch(key: String, value: String, acceptedValues: [String])
/// Value for key is of a valid type, but was not able to convert value to expected type
case invalidValueFormat(key: String)
/// Key was not present
case notPresent(key: String)
/// The file representation couldn't be made
case representationCreationFailed
/// Error with TokenStore operation (write, read or clear)
case tokenStoreFailure
/// Unsuccessful token retrieval. Token not found
case tokenRetrieval
/// OAuth web session authorization failed due to invalid redirect configuration
case invalidOAuthRedirectConfiguration
/// Couldn't obtain authorization code from OAuth web session result
case invalidOAuthState
/// Unauthorized request to API
case unauthorizedAccess
/// Unsuccessful refresh token retrieval. Token not found in the retrieved TokenInfo object
case refreshTokenNotFound
/// Access token has expired
case expiredToken
/// Authorization with JWT token failed
case jwtAuthError
/// Authorization with CCG token failed
case ccgAuthError
/// Couldn't create paging iterable for non-paged response
case nonIterableResponse
/// The end of the list was reached
case endOfList
/// Custom error message
case customValue(String)
public init(_ value: String) {
switch value {
case "clientDestroyed":
self = .clientDestroyed
case "keychainDataConversionError":
self = .keychainDataConversionError
case "keychainNoValue":
self = .keychainNoValue
case "rateLimitMaxRetries":
self = .rateLimitMaxRetries
case "representationCreationFailed":
self = .representationCreationFailed
case "tokenStoreFailure":
self = .tokenStoreFailure
case "tokenRetrieval":
self = .tokenRetrieval
case "invalidOAuthRedirectConfiguration":
self = .invalidOAuthRedirectConfiguration
case "invalidOAuthState":
self = .invalidOAuthState
case "unauthorizedAccess":
self = .unauthorizedAccess
case "refreshTokenNotFound":
self = .refreshTokenNotFound
case "expiredToken":
self = .expiredToken
case "jwtAuthError":
self = .jwtAuthError
case "nonIterableResponse":
self = .nonIterableResponse
case "endOfList":
self = .endOfList
default:
self = .customValue(value)
}
}
public var description: String {
switch self {
case .clientDestroyed:
return "Tried to use a BoxClient instance that was already destroyed"
case let .invalidURL(urlString):
return "Invalid URL: \(urlString)"
case let .notFound(message):
return "Not found: \(message)"
case let .instanceDeallocated(message):
return "Object needed in closure was deallocated: \(message)"
case .keychainDataConversionError:
return "Could not decode or encode data for or from keychain"
case .keychainNoValue:
return "Value not found in Keychain"
case let .keychainUnhandledError(message):
return "Unhandled keychain error: \(message)"
case .rateLimitMaxRetries:
return "Request has hit the maximum number of retries"
case let .typeMismatch(key):
return "Value for key \(key) was of an unexpected type"
case let .valueMismatch(key, value, acceptedValues):
return "Value for key \(key) is \(value), which is not one of the accepted values [\(acceptedValues.map { "\(String(describing: $0))" }.joined(separator: ", "))]"
case let .invalidValueFormat(key):
return "Value for key \(key) is of a valid type, but was not able to convert value to expected type"
case let .notPresent(key):
return "Key \(key) was not present"
case .representationCreationFailed:
return "The file representation could not be made"
case .tokenStoreFailure:
return "Could not finish the operation (write, read or clear) on TokenStore object"
case .tokenRetrieval:
return "Unsuccessful token retrieval. Token was not found"
case .invalidOAuthRedirectConfiguration:
return "Failed OAuth web session authorization"
case .invalidOAuthState:
return "Couldn't obtain authorization code from OAuth web session success result"
case .unauthorizedAccess:
return "Unauthorized request to API"
case .refreshTokenNotFound:
return "Unsuccessful refresh token retrieval. Token was not found in the retrieved TokenInfo object"
case .expiredToken:
return "Access token has expired"
case .jwtAuthError:
return "Authorization with JWT token failed"
case .ccgAuthError:
return "Client Credentials Grant authorization failed"
case .nonIterableResponse:
return "Could not create paging iterable for non-paged response"
case .endOfList:
return "The end of the list has been reached"
case let .customValue(userValue):
return userValue
}
}
// swiftlint:enable cyclomatic_complexity
}
extension BoxSDKErrorEnum: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = BoxSDKErrorEnum(value)
}
}
/// Describes general SDK errors
public class BoxSDKError: Error {
/// Type of error
public var errorType: String
/// Error message
public var message: BoxSDKErrorEnum
/// Stack trace
public var stackTrace: [String]
/// Error
public var error: Error?
init(message: BoxSDKErrorEnum = "Internal SDK Error", error: Error? = nil) {
errorType = "BoxSDKError"
self.message = message
stackTrace = Thread.callStackSymbols
self.error = error
}
/// Get a dictionary representing BoxSDKError
public func getDictionary() -> [String: Any] {
var dict = [String: Any]()
dict["errorType"] = errorType
dict["message"] = message.description
dict["stackTrace"] = stackTrace
dict["error"] = error?.localizedDescription
return dict
}
}
extension BoxSDKError: CustomStringConvertible {
/// Provides error JSON string if found.
public var description: String {
guard
let encodedData = try? JSONSerialization.data(withJSONObject: getDictionary(), options: [.prettyPrinted, .sortedKeys]),
let JSONString = String(data: encodedData, encoding: .utf8)
else {
return "<Unparsed Box Error>"
}
return JSONString.replacingOccurrences(of: "\\", with: "")
}
}
extension BoxSDKError: LocalizedError {
public var errorDescription: String? {
return message.description
}
}
| 555e390811d17b99d52722c3f6a17f93 | 36.877358 | 174 | 0.656663 | false | false | false | false |
mownier/Umalahokan | refs/heads/master | Umalahokan/Source/Transition/ContactListTransitionAnimator.swift | mit | 1 | //
// ContactListTransitionAnimator.swift
// Umalahokan
//
// Created by Mounir Ybanez on 04/03/2017.
// Copyright © 2017 Ner. All rights reserved.
//
import UIKit
class ContactListTransitionAnimator: DrawerMenuTransitionDelegate {
weak var view: ContactListView?
private(set) var toX: CGFloat!
private(set) var toBackgroundColor: UIColor!
func dismissalPreAnimation(transition: DrawerMenuTransition) {
guard let view = view else { return }
toX = -max(view.tableView.frame.width, view.searchTextField.frame.width)
toBackgroundColor = toBackgroundColor.withAlphaComponent(0.0)
}
func dismissalAnimation(transition: DrawerMenuTransition) {
animate()
}
func presentationPreAnimation(transition: DrawerMenuTransition) {
guard let view = view else { return }
let theme = UITheme()
view.setNeedsLayout()
view.layoutIfNeeded()
toX = 0
toBackgroundColor = theme.color.violet.withAlphaComponent(0.5)
let fromX = -max(view.tableView.frame.width, view.searchTextField.frame.width)
view.backgroundColor = toBackgroundColor.withAlphaComponent(0.0)
view.tableView.frame.origin.x = fromX
view.searchTextField.frame.origin.x = fromX
}
func presentationAnimation(transition: DrawerMenuTransition) {
animate()
}
private func animate() {
guard let view = view else { return }
view.backgroundColor = toBackgroundColor
view.tableView.frame.origin.x = toX
view.searchTextField.frame.origin.x = toX
}
}
| 579f27c6739144e5d5008eb6908228ad | 28.45614 | 86 | 0.655152 | false | false | false | false |
iSame7/Panoramic | refs/heads/master | Panoramic/Panoramic/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Panoramic
//
// Created by Sameh Mabrouk on 12/15/14.
// Copyright (c) 2014 SMApps. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let panoramaVC : PanoramaViewController? = PanoramaViewController()
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let window = window {
window.backgroundColor = UIColor.orangeColor()
window.makeKeyAndVisible()
window.rootViewController = panoramaVC
}
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| a8037de8c9ea3906b9675e4d9c7af95f | 45.230769 | 285 | 0.739185 | false | false | false | false |
FreddyZeng/Charts | refs/heads/develop | Carthage/Checkouts/Charts/Source/Charts/Formatters/DefaultAxisValueFormatter.swift | apache-2.0 | 15 | //
// DefaultAxisValueFormatter.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
@objc(ChartDefaultAxisValueFormatter)
open class DefaultAxisValueFormatter: NSObject, IAxisValueFormatter
{
public typealias Block = (
_ value: Double,
_ axis: AxisBase?) -> String
@objc open var block: Block?
@objc open var hasAutoDecimals: Bool = false
private var _formatter: NumberFormatter?
@objc open var formatter: NumberFormatter?
{
get { return _formatter }
set
{
hasAutoDecimals = false
_formatter = newValue
}
}
// TODO: Documentation. Especially the nil case
private var _decimals: Int?
open var decimals: Int?
{
get { return _decimals }
set
{
_decimals = newValue
if let digits = newValue
{
self.formatter?.minimumFractionDigits = digits
self.formatter?.maximumFractionDigits = digits
self.formatter?.usesGroupingSeparator = true
}
}
}
public override init()
{
super.init()
self.formatter = NumberFormatter()
hasAutoDecimals = true
}
@objc public init(formatter: NumberFormatter)
{
super.init()
self.formatter = formatter
}
@objc public init(decimals: Int)
{
super.init()
self.formatter = NumberFormatter()
self.formatter?.usesGroupingSeparator = true
self.decimals = decimals
hasAutoDecimals = true
}
@objc public init(block: @escaping Block)
{
super.init()
self.block = block
}
@objc public static func with(block: @escaping Block) -> DefaultAxisValueFormatter?
{
return DefaultAxisValueFormatter(block: block)
}
open func stringForValue(_ value: Double,
axis: AxisBase?) -> String
{
if let block = block {
return block(value, axis)
} else {
return formatter?.string(from: NSNumber(floatLiteral: value)) ?? ""
}
}
}
| a806009b123a9a17e8bc59811509a295 | 22.8 | 87 | 0.563445 | false | false | false | false |
realgreys/RGPageMenu | refs/heads/master | RGPageMenu/Classes/RGPageMenuController.swift | mit | 1 | //
// PageMenuController.swift
// paging
//
// Created by realgreys on 2016. 5. 10..
// Copyright © 2016 realgreys. All rights reserved.
//
import UIKit
@objc
public protocol RGPageMenuControllerDelegate: class {
optional func willMoveToPageMenuController(viewController: UIViewController, nextViewController: UIViewController)
optional func didMoveToPageMenuController(viewController: UIViewController)
}
public class RGPageMenuController: UIViewController {
weak public var delegate: RGPageMenuControllerDelegate?
private var menuView: MenuView!
private var options: RGPageMenuOptions!
private var menuTitles: [String] {
return viewControllers.map {
return $0.title ?? "Menu"
}
}
private var pageViewController: UIPageViewController!
private(set) var currentPage = 0
private var viewControllers: [UIViewController]!
// MARK: - Lifecycle
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init(viewControllers: [UIViewController], options: RGPageMenuOptions) {
super.init(nibName: nil, bundle: nil)
configure(viewControllers, options: options)
}
public convenience init(viewControllers: [UIViewController]) {
self.init(viewControllers: viewControllers, options: RGPageMenuOptions())
}
override public func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
menuView.moveToMenu(currentPage, animated: false)
}
// MARK: - Layout
private func setupMenuView() {
menuView = MenuView(menuTitles: menuTitles, options: options)
menuView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(menuView)
addTapGestureHandlers()
}
private func layoutMenuView() {
// cleanup
// NSLayoutConstraint.deactivateConstraints(menuView.constraints)
let viewsDictionary = ["menuView": menuView]
let metrics = ["height": options.menuHeight]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuView]|",
options: [],
metrics: nil,
views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView(height)]",
options: [],
metrics: metrics,
views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView(height)]|",
options: [],
metrics: metrics,
views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
menuView.setNeedsLayout()
menuView.layoutIfNeeded()
}
private func setupPageView() {
pageViewController = UIPageViewController(transitionStyle: .Scroll,
navigationOrientation: .Horizontal,
options: nil)
pageViewController.delegate = self
pageViewController.dataSource = self
let childViewControllers = [ viewControllers[currentPage] ]
pageViewController.setViewControllers(childViewControllers,
direction: .Forward,
animated: false,
completion: nil)
addChildViewController(pageViewController)
pageViewController.view.frame = .zero
pageViewController.view.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(pageViewController.view)
pageViewController.didMoveToParentViewController(self)
}
private func layoutPageView() {
let viewsDictionary = ["pageView": pageViewController.view, "menuView": menuView]
let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[pageView]|",
options: [],
metrics: nil,
views: viewsDictionary)
let verticalConstraints: [NSLayoutConstraint]
switch options.menuPosition {
case .Top:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView][pageView]|",
options: [],
metrics: nil,
views: viewsDictionary)
case .Bottom:
verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pageView][menuView]",
options: [],
metrics: nil,
views: viewsDictionary)
}
NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints)
view.setNeedsLayout()
view.layoutIfNeeded()
}
private func validateDefaultPage() {
guard options.defaultPage >= 0 && options.defaultPage < options.menuItemCount else {
NSException(name: "PageMenuException", reason: "default page is not valid!", userInfo: nil).raise()
return
}
}
private func indexOfViewController(viewController: UIViewController) -> Int {
return viewControllers.indexOf(viewController) ?? NSNotFound
}
// MARK: - Gesture handler
private func addTapGestureHandlers() {
menuView.menuItemViews.forEach {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture))
gestureRecognizer.numberOfTapsRequired = 1
$0.addGestureRecognizer(gestureRecognizer)
}
}
func handleTapGesture(recognizer: UITapGestureRecognizer) {
guard let menuItemView = recognizer.view as? MenuItemView else { return }
guard let page = menuView.menuItemViews.indexOf(menuItemView) where page != menuView.currentPage else { return }
moveToPage(page)
}
// MARK: - public
public func configure(viewControllers: [UIViewController], options: RGPageMenuOptions) {
let menuItemCount = viewControllers.count
guard menuItemCount > 0 else {
NSException(name: "PageMenuException", reason: "child view controller is empty!", userInfo: nil).raise()
return
}
self.viewControllers = viewControllers
self.options = options
self.options.menuItemCount = menuItemCount
validateDefaultPage()
currentPage = options.defaultPage
setupMenuView()
layoutMenuView()
setupPageView()
layoutPageView()
}
public func moveToPage(page: Int, animated: Bool = true) {
guard page < options.menuItemCount && page != currentPage else { return }
let direction: UIPageViewControllerNavigationDirection = page < currentPage ? .Reverse : .Forward
// page 이동
currentPage = page % viewControllers.count // for infinite loop
// menu 이동
menuView.moveToMenu(currentPage, animated: animated)
let childViewControllers = [ viewControllers[currentPage] ]
pageViewController.setViewControllers(childViewControllers,
direction: direction,
animated: animated,
completion: nil)
}
}
extension RGPageMenuController: UIPageViewControllerDelegate {
// MARK: - UIPageViewControllerDelegate
public func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) {
if let nextViewController = pendingViewControllers.first {
let index = indexOfViewController(nextViewController)
guard index != NSNotFound else { return }
currentPage = index
menuView.moveToMenu(currentPage, animated: true)
if let viewController = pageViewController.viewControllers?.first {
// delegate가 있으면 notify
delegate?.willMoveToPageMenuController?(viewController, nextViewController: nextViewController)
}
}
}
public func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if !completed {
if let previousViewController = previousViewControllers.first {
let index = indexOfViewController(previousViewController)
guard index != NSNotFound else { return }
currentPage = index
menuView.moveToMenu(currentPage, animated: true)
}
} else {
if let nextViewController = pageViewController.viewControllers?.first {
// delegate가 있으면 notify
delegate?.didMoveToPageMenuController?(nextViewController)
}
}
}
}
extension RGPageMenuController: UIPageViewControllerDataSource {
// MARK: - UIPageViewControllerDataSource
public func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let index = indexOfViewController(viewController)
guard index != 0 && index != NSNotFound else {
return nil
}
return viewControllers[index - 1]
}
public func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let index = indexOfViewController(viewController)
guard index < viewControllers.count - 1 && index != NSNotFound else {
return nil
}
return viewControllers[index + 1]
}
}
| 3ab5b5b44d3e6f46d47c5aacef718cff | 40.017857 | 195 | 0.564475 | false | false | false | false |
KlubJagiellonski/pola-ios | refs/heads/master | BuyPolish/Pola/UI/ProductSearch/Keyboard/KeyboardViewController.swift | gpl-2.0 | 1 | import AudioToolbox
import UIKit
protocol KeyboardViewControllerDelegate: AnyObject {
func keyboardViewController(_ keyboardViewController: KeyboardViewController, didConfirmWithCode code: String)
}
final class KeyboardViewController: UIViewController {
let barcodeValidator: BarcodeValidator
fileprivate let barcode = KeyboardBarcode(code: "")
weak var delegate: KeyboardViewControllerDelegate?
init(barcodeValidator: BarcodeValidator) {
self.barcodeValidator = barcodeValidator
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var castedView: KeyboardView! {
view as? KeyboardView
}
override func loadView() {
view = KeyboardView()
}
override func viewDidLoad() {
super.viewDidLoad()
castedView.numberButtons.forEach { $0.addTarget(self, action: #selector(enterNumber(sender:)), for: .touchUpInside) }
castedView.okButton.addTarget(self, action: #selector(confirm), for: .touchUpInside)
castedView.textView.removeButton.addTarget(self, action: #selector(removeLastNumber), for: .touchUpInside)
castedView.textView.codeLabel.delegate = self
castedView.textView.codeLabel.accessibilityIdentifier =
NSStringFromClass(KeyboardLabel.self)
}
@objc
private func enterNumber(sender: UIButton) {
playSound()
let number = sender.tag
barcode.append(number: number)
castedView.textView.codeLabel.text = barcode.code
updateCodeLabel()
playSound()
}
@objc
private func removeLastNumber() {
playSound()
barcode.removeLast()
updateCodeLabel()
}
@objc
private func confirm() {
playSound()
if let code = castedView.textView.code,
barcodeValidator.isValid(barcode: code) {
delegate?.keyboardViewController(self, didConfirmWithCode: code)
} else {
castedView.textView.showErrorMessage()
}
}
private func playSound() {
AudioServicesPlaySystemSound(1104)
}
fileprivate func updateCodeLabel() {
castedView.textView.codeLabel.text = barcode.code
castedView.textView.hideErrorMessage()
}
}
extension KeyboardViewController: KeyboardLabelDelegate {
func keyboardLabelIsPasteAvailable(_: KeyboardLabel, pasteboardContent: String?) -> Bool {
let isPasteboardNotEmpty = pasteboardContent?.isNotEmpty ?? false
return isPasteboardNotEmpty && barcode.isAppendable
}
func keyboardLabelUserDidTapPaste(_: KeyboardLabel, pasteboardContent: String?) {
guard let pasteboardContent = pasteboardContent else {
return
}
barcode.append(string: pasteboardContent)
updateCodeLabel()
}
func keyboardLabelUserDidTapPasteAndActivate(_ label: KeyboardLabel, pasteboardContent: String?) {
keyboardLabelUserDidTapPaste(label, pasteboardContent: pasteboardContent)
confirm()
}
func keyboardLabelUserDidRemoveContent(_: KeyboardLabel) {
barcode.removeAll()
updateCodeLabel()
}
}
| 290b1ab3471a7555162dd248ea90502b | 30.365385 | 125 | 0.685162 | false | false | false | false |
che1404/RGViperChat | refs/heads/master | RGViperChat/ChatList/DataManager/API/ChatListAPIDataManager.swift | mit | 1 | //
// Created by Roberto Garrido
// Copyright (c) 2017 Roberto Garrido. All rights reserved.
//
import Foundation
import FirebaseDatabase
import FirebaseAuth
class ChatListAPIDataManager: ChatListAPIDataManagerInputProtocol {
let rootRef = Database.database().reference()
weak var newChatListener: NewChatListenerProtocol?
var newChatsObserverHandler: UInt = 0
func fetchChats(completion: @escaping (Result<[Chat]>) -> Void) {
guard let firebaseUser = Auth.auth().currentUser else {
completion(.failure(NSError(domain: "fetchChats", code: -1, userInfo: [NSLocalizedDescriptionKey: "User not logged in"])))
return
}
rootRef.child("User/\(firebaseUser.uid)").observeSingleEvent(of: .value, with: { snapshot in
if let userValues = snapshot.value as? [String: Any], let senderDisplayName = userValues["name"] as? String, let userChats = userValues["chats"] as? [String: Any] {
var chats: [Chat] = []
let dispatchGroup = DispatchGroup()
for chatDict in userChats {
let chatKey = chatDict.key
// Get the chat info
dispatchGroup.enter()
self.rootRef.child("Chat/\(chatKey)").observeSingleEvent(of: .value, with: { snapshot in
let chat = Chat(chatID: chatKey, displayName: "", senderID: firebaseUser.uid, senderDisplayName: senderDisplayName, receiverID: "", lastMessage: "")
chat.senderID = firebaseUser.uid
if let chatDictionary = snapshot.value as? [String: Any], let users = chatDictionary["users"] as? [String: Any] {
var lastMessage = ""
if let message = chatDictionary["lastMessage"] as? String {
lastMessage = message
}
for user in users where user.key != firebaseUser.uid {
if let userDisplayName = user.value as? String {
chat.displayName = userDisplayName
chat.receiverID = user.key
chat.lastMessage = lastMessage
chats.append(chat)
break
}
}
}
dispatchGroup.leave()
})
}
dispatchGroup.notify(queue: .main, execute: {
completion(.success(chats))
})
} else {
completion(.success([]))
}
})
}
func logout() -> Bool {
do {
try Auth.auth().signOut()
return true
} catch (let error) {
print(error.localizedDescription)
return false
}
}
func startListeningForNewChats(listener: NewChatListenerProtocol) {
newChatListener = listener
guard let firebaseUser = Auth.auth().currentUser else {
return
}
newChatsObserverHandler = rootRef.child("User/\(firebaseUser.uid)/chats").observe(.childAdded, with: { [weak self] chatSnapshot in
let chatID = chatSnapshot.key
let senderID = firebaseUser.uid
var receiverID = ""
self?.rootRef.child("Chat/\(chatID)/users").observeSingleEvent(of: .value, with: { snapshot in
guard let chatUsersDict = snapshot.value as? [String: Any] else {
return
}
for chatUser in chatUsersDict where chatUser.key != firebaseUser.uid {
receiverID = chatUser.key
break
}
self?.rootRef.child("User/\(receiverID)/name").observeSingleEvent(of: .value, with: { snapshot in
guard let receiverName = snapshot.value as? String else {
return
}
self?.rootRef.child("User/\(firebaseUser.uid)/name").observeSingleEvent(of: .value, with: { snapshot in
guard let senderName = snapshot.value as? String else {
return
}
self?.rootRef.child("Chat/\(chatID)/lastMessge").observeSingleEvent(of: .value, with: { snapshot in
var lastMessage = ""
if let message = snapshot.value as? String {
lastMessage = message
}
let chat = Chat(chatID: chatID, displayName: receiverName, senderID: senderID, senderDisplayName: senderName, receiverID: receiverID, lastMessage: lastMessage)
self?.newChatListener?.chatAdded(chat: chat)
})
})
})
})
})
}
}
| 22d014fde49b3dfc02e84e22a9130b87 | 41.366667 | 187 | 0.508655 | false | false | false | false |
ZackKingS/Tasks | refs/heads/master | Pods/SwiftTheme/Source/NSObject+Theme.swift | apache-2.0 | 1 | //
// NSObject+Theme.swift
// SwiftTheme
//
// Created by Gesen on 16/1/22.
// Copyright © 2016年 Gesen. All rights reserved.
//
import UIKit
extension NSObject {
typealias ThemePickers = [String: ThemePicker]
var themePickers: ThemePickers {
get {
if let themePickers = objc_getAssociatedObject(self, &themePickersKey) as? ThemePickers {
return themePickers
}
let initValue = ThemePickers()
objc_setAssociatedObject(self, &themePickersKey, initValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return initValue
}
set {
objc_setAssociatedObject(self, &themePickersKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
_removeThemeNotification()
if newValue.isEmpty == false { _setupThemeNotification() }
}
}
func performThemePicker(selector: String, picker: ThemePicker?) {
let sel = Selector(selector)
guard responds(to: sel) else { return }
guard let value = picker?.value() else { return }
if let statePicker = picker as? ThemeStatePicker {
let setState = unsafeBitCast(method(for: sel), to: setValueForStateIMP.self)
statePicker.values.forEach { setState(self, sel, $1.value()! as AnyObject, UIControlState(rawValue: $0)) }
}
else if let statusBarStylePicker = picker as? ThemeStatusBarStylePicker {
let setStatusBarStyle = unsafeBitCast(method(for: sel), to: setStatusBarStyleValueIMP.self)
setStatusBarStyle(self, sel, value as! UIStatusBarStyle, statusBarStylePicker.animated)
}
else if picker is ThemeBarStylePicker {
let setBarStyle = unsafeBitCast(method(for: sel), to: setBarStyleValueIMP.self)
setBarStyle(self, sel, value as! UIBarStyle)
}
else if picker is ThemeKeyboardAppearancePicker {
let setKeyboard = unsafeBitCast(method(for: sel), to: setKeyboardValueIMP.self)
setKeyboard(self, sel, value as! UIKeyboardAppearance)
}
else if picker is ThemeActivityIndicatorViewStylePicker {
let setActivityStyle = unsafeBitCast(method(for: sel), to: setActivityStyleValueIMP.self)
setActivityStyle(self, sel, value as! UIActivityIndicatorViewStyle)
}
else if picker is ThemeCGFloatPicker {
let setCGFloat = unsafeBitCast(method(for: sel), to: setCGFloatValueIMP.self)
setCGFloat(self, sel, value as! CGFloat)
}
else if picker is ThemeCGColorPicker {
let setCGColor = unsafeBitCast(method(for: sel), to: setCGColorValueIMP.self)
setCGColor(self, sel, value as! CGColor)
}
else { perform(sel, with: value) }
}
fileprivate typealias setCGColorValueIMP = @convention(c) (NSObject, Selector, CGColor) -> Void
fileprivate typealias setCGFloatValueIMP = @convention(c) (NSObject, Selector, CGFloat) -> Void
fileprivate typealias setValueForStateIMP = @convention(c) (NSObject, Selector, AnyObject, UIControlState) -> Void
fileprivate typealias setKeyboardValueIMP = @convention(c) (NSObject, Selector, UIKeyboardAppearance) -> Void
fileprivate typealias setActivityStyleValueIMP = @convention(c) (NSObject, Selector, UIActivityIndicatorViewStyle) -> Void
fileprivate typealias setBarStyleValueIMP = @convention(c) (NSObject, Selector, UIBarStyle) -> Void
fileprivate typealias setStatusBarStyleValueIMP = @convention(c) (NSObject, Selector, UIStatusBarStyle, Bool) -> Void
}
extension NSObject {
fileprivate func _setupThemeNotification() {
if #available(iOS 9.0, *) {
NotificationCenter.default.addObserver(self, selector: #selector(_updateTheme), name: NSNotification.Name(rawValue: ThemeUpdateNotification), object: nil)
} else {
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: ThemeUpdateNotification), object: nil, queue: nil, using: { [weak self] notification in self?._updateTheme() })
}
}
fileprivate func _removeThemeNotification() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: ThemeUpdateNotification), object: nil)
}
@objc private func _updateTheme() {
themePickers.forEach { selector, picker in
UIView.animate(withDuration: ThemeManager.animationDuration) {
self.performThemePicker(selector: selector, picker: picker)
}
}
}
}
private var themePickersKey = ""
| d1b9170d182bff0ea38ad5ca554ac2e9 | 42.697248 | 201 | 0.65358 | false | false | false | false |
apple/swift-llbuild | refs/heads/main | products/llbuildSwift/BuildDBBindings.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for Swift project authors
// This file contains Swift bindings for the llbuild C API.
#if canImport(Darwin)
import Darwin.C
#elseif os(Windows)
import ucrt
import WinSDK
#elseif canImport(Glibc)
import Glibc
#else
#error("Missing libc or equivalent")
#endif
import Foundation
// We don't need this import if we're building
// this file as part of the llbuild framework.
#if !LLBUILD_FRAMEWORK
import llbuild
#endif
public typealias KeyID = UInt64
public typealias KeyType = [UInt8]
public typealias ValueType = [UInt8]
/// Defines the result of a call to fetch all keys from the database
/// Wraps calls to the llbuild database, but all results are fetched and available with this result
public final class BuildDBKeysResult {
/// Opaque pointer to the actual result object
private let result: OpaquePointer
fileprivate init(result: OpaquePointer) {
self.result = result
}
private lazy var _count: Int = Int(llb_database_fetch_result_get_count(result))
deinit {
llb_database_destroy_fetch_result(result)
}
}
public final class BuildDBKeysWithResult {
/// Opaque pointer to the actual result object
private let result: OpaquePointer
fileprivate init(result: OpaquePointer) {
self.result = result
assert(llb_database_fetch_result_contains_rule_results(result))
}
private lazy var _count: Int = Int(llb_database_fetch_result_get_count(result))
deinit {
llb_database_destroy_fetch_result(result)
}
}
extension BuildDBKeysResult: Collection {
public typealias Index = Int
public typealias Element = BuildKey
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return self._count + startIndex
}
public subscript(index: Index) -> Iterator.Element {
guard (startIndex..<endIndex).contains(index) else {
fatalError("Index \(index) is out of bounds (\(startIndex)..<\(endIndex))")
}
return BuildKey.construct(key: llb_database_fetch_result_get_key_at_index(self.result, Int32(index)))
}
public func index(after i: Index) -> Index {
return i + 1
}
}
extension BuildDBKeysWithResult: Collection {
public struct Element: Hashable {
public let key: BuildKey
public let result: RuleResult
public func hash(into hasher: inout Hasher) {
hasher.combine(key)
}
}
public typealias Index = Int
public var startIndex: Index {
return 0
}
public var endIndex: Index {
return self._count + startIndex
}
public subscript(index: Index) -> Iterator.Element {
guard (startIndex..<endIndex).contains(index) else {
fatalError("Index \(index) is out of bounds (\(startIndex)..<\(endIndex))")
}
guard let result = llb_database_fetch_result_get_result_at_index(self.result, Int32(index)) else {
fatalError("Build database fetch result doesn't contain result at index \(index) although the count is given at \(count)")
}
let key = BuildKey.construct(key: llb_database_fetch_result_get_key_at_index(self.result, Int32(index)))
let ruleResult = RuleResult(result: result.pointee)!
return Element(key: key, result: ruleResult)
}
public func index(after i: Index) -> Index {
return i + 1
}
}
extension BuildDBKeysResult: CustomReflectable {
public var customMirror: Mirror {
let keys = (startIndex..<endIndex).map { self[$0] }
return Mirror(BuildDBKeysResult.self, unlabeledChildren: keys, displayStyle: .collection)
}
}
extension BuildDBKeysResult: CustomStringConvertible {
public var description: String {
let keyDescriptions = (startIndex..<endIndex).map { "\(self[$0]))" }
return "[\(keyDescriptions.joined(separator: ", "))]"
}
}
/// Defines the result of a built task
public struct RuleResult {
/// The value of the result
public let value: BuildValue
/// Signature of the node that generated the result
public let signature: UInt64
/// The build iteration this result was computed at
public let computedAt: UInt64
/// The build iteration this result was built at
public let builtAt: UInt64
/// The start of the command as a duration since a reference time
public let start: Double
/// The duration since a reference time of when the command finished computing
public let end: Double
/// The duration in seconds the result needed to finish
public var duration: Double { return end - start }
/// A list of the dependencies of the computed task, use the database's allKeys to check for their key
public let dependencies: [BuildKey]
public init(value: BuildValue, signature: UInt64, computedAt: UInt64, builtAt: UInt64, start: Double, end: Double, dependencies: [BuildKey]) {
self.value = value
self.signature = signature
self.computedAt = computedAt
self.builtAt = builtAt
self.start = start
self.end = end
self.dependencies = dependencies
}
fileprivate init?(result: BuildDBResult) {
guard let value = BuildValue.construct(from: Value(ValueType(UnsafeBufferPointer(start: result.value.data, count: Int(result.value.length))))) else {
return nil
}
let dependencies = UnsafeBufferPointer(start: result.dependencies, count: Int(result.dependencies_count))
.map(BuildKey.construct(key:))
self.init(value: value, signature: result.signature, computedAt: result.computed_at, builtAt: result.built_at, start: result.start, end: result.end, dependencies: dependencies)
}
}
extension RuleResult: Equatable {
public static func == (lhs: RuleResult, rhs: RuleResult) -> Bool {
return lhs.value == rhs.value && lhs.signature == rhs.signature && lhs.computedAt == rhs.computedAt && lhs.builtAt == rhs.builtAt && lhs.start == rhs.start && lhs.end == rhs.end && lhs.dependencies == rhs.dependencies
}
}
extension RuleResult: CustomStringConvertible {
public var description: String {
return "<RuleResult value=\(value) signature=\(String(format: "0x%X", signature)) computedAt=\(computedAt) builtAt=\(builtAt) duration=\(duration)sec dependenciesCount=\(dependencies.count)>"
}
}
/// Private class for easier handling of out-parameters
private class MutableStringPointer {
var ptr = llb_data_t()
init() { }
deinit {
ptr.data?.deallocate()
}
var msg: String? {
guard ptr.data != nil else { return nil }
return stringFromData(ptr)
}
}
/// Database object that defines a connection to a llbuild database
public final class BuildDB {
/// Errors that can happen when opening the database or performing operations on it
public enum Error: Swift.Error {
/// If the system can't open the database, this error is thrown at init
case couldNotOpenDB(error: String)
/// If an operation on the database fails, this error is thrown
case operationDidFail(error: String)
/// If the database didn't provide an error but the operation still failed, the unknownError is thrown
case unknownError
}
/// The opaque pointer to the database object
private var _database: OpaquePointer
/// Initializes the build database at a given path
/// If the database at this path doesn't exist, it will created
/// If the clientSchemaVersion is different to the one in the database at this path, its content will be automatically erased!
public init(path: String, clientSchemaVersion: UInt32) throws {
// Safety check that we have linked against a compatibile llbuild framework version
if llb_get_api_version() != LLBUILD_C_API_VERSION {
throw Error.couldNotOpenDB(error: "llbuild C API version mismatch, found \(llb_get_api_version()), expect \(LLBUILD_C_API_VERSION)")
}
// check if the database file exists
var directory: ObjCBool = false
guard FileManager.default.fileExists(atPath: path, isDirectory: &directory) else {
throw Error.couldNotOpenDB(error: "Database at path '\(path)' does not exist.")
}
if directory.boolValue {
throw Error.couldNotOpenDB(error: "Path '\(path)' exists, but is a directory.")
}
let errorPtr = MutableStringPointer()
guard let database = llb_database_open(strdup(path), clientSchemaVersion, &errorPtr.ptr) else {
throw Error.couldNotOpenDB(error: errorPtr.msg ?? "Unknown error.")
}
_database = database
}
deinit {
llb_database_destroy(_database)
}
/// Fetches all keys from the database
public func getKeys() throws -> BuildDBKeysResult {
let errorPtr = MutableStringPointer()
let keys = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
let success = llb_database_get_keys(_database, keys, &errorPtr.ptr)
if let error = errorPtr.msg {
throw Error.operationDidFail(error: error)
}
if !success {
throw Error.unknownError
}
guard let resultKeys = keys.pointee else {
throw Error.unknownError
}
return BuildDBKeysResult(result: resultKeys)
}
public func getKeysWithResult() throws -> BuildDBKeysWithResult {
let errorPtr = MutableStringPointer()
let keys = UnsafeMutablePointer<OpaquePointer?>.allocate(capacity: 1)
let success = llb_database_get_keys_and_results(_database, keys, &errorPtr.ptr)
if let error = errorPtr.msg {
throw Error.operationDidFail(error: error)
}
if !success {
throw Error.unknownError
}
guard let resultKeys = keys.pointee else {
throw Error.unknownError
}
return BuildDBKeysWithResult(result: resultKeys)
}
/// Get the result for a given keyID
public func lookupRuleResult(buildKey: BuildKey) throws -> RuleResult? {
let errorPtr = MutableStringPointer()
var result = BuildDBResult()
let stored = llb_database_lookup_rule_result(_database, buildKey.internalBuildKey, &result, &errorPtr.ptr)
if let error = errorPtr.msg {
throw Error.operationDidFail(error: error)
}
if !stored {
return nil
}
let mappedResult = RuleResult(result: result)
llb_database_destroy_result(&result)
return mappedResult
}
public func currentBuildEpoch() throws -> UInt64 {
let errorPtr = MutableStringPointer()
let epoch = llb_database_get_epoch(_database, &errorPtr.ptr)
if let error = errorPtr.msg {
throw Error.operationDidFail(error: error)
}
return epoch
}
}
| 7868a36852e051a33ff63d1d003a8b17 | 34.374613 | 225 | 0.653685 | 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.