repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Acidburn0zzz/firefox-ios
content-blocker-lib-ios/ContentBlockerGen/Sources/ContentBlockerGenLib/ContentBlockerGenLib.swift
1
3569
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation public enum Action: String { case blockAll = "\"block\"" case blockCookies = "\"block-cookies\"" } public enum CategoryTitle: String, CaseIterable { case Advertising case Analytics case Social // case Fingerprinting // not used, we have special fingerprinting list instead case Disconnect case Cryptomining case Content } public class ContentBlockerGenLib { var companyToRelatedDomains = [String: [String]]() public init(entityListJson: [String: Any]) { parseEntityList(json: entityListJson) } func parseEntityList(json: [String: Any]) { let entities = json["entities"]! as! [String: Any] entities.forEach { let company = $0.key let related = ($0.value as! [String: [String]])["properties"]! companyToRelatedDomains[company] = related } } func buildUnlessDomain(_ domains: [String]) -> String { guard domains.count > 0 else { return "" } let result = domains.reduce("", { $0 + "\"*\($1)\"," }).dropLast() return "[" + result + "]" } func buildUrlFilter(_ domain: String) -> String { let prefix = "^https?://([^/]+\\\\.)?" return prefix + domain.replacingOccurrences(of: ".", with: "\\\\.") } func buildOutputLine(urlFilter: String, unlessDomain: String, action: Action) -> String { let unlessDomainSection = unlessDomain.isEmpty ? "" : ",\"unless-domain\":\(unlessDomain)" let result = """ {"action":{"type":\(action.rawValue)},"trigger":{"url-filter":"\(urlFilter)","load-type":["third-party"]\(unlessDomainSection)}} """ return result } public func handleCategoryItem(_ categoryItem: Any, action: Action) -> [String] { let categoryItem = categoryItem as! [String: [String: Any]] var result = [String]() assert(categoryItem.count == 1) let companyName = categoryItem.first!.key let relatedDomains = companyToRelatedDomains[companyName, default: []] let unlessDomain = buildUnlessDomain(relatedDomains) let entry = categoryItem.first!.value.first(where: { $0.key.hasPrefix("http") || $0.key.hasPrefix("www.") })! // let companyDomain = entry.key // noting that companyDomain is not used anywhere let domains = entry.value as! [String] domains.forEach { let f = buildUrlFilter($0) let line = buildOutputLine(urlFilter: f, unlessDomain: unlessDomain, action: action) result.append(line) } return result } public func parseBlocklist(json: [String: Any], action: Action, categoryTitle: CategoryTitle) -> [String] { let categories = json["categories"]! as! [String: Any] var result = [String]() let category = categories[categoryTitle.rawValue] as! [Any] category.forEach { result += handleCategoryItem($0, action: action) } return result } public func parseFingerprintingList(json: [String]) -> [String] { var result = [String]() for domain in json { let f = buildUrlFilter(domain) let line = buildOutputLine(urlFilter: f, unlessDomain: "", action: .blockAll) result.append(line) } return result } }
mpl-2.0
b12b1b732740be97c2be6f256a485e82
35.418367
148
0.609695
4.389914
false
false
false
false
nathawes/swift
stdlib/public/core/SmallString.swift
8
11651
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // The code units in _SmallString are always stored in memory in the same order // that they would be stored in an array. This means that on big-endian // platforms the order of the bytes in storage is reversed compared to // _StringObject whereas on little-endian platforms the order is the same. // // Memory layout: // // |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes // | _storage.0 | _storage.1 | ← raw bits // | code units | | ← encoded layout // ↑ ↑ // first (leftmost) code unit discriminator (incl. count) // @frozen @usableFromInline internal struct _SmallString { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) // Small strings are values; store them raw @usableFromInline internal var _storage: RawBitPattern @inlinable @inline(__always) internal var rawBits: RawBitPattern { return _storage } @inlinable internal var leadingRawBits: UInt64 { @inline(__always) get { return _storage.0 } @inline(__always) set { _storage.0 = newValue } } @inlinable internal var trailingRawBits: UInt64 { @inline(__always) get { return _storage.1 } @inline(__always) set { _storage.1 = newValue } } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = bits } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } @inlinable @inline(__always) internal init(_ object: _StringObject) { _internalInvariant(object.isSmall) // On big-endian platforms the byte order is the reverse of _StringObject. let leading = object.rawBits.0.littleEndian let trailing = object.rawBits.1.littleEndian self.init(raw: (leading, trailing)) } @inlinable @inline(__always) internal init() { self.init(_StringObject(empty:())) } } extension _SmallString { @inlinable @inline(__always) internal static var capacity: Int { #if arch(i386) || arch(arm) || arch(wasm32) return 10 #else return 15 #endif } // Get an integer equivalent to the _StringObject.discriminatedObjectRawBits // computed property. @inlinable @inline(__always) internal var rawDiscriminatedObject: UInt64 { // Reverse the bytes on big-endian systems. return _storage.1.littleEndian } @inlinable @inline(__always) internal var capacity: Int { return _SmallString.capacity } @inlinable @inline(__always) internal var count: Int { return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject) } @inlinable @inline(__always) internal var unusedCapacity: Int { return capacity &- count } @inlinable @inline(__always) internal var isASCII: Bool { return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject) } // Give raw, nul-terminated code units. This is only for limited internal // usage: it always clears the discriminator and count (in case it's full) @inlinable @inline(__always) internal var zeroTerminatedRawCodeUnits: RawBitPattern { let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte return (self._storage.0, self._storage.1 & smallStringCodeUnitMask) } internal func computeIsASCII() -> Bool { let asciiMask: UInt64 = 0x8080_8080_8080_8080 let raw = zeroTerminatedRawCodeUnits return (raw.0 | raw.1) & asciiMask == 0 } } // Internal invariants extension _SmallString { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _internalInvariant(count <= _SmallString.capacity) _internalInvariant(isASCII == computeIsASCII()) } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.joined() ) """) #endif // INTERNAL_CHECKS_ENABLED } } // Provide a RAC interface extension _SmallString: RandomAccessCollection, MutableCollection { @usableFromInline internal typealias Index = Int @usableFromInline internal typealias Element = UInt8 @usableFromInline internal typealias SubSequence = _SmallString @inlinable @inline(__always) internal var startIndex: Int { return 0 } @inlinable @inline(__always) internal var endIndex: Int { return count } @inlinable internal subscript(_ idx: Int) -> UInt8 { @inline(__always) get { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { return leadingRawBits._uncheckedGetByte(at: idx) } else { return trailingRawBits._uncheckedGetByte(at: idx &- 8) } } @inline(__always) set { _internalInvariant(idx >= 0 && idx <= 15) if idx < 8 { leadingRawBits._uncheckedSetByte(at: idx, to: newValue) } else { trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue) } } } @inlinable @inline(__always) internal subscript(_ bounds: Range<Index>) -> SubSequence { // TODO(String performance): In-vector-register operation return self.withUTF8 { utf8 in let rebased = UnsafeBufferPointer(rebasing: utf8[bounds]) return _SmallString(rebased)._unsafelyUnwrappedUnchecked } } } extension _SmallString { @inlinable @inline(__always) internal func withUTF8<Result>( _ f: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { var raw = self.zeroTerminatedRawCodeUnits return try Swift.withUnsafeBytes(of: &raw) { rawBufPtr in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeBufferPointer(start: ptr, count: self.count)) } } // Overwrite stored code units, including uninitialized. `f` should return the // new count. @inline(__always) internal mutating func withMutableCapacity( _ f: (UnsafeMutableBufferPointer<UInt8>) throws -> Int ) rethrows { let len = try withUnsafeMutableBytes(of: &self._storage) { (rawBufPtr: UnsafeMutableRawBufferPointer) -> Int in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeMutableBufferPointer( start: ptr, count: _SmallString.capacity)) } if len == 0 { self = _SmallString() return } _internalInvariant(len <= _SmallString.capacity) let (leading, trailing) = self.zeroTerminatedRawCodeUnits self = _SmallString(leading: leading, trailing: trailing, count: len) } } // Creation extension _SmallString { @inlinable @inline(__always) internal init(leading: UInt64, trailing: UInt64, count: Int) { _internalInvariant(count <= _SmallString.capacity) let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0 let discriminator = _StringObject.Nibbles .small(withCount: count, isASCII: isASCII) .littleEndian // reversed byte order on big-endian platforms _internalInvariant(trailing & discriminator == 0) self.init(raw: (leading, trailing | discriminator)) _internalInvariant(self.count == count) } // Direct from UTF-8 @inlinable @inline(__always) internal init?(_ input: UnsafeBufferPointer<UInt8>) { if input.isEmpty { self.init() return } let count = input.count guard count <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a masked unaligned // vector load let ptr = input.baseAddress._unsafelyUnwrappedUnchecked let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8)) let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0 self.init(leading: leading, trailing: trailing, count: count) } @inline(__always) internal init( initializingUTF8With initializer: ( _ buffer: UnsafeMutableBufferPointer<UInt8> ) throws -> Int ) rethrows { self.init() try self.withMutableCapacity { return try initializer($0) } self._invariantCheck() } @usableFromInline // @testable internal init?(_ base: _SmallString, appending other: _SmallString) { let totalCount = base.count + other.count guard totalCount <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a couple vector ops var result = base var writeIdx = base.count for readIdx in 0..<other.count { result[writeIdx] = other[readIdx] writeIdx &+= 1 } _internalInvariant(writeIdx == totalCount) let (leading, trailing) = result.zeroTerminatedRawCodeUnits self.init(leading: leading, trailing: trailing, count: totalCount) } } #if _runtime(_ObjC) && !(arch(i386) || arch(arm)) // Cocoa interop extension _SmallString { // Resiliently create from a tagged cocoa string // @_effects(readonly) // @opaque @usableFromInline // testable internal init(taggedCocoa cocoa: AnyObject) { self.init() self.withMutableCapacity { let len = _bridgeTagged(cocoa, intoUTF8: $0) _internalInvariant(len != nil && len! <= _SmallString.capacity, "Internal invariant violated: large tagged NSStrings") return len._unsafelyUnwrappedUnchecked } self._invariantCheck() } } #endif extension UInt64 { // Fetches the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal func _uncheckedGetByte(at i: Int) -> UInt8 { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif return UInt8(truncatingIfNeeded: (self &>> shift)) } // Sets the `i`th byte in memory order. On little-endian systems the byte // at i=0 is the least significant byte (LSB) while on big-endian systems the // byte at i=7 is the LSB. @inlinable @inline(__always) internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) { _internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride) #if _endian(big) let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8 #else let shift = UInt64(truncatingIfNeeded: i) &* 8 #endif let valueMask: UInt64 = 0xFF &<< shift self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift) } } @inlinable @inline(__always) internal func _bytesToUInt64( _ input: UnsafePointer<UInt8>, _ c: Int ) -> UInt64 { // FIXME: This should be unified with _loadPartialUnalignedUInt64LE. // Unfortunately that causes regressions in literal concatenation tests. (Some // owned to guaranteed specializations don't get inlined.) var r: UInt64 = 0 var shift: Int = 0 for idx in 0..<c { r = r | (UInt64(input[idx]) &<< shift) shift = shift &+ 8 } // Convert from little-endian to host byte order. return r.littleEndian }
apache-2.0
6a3c74709c8f25fdb95dc72913866408
30.633152
80
0.671592
4.16792
false
false
false
false
onevcat/CotEditor
CotEditor/Sources/PatternSortViewController.swift
1
5915
// // PatternSortViewController.swift // // CotEditor // https://coteditor.com // // Created by 1024jp on 2018-01-05. // // --------------------------------------------------------------------------- // // © 2018-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Cocoa final class PatternSortViewController: NSViewController, SortPatternViewControllerDelegate { // MARK: Public Properties var sampleLine: String? @objc dynamic var sampleFontName: String? var completionHandler: ((_ pattern: SortPattern, _ options: SortOptions) -> Void)? // MARK: Private Properties @objc private dynamic var sortOptions = SortOptions() @IBOutlet private weak var sampleLineField: NSTextField? private weak var tabViewController: NSTabViewController? // MARK: - // MARK: View Controller Methods /// keep tabViewController override func prepare(for segue: NSStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) guard self.tabViewController == nil, let tabViewController = segue.destinationController as? NSTabViewController else { return } self.tabViewController = tabViewController tabViewController.tabViewItems .compactMap { $0.viewController as? SortPatternViewController } .forEach { $0.delegate = self } } // MARK: Action Messages /// switch sort key setting (tab) view @IBAction func changeSortPattern(_ sender: NSButton) { self.tabViewController?.selectedTabViewItemIndex = sender.tag } /// perform sort @IBAction func apply(_ sender: Any?) { assert(self.completionHandler != nil) guard self.endEditing() else { return NSSound.beep() } guard let pattern = self.sortPattern else { return assertionFailure() } do { try pattern.validate() } catch { NSAlert(error: error).beginSheetModal(for: self.view.window!) return NSSound.beep() } self.completionHandler?(pattern, self.sortOptions) self.dismiss(sender) } // MARK: Sort Pattern View Controller Delegate /// sort pattern setting did update func didUpdate(sortPattern: SortPattern) { guard let sampleLine = self.sampleLine, let field = self.sampleLineField else { return } let attributedLine = NSMutableAttributedString(string: sampleLine) try? sortPattern.validate() // invalidate regex if let range = sortPattern.range(for: sampleLine) { let nsRange = NSRange(range, in: sampleLine) attributedLine.addAttribute(.backgroundColor, value: NSColor.selectedTextBackgroundColor, range: nsRange) } field.attributedStringValue = attributedLine } // MARK: Private Methods /// SortPattern currently edited private var sortPattern: SortPattern? { return self.tabViewController?.tabView.selectedTabViewItem?.viewController?.representedObject as? SortPattern } } // MARK: - final class SortPatternTabViewController: NSTabViewController { override func tabView(_ tabView: NSTabView, willSelect tabViewItem: NSTabViewItem?) { super.tabView(tabView, willSelect: tabViewItem) // initialize viewController in representedObject guard let item = tabViewItem, let viewController = item.viewController, viewController.representedObject == nil else { return } viewController.representedObject = { switch tabView.indexOfTabViewItem(item) { case 0: return EntireLineSortPattern() case 1: return CSVSortPattern() case 2: return RegularExpressionSortPattern() default: preconditionFailure() } }() } } // MARK: - protocol SortPatternViewControllerDelegate: AnyObject { func didUpdate(sortPattern: SortPattern) } final class SortPatternViewController: NSViewController, NSTextFieldDelegate { weak var delegate: SortPatternViewControllerDelegate? override func viewWillAppear() { super.viewWillAppear() self.valueDidUpdate(self) } /// text field value did change func controlTextDidChange(_ obj: Notification) { self.valueDidUpdate(self) } /// notify value change to delegate @IBAction func valueDidUpdate(_ sender: Any?) { guard let pattern = self.representedObject as? SortPattern else { return assertionFailure() } self.delegate?.didUpdate(sortPattern: pattern) } } // MARK: - extension CSVSortPattern { override func setNilValueForKey(_ key: String) { // avoid rising an exception when number field becomes empty switch key { case #keyPath(column): self.column = 1 default: super.setNilValueForKey(key) } } }
apache-2.0
00f365fbcca68948efc0fb6b2e471403
25.63964
117
0.608556
5.527103
false
false
false
false
roambotics/swift
test/Macros/macro_plugin.swift
1
947
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -disable-availability-checking -I%platform-module-dir/../.. -L%platform-dylib-dir/../.. -emit-library -emit-library-path=%t/%target-library-name(MacroDefinition) -working-directory=%t -module-name=MacroDefinition %S/Inputs/macro_definition.swift // RUN: %target-swift-frontend -L%platform-dylib-dir/../.. -enable-experimental-feature Macros -load-plugin-library %t/%target-library-name(MacroDefinition) -disable-availability-checking -dump-ast -primary-file %s | %FileCheck %s // FIXME: Swift parser is not enabled on Linux CI yet. // REQUIRES: OS=macosx let _ = #customStringify(1.byteSwapped + 2.advanced(by: 10)) // CHECK: (macro_expansion_expr type='(Int, String)' {{.*}} name=customStringify // CHECK: (argument_list // EXPANSION BEGINS // CHECK: (tuple_expr type='(Int, String)' // CHECK: (binary_expr type='Int' // CHECK: (string_literal_expr type='String'
apache-2.0
6ef281616cfabedc258f58762e4d8531
62.133333
284
0.717001
3.334507
false
false
false
false
maxadamski/SwiftyHTTP
SwiftyHTTP/HTTPConnection/HTTPServer.swift
2
2542
// // ARIHttpServer.swift // SwiftyHTTP // // Created by Helge Hess on 6/5/14. // Copyright (c) 2014 Always Right Institute. All rights reserved. // import Dispatch public class HTTPServer : HTTPConnectionPool { public var port : Int? = nil public var socket : PassiveSocketIPv4! var handler : ((HTTPRequest, HTTPResponse, HTTPConnection)->Void)? = nil var handlerQueue : dispatch_queue_t? = nil public func onRequest (cb:(HTTPRequest, HTTPResponse, HTTPConnection)->Void) -> Self { handler = cb return self } public func useQueue(queue: dispatch_queue_t) -> Self { handlerQueue = queue return self } override func handleRequest(request: HTTPRequest, _ con: HTTPConnection) { log("Got request: \(request)") log() if let handler = handler { let q = handlerQueue ?? dispatch_get_main_queue() dispatch_async(q!) { let response = HTTPResponse(status: .OK, headers: [ "Content-Type": "text/html" ]) handler(request, response, con) if response.closeConnection || request.closeConnection { con.close() } } } else { let response = HTTPResponse(status: .InternalServerError, headers: [ "Content-Type": "text/html" ]) response.bodyAsString = "No handler configured in HTTP server!\r\n" con.sendResponse(response) con.close() } } public func listen(port: Int) -> HTTPServer { // using Self or Self? seems to crash the compiler socket = PassiveSocket(address: sockaddr_in(port: port)) guard socket.isValid else { log("could not create socket ...") assert(socket.isValid) return self } socket.reuseAddress = true log("Listen socket \(socket) reuse=\(socket.reuseAddress)") let queue = dispatch_get_global_queue(0, 0) socket.listen(queue, backlog: 5) { [unowned self] in let con = HTTPConnection($0) self.log() self.log("-----") self.log("got new connection: \(con)") self.log() // Note: we need to keep the socket around!! self.registerConnection(con) } log("Started running listen socket \(socket)") return self } public func stop() { if let s = socket { s.close() socket = nil } let socketsToClose = openSockets // make a copy for (_, sock) in socketsToClose { sock.close() } } }
mit
bcda015d701e69720935fa43c19c9920
23.442308
79
0.59048
4.250836
false
false
false
false
sebastian989/ParceSwift
Demo/Demo/ViewController.swift
1
2276
// // ViewController.swift // Demo // // Created by Sebastian Gomez on 23/02/16. // // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Api response Mock let apiDictionary: [String : AnyObject] = [ "name": "Brian" as AnyObject, "age" : 80 as AnyObject, "user_email": "[email protected]" as AnyObject, "address": ["street": "Columbus", "avenue":12] as AnyObject, "height": 1.75 as AnyObject, "isOld": true as AnyObject, "mobile_number": "567-876-2343" as AnyObject, "anyDictionary": ["key":2] as AnyObject, "arrayAnyTypes": [1,2,3,4,5] as AnyObject, "modelsArray": [["street":"sabaneta","avenue":12], ["street":"sabaneta","avenue":13]] as AnyObject ] let jsonArray: [Address] = Address.fromJsonArray([["street":"sabaneta" as AnyObject,"avenue":12 as AnyObject], ["street":"sabaneta" as AnyObject,"avenue":13 as AnyObject]]) print("array of models: \(jsonArray)") let user = User() user.fromDictionary(apiDictionary as [String : AnyObject]) print("name: \(user.name!), address: Street \(user.address!.street!) Avenue \(user.address!.avenue!)") // Model to JSON String do { let jsonString = try user.toJSON() print("toJSON: " + jsonString!) } catch { print("The model can't be parsed to JSON format") } // JSON String to Model do{ let jsonString = "{\"name\": \"Jose\",\"age\": 25,\"address\": {\"street\": \"Cupertino\",\"avenue\": 15},\"height\": 1.64,\"isMan\": true,\"anyDictionary\": {\"key\": 2},\"arrayAnyTypes\": [1, 2, 3, 4, 5],\"modelsArray\": [{\"street\": \"Medellín\",\"avenue\": 10}, {\"street\": \"Medellín\",\"avenue\": 11}]}" let userJ = User() try userJ.fromJSON(jsonString) } catch { print("The string isn't a valid JSON") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
40bab122a2896d060fc37a2de73a656b
35.677419
323
0.543536
4.290566
false
false
false
false
freshOS/ws
Sources/ws/WSLogger.swift
2
3002
// // WSLogger.swift // ws // // Created by Sacha Durand Saint Omer on 13/11/2016. // Copyright © 2016 s4cha. All rights reserved. // import Alamofire import Foundation public enum WSLogLevel { @available(*, unavailable, renamed: "off") case none @available(*, unavailable, renamed: "info") case calls @available(*, unavailable, renamed: "debug") case callsAndResponses case off case info case debug } class WSLogger { var logLevels = WSLogLevel.off func logMultipartRequest(_ request: WSRequest) { guard logLevels != .off else { return } print("\(request.httpVerb.rawValue.uppercased()) '\(request.URL)'") print(" params : \(request.params)") for (k, v) in request.headers { print(" \(k) : \(v)") } request.multiPartData.forEach { print(" name : \($0.multipartName)," + "mimeType: \($0.multipartMimeType), filename: \($0.multipartFileName)") } if logLevels == .debug { print() } } func logRequest(_ request: DataRequest) { guard logLevels != .off else { return } if let urlRequest = request.request, let verb = urlRequest.httpMethod, let url = urlRequest.url { print("\(verb) '\(url.absoluteString)'") logHeaders(urlRequest) logBody(urlRequest) if logLevels == .debug { print() } } } func logResponse(_ response: DefaultDataResponse) { guard logLevels != .off else { return } logStatusCodeAndURL(response.response) if logLevels == .debug { print() } } func logResponse(_ response: DataResponse<Any>) { guard logLevels != .off else { return } logStatusCodeAndURL(response.response) if logLevels == .debug { switch response.result { case .success(let value): print(value) case .failure(let error): print(error) } } if logLevels == .debug { print() } } private func logHeaders(_ urlRequest: URLRequest) { if let allHTTPHeaderFields = urlRequest.allHTTPHeaderFields { for (k, v) in allHTTPHeaderFields { print(" \(k) : \(v)") } } } private func logBody(_ urlRequest: URLRequest) { if let body = urlRequest.httpBody, let str = String(data: body, encoding: .utf8) { print(" HttpBody : \(str)") } } private func logStatusCodeAndURL(_ urlResponse: HTTPURLResponse?) { if let urlResponse = urlResponse, let url = urlResponse.url { print("\(urlResponse.statusCode) '\(url.absoluteString)'") } } }
mit
c10249256ecf92a46880ba1642107371
25.324561
89
0.521826
4.809295
false
false
false
false
RameshRM/just-now
JustNow/JustNow/IncidentDetailCell.swift
1
623
// // IncidentDetailCell.swift // JustNow // // Created by Mahadevan, Ramesh on 8/4/15. // Copyright (c) 2015 GoliaMania. All rights reserved. // import Foundation import UIKit class IncidentDetailCell : UITableViewCell{ @IBOutlet weak var message: UILabel! // @IBOutlet weak var response: UILabel! @IBOutlet weak var header: UILabel! func dataBind(dataContext: IncidentDtl){ self.message.text = dataContext.content; self.header.text = dataContext.from; // self.response.text = dataContext.response; // self.response.hidden = dataContext.response == nil; } }
apache-2.0
2f72aa575eac0f71950ab592d1c8367b
25
61
0.680578
4.019355
false
false
false
false
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Linux/Foundation/FileManager+Extensions.swift
1
15504
// // FileManager+Extensions.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // 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 // MARK: - FileManager extension /// This extension adds some useful functions to FileManager. public extension FileManager { // MARK: - Variables /// Path type enum. enum PathType: Int { /// Main bundle path. case mainBundle /// Library path. case library /// Documents path. case documents /// Cache path. case cache /// Application Support path. case applicationSupport /// Temporary path. case temporary } // MARK: - Functions /// Get the path for a PathType. /// /// - Parameter path: Path type. /// - Returns: Returns the path type String. func pathFor(_ path: PathType) -> String? { var pathString: String? switch path { case .mainBundle: pathString = mainBundlePath() case .library: pathString = libraryPath() case .documents: pathString = documentsPath() case .cache: pathString = cachePath() case .applicationSupport: pathString = applicationSupportPath() case .temporary: pathString = temporaryPath() } return pathString } /// Save a file with given content. /// /// - Parameters: /// - file: File to be saved. /// - path: File path. /// - content: Content to be saved. /// - Throws: write(toFile:, atomically:, encoding:) errors. func save(file: String, in path: PathType, content: String) throws { guard let path = FileManager.default.pathFor(path) else { return } try content.write(toFile: path.appendingPathComponent(file), atomically: true, encoding: .utf8) } /// Read a file an returns the content as String. /// /// - Parameters: /// - file: File to be read. /// - path: File path. /// - Returns: Returns the content of the file a String. /// - Throws: Throws String(contentsOfFile:, encoding:) errors. func read(file: String, from path: PathType) throws -> String? { guard let path = FileManager.default.pathFor(path) else { return nil } return try String(contentsOfFile: path.appendingPathComponent(file), encoding: .utf8) } /// Save an object into a PLIST with given filename. /// /// - Parameters: /// - object: Object to save into PLIST. /// - path: Path of PLIST. /// - filename: PLIST filename. /// - Returns: Returns true if the operation was successful, otherwise false. @discardableResult func savePlist(object: Any, in path: PathType, filename: String) -> Bool { let path = checkPlist(path: path, filename: filename) guard !path.exist else { return NSKeyedArchiver.archiveRootObject(object, toFile: path.path) } return false } /// Load an object from a PLIST with given filename. /// /// - Parameters: /// - path: Path of PLIST. /// - filename: PLIST filename. /// - Returns: Returns the loaded object. func readPlist(from path: PathType, filename: String) -> Any? { let path = checkPlist(path: path, filename: filename) guard !path.exist else { return NSKeyedUnarchiver.unarchiveObject(withFile: path.path) } return nil } /// Check if plist exist. /// /// - Parameters: /// - path: Path of plist. /// - filename: Plist filename. /// - Returns: Returns if plist exists and path. private func checkPlist(path: PathType, filename: String) -> (exist: Bool, path: String) { guard let path = FileManager.default.pathFor(path), let finalPath = path.appendingPathComponent(filename).appendingPathExtension("plist") else { return (false, "") } return (true, finalPath) } /// Get Main Bundle path for a filename. /// If no file is specified, the main bundle path will be returned. /// /// - Parameter file: Filename. /// - Returns: Returns the path as a String. func mainBundlePath(file: String = "") -> String? { file.isEmpty ? Bundle.main.bundlePath : Bundle.main.path(forResource: file.deletingPathExtension, ofType: file.pathExtension) } /// Get Documents path for a filename. /// /// - Parameter file: Filename /// - Returns: Returns the path as a String. func documentsPath(file: String = "") -> String? { guard let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil } return documentsURL.path.appendingPathComponent(file) } /// Get Library path for a filename. /// /// - Parameter file: Filename /// - Returns: Returns the path as a String. func libraryPath(file: String = "") -> String? { guard let libraryURL = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else { return nil } return libraryURL.path.appendingPathComponent(file) } /// Get Cache path for a filename. /// /// - Parameter file: Filename /// - Returns: Returns the path as a String. func cachePath(file: String = "") -> String? { guard let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else { return nil } return cacheURL.path.appendingPathComponent(file) } /// Get Application Support path for a filename. /// /// - Parameter file: Filename /// - Returns: Returns the path as a String. func applicationSupportPath(file: String = "") -> String? { guard let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil } if !FileManager.default.fileExists(atPath: applicationSupportURL.absoluteString, isDirectory: nil) { do { try FileManager.default.createDirectory(atPath: applicationSupportURL.path, withIntermediateDirectories: true, attributes: nil) } catch { return nil } } return applicationSupportURL.path.appendingPathComponent(file) } /// Get Temporary path for a filename. /// /// - Parameter file: Filename. /// - Returns: Returns the path as a String. func temporaryPath(file: String = "") -> String? { NSTemporaryDirectory().appendingPathComponent(file) } /// Returns the file size. /// /// - Parameters: /// - file: Filename. /// - path: Path of the file. /// - Returns: Returns the file size. /// - Throws: Throws FileManager.default.attributesOfItem(atPath:) errors. func size(file: String, from path: PathType) throws -> Float? { if !file.isEmpty { guard let path = FileManager.default.pathFor(path) else { return nil } let finalPath = path.appendingPathComponent(file) if FileManager.default.fileExists(atPath: finalPath) { let fileAttributes = try FileManager.default.attributesOfItem(atPath: finalPath) return fileAttributes[FileAttributeKey.size] as? Float } } return nil } /// Delete a file with the given filename. /// /// - Parameters: /// - file: File to delete. /// - path: Path of the file. /// - Throws: Throws FileManager.default.removeItem(atPath:) errors. func delete(file: String, from path: PathType) throws { if !file.isEmpty { guard let path = FileManager.default.pathFor(path) else { throw BFKitError.pathNotExist } if FileManager.default.fileExists(atPath: path.appendingPathComponent(file)) { try FileManager.default.removeItem(atPath: path.appendingPathComponent(file)) } } } /// Move a file from a path to another. /// /// - Parameters: /// - file: Filename to move. /// - origin: Origin path of the file. /// - destination: Destination path of the file. /// - Returns: Returns true if the operation was successful, otherwise false. /// - Throws: Throws FileManager.default.moveItem(atPath:, toPath:) and BFKitError errors. func move(file: String, from origin: PathType, to destination: PathType) throws { let paths = try check(file: file, origin: origin, destination: destination) if paths.fileExist { try FileManager.default.moveItem(atPath: paths.origin, toPath: paths.destination) } } /// Copy a file into another path. /// /// - Parameters: /// - file: Filename to copy. /// - origin: Origin path /// - destination: Destination path /// - Returns: Returns true if the operation was successful, otherwise false. /// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:) and BFKitError errors. func copy(file: String, from origin: PathType, to destination: PathType) throws { let paths = try check(file: file, origin: origin, destination: destination) if paths.fileExist { try FileManager.default.copyItem(atPath: paths.origin, toPath: paths.destination) } } /// Check is orign path, destination path and file exists. /// /// - Parameters: /// - file: File. /// - origin: Origin path. /// - destination: Destination path. /// - Returns: Returns a tuple with origin, destination and if file exist. /// - Throws: Throws BFKitError errors. private func check(file: String, origin: PathType, destination: PathType) throws -> (origin: String, destination: String, fileExist: Bool) { // swiftlint:disable:this large_tuple guard let originPath = FileManager.default.pathFor(origin), let destinationPath = FileManager.default.pathFor(destination) else { throw BFKitError.pathNotExist } guard destination != .mainBundle else { throw BFKitError.pathNotAllowed } let finalOriginPath = originPath.appendingPathComponent(file) let finalDestinationPath = destinationPath.appendingPathComponent(file) guard !FileManager.default.fileExists(atPath: finalOriginPath) else { return (finalOriginPath, finalDestinationPath, true) } return (finalOriginPath, finalDestinationPath, false) } /// Rename a file with another filename. /// /// - Parameters: /// - file: Filename to rename. /// - origin: Origin path. /// - newName: New filename. /// - Returns: Returns true if the operation was successful, otherwise false. /// - Throws: Throws FileManager.default.copyItem(atPath:, toPath:), FileManager.default.removeItem(atPath:, toPath:) and BFKitError errors. func rename(file: String, in origin: PathType, to newName: String) throws { guard let originPath = FileManager.default.pathFor(origin) else { throw BFKitError.pathNotExist } let finalOriginPath = originPath.appendingPathComponent(file) if FileManager.default.fileExists(atPath: finalOriginPath) { let destinationPath: String = finalOriginPath.replacingOccurrences(of: file, with: newName) try FileManager.default.copyItem(atPath: finalOriginPath, toPath: destinationPath) try FileManager.default.removeItem(atPath: finalOriginPath) } } /// Set settings for object and key. The file will be saved in the Library path if not exist. /// /// - Parameters: /// - filename: Settings filename. "-Settings" will be automatically added. /// - object: Object to set. /// - objKey: Object key. /// - Returns: Returns true if the operation was successful, otherwise false. /// - Throws: Throws BFKitError errors. @discardableResult func setSettings(filename: String, object: Any, forKey objectKey: String) -> Bool { guard var path = FileManager.default.pathFor(.applicationSupport) else { return false } path = path.appendingPathComponent("\(filename)-Settings.plist") var settings: [String: Any] if let plistData = try? Data(contentsOf: URL(fileURLWithPath: path)), let plistFile = try? PropertyListSerialization.propertyList(from: plistData, format: nil), let plistDictionary = plistFile as? [String: Any] { settings = plistDictionary } else { settings = [:] } settings[objectKey] = object do { let plistData = try PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0) try plistData.write(to: URL(fileURLWithPath: path)) return true } catch { return false } } /// Get settings for key. /// /// - Parameters: /// - filename: Settings filename. "-Settings" will be automatically added. /// - forKey: Object key. /// - Returns: Returns the object for the given key. func getSettings(filename: String, forKey objectKey: String) -> Any? { guard var path = FileManager.default.pathFor(.applicationSupport) else { return nil } path = path.appendingPathComponent("\(filename)-Settings.plist") var settings: [String: Any] if let plistData = try? Data(contentsOf: URL(fileURLWithPath: path)), let plistFile = try? PropertyListSerialization.propertyList(from: plistData, format: nil), let plistDictionary = plistFile as? [String: Any] { settings = plistDictionary } else { settings = [:] } return settings[objectKey] } }
mit
fc2b787fbc706e4bf2b2bd830791b6c3
36.269231
220
0.613584
4.893939
false
false
false
false
PrimarySA/Hackaton2015
bolsaap/BolsApp/BolsApp/Screens/AllStocks/StockCell.swift
1
701
// // StockCell.swift // BolsApp // // Created by Christopher Amato on 11/15/15. // Copyright © 2015 Christopher Amato. All rights reserved. // import UIKit class Stock { var cficode = "" var marketId = "" var symbol = "" init(json:JSON) { cficode = json["cficode"].stringValue let instrumentId = json["instrumentId"] marketId = instrumentId["marketId"].stringValue symbol = instrumentId["symbol"].stringValue } } class StockCell: UITableViewCell { var stock: Stock! @IBOutlet var name: UILabel! func setStock(stock: Stock) { self.stock = stock name.text = stock.symbol } }
gpl-3.0
f0245271d6e27a8257559487b35e8045
17.447368
60
0.594286
3.954802
false
false
false
false
sjf0213/DingShan
DingshanSwift/DingshanSwift/StageMenuGridView.swift
1
3014
// // StageMenuGridView.swift // DingshanSwift // // Created by song jufeng on 15/12/23. // Copyright © 2015年 song jufeng. All rights reserved. // import Foundation class StageMenuGridView : UIView{ var tapItemHandler : ((index:Int, title:String) -> Void)?// 用户点击处理 var userSelectIndex:Int = 0 var container_h:CGFloat = 0.0 var subItemContainer = UIView()// 按钮容器 // MARK: init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame aRect: CGRect) { super.init(frame: aRect) self.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.3) self.clipsToBounds = true self.subItemContainer = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 0)) self.subItemContainer.backgroundColor = UIColor.whiteColor() self.subItemContainer.clipsToBounds = true self.addSubview(self.subItemContainer) } func loadMenuItems(arr:[AnyObject]){ // 生成所有菜单项 let w:CGFloat = UIScreen.mainScreen().bounds.width / 2 let h:CGFloat = 58 for (var i = 0; i < arr.count; i++){ if let one = arr[i] as? [NSObject:AnyObject]{ let row:Int = i/2 let col:Int = i%2 let rect = CGRect(x: w * CGFloat(col), y: h * CGFloat(row), width: w, height: h) let btn = StageMenuItem(frame: rect) self.subItemContainer.addSubview(btn) btn.tag = i if let t = one["title"] as? String{ btn.setTitle(t, forState: UIControlState.Normal) } // 显示当前正在选中的项目 if userSelectIndex == i{ btn.curSelected = true } btn.addTarget(self, action: Selector("onTapItem:"), forControlEvents: UIControlEvents.TouchUpInside) } } let rowCount:Int = (arr.count-1)/2 + 1 self.container_h = h*CGFloat(rowCount) + 10 self.subItemContainer.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: container_h) } // 点击二级菜单项 func onTapItem(item:GalleryMenuItem) { print("----------sub menu items title:\(item.titleLabel?.text), tagIndex:\(item.tag)") // 低亮其他 for v in self.subItemContainer.subviews{ if let i = v as? GalleryMenuItem{ if i != item{ i.curSelected = false } } } // 高亮所选 item.curSelected = true // 更新设置 userSelectIndex = item.tag self.setNeedsDisplay() let t = item.titleForState(UIControlState.Normal) if (self.tapItemHandler != nil && t != nil) { self.tapItemHandler?(index:self.userSelectIndex, title:t!) } } }
mit
0567da48b27e1e4fb9f65f0aec15d681
34.585366
120
0.561193
4.321481
false
false
false
false
tlax/GaussSquad
GaussSquad/View/Store/VStoreCellPurchased.swift
1
789
import UIKit class VStoreCellPurchased:VStoreCell { override init(frame:CGRect) { super.init(frame:frame) backgroundColor = UIColor.squadBlue isUserInteractionEnabled = false let label:UILabel = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.isUserInteractionEnabled = false label.textAlignment = NSTextAlignment.center label.font = UIFont.medium(size:16) label.textColor = UIColor.white label.text = NSLocalizedString("VStoreCellPurchased_label", comment:"") addSubview(label) NSLayoutConstraint.equals( view:label, toView:self) } required init?(coder:NSCoder) { return nil } }
mit
be4cb25916d9b88eaf83c576a8bf8ff5
25.3
79
0.626109
5.40411
false
false
false
false
ZoranPandovski/al-go-rithms
data_structures/trie/swift/trie.swift
1
1228
import Foundation class TrieNode { private var charMap: [Character: TrieNode] public var size: Int init() { charMap = [:] size = 0 } public func add(c: Character) { if let _ = self.charMap[c] { // do nothing if exists } else { self.charMap[c] = TrieNode() } } public func getChild(c: Character) -> TrieNode? { return self.charMap[c] } } class Trie { private var root: TrieNode init() { root = TrieNode() } init(words: [String]) { root = TrieNode() for word in words { self.add(word: word) } } public func add(word: String) { var current = root for c in word { current.add(c: c) current = current.getChild(c: c)! current.size = current.size + 1 } } public func find(prefix: String) -> Int { var current = root for c in prefix { if let childNode = current.getChild(c: c) { current = childNode } else { return 0 } } return current.size } }
cc0-1.0
f5a46ee4bdd4b88a4efd9fee48899250
19.131148
55
0.463355
4.308772
false
false
false
false
neoneye/SwiftyFORM
Tests/ValidateResultTests.swift
1
1441
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit import XCTest @testable import SwiftyFORM class ValidateResultTests: XCTestCase { func testCompare_same0() { let a = ValidateResult.valid let b = ValidateResult.valid XCTAssertEqual(a, b) } func testCompare_same1() { let a = ValidateResult.hardInvalid(message: "hello") let b = ValidateResult.hardInvalid(message: "hello") XCTAssertEqual(a, b) } func testCompare_same2() { let a = ValidateResult.softInvalid(message: "world") let b = ValidateResult.softInvalid(message: "world") XCTAssertEqual(a, b) } func testCompare_different0() { let a = ValidateResult.valid let b = ValidateResult.hardInvalid(message: "goodbye") XCTAssertNotEqual(a, b) } func testCompare_different1() { let a = ValidateResult.hardInvalid(message: "hello") let b = ValidateResult.hardInvalid(message: "goodbye") XCTAssertNotEqual(a, b) } func testCompare_different2() { let a = ValidateResult.valid let b = ValidateResult.softInvalid(message: "howdy") XCTAssertNotEqual(a, b) } func testCompare_different3() { let a = ValidateResult.softInvalid(message: "world") let b = ValidateResult.softInvalid(message: "candy") XCTAssertNotEqual(a, b) } func testCompare_different4() { let a = ValidateResult.hardInvalid(message: "hello") let b = ValidateResult.softInvalid(message: "candy") XCTAssertNotEqual(a, b) } }
mit
37f26c7d259dba4d233609755b8643fc
24.732143
67
0.727273
3.620603
false
true
false
false
cooldy555/onicolae2017
Source/onicolae2017.swift
1
1497
// // onicolae2017.swift // onicolae2017 // // Created by cooldy555 on May 3, 2017. // Copyright © 2017 ecole42. All rights reserved. // import Foundation import UIKit public class onicolae2017: UIView { public override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.translatesAutoresizingMaskIntoConstraints = false let bundle = Bundle(for: type(of: self)) let image = UIImage(named: "wk", in: bundle, compatibleWith: nil) let imageView = UIImageView(image: image) imageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageView) self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .height, relatedBy: .equal, toItem: self, attribute: .height, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: imageView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) self.layoutIfNeeded() } }
mit
34c8b8f180ab2254fc8fa5ea3c72b921
38.368421
166
0.677139
4.323699
false
false
false
false
magicien/MMDSceneKit
Source/Common/MMDProgram.swift
1
3102
// // MMDProgram.swift // MMDSceneKit // // Created by magicien on 12/24/15. // Copyright © 2015 DarkHorse. All rights reserved. // import SceneKit #if !os(watchOS) public class MMDProgram: SCNProgram, SCNProgramDelegate { override public init() { super.init() self.delegate = self self.vertexFunctionName = "mmdVertex" self.fragmentFunctionName = "mmdFragment" /* let device = MTLCreateSystemDefaultDevice() print("device.name: \(device!.name!)") let libraryPath = Bundle(for: MMDProgram.self).path(forResource: "default", ofType: "metallib") print("libraryPath: \(libraryPath!)") let commandQueue = device!.makeCommandQueue() do { self.library = try device!.makeLibrary(filepath: libraryPath!) } catch { print("********* library setting error ************") } self.vertexFunctionName = "mmdVertex" self.fragmentFunctionName = "mmdFragment" let vertexShader = self.library!.makeFunction(name: "mmdVertex") let fragmentShader = self.library!.makeFunction(name: "mmdFragment") let functionNames = self.library!.functionNames for name in functionNames { print("functionName: \(name)") } */ /* self.setSemantic(SCNModelTransform, forSymbol: "modelTransform", options: nil) self.setSemantic(SCNViewTransform, forSymbol: "viewTransform", options: nil) self.setSemantic(SCNProjectionTransform, forSymbol: "projectionTransform", options: nil) self.setSemantic(SCNNormalTransform, forSymbol: "normalTransform", options: nil) self.setSemantic(SCNModelViewTransform, forSymbol: "modelViewTransform", options: nil) self.setSemantic(SCNModelViewProjectionTransform, forSymbol: "modelViewProjectionTransform", options: nil) self.setSemantic(SCNGeometrySourceSemanticVertex, forSymbol: "aPos", options: nil) self.setSemantic(SCNGeometrySourceSemanticNormal, forSymbol: "aNormal", options: nil) self.setSemantic(SCNGeometrySourceSemanticColor, forSymbol: "aColor", options: nil) self.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "aTexcoord0", options: [SCNProgramMappingChannelKey: 0]) self.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "aTexcoord1", options: [SCNProgramMappingChannelKey: 1]) self.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "aTexcoord2", options: [SCNProgramMappingChannelKey: 2]) self.setSemantic(SCNGeometrySourceSemanticTexcoord, forSymbol: "aTexcoord3", options: [SCNProgramMappingChannelKey: 3]) */ print("*********** MMDProgram created ****************") } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @nonobjc public func program(_ program: SCNProgram, handleError error: NSError) { print("***** GLSL compile error: \(error)") } } #endif
mit
30ccb29aeef0ef3ac434efe35ac303b3
40.346667
127
0.663657
4.875786
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEBrowser/NKE_BrowserWindow.swift
1
6722
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation #if os(iOS) import UIKit #endif class NKE_BrowserWindow: NSObject { internal var _events: NKEventEmitter = NKEventEmitter() internal static var _windowArray: [Int: NKE_BrowserWindow] = [Int: NKE_BrowserWindow]() internal var _window: AnyObject? internal weak var _context: NKScriptContext? internal weak var _webView: AnyObject? internal var _browserType: NKEBrowserType = NKEBrowserType.WKWebView internal var _id: Int = 0 private var _type: String = "" internal var _options: Dictionary <String, AnyObject> = Dictionary <String, AnyObject>() private var _nke_renderer: AnyObject? internal var _webContents: NKE_WebContentsBase? = nil internal var _accessoryBarHeight : CGFloat = 44 internal var _recognizer : AnyObject? = nil internal var _keyboardIsVisible: Bool = false override init() { super.init() } // Creates a new BrowserWindow with native properties as set by the options. required init(options: Dictionary<String, AnyObject>) { super.init() // PARSE & STORE OPTIONS self._options["nk.InstallElectro"] = options["nk.InstallElectro"] as? Bool ?? true self._options["nk.ScriptContextDelegate"] = options["nk.ScriptContextDelegate"] as? NKScriptContextDelegate let allowCustomProtocol: Bool = options[NKEBrowserOptions.nkAllowCustomProtocol] as? Bool ?? false let defaultBrowser: String = allowCustomProtocol ? NKEBrowserType.UIWebView.rawValue : NKEBrowserType.UIWebView.rawValue self._browserType = NKEBrowserType(rawValue: (options[NKEBrowserOptions.nkBrowserType] as? String) ?? defaultBrowser)! switch self._browserType { case .WKWebView: NKLogging.log("+creating Nitro Renderer") self._id = self.createWKWebView(options) self._type = "Nitro" let webContents: NKE_WebContentsWK = NKE_WebContentsWK(window: self) self._webContents = webContents case .UIWebView: NKLogging.log("+creating JavaScriptCore Renderer") self._id = self.createUIWebView(options) self._type = "JavaScriptCore" let webContents: NKE_WebContentsUI = NKE_WebContentsUI(window: self) self._webContents = webContents } NKE_BrowserWindow._windowArray[self._id] = self } deinit { #if os(iOS) unhookKeyboard() #endif } // class functions (for Swift/Objective-C use only, equivalent functions exist in .js helper ) static func fromId(id: Int) -> NKE_BrowserWindowProtocol? { return NKE_BrowserWindow._windowArray[id] } var id: Int { get { return _id } } var type: String { get { return _type } } var webContents: NKE_WebContentsBase { get { return _webContents! } } private static func NotImplemented(functionName: String = #function) -> Void { NKLogging.log("!browserWindow.\(functionName) is not implemented") } private func NotImplemented(functionName: String = #function) -> Void { NKLogging.log("!browserWindow.\(functionName) is not implemented") } } extension NKE_BrowserWindow: NKScriptExport { static func attachTo(context: NKScriptContext) { let principal = NKE_BrowserWindow.self context.loadPlugin(principal, namespace: "io.nodekit.electro.BrowserWindow", options: [String:AnyObject]()) } class func rewriteGeneratedStub(stub: String, forKey: String) -> String { switch (forKey) { case ".global": return NKStorage.getPluginWithStub(stub, "lib-electro.nkar/lib-electro/browser-window.js", NKElectro.self) default: return stub } } class func rewriteScriptNameForKey(name: String) -> String? { return (name == "initWithOptions:" ? "" : nil) } class func isExcludedFromScript(selector: String) -> Bool { return selector.hasPrefix("webView") || selector.hasPrefix("NKScriptEngineLoaded") || selector.hasPrefix("NKApplicationReady") } } extension NKE_BrowserWindow: NKScriptContextDelegate { internal func NKScriptEngineDidLoad(context: NKScriptContext) -> Void { NKLogging.log("+E\(context.id) Renderer Loaded") self._context = context // INSTALL JAVASCRIPT ENVIRONMENT ON RENDERER CONTEXT if (self._options["nk.InstallElectro"] as! Bool) { NKElectro.bootToRenderer(context) } (self._options["nk.ScriptContextDelegate"] as? NKScriptContextDelegate)?.NKScriptEngineDidLoad(context) } internal func NKScriptEngineReady(context: NKScriptContext) -> Void { switch self._browserType { case .WKWebView: WKScriptEnvironmentReady() case .UIWebView: UIScriptEnvironmentReady() } (self._options["nk.ScriptContextDelegate"] as? NKScriptContextDelegate)?.NKScriptEngineReady(context) NKLogging.log("+E\(id) Renderer Ready") } }
apache-2.0
69edd53792eb011a13f33ef031f1aa40
26.325203
128
0.576317
5.198763
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Data/RoomList/Common/MXSuggestedRoomListDataCache.swift
1
1281
// // Copyright 2021 The Matrix.org Foundation C.I.C // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation internal class MXSuggestedRoomListDataCache { private var cache: [MXSpace: MXSpaceChildrenSummary] internal static let shared: MXSuggestedRoomListDataCache = MXSuggestedRoomListDataCache() internal init(withSuggestedRoomsMap cache: [MXSpace: MXSpaceChildrenSummary] = [:]) { self.cache = cache } internal subscript(key: MXSpace) -> MXSpaceChildrenSummary? { get { return cache[key] } set { if let newValue = newValue { cache[key] = newValue } else { cache.removeValue(forKey: key) } } } }
apache-2.0
da704f52094b155a826301c5c50dce2a
30.243902
93
0.663544
4.558719
false
false
false
false
biohazardlover/i3rd
MaChérie/UI/MoreViewController.swift
1
2952
// // MoreViewController.swift // MaChérie // // Created by Leon Li on 2018/6/15. // Copyright © 2018 Leon & Vane. All rights reserved. // import UIKit class MoreViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
mit
33a5400fe13063a3febd92b1973a018a
31.777778
136
0.667119
5.221239
false
false
false
false
mshhmzh/firefox-ios
Storage/Bookmarks/Bookmarks.swift
4
18479
/* 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 UIKit import Shared import Deferred private let log = Logger.syncLogger public protocol SearchableBookmarks: class { func bookmarksByURL(url: NSURL) -> Deferred<Maybe<Cursor<BookmarkItem>>> } public protocol SyncableBookmarks: class, ResettableSyncStorage, AccountRemovalDelegate { // TODO func isUnchanged() -> Deferred<Maybe<Bool>> func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> func treeForMirror() -> Deferred<Maybe<BookmarkTree>> func applyLocalOverrideCompletionOp(op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success } public let NotificationBookmarkBufferValidated = "NotificationBookmarkBufferValidated" public protocol BookmarkBufferStorage: class { func isEmpty() -> Deferred<Maybe<Bool>> func applyRecords(records: [BookmarkMirrorItem]) -> Success func doneApplyingRecordsAfterDownload() -> Success func validate() -> Success func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func applyBufferCompletionOp(op: BufferCompletionOp, itemSources: ItemSources) -> Success // Only use for diagnostics. func synchronousBufferCount() -> Int? } public protocol MirrorItemSource: class { func getMirrorItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> func prefetchMirrorItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success } public protocol BufferItemSource: class { func getBufferItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> func prefetchBufferItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success } public protocol LocalItemSource: class { func getLocalItemWithGUID(guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> func prefetchLocalItemsWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success } public class ItemSources { public let local: LocalItemSource public let mirror: MirrorItemSource public let buffer: BufferItemSource public init(local: LocalItemSource, mirror: MirrorItemSource, buffer: BufferItemSource) { self.local = local self.mirror = mirror self.buffer = buffer } public func prefetchWithGUIDs<T: CollectionType where T.Generator.Element == GUID>(guids: T) -> Success { return self.local.prefetchLocalItemsWithGUIDs(guids) >>> { self.mirror.prefetchMirrorItemsWithGUIDs(guids) } >>> { self.buffer.prefetchBufferItemsWithGUIDs(guids) } } } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" public static let FakeDesktopFolderGUID = "desktop_____" // Pseudo. Never mentioned in a real record. // This is the order we use. public static let RootChildren: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.MobileFolderGUID, ] public static let DesktopRoots: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ] public static let Real = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ]) public static let All = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.FakeDesktopFolderGUID, ]) /** * Sync records are a horrible mess of Places-native GUIDs and Sync-native IDs. * For example: * {"id":"places", * "type":"folder", * "title":"", * "description":null, * "children":["menu________","toolbar_____", * "tags________","unfiled_____", * "jKnyPDrBQSDg","T6XK5oJMU8ih"], * "parentid":"2hYxKgBwvkEH"}" * * We thus normalize on the extended Places IDs (with underscores) for * local storage, and translate to the Sync IDs when creating an outbound * record. * We translate the record's ID and also its parent. Evidence suggests that * we don't need to translate children IDs. * * TODO: We don't create outbound records yet, so that's why there's no * translation in that direction yet! */ public static func translateIncomingRootGUID(guid: GUID) -> GUID { return [ "places": RootGUID, "root": RootGUID, "mobile": MobileFolderGUID, "menu": MenuFolderGUID, "toolbar": ToolbarFolderGUID, "unfiled": UnfiledFolderGUID ][guid] ?? guid } public static func translateOutgoingRootGUID(guid: GUID) -> GUID { return [ RootGUID: "places", MobileFolderGUID: "mobile", MenuFolderGUID: "menu", ToolbarFolderGUID: "toolbar", UnfiledFolderGUID: "unfiled" ][guid] ?? guid } /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This partly matches Places's nsINavBookmarksService, just for sanity. * * It is further extended to support the types that exist in Sync, so we can use * this to store mirrored rows. * * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case Bookmark = 1 case Folder = 2 case Separator = 3 case DynamicContainer = 4 case Livemark = 5 case Query = 6 // No microsummary: those turn into bookmarks. } public func == (lhs: BookmarkMirrorItem, rhs: BookmarkMirrorItem) -> Bool { if lhs.type != rhs.type || lhs.guid != rhs.guid || lhs.serverModified != rhs.serverModified || lhs.isDeleted != rhs.isDeleted || lhs.hasDupe != rhs.hasDupe || lhs.pos != rhs.pos || lhs.faviconID != rhs.faviconID || lhs.localModified != rhs.localModified || lhs.parentID != rhs.parentID || lhs.parentName != rhs.parentName || lhs.feedURI != rhs.feedURI || lhs.siteURI != rhs.siteURI || lhs.title != rhs.title || lhs.description != rhs.description || lhs.bookmarkURI != rhs.bookmarkURI || lhs.tags != rhs.tags || lhs.keyword != rhs.keyword || lhs.folderName != rhs.folderName || lhs.queryID != rhs.queryID { return false } if let lhsChildren = lhs.children, rhsChildren = rhs.children { return lhsChildren == rhsChildren } return lhs.children == nil && rhs.children == nil } public struct BookmarkMirrorItem: Equatable { public let guid: GUID public let type: BookmarkNodeType public var serverModified: Timestamp public let isDeleted: Bool public let hasDupe: Bool public let parentID: GUID? public let parentName: String? // Livemarks. public let feedURI: String? public let siteURI: String? // Separators. let pos: Int? // Folders, livemarks, bookmarks and queries. public let title: String? let description: String? // Bookmarks and queries. let bookmarkURI: String? let tags: String? let keyword: String? // Queries. let folderName: String? let queryID: String? // Folders. public let children: [GUID]? // Internal stuff. let faviconID: Int? public let localModified: Timestamp? let syncStatus: SyncStatus? public func copyWithParentID(parentID: GUID, parentName: String?) -> BookmarkMirrorItem { return BookmarkMirrorItem( guid: self.guid, type: self.type, serverModified: self.serverModified, isDeleted: self.isDeleted, hasDupe: self.hasDupe, parentID: parentID, parentName: parentName, feedURI: self.feedURI, siteURI: self.siteURI, pos: self.pos, title: self.title, description: self.description, bookmarkURI: self.bookmarkURI, tags: self.tags, keyword: self.keyword, folderName: self.folderName, queryID: self.queryID, children: self.children, faviconID: self.faviconID, localModified: self.localModified, syncStatus: self.syncStatus) } // Ignores internal metadata and GUID; a pure value comparison. // Does compare child GUIDs! public func sameAs(rhs: BookmarkMirrorItem) -> Bool { if self.type != rhs.type || self.isDeleted != rhs.isDeleted || self.pos != rhs.pos || self.parentID != rhs.parentID || self.parentName != rhs.parentName || self.feedURI != rhs.feedURI || self.siteURI != rhs.siteURI || self.title != rhs.title || (self.description ?? "") != (rhs.description ?? "") || self.bookmarkURI != rhs.bookmarkURI || self.tags != rhs.tags || self.keyword != rhs.keyword || self.folderName != rhs.folderName || self.queryID != rhs.queryID { return false } if let lhsChildren = self.children, rhsChildren = rhs.children { return lhsChildren == rhsChildren } return self.children == nil && rhs.children == nil } public func asJSON() -> JSON { return self.asJSONWithChildren(self.children) } public func asJSONWithChildren(children: [GUID]?) -> JSON { var out: [String: AnyObject] = [:] out["id"] = BookmarkRoots.translateOutgoingRootGUID(self.guid) func take(key: String, _ val: String?) { guard let val = val else { return } out[key] = val } if self.isDeleted { out["deleted"] = true return JSON(out) } out["hasDupe"] = self.hasDupe // TODO: this should never be nil! if let parentID = self.parentID { out["parentid"] = BookmarkRoots.translateOutgoingRootGUID(parentID) take("parentName", titleForSpecialGUID(parentID) ?? self.parentName) } func takeBookmarkFields() { take("title", self.title) take("bmkUri", self.bookmarkURI) take("description", self.description) if let tags = self.tags { let tagsJSON = JSON.parse(tags) if let tagsArray = tagsJSON.asArray where tagsArray.every({ $0.isString }) { out["tags"] = tagsArray } else { out["tags"] = [] } } else { out["tags"] = [] } take("keyword", self.keyword) } func takeFolderFields() { take("title", titleForSpecialGUID(self.guid) ?? self.title) take("description", self.description) if let children = children { if BookmarkRoots.RootGUID == self.guid { // Only the root contains roots, and so only its children // need to be translated. out["children"] = children.map(BookmarkRoots.translateOutgoingRootGUID) } else { out["children"] = children } } } switch self.type { case .Query: out["type"] = "query" take("folderName", self.folderName) take("queryId", self.queryID) takeBookmarkFields() case .Bookmark: out["type"] = "bookmark" takeBookmarkFields() case .Livemark: out["type"] = "livemark" take("siteUri", self.siteURI) take("feedUri", self.feedURI) takeFolderFields() case .Folder: out["type"] = "folder" takeFolderFields() case .Separator: out["type"] = "separator" if let pos = self.pos { out["pos"] = pos } case .DynamicContainer: // Sigh. preconditionFailure("DynamicContainer not supported.") } return JSON(out) } // The places root is a folder but has no parentName. public static func folder(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, children: [GUID]) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Folder, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: children, faviconID: nil, localModified: nil, syncStatus: nil) } public static func livemark(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String?, description: String?, feedURI: String, siteURI: String) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Livemark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: feedURI, siteURI: siteURI, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func separator(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, pos: Int) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Separator, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: pos, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func bookmark(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, title: String, description: String?, URI: String, tags: String, keyword: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Bookmark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func query(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, title: String, description: String?, URI: String, tags: String, keyword: String?, folderName: String?, queryID: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Query, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: folderName, queryID: queryID, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func deleted(type: BookmarkNodeType, guid: GUID, modified: Timestamp) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) return BookmarkMirrorItem(guid: id, type: type, serverModified: modified, isDeleted: true, hasDupe: false, parentID: nil, parentName: nil, feedURI: nil, siteURI: nil, pos: nil, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } }
mpl-2.0
8b3791af7ff6851c672a273e665a04db
36.482759
257
0.622653
4.886039
false
false
false
false
appfoundry/DRYLogging
Example/Tests/DefaultLoggerInheritanceSpec.swift
1
2494
// // DefaultLoggerInheritanceSpec.swift // DRYLogging // // Created by Michael Seghers on 15/11/2016. // Copyright © 2016 Michael Seghers. All rights reserved. // import Foundation import Quick import Nimble import DRYLogging class DefaultLoggerInheritanceSpec : QuickSpec { override func spec() { describe("DefaultLogger Inheritance") { var child:DefaultLogger! var parent:DefaultLogger! var grandParent:DefaultLogger! beforeEach { grandParent = DefaultLogger(name: "grandparent") parent = DefaultLogger(name: "parent", parent: grandParent) child = DefaultLogger(name: "child", parent: parent) } context("logger hierarchy from grandParent to child") { it("child should inherit logLevel from parent") { parent.logLevel = .info expect(child.isInfoEnabled) == true } it("child should override parent logging level when set") { parent.logLevel = .info child.logLevel = .error expect(child.isInfoEnabled) == false } } context("logger hierarchy with appenders") { var childAppender:LoggingAppenderMock! var parentAppender:LoggingAppenderMock! var grandParentAppender:LoggingAppenderMock! beforeEach { child.logLevel = .info grandParentAppender = LoggingAppenderMock() grandParent.add(appender: grandParentAppender) parentAppender = LoggingAppenderMock() parent.add(appender: parentAppender) childAppender = LoggingAppenderMock() child.add(appender: childAppender) } it("should append the message to the parent appender") { child.info("test") expect(parentAppender.messages).to(haveCount(1)) } it("should append the message to the parent appender") { child.info("test") expect(grandParentAppender.messages).to(haveCount(1)) } } } } }
mit
9ad9bb9e3f2b2cf81c3bbcb8bdbf3781
34.614286
75
0.514641
5.949881
false
false
false
false
ShenYj/Demos
自定义刷新控件/自定义刷新控件/JSRefresh.swift
1
6206
// // JSRefresh.swift // 自定义刷新控件 // // Created by ShenYj on 16/7/1. // Copyright © 2016年 ___ShenYJ___. All rights reserved. // import UIKit // 自定义刷新控件的高度 let REFRESH_HEIGHT: CGFloat = 50 // 设置自定义刷新控件的背景色 let REFRESH_BACKGROUND_COLOR: UIColor = UIColor.orangeColor() // 屏幕宽度 let SCREEN_WIDTH = UIScreen.mainScreen().bounds.width // 自定义刷新控件文字状态字体大小 let STATUS_LABEL_FONT_SIZE: CGFloat = 15 // 自定义刷新控件文字字体颜色 let STATUS_LABEL_FONT_COLOR: UIColor = UIColor.purpleColor() // 刷新控件的状态 enum JSRefreshType: Int { case Normal = 0 // 正常 case Pulling = 1 // 下拉中 case Refreshing = 2 // 刷新中 } class JSRefresh: UIControl { // 被观察对象 var scrollerView: UIScrollView? // MARK: - 懒加载控件 private lazy var statusLabel: UILabel = { let label = UILabel() label.font = UIFont.systemFontOfSize(STATUS_LABEL_FONT_SIZE) label.textColor = STATUS_LABEL_FONT_COLOR label.textAlignment = .Center return label }() // 记录刷新控件状态,初始为正常状态 var refreshStatus: JSRefreshType = .Normal{ didSet{ switch refreshStatus { case .Normal: statusLabel.text = "\(refreshStatus)" // 让自定义控件的上方间距恢复 UIView.animateWithDuration(0.25, animations: { self.scrollerView?.contentInset.top -= REFRESH_HEIGHT }) case .Pulling: statusLabel.text = "\(refreshStatus)" case .Refreshing: statusLabel.text = "\(refreshStatus)" //刷新中状态让自定义刷新控件保留显示 UIView.animateWithDuration(0.25, animations: { self.scrollerView?.contentInset.top += REFRESH_HEIGHT }, completion: { (finished) in self.sendActionsForControlEvents(UIControlEvents.ValueChanged) }) } } } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: -REFRESH_HEIGHT, width: SCREEN_WIDTH, height: REFRESH_HEIGHT)) // 设置视图 setupUI() } // MARK: - 设置视图 private func setupUI () { // 设置背景色 backgroundColor = REFRESH_BACKGROUND_COLOR // 添加控件 addSubview(statusLabel) // 添加约束 statusLabel.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)) addConstraint(NSLayoutConstraint(item: statusLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)) } // MARK: - 监听该类将要添加到哪个父控件上 override func willMoveToSuperview(newSuperview: UIView?) { /* 这里需要监测父控件的ContentOffSet判断状态 因为其控制器可能会使用TableView的代理方法,代理为一对一,考虑到封装性,不推荐使用代理,所以这里使用KVO KVO的使用基本上都是三步:   1.注册观察者 addObserver:forKeyPath:options:context: 2.观察者中实现 observeValueForKeyPath:ofObject:change:context: 3.移除观察者 removeObserver:forKeyPath: */ // 判断是否有值,是否可以滚动 guard let scrollerView = newSuperview as? UIScrollView else { return } self.scrollerView = scrollerView // 注册观察者 scrollerView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil) } // 观察者实现 override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { // 获取所监听的scrollView的Y轴偏移量 let contentOffSetY = self.scrollerView!.contentOffset.y // 判断ScrollView是否正在拖动 if scrollerView!.dragging { // 如果 scrollerView!.dragging == true 代表当前正在拖动ScrollView if contentOffSetY > -(REFRESH_HEIGHT+64) && refreshStatus == .Pulling { // contentOffSet.y > -(自定义刷新控件高度+64) && 当前状态为下拉中 --> 正常状态 refreshStatus = .Normal } else if contentOffSetY <= -(REFRESH_HEIGHT+64) && refreshStatus == .Normal { // contentOffSet.y <= -(自定义刷新控件高度+64) && 当前状态为正常 --> 下拉状态 refreshStatus = .Pulling } // 未拖动ScrollView时 } else { // 停止拖动并松手,而且状态为下拉中 --> 刷新 if refreshStatus == .Pulling { refreshStatus = .Refreshing } } } // MARK: - 结束刷新 func endRefreshing() -> Void { // 将状态改为正常 refreshStatus = .Normal } deinit{ // 移除观察者 self.scrollerView?.removeObserver(self, forKeyPath: "contentOffset") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
3a309b9e675b26009e557e209960bd20
28.112299
213
0.544636
5.026777
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Home/View/MGScanViewStyle.swift
1
2671
// // MGScanViewStyle.swift // MGDYZB // // Created by i-Techsys.com on 17/4/11. // Copyright © 2017年 ming. All rights reserved. // import UIKit // MARK: - 扫码区域动画效果 public enum MGScanViewAnimationStyle { case LineMove //线条上下移动 case NetGrid//网格 case LineStill//线条停止在扫码区域中央 case None //无动画 } // MARK: - 扫码区域4个角位置类型 public enum MGScanViewPhotoframeAngleStyle { case Inner//内嵌,一般不显示矩形框情况下 case Outer//外嵌,包围在矩形框的4个角 case On //在矩形框的4个角上,覆盖 } public struct MGScanViewStyle { // MARK: - 中心位置矩形框 /// 是否需要绘制扫码矩形框,默认YES public var isNeedShowRetangle:Bool = true /** * 默认扫码区域为正方形,如果扫码区域不是正方形,设置宽高比 */ public var whRatio:CGFloat = 1.0 /** @brief 矩形框(视频显示透明区)域向上移动偏移量,0表示扫码透明区域在当前视图中心位置,如果负值表示扫码区域下移 */ public var centerUpOffset:CGFloat = 44 /** * 矩形框(视频显示透明区)域离界面左边及右边距离,默认60 */ public var xScanRetangleOffset:CGFloat = 60 /** @brief 矩形框线条颜色,默认白色 */ public var colorRetangleLine = UIColor.white //MARK -矩形框(扫码区域)周围4个角 /** @brief 扫码区域的4个角类型 */ public var photoframeAngleStyle = MGScanViewPhotoframeAngleStyle.Outer //4个角的颜色 public var colorAngle = UIColor(red: 0.0, green: 167.0/255.0, blue: 231.0/255.0, alpha: 1.0) //扫码区域4个角的宽度和高度 public var photoframeAngleW:CGFloat = 24.0 public var photoframeAngleH:CGFloat = 24.0 /** @brief 扫码区域4个角的线条宽度,默认6,建议8到4之间 */ public var photoframeLineW:CGFloat = 6 //MARK: ----动画效果 /** @brief 扫码动画效果:线条或网格 */ public var anmiationStyle = MGScanViewAnimationStyle.LineMove /** * 动画效果的图像,如线条或网格的图像 */ public var animationImage:UIImage? // MARK: -非识别区域颜色,默认 RGBA (0,0,0,0.5),范围(0--1) public var color_NotRecoginitonArea:UIColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5); public init() { animationImage = UIImage(named: "MGCodeScan.bundle/qrcode_scan_light_green") } }
mit
d055a1cdce639cbe3ab451b88878ff71
20.744681
103
0.619863
3.2704
false
false
false
false
tnantoka/boid
Boid/AlignmentRule.swift
1
884
// // AlignmentRule.swift // Boid // // Created by Tatsuya Tobioka on 9/15/14. // Copyright (c) 2014 tnantoka. All rights reserved. // import UIKit class AlignmentRule: Rule { let factor: CGFloat = 2.0 override func evaluate(targetNode targetNode: BirdNode, birdNodes: [BirdNode]) { super.evaluate(targetNode: targetNode, birdNodes: birdNodes) for birdNode in birdNodes { if birdNode != targetNode { self.velocity.x += birdNode.velocity.x self.velocity.y += birdNode.velocity.y } } self.velocity.x /= CGFloat(birdNodes.count - 1) self.velocity.y /= CGFloat(birdNodes.count - 1) self.velocity.x = (self.velocity.x - targetNode.velocity.x) / self.factor self.velocity.y = (self.velocity.y - targetNode.velocity.y) / self.factor } }
mit
99d36d02096f9513c4350a8d5e72e387
28.466667
84
0.61086
3.860262
false
false
false
false
einsteinx2/iSub
Classes/Supporting Files/Defines.swift
1
1968
// // Defines.swift // iSub // // Created by Benjamin Baron on 12/15/14. // Copyright (c) 2014 Ben Baron. All rights reserved. // import Foundation import UIKit import Device func IS_IPAD() -> Bool { return UIDevice.current.userInterfaceIdiom == .pad } private let BaseWidth : CGFloat = 320 func ISMSNormalize(_ value: CGFloat, multiplier: CGFloat = 1, maxDelta: CGFloat = 1024) -> CGFloat { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { return value } let screenWidth = portraitScreenSize.width let percent = (screenWidth - BaseWidth)/screenWidth let normalizedValue = value * (1 + percent) * multiplier let minValue = min(normalizedValue, value + maxDelta) //capped by a max value if needed return ceil(minValue) // Return whole numbers } var portraitScreenSize: CGSize { let screenSize = UIScreen.main.bounds.size let width = min(screenSize.width, screenSize.height) let height = max(screenSize.width, screenSize.height) return CGSize(width: width, height: height) } func BytesForSecondsAtBitRate(seconds: Int, bitRate: Int) -> Int64 { return (Int64(bitRate) / 8) * 1024 * Int64(seconds) } let ISMSHeaderColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 206.0/255.0, alpha: 1.0) let ISMSHeaderTextColor = UIColor(red: 77.0/255.0, green: 77.0/255.0, blue: 77.0/255.0, alpha: 1.0) let ISMSHeaderButtonColor = UIColor(red: 0.0, green: 122.0/255.0, blue: 1.0, alpha: 1.0) let ISMSiPadBackgroundColor = ISMSHeaderColor let ISMSiPadCornerRadius = 5.0 let CellHeight: CGFloat = 50.0 let CellHeaderHeight: CGFloat = 20.0 let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let cachesPath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0] let songCachePath = documentsPath + "/songCache" let tempCachePath = cachesPath + "/tempCache" let imageCachePath = documentsPath + "/imageCache"
gpl-3.0
a502dd79ee5c7aef030d39e398ab6c75
34.142857
101
0.732215
3.741445
false
false
false
false
blitzagency/amigo-swift
AmigoTests/AmigoQuerySetTests.swift
1
6316
// // AmigoQuerySetTests.swift // Amigo // // Created by Adam Venturella on 7/24/15. // Copyright © 2015 BLITZ. All rights reserved. // import XCTest import CoreData import Amigo class AmigoQuerySetTests: AmigoTestBase { func testMultipleForeignKeys(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let c1 = Cat() c1.label = "Ollie" let p1 = People() p1.label = "Foo" p1.dog = d1 p1.cat = c1 session.add(p1) let people = session .query(People) .selectRelated("dog", "cat") .all() XCTAssertEqual(people.count, 1) XCTAssertNotNil(people[0].dog) XCTAssertNotNil(people[0].cat) XCTAssertEqual(people[0].dog.label, "Lucy") XCTAssertEqual(people[0].cat.label, "Ollie") } func testOrderByDifferentTable(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let d2 = Dog() d2.label = "Ollie" let p1 = People() p1.label = "Foo" p1.dog = d1 let p2 = People() p2.label = "Bar" p2.dog = d2 session.add(p1) session.add(p2) let people = session .query(People) .selectRelated("dog") .orderBy("dog.label", ascending: false) .all() XCTAssertEqual(people.count, 2) XCTAssertEqual(people[0].id, 2) XCTAssertEqual(people[0].dog.label, "Ollie") } func testFilterBy(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let d2 = Dog() d2.label = "Ollie" let p1 = People() p1.label = "Foo" p1.dog = d1 let p2 = People() p2.label = "Bar" p2.dog = d2 session.add(p1) session.add(p2) let people = session .query(People) .filter("label = 'Foo'") .all() XCTAssertEqual(people.count, 1) XCTAssertEqual(people[0].id, 1) } func testFilterByDifferentTable(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let d2 = Dog() d2.label = "Ollie" let p1 = People() p1.label = "Foo" p1.dog = d1 let p2 = People() p2.label = "Bar" p2.dog = d2 session.add(p1) session.add(p2) let people = session .query(People) .selectRelated("dog") .orderBy("dog.label", ascending: false) .filter("dog.label = \"Lucy\"") .all() XCTAssertEqual(people.count, 1) XCTAssertEqual(people[0].id, 1) XCTAssertEqual(people[0].dog.label, "Lucy") } func testOrderBySameTable(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let d2 = Dog() d2.label = "Ollie" session.add(d1) session.add(d2) var dogs = session .query(Dog) .orderBy("label", ascending: false) .all() XCTAssertEqual(dogs.count, 2) XCTAssertEqual(dogs[0].id, 2) XCTAssertEqual(dogs[0].label, "Ollie") dogs = session .query(Dog) .orderBy("label") .all() XCTAssertEqual(dogs.count, 2) XCTAssertEqual(dogs[0].id, 1) XCTAssertEqual(dogs[0].label, "Lucy") } func testForeignKeyAutoSave(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let p1 = People() p1.label = "Ollie Cat" p1.dog = d1 var candidate = session.query(Dog).get(1) XCTAssertNil(candidate) session.add(p1) candidate = session.query(Dog).get(1) XCTAssertNotNil(candidate) } func testSelectRelated(){ let session = amigo.session let d1 = Dog() d1.label = "Lucy" let p1 = People() p1.label = "Ollie Cat" p1.dog = d1 session.add(p1) var person = session.query(People).get(1)! XCTAssertNil(person.dog) person = session .query(People) .selectRelated("dog") .get(1)! XCTAssertNotNil(person.dog) XCTAssertEqual(person.dog.label, "Lucy") } func testLimit(){ let session = amigo.session let a1 = Author() a1.firstName = "Lucy" a1.lastName = "Dog" let a2 = Author() a2.firstName = "Ollie" a2.lastName = "Cat" session.add(a1) session.add(a2) let authors = session .query(Author) .limit(1) .all() XCTAssertEqual(authors.count, 1) XCTAssertEqual(authors[0].firstName, "Lucy") XCTAssertEqual(authors[0].lastName, "Dog") } func testOffset(){ let session = amigo.session let a1 = Author() a1.firstName = "Lucy" a1.lastName = "Dog" let a2 = Author() a2.firstName = "Ollie" a2.lastName = "Cat" session.add(a1) session.add(a2) let authors = session .query(Author) .limit(1) .offset(1) .all() XCTAssertEqual(authors.count, 1) XCTAssertEqual(authors[0].firstName, "Ollie") XCTAssertEqual(authors[0].lastName, "Cat") } func testOneToMany(){ let session = amigo.session let a1 = Author() a1.firstName = "Lucy" a1.lastName = "Dog" let a2 = Author() a2.firstName = "Ollie" a2.lastName = "Cat" let p1 = Post() p1.title = "The Story of Barking" p1.author = a1 let p2 = Post() p2.title = "10 Things You Should Know When Chasing Squirrels" p2.author = a1 let p3 = Post() p3.title = "The Story of Being a Cat" p3.author = a2 session.add(a1) session.add(a2) session.add(p1) session.add(p2) session.add(p3) let posts = session.query(Post) .using(a1) .relationship("posts") .all() XCTAssertEqual(posts.count, 2) } }
mit
0f1e1b9f05ef35a0721729467d7ee0ae
20.334459
69
0.506097
3.785971
false
false
false
false
eguchi-t/Zip
Zip/QuickZip.swift
1
3534
// // QuickZip.swift // Zip // // Created by Roy Marmelstein on 16/01/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation extension Zip { // MARK: Quick Unzip /** Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name. - parameter path: Path of zipped file. NSURL. - throws: Error if unzipping fails or if file is not found. Can be printed with a description variable. - returns: NSURL of the destination folder. */ public class func quickUnzipFile(path: NSURL) throws -> NSURL { return try quickUnzipFile(path, progress: nil) } /** Quick unzip a file. Unzips to a new folder inside the app's documents folder with the zip file's name. - parameter path: Path of zipped file. NSURL. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if unzipping fails or if file is not found. Can be printed with a description variable. - notes: Supports implicit progress composition - returns: NSURL of the destination folder. */ public class func quickUnzipFile(path: NSURL, progress: ((progress: Double) -> Void)?) throws -> NSURL { let fileManager = NSFileManager.defaultManager() guard let fileExtension = path.pathExtension, let fileName = path.lastPathComponent else { throw ZipError.UnzipFail } let directoryName = fileName.stringByReplacingOccurrencesOfString(".\(fileExtension)", withString: "") let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let destinationUrl = documentsUrl.URLByAppendingPathComponent(directoryName, isDirectory: true) try self.unzipFile(path, destination: destinationUrl!, overwrite: true, password: nil, progress: progress) return destinationUrl! } // MARK: Quick Zip /** Quick zip files. - parameter paths: Array of NSURL filepaths. - parameter fileName: File name for the resulting zip file. - throws: Error if zipping fails. - notes: Supports implicit progress composition - returns: NSURL of the destination folder. */ public class func quickZipFiles(paths: [NSURL], fileName: String) throws -> NSURL { return try quickZipFiles(paths, fileName: fileName, progress: nil) } /** Quick zip files. - parameter paths: Array of NSURL filepaths. - parameter fileName: File name for the resulting zip file. - parameter progress: A progress closure called after unzipping each file in the archive. Double value betweem 0 and 1. - throws: Error if zipping fails. - notes: Supports implicit progress composition - returns: NSURL of the destination folder. */ public class func quickZipFiles(paths: [NSURL], fileName: String, progress: ((progress: Double) -> Void)?) throws -> NSURL { let fileManager = NSFileManager.defaultManager() let documentsUrl = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL let destinationUrl = documentsUrl.URLByAppendingPathComponent("\(fileName).zip") try self.zipFiles(paths, zipFilePath: destinationUrl!, password: nil, progress: progress) return destinationUrl! } }
mit
6ab31a866fdc5aeb45b6287e5248b36a
37.402174
128
0.674215
5.039943
false
false
false
false
nbkhope/swift
HackingWithSwift/Project3/Project1/DetailViewController.swift
1
2329
// // DetailViewController.swift // Project3 // // This project extends Project1 by adding social media sharing functionality // // Created by nbkhope on 10/5/15. // Copyright © 2015 nbkdev. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailImageView: UIImageView! var detailItem: String? { /* didSet will be executed any time the property value has been changed */ didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let imageView = self.detailImageView { imageView.image = UIImage(named: detail) // UIView Controller has data member: // public var title: String? self.title = "Viewing " + detail //self.title = "Viewing " + self.detailItem // Use ! to unwrap optional (we are sure there will be value assigned to detailItem) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() // For the share button on the top-right corner navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "shareTapped") } /** * Add the following two methods to add hide menu functionality */ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.hidesBarsOnTap = true /** * All view controllers have an optional property called * navigationController, which, if set, lets us reference the * navigation controller we are inside. */ } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.hidesBarsOnTap = false } func shareTapped() { // arguments are: 1) array of items you want to share and 2) an array of any // of your own app's services you want to make sure are in the list let vc = UIActivityViewController(activityItems: [detailImageView.image!], applicationActivities: []) presentViewController(vc, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-2.0
38cde2bca00fa32e45f3eb22329c0422
27.048193
120
0.713488
4.225045
false
false
false
false
zerozheng/zhibo
Source/DataLayer/AFM0Encoder.swift
1
5937
// // AFM0Encoder.swift // zhiboApp // // Created by zero on 17/3/10. // Copyright © 2017年 zero. All rights reserved. // import Foundation public protocol AFM0Encoder { func append(to data: inout Data) throws -> Void } extension String: AFM0Encoder { public func append(to data: inout Data) throws { let count: Int64 = Int64(self.utf8.count) if count <= 0xFFFF { data.append(AFM0DataType.string.rawValue) let rawPointer = UnsafeMutableRawPointer.allocate(bytes: 2, alignedTo: MemoryLayout<UInt8>.alignment) rawPointer.storeBytes(of: UInt16(count), as: UInt16.self) defer { rawPointer.deallocate(bytes: 2, alignedTo: MemoryLayout<UInt8>.alignment) } data.append(Data(bytes: rawPointer, count: 2)) self.utf8.forEach{ data.append($0) } }else if count <= 0xFFFFFFFF { data.append(AFM0DataType.longString.rawValue) let rawPointer = UnsafeMutableRawPointer.allocate(bytes: 4, alignedTo: MemoryLayout<UInt8>.alignment) rawPointer.storeBytes(of: UInt32(count), as: UInt32.self) defer { rawPointer.deallocate(bytes: 4, alignedTo: MemoryLayout<UInt8>.alignment) } data.append(Data(bytes: rawPointer, count: 4)) self.utf8.forEach{ data.append($0) } }else{ throw RTMPError.afm0EncodeError(reason: .stringOutOfSize) //throw "the string encoder with AFM0 is more than 0xFFFFFFFF" } } } extension Double: AFM0Encoder { public func append(to data: inout Data) throws { data.append(AFM0DataType.number.rawValue) let rawPointer = UnsafeMutableRawPointer.allocate(bytes: 8, alignedTo: MemoryLayout<UInt8>.alignment) rawPointer.storeBytes(of: CFConvertDoubleHostToSwapped(self).v, as: UInt64.self) defer { rawPointer.deallocate(bytes: 8, alignedTo: MemoryLayout<UInt8>.alignment) } data.append(Data(bytes: rawPointer, count: 8)) } } extension Float: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Int: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension UInt: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Int64: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension UInt64: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Int32: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension UInt32: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Int16: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension UInt16: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Int8: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension UInt8: AFM0Encoder { public func append(to data: inout Data) throws { do { try Double(self).append(to: &data) } catch let error { throw error } } } extension Bool: AFM0Encoder { public func append(to data: inout Data) throws { data.append(AFM0DataType.boolean.rawValue) if self == true { data.append(0) }else{ data.append(1) } } } extension Sequence where Iterator.Element == (key: String, value: AFM0Encoder) { public func append(to data: inout Data) throws { data.append(AFM0DataType.object.rawValue) if self.underestimatedCount == 0 { return } for (key, value) in self { //write the key let count: Int64 = Int64(key.utf8.count) if count <= 0xFFFF { let rawPointer = UnsafeMutableRawPointer.allocate(bytes: 2, alignedTo: MemoryLayout<UInt8>.alignment) rawPointer.storeBytes(of: UInt16(count), as: UInt16.self) defer { rawPointer.deallocate(bytes: 2, alignedTo: MemoryLayout<UInt8>.alignment) } data.append(Data(bytes: rawPointer, count: 2)) key.utf8.forEach{ data.append($0) } }else{ throw RTMPError.afm0EncodeError(reason: .stringOutOfSize) } //write the value do { try value.append(to: &data) }catch let error { throw error } } data.append(0x00) data.append(0x00) data.append(AFM0DataType.objectEnd.rawValue) } }
mit
6564bc241d6bd1f3eadd31898c0f04d3
27.123223
117
0.56724
4.115118
false
false
false
false
nguyenantinhbk77/practice-swift
CoreData/SuperDB/SuperDB/AppDelegate.swift
2
6275
// // AppDelegate.swift // SuperDB // // Created by Domenico on 30/05/15. // License MIT // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.domenicosolazzo.swift.SuperDB" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SuperDB", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SuperDB.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." // Migration options var options = [ NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true ] if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
95a36468f5fa2acae78e50565b0931c9
53.094828
290
0.713307
5.820965
false
false
false
false
JustOneLastDance/SpeechSounds
SoundsToText/SoundsToText/ViewController.swift
1
6341
// // ViewController.swift // SoundsToText // // Created by JustinChou on 16/10/25. // Copyright © 2016年 JustinChou. All rights reserved. // /* 1. 苹果公司对每个设备的识别功能都有一定的限制,可咨询苹果公司 2. 苹果公司对每个app也有识别功能限制 3. 如果经常遇到限制,请一定联系苹果公司,他们可以提供解决方案 4. 语音识别会很耗电以及会使用很多数据 5. 语音识别一次只持续大概一分钟的时间 */ import UIKit import Speech class ViewController: UIViewController, SFSpeechRecognizerDelegate { @IBOutlet weak var textView: UITextView! @IBOutlet weak var microphoneButton: UIButton! let speechRecognizer = SFSpeechRecognizer(locale: Locale.init(identifier: "en-US")) /// 处理语音识别请求 var recognitionRequest: SFSpeechAudioBufferRecognitionRequest? /// 输出语音识别对象的结果 var recognitionTask: SFSpeechRecognitionTask? /// 语音引擎,负责提供语音输入 let audioEngine = AVAudioEngine() override func viewDidLoad() { super.viewDidLoad() microphoneButton.isEnabled = false speechRecognizer?.delegate = self SFSpeechRecognizer.requestAuthorization { (authStatus) in var isButtonEnabled = false switch authStatus { case .authorized: isButtonEnabled = true case .denied: isButtonEnabled = false print("User denied access to speech recognition") case .restricted: isButtonEnabled = false print("Speech recognition restricted on this device") case .notDetermined: isButtonEnabled = false print("Speech recognition not yet authorized") } OperationQueue.main.addOperation { self.microphoneButton.isEnabled = isButtonEnabled } } } } extension ViewController { func startRecording() { // 检查 recognitionTask 是否在运行,若在则取消任务 if recognitionTask != nil { recognitionTask?.cancel() recognitionTask = nil } // 创建一个 AVAudioSession 对象来记录语音 设置属性时会抛出一场 因此需要放进 try-catch 语句中 let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryRecord) try audioSession.setMode(AVAudioSessionModeMeasurement) try audioSession.setActive(true, with: .notifyOthersOnDeactivation) } catch { print("audioSession properties weren't set because of an error.") } // 实例化 recognitionRequest 之后需要使用它把语音数据传到苹果后台 recognitionRequest = SFSpeechAudioBufferRecognitionRequest() // 检查 audioEngine 是否有录音功能的语音输入 guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } // 检查 recognitionRequest 是否初始化完毕 guard let recognitionRequest = recognitionRequest else { fatalError("Unable to create an SFSpeechAudioBufferRecognitionRequest object") } // 当用户说话的时候,让recognitionRequest 输出部分语音识别的结果 recognitionRequest.shouldReportPartialResults = true; // 调用 speechRecognizer 的 recognitionTask 方式来开启语音识别 // 有个完成回调 每次会在识别引擎收到输入的时候,完善了当前识别的信息时候,或者被删除或者停止的时候被调用,最后会返回一个最终的文本 recognitionTask = speechRecognizer?.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in var isFinal = false if result != nil { // 如果 result 不是 nil,那么就将语音识别的最优结果输出,设置 isFinal 为 true self.textView.text = result?.bestTranscription.formattedString isFinal = (result?.isFinal)! } if error != nil || isFinal { self.audioEngine.stop() inputNode.removeTap(onBus: 0) // 如果没有错误,或者结果时最终结果的话,停止request&task, 同时使识别按钮生效 self.recognitionRequest = nil self.recognitionTask = nil self.microphoneButton.isEnabled = true } }) // 向 recognitionRequest 增加一个语音输入 // **在开始的 recognitionTask 之后增加语音输入是可行的** // Speech Framework 会在语音输入被加入的同时就开始进行语音识别 let recordingFormat = inputNode.outputFormat(forBus: 0) inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer, when) in self.recognitionRequest?.append(buffer) } // 准备并且开始 audioEngine audioEngine.prepare() do { try audioEngine.start() } catch { print("audioEngine couldn't start because of an error.") } textView.text = "Say Something, I'm listening!" } func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) { if available { microphoneButton.isEnabled = true } else { microphoneButton.isEnabled = false } } @IBAction func microphoneTapped(_ sender: AnyObject) { print("click the button") if audioEngine.isRunning { audioEngine.stop() recognitionRequest?.endAudio() microphoneButton.isEnabled = false microphoneButton.setTitle("Start Recording", for: .normal) } else { startRecording() microphoneButton.setTitle("Stop Recording", for: .normal) } } }
mit
d9b58db2cf18a2be36411f1e42bafb2a
31.023392
121
0.604456
5.27553
false
false
false
false
hfutrell/BezierKit
BezierKit/Library/Draw.swift
1
11230
// // Draw.swift // BezierKit // // Created by Holmes Futrell on 10/29/16. // Copyright © 2016 Holmes Futrell. All rights reserved. // #if canImport(CoreGraphics) #if os(macOS) import AppKit #elseif os(iOS) import UIKit #endif // should Draw just be an extension of CGContext, or have a CGContext instead of passing it in to all these functions? public class Draw { private static let deviceColorspace = CGColorSpaceCreateDeviceRGB() // MARK: - helpers private static func Color(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> CGColor { // have to use this initializer because simpler one is MacOS 10.5+ (not iOS) return CGColor(colorSpace: Draw.deviceColorspace, components: [red, green, blue, alpha])! } /** * HSL to RGB converter. * Adapted from: https://github.com/alessani/ColorConverter */ internal static func HSLToRGB(h: CGFloat, s: CGFloat, l: CGFloat) -> (r: CGFloat, g: CGFloat, b: CGFloat) { // Check for saturation. If there isn't any just return the luminance value for each, which results in gray. if s == 0.0 { return (r: l, g: l, b: l) } var temp1, temp2: CGFloat var temp: [CGFloat] = [0, 0, 0] // Test for luminance and compute temporary values based on luminance and saturation if l < 0.5 { temp2 = l * (1.0 + s) } else { temp2 = l + s - l * s } temp1 = 2.0 * l - temp2 // Compute intermediate values based on hue temp[0] = h + 1.0 / 3.0 temp[1] = h temp[2] = h - 1.0 / 3.0 for i in 0..<3 { // Adjust the range if temp[i] < 0.0 { temp[i] += 1.0 } else if temp[i] > 1.0 { temp[i] -= 1.0 } if (6.0 * temp[i]) < 1.0 { temp[i] = temp1 + (temp2 - temp1) * 6.0 * temp[i] } else if (2.0 * temp[i]) < 1.0 { temp[i] = temp2 } else if (3.0 * temp[i]) < 2.0 { temp[i] = temp1 + (temp2 - temp1) * ((2.0 / 3.0) - temp[i]) * 6.0 } else { temp[i] = temp1 } } // Assign temporary values to R, G, B return (r: temp[0], g: temp[1], b: temp[2]) } // MARK: - some useful hard-coded colors public static let lightGrey = Draw.Color(red: 211.0 / 255.0, green: 211.0 / 255.0, blue: 211.0 / 255.0, alpha: 1.0) public static let black = Draw.Color(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) public static let red = Draw.Color(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0) public static let pinkish = Draw.Color(red: 1.0, green: 100.0 / 255.0, blue: 100.0 / 255.0, alpha: 1.0) public static let transparentBlue = Draw.Color(red: 0.0, green: 0.0, blue: 1.0, alpha: 0.3) public static let transparentBlack = Draw.Color(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.2) public static let blue = Draw.Color(red: 0.0, green: 0.0, blue: 255.0, alpha: 1.0) public static let green = Draw.Color(red: 0.0, green: 255.0, blue: 0.0, alpha: 1.0) private static var randomIndex = 0 private static let randomColors: [CGColor] = { var temp: [CGColor] = [] for i in 0..<360 { var j = (i*47) % 360 let (r, g, b) = HSLToRGB(h: CGFloat(j) / 360.0, s: 0.5, l: 0.5) temp.append(Draw.Color(red: r, green: g, blue: b, alpha: 1.0)) } return temp }() // MARK: - public static func reset(_ context: CGContext) { context.setStrokeColor(black) randomIndex = 0 } // MARK: - setting colors public static func setRandomColor(_ context: CGContext) { randomIndex = (randomIndex+1) % randomColors.count let c = randomColors[randomIndex] context.setStrokeColor(c) } public static func setRandomFill(_ context: CGContext, alpha a: CGFloat = 1.0) { randomIndex = (randomIndex+1) % randomColors.count let c = randomColors[randomIndex] let c2 = c.copy(alpha: a) context.setFillColor(c2!) } public static func setColor(_ context: CGContext, color: CGColor) { context.setStrokeColor(color) } // MARK: - drawing various geometry public static func drawCurve(_ context: CGContext, curve: BezierCurve, offset: CGPoint=CGPoint.zero) { context.beginPath() if let quadraticCurve = curve as? QuadraticCurve { context.move(to: quadraticCurve.p0 + offset) context.addQuadCurve(to: quadraticCurve.p2 + offset, control: quadraticCurve.p1 + offset) } else if let cubicCurve = curve as? CubicCurve { context.move(to: cubicCurve.p0 + offset) context.addCurve(to: cubicCurve.p3 + offset, control1: cubicCurve.p1 + offset, control2: cubicCurve.p2 + offset) } else if let lineSegment = curve as? LineSegment { context.move(to: lineSegment.p0 + offset) context.addLine(to: lineSegment.p1 + offset) } else { fatalError("unsupported curve type") } context.strokePath() } public static func drawCircle(_ context: CGContext, center: CGPoint, radius r: CGFloat, offset: CGPoint = .zero) { context.beginPath() context.addEllipse(in: CGRect(origin: CGPoint(x: center.x - r + offset.x, y: center.y - r + offset.y), size: CGSize(width: 2.0 * r, height: 2.0 * r)) ) context.strokePath() } public static func drawPoint(_ context: CGContext, origin o: CGPoint, offset: CGPoint = .zero) { self.drawCircle(context, center: o, radius: 5.0, offset: offset) } public static func drawPoints(_ context: CGContext, points: [CGPoint], offset: CGPoint=CGPoint(x: 0.0, y: 0.0)) { for p in points { self.drawCircle(context, center: p, radius: 3.0, offset: offset) } } public static func drawLine(_ context: CGContext, from p0: CGPoint, to p1: CGPoint, offset: CGPoint=CGPoint(x: 0.0, y: 0.0)) { context.beginPath() context.move(to: p0 + offset) context.addLine(to: p1 + offset) context.strokePath() } public static func drawText(_ context: CGContext, text: String, offset: CGPoint = .zero) { #if os(macOS) (text as NSString).draw(at: NSPoint(x: offset.x, y: offset.y), withAttributes: [:]) #else (text as NSString).draw(at: CGPoint(x: offset.x, y: offset.y), withAttributes: [:]) #endif } public static func drawSkeleton(_ context: CGContext, curve: BezierCurve, offset: CGPoint=CGPoint(x: 0.0, y: 0.0), coords: Bool=true) { context.setStrokeColor(lightGrey) if let cubicCurve = curve as? CubicCurve { self.drawLine(context, from: cubicCurve.p0, to: cubicCurve.p1, offset: offset) self.drawLine(context, from: cubicCurve.p2, to: cubicCurve.p3, offset: offset) } else if let quadraticCurve = curve as? QuadraticCurve { self.drawLine(context, from: quadraticCurve.p0, to: quadraticCurve.p1, offset: offset) self.drawLine(context, from: quadraticCurve.p1, to: quadraticCurve.p2, offset: offset) } if coords == true { context.setStrokeColor(black) self.drawPoints(context, points: curve.points, offset: offset) } } public static func drawHull(_ context: CGContext, hull: [CGPoint], offset: CGPoint = .zero) { context.beginPath() if hull.count == 6 { context.move(to: hull[0]) context.addLine(to: hull[1]) context.addLine(to: hull[2]) context.move(to: hull[3]) context.addLine(to: hull[4]) } else { context.move(to: hull[0]) context.addLine(to: hull[1]) context.addLine(to: hull[2]) context.addLine(to: hull[3]) context.move(to: hull[4]) context.addLine(to: hull[5]) context.addLine(to: hull[6]) context.move(to: hull[7]) context.addLine(to: hull[8]) } context.strokePath() } public static func drawBoundingBox(_ context: CGContext, boundingBox: BoundingBox, offset: CGPoint = .zero) { context.beginPath() context.addRect(boundingBox.cgRect.offsetBy(dx: offset.x, dy: offset.y)) context.closePath() context.strokePath() } public static func drawShape(_ context: CGContext, shape: Shape, offset: CGPoint = .zero) { let order = shape.forward.points.count - 1 context.beginPath() context.move(to: offset + shape.startcap.curve.startingPoint) context.addLine(to: offset + shape.startcap.curve.endingPoint) if order == 3 { context.addCurve(to: offset + shape.forward.points[3], control1: offset + shape.forward.points[1], control2: offset + shape.forward.points[2] ) } else { context.addQuadCurve(to: offset + shape.forward.points[2], control: offset + shape.forward.points[1] ) } context.addLine(to: offset + shape.endcap.curve.endingPoint) if order == 3 { context.addCurve(to: offset + shape.back.points[3], control1: offset + shape.back.points[1], control2: offset + shape.back.points[2] ) } else { context.addQuadCurve(to: offset + shape.back.points[2], control: offset + shape.back.points[1] ) } context.closePath() context.drawPath(using: .fillStroke) } public static func drawPathComponent(_ context: CGContext, pathComponent: PathComponent, offset: CGPoint = .zero, includeBoundingVolumeHierarchy: Bool = false) { if includeBoundingVolumeHierarchy { pathComponent.bvh.visit { node, depth in setColor(context, color: randomColors[depth]) context.setLineWidth(1.0) context.setLineWidth(5.0 / CGFloat(depth+1)) context.setAlpha(1.0 / CGFloat(depth+1)) drawBoundingBox(context, boundingBox: node.boundingBox, offset: offset) return true // always visit children } } Draw.setRandomFill(context, alpha: 0.2) context.addPath(Path(components: [pathComponent]).cgPath) context.drawPath(using: .fillStroke) } public static func drawPath(_ context: CGContext, _ path: Path, offset: CGPoint = .zero) { Draw.setRandomFill(context, alpha: 0.2) context.addPath(path.cgPath) context.drawPath(using: .fillStroke) } } #endif
mit
0a339de282170dccd6b730942bfb592a
37.72069
165
0.562828
3.934478
false
false
false
false
v-andr/LakestoneCore
Source/Directory.swift
1
10023
// // Directory.swift // LakestoneCore // // Created by Taras Vozniuk on 9/29/16. // Copyright © 2016 GeoThings. All rights reserved. // // -------------------------------------------------------- // // 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. // #if COOPER #else import Foundation #if os(OSX) || os(Linux) import PerfectThread #endif #endif public class Directory: AnyFileOrDirectory { #if COOPER private let _fileEntity: File #else public let path: String #endif public init(path: String){ #if COOPER _fileEntity = File(path: path) #else self.path = path #endif } public init(directoryURL: URL){ #if COOPER _fileEntity = File(fileURL: directoryURL) #else self.path = directoryURL.path #endif } #if COOPER public var path: String { return _fileEntity.path } public var exists: Bool { return _fileEntity.exists } public var isDirectory: Bool { return _fileEntity.isDirectory } public var lastModificationDateº: Date? { return _fileEntity.lastModificationDateº } #endif public var url: URL { return URL(fileURLWithPath: self.path) } public var name: String { #if COOPER return _fileEntity.getName() #else return self.url.lastPathComponent #endif } public var size: Int64 { var accumulativeSize: Int64 = 0 for entity in self.filesAndSubdirectories { accumulativeSize += entity.size } return accumulativeSize } public func getSize(completionHandler: @escaping (Int64) -> Void){ let sizeRetrievalQueue = Threading.serialQueue(withLabel: "lakestone.core.size-retrieval-queue") sizeRetrievalQueue.dispatch { let targetSize = self.size completionHandler(targetSize) } } /// Creates a directory corresponfing to current Directory object /// - Throws: Creation error public func create() throws { #if COOPER if (!_fileEntity.mkdir()){ throw Error.CreationFailed } #else return try FileManager.default.createDirectory(atPath: self.path, withIntermediateDirectories: false, attributes: nil) #endif } /// Creates a new directory within the given one /// - Parameters: /// - named: Subdirectory name /// - Throws: Creation error /// - Returns: Subdirectory object public func createSubdirectory(named: String) throws -> Directory { let subdirectory = Directory(directoryURL: self.url.appendingPathComponent(named)) try subdirectory.create() return subdirectory } public var filesAndSubdirectories: [AnyFileOrDirectory] { #if COOPER let names = [String](_fileEntity.list()) #else guard let names = try? FileManager.default.contentsOfDirectory(atPath: self.path) else { return [] } #endif return [AnyFileOrDirectory](names.map { self.url.appendingPathComponent($0) } .map { FileOrDirectory(with: $0) }) } public var files: [File] { return [File](self.filesAndSubdirectories.filter { !$0.isDirectory }.map { File(path: $0.path) }) } public var subdirectories: [Directory] { return [Directory](self.filesAndSubdirectories.filter { $0.isDirectory }.map { Directory(path: $0.path) }) } /// Removes the target with all files and subdirectories /// - Throws: remove error public func remove() throws { for entity in self.filesAndSubdirectories { try entity.remove() } #if COOPER try _fileEntity.remove() #else try FileManager.default.removeItem(atPath: self.path) #endif } /// Asynchronous calling of remove function public func remove(completionHandler: @escaping (ThrowableError?) -> Void){ let deletionQueue = Threading.serialQueue(withLabel: "lakestone.core.file-deletion-queue") deletionQueue.dispatch { do { try self.remove() completionHandler(nil) } catch { // in Java silver error has Object type, so conditionals to avoid warning for redundant as! in Swift #if COOPER completionHandler(error as! ThrowableError) #else completionHandler(error) #endif } } } /// - Returns: nil if already at root directory or Directory object based on target's url without ending public var parentDirectoryº: Directory? { return (self.path == "/") ? nil : Directory(directoryURL: self.url.deletingLastPathComponent()) } /// Copies the current folder with all files and subfolders into a new folder location /// - Parameters: /// - destination: Parent directory for new target folder location /// - overwrites: True to overwrite or false to throw exception if any file exists at the new location /// - Throws: Error occurs when the destination doesn't exist or is not a folder; /// when the new folder cannot be created at the new location; /// when copying or overwriting fails /// - Returns: The new folder location as AnyFileOrDirectory /// - Note: recursively copies all subfolders, thus may take long time to complete public func copy(to destination: AnyFileOrDirectory, overwrites: Bool) throws -> AnyFileOrDirectory { var destinationFolder: Directory if destination.isDirectory { destinationFolder = Directory (directoryURL: destination.url) } else { throw Error.WrongDestination } // create new subdirectory if necessary let copyDirectory = Directory(directoryURL: destinationFolder.url.appendingPathComponent(self.name)) if (!copyDirectory.exists) { try copyDirectory.create() } for entity in self.filesAndSubdirectories { #if COOPER if (entity.isDirectory){ _ = try Directory(path: entity.path).copy(to: copyDirectory, overwrites: overwrites) } else { _ = try File(path: entity.path).copy(to: copyDirectory, overwrites: overwrites) } #else _ = try entity.copy(to: copyDirectory, overwrites: overwrites) #endif } return copyDirectory } /// Asynchronous calling of copy function public func copy(to destination: AnyFileOrDirectory, overwrites: Bool, completionHandler: @escaping (ThrowableError?, AnyFileOrDirectory?) -> Void){ let copyQueue = Threading.serialQueue(withLabel: "lakestone.core.filedir-copy-queue") copyQueue.dispatch { do { let copyDirectory = try self.copy(to: destination, overwrites: overwrites) completionHandler(nil, copyDirectory) } catch { // in Java silver error has Object type, so conditionals to avoid warning for redundant as! in Swift #if COOPER completionHandler(error as! ThrowableError, nil) #else completionHandler(error, nil) #endif } } } /// Moves the current folder with all files and subfolders into a new folder location by copying and then removing original /// - Parameters: /// - destination: Parent directory for new target folder location /// - overwrites: True to overwrite or false to throw exception if any file exists at the new location /// - Throws: Error occurs when the destination doesn't exist or is not a folder; /// when the new folder cannot be created at the new location; /// when copying, overwriting or deletion fails /// - Returns: The new folder location as AnyFileOrDirectory /// - Note: recursively moves all subfolders, thus may take long time to complete public func move(to destination: AnyFileOrDirectory, overwrites: Bool) throws -> AnyFileOrDirectory { let destinationFolder = try self.copy(to: destination, overwrites: overwrites) if self.exists { try self.remove() } return destinationFolder } /// Asynchronous calling of move function public func move(to destination: AnyFileOrDirectory, overwrites: Bool, completionHandler: @escaping (ThrowableError?, AnyFileOrDirectory?) -> Void){ let moveQueue = Threading.serialQueue(withLabel: "lakestone.core.filedir-move-queue") moveQueue.dispatch { do { let destinationFolder = try self.move(to: destination, overwrites: overwrites) completionHandler(nil, destinationFolder) } catch { // in Java silver error has Object type, so conditionals to avoid warning for redundant as! in Swift #if COOPER completionHandler(error as! ThrowableError, nil) #else completionHandler(error, nil) #endif } } } } extension Directory: CustomStringConvertible { public var description: String { return self.path } } extension Directory { //prevent name collision with Foundation.Error that is used in remove(completionHandler:) public class Error { static let CreationFailed = LakestoneError.with(stringRepresentation: "Directory creation failed") static let DeletionFailed = LakestoneError.with(stringRepresentation: "Directory deletion failed") static let WrongDestination = LakestoneError.with(stringRepresentation: "Provided destination is not a folder or doesn't exist") public static let OverwriteFailed = LakestoneError.with(stringRepresentation: "File(s) already exists. You need to explicitly allow overwriting, if desired.") } } extension Directory: Equatable { #if COOPER public override func equals(_ o: Object!) -> Bool { guard let other = o as? Self else { return false } return (self == other) } #endif } public func ==(lhs: Directory, rhs: Directory) -> Bool { return lhs.path == rhs.path }
apache-2.0
6a208ae43b92e97a94aa6b1a80250921
31.003195
160
0.687831
4.293613
false
false
false
false
carsonmcdonald/HealthkitFBSync
HealthkitSync/FBWeightData.swift
1
2001
import Foundation class FBWeightData: NSObject { var bmi: Float = 0.0 var dateTime: NSDate! var fat: Float = 0.0 var logId: Int = 0 var weightInKilograms: Float = 0.0 override var description : String { return "{bmi=\(bmi),dateTime=\(dateTime),fat=\(fat),logId=\(logId),weight=\(weightInKilograms)}" } class func parseWeightData(weightWrapperDict: AnyObject!) -> [FBWeightData] { var parsedWeightList = [FBWeightData]() if let weightArray = weightWrapperDict["weight"] as? NSArray { for weightDict in weightArray { let weightEntry = FBWeightData() if let bmi = weightDict["bmi"] as? Float { weightEntry.bmi = bmi } if let fat = weightDict["fat"] as? Float { weightEntry.fat = fat } if let weight = weightDict["weight"] as? Float { weightEntry.weightInKilograms = weight } if let logId = weightDict["logId"] as? Int { weightEntry.logId = logId } if let date = weightDict["date"] as? String { if let time = weightDict["time"] as? String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" weightEntry.dateTime = dateFormatter.dateFromString("\(date) \(time)") } } if weightEntry.dateTime != nil { parsedWeightList.append(weightEntry) } } } parsedWeightList.sortInPlace { $0.dateTime.compare($1.dateTime) == NSComparisonResult.OrderedAscending } return parsedWeightList } }
mit
0d99845273bf1cc75659fbb5d26b6eb6
33.517241
112
0.484258
5.497253
false
false
false
false
michaelgwelch/swift-parsing
ParsingTutorial.playground/Pages/NumericExpressions.xcplaygroundpage/Contents.swift
1
9009
//: [Previous](@previous) import Foundation import SwiftParsing import Darwin //: # Parsing and evaluating expressions //: //: For this example we'll parse the following grammar //: //: //: expr ::= term term_tail //: term_tail ::= plus_op term term_tail //: | sub_op term term_tail //: | epsilon //: term ::= factor factor_tail //: factor_tail ::= mult_op factor factor_tail //: | div_op factor factor_tail //: | epsilon //: factor ::= basic basic_tail //: basic_tail ::= exp_op basic basic_tail //: | epsilon //: basic ::= ( expr ) //: | id //: | literal //: | sub_op expr //: | plus_op expr //: plus_op ::= + //: sub_op ::= - //: mult_op ::= * //: div_op ::= / //: exp_op ::= ^ //: epsilon ::= 𝜖 (Empty string) //: [Next](@next) //: Declare an enum that can store the results of our parsing indirect enum NumericExpression { case Expression(NumericExpression, NumericExpression) case AddTermTail(NumericExpression, NumericExpression) case SubtractTermTail(NumericExpression, NumericExpression) case Term(NumericExpression, NumericExpression) case MultiplyFactorTail(NumericExpression, NumericExpression) case DivideFactorTail(NumericExpression, NumericExpression) case Factor(NumericExpression, NumericExpression) case BasicTail(NumericExpression, NumericExpression) case Paren(NumericExpression) case Identifier(String) case Literal(Int) case Negate(NumericExpression) case Epsilon } //: Declare curried functions for creating NumericExpressions as these work best //: with the applicative operators we'll be using let createExpression = curry(NumericExpression.Expression) let createAdd = curry(NumericExpression.AddTermTail) let createSub = curry(NumericExpression.SubtractTermTail) let createTerm = curry(NumericExpression.Term) let createMult = curry(NumericExpression.MultiplyFactorTail) let createDiv = curry(NumericExpression.DivideFactorTail) let createFactor = curry(NumericExpression.Factor) let createBasic = curry(NumericExpression.BasicTail) var num_expr:ParserOf<NumericExpression>! = nil let expr = Parser.lazy(num_expr) //: Now just start defining parsers for each line of the grammar starting at the bottom let epsilon = Parser.success(NumericExpression.Epsilon) let exp_op = Parser.char("^").token() let div_op = Parser.char("/").token() let mult_op = Parser.char("*").token() let sub_op = Parser.char("-").token() let plus_op = Parser.char("+").token() let lparen = Parser.char("(").token() let rparen = Parser.char(")").token() let unaryPlus = plus_op *> expr let unaryNegate = NumericExpression.Negate <§> (sub_op *> expr) let literal = NumericExpression.Literal <§> Parser.natural let identifier = NumericExpression.Identifier <§> Parser.identifier let paren_expr = NumericExpression.Paren <§> (lparen *> expr) <* rparen let basic = paren_expr <|> identifier <|> literal <|> unaryNegate <|> unaryPlus var basic_tail:ParserOf<NumericExpression>! = nil basic_tail = createBasic <§> (exp_op *> basic) <*> Parser.lazy(basic_tail) <|> epsilon let factor = createFactor <§> basic <*> basic_tail var factor_tail:ParserOf<NumericExpression>! = nil factor_tail = createMult <§> (mult_op *> factor) <*> Parser.lazy(factor_tail) <|> createDiv <§> (div_op *> factor) <*> Parser.lazy(factor_tail) <|> epsilon let term = createTerm <§> factor <*> factor_tail var term_tail:ParserOf<NumericExpression>! = nil term_tail = createAdd <§> (plus_op *> term) <*> Parser.lazy(term_tail) <|> createSub <§> (sub_op *> term) <*> Parser.lazy(term_tail) <|> epsilon num_expr = createExpression <§> term <*> term_tail extension NumericExpression { static func eval(_ expr1:NumericExpression, inExpression expr2:NumericExpression, withStore store:[String:Int]) -> Int? { let e1 = expr1.eval(withMemory:store) return expr2.eval(withLeftHandSide:e1, andMemory:store) } func eval(withMemory store:[String:Int]) -> Int? { switch self { case .Expression(let expr1, let expr2): return NumericExpression.eval(expr1, inExpression: expr2, withStore:store) case .Term(let expr1, let expr2): return NumericExpression.eval(expr1, inExpression: expr2, withStore:store) case .Factor(let expr1, let expr2): return NumericExpression.eval(expr1, inExpression: expr2, withStore:store) case .Paren(let e): return e.eval(withMemory: store) case .Identifier(let id): return store[id] case .Literal(let num): return num case .Negate(let expr): return { -$0 } <§> expr.eval(withMemory: store) case .AddTermTail(_), .SubtractTermTail(_), .MultiplyFactorTail(_), .DivideFactorTail(_), .BasicTail(_), .Epsilon: return nil } } func eval(withLeftHandSide accumulator:Int?, andMemory store:[String:Int]) -> Int? { switch self { case .Expression(_), .Term(_), .Factor(_), .Paren(_), .Identifier, .Literal, .Negate: return nil case .AddTermTail(let expr1, let expr2): let sum:(Int) -> (Int) -> Int = { x in { y in x + y } } return sum <§> accumulator <*> NumericExpression.eval(expr1, inExpression: expr2, withStore: store) case .SubtractTermTail(let expr1, let expr2): let diff:(Int) -> (Int) -> Int = { x in { y in x - y } } return diff <§> accumulator <*> NumericExpression.eval(expr1, inExpression: expr2, withStore: store) case .MultiplyFactorTail(let expr1, let expr2): let product:(Int) -> (Int) -> Int = { x in { y in x * y } } return product <§> accumulator <*> NumericExpression.eval(expr1, inExpression: expr2, withStore: store) case .DivideFactorTail(let expr1, let expr2): let quotient:(Int) -> (Int) -> Int = { x in { y in x / y } } return quotient <§> accumulator <*> NumericExpression.eval(expr1, inExpression: expr2, withStore: store) case .BasicTail(let expr1, let expr2): let exp:(Int) -> (Int) -> Int = { x in { y in Int(pow(Double(x), Double(y))) } } return exp <§> accumulator <*> NumericExpression.eval(expr1, inExpression: expr2, withStore: store) case .Epsilon: return accumulator } } var graph : String { switch self { case .Expression(let e1, let e2): return "Expression(\(e1.graph), \(e2.graph))" case .AddTermTail(let e1, let e2): return "AddTermTail(\(e1.graph), \(e2.graph))" case .SubtractTermTail(let e1, let e2): return "SubtractTermTail(\(e1.graph), \(e2.graph))" case .Term(let e1, let e2): return "Term(\(e1.graph), \(e2.graph))" case .MultiplyFactorTail(let e1, let e2): return "MultiplyFactorTail(\(e1.graph), \(e2.graph))" case .DivideFactorTail(let e1, let e2): return "DivideFactorTail(\(e1.graph), \(e2.graph))" case .Factor(let e1, let e2): return "Factor(\(e1.graph), \(e2.graph))" case .BasicTail(let e1, let e2): return "ExponentOperandTail(\(e1.graph), \(e2.graph))" case .Paren(let e): return "Paren(\(e.graph))" case .Identifier(let s): return "\"\(s)\"" case .Literal(let n): return String(n) case .Negate(let n): return "Negate(\(n))" case .Epsilon: return "𝜖" } } var description : String { switch self { case .Expression(let e1, let e2): return e1.description + e2.description case .AddTermTail(let e1, let e2): return "+" + e1.description + e2.description case .SubtractTermTail(let e1, let e2): return "-" + e1.description + e2.description case .Term(let e1, let e2): return e1.description + e2.description case .MultiplyFactorTail(let e1, let e2): return "*" + e1.description + e2.description case .DivideFactorTail(let e1, let e2): return "/" + e1.description + e2.description case .Factor(let e1, let e2): return e1.description + e2.description case .BasicTail(let e1, let e2): return "^" + e1.description + e2.description case .Paren(let e): return "(\(e.description))" case .Identifier(let s): return s case .Literal(let n): return n.description case .Negate(let e): return "-" + e.description case .Epsilon: return "" } } } let result = num_expr.parse("(8 + 4) * 12")! let parsedExpression = result.token print(parsedExpression.description) print(result.output) print(parsedExpression.graph) NumericExpression.eval <§> parsedExpression <*> [String:Int]()
mit
a7ae49250210a24753a1ff1359fe27df
37.891775
125
0.622551
4.094804
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/Swifter/Sources/SwifterSuggested.swift
2
3061
// // SwifterSuggested.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /** GET users/suggestions/:slug Access the users in a given category of the Twitter suggested user list. It is recommended that applications cache this data for no more than one hour. */ public func getUserSuggestions(slug: String, lang: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions/\(slug).json" var parameters = [String: Any]() parameters["lang"] ??= lang self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/suggestions Access to Twitter's suggested user list. This returns the list of suggested user categories. The category can be used in GET users/suggestions/:slug to get the users in that category. */ public func getUsersSuggestions(lang: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions.json" var parameters = [String: Any]() parameters["lang"] ??= lang self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET users/suggestions/:slug/members Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user. */ public func getUsersSuggestions(for slug: String, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "users/suggestions/\(slug)/members.json" self.getJSON(path: path, baseURL: .api, parameters: [:], success: { json, _ in success?(json) }, failure: failure) } }
mit
1b31a34f8676d1017c309aee6811df98
35.879518
187
0.68017
4.341844
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/CtvCellSettingCheck.swift
1
4454
// // CtvCellSettingCheck.swift // Liplis // //ウィジェット設定画面 要素 チェックボックス // //アップデート履歴 // 2015/05/01 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/01. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class CtvCellSettingCheck : UITableViewCell { ///============================= ///カスタムセル要素 internal var parView : ViewWidgetSetting! ///============================= ///カスタムセル要素 internal var lblTitle = UILabel(); internal var lblContent = UILabel(); internal var btnCheckBox = UIButton(); ///============================= ///レイアウト情報 var viewWidth : CGFloat! = 0 ///============================= ///設定インデックス internal var settingIdx : Int! = 0 ///============================= ///ON/OFF internal var on : Bool! = false //============================================================ // //初期化処理 // //============================================================ internal override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.lblTitle = UILabel(frame: CGRectMake(20, 5, 300, 15)); self.lblTitle.text = ""; self.lblTitle.font = UIFont.systemFontOfSize(20) self.addSubview(self.lblTitle); self.lblContent = UILabel(frame: CGRectMake(20, 24, 300, 15)); self.lblContent.text = ""; self.lblContent.font = UIFont.systemFontOfSize(10) self.addSubview(self.lblContent); //チェックボッックス self.btnCheckBox = UIButton() self.btnCheckBox.titleLabel?.font = UIFont.systemFontOfSize(12) self.btnCheckBox.frame = CGRectMake(0,0,32,32) self.btnCheckBox.layer.masksToBounds = true self.btnCheckBox.setTitle("", forState: UIControlState.Normal) self.btnCheckBox.addTarget(self, action: "onClickCheck:", forControlEvents: .TouchDown) self.btnCheckBox.setImage(UIImage(named: "checkOff.png"), forState: UIControlState.Normal) self.btnCheckBox.layer.cornerRadius = 3.0 self.addSubview(self.btnCheckBox) } /* ビューを設定する */ internal func setView(parView : ViewWidgetSetting) { self.parView = parView } /* 要素の位置を調整する */ internal func setSize(viewWidth : CGFloat) { self.viewWidth = viewWidth let locationY : CGFloat = CGFloat(viewWidth - 50 - 9) self.btnCheckBox.frame = CGRectMake(locationY, 6, 32, 32) } /* 値をセットする */ internal func setVal(settingIdx : Int, val : Int) { self.on = LiplisUtil.int2Bit(val) self.settingIdx = settingIdx if(self.on == true) { let imgOn : UIImage = UIImage(named: "checkOn.png")! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) } else { let imgOff : UIImage = UIImage(named: "checkOff.png")! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //============================================================ // //イベントハンドラ // //============================================================ /* スイッチ選択 */ internal func onClickCheck(sender: UIButton) { if(self.on == true) { print("チェックボックスOFF") let imgOff : UIImage = UIImage(named: "checkOff.png")! self.btnCheckBox.setImage(imgOff, forState: UIControlState.Normal) self.on = false self.parView.selectCheck(self.settingIdx,val: false) } else { print("チェックボックスON") let imgOn : UIImage = UIImage(named: "checkOn.png")! self.btnCheckBox.setImage(imgOn, forState: UIControlState.Normal) self.on = true self.parView.selectCheck(self.settingIdx,val: true) } } }
mit
13210eec908950f7c45cbcb020e90f65
27.737931
98
0.530485
4.399155
false
false
false
false
dritani/Antique-Book-Scan
Antique Book Scan/XMLParser.swift
1
6516
// // XMLParser.swift // CloudSightExample // // Created by Dritani on 2017-03-25. // Copyright © 2017 CloudSight, Inc. All rights reserved. // //<Binding> //Mass Market Paperback //trade paperback //Paperback //Kindle Edition //Hardcover import Foundation protocol VCDelegate { var priceUrl:String? { get set } } class ParseAmazonXML : NSObject, XMLParserDelegate { var parser: XMLParser! var bookResults:[BookResult]? = [] var market:String = "amazon" var price:Float! var condition:String! var buyLink:String? var foundNew:Bool = false var foundUsed:Bool = false var foundURL:Bool = false var get:Bool = false var done:Int = 0 init(data: Data) { super.init() parser = XMLParser(data: data) parser.delegate = self } func execute() { parser.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if elementName == "MoreOffersUrl" { foundURL = true } if elementName == "LowestNewPrice" { foundNew = true } else if elementName == "LowestUsedPrice" { foundUsed = true } if (foundNew == true || foundUsed == true) { if elementName == "FormattedPrice" { get = true } } } func parser(_ parser: XMLParser, foundCharacters string: String) { if foundURL == true { self.buyLink = string foundURL = false done += 1 var newResults:[BookResult]? = [] for bookResult in bookResults! { var newResult = bookResult newResult.buyLink = self.buyLink newResults?.append(newResult) } bookResults = newResults } if get == true { let startIndex = string.index(string.startIndex, offsetBy: 1) let endIndex = string.endIndex let priceString = string[Range(startIndex ..< endIndex)] self.price = Float(priceString) if foundNew == true { condition = "new" print("new price :", price) foundNew = false } else if foundUsed == true { condition = "used" print("used price :", price) foundUsed = false } let newBookResult = BookResult(market: self.market, price: self.price, condition: self.condition, buyLink: self.buyLink) bookResults?.append(newBookResult) done += 1 get = false } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if done == 3 { parser.abortParsing() } } } class ParseEBayXML : NSObject, XMLParserDelegate { var parser: XMLParser! var bookResults:[BookResult]? = [] var market:String = "ebay" var price:Float! var condition:String! var buyLink:String? var foundCondition:Bool = false var foundPrice:Bool = false var foundURL:Bool = false var done:Int = 0 var newDone:Bool = false var usedDone:Bool = false init(data: Data) { super.init() parser = XMLParser(data: data) parser.delegate = self } func execute() { parser.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { if elementName == "viewItemURL" { foundURL = true } if elementName == "conditionId" { foundCondition = true } else if elementName == "currentPrice" { foundPrice = true } } func parser(_ parser: XMLParser, foundCharacters string: String) { if foundURL == true { self.buyLink = string foundURL = false } if (foundCondition == true) { if string == "1000" { self.condition = "new" if !newDone { let bookResult = BookResult(market: self.market, price: self.price, condition: self.condition, buyLink: self.buyLink) bookResults?.append(bookResult) done += 1 newDone = true } } else { self.condition = "used" if !usedDone { let bookResult = BookResult(market: self.market, price: self.price, condition: self.condition, buyLink: self.buyLink) bookResults?.append(bookResult) done += 1 usedDone = true } } foundCondition = false } if (foundPrice == true) { self.price = Float(string) foundPrice = false } } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { if done == 2 { parser.abortParsing() } } } class ParseDTXML : NSObject, XMLParserDelegate { var parser: XMLParser! var priceUrl:String = "" var bookResults:[BookResult]? var foundValidVendor:Bool = false // var market:String // var price:Float // var condition:String // var buyLink:String? init(data: Data) { super.init() parser = XMLParser(data: data) parser.delegate = self } func execute() { parser.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { print(elementName) } func parser(_ parser: XMLParser, foundCharacters string: String) { print(string) } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { print(elementName) } }
mit
aad1e0c9e050ee425ef28c8a1dd53c77
24.15444
173
0.537836
4.984698
false
false
false
false
JunDang/SwiftFoundation
Sources/SwiftFoundation/JSONSerialization.swift
1
2694
// // JSONSerialization.swift // JSONC // // Created by Alsey Coleman Miller on 8/22/15. // Copyright © 2015 PureSwift. All rights reserved. // #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import JSON #elseif os(Linux) import CJSONC #endif public extension JSON.Value { /// Serializes the JSON to a string. /// /// - Precondition: JSON value must be an array or object. /// /// - Note: Uses the [JSON-C](https://github.com/json-c/json-c) library. func toString(options: [JSON.WritingOption] = []) -> Swift.String? { switch self { case .Array(_), .Object(_): break default: return nil } let jsonObject = self.toJSONObject() defer { json_object_put(jsonObject) } let writingFlags = options.optionsBitmask() let stringPointer = json_object_to_json_string_ext(jsonObject, writingFlags) let string = Swift.String.fromCString(stringPointer)! return string } } // MARK: - Private private extension JSON.Value { func toJSONObject() -> COpaquePointer { switch self { case .Null: return nil case .String(let value): return json_object_new_string(value) case .Number(let number): switch number { case .Boolean(let value): let jsonBool: Int32 = { if value { return Int32(1) } else { return Int32(0) } }() return json_object_new_boolean(jsonBool) case .Integer(let value): return json_object_new_int64(Int64(value)) case .Double(let value): return json_object_new_double(value) } case .Array(let arrayValue): let jsonArray = json_object_new_array() for (index, value) in arrayValue.enumerate() { let jsonValue = value.toJSONObject() json_object_array_put_idx(jsonArray, Int32(index), jsonValue) } return jsonArray case .Object(let dictionaryValue): let jsonObject = json_object_new_object() for (key, value) in dictionaryValue { let jsonValue = value.toJSONObject() json_object_object_add(jsonObject, key, jsonValue) } return jsonObject } } }
mit
579641cc06b6259d08af4094c2285fb3
25.93
97
0.497958
4.914234
false
false
false
false
TwoRingSoft/shared-utils
Sources/PippinLibrary/UIKit/UIViewController/BlurViewController.swift
1
2781
// // BlurViewController.swift // Pippin // // Created by Andrew McKnight on 4/25/16. // Copyright © 2016 Two Ring Software. All rights reserved. // import UIKit /// A `UIViewController` subclass that displays a child view controller with an active blur background. public final class BlurViewController: UIViewController { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /// Instantiate a new `BlurViewController` with a child view controller and a blur style. /// /// - Parameters: /// - viewController: the view controller to show with a blur. /// - blurStyle: the type of blur to use. /// /// - Note: `viewController`'s subviews must have transparent background. @available(iOS, deprecated: 13.0, message: "Use init(blurredViewController:material:vibrancyStyle:)") public required init(viewController: UIViewController, blurStyle: UIBlurEffect.Style = .light, vibrancy: Bool = false) { super.init(nibName: nil, bundle: nil) let blurEffect = UIBlurEffect(style: blurStyle) let blurView = UIVisualEffectView(effect: blurEffect) addNewChildViewController(newChildViewController: viewController, containerView: blurView.contentView) viewController.view.fillSuperview() view.addSubview(blurView) blurView.fillSuperview() if vibrancy { let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect) let vibrancyView = UIVisualEffectView(effect: vibrancyEffect) vibrancyView.isUserInteractionEnabled = false blurView.contentView.addSubview(vibrancyView) vibrancyView.fillSuperview() } self.title = viewController.title } @available(iOS 13.0, *) public init(blurredViewController viewController: UIViewController, material: UIBlurEffect.Style = .systemMaterial, vibrancyStyle: UIVibrancyEffectStyle? = nil) { super.init(nibName: nil, bundle: nil) let blurEffect = UIBlurEffect(style: material) let blurView = UIVisualEffectView(effect: blurEffect) addNewChildViewController(newChildViewController: viewController, containerView: blurView.contentView) viewController.view.fillSuperview() view.addSubview(blurView) blurView.fillSuperview() if let vibrancyStyle = vibrancyStyle { let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect, style: vibrancyStyle) let vibrancyView = UIVisualEffectView(effect: vibrancyEffect) vibrancyView.isUserInteractionEnabled = false blurView.contentView.addSubview(vibrancyView) vibrancyView.fillSuperview() } self.title = viewController.title } }
mit
33d8cf2557f944cb76802ea4547a62e1
38.15493
166
0.699281
5.335893
false
false
false
false
cjcaufield/SecretKit
SecretKitTouchTest/MasterViewController.swift
1
3563
// // MasterViewController.swift // SecretKitTouchTest // // Created by Colin Caufield on 2016-02-16. // Copyright © 2016 Secret Geometry, Inc. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(MasterViewController.insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(_ sender: AnyObject) { objects.insert(Date() as AnyObject, at: 0) let indexPath = IndexPath(row: 0, section: 0) self.tableView.insertRows(at: [indexPath], with: .automatic) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let object = objects[(indexPath as IndexPath).row] as! Date let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object as AnyObject? controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let object = objects[(indexPath as IndexPath).row] as! Date cell.textLabel!.text = object.description return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { objects.remove(at: (indexPath as IndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
mit
4f3f5749b4cbc2180de8f275e7f9aa85
36.893617
144
0.681078
5.446483
false
false
false
false
qiscus/qiscus-sdk-ios
Qiscus/Qiscus/Library/QToasterView.swift
1
7542
// // QToasterView.swift // QToasterSwift // // Created by Ahmad Athaullah on 7/3/16. // Copyright © 2016 Ahmad Athaullah. All rights reserved. // import UIKit class QToasterView: UIButton { /** Define toaster to use variable and function on QToasterSwift. */ var toaster = QToasterSwift() /** Define area view to toaster. */ var viewArea = UIView() /** Minimum height for toaster in CGFloat. - returns: Height of status bar + 40 on **QToasterConfig**. */ var minHeight:CGFloat{ return QToasterConfig.statusBarHeight + 40 } /** Your toaster text size in CGSize. This is defined again to distinguish if there is a badge. - returns: Toaster text size consist of toaster text, font and maximum width */ var textSize:CGSize{ if toaster.iconImage == nil && (toaster.iconURL == nil || toaster.iconURL == "") { return QToasterConfig.textSize(text: toaster.text as NSString, font: toaster.textFont, maxWidth: QToasterConfig.screenWidth) }else{ return QToasterConfig.textSize(text: toaster.text as NSString, font: toaster.textFont, maxWidth: QToasterConfig.screenWidth - toaster.iconSquareSize - 25) } } /** Your toaster title size in CGSize. - returns: If toaster title text is nil and blank then toaster text size consist of toaster text, font and maximum width. Otherwise, set CGSizeMake(0, 0) */ var titleSize:CGSize{ if toaster.titleText != nil && toaster.titleText != ""{ if toaster.iconImage == nil && (toaster.iconURL == nil || toaster.iconURL == "") { return QToasterConfig.textSize(text: toaster.titleText! as NSString, font: toaster.textFont, maxWidth: QToasterConfig.screenWidth - 20) }else{ return QToasterConfig.textSize(text: toaster.titleText! as NSString, font: toaster.textFont, maxWidth: QToasterConfig.screenWidth - toaster.iconSquareSize - 25) } }else{ return CGSize(width: 0, height: 0) } } override init(frame: CGRect) { super.init(frame: frame) commonInit() } // The storyboard loader uses this at runtime. required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /** Function will be called on override. It is called whenever creating objects. */ func commonInit(){ self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.tag = 1313 self.layer.zPosition = 9999 } /** To configure toaster view - parameter toaster: QToasterSwift. */ func setupToasterView(toaster: QToasterSwift){ self.toaster = toaster var textAreaWidth = QToasterConfig.screenWidth - 20 var imageToasterHeight:CGFloat = 0 var textXPos:CGFloat = 10 if toaster.iconImage != nil || (toaster.iconURL != nil && toaster.iconURL != ""){ imageToasterHeight = toaster.iconSquareSize + QToasterConfig.statusBarHeight + 20 textAreaWidth -= (toaster.iconSquareSize + 5) toaster.textAlignment = NSTextAlignment.left textXPos += toaster.iconSquareSize + 5 } var toasterHeight = self.textSize.height + self.titleSize.height + QToasterConfig.statusBarHeight + 20 if self.titleSize.height > 0 { toasterHeight += 3 } if toasterHeight < self.minHeight { toasterHeight = self.minHeight } if toasterHeight < imageToasterHeight{ toasterHeight = imageToasterHeight } var yPos:CGFloat = QToasterConfig.statusBarHeight + 10 let toasterViewFrame = CGRect(x: 0, y: 0 - toasterHeight, width: QToasterConfig.screenWidth, height: toasterHeight) viewArea.frame = toasterViewFrame viewArea.isUserInteractionEnabled = false viewArea.backgroundColor = toaster.backgroundColor if toaster.iconImage != nil || (toaster.iconURL != nil && toaster.iconURL != ""){ let iconView = UIImageView(frame: CGRect(x: 10, y: yPos, width: toaster.iconSquareSize, height: toaster.iconSquareSize)) iconView.backgroundColor = toaster.iconBackgroundColor iconView.layer.cornerRadius = toaster.iconCornerRadius iconView.clipsToBounds = true if toaster.iconImage != nil { iconView.image = toaster.iconImage } if toaster.iconURL != nil && toaster.iconURL != "" { QToasterConfig.imageForUrl(urlString: toaster.iconURL!, completionHandler:{(image: UIImage?, url: String) in iconView.image = image }) } viewArea.addSubview(iconView) } if toaster.titleText != nil && toaster.titleText != "" { let titleLabel = UILabel(frame: CGRect(x: textXPos, y: yPos, width: textAreaWidth, height: self.titleSize.height)) titleLabel.numberOfLines = 0 titleLabel.textAlignment = toaster.textAlignment titleLabel.text = toaster.titleText titleLabel.textColor = toaster.textColor titleLabel.font = toaster.titleFont viewArea.addSubview(titleLabel) yPos += 3 + self.titleSize.height }else{ yPos = ((toasterHeight - self.textSize.height) / 2) + 10 } let textLabel = UILabel(frame: CGRect(x: textXPos, y: yPos, width: textAreaWidth, height: self.textSize.height)) textLabel.text = toaster.text textLabel.textAlignment = toaster.textAlignment textLabel.textColor = toaster.textColor textLabel.numberOfLines = 0 textLabel.font = toaster.textFont viewArea.addSubview(textLabel) self.frame = CGRect(x: 0, y: 0, width: QToasterConfig.screenWidth, height: toasterHeight) self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) self.addTarget(self, action: #selector(QToasterView.touchAction), for: UIControlEvents.touchUpInside) self.addSubview(viewArea) } @objc func touchAction(){ self.toaster.touchAction() } /** To show toaster */ func show(){ UIView.animate(withDuration: self.toaster.animateDuration, delay: 0, options: UIViewAnimationOptions.allowUserInteraction, animations: { let showFrame = CGRect(x: 0,y:0,width:QToasterConfig.screenWidth,height:self.frame.height) self.viewArea.frame = showFrame }, completion: { _ in self.hide() } ) } /** To hide toaster - parameter completion: **()->Void** as hide for your toaster. */ func hide(completion: @escaping () -> Void = ({})){ UIView.animate(withDuration: self.toaster.animateDuration, delay: self.toaster.delayDuration, options: UIViewAnimationOptions.allowUserInteraction, animations: { let hideFrame = CGRect(x:0,y:0 - self.frame.height,width:QToasterConfig.screenWidth,height:self.frame.height) self.viewArea.frame = hideFrame }, completion: { _ in self.isHidden = true self.removeFromSuperview() completion() } ) } }
mit
bc7f378d630be6e32e55b2be74444525
37.871134
177
0.613314
5.023984
false
true
false
false
blokadaorg/blokada
ios/NETX/StatsModel.swift
1
3300
// // This file is part of Blokada. // // 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 https://mozilla.org/MPL/2.0/. // // Copyright © 2020 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation struct Stats: Codable { let allowed: UInt64 let denied: UInt64 let entries: [HistoryEntry] } struct HistoryEntry: Codable { let name: String let type: HistoryEntryType let time: Date let requests: UInt64 } enum HistoryEntryType: Int, Codable { case whitelisted case blocked case passed } extension HistoryEntryType { static func fromTypedef(value: DNSHistoryAction) -> HistoryEntryType { if value == Blocked { return HistoryEntryType.blocked } else if value == Whitelisted { return HistoryEntryType.whitelisted } else { return HistoryEntryType.passed } } } extension Stats { func persist() { if let statsString = self.toJson() { UserDefaults.standard.set(statsString, forKey: "netx.stats") } else { NELogger.w("Could not convert stats to json") } } static func load() -> Stats { let result = UserDefaults.standard.string(forKey: "netx.stats") guard let stringData = result else { return Stats.empty() } let jsonData = stringData.data(using: .utf8) guard let json = jsonData else { NELogger.e("Failed getting stats json") return Stats.empty() } do { return try decoder.decode(Stats.self, from: json) } catch { NELogger.e("Failed decoding stats json".cause(error)) return Stats.empty() } } static func empty() -> Stats { return Stats(allowed: 0, denied: 0, entries: []) } func combine(with stats: Stats) -> Stats { return Stats( allowed: allowed + stats.allowed, denied: denied + stats.denied, entries: stats.entries ) } } extension Encodable { func toJson() -> String? { do { let jsonData = try encoder.encode(self) let jsonString = String(data: jsonData, encoding: .utf8) guard let json = jsonString else { NELogger.e("jsonString was nil") return nil } return json } catch { NELogger.e("Failed encoding to json".cause(error)) return nil } } } private let blockaDateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ" private let decoder = initJsonDecoder() private let encoder = initJsonEncoder() private func initJsonDecoder() -> JSONDecoder { let decoder = JSONDecoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = blockaDateFormat decoder.dateDecodingStrategy = .formatted(dateFormatter) return decoder } private func initJsonEncoder() -> JSONEncoder { let encoder = JSONEncoder() let dateFormatter = DateFormatter() dateFormatter.dateFormat = blockaDateFormat encoder.dateEncodingStrategy = .formatted(dateFormatter) return encoder }
mpl-2.0
f906ebd4454a49046d548b2801d84856
25.821138
74
0.612913
4.482337
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01150-void.swift
1
539
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck struct B<T : A> { func g<T wh typealias F = Int func g<T where T.E == F>(f: B<T>) { } } struct d<f : e, g: e where g.h == f.h> {{ } let d: I
apache-2.0
c677dc5e1bde14a52acd5971fb8e556f
32.6875
79
0.692022
3.208333
false
false
false
false
Rdxer/SnapKit
SnapKitPlayground.playground/Contents.swift
3
837
//: A UIKit based Playground for presenting user interface // To use this playground, build SnapKit.framework for any simulator first. import SnapKit import UIKit import PlaygroundSupport class MyViewController : UIViewController { override func loadView() { let view = UIView() view.backgroundColor = .white let label = UILabel() label.text = "Hello World!" label.textColor = .black view.addSubview(label) label.snp.makeConstraints { (make) in make.left.equalToSuperview().offset(150) make.top.equalToSuperview().offset(200) make.size.equalTo(CGSize(width: 200, height: 20)) } self.view = view } } // Present the view controller in the Live View window PlaygroundPage.current.liveView = MyViewController()
mit
d6cb25723aa20bedd0627d2c9a3c2657
27.862069
75
0.658303
4.83815
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/WMFWelcomePanelViewController.swift
2
5759
class WMFWelcomePanelViewController: ThemeableViewController { override func apply(theme: Theme) { super.apply(theme: theme) guard viewIfLoaded != nil else { return } scrollView.apply(theme: theme) nextButton.backgroundColor = theme.colors.link for child in children { guard let themeable = child as? Themeable else { continue } themeable.apply(theme: theme) } } @IBOutlet private var containerView:UIView! @IBOutlet private var titleLabel:UILabel! @IBOutlet private var nextButton:AutoLayoutSafeMultiLineButton! @IBOutlet private var scrollView:WMFWelcomePanelGradientScrollView! @IBOutlet private var nextButtonContainerView:UIView! private var viewControllerForContainerView:UIViewController? = nil var welcomePageType:WMFWelcomePageType = .intro override func viewDidLoad() { super.viewDidLoad() // For iPhone 5 a smaller size is used. if view.bounds.size.height <= 568 { titleLabel.font = UIFont.systemFont(ofSize: 28, weight: .medium) } embedContainerControllerView() updateUIStrings() // If the button itself was directly an arranged stackview subview we couldn't // set padding contraints and also get clean collapsing when enabling isHidden. nextButtonContainerView.isHidden = welcomePageType != .analytics view.wmf_configureSubviewsForDynamicType() } private func embedContainerControllerView() { if let containerController = containerController { containerController.apply(theme: theme) addChild(containerController) containerView.wmf_addSubviewWithConstraintsToEdges(containerController.view) containerController.didMove(toParent: self) } } private lazy var containerController: ThemeableViewController? = { switch welcomePageType { case .intro: return WMFWelcomeIntroductionViewController.wmf_viewControllerFromWelcomeStoryboard() case .exploration: return WMFWelcomeExplorationViewController.wmf_viewControllerFromWelcomeStoryboard() case .languages: return WMFWelcomeLanguageTableViewController.wmf_viewControllerFromWelcomeStoryboard() case .analytics: return WMFWelcomeAnalyticsViewController.wmf_viewControllerFromWelcomeStoryboard() } }() private func updateUIStrings(){ switch welcomePageType { case .intro: titleLabel.text = WMFLocalizedString("welcome-intro-free-encyclopedia-title", value:"The free encyclopedia", comment:"Title for introductory welcome screen") case .exploration: titleLabel.text = WMFLocalizedString("welcome-explore-new-ways-title", value:"New ways to explore", comment:"Title for welcome screens including explanation of new notification features") case .languages: titleLabel.text = WMFLocalizedString("welcome-languages-search-title", value:"Search in nearly 300 languages", comment:"Title for welcome screen describing Wikipedia languages") case .analytics: titleLabel.text = WMFLocalizedString("welcome-send-data-helps-title", value:"Help make the app better", comment:"Title for welcome screen allowing user to opt in to send usage reports") } nextButton.setTitle(CommonStrings.getStartedTitle, for: .normal) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if scrollView.wmf_contentSizeHeightExceedsBoundsHeight() { scrollView.wmf_flashVerticalScrollIndicatorAfterDelay(1.5) } } } private extension UIScrollView { func wmf_contentSizeHeightExceedsBoundsHeight() -> Bool { return contentSize.height - bounds.size.height > 0 } func wmf_flashVerticalScrollIndicatorAfterDelay(_ delay: TimeInterval) { dispatchOnMainQueueAfterDelayInSeconds(delay) { self.flashScrollIndicators() } } } class WMFWelcomePanelGradientScrollView : UIScrollView, Themeable { func apply(theme: Theme) { fadeColor = theme.colors.paperBackground clear = theme.colors.paperBackground.withAlphaComponent(0) bottomGradientView.setStart(fadeColor, end: clear) topGradientView.setStart(fadeColor, end: clear) } private let fadeHeight: CGFloat = 8 private var fadeColor = UIColor.white private var clear = UIColor.white.withAlphaComponent(0) private lazy var topGradientView: WMFGradientView = { let gradient = WMFGradientView() gradient.translatesAutoresizingMaskIntoConstraints = false gradient.startPoint = .zero gradient.endPoint = CGPoint(x: 0, y: 1) gradient.setStart(fadeColor, end: clear) addSubview(gradient) return gradient }() private lazy var bottomGradientView: WMFGradientView = { let gradient = WMFGradientView() gradient.translatesAutoresizingMaskIntoConstraints = false gradient.startPoint = CGPoint(x: 0, y: 1) gradient.endPoint = .zero gradient.setStart(fadeColor, end: clear) addSubview(gradient) return gradient }() override func layoutSubviews() { super.layoutSubviews() updateGradientFrames() } private func updateGradientFrames() { topGradientView.frame = CGRect(x: 0, y: contentOffset.y, width: bounds.size.width, height: fadeHeight) bottomGradientView.frame = topGradientView.frame.offsetBy(dx: 0, dy: bounds.size.height - fadeHeight) } }
mit
f020c17acba651e7d37c699f6d6148c0
39.556338
199
0.686057
5.397376
false
false
false
false
assist-group/assist-mcommerce-sdk-ios
AssistMobileTest/AssistMobile/ApplePayPayment.swift
1
9924
// // ApplePayPayment.swift // AssistMobileTest // // Created by Sergey Kulikov on 26.12.16. // Copyright © 2016 Assist. All rights reserved. // import Foundation import PassKit @available(iOS 10.0, *) class ApplePayPayment: NSObject, PKPaymentAuthorizationViewControllerDelegate, DeviceLocationDelegate, RegistrationDelegate, ResultServiceDelegate { let supportedPaymentNetworks = [PKPaymentNetwork.masterCard, PKPaymentNetwork.visa, PKPaymentNetwork.mir] var payData: PayData? var payDelegate: AssistPayDelegate var deviceLocation: DeviceLocation? var locationUpdated = false var registrationCompleted = false var merchantId: String? var controller: UIViewController? init(delegate: AssistPayDelegate) { payDelegate = delegate } func collectDeviceData(toResult: Bool) { if let data = payData { data.deviceUniqueId = Configuration.uuid data.device = Configuration.model data.applicationName = Configuration.appName data.applicationVersion = Configuration.version data.osLanguage = Configuration.preferredLang deviceLocation = DeviceLocation(delegate: self, toResult: toResult, payAfterResult: true) deviceLocation!.requestLocation() } } func pay(_ controller: UIViewController, withData: PayData, withMerchantId: String) { payData = withData self.controller = controller merchantId = withMerchantId if let params = payData { if (params.link ?? "").isEmpty { checkRegistrationAndLocation(toResult: false) } else { checkRegistrationAndLocation(toResult: true) } } } func checkRegistrationAndLocation(toResult: Bool) { if let params = payData { collectDeviceData(toResult: toResult) if let regId = Configuration.regId { params.registrationId = regId registrationCompleted = true if toResult { continueResult() } else { continuePay() } } else { startRegistration(toResult: toResult) } } } func isApplePayAvailable(withMerchantId: String) -> Bool { merchantId = withMerchantId let request = PKPaymentRequest() request.merchantIdentifier = merchantId! request.supportedNetworks = supportedPaymentNetworks request.merchantCapabilities = PKMerchantCapability.capability3DS request.countryCode = "RU" request.currencyCode = "RUB" let formatter = NumberFormatter() formatter.generatesDecimalNumbers = true formatter.decimalSeparator = "," var amount = formatter.number(from: "1.0") as! NSDecimalNumber? ?? 1.0 if !(amount.doubleValue > 0.0) { formatter.decimalSeparator = "." amount = formatter.number(from: "1.0") as! NSDecimalNumber? ?? 1.0 } if amount.doubleValue > 0.0 { request.paymentSummaryItems = [ PKPaymentSummaryItem(label: "payment", amount: amount) ] } else { return false } if let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request) { applePayController.delegate = self if PKPaymentAuthorizationViewController.canMakePayments() { return true } else { return false } } return false } func continuePay() { if !locationUpdated || !registrationCompleted { return // wait for completion registration and location updaing } let request = PKPaymentRequest() request.merchantIdentifier = merchantId! request.supportedNetworks = supportedPaymentNetworks request.merchantCapabilities = PKMerchantCapability.capability3DS request.countryCode = payData?.country ?? "RU" request.currencyCode = payData?.orderCurrencyStr ?? "RUB" let formatter = NumberFormatter() formatter.generatesDecimalNumbers = true formatter.decimalSeparator = "," var amount = formatter.number(from: payData?.orderAmount ?? "0.0") as! NSDecimalNumber? ?? 0.0 if !(amount.doubleValue > 0.0) { formatter.decimalSeparator = "." amount = formatter.number(from: payData?.orderAmount ?? "0.0") as! NSDecimalNumber? ?? 0.0 } if amount.doubleValue > 0.0 { request.paymentSummaryItems = [ PKPaymentSummaryItem(label: payData?.orderComment ?? "payment", amount: amount) ] } else { payDelegate.payFinished("", status: "ERROR", message: "Amount should be greather than zero.") return } if let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request) { applePayController.delegate = self if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: supportedPaymentNetworks) { controller?.present(applePayController, animated: true, completion: nil) } else { let library = PKPassLibrary() library.openPaymentSetup() payDelegate.payFinished("", status: "ERROR", message: "Can not make payment through ApplePay") } } } func continueResult() { print("continue result loc = \(locationUpdated), reg = \(registrationCompleted)") if locationUpdated && registrationCompleted { getResultReal() } } func getResultReal() { let request = ResultRequest() if let data = payData { request.deviceId = Configuration.uuid request.regId = Configuration.regId request.orderNo = data.orderNumber request.merchantId = data.merchantId let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd.MM.yyyy" let date = data.date ?? Date() request.date = dateFormatter.string(from: date) let service = ResultService(requestData: request, payAfterResult: true, delegate: self) service.start() } } func startRegistration(toResult: Bool) { let regData = RegistrationData() regData.name = Configuration.appName regData.version = Configuration.version regData.deviceId = Configuration.uuid regData.merchId = payData?.merchantId regData.shop = "1" let reg = Registration(regData: regData, regDelegate: self, toResult: toResult, payAfterResult: true) reg.start() } func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) { if let data = payData { data.paymentToken = String(data: payment.token.paymentData, encoding: String.Encoding.utf8) let service = ApplePayService(requestData: data, delegate: payDelegate, completion: completion) service.start() } } func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) { controller.dismiss(animated: true, completion: nil) } func location(_ latitude: String, longitude: String, toResult: Bool, payAfterResult: Bool) { if !locationUpdated { payData!.latitude = latitude payData!.longitude = longitude locationUpdated = true DispatchQueue.main.async { [unowned self] in if toResult { self.continueResult() } else { self.continuePay() } } } } func locationError(_ text: String) { if !locationUpdated { locationUpdated = true DispatchQueue.main.async { [unowned self] in self.continuePay() } } } func registration(_ id: String, toResult: Bool, payAfterResult: Bool) { if let params = payData { params.registrationId = id Configuration.regId = id registrationCompleted = true DispatchQueue.main.async { [unowned self] in if toResult { self.continueResult() } else { self.continuePay() } } } } func registration(_ faultcode: String?, faultstring: String?) { DispatchQueue.main.async { [unowned self] in var errorMessage = "Error:" if let code = faultcode, let string = faultstring { errorMessage += " faultcode = \(code), faultstring = \(string)"; } else { errorMessage += " unknown" } self.payDelegate.payFinished("", status: "Unknown", message: errorMessage) } } func result(_ bill: String, state: String, message: String?) { // TODO result } func resultFull(_ resData: PayData) { resData.link = payData?.link resData.login = payData?.login resData.password = payData?.password payData = resData DispatchQueue.main.async { [unowned self] in self.checkRegistrationAndLocation(toResult: false) } } func resultError(_ faultcode: String?, faultstring: String?) { // TODO resultError } }
apache-2.0
cb45abe98166d189668c08a3bf3e614c
35.215328
199
0.59216
5.491422
false
false
false
false
bojanb89pa/OAuth2Swift
OAuth2Swift/ViewController.swift
1
3223
// // ViewController.swift // OAuth2Swiftn// // Created by Bojan Bogojevic on 11/3/16. // Copyright © 2016 Gecko Solutions. All rights reserved. // import UIKit import Alamofire import AlamofireObjectMapper class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Actions @IBAction func checkServer(_ sender: Any) { API.requestObject(Router.health, viewController: self) { (health: Health) in if let status = health.status { self.showMessage("Status: \(status)") } } } @IBAction func loginPressed(_ sender: AnyObject) { self.login("user", "password") } @IBAction func logout(_ sender: Any) { AuthManager.oauth2Token = nil AuthManager.currentAccount = nil self.showMessage("Access token removed!") } @IBAction func register(_ sender: Any) { let username = "test" let email = "[email protected]" let password = "test123" API.request(Router.signup(user: User(username: username, email: email, password: password)), viewController: self) .responseData {response in do { let _ = try response.result.get() self.login(username, password) } catch _ { API.showError(self) } } } @IBAction func checkUser(_ sender: Any) { let username = "test" API.requestObject(Router.getUser(username: username), viewController: self) { (user: User) in if let username = user.username, let email = user.email { self.showMessage("Username: \(username)\nemail: \(email)") } } } func login(_ username: String, _ password: String) { API.requestObject(Router.login(username: username, password: password), viewController: self) { (oauth2Token: OAuth2Token) in if let accessToken = oauth2Token.accessToken { print("Access token \(accessToken)") self.showMessage("Access token: \(accessToken)") } if let refreshToken = oauth2Token.refreshToken { print("Refresh token \(refreshToken)") } print("Is token expired: \(oauth2Token.isExpired())") AuthManager.oauth2Token = oauth2Token } } // MARK: Messages func showMessage(_ message: String) { let alertController = UIAlertController(title: "Message", message: message, preferredStyle: UIAlertController.Style.alert) let okAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in print("OK") } alertController.addAction(okAction) self.present(alertController, animated: true, completion: nil) } }
apache-2.0
6424452a430c27e93151a24f34093dce
29.396226
133
0.568281
4.987616
false
false
false
false
tmandry/Swindler
Sources/State.swift
1
17760
import AXSwift import Cocoa import PromiseKit /// Initializes a new Swindler state and returns it in a Promise. public func initialize() -> Promise<State> { let notifier = EventNotifier() let ssd = OSXSystemScreenDelegate(notifier) return OSXStateDelegate< AXSwift.UIElement, AXSwift.Application, AXSwift.Observer, ApplicationObserver >.initialize( notifier, ApplicationObserver(), ssd, OSXSpaceObserver(notifier, ssd, OSXSystemSpaceTracker()) ).map { delegate in State(delegate: delegate) } } // MARK: - State /// The state represents the entire state of the OS, including all known windows, applications, and /// spaces. public final class State { let delegate: StateDelegate init(delegate: StateDelegate) { self.delegate = delegate } /// The currently running applications. public var runningApplications: [Application] { return delegate.runningApplications.map {Application(delegate: $0, stateDelegate: delegate)} } /// The frontmost application. public var frontmostApplication: WriteableProperty<OfOptionalType<Application>> { return delegate.frontmostApplication } /// All windows that we know about. Windows on spaces that we haven't seen yet aren't included. public var knownWindows: [Window] { return delegate.knownWindows.compactMap {Window(delegate: $0)} } /// The physical screens in the current display configuration. public var screens: [Screen] { return delegate.systemScreens.screens.map {Screen(delegate: $0)} } /// The main screen, if any. public var mainScreen: Screen? { return delegate.systemScreens.main.map {Screen(delegate: $0)} } /// Calls `handler` when the specified `Event` occurs. public func on<Event: EventType>(_ handler: @escaping (Event) -> Void) { delegate.notifier.on(handler) } } // All public classes in Swindler are implemented with an internal delegate. This decoupling aids in // testing and hides implementation details from the API. // // Our delegates differ from most Apple API delegates in that they are internal and are critical to // the functioning of the class, so they are not held with weak references. protocol StateDelegate: AnyObject { var runningApplications: [ApplicationDelegate] { get } var frontmostApplication: WriteableProperty<OfOptionalType<Application>>! { get } var knownWindows: [WindowDelegate] { get } var systemScreens: SystemScreenDelegate { get } var notifier: EventNotifier { get } } // MARK: - OSXStateDelegate /// Wraps behavior needed to track the frontmost applications. protocol ApplicationObserverType { var frontmostApplicationPID: pid_t? { get } func onFrontmostApplicationChanged(_ handler: @escaping () -> Void) func onApplicationLaunched(_ handler: @escaping (pid_t) -> Void) func onApplicationTerminated(_ handler: @escaping (pid_t) -> Void) func makeApplicationFrontmost(_ pid: pid_t) throws associatedtype ApplicationElement: ApplicationElementType func allApplications() -> [ApplicationElement] func appElement(forProcessID processID: pid_t) -> ApplicationElement? } /// Simple pubsub. class EventNotifier { private typealias EventHandler = (EventType) -> Void private var eventHandlers: [String: [EventHandler]] = [:] func on<Event: EventType>(_ handler: @escaping (Event) -> Void) { let notification = Event.typeName if eventHandlers[notification] == nil { eventHandlers[notification] = [] } // Wrap in a casting closure to preserve type information that gets erased in the // dictionary. eventHandlers[notification]!.append({ handler($0 as! Event) }) } func notify<Event: EventType>(_ event: Event) { assert(Thread.current.isMainThread) if let handlers = eventHandlers[Event.typeName] { for handler in handlers { handler(event) } } } } struct ApplicationObserver: ApplicationObserverType { var frontmostApplicationPID: pid_t? { return NSWorkspace.shared.frontmostApplication?.processIdentifier } func onFrontmostApplicationChanged(_ handler: @escaping () -> Void) { let sharedWorkspace = NSWorkspace.shared let notificationCenter = sharedWorkspace.notificationCenter // Err on the side of updating too often; watch both activate and deactivate notifications. notificationCenter.addObserver( forName: NSWorkspace.didActivateApplicationNotification, object: sharedWorkspace, queue: nil ) { _ in handler() } notificationCenter.addObserver( forName: NSWorkspace.didDeactivateApplicationNotification, object: sharedWorkspace, queue: nil ) { _ in handler() } } func onApplicationLaunched(_ handler: @escaping (pid_t) -> Void) { let sharedWorkspace = NSWorkspace.shared let notificationCenter = sharedWorkspace.notificationCenter notificationCenter.addObserver( forName: NSWorkspace.didLaunchApplicationNotification, object: sharedWorkspace, queue: nil ) { note in guard let userInfo = note.userInfo else { log.warn("Missing notification info on NSWorkspaceDidLaunchApplication") return } let runningApp = userInfo[NSWorkspace.applicationUserInfoKey] as! NSRunningApplication handler(runningApp.processIdentifier) } } func onApplicationTerminated(_ handler: @escaping (pid_t) -> Void) { let sharedWorkspace = NSWorkspace.shared let notificationCenter = sharedWorkspace.notificationCenter notificationCenter.addObserver( forName: NSWorkspace.didTerminateApplicationNotification, object: sharedWorkspace, queue: nil ) { note in guard let userInfo = note.userInfo else { log.warn("Missing notification info on NSWorkspaceDidTerminateApplication") return } let runningApp = userInfo[NSWorkspace.applicationUserInfoKey] as! NSRunningApplication handler(runningApp.processIdentifier) } } func makeApplicationFrontmost(_ pid: pid_t) throws { guard let app = NSRunningApplication(processIdentifier: pid) else { log.info("Could not find requested application to make frontmost with pid \(pid)") throw OSXDriverError.runningApplicationNotFound(processID: pid) } let success = try traceRequest(app, "activate", "") { app.activate(options: [NSApplication.ActivationOptions.activateIgnoringOtherApps]) } if !success { log.debug("Failed to activate application \(app), it probably quit") } } typealias ApplicationElement = AXSwift.Application func allApplications() -> [ApplicationElement] { AXSwift.Application.all() } func appElement(forProcessID processID: pid_t) -> ApplicationElement? { return AXSwift.Application(forProcessID: processID) } } /// Implements StateDelegate using the AXUIElement API. final class OSXStateDelegate< UIElement, ApplicationElement, Observer: ObserverType, ApplicationObserver: ApplicationObserverType >: StateDelegate where Observer.UIElement == UIElement, ApplicationElement.UIElement == UIElement, ApplicationObserver.ApplicationElement == ApplicationElement { typealias WinDelegate = OSXWindowDelegate<UIElement, ApplicationElement, Observer> typealias AppDelegate = OSXApplicationDelegate<UIElement, ApplicationElement, Observer> private var applicationsByPID: [pid_t: AppDelegate] = [:] // This should be the only strong reference to EventNotifier. var notifier: EventNotifier fileprivate var appObserver: ApplicationObserver fileprivate var spaceObserver: OSXSpaceObserver // For convenience/readability. fileprivate var applications: Dictionary<pid_t, AppDelegate>.Values { return applicationsByPID.values } var runningApplications: [ApplicationDelegate] { return applications.map({ $0 as ApplicationDelegate }) } var frontmostApplication: WriteableProperty<OfOptionalType<Application>>! var knownWindows: [WindowDelegate] { return applications.flatMap({ $0.knownWindows }) } var systemScreens: SystemScreenDelegate var spaceIds: [Int]! fileprivate var initialized: Promise<Void>! // TODO: retry instead of ignoring an app/window when timeouts are encountered during // initialization? static func initialize<Screens: SystemScreenDelegate>( _ notifier: EventNotifier, _ appObserver: ApplicationObserver, _ screens: Screens, _ spaces: OSXSpaceObserver ) -> Promise<OSXStateDelegate> { return firstly { () -> Promise<OSXStateDelegate> in let delegate = OSXStateDelegate(notifier, appObserver, screens, spaces) return delegate.initialized.map { delegate } } } // TODO make private init<Screens: SystemScreenDelegate>( _ notifier: EventNotifier, _ appObserver: ApplicationObserver, _ screens: Screens, _ spaces: OSXSpaceObserver ) { log.debug("Initializing Swindler") self.notifier = notifier systemScreens = screens self.appObserver = appObserver spaceObserver = spaces let appPromises = appObserver.allApplications().map { appElement in watchApplication(appElement: appElement) .asVoid() .recover { error -> Void in // drop errors } } let (propertyInitPromise, seal) = Promise<Void>.pending() frontmostApplication = WriteableProperty( FrontmostApplicationPropertyDelegate( appFinder: self, appObserver: appObserver, initPromise: propertyInitPromise), withEvent: FrontmostApplicationChangedEvent.self, receivingObject: State.self, notifier: self) let properties: [PropertyType] = [ frontmostApplication ] // Must add the observer after configuring frontmostApplication. appObserver.onFrontmostApplicationChanged(frontmostApplication.issueRefresh) appObserver.onApplicationLaunched(onApplicationLaunch) appObserver.onApplicationTerminated(onApplicationTerminate) notifier.on { [weak self] (event: SpaceWillChangeEvent) in guard let self = self else { return } log.info("Space changed: \(event.ids)") self.spaceIds = event.ids for (idx, screen) in self.systemScreens.screens.enumerated() { screen.spaceId = event.ids[idx] } let updateWindows = self.applications.map { app in app.onSpaceChanged() } when(resolved: updateWindows).done { _ in // The space may have changed again in the meantime. Make sure // we only emit events consistent with the current state. // TODO needs a test if event.ids == self.spaceIds { log.notice("Known windows updated") self.notifier.notify(SpaceDidChangeEvent(external: true, ids: event.ids)) } }.recover { error in log.error("Couldn't update window list after space change: \(error)") } } spaces.emitSpaceWillChangeEvent() // Must not allow frontmostApplication to initialize until the observer is in place. when(fulfilled: appPromises) //.asVoid() .done { seal.fulfill(()) } .catch(seal.reject) frontmostApplication.initialized.catch { error in log.error("Caught error initializing frontmostApplication: \(error)") }.finally { log.debug("Done initializing") } initialized = initializeProperties(properties).asVoid() } func watchApplication(appElement: ApplicationElement) -> Promise<AppDelegate> { return watchApplication(appElement: appElement, retry: 0) } func watchApplication(appElement: ApplicationElement, retry: Int) -> Promise<AppDelegate> { return AppDelegate.initialize(axElement: appElement, stateDelegate: self, notifier: notifier) .map { appDelegate in self.applicationsByPID[try appDelegate.axElement.pid()] = appDelegate return appDelegate } //.asVoid() .recover { error -> Promise<AppDelegate> in if retry < 3 { return self.watchApplication(appElement: appElement, retry: retry + 1) } throw error } .recover { error -> Promise<AppDelegate> in // Log errors let pid = try? appElement.pid() let bundleID = pid.flatMap { NSRunningApplication(processIdentifier: $0) } .flatMap { $0.bundleIdentifier } let pidString = (pid == nil) ? "??" : String(pid!) log.trace("Could not watch application \(bundleID ?? "") (pid=\(pidString)): " + String(describing: error)) throw error } } } extension OSXStateDelegate { fileprivate func onApplicationLaunch(_ pid: pid_t) { guard let appElement = appObserver.appElement(forProcessID: pid) else { return } addAppElement(appElement).catch { err in log.error("Error while watching new application: \(String(describing: err))") } } // Also used by FakeSwindler. internal func addAppElement(_ appElement: ApplicationElement) -> Promise<AppDelegate> { watchApplication(appElement: appElement).map { appDelegate in self.notifier.notify(ApplicationLaunchedEvent( external: true, application: Application(delegate: appDelegate, stateDelegate: self) )) self.frontmostApplication.refresh() return appDelegate } } fileprivate func onApplicationTerminate(_ pid: pid_t) { guard let appDelegate = self.applicationsByPID[pid] else { log.debug("Saw termination for unknown pid \(pid)") return } applicationsByPID.removeValue(forKey: pid) notifier.notify(ApplicationTerminatedEvent( external: true, application: Application(delegate: appDelegate, stateDelegate: self) )) // TODO: Clean up observers? } } extension OSXStateDelegate: PropertyNotifier { typealias Object = State // TODO... can we get rid of this or simplify it? func notify<Event: PropertyEventType>( _ event: Event.Type, external: Bool, oldValue: Event.PropertyType, newValue: Event.PropertyType ) where Event.Object == State { notifier.notify(Event(external: external, object: State(delegate: self), oldValue: oldValue, newValue: newValue)) } /// Called when the underlying object has become invalid. func notifyInvalid() { assertionFailure("State can't become invalid") } } // MARK: PropertyDelegates protocol AppFinder: AnyObject { func findAppByPID(_ pid: pid_t) -> Application? } extension OSXStateDelegate: AppFinder { func findAppByPID(_ pid: pid_t) -> Application? { guard let appDelegate = applicationsByPID[pid] else { return nil } return Application(delegate: appDelegate) } } private final class FrontmostApplicationPropertyDelegate< ApplicationObserver: ApplicationObserverType >: PropertyDelegate { typealias T = Application weak var appFinder: AppFinder? let appObserver: ApplicationObserver let initPromise: Promise<Void> init(appFinder: AppFinder, appObserver: ApplicationObserver, initPromise: Promise<Void>) { self.appFinder = appFinder self.appObserver = appObserver self.initPromise = initPromise } func readValue() -> Application? { guard let pid = appObserver.frontmostApplicationPID else { return nil } guard let app = findAppByPID(pid) else { return nil } return app } func writeValue(_ newValue: Application) throws { let pid = newValue.delegate.processIdentifier do { try appObserver.makeApplicationFrontmost(pid!) } catch { log.debug("Failed to make application PID \(pid!) frontmost: \(error)") throw PropertyError.invalidObject(cause: error) } } func initialize() -> Promise<Application?> { // No need to run in background, the call happens instantly. return initPromise.map { self.readValue() } } fileprivate func findAppByPID(_ pid: pid_t) -> Application? { // TODO: extract into runOnMainThread util // Avoid using locks by forcing calls out to `windowFinder` to happen on the main thead. var app: Application? if Thread.current.isMainThread { app = appFinder?.findAppByPID(pid) } else { DispatchQueue.main.sync { app = self.appFinder?.findAppByPID(pid) } } return app } }
mit
6e50f14cab6eec63b302d39a89954017
35.54321
101
0.646171
5.334935
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/Algorithm4Swift/Algorithm4Swift/Algorithm/Other/Search.swift
1
5833
// // Search.swift // Algorithm // // Created by 朱双泉 on 26/02/2018. // Copyright © 2018 Castie!. All rights reserved. // import Foundation @discardableResult func binSearch(list: [Int], find: Int) -> Int { var low = 0, high = list.count - 1 while low <= high { let mid = (low + high) / 2 if find == list[mid] {return mid} else if (find > list[mid]) {low = mid + 1} else {high = mid - 1} } return -1; } @discardableResult func recursiveBinSearch(list: [Int], find: Int) -> Int { func search(list: [Int], low: Int, high: Int, find: Int) -> Int { if low <= high { let mid = (low + high) / 2 if find == list[mid] {return mid} else if (find > list[mid]) { return search(list: list, low: mid+1, high: high, find: find) } else { return search(list: list, low: low, high: mid-1, find: find) } } return -1; } return search(list: list, low: 0, high: list.count - 1, find: find) } @discardableResult func findMedianSortedArrays_1(_ array1: [Int], _ array2: [Int]) -> Double { var array = [Int]() array.append(contentsOf: array1) array.append(contentsOf: array2) quickSort(list: &array) let b = array.count % 2 let c = array.count var result = 0.0; if b == 1 { result = Double(array[c / 2]) } else { let n1 = array[c / 2 - 1] let n2 = array[c / 2] result = Double((n1 + n2)) / 2.0 } return result } @discardableResult func findMedianSortedArrays_2(_ array1: [Int], _ array2: [Int]) -> Double { let c1 = array1.count, c2 = array2.count var a1 = array1, a2 = array2 if c1 <= 0 && c2 <= 0 { return 0.0 } func findKth(_ nums1: inout [Int], i: Int, _ nums2: inout [Int], j: Int, k: Int) -> Double { if nums1.count - i > nums2.count - j { return findKth(&nums2, i: j, &nums1, j: i, k: k) } if nums1.count == i { return Double(nums2[j + k - 1]) } if k == 1 { return Double(min(nums1[i], nums2[j])) } let pa = min(i + k / 2, nums1.count), pb = j + k - pa + i if nums1[pa - 1] < nums2[pb - 1] { return findKth(&nums1, i: pa, &nums2, j: j, k: k - pa + i) } else if nums1[pa - 1] > nums2[pb - 1] { return findKth(&nums1, i: i, &nums2, j: pb, k: k - pb + j) } else { return Double(nums1[pa - 1]) } } let total = c1 + c2 if total % 2 == 1 { return findKth(&a1, i: 0, &a2, j: 0, k: total / 2 + 1) } else { return (findKth(&a1, i: 0, &a2, j: 0, k: total / 2) + findKth(&a1, i: 0, &a2, j: 0, k: total / 2 + 1)) / 2.0 } } @discardableResult func findMedianSortedArrays_3(_ array1: [Int], _ array2: [Int]) -> Double { if array1.count == 0 { if array2.count % 2 == 1 { return Double(array2[array2.count / 2]) } else { return Double(array2[array2.count / 2] + array2[array2.count / 2 - 1]) * 0.5 } } else if array2.count == 0 { if array1.count % 2 == 1 { return Double(array1[array1.count / 2]) } else { return Double(array1[array1.count / 2] + array1[array1.count / 2 - 1]) * 0.5 } } let total = array1.count + array2.count let index = total / 2 let count = array1.count < array2.count ? array1.count : array2.count var array = [Int]() var i = 0, j = 0; for _ in 0...count { if array.count >= index + 1 { break } if array1[i] < array2[j] { array.append(array1[i]) i += 1 } else { array.append(array2[j]) j += 1 } } return total % 2 == 1 ? Double(array[index]) : Double(array[index] + array[index - 1]) * 0.5 } @discardableResult func findMedianSortedArrays_4(_ array1: [Int], _ array2: [Int]) -> Double { if array1.count == 0 { if array2.count % 2 == 1 { return Double(array2[array2.count / 2]) } else { return Double(array2[array2.count / 2] + array2[array2.count / 2 - 1]) * 0.5 } } else if array2.count == 0 { if array1.count % 2 == 1 { return Double(array1[array1.count / 2]) } else { return Double(array1[array1.count / 2] + array1[array1.count / 2 - 1]) * 0.5 } } let total = array1.count + array2.count let count = array1.count < array2.count ? array1.count : array2.count let odd = total % 2 == 1 var i = 0, j = 0, f = 1, m1 = 0.0, m2 = 0.0, result = 0.0; for _ in 0...count { if odd { array1[i] < array2[j] ? (i += 1) : (j += 1) } if f >= total / 2 { if odd { result = array1[i] < array2[j] ? Double(array1[i]) : Double(array2[j]) } else { if array1[i] < array2[j] { m1 = Double(array1[i]) if (i + 1) < array1.count && array1[i + 1] < array2[j] { m2 = Double(array1[i + 1]) } else { m2 = Double(array2[j]) } } else { m1 = Double(array2[j]) if (j + 1) < array2.count && array2[j + 1] < array1[i] { m2 = Double(array2[j + 1]) } else { m2 = Double(array1[i]) } } result = (m1 + m2) * 0.5 } break } if !odd { array1[i] < array2[j] ? (i += 1) : (j += 1) } f += 1 } return result }
mit
eebb64e7bc8176e2f7bf3a043ed29ad2
30.322581
116
0.465671
3.249303
false
false
false
false
tomlokhorst/XcodeEdit
Sources/XcodeEdit/Serialization.swift
1
10197
// // Serialization.swift // XcodeEdit // // Created by Tom Lokhorst on 2015-08-29. // Copyright © 2015 nonstrict. All rights reserved. // import Foundation extension XCProjectFile { public func write(to url: URL, format: PropertyListSerialization.PropertyListFormat? = nil) throws { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil) let name = try XCProjectFile.projectName(from: url) let path = url.appendingPathComponent("project.pbxproj", isDirectory: false) let serializer = Serializer(projectName: name, projectFile: self) let plformat = format ?? self.format if plformat == PropertyListSerialization.PropertyListFormat.openStep { try serializer.openStepSerialization.write(to: path, atomically: true, encoding: String.Encoding.utf8) } else { let data = try PropertyListSerialization.data(fromPropertyList: fields, format: plformat, options: 0) try data.write(to: path) } } public func serialized(projectName: String) throws -> Data { let serializer = Serializer(projectName: projectName, projectFile: self) if format == PropertyListSerialization.PropertyListFormat.openStep { return serializer.openStepSerialization.data(using: String.Encoding.utf8)! } else { return try PropertyListSerialization.data(fromPropertyList: fields, format: format, options: 0) } } } private let nonescapeRegex = try! NSRegularExpression(pattern: "^[a-z0-9_\\$\\.\\/]+$", options: NSRegularExpression.Options.caseInsensitive) internal class Serializer { let projectName: String let projectFile: XCProjectFile init(projectName: String, projectFile: XCProjectFile) { self.projectName = projectName self.projectFile = projectFile } lazy var targetsByConfigId: [Guid: PBXTarget] = { var dict: [Guid: PBXTarget] = [:] for reference in self.projectFile.project.targets { if let target = reference.value { dict[target.buildConfigurationList.id] = target } } return dict }() lazy var buildPhaseByFileId: [Guid: PBXBuildPhase] = { let buildPhases = self.projectFile.allObjects.objects.values.compactMap { $0 as? PBXBuildPhase } var dict: [Guid: PBXBuildPhase] = [:] for buildPhase in buildPhases { for file in buildPhase.files { dict[file.id] = buildPhase } } return dict }() var openStepSerialization: String { var lines = [ "// !$*UTF8*$!", "{", ] for key in projectFile.fields.keys.sorted() { let val = projectFile.fields[key]! if key == "objects" { lines.append("\tobjects = {") let groupedObjects = projectFile.allObjects.objects.values .grouped { $0.isa } .map { (isa: $0.0, objects: $0.1) } .sorted { $0.isa } for (isa, objects) in groupedObjects { lines.append("") lines.append("/* Begin \(isa) section */") for object in objects.sorted(by: { $0.id }) { let multiline = isa != "PBXBuildFile" && isa != "PBXFileReference" let parts = rows(type: isa, objectId: object.id, multiline: multiline, fields: object.fields) if multiline { for ln in parts { lines.append("\t\t" + ln) } } else { lines.append("\t\t" + parts.joined(separator: "")) } } lines.append("/* End \(isa) section */") } lines.append("\t};") } else { var comment = ""; if key == "rootObject" { comment = " /* Project object */" } let row = "\(key) = \(val)\(comment);" for line in row.components(separatedBy: "\n") { lines.append("\t\(line)") } } } lines.append("}\n") return lines.joined(separator: "\n") } func comment(id: Guid) -> String? { if id == projectFile.project.id { return "Project object" } if let obj = projectFile.allObjects.objects[id] { if let ref = obj as? PBXReference { return ref.name ?? ref.path } if let target = obj as? PBXTarget { return target.name } if let config = obj as? XCBuildConfiguration { return config.name } if let copyFiles = obj as? PBXCopyFilesBuildPhase { return copyFiles.name ?? "CopyFiles" } if let dependency = obj as? XCSwiftPackageProductDependency { let plugin = "plugin:" if let productName = dependency.productName, productName.hasPrefix(plugin) { return String(productName.dropFirst(plugin.count)) } return dependency.productName } if let reference = obj as? XCRemoteSwiftPackageReference { if let repositoryName = reference.repositoryURL?.deletingPathExtension().lastPathComponent { return "XCRemoteSwiftPackageReference \"\(repositoryName)\"" } return "XCRemoteSwiftPackageReference" } if obj is PBXFrameworksBuildPhase { return "Frameworks" } if obj is PBXHeadersBuildPhase { return "Headers" } if obj is PBXResourcesBuildPhase { return "Resources" } if let shellScript = obj as? PBXShellScriptBuildPhase { return shellScript.name ?? "ShellScript" } if obj is PBXSourcesBuildPhase { return "Sources" } if let buildFile = obj as? PBXBuildFile { if let buildPhase = buildPhaseByFileId[id], let group = comment(id: buildPhase.id) { if let fileRefId = buildFile.fileRef?.id { if let fileRef = comment(id: fileRefId) { return "\(fileRef) in \(group)" } } else if let productRefId = buildFile.productRef?.id { if let productRef = comment(id: productRefId) { return "\(productRef) in \(group)" } } else { return "(null) in \(group)" } } } if obj is XCConfigurationList { if let target = targetsByConfigId[id] { return "Build configuration list for \(target.isa) \"\(target.name)\"" } return "Build configuration list for PBXProject \"\(projectName)\"" } return obj.isa } return nil } func valStr(_ val: String) -> String { let replacements: [(String, String)] = [ ("\\", "\\\\"), ("\t", "\\t"), ("\n", "\\n"), ("\r", "\\r"), ("\"", "\\\"") ] var str = val for (template, replacement) in replacements { str = str.replacingOccurrences(of: template, with: replacement) } let range = NSRange(location: 0, length: str.utf16.count) if let _ = nonescapeRegex.firstMatch(in: str, options: [], range: range) { return str } return "\"\(str)\"" } func objval(key: String, val: Any, multiline: Bool) -> [String] { var parts: [String] = [] let keyStr = valStr(key) if let valArr = val as? [String] { parts.append("\(keyStr) = (") var ps: [String] = [] for valItem in valArr { let str = valStr(valItem) var extraComment = "" if let c = comment(id: Guid(valItem)) { extraComment = " /* \(c) */" } ps.append("\(str)\(extraComment),") } if multiline { for p in ps { parts.append("\t\(p)") } parts.append(");") } else { parts.append(ps.map { $0 + " "}.joined(separator: "") + "); ") } } else if let valArr = val as? [Fields] { parts.append("\(keyStr) = (") for valObj in valArr { if multiline { parts.append("\t{") } for valKey in valObj.keys.sorted() { let valVal = valObj[valKey]! let ps = objval(key: valKey, val: valVal, multiline: multiline) if multiline { for p in ps { parts.append("\t\t\(p)") } } else { parts.append("\t" + ps.joined(separator: "") + "}; ") } } if multiline { parts.append("\t},") } } parts.append(");") } else if let valObj = val as? Fields { parts.append("\(keyStr) = {") for valKey in valObj.keys.sorted() { let valVal = valObj[valKey]! let ps = objval(key: valKey, val: valVal, multiline: multiline) if multiline { for p in ps { parts.append("\t\(p)") } } else { parts.append(ps.joined(separator: "") + "}; ") } } if multiline { parts.append("};") } } else { let str = valStr("\(val)") var extraComment = ""; if let c = comment(id: Guid("\(val)")) { extraComment = " /* \(c) */" } if key == "remoteGlobalIDString" || key == "TestTargetID" { extraComment = "" } if multiline { parts.append("\(keyStr) = \(str)\(extraComment);") } else { parts.append("\(keyStr) = \(str)\(extraComment); ") } } return parts } func rows(type: String, objectId: Guid, multiline: Bool, fields: Fields) -> [String] { var parts: [String] = [] if multiline { parts.append("isa = \(type);") } else { parts.append("isa = \(type); ") } for key in fields.keys.sorted() { if key == "isa" { continue } let val = fields[key]! for p in objval(key: key, val: val, multiline: multiline) { parts.append(p) } } let keyStr = valStr(objectId.value) var objComment = "" if let c = comment(id: objectId) { objComment = " /* \(c) */" } let opening = "\(keyStr)\(objComment) = {" let closing = "};" if multiline { var lines: [String] = [] lines.append(opening) for part in parts { lines.append("\t\(part)") } lines.append(closing) return lines } else { return [opening + parts.joined(separator: "") + closing] } } }
mit
a1c9c950bf5e29f0ee4bc97e5f7a3980
25.346253
141
0.554923
4.269682
false
false
false
false
robconrad/fledger-common
FledgerCommon/services/models/location/LocationServiceImpl.swift
1
1986
// // TypeService.swift // fledger-ios // // Created by Robert Conrad on 4/12/15. // Copyright (c) 2015 TwoSpec Inc. All rights reserved. // import Foundation import SQLite import MapKit #if os(iOS) import Parse #elseif os(OSX) import ParseOSX #endif class LocationServiceImpl: LocationService, HasShieldedPersistenceEngine { let engine = ShieldedPersistenceEngine(engine: StandardPersistenceEngine<Location>( modelType: ModelType.Location, fromPFObject: { pf in Location(pf: pf) }, fromRow: { row in Location(row: row) }, table: DatabaseSvc().locations, defaultOrder: { q in q.order(Fields.name) } )) func itemCount(id: Int64) -> Int { return DatabaseSvc().db.scalar(DatabaseSvc().items.filter(Fields.locationId == id).count) } func nearest(coordinate: CLLocationCoordinate2D, sortBy: LocationSortBy) -> [Location] { let orderBy: String switch sortBy { case .Name: orderBy = "CASE WHEN name IS NULL THEN address ELSE name END" case .Distance: orderBy = "computedDistance" } var elements: [Location] = [] let stmt = DatabaseSvc().db.prepare("SELECT id, name, latitude, longitude, address, distance(latitude, longitude, ?, ?) AS computedDistance FROM locations ORDER BY \(orderBy)") do { for row in try stmt.run(coordinate.latitude, coordinate.longitude) { elements.append(Location( id: (row[0] as! Int64), name: row[1] as? String, latitude: row[2] as! Double, longitude: row[3] as! Double, address: row[4] as! String, distance: row[5] as? Double) ) } } catch { } return elements } func cleanup() { // TODO delete locations that have 0 items attached } }
mit
7675ffed6d32de1430c1238932732707
29.106061
184
0.58006
4.442953
false
false
false
false
kukushi/Torch
Torch/ScrollObserver.swift
1
12777
// // RefreshObserverView.swift // Torch // // Created by Xing He on 3/19/16. // Copyright © 2016 Xing He. All rights reserved. // import UIKit class ScrollObserver: NSObject { let option: PullOption let action: RefreshAction var isEnabled = true weak var refreshView: RefreshView? weak var containerView: UIView? private lazy var feedbackGenerator = RefreshFeedbackGenerator() var topConstraint: NSLayoutConstraint? // Keep track of the last refreshing height, used to prevent infinite automatic refreshing private var lastRefreshingHeight: CGFloat = 0 // When the content height significant changed, disable the bottom refreshing until it go back to normal region private var contentHeightSignificantShrank = false var contentOffsetBeforeAnimationEnd: CGPoint? var contentInsetBeforeAnimationEnd: UIEdgeInsets? private var direction: PullDirection { return option.direction } private var pullingHeight: CGFloat { return option.areaHeight + option.topPadding } private var isPullingDown: Bool { direction == .down } private var oldContentSizeHeight: CGFloat? private var originalContentOffsetY: CGFloat = 0 private var observingContentOffsetToken: NSKeyValueObservation? private var observingContentSizeToken: NSKeyValueObservation? open private(set) var state: PullState = .done { didSet { guard oldValue != state else { return } stateChanged(from: oldValue, to: state) } } private var appropriateContentInset: UIEdgeInsets { if #available(iOS 11.0, *) { return scrollView.adjustedContentInset } else { return scrollView.contentInset } } var scrollView: UIScrollView { guard let parentScrollView = containerView?.superview as? UIScrollView else { fatalError("ScrollObserver can only be used in UIScrollView and it's subclasses.") } return parentScrollView } init(refreshView: RefreshView, option: PullOption, action: @escaping RefreshAction) { self.refreshView = refreshView self.option = option self.action = action } deinit { cancelKVO() } func stopObserving() { cancelKVO() } private func cancelKVO() { if #available(iOS 11.0, *) { observingContentSizeToken = nil observingContentOffsetToken = nil } else { // NSKeyValueObservation crash on deinit on iOS 10 // https://bugs.swift.org/browse/SR-5816 guard containerView != nil else { return } if let scrollView = containerView?.superview { if let observingContentSizeToken = observingContentSizeToken { scrollView.removeObserver(observingContentSizeToken, forKeyPath: "contentSize") } if let observingContentOffsetToken = observingContentOffsetToken { scrollView.removeObserver(observingContentOffsetToken, forKeyPath: "contentOffset") } } observingContentSizeToken = nil observingContentOffsetToken = nil } } func startObserving() { if containerView?.superview == nil { return } guard containerView?.superview is UIScrollView else { preconditionFailure("ScrollObserver can only be used in UIScrollView and it's subclasses.") } if !isPullingDown { observingContentSizeToken = scrollView.observe(\.contentSize, options: [.new]) { [weak self] (_, _) in guard let self = self else { return } self.checkIfContentHeightShrank() self.observingContentSizeChanges() } } observingContentOffsetToken = scrollView.observe(\.contentOffset, options: .new) { [weak self] (_, _) in guard let self = self else { return } self.checkIfContentHeightShrank() self.observingContentOffsetChanges() } originalContentOffsetY = scrollView.contentOffset.y } private func checkIfContentHeightShrank() { if let oldValue = oldContentSizeHeight { contentHeightSignificantShrank = (oldValue - scrollView.contentSize.height) >= pullingHeight } oldContentSizeHeight = scrollView.contentSize.height } // MARK: KVO func observingContentOffsetChanges() { guard isEnabled else { return } guard state != .refreshing else { return } let viewHeight = pullingHeight switch direction { case .down: let offset = scrollView.contentOffset.y + appropriateContentInset.top if !scrollView.isDragging { if offset <= -viewHeight { // Enough pulling, action should be triggered startAnimating() } else if offset < 0 && state == .pulling { state = .cancel // Mark the refresh as done state = .done if option.enableTapticFeedback { feedbackGenerator.reset() } } } else { if offset < 0 { // Still pulling let process = -offset / viewHeight if option.enableTapticFeedback { if state == .done { feedbackGenerator.prepare() } if state == .pulling && process >= 1 { feedbackGenerator.generate() } } processAnimatingAndState(process) } } case .up: let contentHeight = scrollView.contentSize.height let containerHeight = scrollView.frame.height if contentHeight < containerHeight { return } let offset = scrollView.contentOffset.y - appropriateContentInset.bottom let bottomOffset = containerHeight + offset - contentHeight // Ignore offset change when height shrank if contentHeightSignificantShrank { if bottomOffset >= viewHeight { return } else { contentHeightSignificantShrank = false } } // Starts animation automatically and remember this location to prevent infinite animation if option.shouldStartBeforeReachingBottom && state != .refreshing && lastRefreshingHeight != scrollView.contentSize.height { if bottomOffset > -option.startBeforeReachingBottomFactor * scrollView.contentSize.height { debugLog("[Torch] Start refreshing because almost reaching the bottom") lastRefreshingHeight = scrollView.contentSize.height startAnimating() } return } if scrollView.isDragging { if bottomOffset > 0 { let process = bottomOffset / viewHeight processAnimatingAndState(process) } } else { if bottomOffset >= viewHeight { startAnimating() } else if bottomOffset > 0 && state == .pulling { state = .cancel state = .done } } } } func observingContentSizeChanges() { guard isEnabled else { return } if !isPullingDown { topConstraint?.constant = scrollView.contentSize.height scrollView.layoutIfNeeded() } } func stateChanged(from oldState: PullState, to state: PullState) { guard let refreshView = refreshView else { return } refreshView.pullToRefresh(refreshView, stateDidChange: state, direction: direction) } // MARK: Animation func processAnimatingAndState(_ process: CGFloat) { state = process < 1 ? .pulling : .readyToRelease guard let refreshView = refreshView else { return } refreshView.pullToRefresh(refreshView, progressDidChange: process, direction: direction) } open func pauseAnimation() { guard let refreshView = refreshView else { return } refreshView.pullToRefreshAnimationDidPause(refreshView, direction: direction) } open func resumeAnimation() { guard let refreshView = refreshView else { return } refreshView.pullToRefreshAnimationDidResume(refreshView, direction: direction) } open func startAnimating(animated: Bool = true) { guard state != .refreshing else { return } state = .refreshing let updateClosure = { [weak self] in guard let self = self else { return } if self.isPullingDown { self.scrollView.contentInset.top += self.pullingHeight self.scrollView.contentOffset.y = self.originalContentOffsetY - self.pullingHeight } else { self.scrollView.contentInset.bottom += self.pullingHeight self.scrollView.contentOffset.y += self.pullingHeight } self.contentOffsetBeforeAnimationEnd = self.scrollView.contentOffset self.contentInsetBeforeAnimationEnd = self.scrollView.contentInset } let completionClosure = { [weak self] (_: Bool) in guard let self = self else { return } guard let refreshView = self.refreshView else { return } refreshView.pullToRefreshAnimationDidStart(refreshView, direction: self.direction) self.action(self.scrollView) } if animated { UIView.animate(withDuration: 0.4, animations: updateClosure, completion: completionClosure) } else { updateClosure() completionClosure(true) } } open func stopAnimating(animated: Bool = true, scrollToOriginalPosition: Bool = true) { guard state == .refreshing else { return } state = .done guard let refreshView = refreshView else { return } refreshView.pullToRefreshAnimationDidEnd(refreshView, direction: direction) // Don't hold self. Action don't need to be executed if the view is released. let updateClosure = { [weak self] in guard let self = self else { return } // Restore to original position only when offset is unchanged if self.contentOffsetBeforeAnimationEnd == self.scrollView.contentOffset && scrollToOriginalPosition { if self.isPullingDown { self.scrollView.contentOffset.y = self.originalContentOffsetY } else { self.scrollView.contentOffset.y -= self.pullingHeight } } // Restore to original content inset only when offset is unchanged if self.contentInsetBeforeAnimationEnd == self.scrollView.contentInset { if self.isPullingDown { self.scrollView.contentInset.top -= self.pullingHeight } else { self.scrollView.contentInset.bottom -= self.pullingHeight } } } let actionClosure = { [weak self] in guard let self = self else { return } if animated { UIView.animate(withDuration: 0.4, animations: updateClosure) { _ in guard let refreshView = self.refreshView else { return } refreshView.pullToRefreshAnimationDidFinished(refreshView, direction: self.direction, animated: animated) } } else { updateClosure() refreshView.pullToRefreshAnimationDidFinished(refreshView, direction: self.direction, animated: false) } } if !scrollToOriginalPosition { // Make sure the animation run after the table view reloading DispatchQueue.main.async { actionClosure() } } else { actionClosure() } } }
mit
e7fb2fb4db82b7355f898a961807f912
32.888594
125
0.574436
6.130518
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/KeychainUtils.swift
1
1657
@objcMembers class KeychainUtils: NSObject { private let keychainUtils: SFHFKeychainUtils.Type init(keychainUtils: SFHFKeychainUtils.Type = SFHFKeychainUtils.self) { self.keychainUtils = keychainUtils } func copyKeychain(from sourceAccessGroup: String?, to destinationAccessGroup: String?, updateExisting: Bool = true) throws { let sourceItems = try keychainUtils.getAllPasswords(forAccessGroup: sourceAccessGroup) for item in sourceItems { guard let username = item["username"], let password = item["password"], let serviceName = item["serviceName"] else { continue } try keychainUtils.storeUsername(username, andPassword: password, forServiceName: serviceName, accessGroup: destinationAccessGroup, updateExisting: updateExisting) } } func password(for username: String, serviceName: String, accessGroup: String? = nil) throws -> String? { return try keychainUtils.getPasswordForUsername(username, andServiceName: serviceName, accessGroup: accessGroup) } func store(username: String, password: String, serviceName: String, accessGroup: String? = nil, updateExisting: Bool) throws { return try keychainUtils.storeUsername(username, andPassword: password, forServiceName: serviceName, accessGroup: accessGroup, updateExisting: updateExisting) } }
gpl-2.0
c72a59e5a04d3176d275f10d5bb049e6
43.783784
174
0.611346
6.091912
false
false
false
false
AshuMishra/BMSLocationFinder
BMSLocationFinder/BMSLocationFinder/Network Handler/NetworkManager.swift
1
4569
// // BMSNetworkManager.swift // BMSLocationFinder // // Created by Ashutosh on 03/04/2015. // Copyright (c) 2015 Ashutosh. All rights reserved. // import Foundation import CoreLocation import UIKit typealias LocationFetchCompletionBlock = (CLLocation?,error:NSError?) -> () typealias RequestCompletionBlock = (result: NSArray?, error: NSError?) -> () typealias PhotoRequestCompletionBlock = (image:UIImage?, error: NSError?) -> () class BMSNetworkManager : NSObject,CLLocationManagerDelegate,UIAlertViewDelegate { var currentUserLocation :CLLocation? var locationManager :CLLocationManager? var placePaginator : Paginator? //Shared Instance var locationFetchCompletionBlock : LocationFetchCompletionBlock? class var sharedInstance: BMSNetworkManager { struct Static { static var instance: BMSNetworkManager? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = BMSNetworkManager() } return Static.instance! } override init() { super.init() //Initialize Location manager to update location if (locationManager == nil) { locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBest } } func updatePlacePaginator(#radius:Int, type:NSString) { //To update your location and pass required parameter to load the page using Paginator class var coordinate : CLLocationCoordinate2D = self.currentUserLocation!.coordinate var locationString = NSString(format: "%f,%f", coordinate.latitude,coordinate.longitude) var parameterDictionary = ["location":locationString,"radius":NSString(format: "%d",radius),"types":type] self.placePaginator = Paginator(urlString: urlStruct.placeSearchURL, queryParameters: parameterDictionary) } func updateLocation() { //To check what method we use to update the location depending upon on ios version if (constantStruct.IS_OS_8_AND_ABOVE) { locationManager?.requestWhenInUseAuthorization() } var authorizationDenied: Bool = (CLLocationManager.authorizationStatus().rawValue == CLAuthorizationStatus.Denied.rawValue) if (authorizationDenied) { var alert: UIAlertView = UIAlertView(title: "Location Service Disabled", message: "To enable, please go to Settings and turn on Location Service for this app.", delegate: self, cancelButtonTitle: "Not Now", otherButtonTitles: "Enable") alert.show() } else { locationManager?.startUpdatingLocation() } } // MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { self.locationFetchCompletionBlock!(nil,error: error) } func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) { //This method is used to update the user location manager.stopUpdatingLocation() self.currentUserLocation = newLocation self.locationFetchCompletionBlock!(newLocation,error: nil) } func fetchLocation(completionBlock:LocationFetchCompletionBlock) { self.locationFetchCompletionBlock = completionBlock self.updateLocation() } func sendRequestForPhoto(photoReference:NSString,completionBlock:PhotoRequestCompletionBlock) { //Method is used for to download place image when seeing it's deatil var url = self.createPhotoURLWithParameter(photoReference) ImageDownloader.sharedInstance.fetchImage(url!, completionBlock: completionBlock) } func createPhotoURLWithParameter(photoReference:NSString)-> NSString? { //This method is used to make proper string to fetch place image. var parameters:NSString if (self.currentUserLocation != nil) { var maxwidth = NSString(format: "maxwidth=%d", 400) var photoReference = NSString(format: "photoreference=%@", photoReference) var apiParameter = NSString(format: "key=%@",urlStruct.APIKey) let URLString = urlStruct.baseURL + urlStruct.photoFetchURL + maxwidth + "&" + photoReference + "&" + apiParameter return URLString; }else { return nil; } } }
mit
3e3aeda8d999210e1c5b2227f0fa39a4
37.394958
247
0.680674
5.413507
false
false
false
false
apple/swift-nio
Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests+XCTest.swift
1
1845
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // // ApplicationProtocolNegotiationHandlerTests+XCTest.swift // import XCTest /// /// NOTE: This file was generated by generate_linux_tests.rb /// /// Do NOT edit this file directly as it will be regenerated automatically when needed. /// extension ApplicationProtocolNegotiationHandlerTests { @available(*, deprecated, message: "not actually deprecated. Just deprecated to allow deprecated tests (which test deprecated functionality) without warnings") static var allTests : [(String, (ApplicationProtocolNegotiationHandlerTests) -> () throws -> Void)] { return [ ("testChannelProvidedToCallback", testChannelProvidedToCallback), ("testIgnoresUnknownUserEvents", testIgnoresUnknownUserEvents), ("testCallbackReflectsNotificationResult", testCallbackReflectsNotificationResult), ("testCallbackNotesFallbackForNoNegotiation", testCallbackNotesFallbackForNoNegotiation), ("testNoBufferingBeforeEventFires", testNoBufferingBeforeEventFires), ("testBufferingWhileWaitingForFuture", testBufferingWhileWaitingForFuture), ("testNothingBufferedDoesNotFireReadCompleted", testNothingBufferedDoesNotFireReadCompleted), ("testUnbufferingFiresReadCompleted", testUnbufferingFiresReadCompleted), ] } }
apache-2.0
8780a2b60be0049aa8874bce89172607
44
162
0.674255
5.557229
false
true
false
false
ehtd/HackerNews
Hackyto/Hackyto/Content/ContentProvider.swift
1
3980
// // ContentProvider.swift // Hackyto // // Created by Ernesto Torres on 6/3/17. // Copyright © 2017 ehtd. All rights reserved. // import Foundation class ContentProvider { fileprivate let topListFetcher: ListFetcher fileprivate var itemFetchers = [ItemFetcher]() fileprivate let session: URLSession fileprivate let apiEndPoint: String typealias StoryList = [Story] fileprivate var stories = StoryList() fileprivate var availableStoryIds = [Int]() fileprivate(set) var errorHandler: ((Error) -> Void) = { _ in } fileprivate(set) var successHandler: ((StoryList) -> Void) = { _ in } fileprivate let contentPath: String fileprivate var fetching = false fileprivate let pageSize = 20 init(with session: URLSession, apiEndPoint: String, contentPath: String) { self.contentPath = contentPath self.session = session self.apiEndPoint = apiEndPoint topListFetcher = ListFetcher(with: session, apiEndPoint: apiEndPoint) } } fileprivate extension ContentProvider { func getStoryList(success: @escaping (([Int]) -> Void), error: @escaping ((Error) -> Void)) { stories = StoryList() topListFetcher.fetch(contentPath, success: { (response) in if let response = response as? [Int] { success(response) } }, error: error) } func fetchItems(in list: [Int]) { itemFetchers = [ItemFetcher]() var stories = Array<Story?>(repeatElement(nil, count: list.count)) var pendingItems = list.count let fetchCompleted: (() -> Void) = { [weak self] in pendingItems -= 1 if pendingItems <= 0 { let fullStories = stories.filter { $0 != nil }.map { $0! } self?.fetching = false self?.successHandler(fullStories) } } var storyIndex = 0 for item in list { let segment = "item/\(item).json" let fetcher = ItemFetcher(with: session, apiEndPoint: apiEndPoint) itemFetchers.append(fetcher) fetcher.fetch(segment, success: { [constIndex = storyIndex](response) in if let response = response as? [String: Any] { let story = Story(response as NSDictionary) stories[constIndex] = story fetchCompleted() } }, error: { (error) in fetchCompleted() }) storyIndex += 1 } } func fetchNextBatch(size: Int) { if size < availableStoryIds.count { let truncatedList = Array(availableStoryIds[0..<size]) availableStoryIds = Array(availableStoryIds[size..<availableStoryIds.count]) fetchItems(in: truncatedList) } else { fetchItems(in: availableStoryIds) availableStoryIds.removeAll() } } } extension ContentProvider { @discardableResult func onError(error: @escaping ((Error) -> Void)) -> Self { self.errorHandler = error return self } @discardableResult func onSuccess(success: @escaping (StoryList) -> Void) -> Self { self.successHandler = success return self } } extension ContentProvider { func getStories(_ number: Int) { guard fetching == false else { return } fetching = true getStoryList(success: { [weak self] (list) in if let strongSelf = self { strongSelf.availableStoryIds = list strongSelf.fetchNextBatch(size: number) } }) { [weak self] (error) in self?.fetching = false self?.errorHandler(error) } } func next() { guard fetching == false, availableStoryIds.count > 0 else { return } fetching = true fetchNextBatch(size: pageSize) } }
gpl-3.0
58330f3ebf0899d1476543b9cf75e3a6
27.421429
88
0.578789
4.788207
false
false
false
false
mnisn/zhangchu
zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendWidgetImgCell.swift
1
3779
// // RecommendWidgetImgCell.swift // zhangchu // // Created by 苏宁 on 2016/10/26. // Copyright © 2016年 suning. All rights reserved. // import UIKit class RecommendWidgetImgCell: UITableViewCell { var clickClosure:RecipClickClosure? @IBOutlet weak var scrollView: UIScrollView! var listModel:RecipeRecommendWidgetList? { didSet{ showData() } } func showData() { if listModel!.widget_data?.count > 0 { // let contentView = UIView.createView() scrollView.addSubview(contentView) contentView.snp_makeConstraints(closure: { [weak self](make) in make.edges.equalTo(self!.scrollView) make.height.equalTo(self!.scrollView) }) // var lastView:UIView? = nil for i in 0 ..< (listModel!.widget_data?.count)! { let data = listModel!.widget_data![i] // let tmpImgView = UIImageView() if data.type == "image" { tmpImgView.kf_setImageWithURL(NSURL(string: data.content!), placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) contentView.addSubview(tmpImgView) tmpImgView.userInteractionEnabled = true tmpImgView.tag = 450 + i let tap = UITapGestureRecognizer(target: self, action: #selector(imgTapClick(_:))) tmpImgView.addGestureRecognizer(tap) tmpImgView.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(contentView) make.width.equalTo(210) if i == 0 { make.left.equalTo(contentView) } else { make.left.equalTo((lastView?.snp_right)!) } }) // lastView = tmpImgView } } // contentView.snp_makeConstraints(closure: { (make) in make.right.equalTo(lastView!) }) scrollView.showsHorizontalScrollIndicator = false } } func imgTapClick(tap:UITapGestureRecognizer) { let index = (tap.view?.tag)! - 450 let data = listModel?.widget_data![index] if clickClosure != nil && data?.link != nil { clickClosure!((data?.link)!) } } //创建cell class func createWidgetImgCell(tableView: UITableView, atIndexPath indexPath:NSIndexPath, listModel:RecipeRecommendWidgetList?) ->RecommendWidgetImgCell { let cellID = "RecommendWidgetImgCell" var cell = tableView.dequeueReusableCellWithIdentifier(cellID) as? RecommendWidgetImgCell if cell == nil { cell = NSBundle.mainBundle().loadNibNamed("RecommendWidgetImgCell", owner: nil, options: nil).last as? RecommendWidgetImgCell } cell?.listModel = listModel! return cell! } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
c1cd7f618cb61e4cbf92ec8d8022bc57
30.932203
192
0.507962
5.761468
false
false
false
false
milseman/swift
test/attr/attributes.swift
4
9914
// RUN: %target-typecheck-verify-swift @unknown func f0() {} // expected-error{{unknown attribute 'unknown'}} @unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}} enum binary { case Zero case One init() { self = .Zero } } func f5(x: inout binary) {} //===--- //===--- IB attributes //===--- @IBDesignable class IBDesignableClassTy { @IBDesignable func foo() {} // expected-error {{@IBDesignable cannot be applied to this declaration}} {{3-17=}} } @IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}} struct IBDesignableStructTy {} @IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}} protocol IBDesignableProtTy {} @IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}} extension IBDesignableStructTy {} class IBDesignableClassExtensionTy {} @IBDesignable // okay extension IBDesignableClassExtensionTy {} class Inspect { @IBInspectable var value : Int = 0 // okay @GKInspectable var value2: Int = 0 // okay @IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}} @GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}} @IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}} @GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}} } @IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}} @GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}} func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}} func foo(x: @convention(block) (Int) -> Int) {} @_transparent func zim() {} @_transparent func zung<T>(_: T) {} @_transparent // expected-error{{@_transparent cannot be applied to stored properties}} {{1-15=}} var zippity : Int func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}} protocol ProtoWithTransparent { @_transparent// expected-error{{@_transparent is not supported on declarations within protocols}} {{3-16=}} func transInProto() } class TestTranspClass : ProtoWithTransparent { @_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}} init () {} @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{3-17=}} deinit {} @_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}} class func transStatic() {} @_transparent// expected-error{{@_transparent is not supported on declarations within classes}} {{3-16=}} func transInProto() {} } struct TestTranspStruct : ProtoWithTransparent{ @_transparent init () {} @_transparent init <T> (x : T) { } @_transparent static func transStatic() {} @_transparent func transInProto() {} } @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}} struct CannotHaveTransparentStruct { func m1() {} } @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}} extension TestTranspClass { func tr1() {} } @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}} extension TestTranspStruct { func tr1() {} } @_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}} extension binary { func tr1() {} } class transparentOnClassVar { @_transparent var max: Int { return 0xFF }; // expected-error {{@_transparent is not supported on declarations within classes}} {{3-17=}} func blah () { var _: Int = max } }; class transparentOnClassVar2 { var max: Int { @_transparent // expected-error {{@_transparent is not supported on declarations within classes}} {{5-19=}} get { return 0xFF } } func blah () { var _: Int = max } }; @thin // expected-error {{attribute can only be applied to types, not declarations}} func testThinDecl() -> () {} protocol Class : class {} protocol NonClass {} @objc class Ty0 : Class, NonClass { init() { } } // Attributes that should be reported by parser as unknown // See rdar://19533915 @__accessibility struct S__accessibility {} // expected-error{{unknown attribute '__accessibility'}} @__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}} @__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}} weak var weak0 : Ty0? weak var weak0x : Ty0? weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned var weak3 : Ty0 unowned var weak3a : Ty0 unowned(safe) var weak3b : Ty0 unowned(unsafe) var weak3c : Ty0 unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}} weak var weak6 : Int? // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}} unowned var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}} weak var weak8 : Class? = Ty0() unowned var weak9 : Class = Ty0() weak var weak10 : NonClass? = Ty0() // expected-error {{'weak' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak11 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak12 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} unowned var weak13 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}} weak var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}} weak var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}} weak var weak16 : Class! @weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}} @_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} @_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}} // Function result type attributes. var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}} func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}} return 4 } func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected parameter type following ':'}} func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected ',' separator}} {{47-47=,}} expected-error {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }} func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren. // @thin is not supported except in SIL. var thinFunc : @thin () -> () // expected-error {{attribute is not supported}} @inline(never) func nolineFunc() {} @inline(never) var noinlineVar : Int // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}} @inline(never) class FooClass { // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}} } @inline(__always) func AlwaysInlineFunc() {} @inline(__always) var alwaysInlineVar : Int // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}} @inline(__always) class FooClass2 { // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}} } class A { @inline(never) init(a : Int) {} var b : Int { @inline(never) get { return 42 } @inline(never) set { } } } class B { @inline(__always) init(a : Int) {} var b : Int { @inline(__always) get { return 42 } @inline(__always) set { } } } class SILStored { @sil_stored var x : Int = 42 // expected-error {{'sil_stored' only allowed in SIL modules}} } @_show_in_interface protocol _underscored {} @_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
apache-2.0
004df819d1a17e77d54e735019b61d6a
39.465306
256
0.693565
3.889368
false
false
false
false
milseman/swift
test/SILGen/tuples.swift
4
7189
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class C {} enum Foo { case X(C, Int) } // <rdar://problem/16020428> // CHECK-LABEL: sil hidden @_T06tuples8matchFooyAA0C0O1x_tF func matchFoo(x x: Foo) { switch x { case .X(let x): () } } protocol P { func foo() } struct A : P { func foo() {} } func make_int() -> Int { return 0 } func make_p() -> P { return A() } func make_xy() -> (x: Int, y: P) { return (make_int(), make_p()) } // CHECK-LABEL: sil hidden @_T06tuples17testShuffleOpaqueyyF func testShuffleOpaque() { // CHECK: [[X:%.*]] = alloc_box ${ var P } // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK: [[Y:%.*]] = alloc_box ${ var Int } // CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[T0:%.*]] = function_ref @_T06tuples7make_xySi1x_AA1P_p1ytyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[PBX]]) // CHECK-NEXT: store [[T1]] to [trivial] [[PBY]] var (x,y) : (y:P, x:Int) = make_xy() // CHECK-NEXT: [[PAIR:%.*]] = alloc_box ${ var (y: P, x: Int) } // CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]] // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06tuples7make_xySi1x_AA1P_p1ytyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[PAIR_0]]) // CHECK-NEXT: store [[T1]] to [trivial] [[PAIR_1]] var pair : (y:P, x:Int) = make_xy() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06tuples7make_xySi1x_AA1P_p1ytyF // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $P // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBPAIR]] : $*(y: P, x: Int) // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[TEMP]] to [[PAIR_0]] // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 1 // CHECK-NEXT: assign [[T1]] to [[PAIR_1]] // CHECK-NEXT: end_access [[WRITE]] : $*(y: P, x: Int) // CHECK-NEXT: dealloc_stack [[TEMP]] pair = make_xy() } // CHECK-LABEL: testShuffleTuple func testShuffleTuple() { // CHECK: [[X:%.*]] = alloc_box ${ var P } // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK: [[Y:%.*]] = alloc_box ${ var Int } // CHECK-NEXT: [[PBY:%.*]] = project_box [[Y]] // CHECK: [[T0:%.*]] = function_ref @_T06tuples8make_intSiyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [trivial] [[PBY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06tuples6make_pAA1P_pyF // CHECK-NEXT: apply [[T0]]([[PBX]]) var (x,y) : (y:P, x:Int) = (x: make_int(), y: make_p()) // CHECK-NEXT: [[PAIR:%.*]] = alloc_box ${ var (y: P, x: Int) } // CHECK-NEXT: [[PBPAIR:%.*]] = project_box [[PAIR]] // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 0 // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[PBPAIR]] : $*(y: P, x: Int), 1 // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_T06tuples8make_intSiyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]() // CHECK-NEXT: store [[T1]] to [trivial] [[PAIR_1]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06tuples6make_pAA1P_pyF // CHECK-NEXT: apply [[T0]]([[PAIR_0]]) var pair : (y:P, x:Int) = (x: make_int(), y: make_p()) // This isn't really optimal; we should be evaluating make_p directly // into the temporary. // CHECK-NEXT: // function_ref // CHECK: [[T0:%.*]] = function_ref @_T06tuples8make_intSiyF // CHECK-NEXT: [[INT:%.*]] = apply [[T0]]() // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_T06tuples6make_pAA1P_pyF // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $P // CHECK-NEXT: apply [[T0]]([[TEMP]]) // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBPAIR]] : $*(y: P, x: Int) // CHECK-NEXT: [[PAIR_0:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 0 // CHECK-NEXT: copy_addr [take] [[TEMP]] to [[PAIR_0]] // CHECK-NEXT: [[PAIR_1:%.*]] = tuple_element_addr [[WRITE]] : $*(y: P, x: Int), 1 // CHECK-NEXT: assign [[INT]] to [[PAIR_1]] // CHECK-NEXT: end_access [[WRITE]] : $*(y: P, x: Int) // CHECK-NEXT: dealloc_stack [[TEMP]] pair = (x: make_int(), y: make_p()) } enum GenericEnum<T> { case one(T) static var callback: (T) -> Void { fatalError() } } // CHECK-LABEL: _T06tuples16testTupleUnsplatyyF func testTupleUnsplat() { // CHECK: debug_value [[X:%.+]] : $Int, let, name "x" // CHECK: debug_value [[Y:%.+]] : $Int, let, name "y" let x = 1, y = 2 // CHECK: [[TUPLE:%.+]] = tuple ([[X]] : $Int, [[Y]] : $Int) // CHECK: enum $GenericEnum<(Int, Int)>, #GenericEnum.one!enumelt.1, [[TUPLE]] _ = GenericEnum<(Int, Int)>.one((x, y)) // CHECK: [[TUPLE:%.+]] = tuple ([[X]] : $Int, [[Y]] : $Int) // CHECK: enum $GenericEnum<(Int, Int)>, #GenericEnum.one!enumelt.1, [[TUPLE]] _ = GenericEnum<(Int, Int)>.one(x, y) // CHECK: [[THUNK:%.+]] = function_ref @_T0Si_SitIxi_S2iIxyy_TR // CHECK: [[REABSTRACTED:%.+]] = partial_apply [[THUNK]]({{%.+}}) // CHECK: apply [[REABSTRACTED]]([[X]], [[Y]]) _ = GenericEnum<(Int, Int)>.callback((x, y)) // CHECK: [[THUNK:%.+]] = function_ref @_T0Si_SitIxi_S2iIxyy_TR // CHECK: [[REABSTRACTED:%.+]] = partial_apply [[THUNK]]({{%.+}}) // CHECK: apply [[REABSTRACTED]]([[X]], [[Y]]) _ = GenericEnum<(Int, Int)>.callback(x, y) } // CHECK: end sil function '_T06tuples16testTupleUnsplatyyF' // Make sure that we use a load_borrow instead of a load [take] when RValues are // formed with isGuaranteed set. extension P { // CHECK-LABEL: sil hidden @_T06tuples1PPAAE12immutableUseyAA1CC5index_x5valuet5tuple_tFZ // CHECK: bb0([[TUP0:%.*]] : $C, [[TUP1:%.*]] : $*Self // Allocate space for the RValue. // CHECK: [[RVALUE:%.*]] = alloc_stack $(index: C, value: Self), let, name "tuple" // // Initialize the RValue. (This is here to help pattern matching). // CHECK: [[ZERO_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 0 // CHECK: store [[TUP0]] to [init] [[ZERO_ADDR]] // CHECK: [[ONE_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 1 // CHECK: copy_addr [take] [[TUP1]] to [initialization] [[ONE_ADDR]] // // What we are actually trying to check. Note that there is no actual use of // LOADED_CLASS. This is b/c of the nature of the RValue we are working with. // CHECK: [[ZERO_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 0 // CHECK: [[LOADED_CLASS:%.*]] = load_borrow [[ZERO_ADDR]] // CHECK: [[ONE_ADDR:%.*]] = tuple_element_addr [[RVALUE]] : $*(index: C, value: Self), 1 // CHECK: apply {{.*}}([[ONE_ADDR]]) : $@convention(witness_method) // CHECK: end_borrow [[LOADED_CLASS]] from [[ZERO_ADDR]] // CHECK: destroy_addr [[RVALUE]] // CHECK: dealloc_stack [[RVALUE]] public static func immutableUse(tuple: (index: C, value: Self)) -> () { return tuple.value.foo() } }
apache-2.0
03a110532fae735d00ab79238502429f
43.376543
94
0.556962
2.980514
false
false
false
false
achappell/dungeonsanddragonscharactersheet
DungeonsDragonsCCTests/Models/Mapping/AbilityScoreFEMMappingTests.swift
1
1600
// // Races+FEMMappingTests.swift // DungeonsDragonsCC // // Created by Amanda Chappell on 3/5/16. // Copyright © 2016 AmplifiedProjects. All rights reserved. // import XCTest @testable import DungeonsDragonsCC class AbilityScoreFEMMappingTests: 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 testFEMMapping() { let bundle = Bundle(for: AbilityScoreFEMMappingTests.self) let path = bundle.path(forResource: "testcorerulebook", ofType: "json") let data = try? Data(contentsOf: URL(fileURLWithPath: path!)) do { let JSONDict = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:AnyObject] let deserializer = JSONDeserializer() if let book = JSONDict["coreRulebook"] as? [String: AnyObject], let races = book["races"] as? [[String: AnyObject]], let modifiers = races[0]["modifiers"] as? [[String:Int]] { let modifier = deserializer.objectFromDictionary(modifiers[0] as [String : AnyObject], classType: AbilityScore.self)! as AbilityScore XCTAssertEqual(modifier.baseScore, 2) XCTAssertEqual(modifier.type, AbilityType.constitution.rawValue) } } catch { } } }
mit
fbbc45a61d53400907603d065c40cd5e
33.021277
187
0.664165
4.491573
false
true
false
false
rodrigobell/twitter-clone
twitter-clone/ComposeViewController.swift
1
2665
// // ComposeViewController.swift // twitter-clone // // Created by Rodrigo Bell on 2/27/17. // Copyright © 2017 Rodrigo Bell. All rights reserved. // import UIKit class ComposeViewController: UIViewController, UITextViewDelegate { var tweet: Tweet? var message: String = "" var isReply: Bool? @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var composeTextView: UITextView! @IBOutlet weak var tweetButton: UIButton! @IBOutlet weak var characterCount: UILabel! override func viewDidLoad() { super.viewDidLoad() composeTextView.delegate = self composeTextView.becomeFirstResponder() profileImageView.setImageWith((User._currentUser?.profileImageURL)!) profileImageView.layer.cornerRadius = 3 profileImageView.clipsToBounds = true tweetButton.layer.cornerRadius = 5 if (isReply) == true { composeTextView.text = "@\((tweet?.user?.handle)!) " isReply = false } characterCount.text = "\(140 - composeTextView.text!.characters.count)" } @IBAction func onTweetButtonTapped(_ sender: Any) { self.message = composeTextView.text let escapedTweetMessage = self.message.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) if isReply == true { TwitterClient.sharedInstance.reply(escapedTweet: escapedTweetMessage!, statusID: tweet!.id!, params: nil , completion: { (error) -> () in }) isReply = false self.dismiss(animated: true, completion: {}); } else { TwitterClient.sharedInstance.compose(escapedTweet: escapedTweetMessage!, params: nil, completion: { (error) -> () in }) self.dismiss(animated: true, completion: {}); } } func textViewDidChange(_ textView: UITextView) { if 0 < (141 - composeTextView.text!.characters.count) { tweetButton.backgroundColor = UIColor(red: 85.0/255.0, green: 172.0/255.0, blue: 253.0/255.0, alpha: 1.0) tweetButton.isEnabled = true characterCount.textColor = UIColor.darkGray characterCount.text = "\(140 - composeTextView.text!.characters.count)" } else { tweetButton.backgroundColor = UIColor.lightGray tweetButton.isEnabled = false characterCount.textColor = UIColor.red characterCount.text = "\(140 - composeTextView.text!.characters.count)" } } @IBAction func didTapExit(_ sender: Any) { self.dismiss(animated: true, completion: {}); } }
mit
1a6efd2bb89d16cd6673c9c151a771b1
35.493151
152
0.637012
5.016949
false
false
false
false
SAP/SAPJamSampleCode
iOS_Integrations/mobile-sdk-ios/Swift 2.x/SAPJamSDK/SAPJamSDK/GroupsListViewController.swift
1
1835
// // GroupsListViewController.swift // SAPJamSDK // // Copyright © 2016 SAP SE. All rights reserved. // import UIKit import OAuthSwift class GroupsListViewController: UITableViewController { private var groups = [] override func viewDidLoad() { super.viewDidLoad() loadGroupsFromServer() } private func loadGroupsFromServer() { let jamSession = JamAuthConfig.sharedInstance let urlStr = jamSession.getServerUrl() + "/api/v1/OData/Groups?$select=Id,Name" jamSession.oauthswift!.client.get(urlStr, headers: ["Accept": "application/json"], success: { data, response in do { let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary // Display the list of groups self.groups = jsonResult["d"]!["results"] as! NSArray self.tableView.reloadData() } catch let error { print(error) } }, failure: { error in print(error) } ) } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return groups.count } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let group = self.groups[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier("cell") cell?.textLabel?.text = group["Name"]! as? String return cell! } }
apache-2.0
c9d87ceb0d242e3f33144e21d25451d5
27.65625
165
0.561614
5.507508
false
false
false
false
justindarc/firefox-ios
StorageTests/TestBrowserDB.swift
8
7718
/* 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 @testable import Storage import XCGLogger import XCTest private let log = XCGLogger.default class TestBrowserDB: XCTestCase { let files = MockFiles() fileprivate func rm(_ path: String) { do { try files.remove(path) } catch { } } override func setUp() { super.setUp() rm("foo.db") rm("foo.db-shm") rm("foo.db-wal") rm("foo.db.bak.1") rm("foo.db.bak.1-shm") rm("foo.db.bak.1-wal") } class MockFailingSchema: Schema { var name: String { return "FAILURE" } var version: Int { return BrowserSchema.DefaultVersion + 1 } func drop(_ db: SQLiteDBConnection) -> Bool { return true } func create(_ db: SQLiteDBConnection) -> Bool { return false } func update(_ db: SQLiteDBConnection, from: Int) -> Bool { return false } } fileprivate class MockListener { var notification: Notification? @objc func onDatabaseWasRecreated(_ notification: Notification) { self.notification = notification } } func testUpgradeV33toV34RemovesLongURLs() { let db = BrowserDB(filename: "v33.db", schema: BrowserSchema(), files: SupportingFiles()) let results = db.runQuery("SELECT bmkUri, title FROM bookmarksLocal WHERE type = 1", args: nil, factory: { row in (row[0] as! String, row[1] as! String) }).value.successValue! // The bookmark with the long URL has been deleted. XCTAssertTrue(results.count == 1) let remaining = results[0]! // This one's title has been truncated to 4096 chars. XCTAssertEqual(remaining.1.count, 4096) XCTAssertEqual(remaining.1.utf8.count, 4096) XCTAssertTrue(remaining.1.hasPrefix("abcdefghijkl")) XCTAssertEqual(remaining.0, "http://example.com/short") } func testMovesDB() { var db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // Grab a pointer to the -shm so we can compare later. let shmAAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationA = shmAAttributes[FileAttributeKey.creationDate] as! Date let inodeA = (shmAAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertFalse(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) let center = NotificationCenter.default let listener = MockListener() center.addObserver(listener, selector: #selector(MockListener.onDatabaseWasRecreated), name: .DatabaseWasRecreated, object: nil) defer { center.removeObserver(listener) } // It'll still fail, but it moved our old DB. // Our current observation is that closing the DB deletes the .shm file and also // checkpoints the WAL. db.forceClose() db = BrowserDB(filename: "foo.db", schema: MockFailingSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").failed() // This won't actually write since we'll get a failed connection db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (bar TEXT)").succeeded() // Just so we have writes in the WAL. XCTAssertTrue(files.exists("foo.db")) XCTAssertTrue(files.exists("foo.db-shm")) XCTAssertTrue(files.exists("foo.db-wal")) // But now it's been reopened, it's not the same -shm! let shmBAttributes = try! files.attributesForFileAt(relativePath: "foo.db-shm") let creationB = shmBAttributes[FileAttributeKey.creationDate] as! Date let inodeB = (shmBAttributes[FileAttributeKey.systemFileNumber] as! NSNumber).uintValue XCTAssertTrue(creationA.compare(creationB) != ComparisonResult.orderedDescending) XCTAssertNotEqual(inodeA, inodeB) XCTAssertTrue(files.exists("foo.db.bak.1")) XCTAssertFalse(files.exists("foo.db.bak.1-shm")) XCTAssertFalse(files.exists("foo.db.bak.1-wal")) // The right notification was issued. XCTAssertEqual("foo.db", (listener.notification?.object as? String)) } func testConcurrentQueries() { let expectation = self.expectation(description: "Got all DB results") var db = BrowserDB(filename: "foo.db", schema: BrowserSchema(), files: self.files) db.run("CREATE TABLE foo (id INTEGER PRIMARY KEY AUTOINCREMENT, bar TEXT)").succeeded() // Just so we have writes in the WAL. _ = db.withConnection { connection -> Void in for i in 0..<1000 { let args: Args = ["bar \(i)"] try connection.executeChange("INSERT INTO foo (bar) VALUES (?)", withArgs: args) } } func fooBarFactory(_ row: SDRow) -> [String : Any] { var result: [String : Any] = [:] result["id"] = row["id"] result["bar"] = row["bar"] return result } let longQuery = db.runQuery("SELECT * FROM (SELECT * FROM (SELECT * FROM foo WHERE bar LIKE ?) WHERE bar LIKE ?) WHERE bar LIKE ?", args: ["%b%", "%a%", "%r%"], factory: fooBarFactory) let shortConcurrentQuery = db.runQueryConcurrently("SELECT * FROM foo LIMIT 1", args: nil, factory: fooBarFactory) var isLongQueryDone = false var isShortConcurrentQueryDone = false var longQueryRuntimeDuration: Timestamp = 0 var shortConcurrentQueryRuntimeDuration: Timestamp = 0 let longQueryStartTimestamp = Date.now() let longQueryResult = longQuery.bind { result -> Deferred<Maybe<[[String : Any]]>> in if let results = result.successValue?.asArray() { isLongQueryDone = true longQueryRuntimeDuration = Date.now() - longQueryStartTimestamp XCTAssertTrue(isShortConcurrentQueryDone) return deferMaybe(results) } return deferMaybe(DatabaseError(description: "Unable to execute long-running query")) } let shortConcurrentQueryStartTimestamp = Date.now() let shortConcurrentQueryResult = shortConcurrentQuery.bind { result -> Deferred<Maybe<[[String : Any]]>> in if let results = result.successValue?.asArray() { isShortConcurrentQueryDone = true shortConcurrentQueryRuntimeDuration = Date.now() - shortConcurrentQueryStartTimestamp XCTAssertFalse(isLongQueryDone) return deferMaybe(results) } return deferMaybe(DatabaseError(description: "Unable to execute concurrent short-running query")) } _ = all([longQueryResult, shortConcurrentQueryResult]).bind { results -> Success in XCTAssert(longQueryRuntimeDuration > shortConcurrentQueryRuntimeDuration, "Long query runtime duration should be greater than short concurrent query runtime duration") expectation.fulfill() return succeed() } waitForExpectations(timeout: 10, handler: nil) } }
mpl-2.0
3517d1f8d528dc8b5e099ab7987462e4
40.494624
192
0.636823
4.602266
false
false
false
false
xedin/swift
stdlib/public/core/StringLegacy.swift
4
6830
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string representing the given string repeated the specified /// number of times. /// /// For example, you can use this initializer to create a string with ten /// `"ab"` strings in a row. /// /// let s = String(repeating: "ab", count: 10) /// print(s) /// // Prints "abababababababababab" /// /// - Parameters: /// - repeatedValue: The string to repeat. /// - count: The number of times to repeat `repeatedValue` in the resulting /// string. public init(repeating repeatedValue: String, count: Int) { precondition(count >= 0, "Negative count not allowed") guard count > 1 else { self = count == 0 ? "" : repeatedValue return } // TODO(String performance): We can directly call appendInPlace var result = String() result.reserveCapacity(repeatedValue._guts.count &* count) for _ in 0..<count { result += repeatedValue } self = result } /// A Boolean value indicating whether a string has no characters. @inlinable public var isEmpty: Bool { @inline(__always) get { return _guts.isEmpty } } } extension StringProtocol { /// Returns a Boolean value indicating whether the string begins with the /// specified prefix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let cafe = "Café du Monde" /// /// // Case sensitive /// print(cafe.hasPrefix("café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode extended grapheme clusters /// rather than the code points used to compose them. The example below uses /// two strings with different forms of the `"é"` character---the first uses /// the composed form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "Café" /// let decomposedCafe = "Cafe\u{0301}" /// /// print(cafe.hasPrefix(composedCafe)) /// // Prints "true" /// print(cafe.hasPrefix(decomposedCafe)) /// // Prints "true" /// /// - Parameter prefix: A possible prefix to test against this string. /// - Returns: `true` if the string begins with `prefix`; otherwise, `false`. @inlinable public func hasPrefix<Prefix: StringProtocol>(_ prefix: Prefix) -> Bool { return self.starts(with: prefix) } /// Returns a Boolean value indicating whether the string ends with the /// specified suffix. /// /// The comparison is both case sensitive and Unicode safe. The /// case-sensitive comparison will only match strings whose corresponding /// characters have the same case. /// /// let plans = "Let's meet at the café" /// /// // Case sensitive /// print(plans.hasSuffix("Café")) /// // Prints "false" /// /// The Unicode-safe comparison matches Unicode extended grapheme clusters /// rather than the code points used to compose them. The example below uses /// two strings with different forms of the `"é"` character---the first uses /// the composed form and the second uses the decomposed form. /// /// // Unicode safe /// let composedCafe = "café" /// let decomposedCafe = "cafe\u{0301}" /// /// print(plans.hasSuffix(composedCafe)) /// // Prints "true" /// print(plans.hasSuffix(decomposedCafe)) /// // Prints "true" /// /// - Parameter suffix: A possible suffix to test against this string. /// - Returns: `true` if the string ends with `suffix`; otherwise, `false`. @inlinable public func hasSuffix<Suffix: StringProtocol>(_ suffix: Suffix) -> Bool { return self.reversed().starts(with: suffix.reversed()) } } extension String { public func hasPrefix(_ prefix: String) -> Bool { if _fastPath(self._guts.isNFCFastUTF8 && prefix._guts.isNFCFastUTF8) { guard prefix._guts.count <= self._guts.count else { return false } return prefix._guts.withFastUTF8 { nfcPrefix in let prefixEnd = nfcPrefix.count return self._guts.withFastUTF8(range: 0..<prefixEnd) { nfcSlicedSelf in return _binaryCompare(nfcSlicedSelf, nfcPrefix) == 0 } } } return starts(with: prefix) } public func hasSuffix(_ suffix: String) -> Bool { if _fastPath(self._guts.isNFCFastUTF8 && suffix._guts.isNFCFastUTF8) { guard suffix._guts.count <= self._guts.count else { return false } return suffix._guts.withFastUTF8 { nfcSuffix in let suffixStart = self._guts.count - nfcSuffix.count return self._guts.withFastUTF8(range: suffixStart..<self._guts.count) { nfcSlicedSelf in return _binaryCompare(nfcSlicedSelf, nfcSuffix) == 0 } } } return self.reversed().starts(with: suffix.reversed()) } } // Conversions to string from other types. extension String { /// Creates a string representing the given value in base 10, or some other /// specified base. /// /// The following example converts the maximal `Int` value to a string and /// prints its length: /// /// let max = String(Int.max) /// print("\(max) has \(max.count) digits.") /// // Prints "9223372036854775807 has 19 digits." /// /// Numerals greater than 9 are represented as Roman letters. These letters /// start with `"A"` if `uppercase` is `true`; otherwise, with `"a"`. /// /// let v = 999_999 /// print(String(v, radix: 2)) /// // Prints "11110100001000111111" /// /// print(String(v, radix: 16)) /// // Prints "f423f" /// print(String(v, radix: 16, uppercase: true)) /// // Prints "F423F" /// /// - Parameters: /// - value: The value to convert to a string. /// - radix: The base to use for the string representation. `radix` must be /// at least 2 and at most 36. The default is 10. /// - uppercase: Pass `true` to use uppercase letters to represent numerals /// greater than 9, or `false` to use lowercase letters. The default is /// `false`. public init<T : BinaryInteger>( _ value: T, radix: Int = 10, uppercase: Bool = false ) { self = value._description(radix: radix, uppercase: uppercase) } }
apache-2.0
45437352fd1c5f56728699b2c5a370f4
35.095238
80
0.62489
4.211111
false
false
false
false
GabrielAraujo/VaporMongo
Sources/App/Models/User.swift
1
5345
// // User.swift // MongoTest // // Created by Gabriel Araujo on 05/11/16. // // import Vapor import Fluent import Foundation import VaporJWT final class User: Model { var id: Node? var data: Node? var username:String? var password: String? var accessToken:String? var exists: Bool = false enum Error: Swift.Error { case userNotFound case registerNotSupported case unsupportedCredentials } init(id: Node) { self.id = id } init(data: Node) { self.data = data } init(node: Node, in context: Context) throws { self.id = nil self.data = try node.extract("data") self.username = try node.extract("username") self.password = try node.extract("password") self.accessToken = try node.extract("access_token") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "id": id, "data": data, "username": username, "password": password, "access_token": accessToken ]) } static func prepare(_ database: Database) throws { // } static func revert(_ database: Database) throws { // } } import Auth extension User: Auth.User { static func authenticate(credentials: Credentials) throws -> Auth.User { let user: User? switch credentials { //case let id as Identifier: case _ as Identifier: //user = try User.find(id.id) throw Errors.registrationPerIdNotFound //throw Abort.custom(status: .badRequest, message: "Registration per id not implemented!") case let accessToken as AccessToken: //Queries for the user user = try User.query().filter("access_token", accessToken.string).first() //Validate if the user was fetched guard let u = user else { //If not throw error throw Errors.userNotFound //throw Abort.custom(status: .badRequest, message: "User not found") } guard let accessToken = u.accessToken, let username = u.username, let password = u.password else { throw Errors.missingUsernameOrPasswordOrAccessToken //throw Abort.custom(status: .badRequest, message: "User found - Missing info") } //Create a token based with the one stored in the db let jwt = try JWT(token: accessToken) if try jwt.verifySignatureWith(HS256(key: "\(username)\(password)")) { return u }else{ throw Errors.invalidToken //throw Abort.custom(status: .badRequest, message: "Invalid token") } case let apiKey as APIKey: user = try User.query().filter("username", apiKey.id).filter("password", apiKey.secret).first() //Validate if the user was fetched guard var u = user else { //If not throw error throw Errors.userNotFound //throw Abort.custom(status: .badRequest, message: "User not found") } guard let username = u.username, let password = u.password else { throw Errors.missingUsernameOrPassword } let jwt = try JWT(payload: Node([ExpirationTimeClaim(60, leeway: 10)]), signer: HS256(key: "\(username)\(password)")) let token = try jwt.createToken() u.accessToken = token try u.save() return u default: throw Errors.invalidCredentials //throw Abort.custom(status: .badRequest, message: "Invalid credentials.") } } static func register(credentials: Credentials) throws -> Auth.User { let user: User? switch credentials { case _ as Identifier: throw Abort.custom(status: .badRequest, message: "Registration per id not implemented!") case _ as AccessToken: throw Abort.custom(status: .badRequest, message: "Registration per access_token not implemented!") case let apiKey as APIKey: user = try User.query().filter("email", apiKey.id).filter("password", apiKey.secret).first() default: throw Errors.invalidCredentials //throw Abort.custom(status: .badRequest, message: "Invalid credentials.") } guard let u = user else { throw Errors.userNotFound //throw Abort.custom(status: .badRequest, message: "User not found") } return u //throw Abort.custom(status: .badRequest, message: "Register not supported.") } } import HTTP extension Request { func authUser() throws -> User { guard let user = try auth.user() as? User else { throw Errors.invalidUser //throw Abort.custom(status: .badRequest, message: "Invalid user type.") } return user } }
mit
28d210755a52c5ad2ae20d8aa846d939
30.25731
129
0.546679
4.930812
false
false
false
false
stuart-grey/shinobicharts-style-guide
case-studies/StyleGuru/StyleGuru/sport/RunningStyling.swift
1
2197
// // Copyright 2015 Scott Logic // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation extension AxisStyler { static func runningXAxis() -> SChartAxis { let axis = SChartNumberAxis() axis.enableTouch() return axis } static func runningElevationYAxis() -> SChartAxis { let axis = SChartNumberAxis() axis.enableTouch() axis.axisPosition = SChartAxisPositionReverse axis.rangePaddingHigh = 1500 // Want to see tick marks. Set their colour, thickness and length axis.style.majorTickStyle.showTicks = true axis.style.majorTickStyle.lineWidth = 0.5 axis.style.majorTickStyle.lineLength = 20 axis.style.majorTickStyle.lineColor = UIColor.blackColor() return axis } static func runningPaceYAxis() -> SChartAxis { let axis = SChartNumberAxis() axis.rangePaddingLow = 5 return axis } } private extension SChartAxis { func enableTouch() { enableGesturePanning = true enableGestureZooming = true enableMomentumPanning = true enableMomentumZooming = true } } extension AxisStyler { static func hideOutOfRangeTickMark(tickMark: SChartTickMark, axis: SChartAxis) { if !axis.visibleRange().contains(tickMark.value) { tickMark.disableTick(axis) if let tickMarkView = tickMark.tickMarkView { tickMarkView.hidden = true } } } static func negateTickMarkLabelsForTickMark(tickMark: SChartTickMark, axis: SChartAxis) { let negatedValue = -tickMark.value if let tickLabel = tickMark.tickLabel, let formatter = axis.labelFormatter { tickLabel.text = formatter.stringForObjectValue(negatedValue, onAxis: axis) } } }
apache-2.0
0472cfd316b7ceb94da85c205323333a
27.907895
91
0.718252
4.307843
false
false
false
false
groue/GRMustache.swift
Sources/Logger.swift
4
3721
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation extension StandardLibrary { /// StandardLibrary.Logger is a tool intended for debugging templates. /// /// It logs the rendering of variable and section tags such as `{{name}}` /// and `{{#name}}...{{/name}}`. /// /// To activate logging, add a Logger to the base context of a template: /// /// let template = try! Template(string: "{{name}} died at {{age}}.") /// /// // Logs all tag renderings with print: /// let logger = StandardLibrary.Logger() { print($0) } /// template.extendBaseContext(logger) /// /// // Render /// let data = ["name": "Freddy Mercury", "age": 45] /// let rendering = try! template.render(data) /// /// // Prints: /// // {{name}} at line 1 did render "Freddy Mercury" as "Freddy Mercury" /// // {{age}} at line 1 did render 45 as "45" public final class Logger : MustacheBoxable { /// Creates a Logger. /// /// - parameter log: A closure that takes a String. Default one logs that /// string with NSLog(). public init(_ log: ((String) -> Void)? = nil) { if let log = log { self.log = log } else { self.log = { NSLog($0) } } } /// Logger adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. public var mustacheBox: MustacheBox { return MustacheBox( willRender: { (tag, box) in if tag.type == .section { self.log("\(self.indentationPrefix)\(tag) will render \(box.valueDescription)") self.indentationLevel += 1 } return box }, didRender: { (tag, box, string) in if tag.type == .section { self.indentationLevel -= 1 } if let string = string { self.log("\(self.indentationPrefix)\(tag) did render \(box.valueDescription) as \(string.debugDescription)") } } ) } var indentationPrefix: String { return String(repeating: " ", count: indentationLevel * 2) } fileprivate let log: (String) -> Void fileprivate var indentationLevel: Int = 0 } }
mit
51b807bbe730f4081acf82c369e6d982
39.879121
132
0.570968
4.875491
false
false
false
false
ijovi23/JvPunchIO
JvPunchIO-Recorder/JvPunchIO-Recorder/View/PRModifyRecordView.swift
1
1831
// // PRModifyRecordView.swift // JvPunchIO-Recorder // // Created by Jovi Du on 25/10/2016. // Copyright © 2016 org.Jovistudio. All rights reserved. // import UIKit protocol PRModifyRecordViewDelegate: class { func modifyRecordView(_ modifyRecordView: PRModifyRecordView, didModify date: Date) } class PRModifyRecordView: UIView { weak var delegate: PRModifyRecordViewDelegate? @IBOutlet weak var mainView: UIView! @IBOutlet weak var btnClose: UIButton! @IBOutlet weak var picker: UIDatePicker! @IBOutlet weak var btnModify: UIButton! func show(withDate date: Date) { if superview == nil { UIApplication.shared.keyWindow?.addSubview(self) } picker.setDate(date, animated: false) let sWidth = bounds.size.width let sHeight = bounds.size.height self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight + mainView.bounds.height / 2)) self.alpha = 0 UIView.animate(withDuration: 0.2) { self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight / 2)) self.alpha = 1 } } func hide() { let sWidth = bounds.size.width let sHeight = bounds.size.height UIView.animate(withDuration: 0.2, animations: { self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight + self.mainView.bounds.height / 2)) self.alpha = 0 }) { (finished) in self.removeFromSuperview() } } @IBAction func btnClosePressed(_ sender: UIButton) { hide() } @IBAction func btnModifyPressed(_ sender: UIButton) { delegate?.modifyRecordView(self, didModify: picker.date) hide() } }
mit
c623ce7c17d29b67081c3f88103f9c08
25.142857
107
0.588525
4.357143
false
false
false
false
wowiwj/Yeep
Yeep/Yeep/Realm/Models.swift
1
41839
// // Models.swift // Yeep // // Created by wangju on 16/7/19. // Copyright © 2016年 wangju. All rights reserved. // import UIKit import RealmSwift import CoreLocation /** dispatch_queue_attr_make_with_qos_class - 返回通过指定服务质量信息创建的队列的属性信息 dispatch_queue_t queue = dispatch_queue_create("com.dispatch.serial", DISPATCH_QUEUE_SERIAL); //生成一个串行队列,队列中的block按照先进先出(FIFO)的顺序去执行,实际上为单线程执行。第一个参数是队列的名称,在调试程序时会非常有用,所有尽量不要重名了。 - 所有的队列类型 1. dispatch_queue_t queue = dispatch_queue_create("com.dispatch.serial", DISPATCH_QUEUE_SERIAL); //生成一个串行队列,队列中的block按照先进先出(FIFO)的顺序去执行,实际上为单线程执行。第一个参数是队列的名称,在调试程序时会非常有用,所有尽量不要重名了。 2. dispatch_queue_t queue = dispatch_queue_create("com.dispatch.concurrent", DISPATCH_QUEUE_CONCURRENT); //生成一个并发执行队列,block被分发到多个线程去执行 3. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //获得程序进程缺省产生的并发队列,可设定优先级来选择高、中、低三个优先级队列。由于是系统默认生成的,所以无法调用dispatch_resume()和dispatch_suspend()来控制执行继续或中断。需要注意的是,三个队列不代表三个线程,可能会有更多的线程。并发队列可以根据实际情况来自动产生合理的线程数,也可理解为dispatch队列实现了一个线程池的管理,对于程序逻辑是透明的。 官网文档解释说共有三个并发队列,但实际还有一个更低优先级的队列,设置优先级为DISPATCH_QUEUE_PRIORITY_BACKGROUND。Xcode调试时可以观察到正在使用的各个dispatch队列。 4. dispatch_queue_t queue = dispatch_get_main_queue(); //获得主线程的dispatch队列,实际是一个串行队列。同样无法控制主线程dispatch队列的执行继续或中断。 接下来我们可以使用dispatch_async或dispatch_sync函数来加载需要运行的block。 QOS_CLASS_USER_INTERACTIVE: user interactive等级表示任务需要被立即执行以提供好的用户体验。使用它来更新UI,响应事件以及需要低延时的小工作量任务。这个等级的工作总量应该保持较小规模。 QOS_CLASS_USER_INITIATED:user initiated等级表示任务由UI发起并且可以异步执行。它应该用在用户需要即时的结果同时又要求可以继续交互的任务。 QOS_CLASS_UTILITY:utility等级表示需要长时间运行的任务,常常伴随有用户可见的进度指示器。使用它来做计算,I/O,网络,持续的数据填充等任务。这个等级被设计成节能的。 QOS_CLASS_BACKGROUND:background等级表示那些用户不会察觉的任务。使用它来执行预加载,维护或是其它不需用户交互和对时间不敏感的任务。 url: http://www.cocoachina.com/swift/20150129/11057.html */ /// 总是在这个队列里使用 Realm let realmQueue = dispatch_queue_create("com.YourApp.YourQueue", dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0)) // MARK: User // MARK: User // 朋友的“状态”, 注意:上线后若要调整,只能增加新状态 enum UserFriendState: Int { case Stranger = 0 // 陌生人 case IssuedRequest = 1 // 已对其发出好友请求 case Normal = 2 // 正常状态的朋友 case Blocked = 3 // 被屏蔽 case Me = 4 // 自己 case Yep = 5 // Yep官方账号 } class Avatar: Object { dynamic var avatarURLString: String = "" dynamic var avatarFileName: String = "" dynamic var roundMini: NSData = NSData() // 60 dynamic var roundNano: NSData = NSData() // 40 let users = LinkingObjects(fromType: User.self, property: "avatar") var user: User? { return users.first } } class UserSkillCategory: Object { dynamic var skillCategoryID: String = "" dynamic var name: String = "" dynamic var localName: String = "" let skills = LinkingObjects(fromType: UserSkill.self, property: "category") } class UserSkill: Object { dynamic var category: UserSkillCategory? var skillCategory: SkillCell.Skill.Category? { if let category = category { return SkillCell.Skill.Category(rawValue: category.name) } return nil } dynamic var skillID: String = "" dynamic var name: String = "" dynamic var localName: String = "" dynamic var coverURLString: String = "" let learningUsers = LinkingObjects(fromType: User.self, property: "learningSkills") let masterUsers = LinkingObjects(fromType: User.self, property: "masterSkills") } class UserSocialAccountProvider: Object { dynamic var name: String = "" dynamic var enabled: Bool = false } class UserDoNotDisturb: Object { dynamic var isOn: Bool = false dynamic var fromHour: Int = 22 dynamic var fromMinute: Int = 0 dynamic var toHour: Int = 7 dynamic var toMinute: Int = 30 var hourOffset: Int { let localTimeZone = NSTimeZone.localTimeZone() /** + (id)timeZoneForSecondsFromGMT:(NSInteger)seconds 根据零时区的秒数偏移返回一个新时区对象 */ let totalSecondsOffset = localTimeZone.secondsFromGMT let hourOffset = totalSecondsOffset / (60 * 60) return hourOffset } var minuteOffset: Int { let localTimeZone = NSTimeZone.localTimeZone() let totalSecondsOffset = localTimeZone.secondsFromGMT let hourOffset = totalSecondsOffset / (60 * 60) let minuteOffset = (totalSecondsOffset - hourOffset * (60 * 60)) / 60 return minuteOffset } func serverStringWithHour(hour: Int, minute: Int) -> String { if minute - minuteOffset > 0 { return String(format: "%02d:%02d", (hour - hourOffset) % 24, (minute - minuteOffset) % 60) } else { return String(format: "%02d:%02d", (hour - hourOffset - 1) % 24, ((minute + 60) - minuteOffset) % 60) } } var serverFromString: String { return serverStringWithHour(fromHour, minute: fromMinute) } var serverToString: String { return serverStringWithHour(toHour, minute: toMinute) } var localFromString: String { return String(format: "%02d:%02d", fromHour, fromMinute) } var localToString: String { return String(format: "%02d:%02d", toHour, toMinute) } } // 关于 “@objc 和 dynamic” 100个swifter必备的tips class User: Object { /// 用户ID dynamic var userID: String = "" /// 用户名字 dynamic var username: String = "" /// 用户昵称 dynamic var nickname: String = "" /// 用户介绍 dynamic var introduction: String = "" /// 用户的头像URL dynamic var avatarURLString: String = "" dynamic var avatar: Avatar? dynamic var badge: String = "" /// 用户的博客URL dynamic var blogURLString: String = "" /// 用户的博客标题 dynamic var blogTitle: String = "" /// 索引属性 override class func indexedProperties() -> [String] { return ["userID"] } dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var lastSignInUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var friendState: Int = UserFriendState.Stranger.rawValue dynamic var friendshipID: String = "" dynamic var isBestfriend: Bool = false dynamic var bestfriendIndex: Int = 0 var canShowProfile: Bool { return friendState != UserFriendState.Yep.rawValue } dynamic var longitude: Double = 0 dynamic var latitude: Double = 0 dynamic var notificationEnabled: Bool = true dynamic var blocked: Bool = false dynamic var doNotDisturb: UserDoNotDisturb? var learningSkills = List<UserSkill>() var masterSkills = List<UserSkill>() var socialAccountProviders = List<UserSocialAccountProvider>() let messages = LinkingObjects(fromType: Message.self, property: "fromFriend") let conversations = LinkingObjects(fromType: Conversation.self, property: "withFriend") var conversation: Conversation? { return conversations.first } } func userWithUserID(userID:String,inRealm realm:Realm)->User? { // 设置过滤断言 let predicate = NSPredicate(format: "userID = %@", userID) #if DEBUG let users = realm.objects(User).filter(predicate) if users.count > 1 { print("Warning: same userID: \(users.count), \(userID)") } #endif print(realm.objects(User).first) // 过滤 return realm.objects(User).filter(predicate).first } // MARK: Conversation 消息 enum ConversationType: Int { case OneToOne = 0 // 一对一对话 case Group = 1 // 群组对话 var nameForServer: String { switch self { case .OneToOne: return "User" case .Group: return "Circle" } } var nameForBatchMarkAsRead: String { switch self { case .OneToOne: return "users" case .Group: return "circles" } } } class Conversation: Object { var fakeID: String? { if invalidated { return nil } switch type { case ConversationType.OneToOne.rawValue: if let withFriend = withFriend { return "user" + withFriend.userID } case ConversationType.Group.rawValue: if let withGroup = withGroup { return "group" + withGroup.groupID } default: return nil } return nil } dynamic var hasUnreadMessages: Bool = false dynamic var type: Int = ConversationType.OneToOne.rawValue dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var withFriend: User? dynamic var withGroup: Group? let messages = LinkingObjects(fromType: Message.self, property: "conversation") dynamic var unreadMessagesCount: Int = 0 dynamic var mentionedMe: Bool = false dynamic var lastMentionedMeUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 - 60*60*12 // 默认为此Conversation创建时间之前半天 var latestValidMessage: Message? { return messages.filter({ ($0.hidden == false) && ($0.isIndicator == false && ($0.mediaType != MessageMediaType.SectionDate.rawValue)) }).sort({ $0.createdUnixTime > $1.createdUnixTime }).first } } // MARK: Message class Coordinate: Object { dynamic var latitude: Double = 0 // 合法范围 (-90, 90) dynamic var longitude: Double = 0 // 合法范围 (-180, 180) // NOTICE: always use safe version property var safeLatitude: Double { return abs(latitude) > 90 ? 0 : latitude } var safeLongitude: Double { return abs(longitude) > 180 ? 0 : longitude } var locationCoordinate: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: safeLatitude, longitude: safeLongitude) } func safeConfigureWithLatitude(latitude: Double, longitude: Double) { self.latitude = abs(latitude) > 90 ? 0 : latitude self.longitude = abs(longitude) > 180 ? 0 : longitude } } enum MessageDownloadState: Int { case NoDownload = 0 // 未下载 case Downloading = 1 // 下载中 case Downloaded = 2 // 已下载 } enum MessageMediaType: Int, CustomStringConvertible { case Text = 0 case Image = 1 case Video = 2 case Audio = 3 case Sticker = 4 case Location = 5 case SectionDate = 6 case SocialWork = 7 case ShareFeed = 8 var description: String { switch self { case .Text: return "text" case .Image: return "image" case .Video: return "video" case .Audio: return "audio" case .Sticker: return "sticker" case .Location: return "location" case .SectionDate: return "sectionDate" case .SocialWork: return "socialWork" case .ShareFeed: return "shareFeed" } } var fileExtension: FileExtension? { switch self { case .Image: return .JPEG case .Video: return .MP4 case .Audio: return .M4A default: return nil // TODO: more } } var placeholder: String? { switch self { case .Text: return nil case .Image: return NSLocalizedString("[Image]", comment: "") case .Video: return NSLocalizedString("[Video]", comment: "") case .Audio: return NSLocalizedString("[Audio]", comment: "") case .Sticker: return NSLocalizedString("[Sticker]", comment: "") case .Location: return NSLocalizedString("[Location]", comment: "") case .SocialWork: return NSLocalizedString("[Social Work]", comment: "") default: return NSLocalizedString("All message read", comment: "") } } } class Message: Object { dynamic var messageID: String = "" dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var arrivalUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var mediaType: Int = MessageMediaType.Text.rawValue dynamic var textContent: String = "" dynamic var fromFriend: User? dynamic var conversation: Conversation? dynamic var openGraphDetected: Bool = false dynamic var openGraphInfo: OpenGraphInfo? dynamic var readed: Bool = false dynamic var mediaPlayed: Bool = false // 音频播放过,图片查看过等 dynamic var hidden: Bool = false // 隐藏对方消息,使之不再显示 dynamic var deletedByCreator: Bool = false dynamic var blockedByRecipient: Bool = false var nicknameWithTextContent: String { if let nickname = fromFriend?.nickname { return String(format: NSLocalizedString("%@: %@", comment: ""), nickname, textContent) } else { return textContent } } var isIndicator: Bool { return deletedByCreator || blockedByRecipient } } enum MessageSocialWorkType: Int { case GithubRepo = 0 case DribbbleShot = 1 case InstagramMedia = 2 var accountName: String { switch self { case .GithubRepo: return "github" case .DribbbleShot: return "dribbble" case .InstagramMedia: return "instagram" } } } class SocialWorkGithubRepo: Object { dynamic var repoID: Int = 0 dynamic var name: String = "" dynamic var fullName: String = "" dynamic var URLString: String = "" dynamic var repoDescription: String = "" dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var synced: Bool = false class func getWithRepoID(repoID: Int, inRealm realm: Realm) -> SocialWorkGithubRepo? { let predicate = NSPredicate(format: "repoID = %d", repoID) return realm.objects(SocialWorkGithubRepo).filter(predicate).first } func fillWithGithubRepo(githubRepo: GithubRepo) { self.repoID = githubRepo.ID self.name = githubRepo.name self.fullName = githubRepo.fullName self.URLString = githubRepo.URLString self.repoDescription = githubRepo.description self.createdUnixTime = githubRepo.createdAt.timeIntervalSince1970 } func fillWithFeedGithubRepo(githubRepo: DiscoveredFeed.GithubRepo) { self.repoID = githubRepo.ID//(githubRepo.ID as NSString).integerValue self.name = githubRepo.name self.fullName = githubRepo.fullName self.URLString = githubRepo.URLString self.repoDescription = githubRepo.description self.createdUnixTime = githubRepo.createdUnixTime } } class MessageSocialWork: Object { dynamic var type: Int = MessageSocialWorkType.GithubRepo.rawValue dynamic var githubRepo: SocialWorkGithubRepo? dynamic var dribbbleShot: SocialWorkDribbbleShot? dynamic var instagramMedia: SocialWorkInstagramMedia? } class SocialWorkDribbbleShot: Object { dynamic var shotID: Int = 0 dynamic var title: String = "" dynamic var htmlURLString: String = "" dynamic var imageURLString: String = "" dynamic var shotDescription: String = "" dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var synced: Bool = false class func getWithShotID(shotID: Int, inRealm realm: Realm) -> SocialWorkDribbbleShot? { let predicate = NSPredicate(format: "shotID = %d", shotID) return realm.objects(SocialWorkDribbbleShot).filter(predicate).first } func fillWithDribbbleShot(dribbbleShot: DribbbleShot) { self.shotID = dribbbleShot.ID self.title = dribbbleShot.title self.htmlURLString = dribbbleShot.htmlURLString if let hidpi = dribbbleShot.images.hidpi where dribbbleShot.images.normal.contains("gif") { self.imageURLString = hidpi } else { self.imageURLString = dribbbleShot.images.normal } if let description = dribbbleShot.description { self.shotDescription = description } self.createdUnixTime = dribbbleShot.createdAt.timeIntervalSince1970 } func fillWithFeedDribbbleShot(dribbbleShot: DiscoveredFeed.DribbbleShot) { self.shotID = dribbbleShot.ID//(dribbbleShot.ID as NSString).integerValue self.title = dribbbleShot.title self.htmlURLString = dribbbleShot.htmlURLString self.imageURLString = dribbbleShot.imageURLString if let description = dribbbleShot.description { self.shotDescription = description } self.createdUnixTime = dribbbleShot.createdUnixTime } } class SocialWorkInstagramMedia: Object { dynamic var repoID: String = "" dynamic var linkURLString: String = "" dynamic var imageURLString: String = "" dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var synced: Bool = false } // MARK: Github Repo struct GithubRepo { let ID: Int let name: String let fullName: String let URLString: String let description: String let createdAt: NSDate } // ref https://developer.github.com/v3/ // MARK: Group // Group 类型,注意:上线后若要调整,只能增加新状态 enum GroupType: Int { case Public = 0 case Private = 1 } class Group: Object { dynamic var groupID: String = "" dynamic var groupName: String = "" dynamic var notificationEnabled: Bool = true dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var owner: User? var members = List<User>() dynamic var includeMe: Bool = false dynamic var groupType: Int = GroupType.Private.rawValue dynamic var withFeed: Feed? let conversations = LinkingObjects(fromType: Conversation.self, property: "withGroup") var conversation: Conversation? { return conversations.first } } // MARK: Feed class Attachment: Object { //dynamic var kind: String = "" dynamic var metadata: String = "" dynamic var URLString: String = "" } class FeedAudio: Object { dynamic var feedID: String = "" dynamic var URLString: String = "" dynamic var metadata: NSData = NSData() dynamic var fileName: String = "" var belongToFeed: Feed? { return LinkingObjects(fromType: Feed.self, property: "audio").first } class func feedAudioWithFeedID(feedID: String, inRealm realm: Realm) -> FeedAudio? { let predicate = NSPredicate(format: "feedID = %@", feedID) return realm.objects(FeedAudio).filter(predicate).first } var audioMetaInfo: (duration: NSTimeInterval, samples: [CGFloat])? { if let metaDataInfo = decodeJSON(metadata) { if let duration = metaDataInfo[YeepConfig.MetaData.audioDuration] as? NSTimeInterval, samples = metaDataInfo[YeepConfig.MetaData.audioSamples] as? [CGFloat] { return (duration, samples) } } return nil } func deleteAudioFile() { guard !fileName.isEmpty else { return } NSFileManager.removeMessageAudioFileWithName(fileName) } } class FeedLocation: Object { dynamic var name: String = "" dynamic var coordinate: Coordinate? } class OpenGraphInfo: Object { dynamic var URLString: String = "" dynamic var siteName: String = "" dynamic var title: String = "" dynamic var infoDescription: String = "" dynamic var thumbnailImageURLString: String = "" let messages = LinkingObjects(fromType: Message.self, property: "openGraphInfo") let feeds = LinkingObjects(fromType: Feed.self, property: "openGraphInfo") override class func primaryKey() -> String? { return "URLString" } override class func indexedProperties() -> [String] { return ["URLString"] } convenience init(URLString: String, siteName: String, title: String, infoDescription: String, thumbnailImageURLString: String) { self.init() self.URLString = URLString self.siteName = siteName self.title = title self.infoDescription = infoDescription self.thumbnailImageURLString = thumbnailImageURLString } class func withURLString(URLString: String, inRealm realm: Realm) -> OpenGraphInfo? { return realm.objects(OpenGraphInfo).filter("URLString = %@", URLString).first } } class Feed: Object { dynamic var feedID: String = "" dynamic var allowComment: Bool = true dynamic var createdUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var updatedUnixTime: NSTimeInterval = NSDate().timeIntervalSince1970 dynamic var creator: User? dynamic var distance: Double = 0 dynamic var messagesCount: Int = 0 dynamic var body: String = "" dynamic var kind: String = FeedKind.Text.rawValue var attachments = List<Attachment>() dynamic var socialWork: MessageSocialWork? dynamic var audio: FeedAudio? dynamic var location: FeedLocation? dynamic var openGraphInfo: OpenGraphInfo? dynamic var skill: UserSkill? dynamic var group: Group? dynamic var deleted: Bool = false // 已被管理员或建立者删除 // 级联删除关联的数据对象 func cascadeDeleteInRealm(realm: Realm) { attachments.forEach { realm.delete($0) } if let socialWork = socialWork { if let githubRepo = socialWork.githubRepo { realm.delete(githubRepo) } if let dribbbleShot = socialWork.dribbbleShot { realm.delete(dribbbleShot) } if let instagramMedia = socialWork.instagramMedia { realm.delete(instagramMedia) } realm.delete(socialWork) } if let audio = audio { audio.deleteAudioFile() realm.delete(audio) } if let location = location { if let coordinate = location.coordinate { realm.delete(coordinate) } realm.delete(location) } // 除非没有谁指向 openGraphInfo,不然不能删除它 if let openGraphInfo = openGraphInfo { if openGraphInfo.messages.isEmpty { if openGraphInfo.feeds.count == 1, let first = openGraphInfo.messages.first where first == self { realm.delete(openGraphInfo) } } } realm.delete(self) } } func feedWithFeedID(feedID: String, inRealm realm: Realm) -> Feed? { let predicate = NSPredicate(format: "feedID = %@", feedID) #if DEBUG let feeds = realm.objects(Feed).filter(predicate) if feeds.count > 1 { print("Warning: same feedID: \(feeds.count), \(feedID)") } #endif return realm.objects(Feed).filter(predicate).first } func saveFeedWithDiscoveredFeed(feedData: DiscoveredFeed, group: Group, inRealm realm: Realm) { // save feed var _feed = feedWithFeedID(feedData.id, inRealm: realm) if _feed == nil { let newFeed = Feed() newFeed.feedID = feedData.id newFeed.allowComment = feedData.allowComment newFeed.createdUnixTime = feedData.createdUnixTime newFeed.updatedUnixTime = feedData.updatedUnixTime newFeed.creator = getOrCreateUserWithDiscoverUser(feedData.creator, inRealm: realm) newFeed.body = feedData.body if let feedSkill = feedData.skill { newFeed.skill = userSkillsFromSkills([feedSkill], inRealm: realm).first } realm.add(newFeed) _feed = newFeed } else { #if DEBUG if _feed?.group == nil { print("feed have not with group, it may old (not deleted with conversation before)") } #endif } guard let feed = _feed else { return } // update feed print("update feed: \(feedData.kind.rawValue), \(feed.feedID)") feed.kind = feedData.kind.rawValue feed.deleted = false feed.group = group group.withFeed = feed group.groupType = GroupType.Public.rawValue if let distance = feedData.distance { feed.distance = distance } feed.messagesCount = feedData.messagesCount if let attachment = feedData.attachment { switch attachment { case .Images(let attachments): guard feed.attachments.isEmpty else { break } feed.attachments.removeAll() let attachments = attachmentFromDiscoveredAttachment(attachments) feed.attachments.appendContentsOf(attachments) case .Github(let repo): guard feed.socialWork?.githubRepo == nil else { break } let socialWork = MessageSocialWork() socialWork.type = MessageSocialWorkType.GithubRepo.rawValue let repoID = repo.ID var socialWorkGithubRepo = SocialWorkGithubRepo.getWithRepoID(repoID, inRealm: realm) if socialWorkGithubRepo == nil { let newSocialWorkGithubRepo = SocialWorkGithubRepo() newSocialWorkGithubRepo.fillWithFeedGithubRepo(repo) realm.add(newSocialWorkGithubRepo) socialWorkGithubRepo = newSocialWorkGithubRepo } if let socialWorkGithubRepo = socialWorkGithubRepo { socialWorkGithubRepo.synced = true } socialWork.githubRepo = socialWorkGithubRepo feed.socialWork = socialWork case .Dribbble(let shot): guard feed.socialWork?.dribbbleShot == nil else { break } let socialWork = MessageSocialWork() socialWork.type = MessageSocialWorkType.DribbbleShot.rawValue let shotID = shot.ID var socialWorkDribbbleShot = SocialWorkDribbbleShot.getWithShotID(shotID, inRealm: realm) if socialWorkDribbbleShot == nil { let newSocialWorkDribbbleShot = SocialWorkDribbbleShot() newSocialWorkDribbbleShot.fillWithFeedDribbbleShot(shot) realm.add(newSocialWorkDribbbleShot) socialWorkDribbbleShot = newSocialWorkDribbbleShot } if let socialWorkDribbbleShot = socialWorkDribbbleShot { socialWorkDribbbleShot.synced = true } socialWork.dribbbleShot = socialWorkDribbbleShot feed.socialWork = socialWork case .Audio(let audioInfo): guard feed.audio == nil else { break } let feedAudio = FeedAudio() feedAudio.feedID = audioInfo.feedID feedAudio.URLString = audioInfo.URLString feedAudio.metadata = audioInfo.metaData feed.audio = feedAudio case .Location(let locationInfo): guard feed.location == nil else { break } let feedLocation = FeedLocation() feedLocation.name = locationInfo.name let coordinate = Coordinate() coordinate.safeConfigureWithLatitude(locationInfo.latitude, longitude:locationInfo.longitude) feedLocation.coordinate = coordinate feed.location = feedLocation case .URL(let info): guard feed.openGraphInfo == nil else { break } let openGraphInfo = OpenGraphInfo(URLString: info.URL.absoluteString, siteName: info.siteName, title: info.title, infoDescription: info.infoDescription, thumbnailImageURLString: info.thumbnailImageURLString) realm.add(openGraphInfo, update: true) feed.openGraphInfo = openGraphInfo } } } // MARK: Update with info func updateUserWithUserID(userID: String, useUserInfo userInfo: JSONDictionary, inRealm realm: Realm) { if let user = userWithUserID(userID, inRealm: realm) { // 更新用户信息 if let lastSignInUnixTime = userInfo["last_sign_in_at"] as? NSTimeInterval { user.lastSignInUnixTime = lastSignInUnixTime } if let username = userInfo["username"] as? String { user.username = username } if let nickname = userInfo["nickname"] as? String { user.nickname = nickname } if let introduction = userInfo["introduction"] as? String { user.introduction = introduction } if let avatarInfo = userInfo["avatar"] as? JSONDictionary, avatarURLString = avatarInfo["url"] as? String { user.avatarURLString = avatarURLString } if let longitude = userInfo["longitude"] as? Double { user.longitude = longitude } if let latitude = userInfo["latitude"] as? Double { user.latitude = latitude } if let badge = userInfo["badge"] as? String { user.badge = badge } if let blogURLString = userInfo["website_url"] as? String { user.blogURLString = blogURLString } if let blogTitle = userInfo["website_title"] as? String { user.blogTitle = blogTitle } // 更新技能 if let learningSkillsData = userInfo["learning_skills"] as? [JSONDictionary] { user.learningSkills.removeAll() let userSkills = userSkillsFromSkillsData(learningSkillsData, inRealm: realm) user.learningSkills.appendContentsOf(userSkills) } if let masterSkillsData = userInfo["master_skills"] as? [JSONDictionary] { user.masterSkills.removeAll() let userSkills = userSkillsFromSkillsData(masterSkillsData, inRealm: realm) user.masterSkills.appendContentsOf(userSkills) } // 更新 Social Account Provider if let providersInfo = userInfo["providers"] as? [String: Bool] { user.socialAccountProviders.removeAll() for (name, enabled) in providersInfo { let provider = UserSocialAccountProvider() provider.name = name provider.enabled = enabled user.socialAccountProviders.append(provider) } } } } func userSkillWithSkillID(skillID: String, inRealm realm: Realm) -> UserSkill? { let predicate = NSPredicate(format: "skillID = %@", skillID) return realm.objects(UserSkill).filter(predicate).first } func userSkillCategoryWithSkillCategoryID(skillCategoryID: String, inRealm realm: Realm) -> UserSkillCategory? { let predicate = NSPredicate(format: "skillCategoryID = %@", skillCategoryID) return realm.objects(UserSkillCategory).filter(predicate).first } // MARK: - Helpers func normalFriends() -> Results<User> { let realm = try! Realm() let predicate = NSPredicate(format: "friendState = %d", UserFriendState.Normal.rawValue) return realm.objects(User).filter(predicate).sorted("lastSignInUnixTime", ascending: false) } func normalUsers() -> Results<User> { let realm = try! Realm() let predicate = NSPredicate(format: "friendState != %d", UserFriendState.Blocked.rawValue) return realm.objects(User).filter(predicate) } func oneToOneConversationsInRealm(realm: Realm) -> Results<Conversation> { let predicate = NSPredicate(format: "type = %d", ConversationType.OneToOne.rawValue) return realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false) } func countOfUnreadMessagesInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Int { switch conversationType { case .OneToOne: let predicate = NSPredicate(format: "readed = false AND fromFriend != nil AND fromFriend.friendState != %d AND conversation != nil AND conversation.type = %d", UserFriendState.Me.rawValue, conversationType.rawValue) return realm.objects(Message).filter(predicate).count case .Group: // Public for now let predicate = NSPredicate(format: "includeMe = true AND groupType = %d", GroupType.Public.rawValue) let count = realm.objects(Group).filter(predicate).map({ $0.conversation }).flatMap({ $0 }).map({ $0.hasUnreadMessages ? 1 : 0 }).reduce(0, combine: +) return count } } func countOfConversationsInRealm(realm: Realm) -> Int { return realm.objects(Conversation).count } func conversationWithDiscoveredUser(discoveredUser: DiscoveredUser, inRealm realm: Realm) -> Conversation? { var stranger = userWithUserID(discoveredUser.id, inRealm: realm) if stranger == nil { let newUser = User() newUser.userID = discoveredUser.id newUser.friendState = UserFriendState.Stranger.rawValue realm.add(newUser) stranger = newUser } guard let user = stranger else { return nil } // 更新用户信息 user.lastSignInUnixTime = discoveredUser.lastSignInUnixTime user.username = discoveredUser.username ?? "" user.nickname = discoveredUser.nickname if let introduction = discoveredUser.introduction { user.introduction = introduction } user.avatarURLString = discoveredUser.avatarURLString user.longitude = discoveredUser.longitude user.latitude = discoveredUser.latitude if let badge = discoveredUser.badge { user.badge = badge } if let blogURLString = discoveredUser.blogURLString { user.blogURLString = blogURLString } // 更新技能 user.learningSkills.removeAll() let learningUserSkills = userSkillsFromSkills(discoveredUser.learningSkills, inRealm: realm) user.learningSkills.appendContentsOf(learningUserSkills) user.masterSkills.removeAll() let masterUserSkills = userSkillsFromSkills(discoveredUser.masterSkills, inRealm: realm) user.masterSkills.appendContentsOf(masterUserSkills) // 更新 Social Account Provider user.socialAccountProviders.removeAll() let socialAccountProviders = userSocialAccountProvidersFromSocialAccountProviders(discoveredUser.socialAccountProviders) user.socialAccountProviders.appendContentsOf(socialAccountProviders) if user.conversation == nil { let newConversation = Conversation() newConversation.type = ConversationType.OneToOne.rawValue newConversation.withFriend = user realm.add(newConversation) } return user.conversation } func avatarWithAvatarURLString(avatarURLString: String, inRealm realm: Realm) -> Avatar? { let predicate = NSPredicate(format: "avatarURLString = %@", avatarURLString) return realm.objects(Avatar).filter(predicate).first } func refreshGroupTypeForAllGroups() { if let realm = try? Realm() { realm.beginWrite() realm.objects(Group).forEach({ if $0.withFeed == nil { $0.groupType = GroupType.Private.rawValue print("We have group with NO feed") } }) let _ = try? realm.commitWrite() } } func groupWithGroupID(groupID: String, inRealm realm: Realm) -> Group? { let predicate = NSPredicate(format: "groupID = %@", groupID) return realm.objects(Group).filter(predicate).first } func countOfUnreadMessagesInConversation(conversation: Conversation) -> Int { return conversation.messages.filter({ message in if let fromFriend = message.fromFriend { return (message.readed == false) && (fromFriend.friendState != UserFriendState.Me.rawValue) } else { return false } }).count } func latestUnreadValidMessageInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Message? { switch conversationType { case .OneToOne: let predicate = NSPredicate(format: "readed = false AND hidden = false AND deletedByCreator = false AND blockedByRecipient == false AND mediaType != %d AND fromFriend != nil AND conversation != nil AND conversation.type = %d", MessageMediaType.SocialWork.rawValue, conversationType.rawValue) return realm.objects(Message).filter(predicate).sorted("updatedUnixTime", ascending: false).first case .Group: // Public for now let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d", GroupType.Public.rawValue) let messages: [Message]? = realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false).first?.messages.filter({ $0.readed == false && $0.fromFriend?.userID != YeepUserDefaults.userID.value }).sort({ $0.createdUnixTime > $1.createdUnixTime }) return messages?.filter({ ($0.hidden == false) && ($0.isIndicator == false) && ($0.mediaType != MessageMediaType.SectionDate.rawValue) }).first } } func latestValidMessageInRealm(realm: Realm, withConversationType conversationType: ConversationType) -> Message? { switch conversationType { case .OneToOne: let predicate = NSPredicate(format: "hidden = false AND deletedByCreator = false AND blockedByRecipient == false AND mediaType != %d AND fromFriend != nil AND conversation != nil AND conversation.type = %d", MessageMediaType.SocialWork.rawValue, conversationType.rawValue) return realm.objects(Message).filter(predicate).sorted("updatedUnixTime", ascending: false).first case .Group: // Public for now let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d", GroupType.Public.rawValue) let messages: [Message]? = realm.objects(Conversation).filter(predicate).sorted("updatedUnixTime", ascending: false).first?.messages.sort({ $0.createdUnixTime > $1.createdUnixTime }) return messages?.filter({ ($0.hidden == false) && ($0.isIndicator == false) && ($0.mediaType != MessageMediaType.SectionDate.rawValue)}).first } } func mentionedMeInFeedConversationsInRealm(realm: Realm) -> Bool { let predicate = NSPredicate(format: "withGroup != nil AND withGroup.includeMe = true AND withGroup.groupType = %d AND mentionedMe = true", GroupType.Public.rawValue) return realm.objects(Conversation).filter(predicate).count > 0 }
mit
b657cafa4d057cbaf4946545ac558fa2
31.294737
299
0.630529
4.852068
false
false
false
false
quintonwall/SalesforceViews
SalesforceViews/SalesforceViewsDefaults.swift
1
1077
// // SalesforceViewsGlobals.swift // SalesforceViews // // Created by QUINTON WALL on 4/8/17. // Copyright © 2017 me.quinton. All rights reserved. // import Foundation import UIKit public final class SalesforceViewsDefaults { public static let shared = SalesforceViewsDefaults() } public enum SalesforceViewError: Error { case notificationObjectMismatch } public struct ColorPalette { static let primaryDark: UIColor = UIColor(netHex: 0x397367) static let primaryLight: UIColor = UIColor(netHex: 0x5DA38B) static let secondaryDark: UIColor = UIColor(netHex: 0x42858C) static let secondaryLight: UIColor = UIColor(netHex: 0x63CCCA) static let tertiary: UIColor = UIColor(netHex: 0x35393C) } public struct ViewNotifications { static let accountList : String = "sfv-account-list" static let accountDetail : String = "sfv-account-detail" static let accountInsert : String = "sfv-account-insert" static let accountUpdate : String = "sfv-account-update" static let accountDelete : String = "sfv-account-delete" }
mit
d75aab89bc673811d3e3b84629e455a2
28.081081
66
0.736989
3.898551
false
false
false
false
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Constant/EYEAPIHeaper.swift
1
1192
// // EYEAPIHeaper.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/14. // Copyright © 2016年 xiaoming. All rights reserved. // import Foundation import Alamofire struct EYEAPIHeaper { static let API_Service = "http://baobab.wandoujia.com/api/v2/" /// 一.每日精选api 参数 1.date:时间戳 2.num:数量(默认7) date=1457883945551&num=7 static let API_Choice = API_Service+"feed" /// 二.发现更多(分类) http://baobab.wandoujia.com/api/v2/categories static let API_Discover = API_Service+"categories" /// 三. 热门排行(周排行) static let API_Popular_Weakly = API_Service+"ranklist?strategy=weekly" /// 四.热门排行(月排行) static let API_Popular_Monthly = API_Service+"ranklist?strategy=monthly" /// 五.热门排行(总排行) static let API_Popular_Historical = API_Service+"ranklist?strategy=historical" /// 六.发现更多 - 按时间排序 参数:categoryId static let API_Discover_Date = API_Service+"videos?strategy=date" /// 七.发现更多 - 分享排行版 参数:categoryId static let API_Discover_Share = API_Service+"videos?strategy=shareCount" }
mit
aa1bd5f9fabbc78822efc658382cbd67
36
82
0.683092
3.11747
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/UIComponents/UIComponentsKit/Utilities/HostingTableViewCell.swift
1
2542
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation import SwiftUI import UIKit public final class HostingTableViewCell<Content: View>: UITableViewCell { private var hostingController: UIHostingController<Content?>? private var heightConstraint: NSLayoutConstraint? override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = .lightBorder } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func host( _ rootView: Content, parent: UIViewController, height: CGFloat? = nil, insets: UIEdgeInsets = .zero, showSeparator: Bool = true, backgroundColor: UIColor = .lightBorder ) { contentView.backgroundColor = backgroundColor hostingController?.view.removeFromSuperview() hostingController?.rootView = nil hostingController = .init(rootView: rootView) guard let hostingController = hostingController else { return } hostingController.view.invalidateIntrinsicContentSize() let requiresControllerMove = hostingController.parent != parent if requiresControllerMove { parent.addChild(hostingController) } if !contentView.subviews.contains(hostingController.view) { contentView.addSubview(hostingController.view) var insets = insets insets.bottom += showSeparator ? 1 : 0 hostingController.view.constraint( edgesTo: contentView, insets: insets ) if let height = height, heightConstraint == nil { heightConstraint = contentView.heightAnchor .constraint(equalToConstant: height) heightConstraint?.isActive = true } } if requiresControllerMove { hostingController.didMove(toParent: parent) } } @discardableResult public func updateRootView(height: CGFloat) -> Bool { if heightConstraint?.constant == height { return false } if heightConstraint != nil { contentView.backgroundColor = height <= 1 ? .clear : .lightBorder heightConstraint?.constant = height contentView.setNeedsLayout() } return true } }
lgpl-3.0
7fcc2e30c879edc8dda607c779172ae9
32.434211
79
0.635577
5.923077
false
false
false
false
studyYF/Weibo-swift-
WeiBo/WeiBo/CLasses/Home(首页)/UIPopover/WBPresentationController.swift
1
1217
// // WBPresentationController.swift // Weibo // // Created by YF on 16/10/2. // Copyright © 2016年 YF. All rights reserved. // import UIKit class WBPresentationController: UIPresentationController { //MARK: - 懒加载属性 lazy var coverView = UIView() var presentFrame = CGRectZero //MARK: - 系统回调函数 override func containerViewDidLayoutSubviews() { super.containerViewDidLayoutSubviews() //设置弹出视图的位置 presentedView()?.frame = presentFrame setCoverView() } } //MARK: - 设置UI extension WBPresentationController { ///设置UI控件 func setCoverView() { // containerView?.addSubview(coverView) containerView?.insertSubview(coverView, atIndex: 0) coverView.backgroundColor = UIColor(white: 0.0, alpha: 0.4) coverView.frame = containerView!.bounds let tap = UITapGestureRecognizer(target: self, action: "coverViewClick") coverView.addGestureRecognizer(tap) } } //MARK: - 事件监听 extension WBPresentationController { @objc private func coverViewClick() { presentedViewController.dismissViewControllerAnimated(true, completion: nil) } }
apache-2.0
5d1663c3d76c5ca867bf71891744de4b
24.666667
84
0.682842
4.788382
false
false
false
false
NitWitStudios/NWSTokenView
Pod/Classes/NWSToken/NWSToken.swift
1
1736
// // NWSToken.swift // NWSTokenView // // Created by James Hickman on 8/11/15. /* Copyright (c) 2015 Appmazo, LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.// */ import UIKit open class NWSToken: UIView { open var hiddenTextView = UITextView() open var isSelected: Bool = false required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Hide text view (for using keyboard to delete token) hiddenTextView.isHidden = true hiddenTextView.text = "NWSTokenDeleteKey" // Set default text for detection in delegate hiddenTextView.autocorrectionType = UITextAutocorrectionType.no // Hide suggestions to prevent key from being displayed addSubview(hiddenTextView) } }
mit
2d342f03acc5722added06a5976d8140
53.25
462
0.759793
4.704607
false
false
false
false
Dougly/2For1
2for1/AddDieOrDrinkView.swift
1
1235
// // AddDieOrDrink.swift // 2for1 // // Created by Douglas Galante on 12/27/16. // Copyright © 2016 Flatiron. All rights reserved. // import UIKit class AddDieOrDrinkView: UIView { @IBOutlet var contentView: UIView! @IBOutlet weak var drinkView: UIView! @IBOutlet weak var addDieView: UIView! @IBOutlet weak var addDieViewShadow: UIView! @IBOutlet weak var drinkViewShadow: UIView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } func commonInit() { Bundle.main.loadNibNamed("AddDieOrDrinkView", owner: self, options: nil) self.addSubview(contentView) self.constrain(contentView) } func setCornerRadius(with size: CGFloat) { let constraintMultiplier: CGFloat = 0.8 let cornerRadius = (size * constraintMultiplier) / 2 drinkView.layer.cornerRadius = cornerRadius drinkViewShadow.layer.cornerRadius = cornerRadius addDieView.layer.cornerRadius = cornerRadius addDieViewShadow.layer.cornerRadius = cornerRadius } }
mit
dfd1bd624f69885a1fa09127720e071d
24.183673
80
0.649919
4.454874
false
false
false
false
nekrich/GlobalMessageService-iOS
Source/InboxViewController/GlobalMessageServiceInboxViewController.swift
1
18907
// // InboxViewController.swift // GlobalMessageService // // Created by Vitalii Budnik on 2/25/16. // Copyright © 2016 Global Message Services Worldwide. All rights reserved. // import Foundation import UIKit import JSQMessagesViewController /** Shows delivered `GlobalMessageServiceMessage`s */ public class GlobalMessageServiceInboxViewController: JSQMessagesViewController { // swiftlint:disable line_length /// Message fetcher private let fetcher: GlobalMessageServiceMessageFetcherJSQ = GlobalMessageServiceMessageFetcherJSQ.sharedInstance // swiftlint:enable line_length public var isVisible: Bool { if isViewLoaded() { return view.window != nil } return false } public var isTopViewController: Bool { if let navigationController = navigationController { return navigationController.visibleViewController === self } else if let tabBarController = tabBarController { return tabBarController.selectedViewController == self && self.presentedViewController == nil } else { return self.presentedViewController == nil && self.isVisible } } /** The number of seconds between firings of the todays messages fetcher timer. If it is less than or equal to 30.0, sets the value of 30.0 seconds instead. (private) */ private var _todaysMesagesUpdateInterval: NSTimeInterval = 60 /// Auto-fetch delivered messages timer private weak var todaysMesagesUpdateTimer: NSTimer? = .None public func fetchTodaysMesagesTimerFired(sender: NSTimer) { fetchTodaysMesages() } public func fetchTodaysMesages(fetch: Bool = true) { stopTimer() fetcher.fetchTodaysMessages(fetch) { [weak self] newMessagesFetched in guard let sSelf = self else { return } if newMessagesFetched { sSelf.finishReceivingMessageAnimated(true) } if sSelf.isTopViewController == true { sSelf.startTimer() } } } /** The number of seconds between firings of the todays messages fetcher timer. If it is less than or equal to 30.0, sets the value of 30.0 seconds instead. Calculated variable */ public var todaysMesagesUpdateInterval: NSTimeInterval { get { return _todaysMesagesUpdateInterval } set { _todaysMesagesUpdateInterval = max(newValue, 30) startTimer() } } // MARK: Lifecycle override public func viewDidLoad() { super.viewDidLoad() collectionView?.collectionViewLayout.messageBubbleLeftRightMargin = 58.0 JSQMessagesCollectionViewCell.registerMenuAction(#selector(NSObject.delete(_:))) showLoadEarlierMessagesHeader = fetcher.hasMorePrevious fetcher.delegate = self JSQMessagesTimestampFormatter.sharedFormatter().dateFormatter.timeStyle = .NoStyle JSQMessagesTimestampFormatter.sharedFormatter().dateFormatter.dateStyle = .LongStyle senderId = "SenderID" senderDisplayName = "Sender display name" setupBubbles() setupBubbleTextColors() setupAvatars() loadPrevious() hideInputToolbar() fetchTodaysMesages(false) } /// Data source for `JSQMessagesCollectionView` var dataSource: [GlobalMessageServiceMessageJSQ] { get { return fetcher.messages } } /// Stops auto-fetch delivered messages timer private func stopTimer() { todaysMesagesUpdateTimer?.invalidate() todaysMesagesUpdateTimer = .None } /// Starts auto-fetch delivered messages timer private func startTimer() { stopTimer() todaysMesagesUpdateTimer = NSTimer.scheduledTimerWithTimeInterval( _todaysMesagesUpdateInterval, target: self, selector: #selector(fetchTodaysMesagesTimerFired(_:)), userInfo: .None, repeats: false) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchTodaysMesages() } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) stopTimer() } override public func willTransitionToTraitCollection( newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) // swiftlint:disable:this line_length { coordinator.animateAlongsideTransition(.None) { [weak self] _ in self?.reloadViews() } } /// Redraws visible cells (Time label text update) private func reloadViews() { collectionView?.visibleCells().forEach { (cell) -> () in guard let indexPath = collectionView?.indexPathForCell(cell) else { return } let date = dataSource[indexPath.item].date() addTimeLabelToCell(cell, withDate: date) } } // MARK: Setup /// Setups avatar sizes private func setupAvatars() { collectionView?.collectionViewLayout.incomingAvatarViewSize = CGSize.zero collectionView?.collectionViewLayout.outgoingAvatarViewSize = CGSize.zero } public var smsBubbleImageView: JSQMessagesBubbleImage! public var viberBubbleImageView: JSQMessagesBubbleImage! public var pushBubbleImageView: JSQMessagesBubbleImage! public var smsBubbleTextColor: UIColor! public var viberBubbleTextColor: UIColor! public var pushBubbleTextColor: UIColor! /// Setups messages bubble colors for diffrent message types private func setupBubbles() { let factory = JSQMessagesBubbleImageFactory() smsBubbleImageView = factory.incomingMessagesBubbleImageWithColor( UIColor(red: 0.0/255.0, green: 195.0/255.0, blue: 82.0/255.0, alpha: 1)) viberBubbleImageView = factory.incomingMessagesBubbleImageWithColor( UIColor(red: 124.0/255.0, green: 83.0/255.0, blue: 156.0/255.0, alpha: 1)) pushBubbleImageView = factory.incomingMessagesBubbleImageWithColor( UIColor(red: 229.0/255.0, green: 229.0/255.0, blue: 234.0/255.0, alpha: 1)) } /// Setups messages text colors for diffrent message types private func setupBubbleTextColors() { smsBubbleTextColor = UIColor.whiteColor() viberBubbleTextColor = UIColor.whiteColor() pushBubbleTextColor = UIColor.blackColor() } /// Loads messages for previous dates private func loadPrevious() { fetcher.loadPrevious { [weak self] in guard let sSelf = self else { return } sSelf.showLoadEarlierMessagesHeader = sSelf.fetcher.hasMorePrevious sSelf.automaticallyScrollsToMostRecentMessage = false sSelf.finishReceivingMessage() } } /** Returns `true` if day of current message is not equal to previous message date. `false` otherwise Actually returns `Bool` flag if we need to display header for bubble or not - Parameter indexPath: - Returns: `true` if day of current message is not equal to previous message date */ private func previousMessageForIndexPathIsWithAnotherDate(indexPath: NSIndexPath) -> Bool { if indexPath.item == 0 { return true } else { let message = dataSource[indexPath.item] let previousMessage = dataSource[indexPath.item - 1] if previousMessage.date().startOfDay().timeIntervalSinceReferenceDate != message.date().startOfDay().timeIntervalSinceReferenceDate // swiftlint:disable:this opening_brace { return true } } return false } /// Time label tag const (right side of collection view cell) private let kTimeLabelTag = 1001 /// Attributes for date label (bubble header) lazy private var dateFormatAttributes: [String: AnyObject] = { return [NSFontAttributeName: UIFont.boldSystemFontOfSize(12.0)] }() /// Attributes for alpha name label (bubble footer) lazy private var alphaNameFormatAttributes: [String: AnyObject] = { return [NSFontAttributeName: UIFont.systemFontOfSize(12.0)] }() /// `CGFloat` with alphaNameLabel (bubble footer) height lazy private var alphaNameLabelHeight: CGFloat = { let attr = NSAttributedString(string: "qW", attributes: self.alphaNameFormatAttributes) let frame = attr.boundingRectWithSize( CGSize(width: 100, height: 20), options: [.UsesLineFragmentOrigin, .UsesFontLeading], context: .None) return frame.size.height }() /// `NSDateFormatter` for time label private lazy var timeFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.timeStyle = .ShortStyle formatter.dateStyle = .NoStyle return formatter }() /// `NSDateFormatter` for date label (bubble header) private lazy var dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.timeStyle = .NoStyle formatter.dateStyle = .LongStyle formatter.doesRelativeDateFormatting = true return formatter }() } // MARK: Multi-language support public extension GlobalMessageServiceInboxViewController { public func setLanguage(localeIdentifier: String) { timeFormatter.locale = NSLocale(localeIdentifier: localeIdentifier) dateFormatter.locale = NSLocale(localeIdentifier: localeIdentifier) reloadViews() automaticallyScrollsToMostRecentMessage = true finishReceivingMessageAnimated(true) } } // MARK: - Hide input toolbar view private extension GlobalMessageServiceInboxViewController { /** Sets collection view insets. Overrides `super` private method - Parameter top: top inset - Parameter bottom: bottom inset */ private func jsq_setCollectionViewInsetsTopValue(top: CGFloat, bottomValue bottom: CGFloat) { var insets = collectionView?.contentInset ?? UIEdgeInsetsZero insets.top = top insets.bottom = bottom //insets.bottom = 50 collectionView?.contentInset = insets collectionView?.scrollIndicatorInsets = insets } /// Updates collection view insets. Overrides `super` private method private func jsq_updateCollectionViewInsets() { jsq_setCollectionViewInsetsTopValue(0, bottomValue: 0) } /// Hides input bar private func hideInputToolbar() { inputToolbar?.hidden = true jsq_updateCollectionViewInsets() inputToolbar?.removeFromSuperview() } } // MARK: - Collection View // MARK: DataSource public extension GlobalMessageServiceInboxViewController { override public func collectionView( collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell // swiftlint:disable:this opening_brace { let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) self.addTimeLabelToCell(cell, withDate: dataSource[indexPath.item].date()) if let cell = cell as? JSQMessagesCollectionViewCell, let cellTextView = cell.textView // swiftlint:disable:this opening_brace { cellTextView.userInteractionEnabled = false let message = dataSource[indexPath.item] if message.type == .PushNotification { cellTextView.textColor = pushBubbleTextColor } else if message.type == .SMS { cellTextView.textColor = smsBubbleTextColor } else if message.type == .Viber { cellTextView.textColor = viberBubbleTextColor } } return cell } override public func collectionView( collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! // swiftlint:disable:this opening_brace { return dataSource[indexPath.item] } override public func collectionView( collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int // swiftlint:disable:this opening_brace { return dataSource.count } } // MARK: Delegate public extension GlobalMessageServiceInboxViewController { override public func collectionView( collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! // swiftlint:disable:this opening_brace { let message = dataSource[indexPath.item] switch message.type { case .PushNotification: return pushBubbleImageView case .SMS: return smsBubbleImageView case .Viber: return viberBubbleImageView } } override public func collectionView( collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! // swiftlint:disable:this opening_brace { return nil } public override func collectionView( collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) // swiftlint:disable:this opening_brace { fetcher.delete(indexPath.item) } } // swiftlint:disable file_length // MARK: Header public extension GlobalMessageServiceInboxViewController { override public func collectionView( collectionView: JSQMessagesCollectionView!, header headerView: JSQMessagesLoadEarlierHeaderView!, didTapLoadEarlierMessagesButton sender: UIButton!) // swiftlint:disable:this opening_brace { loadPrevious() } } // MARK: Buble Header public extension GlobalMessageServiceInboxViewController { override public func collectionView( collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! // swiftlint:disable:this opening_brace { let message = dataSource[indexPath.item] let messageDate: NSDate? if previousMessageForIndexPathIsWithAnotherDate(indexPath) { messageDate = message.date().startOfDay() } else { messageDate = .None } if let messageDate = messageDate { return NSAttributedString( string: dateFormatter.stringFromDate(messageDate), attributes: dateFormatAttributes) } return .None } override public func collectionView( collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat // swiftlint:disable:this opening_brace { if previousMessageForIndexPathIsWithAnotherDate(indexPath) { return kJSQMessagesCollectionViewCellLabelHeightDefault } else { return 0.0 } } } // MARK: Buble Footer public extension GlobalMessageServiceInboxViewController { public override func collectionView( collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! // swiftlint:disable:this opening_brace { let message = dataSource[indexPath.item] let alphaNameAttributedString = NSAttributedString( string: message.alphaName + ". " + message.type.description, attributes: alphaNameFormatAttributes) return alphaNameAttributedString } public override func collectionView( collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat // swiftlint:disable:this opening_brace { return alphaNameLabelHeight } } // MARK: Time Label private extension GlobalMessageServiceInboxViewController { /** Returns configured time-`UILabel` - Returns: configured `UILabel` */ private func timeLabel() -> UILabel { let timeLabel = UILabel() timeLabel.tag = kTimeLabelTag timeLabel.textColor = UIColor.grayColor() timeLabel.text = .None timeLabel.font = timeLabel.font.fontWithSize(11) timeLabel.textColor = UIColor.grayColor() return timeLabel } /** Adds time label to collection view cell - Parameter cell: `UICollectionViewCell` where to add time label - Parameter date: Time to display on label */ private func addTimeLabelToCell(cell: UICollectionViewCell, withDate date: NSDate) { let timeLabel: UILabel if let existingLabel = cell.viewWithTag(kTimeLabelTag) as? UILabel { timeLabel = existingLabel } else { timeLabel = self.timeLabel() cell.addSubview(timeLabel) } timeLabel.text = timeFormatter.stringFromDate(date) let size = timeLabel.sizeThatFits(cell.frame.size) timeLabel.frame.size = size timeLabel.frame = CGRect( origin: CGPoint( x: cell.frame.size.width - timeLabel.frame.size.width - 8, y: cell.frame.size.height - timeLabel.frame.size.height - 2 - alphaNameLabelHeight), size: timeLabel.frame.size) } } extension GlobalMessageServiceInboxViewController: GlobalMessageServiceMessageFetcherJSQDelegate { /** Calls when new remote push-notification delivered */ public func newMessagesFetched() { automaticallyScrollsToMostRecentMessage = true finishReceivingMessageAnimated(true) } } //extension GlobalMessageServiceInboxViewController: UISearchResultsUpdating { // // private func filterPresentedData(withText text: String?, // forScope scope: GlobalMessageServiceMessageType? = .None) { // // automaticallyScrollsToMostRecentMessage = true // // let searchText = text?.lowercaseString ?? "" // // let words = searchText.componentsSeparatedByString(" ").filter( { !$0.isEmpty }) // // if ((searchText.isEmpty && scope == .None) || words.count == 0) // && (selectedSearchMessageType == .None) { // filteredMessages = fetcher.messages // collectionView.reloadData() // return // } // // filteredMessages = fetcher.messages.filter { message -> Bool in // var acceptable: Bool = words.count == 0 // for searchText in words { // if message.alphaName.lowercaseString.containsString(searchText) { // acceptable = true // } // if let text = message.text() where text.lowercaseString.containsString(searchText) { // acceptable = true // } // } // if let scope = scope where acceptable { // acceptable = acceptable && message.type == scope // } // return acceptable // } // collectionView.reloadData() // } // // public func updateSearchResultsForSearchController(searchController: UISearchController) { // filterPresentedData(withText: searchController.searchBar.text, forScope: selectedSearchMessageType) // } // //} // //extension GlobalMessageServiceInboxViewController: UISearchBarDelegate { // public func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { // //let selectedCategory: PlaceCategory? // if selectedScope < 1 { // selectedSearchMessageType = .None // } else if (selectedScope - 1) < selectedSearchMessageTypes.count { // selectedSearchMessageType = selectedSearchMessageTypes[selectedScope - 1] // } else { // selectedSearchMessageType = .None // } // self.filterPresentedData(withText: searchController.searchBar.text, forScope: selectedSearchMessageType) // } //}
apache-2.0
ba4e4ac695324b03a62ce0859e4811a7
31.044068
119
0.721147
5.224095
false
false
false
false
gmission/gmission-ios
gmission/gmission/HTTP.swift
1
6013
// // HTTP.swift // gmission // // Created by CHEN Zhao on 4/12/2015. // Copyright © 2015 CHEN Zhao. All rights reserved. // import Foundation import Alamofire import SwiftyJSON let defaultUrlPrefix = "http://lccpu3.cse.ust.hk/gmission-dev/" class HTTP{ typealias OnFailFunc = (Int?, String?)->() static func isAuthError(statusCode:Int, content:String)->Bool{ if statusCode == 401{ return true } if statusCode == 400{ if content.containsString("Invalid JWT"){ return true } } return false } static func handleErrors(url:String, statusCode:Int?, content:String?){ print("Global handler: status: \(statusCode) content: \(content)") if let statusCode=statusCode{ if statusCode == 503{ EnhancedVC.showAlert("Server is unavailable now.", msg: "Please try again later.") }else if isAuthError(statusCode, content: content!){ print("auth error happened..") EnhancedVC.showModalLoginView() }else{ EnhancedVC.showAlert("HTTP Error \(statusCode)", msg: "request \(url) failed: \(content!)") } }else{ EnhancedVC.showAlert("Network error", msg: "Please try again later.") } } static func imageURLForName(name:String)->String{ return "\(defaultUrlPrefix)static/image/original/\(name)" } static func newRequest(method: Alamofire.Method, var _ url: String, _ parameters: [String : AnyObject]?, _ encoding: Alamofire.ParameterEncoding, _ headers: [String : String]?, onFail:OnFailFunc?) -> Alamofire.Request{ if !(url.hasPrefix("http://") || url.hasPrefix("https://")){ url = "\(defaultUrlPrefix)\(url)" } print("HTTP request: \(url) \(parameters)") let alamofireRequest = Alamofire.request(method, url, parameters: parameters, encoding:encoding, headers:headers).validate(statusCode: 200..<300).response { (req, resp, data, err) -> Void in print("status: \(resp?.statusCode)") if let e = err{ print("\(url) error: \(e)") let content = NSString(data: data!, encoding:NSUTF8StringEncoding) as? String if let onFail = onFail{ onFail(resp?.statusCode, content) }else{ print("to global handle error.", "url:", req?.URLString) HTTP.handleErrors(url, statusCode: resp?.statusCode, content: content ) } } } return alamofireRequest } static func newRequestWithToken(method: Alamofire.Method, _ url: String, _ parameters: [String : AnyObject]?, _ encoding: Alamofire.ParameterEncoding, onFail:OnFailFunc?) -> Alamofire.Request{ var headers = [String : String]() let token = UserManager.currentUser?.token ?? "" if token != ""{ headers["Authorization"] = "gMission \(token)" } return newRequest(method, url, parameters, encoding, headers, onFail:onFail) } static func requestJSON(method: Alamofire.Method, _ url:String, _ parameters:[String:AnyObject]?=nil, _ encoding:Alamofire.ParameterEncoding = .JSON, _ onFail:OnFailFunc?=nil, _ onJSONSucceed:(JSON)->()) -> Request{ return newRequestWithToken(method, url, parameters, encoding, onFail:onFail).responseJSON{ response in switch response.result{ case .Success: if let value = response.result.value { let json = JSON(value) // print("HTTP return:", json) onJSONSucceed(json) } case .Failure(let error): print(error) } } } static func uploadFile(var url:String, imageData:NSData, fileName:String, callback:(JSON:AnyObject?, error:NSError?)->()){ if !(url.hasPrefix("http://") || url.hasPrefix("https://")){ url = "\(defaultUrlPrefix)\(url)" } var headers = [String : String]() let token = UserManager.currentUser?.token ?? "" if token != ""{ headers["Authorization"] = "gMission \(token)" } Alamofire.upload(.POST, url, headers: headers, multipartFormData: { (multipartFormData) -> Void in multipartFormData.appendBodyPart(data: imageData, name: "file", fileName: fileName, mimeType: "image/jpg") }) { (encodingResult) -> Void in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) callback(JSON:response.result.value, error:nil) } case .Failure(let encodingError): print(encodingError) } } } class func uploadImage(imageData:NSData, fileName:String, callback:(nameFromServer:String?, error:NSError?)->()){ let urlStr = "image/upload" HTTP.uploadFile(urlStr, imageData: imageData, fileName: fileName, callback: {(JSON, error) in if let JSONDict = JSON as? NSDictionary{ callback(nameFromServer: (JSONDict["filename"] as! String), error: nil) }else{ callback(nameFromServer: nil, error: error!) } }) } // static func downloadFile(urlStr:String, callback:(imageData:NSData?, error:NSError?)->()){ // let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) // // Alamofire.request(.GET, urlStr).response { (request, response, data, error) in // callback(imageData: data as? NSData, error: error) // } // // } }
mit
f73b8cf4d92270033ae10653e31d5f44
39.086667
222
0.567199
4.821171
false
false
false
false
uber/RIBs
ios/RIBsTests/Worker/WorkerTests.swift
1
3384
// // Copyright (c) 2017. Uber Technologies // // 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 XCTest import RxSwift @testable import RIBs final class WorkerTests: XCTestCase { private var worker: TestWorker! private var interactor: InteractorMock! private var disposable: DisposeBag! // MARK: - Setup override func setUp() { super.setUp() disposable = DisposeBag() worker = TestWorker() interactor = InteractorMock() } // MARK: - Tests func test_didStart_onceOnly_boundToInteractor() { XCTAssertEqual(worker.didStartCallCount, 0) XCTAssertEqual(worker.didStopCallCount, 0) worker.start(interactor) XCTAssertTrue(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 0) XCTAssertEqual(worker.didStopCallCount, 0) interactor.activate() XCTAssertTrue(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 1) XCTAssertEqual(worker.didStopCallCount, 0) interactor.deactivate() XCTAssertTrue(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 1) XCTAssertEqual(worker.didStopCallCount, 1) worker.start(interactor) XCTAssertTrue(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 1) XCTAssertEqual(worker.didStopCallCount, 1) interactor.activate() XCTAssertTrue(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 2) XCTAssertEqual(worker.didStopCallCount, 1) worker.stop() XCTAssertFalse(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 2) XCTAssertEqual(worker.didStopCallCount, 2) worker.stop() XCTAssertFalse(worker.isStarted) XCTAssertEqual(worker.didStartCallCount, 2) XCTAssertEqual(worker.didStopCallCount, 2) } func test_start_stop_lifecycle() { worker.isStartedStream .take(1) .subscribe(onNext: { XCTAssertFalse($0) }) .disposed(by: disposable) interactor.activate() worker.start(interactor) worker.isStartedStream .take(1) .subscribe(onNext: { XCTAssertTrue($0) }) .disposed(by: disposable) worker.stop() worker.isStartedStream .take(1) .subscribe(onNext: { XCTAssertFalse($0) }) .disposed(by: disposable) } } private final class TestWorker: Worker { private(set) var didStartCallCount: Int = 0 private(set) var didStopCallCount: Int = 0 // MARK: - Overrides override func didStart(_ interactorScope: InteractorScope) { super.didStart(interactorScope) didStartCallCount += 1 } override func didStop() { super.didStop() didStopCallCount += 1 } }
apache-2.0
da1753596db85cee8857ad622f52a6c8
25.4375
76
0.659279
4.834286
false
true
false
false
markusthoemmes/openwhisk
tests/dat/actions/httpGet.swift
11
2101
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** * Sample code using the experimental Swift 3 runtime * with links to KituraNet and GCD */ import KituraNet import Dispatch import Foundation import SwiftyJSON func main(args:[String:Any]) -> [String:Any] { // Force KituraNet call to run synchronously on a global queue var str = "No response" dispatch_sync(dispatch_get_global_queue(0, 0)) { HTTP.get("https://httpbin.org/get") { response in do { str = try response!.readString()! } catch { print("Error \(error)") } } } // Assume string is JSON print("Got string \(str)") var result:[String:Any]? // Convert to NSData let data = str.data(using: NSUTF8StringEncoding, allowLossyConversion: true)! // test SwiftyJSON let json = JSON(data: data) if let jsonUrl = json["url"].string { print("Got json url \(jsonUrl)") } else { print("JSON DID NOT PARSE") } // create result object to return do { result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print("Error \(error)") } // return, which should be a dictionary print("Result is \(result!)") return result! }
apache-2.0
e52afa7fc5f4403a77c4e9424ed217a4
29.014286
94
0.646359
4.340909
false
false
false
false
anilkumarbp/ringcentral-swiftv2.0
src/Pods/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift
11
5512
// // ChaCha20.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 25/08/14. // Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved. // final public class ChaCha20 { public enum Error: ErrorType { case MissingContext } static let blockSize = 64 // 512 / 8 private let stateSize = 16 private var context:Context? final private class Context { var input:[UInt32] = [UInt32](count: 16, repeatedValue: 0) deinit { for i in 0..<input.count { input[i] = 0x00; } } } public init?(key:[UInt8], iv:[UInt8]) { if let c = contextSetup(iv: iv, key: key) { context = c } else { return nil } } public func encrypt(bytes:[UInt8]) throws -> [UInt8] { guard context != nil else { throw Error.MissingContext } return try encryptBytes(bytes) } public func decrypt(bytes:[UInt8]) throws -> [UInt8] { return try encrypt(bytes) } private final func wordToByte(input:[UInt32] /* 64 */) -> [UInt8]? /* 16 */ { if (input.count != stateSize) { return nil; } var x = input for _ in 0..<10 { quarterround(&x[0], &x[4], &x[8], &x[12]) quarterround(&x[1], &x[5], &x[9], &x[13]) quarterround(&x[2], &x[6], &x[10], &x[14]) quarterround(&x[3], &x[7], &x[11], &x[15]) quarterround(&x[0], &x[5], &x[10], &x[15]) quarterround(&x[1], &x[6], &x[11], &x[12]) quarterround(&x[2], &x[7], &x[8], &x[13]) quarterround(&x[3], &x[4], &x[9], &x[14]) } var output = [UInt8]() output.reserveCapacity(16) for i in 0..<16 { x[i] = x[i] &+ input[i] output.appendContentsOf(x[i].bytes().reverse()) } return output; } private func contextSetup(iv iv:[UInt8], key:[UInt8]) -> Context? { let ctx = Context() let kbits = key.count * 8 if (kbits != 128 && kbits != 256) { return nil } // 4 - 8 for i in 0..<4 { let start = i * 4 ctx.input[i + 4] = wordNumber(key[start..<(start + 4)]) } var addPos = 0; switch (kbits) { case 256: addPos += 16 // sigma ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3320646e //3 dn ctx.input[2] = 0x79622d32 //yb-2 ctx.input[3] = 0x6b206574 //k et default: // tau ctx.input[0] = 0x61707865 //apxe ctx.input[1] = 0x3620646e //6 dn ctx.input[2] = 0x79622d31 //yb-1 ctx.input[3] = 0x6b206574 //k et break; } // 8 - 11 for i in 0..<4 { let start = addPos + (i*4) let bytes = key[start..<(start + 4)] ctx.input[i + 8] = wordNumber(bytes) } // iv ctx.input[12] = 0 ctx.input[13] = 0 ctx.input[14] = wordNumber(iv[0..<4]) ctx.input[15] = wordNumber(iv[4..<8]) return ctx } private final func encryptBytes(message:[UInt8]) throws -> [UInt8] { guard let ctx = context else { throw Error.MissingContext } var c:[UInt8] = [UInt8](count: message.count, repeatedValue: 0) var cPos:Int = 0 var mPos:Int = 0 var bytes = message.count while (true) { if let output = wordToByte(ctx.input) { ctx.input[12] = ctx.input[12] &+ 1 if (ctx.input[12] == 0) { ctx.input[13] = ctx.input[13] &+ 1 /* stopping at 2^70 bytes per nonce is user's responsibility */ } if (bytes <= ChaCha20.blockSize) { for i in 0..<bytes { c[i + cPos] = message[i + mPos] ^ output[i] } return c } for i in 0..<ChaCha20.blockSize { c[i + cPos] = message[i + mPos] ^ output[i] } bytes -= ChaCha20.blockSize cPos += ChaCha20.blockSize mPos += ChaCha20.blockSize } } } private final func quarterround(inout a:UInt32, inout _ b:UInt32, inout _ c:UInt32, inout _ d:UInt32) { a = a &+ b d = rotateLeft((d ^ a), 16) //FIXME: WAT? n: c = c &+ d b = rotateLeft((b ^ c), 12); a = a &+ b d = rotateLeft((d ^ a), 8); c = c &+ d b = rotateLeft((b ^ c), 7); } } // MARK: - Cipher extension ChaCha20: Cipher { public func cipherEncrypt(bytes:[UInt8]) throws -> [UInt8] { return try self.encrypt(bytes) } public func cipherDecrypt(bytes: [UInt8]) throws -> [UInt8] { return try self.decrypt(bytes) } } // MARK: Helpers /// Change array to number. It's here because arrayOfBytes is too slow private func wordNumber(bytes:ArraySlice<UInt8>) -> UInt32 { var value:UInt32 = 0 for i:UInt32 in 0..<4 { let j = bytes.startIndex + Int(i) value = value | UInt32(bytes[j]) << (8 * i) } return value}
mit
ef6af89af205149185a88ec8c64db8a4
26.56
107
0.458454
3.744565
false
false
false
false
meetkei/KeiSwiftFramework
KeiSwiftFramework/View/KRoundView.swift
1
2067
// // KRoundView.swift // // Copyright (c) 2016 Keun young Kim <[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 @IBDesignable open class KRoundView: UIView { @IBInspectable open var cornerRadius: CGFloat = 3 { didSet { setupView() } } @IBInspectable open var borderWidth: CGFloat = 0 { didSet { setupView() } } @IBInspectable open var borderColor: UIColor = UIColor.clear { didSet { setupView() } } public override init(frame: CGRect) { super.init(frame: frame) setupView() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupView() } func setupView() { layer.cornerRadius = cornerRadius layer.borderWidth = borderWidth layer.borderColor = borderColor.cgColor clipsToBounds = true } }
mit
0c8809b4e6e0b30748cd845817d0bda3
27.708333
81
0.652153
4.708428
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift
5
4813
// // ObservableType+Extensions.swift // RxSwift // // Created by Krunoslav Zaher on 2/21/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if DEBUG import Foundation #endif extension ObservableType { /** Subscribes an event handler to an observable sequence. - parameter on: Action to invoke for each event in the observable sequence. - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(_ on: @escaping (Event<E>) -> Void) -> Disposable { let observer = AnonymousObserver { e in on(e) } return self.asObservable().subscribe(observer) } /** Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. - parameter onNext: Action to invoke for each element in the observable sequence. - parameter onError: Action to invoke upon errored termination of the observable sequence. - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has gracefully completed, errored, or if the generation is canceled by disposing subscription). - returns: Subscription object used to unsubscribe from the observable sequence. */ public func subscribe(onNext: ((E) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil, onDisposed: (() -> Void)? = nil) -> Disposable { let disposable: Disposable if let disposed = onDisposed { disposable = Disposables.create(with: disposed) } else { disposable = Disposables.create() } #if DEBUG let synchronizationTracker = SynchronizationTracker() #endif let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] let observer = AnonymousObserver<E> { event in #if DEBUG synchronizationTracker.register(synchronizationErrorMessage: .default) defer { synchronizationTracker.unregister() } #endif switch event { case .next(let value): onNext?(value) case .error(let error): if let onError = onError { onError(error) } else { Hooks.defaultErrorHandler(callStack, error) } disposable.dispose() case .completed: onCompleted?() disposable.dispose() } } return Disposables.create( self.asObservable().subscribe(observer), disposable ) } } import class Foundation.NSRecursiveLock extension Hooks { public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void public typealias CustomCaptureSubscriptionCallstack = () -> [String] fileprivate static let _lock = RecursiveLock() fileprivate static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in #if DEBUG let serializedCallStack = subscriptionCallStack.joined(separator: "\n") print("Unhandled error happened: \(error)\n subscription called from:\n\(serializedCallStack)") #endif } fileprivate static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { #if DEBUG return Thread.callStackSymbols #else return [] #endif } /// Error handler called in case onError handler wasn't provided. public static var defaultErrorHandler: DefaultErrorHandler { get { _lock.lock(); defer { _lock.unlock() } return _defaultErrorHandler } set { _lock.lock(); defer { _lock.unlock() } _defaultErrorHandler = newValue } } /// Subscription callstack block to fetch custom callstack information. public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { get { _lock.lock(); defer { _lock.unlock() } return _customCaptureSubscriptionCallstack } set { _lock.lock(); defer { _lock.unlock() } _customCaptureSubscriptionCallstack = newValue } } }
apache-2.0
a3752dedd725e1b1a537980dca531acf
35.732824
163
0.587697
5.861145
false
false
false
false
steelwheels/Canary
Source/CNNumber.swift
1
1497
/** * @file NSNumberExtension.h * @brief Extend NSNumber class * @par Copyright * Copyright (C) 2016,2017 Steel Wheels Project */ import Foundation public enum NSNumberKind:Int { case int8Number case uInt8Number case int16Number case uInt16Number case int32Number case uInt32Number case int64Number case uInt64Number case doubleNumber case floatNumber public var description:String { get { var result: String switch self { case .int8Number: result = "int8" case .uInt8Number: result = "uInt8" case .int16Number: result = "int16" case .uInt16Number: result = "uInt16" case .int32Number: result = "int32" case .uInt32Number: result = "uInt32" case .int64Number: result = "int64" case .uInt64Number: result = "uInt64" case .doubleNumber: result = "double" case .floatNumber: result = "float" } return result } } } extension NSNumber { public var kind: NSNumberKind { get { return decodeKind() } } internal func decodeKind() -> NSNumberKind { var result: NSNumberKind switch String(cString: self.objCType) { case "c": result = .int8Number case "C": result = .uInt8Number case "s": result = .int16Number case "S": result = .uInt16Number case "i": result = .int32Number case "I": result = .uInt32Number case "q": result = .int64Number case "Q": result = .uInt64Number case "f": result = .floatNumber case "d": result = .doubleNumber default: fatalError("Unknown number kind") } return result } }
gpl-2.0
fddf7e9aeb670ca015e5fc60791eddf1
22.030769
49
0.692051
3.04888
false
false
false
false
williamFalcon/Bolt_Swift
Source/Set/Set.swift
2
619
// // Set.swift // Testee // // Created by William Falcon on 5/23/15. // Copyright (c) 2015 William Falcon. All rights reserved. // import Foundation public extension Set { /** Returns char at an index Example: string[0] == "a" */ subscript (index: Int) -> Element { //support negative indices var i = index if i < 0 { i = self.count - abs(index) } var array = _allObjects //return the requested item return array[i] } var _allObjects : Array<Element> { return Array(self) } }
mit
b464844fcb92752ae4cca16222df4dc6
17.757576
59
0.52504
3.967949
false
false
false
false
seanhenry/Chain
Chain/Chain.swift
1
1071
// // Chain.swift // // Copyright © 2016 Sean Henry. All rights reserved. // import Swift open class Chain<InitialType, ResultType>: Runnable { let last: Link<InitialType, ResultType> public init(_ link: Link<InitialType, ResultType>) { self.last = link } public init(initialValue: InitialType, _ link: Link<InitialType, ResultType>) { link.initial = .success(initialValue) self.last = link } open func then<T>(_ link: Link<ResultType, T>) -> Chain<ResultType, T> { link.previous = last last.next = link return Chain<ResultType, T>(link) } open func finally(_ block: @escaping (ChainResult<ResultType, Error>) -> ()) -> Runnable { let blockLink = BlockLink(block: block) last.next = blockLink return self } func findFirst() -> RunnableLink { var previous: RunnableLink = last while let p = previous.previous { previous = p } return previous } open func run() { findFirst().run() } }
mit
bddb7d444b4e2efcb36044bf510dc720
22.777778
94
0.593458
4.163424
false
false
false
false
0x0c/RDImageViewerController
RDImageViewerController/Classes/View/PagingView/PagingViewFlowLayout.swift
1
1113
// // PagingViewFlowLayout.swift // Pods-RDImageViewerController_Example // // Created by Akira Matsuda on 2020/01/16. // import UIKit class PagingViewFlowLayout: UICollectionViewFlowLayout { private var previousSizs: CGSize = .zero var currentPageIndex: PagingView.VisibleIndex = .single(index: 0) var isDoubleSpread: Bool = false var ignoreTargetContentOffset = false override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint) -> CGPoint { if ignoreTargetContentOffset { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset) } guard let collectionView = collectionView else { return super.targetContentOffset(forProposedContentOffset: proposedContentOffset) } let width = collectionView.frame.width var xPosition = CGFloat(currentPageIndex.primaryIndex()) * width if collectionView.contentOffset.x <= xPosition, isDoubleSpread { xPosition = collectionView.contentOffset.x } return CGPoint(x: xPosition, y: 0) } }
mit
51e3bd165b7126545cf9c0ef7521052a
36.1
107
0.720575
5.678571
false
false
false
false
jemmons/SessionArtist
Tests/SessionArtistTests/PostTests.swift
1
1653
import Foundation import XCTest import SessionArtist import Perfidy class PostTests: XCTestCase { let fakeHost = Host(baseURL: FakeServer.defaultURL) func testPostParams() { doFakePost("/test", json: ["foo": "bar"], headers: [:]) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Content-Type"], "application/json") XCTAssertEqual(req.httpBody, "{\"foo\":\"bar\"}".data(using: .utf8)) } } func testPostEmptyParams() { doFakePost("/test", json: [:], headers: [:]) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Content-Type"], "application/json") XCTAssertEqual(req.httpBody, "{}".data(using: .utf8)) } } func testPostHeaders() { doFakePost("/test", json: [:], headers: [.accept: "foobar"]) { req in XCTAssertEqual(req.allHTTPHeaderFields!["Accept"], "foobar") } } } private extension PostTests { func doFakePost(_ path: String, json: JSONObject, headers: [HTTPHeaderField: String], postHandler: @escaping (URLRequest)->Void) { let expectedRequest = expectation(description: "waiting for request") let expectedResponse = expectation(description: "waiting for response") FakeServer.runWith { server in server.add(Route(method: .post, path: path)) { req in postHandler(req) expectedRequest.fulfill() } let validJSON = try! ValidJSONObject(json) fakeHost.post(path, json: validJSON, headers: headers).data { res in if case .success((.ok, _, _)) = res { expectedResponse.fulfill() } } wait(for: [expectedRequest, expectedResponse], timeout: 1) } } }
mit
0d37320f218e64fdac112c1e3f036957
27.5
132
0.640653
4.238462
false
true
false
false
analuizaferrer/TrocaComigo
Example/SwapIt/UserTableViewController.swift
1
6270
// // UserTableViewController.swift // Koloda // // Created by Helena Leitão on 14/06/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Firebase var closetArray : [NSData] = [] class UserTableViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var profileImage: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! var closetImageIds : [String] = [] override func viewDidLoad() { super.viewDidLoad() self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2 self.profileImage.clipsToBounds = true profileImage.contentMode = UIViewContentMode.ScaleAspectFill let user = UIImage(named: "user-fill") let imageView = UIImageView(image: user) self.navigationItem.titleView = imageView generateClosetImageIDArray() } func generateClosetImageIDArray () { for i in User.singleton.products { closetImageIds.append(i.id!) } DAO().getClosetImages(closetImageIds, callback: { images in for image in images { closetArray.append(image) print("appending 2") } }) } override func viewWillAppear(animated: Bool) { if User.singleton.name != nil { self.nameLabel.text = User.singleton.name } if User.singleton.location != nil { self.locationLabel.text = User.singleton.location } if User.singleton.profilePic != nil { profileImage.image = User.singleton.profilePic } let imageData: NSData = UIImagePNGRepresentation(profileImage.image!)! DAO().registerProfilePic(imageData) User.singleton.profilePic = profileImage.image } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func callbackName(snapshot: FIRDataSnapshot) { self.nameLabel.text = snapshot.value! as? String } func callbackLocation(snapshot: FIRDataSnapshot) { self.locationLabel.text = snapshot.value! as? String } @IBAction func image(sender: AnyObject) { let alert = UIAlertController(title: "Change Profile Photo", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let removeCurrentPhoto = UIAlertAction(title: "Remove Current Photo", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in self.profileImage.image = UIImage(named: "profile") User.singleton.profilePic = self.profileImage.image DAOCache().saveUser() }) alert.addAction(removeCurrentPhoto) let takePhoto = UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .Camera self.presentViewController(picker, animated: true, completion: nil) }) alert.addAction(takePhoto) let chooseFromLibrary = UIAlertAction(title: "Choose From Library", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction) in let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .PhotoLibrary self.presentViewController(picker, animated: true, completion: nil) }) alert.addAction(chooseFromLibrary) let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) alert.addAction(cancel) self.presentViewController(alert, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let profilePhoto = info[UIImagePickerControllerOriginalImage] as? UIImage; dismissViewControllerAnimated(true, completion: nil) self.profileImage.image = profilePhoto User.singleton.profilePic = profilePhoto DAOCache().saveUser() } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.row { case 1: performSegueWithIdentifier("profile", sender: self) break case 2: if closetArray.count == User.singleton.products.count { self.performSegueWithIdentifier("closet", sender: self) } break case 3: performSegueWithIdentifier("settings", sender: self) break default: print("pmsdinv") } } override func viewDidLayoutSubviews() { if self.tableView.respondsToSelector(Selector("setSeparatorInset:")) { self.tableView.separatorInset = UIEdgeInsetsZero } if self.tableView.respondsToSelector(Selector("setLayoutMargins:")) { self.tableView.layoutMargins = UIEdgeInsetsZero } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector(Selector("setSeparatorInset:")) { cell.separatorInset = UIEdgeInsetsZero } if cell.respondsToSelector(Selector("setLayoutMargins:")) { cell.layoutMargins = UIEdgeInsetsZero } } func encodeProfilePhoto (profilePhoto: UIImage) -> String { //Image into NSData format let imageData:NSData = UIImagePNGRepresentation(profilePhoto)! //Encoding let strBase64:String = imageData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) return strBase64 } }
mit
b113b66888040a24766b55fca62d9c92
32.340426
148
0.62508
5.755739
false
false
false
false
dn-m/Collections
Collections/Stack.swift
1
4126
// // Stack.swift // Collections // // Created by James Bean on 12/9/16. // // import Algebra /// Stack structure. public struct Stack <Element> { fileprivate var elements: [Element] = [] // MARK: - Instance Properties /// Top element of `Stack`. public var top: Element? { return elements.last } /// - returns: The `top` and the remaining items, if possible. Otherwise, `nil`. public var destructured: (Element, Stack<Element>)? { guard self.count > 0 else { return nil } var copy = self let top = copy.pop()! return (top, copy) } // MARK: - Initializers /// Create an empty `Stack`. public init() { } /// Create a `Stack` with the given sequence of `elements`. public init <S: Sequence> (_ elements: S) where S.Iterator.Element == Element { self.elements = Array(elements) } // MARK: - Instance Methods /// Push item to end of `Stack`. public mutating func push(_ item: Element) { elements.append(item) } /// - returns: A new `Stack` with the given `item` pushed to the top. public func pushing(_ item: Element) -> Stack<Element> { var copy = self copy.push(item) return copy } /// - returns: Item from top of `Stack` if there are any. Otherwise, `nil`. @discardableResult public mutating func pop() -> Element? { return elements.popLast() } /// - returns: `Stack` containing items popped from end of `Stack` public mutating func pop(amount: Int) -> Stack<Element>? { guard elements.count > amount else { return nil } var poppedItems = Stack<Element>() for _ in 0..<amount { poppedItems.push(pop()!) } return poppedItems } // TODO: - Returns: original, modified stack, with popped items, if possible. Otherwise, `nil`. // func popping(amount: Int) -> (Stack<Element>, Stack<Element>)? { ... } } extension Stack: Collection { // MARK: - `Collection` /// - Returns: Index after the given `index`. public func index(after index: Int) -> Int { assert(index < endIndex, "Cannot increment to \(index + 1).") return index + 1 } /// - Start index. public var startIndex: Int { return 0 } /// - End index. public var endIndex: Int { return elements.count } /// - returns: Element at the given `index`. public subscript (index: Int) -> Element { return elements[index] } } extension Stack: BidirectionalCollection { /// - Returns: Index before the given `index`. public func index(before index: Int) -> Int { assert(index > 0, "Cannot decrement index to \(index - 1)") return index - 1 } /// Count of elements contained herein. /// /// - Complexity: O(_1_) /// public var count: Int { return elements.count } } extension Stack: ExpressibleByArrayLiteral { // MARK: - `ExpressibleByArrayLiteral`. /// - returns: Create a `SortedArray` with an array literal. public init(arrayLiteral elements: Element...) { self.init(elements) } } extension Stack: Additive { // MARK: - Additive /// - Returns: Empty `Stack`. public static var zero: Stack<Element> { return Stack() } /// - Returns: `Stack` with the contents of two `Stack` values. public static func + (lhs: Stack, rhs: Stack) -> Stack { return Stack(lhs.elements + rhs.elements) } } extension Stack: Monoid { // MARK: - Monoid /// - Returns: Empty `Stack`. public static var identity: Stack<Element> { return .zero } /// - Returns: Composition of two of the same `Semigroup` type values. public static func <> (lhs: Stack<Element>, rhs: Stack<Element>) -> Stack<Element> { return lhs + rhs } } /// - returns: `true` if all items in both `Stack` structs are equivalent. Otherwise `false`. public func == <T: Equatable> (lhs: Stack<T>, rhs: Stack<T>) -> Bool { return lhs.elements == rhs.elements }
mit
908fcd81fc3de7bae26caa017f1576d6
23.855422
99
0.589433
4.097319
false
false
false
false
box/box-ios-sdk
Sources/Core/Coders.swift
1
986
import Foundation let requestBodyEncoder: JSONEncoder = { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.keyEncodingStrategy = .convertToSnakeCase return encoder }() let requestBodyEncoderWithDefaultKeys: JSONEncoder = { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.keyEncodingStrategy = .useDefaultKeys return encoder }() let responseBodyDecoder: JSONDecoder = { let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder }() let prettyPrintEncoder: JSONEncoder = { let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 encoder.keyEncodingStrategy = .convertToSnakeCase encoder.outputFormatting = .prettyPrinted return encoder }() let queryParameterEncoder: JSONEncoder = { JSONEncoder() }() let queryParameterDecoder: JSONDecoder = { JSONDecoder() }()
apache-2.0
f2c5178dae76255dbb5babb28dc76c49
24.947368
55
0.744422
5.417582
false
false
false
false
hhcszgd/cszgdCode
weibo1/weibo1/AppDelegate.swift
1
8248
// // AppDelegate.swift // weibo1 // // Created by WY on 15/11/26. // Copyright © 2015年 WY. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeVC:", name: JumpVCNotification, object: nil) // Override point for customization after application launch. window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() window?.rootViewController = returnVC ()//UINavigationController(rootViewController: LoginVC())// window?.makeKeyAndVisible() // let account = Account.loadAccount() return true } func changeVC (noti:NSNotification){ window?.rootViewController = noti.object == nil ? BarViewController () : WelcomeVC() // print("通知来了,走不走") //判断用户是否登录 //如果已经登录就检查是否是新版本, //如果是新版本跳转到新特性(再发通知自动跳转到主界面) //如果不是新版本跳转到欢迎界面(再发通知自动跳转到主界面) //如果没有登录,跳转到主控制器的 访客视图界面 //点击登录跳转到loginVC //登录成功,跳转到欢迎界面(再发通知自动跳转到主界面) // print("打印通知信息\(noti)") } func returnVC () -> (UIViewController){ if UserAccountViewModel().userLogin { if isNewBuNew() { return NewFeatureCollectionVC() } return WelcomeVC() } return BarViewController() } //判断新老版本 func isNewBuNew () ->Bool{ let dict = NSBundle.mainBundle().infoDictionary let currentVersion = (dict!["CFBundleShortVersionString"] as! NSString).doubleValue let userDef = NSUserDefaults.standardUserDefaults() let oldVersion = userDef.doubleForKey("versionNum") if currentVersion > oldVersion { // print("新版本") userDef.setDouble(currentVersion, forKey: "versionNum") // print("版本信息\(currentVersion+1)") return true }else{ // print("老版本") return false } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "hhcszgd.weibo1" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("weibo1", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
apache-2.0
74afbf7dea08ce60f558f57f71a3578a
46.267857
291
0.680645
5.619958
false
false
false
false
Mogendas/apiproject
apiproject/WeatherVC.swift
1
3617
// // WeatherVC.swift // apiproject // // Created by Johan Wejdenstolpe on 2017-05-05. // Copyright © 2017 Johan Wejdenstolpe. All rights reserved. // import UIKit class WeatherVC: UIViewController { var weatherData: [String: Any]? @IBOutlet weak var weatherLocation: UILabel! @IBOutlet weak var weatherDescription: UILabel! @IBOutlet weak var weatherTemperature: UILabel! @IBOutlet weak var weatherWindSpeed: UILabel! @IBOutlet weak var weatherImage: UIImageView! @IBOutlet weak var windArrow: UIImageView! override func viewDidLoad() { super.viewDidLoad() if let location = weatherData!["location"] as? String, let description = weatherData?["description"] as? String, let temp = weatherData?["temp"] as? String, let wind = weatherData?["windDeg"] as? String, let windSpeed = weatherData?["windSpeed"] as? String, let icon = weatherData?["icon"] as? String { switch icon { case "01d": weatherImage.image = #imageLiteral(resourceName: "01d") break case "01n": weatherImage.image = #imageLiteral(resourceName: "01n") break case "02d": weatherImage.image = #imageLiteral(resourceName: "02d") break case "02n": weatherImage.image = #imageLiteral(resourceName: "02n") break case "03d": weatherImage.image = #imageLiteral(resourceName: "03d") break case "03n": weatherImage.image = #imageLiteral(resourceName: "03n") break case "04d": weatherImage.image = #imageLiteral(resourceName: "04d") break case "04n": weatherImage.image = #imageLiteral(resourceName: "04n") break case "09d": weatherImage.image = #imageLiteral(resourceName: "09d") break case "09n": weatherImage.image = #imageLiteral(resourceName: "09n") break case "10d": weatherImage.image = #imageLiteral(resourceName: "10d") break case "10n": weatherImage.image = #imageLiteral(resourceName: "10n") break case "11d": weatherImage.image = #imageLiteral(resourceName: "11d") break case "11n": weatherImage.image = #imageLiteral(resourceName: "11n") break case "13d": weatherImage.image = #imageLiteral(resourceName: "13d") break case "13n": weatherImage.image = #imageLiteral(resourceName: "13n") break default: weatherImage.image = #imageLiteral(resourceName: "na") } weatherLocation.text = "\(location)" weatherDescription.text = "\(description.capitalized)" weatherTemperature.text = "\(temp)ºc" let degrees = Double(wind) let radians: CGFloat = CGFloat(degrees! * Double.pi/180) windArrow.transform = windArrow.transform.rotated(by: radians) weatherWindSpeed.text = "\(windSpeed) m/s" } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
gpl-3.0
abd8d94a007a0d781134a2631c207f52
33.103774
310
0.541355
5.12766
false
false
false
false
jjjjjeffrey/DQLoopBanner
Example/DQLoopBanner/ViewController.swift
1
1591
// // ViewController.swift // DQLoopBanner // // Created by zengdaqian on 11/04/2015. // Copyright (c) 2015 zengdaqian. All rights reserved. // import UIKit import DQLoopBanner class ViewController: UIViewController { @IBOutlet var bannerView: LoopBannerView! @IBOutlet var pageControl: UIPageControl! override func viewDidLoad() { super.viewDidLoad() self.bannerView.dataSource = self self.bannerView.pageIndex = 3 self.pageControl.numberOfPages = 5; self.pageControl.currentPage = self.bannerView.pageIndex self.bannerView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: LoopBannerViewDataSource { func numberOfBannersInLoopBannerView(_ loopBannerView: LoopBannerView) -> Int { return 5 } func loopBannerView(_ loopBannerView: LoopBannerView, bannerForIndex index: Int) -> UIView { let colors = [UIColor.gray, UIColor.lightGray, UIColor.red, UIColor.blue, UIColor.purple] return { let view = UIView() view.backgroundColor = colors[index] return view }() } func loopBannerView(_ loopBannerView: LoopBannerView, didScrollToIndex index: Int) { self.pageControl.currentPage = index } func loopBannerView(_ loopBannerView: LoopBannerView, didTappedBannerForIndex index: Int) { print("点击第\(index+1)页") } }
mit
2efa50ff88d1baeeaf063eef8285e5ca
25.830508
97
0.660771
4.916149
false
false
false
false
benlangmuir/swift
test/Constraints/default_literals.swift
66
920
// RUN: %target-typecheck-verify-swift func acceptInt(_ : inout Int) {} func acceptDouble(_ : inout Double) {} var i1 = 1 acceptInt(&i1) var i2 = 1 + 2.0 + 1 acceptDouble(&i2) func ternary<T>(_ cond: Bool, _ ifTrue: @autoclosure () -> T, _ ifFalse: @autoclosure () -> T) -> T {} _ = ternary(false, 1, 2.5) _ = ternary(false, 2.5, 1) // <rdar://problem/18447543> _ = ternary(false, 1, 2 as Int32) _ = ternary(false, 1, 2 as Float) func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(_ x: T) { var _ : T = 2.5 } var d = 3.5 genericFloatingLiteral(d) extension UInt32 { func asChar() -> UnicodeScalar { return UnicodeScalar(self)! } } var ch = UInt32(65).asChar() // <rdar://problem/14634379> extension Int { func call0() {} typealias Signature = (a: String, b: String) func call(_ x: Signature) {} } 3.call((a: "foo", b: "bar")) var (div, mod) = (9 / 4, 9 % 4)
apache-2.0
47fc22f70b1227f0ad84236960379e7f
19.909091
68
0.598913
2.857143
false
false
false
false
PjGeeroms/IOSRecipeDB
YummlyProject/Controllers/LoginViewController.swift
1
2267
// // LoginViewController.swift // YummlyProject // // Created by Pieter-Jan Geeroms on 27/12/2016. // Copyright © 2016 Pieter-Jan Geeroms. All rights reserved. // import Foundation import UIKit import Alamofire import SwiftyJSON class LoginViewController: UIViewController { @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var error: UILabel! override func viewDidLoad() { error.isHidden = true } @IBAction func login() { let email = self.email.text! let password = self.password.text! let parameters: Parameters = [ "user": [ "email" : email, "password" : password ], ] let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type" : "application/json" ] let url = "http://recipedb.pw/api/users/login" Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: { response in if response.result.isSuccess { let data = JSON(response.result.value!) if !data["errors"].dictionaryValue.isEmpty { self.error.text = "Username or password is invalid" self.error.isHidden = false } if !data["user"].dictionaryValue.isEmpty { self.error.isHidden = true let userData = data["user"].dictionaryValue let user = Service.shared.user user.email = userData["email"]!.string! user.username = userData["username"]!.string! user.token = userData["token"]!.string! self.performSegue(withIdentifier: "startScreen", sender: self) } } }) } } extension LoginViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
2f8852295a7e28c64941c7df71be77d0
29.621622
165
0.544572
5.269767
false
false
false
false
elationfoundation/Reporta-iOS
IWMF/ViewControllers/AlertViewController/SituationViewController.swift
1
12616
// // SituationViewController.swift // IWMF // // This class is used for display and select situations for Alert. // // import UIKit protocol AlertSituationProtocol{ func alertSituation(situation : NSString) } class SituationViewController: UIViewController,UITableViewDataSource, UITableViewDelegate, SituationCellDoneProtocol,ARSituationCellDoneProtocol { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var btnBack: UIButton! @IBOutlet weak var ARbtnBack: UIButton! var arrRawData: NSMutableArray! var delegat : AlertSituationProtocol! var situationTitle : NSString! var arrSelected : NSMutableArray! @IBOutlet weak var alertLable: UILabel! override func viewDidLoad() { super.viewDidLoad() alertLable.text=NSLocalizedString(Utility.getKey("alerts"),comment:"") btnBack.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal) ARbtnBack.setTitle(NSLocalizedString(Utility.getKey("back"),comment:""), forState: .Normal) self.alertLable.font = Utility.setNavigationFont() self.arrRawData = NSMutableArray() if let path = NSBundle.mainBundle().pathForResource("IAmFacing", ofType: "plist") { arrRawData = NSMutableArray(contentsOfFile: path) let arrTemp : NSMutableArray = NSMutableArray(array: arrRawData) for (index, element) in arrTemp.enumerate() { if var innerDict = element as? Dictionary<String, AnyObject> { let strTitle = innerDict["Title"] as! String! if strTitle.characters.count != 0 { innerDict["Title"] = NSLocalizedString(Utility.getKey(strTitle),comment:"") arrRawData.replaceObjectAtIndex(index, withObject: innerDict) } } } } updateRawData() self.tableView.registerNib(UINib(nibName: "FrequencyTitleTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.TitleTableViewCellIdentifier) self.tableView.registerNib(UINib(nibName: "FrequencyDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier) self.tableView.registerNib(UINib(nibName: "SituationTitleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.SituationTitleCellIdentifier) self.tableView.registerNib(UINib(nibName: "ARDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARDetailTableViewCellIdentifier) self.tableView.registerNib(UINib(nibName: "ARSituationTitleCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: Structures.TableViewCellIdentifiers.ARSituationTitleCellIdentifier) self.tableView.registerNib(UINib(nibName: "NewDetailTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "NewDetailTableViewCell") self.tableView.rowHeight = UITableViewAutomaticDimension } func updateRawData(){ if self.situationTitle.length > 0{ arrSelected = NSMutableArray(array: self.situationTitle.componentsSeparatedByString(",, ")) for (index, element) in self.arrRawData.enumerate() { if var innerDict = element as? Dictionary<String, AnyObject> { let mainTitle = innerDict["Title"] as! NSString! var isFound : Bool = false for selTitle in self.arrSelected{ let tempTitle : NSString = selTitle as! NSString if mainTitle == tempTitle{ isFound = true } } if isFound { innerDict["IsSelected"] = true }else{ innerDict["IsSelected"] = false } self.arrRawData.replaceObjectAtIndex(index, withObject: innerDict) } } }else{ arrSelected = NSMutableArray() } self.tableView.reloadData() } override func viewWillAppear(animated: Bool) { if Structures.Constant.appDelegate.isArabic == true { btnBack.hidden = true ARbtnBack.hidden = false } else { btnBack.hidden = false ARbtnBack.hidden = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnBackPressed(sender: AnyObject) { self.navigationController?.popViewControllerAnimated(true) } @IBAction func doneBtnPressed(sender: AnyObject) { delegat?.alertSituation(self.situationTitle) self.navigationController?.popViewControllerAnimated(true) } func doneButtonPressed() { if situationTitle.length != 0 { delegat?.alertSituation(self.situationTitle) self.navigationController?.popViewControllerAnimated(true) } } //MARK : - TableView Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.arrRawData.count } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let kRowHeight = self.arrRawData[indexPath.row]["RowHeight"] as! CGFloat if Structures.Constant.appDelegate.isArabic == false { let strInfo : String! = self.arrRawData[indexPath.row]["Title"] as! String let rect = strInfo.boundingRectWithSize(CGSizeMake(UIScreen.mainScreen().bounds.size.width-50, 999), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName : Utility.setFont()], context: nil) let H :CGFloat = rect.height + 25 if kRowHeight > H{ return kRowHeight } return H } return kRowHeight; } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if Structures.Constant.appDelegate.isArabic == true { let cell: ARSituationTitleCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.ARSituationTitleCellIdentifier) as! ARSituationTitleCell cell.lblTitle.text = NSLocalizedString(Utility.getKey("I am facing"),comment:"") cell.btnDone.setTitle(NSLocalizedString(Utility.getKey("done"),comment:""), forState: .Normal) cell.delegate = self cell.intialize() return cell } else { let cell: SituationTitleCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.SituationTitleCellIdentifier) as! SituationTitleCell cell.lblTitle.text = NSLocalizedString(Utility.getKey("I am facing"),comment:"") cell.btnDone.setTitle(NSLocalizedString(Utility.getKey("done"),comment:""), forState: .Normal) cell.delegate = self cell.intialize() return cell } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 46 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let kCellIdentifier = self.arrRawData[indexPath.row]["CellIdentifier"] as! String if let cell: TitleTableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as? TitleTableViewCell { cell.lblDetail.text = "" cell.levelString = self.arrRawData[indexPath.row]["Level"] as! NSString! cell.lblTitle.text = self.arrRawData[indexPath.row]["Title"] as! String! cell.type = self.arrRawData[indexPath.row]["Type"] as! Int! cell.intialize() return cell } if Structures.Constant.appDelegate.isArabic == true && kCellIdentifier == Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier { if let cell: ARDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier(Structures.TableViewCellIdentifiers.ARDetailTableViewCellIdentifier) as? ARDetailTableViewCell { cell.lblSubDetail.text = "" cell.levelString = self.arrRawData[indexPath.row]["Level"] as! NSString! cell.lblDetail.text = self.arrRawData[indexPath.row]["Title"] as! String! cell.isSelectedValue = self.arrRawData[indexPath.row]["IsSelected"] as! Bool! cell.type = self.arrRawData[indexPath.row]["Type"] as! Int! cell.intialize() dispatch_async(dispatch_get_main_queue(), { () -> Void in cell.lblDetail.translatesAutoresizingMaskIntoConstraints = true cell.lblDetail.numberOfLines = 0 cell.lblDetail.lineBreakMode = NSLineBreakMode.ByWordWrapping }) cell.lblWidth.constant = UIScreen.mainScreen().bounds.size.width - 34 cell.widthChooseOption.constant = 0 return cell } } else { if kCellIdentifier == Structures.TableViewCellIdentifiers.DetailTableViewCellIdentifier { if let cell: NewDetailTableViewCell = tableView.dequeueReusableCellWithIdentifier("NewDetailTableViewCell") as? NewDetailTableViewCell { cell.levelString = self.arrRawData[indexPath.row]["Level"] as! NSString! cell.lblDetail.text = self.arrRawData[indexPath.row]["Title"] as! String! cell.isSelectedValue = self.arrRawData[indexPath.row]["IsSelected"] as! Bool! cell.type = self.arrRawData[indexPath.row]["Type"] as! Int! cell.intialize() return cell } } } let blankCell : UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier)! return blankCell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let title : NSString = self.arrRawData[indexPath.row]["Title"] as! NSString! if self.arrSelected.containsObject(title){ self.arrSelected.removeObject(title) }else{ self.arrSelected.addObject(title) } let strMutable : NSMutableString = NSMutableString() for(var i : Int = 0 ; i < self.arrSelected.count ; i++) { if self.arrSelected.count == 1{ strMutable.appendString((self.arrSelected.objectAtIndex(i) as! String)) } else if self.arrSelected.count - 1 == i{ strMutable.appendString((self.arrSelected.objectAtIndex(i) as! String)) } else{ strMutable.appendString((self.arrSelected.objectAtIndex(i) as! String)) strMutable.appendString(",, ") } } self.situationTitle = strMutable for (index, element) in self.arrRawData.enumerate() { if var innerDict = element as? Dictionary<String, AnyObject> { let mainTitle = innerDict["Title"] as! NSString! var isFound : Bool = false for selTitle in self.arrSelected{ let tempTitle : NSString = selTitle as! NSString if mainTitle == tempTitle{ isFound = true } } if isFound{ innerDict["IsSelected"] = true }else{ innerDict["IsSelected"] = false } self.arrRawData.replaceObjectAtIndex(index, withObject: innerDict) } } self.tableView.reloadData() } }
gpl-3.0
9fe117d29bd511cd84ad7c0a8c188509
45.212454
238
0.614299
5.739763
false
false
false
false
insidegui/WWDC
PlayerUI/Util/AVAsset+AsyncHelpers.swift
1
477
// // AVAsset+AsyncHelpers.swift // PlayerUI // // Created by Allen Humphreys on 25/6/18. // Copyright © 2018 Guilherme Rambo. All rights reserved. // import AVFoundation extension AVAsset { public var durationIfLoaded: CMTime? { let error: NSErrorPointer = nil let durationStatus = statusOfValue(forKey: "duration", error: error) guard durationStatus == .loaded, error?.pointee == nil else { return nil } return duration } }
bsd-2-clause
ab9460493b5f611fbd60c4646bb9e486
20.636364
82
0.665966
4.068376
false
false
false
false
bingoogolapple/SwiftNote-PartOne
归档和恢复/归档和恢复/ViewController.swift
1
3948
// // ViewController.swift // 归档和恢复 // // Created by bingoogol on 14/8/24. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit /* 需求: 1.自定义一个个人信息类:姓名、年龄、电话、头像 2.如果没有保存在磁盘上的记录,那么直接允许用户设置 3.如果存在磁盘记录,显示在界面上 4.需要一个保存按钮来帮助完成保存操作 开发步骤: 1.定义个人信息类 2.在界面上添加按钮,保存假数据到磁盘 3.设置完整的界面,从磁盘读取数据,显示UI */ class ViewController: UIViewController { let documentPath: NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as NSString override func viewDidLoad() { super.viewDidLoad() var saveBtn:UIButton = UIButton.buttonWithType(UIButtonType.System) as UIButton saveBtn.frame = CGRect(x: 110, y: 400, width: 100, height: 40) saveBtn.setTitle("保存", forState: UIControlState.Normal) saveBtn.addTarget(self, action: Selector("savePersonData"), forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(saveBtn) // 1.姓名 var nameTv:UITextView = UITextView(frame: CGRect(x: 100, y: 22, width: 200, height: 40)) self.view.addSubview(nameTv) // 2.年龄 var ageTv:UITextView = UITextView(frame: CGRect(x: 100, y: 72, width: 200, height: 40)) self.view.addSubview(ageTv) // 3.电话 var phoneTv:UITextView = UITextView(frame: CGRect(x: 100, y: 122, width: 200, height: 40)) self.view.addSubview(phoneTv) // 4.头像 var imageIv:UIImageView = UIImageView(frame: CGRect(x: 100, y: 182, width: 200, height: 200)) imageIv.backgroundColor = UIColor.lightGrayColor() self.view.addSubview(imageIv) var personPath = "\(documentPath)/person.plist" // 归档的对象必须是遵守NSCoding协议的对象,如果该对象遵守了NSCoding协议 // 那么,调用unarchiveObjectWithFile方法时,会自动调用该对象的init(coder aDecoder: NSCoder)方法 var person:Person? = NSKeyedUnarchiver.unarchiveObjectWithFile(personPath) as? Person if person != nil { nameTv.text = person!.name ageTv.text = "\(person!.age)" phoneTv.text = person!.phoneNo imageIv.image = person!.image } } func savePersonData() { println("保存用户数据") // 实例化一条假数据,并且保存到磁盘 var person:Person = Person() person.name = "张三" person.age = 19 person.phoneNo = "15216661111" // 使用imageNamed加载的UIImage对象,会被保存在系统缓存中,并且释放的非常缓慢 // 使用该方法适合加载较小的图像或频繁使用的图像(按钮背景图片等) // person.image = UIImage(named: "ppt.png") var imagePath = NSBundle.mainBundle().pathForResource("ppt", ofType: "png") // 而对于较大的图像,或者使用不频繁的图像,应该使用绝对路径的方式加载 // 以下代码加载的UIImage一旦使用完毕就会被释放 person.image = UIImage(contentsOfFile: imagePath) // 写入文件 // 1.确定文件写入路径 var personPath = "\(documentPath)/person.plist" println(personPath) // 2.调用归档方法保存个人数据 // 归档的对象必须是遵守NSCoding协议的对象,如果该对象遵守了NSCoding协议 // 那么,调用archiveRootObject方法时,会自动调用该对象的encodeWithCoder方法 // 编码完成之后,再去写入 NSKeyedArchiver.archiveRootObject(person, toFile: personPath) } }
apache-2.0
1e920016b74470a3212540e9427deed9
34.704545
169
0.650541
3.727165
false
false
false
false
hirohisa/RxSwift
RxTests/RxCocoaTests/UIControl+RxTests.swift
6
826
// // UIControl+RxTests.swift // RxTests // // Created by Ash Furrow on 2015-07-04. // // import UIKit import RxSwift import RxCocoa import XCTest class UIControlRxTests : RxTest { func testSubscribeEnabledToTrue() { let subject = UIControl() let enabledSequence = Variable<Bool>(false) let disposable = enabledSequence >- subject.rx_subscribeEnabledTo enabledSequence.next(true) XCTAssert(subject.enabled == true, "Expected enabled set to true") } func testSubscribeEnabledToFalse() { let subject = UIControl() let enabledSequence = Variable<Bool>(true) let disposable = enabledSequence >- subject.rx_subscribeEnabledTo enabledSequence.next(false) XCTAssert(subject.enabled == false, "Expected enabled set to false") } }
mit
034017ed8c14e0f82776d06adfdc599d
24.8125
76
0.679177
4.588889
false
true
false
false