repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Mr-Small/swift-auction
|
lib/SwiftAuction/provider/YahooRequestProvider.swift
|
1
|
1331
|
//
// YahooRequestProvider.swift
// swift-auction
//
// Created by Mr-Small on 2016-04
//
// Provider for request url of yahoo auction site api.
public final class YahooRequestProvider : RequestProvider {
// Id of auction site.
public let id: String = ""
// Name of auction site.
public let name: String = "yahoo"
// Base url of auction site.
public let url: String = "http://auctions.yahooapis.jp/AuctionWebService/V2/json/"
// Action to auction size.
public var action: String = ""
// User params.
public var userParams: String = ""
// Get request url of auction site.
public func getRequestUrl() -> String {
// Add url string value.
var str: String = ""
let actionType = getAction()
switch actionType {
case .None:
str = ""
case .Category:
str = "categoryTree"
case .Stock:
str = "categoryLeaf"
case .SellingList:
str = "sellingList"
case .Search:
str = "search"
case .Item:
str = "auctionItem"
case .BidHistory:
str = "BidHistory"
}
return url + str
}
// Get action enum.
public func getAction() -> Actions {
return Actions.toAction(action)!
}
}
|
mit
|
2dfcd5c7f82ef638fce1c433a81fd8b4
| 23.2 | 86 | 0.55973 | 4.266026 | false | false | false | false |
metova/MetovaTestKit
|
MetovaTestKit/UIKitTesting/ConstraintTesting/MTKConstraintTester.swift
|
1
|
2196
|
//
// MTKConstraintTester.swift
// MetovaTestKit
//
// Created by Nick Griffith on 7/29/16.
// Copyright © 2016 Metova. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import XCTest
/**
Synchronously tests the provided block for broken constraints. If any constraints are broken, the test fails. Otherwise, it passes.
- parameter message: The message to log upon test failure.
- parameter file: The file the test is called from.
- parameter line: The line number the test is called from.
- parameter testBlock: The block to test.
- returns: Number of broken constraints during test
*/
@discardableResult public func MTKAssertNoBrokenConstraints(message: @autoclosure () -> String? = nil, file: StaticString = #file, line: UInt = #line, testBlock: () -> Void) -> UInt {
let brokenConstraintCount = MTKCountBrokenConstraints(testBlock)
let message = message() ?? "Found \(brokenConstraintCount) broken constraints while executing test block."
XCTAssertEqual(0, brokenConstraintCount, message, file: file, line: line)
return brokenConstraintCount
}
|
mit
|
22c84045ccb28b787ba0da56d5c1ec4f
| 42.9 | 183 | 0.737585 | 4.37251 | false | true | false | false |
eoger/firefox-ios
|
Account/FxAClient10.swift
|
1
|
23651
|
/* 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 Alamofire
import Shared
import Foundation
import FxA
import Deferred
import SwiftyJSON
public let FxAClientErrorDomain = "org.mozilla.fxa.error"
public let FxAClientUnknownError = NSError(domain: FxAClientErrorDomain, code: 999,
userInfo: [NSLocalizedDescriptionKey: "Invalid server response"])
let KeyLength: Int = 32
public struct FxALoginResponse {
public let remoteEmail: String
public let uid: String
public let verified: Bool
public let sessionToken: Data
public let keyFetchToken: Data
}
public struct FxAccountRemoteError {
static let AttemptToOperateOnAnUnverifiedAccount: Int32 = 104
static let InvalidAuthenticationToken: Int32 = 110
static let EndpointIsNoLongerSupported: Int32 = 116
static let IncorrectLoginMethodForThisAccount: Int32 = 117
static let IncorrectKeyRetrievalMethodForThisAccount: Int32 = 118
static let IncorrectAPIVersionForThisAccount: Int32 = 119
static let UnknownDevice: Int32 = 123
static let DeviceSessionConflict: Int32 = 124
static let UnknownError: Int32 = 999
}
public struct FxAKeysResponse {
let kA: Data
let wrapkB: Data
}
public struct FxASignResponse {
let certificate: String
}
public struct FxAStatusResponse {
let exists: Bool
}
public struct FxADevicesResponse {
let devices: [FxADevice]
}
public struct FxANotifyResponse {
let success: Bool
}
public struct FxAOAuthResponse {
let accessToken: String
}
public struct FxAProfileResponse {
let email: String
let uid: String
let avatarURL: String?
let displayName: String?
}
public struct FxADeviceDestroyResponse {
let success: Bool
}
// fxa-auth-server produces error details like:
// {
// "code": 400, // matches the HTTP status code
// "errno": 107, // stable application-level error number
// "error": "Bad Request", // string description of the error type
// "message": "the value of salt is not allowed to be undefined",
// "info": "https://docs.dev.lcip.og/errors/1234" // link to more info on the error
// }
public enum FxAClientError {
case remote(RemoteError)
case local(NSError)
}
// Be aware that string interpolation doesn't work: rdar://17318018, much good that it will do.
extension FxAClientError: MaybeErrorType {
public var description: String {
switch self {
case let .remote(error):
let errorString = error.error ?? NSLocalizedString("Missing error", comment: "Error for a missing remote error number")
let messageString = error.message ?? NSLocalizedString("Missing message", comment: "Error for a missing remote error message")
return "<FxAClientError.Remote \(error.code)/\(error.errno): \(errorString) (\(messageString))>"
case let .local(error):
return "<FxAClientError.Local Error Domain=\(error.domain) Code=\(error.code) \"\(error.localizedDescription)\">"
}
}
}
public struct RemoteError {
let code: Int32
let errno: Int32
let error: String?
let message: String?
let info: String?
var isUpgradeRequired: Bool {
return errno == FxAccountRemoteError.EndpointIsNoLongerSupported
|| errno == FxAccountRemoteError.IncorrectLoginMethodForThisAccount
|| errno == FxAccountRemoteError.IncorrectKeyRetrievalMethodForThisAccount
|| errno == FxAccountRemoteError.IncorrectAPIVersionForThisAccount
}
var isInvalidAuthentication: Bool {
return code == 401
}
var isUnverified: Bool {
return errno == FxAccountRemoteError.AttemptToOperateOnAnUnverifiedAccount
}
}
open class FxAClient10 {
let authURL: URL
let oauthURL: URL
let profileURL: URL
public init(authEndpoint: URL? = nil, oauthEndpoint: URL? = nil, profileEndpoint: URL? = nil) {
self.authURL = authEndpoint ?? ProductionFirefoxAccountConfiguration().authEndpointURL as URL
self.oauthURL = oauthEndpoint ?? ProductionFirefoxAccountConfiguration().oauthEndpointURL as URL
self.profileURL = profileEndpoint ?? ProductionFirefoxAccountConfiguration().profileEndpointURL as URL
}
open class func KW(_ kw: String) -> Data {
return ("identity.mozilla.com/picl/v1/" + kw).utf8EncodedData
}
/**
* The token server accepts an X-Client-State header, which is the
* lowercase-hex-encoded first 16 bytes of the SHA-256 hash of the
* bytes of kB.
*/
open class func computeClientState(_ kB: Data) -> String {
return kB.sha256.subdata(in: 0..<16).hexEncodedString
}
open class func deriveKSync(_ kB: Data) -> Data {
let salt = Data()
let contextInfo = FxAClient10.KW("oldsync")
let len: UInt = 64 // KeyLength + KeyLength, without type nonsense.
return (kB as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: len)!
}
open class func quickStretchPW(_ email: Data, password: Data) -> Data {
var salt = KW("quickStretch")
salt.append(":".utf8EncodedData)
salt.append(email)
return (password as NSData).derivePBKDF2HMACSHA256Key(withSalt: salt as Data, iterations: 1000, length: 32)
}
open class func computeUnwrapKey(_ stretchedPW: Data) -> Data {
let salt: Data = Data()
let contextInfo: Data = KW("unwrapBkey")
let bytes = (stretchedPW as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(KeyLength))
return bytes!
}
fileprivate class func remoteError(fromJSON json: JSON, statusCode: Int) -> RemoteError? {
if json.error != nil || 200 <= statusCode && statusCode <= 299 {
return nil
}
if let code = json["code"].int32 {
if let errno = json["errno"].int32 {
return RemoteError(code: code, errno: errno,
error: json["error"].string,
message: json["message"].string,
info: json["info"].string)
}
}
return nil
}
fileprivate class func loginResponse(fromJSON json: JSON) -> FxALoginResponse? {
guard json.error == nil,
let uid = json["uid"].string,
let verified = json["verified"].bool,
let sessionToken = json["sessionToken"].string,
let keyFetchToken = json["keyFetchToken"].string else {
return nil
}
return FxALoginResponse(remoteEmail: "", uid: uid, verified: verified,
sessionToken: sessionToken.hexDecodedData, keyFetchToken: keyFetchToken.hexDecodedData)
}
fileprivate class func keysResponse(fromJSON keyRequestKey: Data, json: JSON) -> FxAKeysResponse? {
guard json.error == nil,
let bundle = json["bundle"].string else {
return nil
}
let data = bundle.hexDecodedData
guard data.count == 3 * KeyLength else {
return nil
}
let ciphertext = data.subdata(in: 0..<(2 * KeyLength))
let MAC = data.subdata(in: (2 * KeyLength)..<(3 * KeyLength))
let salt: Data = Data()
let contextInfo: Data = KW("account/keys")
let bytes = (keyRequestKey as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))
let respHMACKey = bytes?.subdata(in: 0..<KeyLength)
let respXORKey = bytes?.subdata(in: KeyLength..<(3 * KeyLength))
guard let hmacKey = respHMACKey,
ciphertext.hmacSha256WithKey(hmacKey) == MAC else {
NSLog("Bad HMAC in /keys response!")
return nil
}
guard let xorKey = respXORKey,
let xoredBytes = ciphertext.xoredWith(xorKey) else {
return nil
}
let kA = xoredBytes.subdata(in: 0..<KeyLength)
let wrapkB = xoredBytes.subdata(in: KeyLength..<(2 * KeyLength))
return FxAKeysResponse(kA: kA, wrapkB: wrapkB)
}
fileprivate class func signResponse(fromJSON json: JSON) -> FxASignResponse? {
guard json.error == nil,
let cert = json["cert"].string else {
return nil
}
return FxASignResponse(certificate: cert)
}
fileprivate class func statusResponse(fromJSON json: JSON) -> FxAStatusResponse? {
guard json.error == nil,
let exists = json["exists"].bool else {
return nil
}
return FxAStatusResponse(exists: exists)
}
fileprivate class func devicesResponse(fromJSON json: JSON) -> FxADevicesResponse? {
guard json.error == nil,
let jsonDevices = json.array else {
return nil
}
let devices = jsonDevices.compactMap { (jsonDevice) -> FxADevice? in
return FxADevice.fromJSON(jsonDevice)
}
return FxADevicesResponse(devices: devices)
}
fileprivate class func notifyResponse(fromJSON json: JSON) -> FxANotifyResponse {
return FxANotifyResponse(success: json.error == nil)
}
fileprivate class func deviceDestroyResponse(fromJSON json: JSON) -> FxADeviceDestroyResponse {
return FxADeviceDestroyResponse(success: json.error == nil)
}
fileprivate class func oauthResponse(fromJSON json: JSON) -> FxAOAuthResponse? {
guard json.error == nil,
let accessToken = json["access_token"].string else {
return nil
}
return FxAOAuthResponse(accessToken: accessToken)
}
fileprivate class func profileResponse(fromJSON json: JSON) -> FxAProfileResponse? {
guard json.error == nil,
let uid = json["uid"].string,
let email = json["email"].string else {
return nil
}
let avatarURL = json["avatar"].string
let displayName = json["displayName"].string
return FxAProfileResponse(email: email, uid: uid, avatarURL: avatarURL, displayName: displayName)
}
lazy fileprivate var alamofire: SessionManager = {
let ua = UserAgent.fxaUserAgent
let configuration = URLSessionConfiguration.ephemeral
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = ua
configuration.httpAdditionalHeaders = defaultHeaders
return SessionManager(configuration: configuration)
}()
open func login(_ emailUTF8: Data, quickStretchedPW: Data, getKeys: Bool) -> Deferred<Maybe<FxALoginResponse>> {
let authPW = (quickStretchedPW as NSData).deriveHKDFSHA256Key(withSalt: Data(), contextInfo: FxAClient10.KW("authPW"), length: 32) as NSData
let parameters = [
"email": NSString(data: emailUTF8, encoding: String.Encoding.utf8.rawValue)!,
"authPW": authPW.base16EncodedString(options: NSDataBase16EncodingOptions.lowerCase) as NSString,
]
var URL: URL = self.authURL.appendingPathComponent("/account/login")
if getKeys {
var components = URLComponents(url: URL, resolvingAgainstBaseURL: false)!
components.query = "keys=true"
URL = components.url!
}
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = JSON(parameters).stringValue()?.utf8EncodedData
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.loginResponse)
}
open func status(forUID uid: String) -> Deferred<Maybe<FxAStatusResponse>> {
let statusURL = self.authURL.appendingPathComponent("/account/status").withQueryParam("uid", value: uid)
var mutableURLRequest = URLRequest(url: statusURL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.statusResponse)
}
open func devices(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevicesResponse>> {
let URL = self.authURL.appendingPathComponent("/account/devices")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.devicesResponse)
}
open func notify(deviceIDs: [GUID], collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let httpBody = JSON([
"to": deviceIDs,
"payload": [
"version": 1,
"command": "sync:collection_changed",
"data": [
"collections": collections,
"reason": reason
]
]
])
return self.notify(httpBody: httpBody, withSessionToken: sessionToken)
}
open func notifyAll(ownDeviceId: GUID, collectionsChanged collections: [String], reason: String, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let httpBody = JSON([
"to": "all",
"excluded": [ownDeviceId],
"payload": [
"version": 1,
"command": "sync:collection_changed",
"data": [
"collections": collections,
"reason": reason
]
]
])
return self.notify(httpBody: httpBody, withSessionToken: sessionToken)
}
fileprivate func notify(httpBody: JSON, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxANotifyResponse>> {
let URL = self.authURL.appendingPathComponent("/account/devices/notify")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.notifyResponse)
}
open func destroyDevice(ownDeviceId: GUID, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADeviceDestroyResponse>> {
let URL = self.authURL.appendingPathComponent("/account/device/destroy")
var mutableURLRequest = URLRequest(url: URL)
let httpBody: JSON = JSON(["id": ownDeviceId])
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = httpBody.stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.deviceDestroyResponse)
}
open func registerOrUpdate(device: FxADevice, withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxADevice>> {
let URL = self.authURL.appendingPathComponent("/account/device")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = device.toJSON().stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxADevice.fromJSON)
}
open func oauthAuthorize(withSessionToken sessionToken: NSData, keyPair: RSAKeyPair, certificate: String) -> Deferred<Maybe<FxAOAuthResponse>> {
let audience = self.getAudience(forURL: self.oauthURL)
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience)
let oauthAuthorizationURL = self.oauthURL.appendingPathComponent("/authorization")
var mutableURLRequest = URLRequest(url: oauthAuthorizationURL)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = [
"assertion": assertion,
"client_id": AppConstants.FxAiOSClientId,
"response_type": "token",
"scope": "profile",
"ttl": "300"
]
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = sessionToken.deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
guard let httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData else {
return deferMaybe(FxAClientError.local(FxAClientUnknownError))
}
mutableURLRequest.httpBody = httpBody
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.oauthResponse)
}
open func getProfile(withSessionToken sessionToken: NSData) -> Deferred<Maybe<FxAProfileResponse>> {
let keyPair = RSAKeyPair.generate(withModulusSize: 1024)!
return self.sign(sessionToken as Data, publicKey: keyPair.publicKey) >>== { signResult in
return self.oauthAuthorize(withSessionToken: sessionToken, keyPair: keyPair, certificate: signResult.certificate) >>== { oauthResult in
let profileURL = self.profileURL.appendingPathComponent("/profile")
var mutableURLRequest = URLRequest(url: profileURL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue("Bearer " + oauthResult.accessToken, forHTTPHeaderField: "Authorization")
return self.makeRequest(mutableURLRequest, responseHandler: FxAClient10.profileResponse)
}
}
}
open func getAudience(forURL URL: URL) -> String {
if let port = URL.port {
return "\(URL.scheme!)://\(URL.host!):\(port)"
} else {
return "\(URL.scheme!)://\(URL.host!)"
}
}
fileprivate func makeRequest<T>(_ request: URLRequest, responseHandler: @escaping (JSON) -> T?) -> Deferred<Maybe<T>> {
let deferred = Deferred<Maybe<T>>()
alamofire.request(request)
.validate(contentType: ["application/json"])
.responseJSON { response in
withExtendedLifetime(self.alamofire) {
if let error = response.result.error {
deferred.fill(Maybe(failure: FxAClientError.local(error as NSError)))
return
}
if let data = response.result.value {
let json = JSON(data)
if let remoteError = FxAClient10.remoteError(fromJSON: json, statusCode: response.response!.statusCode) {
deferred.fill(Maybe(failure: FxAClientError.remote(remoteError)))
return
}
if let response = responseHandler(json) {
deferred.fill(Maybe(success: response))
return
}
}
deferred.fill(Maybe(failure: FxAClientError.local(FxAClientUnknownError)))
}
}
return deferred
}
}
extension FxAClient10: FxALoginClient {
func keyPair() -> Deferred<Maybe<KeyPair>> {
let result = RSAKeyPair.generate(withModulusSize: 2048)! // TODO: debate key size and extract this constant.
return Deferred(value: Maybe(success: result))
}
open func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>> {
let URL = self.authURL.appendingPathComponent("/account/keys")
var mutableURLRequest = URLRequest(url: URL)
mutableURLRequest.httpMethod = HTTPMethod.get.rawValue
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("keyFetchToken")
let key = (keyFetchToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(3 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
let rangeStart = 2 * KeyLength
let keyRequestKey = key.subdata(in: rangeStart..<(rangeStart + KeyLength))
return makeRequest(mutableURLRequest) { FxAClient10.keysResponse(fromJSON: keyRequestKey, json: $0) }
}
open func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>> {
let parameters = [
"publicKey": publicKey.jsonRepresentation() as NSDictionary,
"duration": NSNumber(value: OneDayInMilliseconds), // The maximum the server will allow.
]
let url = self.authURL.appendingPathComponent("/certificate/sign")
var mutableURLRequest = URLRequest(url: url)
mutableURLRequest.httpMethod = HTTPMethod.post.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.httpBody = JSON(parameters as NSDictionary).stringValue()?.utf8EncodedData
let salt: Data = Data()
let contextInfo: Data = FxAClient10.KW("sessionToken")
let key = (sessionToken as NSData).deriveHKDFSHA256Key(withSalt: salt, contextInfo: contextInfo, length: UInt(2 * KeyLength))!
mutableURLRequest.addAuthorizationHeader(forHKDFSHA256Key: key)
return makeRequest(mutableURLRequest, responseHandler: FxAClient10.signResponse)
}
}
|
mpl-2.0
|
18f88199d5e1b4bf309076014c6f7de1
| 40.786219 | 179 | 0.651474 | 4.952052 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/AssistantV2/Models/MessageInputOptions.swift
|
1
|
4708
|
/**
* (C) Copyright IBM Corp. 2018, 2020.
*
* 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
/**
Optional properties that control how the assistant responds.
*/
public struct MessageInputOptions: Codable, Equatable {
/**
Whether to restart dialog processing at the root of the dialog, regardless of any previously visited nodes.
**Note:** This does not affect `turn_count` or any other context variables.
*/
public var restart: Bool?
/**
Whether to return more than one intent. Set to `true` to return all matching intents.
*/
public var alternateIntents: Bool?
/**
Spelling correction options for the message. Any options specified on an individual message override the settings
configured for the skill.
*/
public var spelling: MessageInputOptionsSpelling?
/**
Whether to return additional diagnostic information. Set to `true` to return additional information in the
`output.debug` property. If you also specify **return_context**=`true`, the returned skill context includes the
`system.state` property.
*/
public var debug: Bool?
/**
Whether to return session context with the response. If you specify `true`, the response includes the `context`
property. If you also specify **debug**=`true`, the returned skill context includes the `system.state` property.
*/
public var returnContext: Bool?
/**
Whether to return session context, including full conversation state. If you specify `true`, the response includes
the `context` property, and the skill context includes the `system.state` property.
**Note:** If **export**=`true`, the context is returned regardless of the value of **return_context**.
*/
public var export: Bool?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case restart = "restart"
case alternateIntents = "alternate_intents"
case spelling = "spelling"
case debug = "debug"
case returnContext = "return_context"
case export = "export"
}
/**
Initialize a `MessageInputOptions` with member variables.
- parameter restart: Whether to restart dialog processing at the root of the dialog, regardless of any
previously visited nodes. **Note:** This does not affect `turn_count` or any other context variables.
- parameter alternateIntents: Whether to return more than one intent. Set to `true` to return all matching
intents.
- parameter spelling: Spelling correction options for the message. Any options specified on an individual
message override the settings configured for the skill.
- parameter debug: Whether to return additional diagnostic information. Set to `true` to return additional
information in the `output.debug` property. If you also specify **return_context**=`true`, the returned skill
context includes the `system.state` property.
- parameter returnContext: Whether to return session context with the response. If you specify `true`, the
response includes the `context` property. If you also specify **debug**=`true`, the returned skill context
includes the `system.state` property.
- parameter export: Whether to return session context, including full conversation state. If you specify `true`,
the response includes the `context` property, and the skill context includes the `system.state` property.
**Note:** If **export**=`true`, the context is returned regardless of the value of **return_context**.
- returns: An initialized `MessageInputOptions`.
*/
public init(
restart: Bool? = nil,
alternateIntents: Bool? = nil,
spelling: MessageInputOptionsSpelling? = nil,
debug: Bool? = nil,
returnContext: Bool? = nil,
export: Bool? = nil
)
{
self.restart = restart
self.alternateIntents = alternateIntents
self.spelling = spelling
self.debug = debug
self.returnContext = returnContext
self.export = export
}
}
|
apache-2.0
|
7612057fd151976a5913de8f2f4e4987
| 42.192661 | 119 | 0.693288 | 4.784553 | false | false | false | false |
tus/TUSKit
|
TUSKitExample/TUSKitExample/ContentView.swift
|
1
|
1161
|
//
// ContentView.swift
// TUSKitExample
//
// Created by Tjeerd in ‘t Veen on 14/09/2021.
//
import SwiftUI
import TUSKit
import PhotosUI
struct ContentView: View {
let photoPicker: PhotoPicker
@State private var showingImagePicker = false
init(photoPicker: PhotoPicker) {
self.photoPicker = photoPicker
}
var body: some View {
VStack {
Text("TUSKit Demo")
.font(.title)
.padding()
Button("Select image") {
showingImagePicker.toggle()
}.sheet(isPresented:$showingImagePicker, content: {
self.photoPicker
})
}
}
}
struct ContentView_Previews: PreviewProvider {
@State static var isPresented = false
static let tusClient = try! TUSClient(server: URL(string: "https://tusd.tusdemo.net/files")!, sessionIdentifier: "TUSClient", storageDirectory: URL(string: "TUS")!)
static var previews: some View {
let photoPicker = PhotoPicker(tusClient: tusClient)
ContentView(photoPicker: photoPicker)
}
}
|
mit
|
bb9fe92f526a44b0ed0fd7676279236d
| 25.340909 | 168 | 0.584987 | 4.562992 | false | false | false | false |
Isuru-Nanayakkara/Swift-Extensions
|
Swift+Extensions/Swift+Extensions/UIKit/UINavigationItem+Extensions.swift
|
1
|
511
|
import UIKit
extension UINavigationItem {
func setDynamicTitle(_ title: String) {
self.title = title
let frame = CGRect(x: 0, y: 0, width: 200, height: 40)
let label = UILabel(frame: frame)
label.text = self.title
label.textColor = UIColor.white
label.font = UIFont.boldSystemFont(ofSize: 17)
label.backgroundColor = UIColor.clear
label.adjustsFontSizeToFitWidth = true
label.textAlignment = .center
titleView = label
}
}
|
mit
|
8b97a3af7ca8ca2f5b64aceda36ed606
| 30.9375 | 62 | 0.634051 | 4.443478 | false | false | false | false |
swernimo/iOS
|
UI Kit Fundamentals 1/ColorMaker/ColorMaker/ViewController.swift
|
1
|
993
|
//
// ViewController.swift
// ColorMaker
//
// Created by Sean Wernimont on 10/23/15.
// Copyright © 2015 Udacity. All rights reserved.
//
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var colorView: UIView!
@IBOutlet weak var blueSlider: UISlider!
@IBOutlet weak var greenSlider: UISlider!
@IBOutlet weak var redSlider: UISlider!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func changeColor(sender: AnyObject) {
if((self.blueSlider == nil) || (self.redSlider == nil) || (self.greenSlider == nil)){
return;
}
let r = CGFloat(self.redSlider.value);
let g = CGFloat(self.greenSlider.value);
let b = CGFloat(self.blueSlider.value);
colorView.backgroundColor = UIColor.whiteColor();
if(r+g+b > 0){
colorView.backgroundColor = UIColor(red:r, green: g, blue: b, alpha:1);
}
}
}
|
mit
|
e7ed481bafb75a75315c74b55de4474b
| 25.105263 | 93 | 0.600806 | 4.099174 | false | false | false | false |
ArnavChawla/InteliChat
|
Carthage/Checkouts/swift-sdk/Source/NaturalLanguageClassifierV1/Models/Classifier.swift
|
1
|
1905
|
/**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** A classifier for natural language phrases. */
public struct Classifier: Decodable {
/// The state of the classifier.
public enum Status: String {
case nonExistent = "Non Existent"
case training = "Training"
case failed = "Failed"
case available = "Available"
case unavailable = "Unavailable"
}
/// User-supplied name for the classifier.
public var name: String?
/// Link to the classifier.
public var url: String
/// The state of the classifier.
public var status: String?
/// Unique identifier for this classifier.
public var classifierID: String
/// Date and time (UTC) the classifier was created.
public var created: String?
/// Additional detail about the status.
public var statusDescription: String?
/// The language used for the classifier.
public var language: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case url = "url"
case status = "status"
case classifierID = "classifier_id"
case created = "created"
case statusDescription = "status_description"
case language = "language"
}
}
|
mit
|
9293b65bf366ad42c93342a93bcb7f90
| 29.238095 | 82 | 0.675591 | 4.590361 | false | false | false | false |
kwkhaw/SwiftAnyPic
|
SwiftAnyPic/PAPFindFriendsViewController.swift
|
1
|
25147
|
import UIKit
import MessageUI
import ParseUI
import AddressBookUI
import MBProgressHUD
import Synchronized
enum PAPFindFriendsFollowStatus: Int {
case FollowingNone = 0, // User isn't following anybody in Friends list
FollowingAll, // User is following all Friends
FollowingSome // User is following some of their Friends
}
class PAPFindFriendsViewController: PFQueryTableViewController, PAPFindFriendsCellDelegate, ABPeoplePickerNavigationControllerDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate, UIActionSheetDelegate {
private var headerView: UIView?
private var followStatus: PAPFindFriendsFollowStatus
private var selectedEmailAddress: String
private var outstandingFollowQueries: [NSObject: AnyObject]
private var outstandingCountQueries: [NSIndexPath: AnyObject]
// MARK:- Initialization
init(style: UITableViewStyle) {
self.selectedEmailAddress = ""
// Used to determine Follow/Unfollow All button status
self.followStatus = PAPFindFriendsFollowStatus.FollowingSome
self.outstandingFollowQueries = [NSObject: AnyObject]()
self.outstandingCountQueries = [NSIndexPath: AnyObject]()
super.init(style: style, className: nil)
// Whether the built-in pull-to-refresh is enabled
self.pullToRefreshEnabled = true
// The number of objects to show per page
self.objectsPerPage = 15
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIViewController
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
self.tableView.backgroundColor = UIColor.blackColor()
self.navigationItem.titleView = UIImageView(image: UIImage(named: "TitleFindFriends.png"))
if self.navigationController!.viewControllers[0] == self {
let dismissLeftBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPFindFriendsViewController.dismissPresentingViewController))
self.navigationItem.leftBarButtonItem = dismissLeftBarButtonItem
} else {
self.navigationItem.leftBarButtonItem = nil
}
if MFMailComposeViewController.canSendMail() || MFMessageComposeViewController.canSendText() {
self.headerView = UIView(frame: CGRectMake(0, 0, 320, 67))
self.headerView!.backgroundColor = UIColor.blackColor()
let clearButton = UIButton(type: UIButtonType.Custom)
clearButton.backgroundColor = UIColor.clearColor()
clearButton.addTarget(self, action: #selector(PAPFindFriendsViewController.inviteFriendsButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside)
clearButton.frame = self.headerView!.frame
self.headerView!.addSubview(clearButton)
let inviteString = NSLocalizedString("Invite friends", comment: "Invite friends")
let boundingRect: CGRect = inviteString.boundingRectWithSize(CGSizeMake(310.0, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(18.0)],
context: nil)
let inviteStringSize: CGSize = boundingRect.size
let inviteLabel = UILabel(frame: CGRectMake(10, (self.headerView!.frame.size.height-inviteStringSize.height)/2, inviteStringSize.width, inviteStringSize.height))
inviteLabel.text = inviteString
inviteLabel.font = UIFont.boldSystemFontOfSize(18)
inviteLabel.textColor = UIColor.whiteColor()
inviteLabel.backgroundColor = UIColor.clearColor()
self.headerView!.addSubview(inviteLabel)
self.tableView!.tableHeaderView = self.headerView
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tableView.separatorColor = UIColor(red: 30.0/255.0, green: 30.0/255.0, blue: 30.0/255.0, alpha: 1.0)
}
func dismissPresentingViewController() {
self.navigationController!.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- UITableViewDelegate
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row < self.objects!.count {
return PAPFindFriendsCell.heightForCell()
} else {
return 44.0
}
}
// MARK:- PFQueryTableViewController
override func queryForTable() -> PFQuery {
// Use cached facebook friend ids
let facebookFriends: [PFUser]? = PAPCache.sharedCache.facebookFriends()
// Query for all friends you have on facebook and who are using the app
let friendsQuery: PFQuery = PFUser.query()!
friendsQuery.whereKey(kPAPUserFacebookIDKey, containedIn: facebookFriends!)
// Query for all Parse employees
var parseEmployees: [String] = kPAPParseEmployeeAccounts
let currentUserFacebookId = PFUser.currentUser()!.objectForKey(kPAPUserFacebookIDKey) as! String
parseEmployees = parseEmployees.filter { (facebookId) in facebookId != currentUserFacebookId }
let parseEmployeeQuery: PFQuery = PFUser.query()!
parseEmployeeQuery.whereKey(kPAPUserFacebookIDKey, containedIn: parseEmployees)
let query: PFQuery = PFQuery.orQueryWithSubqueries([friendsQuery, parseEmployeeQuery])
query.cachePolicy = PFCachePolicy.NetworkOnly
if self.objects!.count == 0 {
query.cachePolicy = PFCachePolicy.CacheThenNetwork
}
query.orderByAscending(kPAPUserDisplayNameKey)
return query
}
override func objectsDidLoad(error: NSError?) {
super.objectsDidLoad(error)
let isFollowingQuery = PFQuery(className: kPAPActivityClassKey)
isFollowingQuery.whereKey(kPAPActivityFromUserKey, equalTo: PFUser.currentUser()!)
isFollowingQuery.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
isFollowingQuery.whereKey(kPAPActivityToUserKey, containedIn: self.objects!)
isFollowingQuery.cachePolicy = PFCachePolicy.NetworkOnly
isFollowingQuery.countObjectsInBackgroundWithBlock { (number, error) in
if error == nil {
if Int(number) == self.objects!.count {
self.followStatus = PAPFindFriendsFollowStatus.FollowingAll
self.configureUnfollowAllButton()
for user in self.objects as! [PFUser] {
PAPCache.sharedCache.setFollowStatus(true, user: user)
}
} else if number == 0 {
self.followStatus = PAPFindFriendsFollowStatus.FollowingNone
self.configureFollowAllButton()
for user in self.objects as! [PFUser] {
PAPCache.sharedCache.setFollowStatus(false, user: user)
}
} else {
self.followStatus = PAPFindFriendsFollowStatus.FollowingSome
self.configureFollowAllButton()
}
}
if self.objects!.count == 0 {
self.navigationItem.rightBarButtonItem = nil
}
}
if self.objects!.count == 0 {
self.navigationItem.rightBarButtonItem = nil
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
let FriendCellIdentifier = "FriendCell"
var cell: PAPFindFriendsCell? = tableView.dequeueReusableCellWithIdentifier(FriendCellIdentifier) as? PAPFindFriendsCell
if cell == nil {
cell = PAPFindFriendsCell(style: UITableViewCellStyle.Default, reuseIdentifier: FriendCellIdentifier)
cell!.delegate = self
}
cell!.user = object as? PFUser
cell!.photoLabel!.text = "0 photos"
let attributes: [NSObject: AnyObject]? = PAPCache.sharedCache.attributesForUser(object as! PFUser)
if attributes != nil {
// set them now
let number = PAPCache.sharedCache.photoCountForUser(object as! PFUser)
let appendS = number == 1 ? "": "s"
cell!.photoLabel.text = "\(number) photo\(appendS)"
} else {
synchronized(self) {
let outstandingCountQueryStatus: Int? = self.outstandingCountQueries[indexPath] as? Int
if outstandingCountQueryStatus == nil {
self.outstandingCountQueries[indexPath] = true
let photoNumQuery = PFQuery(className: kPAPPhotoClassKey)
photoNumQuery.whereKey(kPAPPhotoUserKey, equalTo: object!)
photoNumQuery.cachePolicy = PFCachePolicy.CacheThenNetwork
photoNumQuery.countObjectsInBackgroundWithBlock { (number, error) in
synchronized(self) {
PAPCache.sharedCache.setPhotoCount(Int(number), user: object as! PFUser)
self.outstandingCountQueries.removeValueForKey(indexPath)
}
let actualCell: PAPFindFriendsCell? = tableView.cellForRowAtIndexPath(indexPath) as? PAPFindFriendsCell
let appendS = number == 1 ? "" : "s"
actualCell?.photoLabel?.text = "\(number) photo\(appendS)"
}
}
}
}
cell!.followButton.selected = false
cell!.tag = indexPath.row
if self.followStatus == PAPFindFriendsFollowStatus.FollowingSome {
if attributes != nil {
cell!.followButton.selected = PAPCache.sharedCache.followStatusForUser(object as! PFUser)
} else {
synchronized(self) {
let outstandingQuery: Int? = self.outstandingFollowQueries[indexPath] as? Int
if outstandingQuery == nil {
self.outstandingFollowQueries[indexPath] = true
let isFollowingQuery = PFQuery(className: kPAPActivityClassKey)
isFollowingQuery.whereKey(kPAPActivityFromUserKey, equalTo: PFUser.currentUser()!)
isFollowingQuery.whereKey(kPAPActivityTypeKey, equalTo: kPAPActivityTypeFollow)
isFollowingQuery.whereKey(kPAPActivityToUserKey, equalTo: object!)
isFollowingQuery.cachePolicy = PFCachePolicy.CacheThenNetwork
isFollowingQuery.countObjectsInBackgroundWithBlock { (number, error) in
synchronized(self) {
self.outstandingFollowQueries.removeValueForKey(indexPath)
PAPCache.sharedCache.setFollowStatus((error == nil && number > 0), user: object as! PFUser)
}
if cell!.tag == indexPath.row {
cell!.followButton.selected = (error == nil && number > 0)
}
}
}
}
}
} else {
cell!.followButton.selected = (self.followStatus == PAPFindFriendsFollowStatus.FollowingAll)
}
return cell!
}
override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? {
let NextPageCellIdentifier = "NextPageCell"
var cell: PAPLoadMoreCell? = tableView.dequeueReusableCellWithIdentifier(NextPageCellIdentifier) as? PAPLoadMoreCell
if cell == nil {
cell = PAPLoadMoreCell(style: UITableViewCellStyle.Default, reuseIdentifier: NextPageCellIdentifier)
cell!.mainView!.backgroundColor = UIColor.blackColor()
cell!.hideSeparatorBottom = true
cell!.hideSeparatorTop = true
}
cell!.selectionStyle = UITableViewCellSelectionStyle.None
return cell!
}
// MARK:- PAPFindFriendsCellDelegate
func cell(cellView: PAPFindFriendsCell, didTapUserButton aUser: PFUser) {
// Push account view controller
let accountViewController = PAPAccountViewController(user: aUser)
print("Presenting account view controller with user: \(aUser)")
self.navigationController!.pushViewController(accountViewController, animated: true)
}
func cell(cellView: PAPFindFriendsCell, didTapFollowButton aUser: PFUser) {
self.shouldToggleFollowFriendForCell(cellView)
}
// MARK:- ABPeoplePickerDelegate
/* Called when the user cancels the address book view controller. We simply dismiss it. */
// FIXME!!!!!!!!!
func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController) {
self.dismissViewControllerAnimated(true, completion: nil)
}
/* Called when a member of the address book is selected, we return YES to display the member's details. */
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, shouldContinueAfterSelectingPerson person: ABRecord) -> Bool {
return true
}
/* Called when the user selects a property of a person in their address book (ex. phone, email, location,...)
This method will allow them to send a text or email inviting them to Anypic. */
func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController, shouldContinueAfterSelectingPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool {
// if property == kABPersonEmailProperty {
// let emailProperty: ABMultiValueRef = ABRecordCopyValue(person,property)
// let email = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(emailProperty,identifier);
// self.selectedEmailAddress = email;
//
// if ([MFMailComposeViewController canSendMail] && [MFMessageComposeViewController canSendText]) {
// // ask user
// UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:[NSString stringWithFormat:@"Invite %@",@""] delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Email", @"iMessage", nil];
// [actionSheet showFromTabBar:self.tabBarController.tabBar];
// } else if ([MFMailComposeViewController canSendMail]) {
// // go directly to mail
// [self presentMailComposeViewController:email];
// } else if ([MFMessageComposeViewController canSendText]) {
// // go directly to iMessage
// [self presentMessageComposeViewController:email];
// }
//
// } else if (property == kABPersonPhoneProperty) {
// ABMultiValueRef phoneProperty = ABRecordCopyValue(person,property);
// NSString *phone = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(phoneProperty,identifier);
//
// if ([MFMessageComposeViewController canSendText]) {
// [self presentMessageComposeViewController:phone];
// }
// }
return false
}
// MARK:- MFMailComposeDelegate
/* Simply dismiss the MFMailComposeViewController when the user sends an email or cancels */
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- MFMessageComposeDelegate
/* Simply dismiss the MFMessageComposeViewController when the user sends a text or cancels */
func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
self.dismissViewControllerAnimated(true, completion: nil)
}
// MARK:- UIActionSheetDelegate
// FIXME!!!!!!!!
func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == actionSheet.cancelButtonIndex {
return
}
if buttonIndex == 0 {
self.presentMailComposeViewController(self.selectedEmailAddress)
} else if buttonIndex == 1 {
self.presentMessageComposeViewController(self.selectedEmailAddress)
}
}
// MARK:- ()
func backButtonAction(sender: AnyObject) {
self.navigationController!.popViewControllerAnimated(true)
}
func inviteFriendsButtonAction(sender: AnyObject) {
let addressBook = ABPeoplePickerNavigationController()
addressBook.peoplePickerDelegate = self
if MFMailComposeViewController.canSendMail() && MFMessageComposeViewController.canSendText() {
addressBook.displayedProperties = [Int(kABPersonEmailProperty), Int(kABPersonPhoneProperty)]
} else if MFMailComposeViewController.canSendMail() {
addressBook.displayedProperties = [Int(kABPersonEmailProperty)]
} else if MFMessageComposeViewController.canSendText() {
addressBook.displayedProperties = [Int(kABPersonPhoneProperty)]
}
self.presentViewController(addressBook, animated: true, completion: nil)
}
func followAllFriendsButtonAction(sender: AnyObject) {
MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow, animated: true)
self.followStatus = PAPFindFriendsFollowStatus.FollowingAll
self.configureUnfollowAllButton()
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.01 * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Unfollow All", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPFindFriendsViewController.unfollowAllFriendsButtonAction(_:)))
var indexPaths = Array<NSIndexPath>(count: self.objects!.count, repeatedValue: NSIndexPath())
for var r = 0; r < self.objects!.count; r += 1 {
let user: PFObject = self.objects![r] as! PFObject
let indexPath: NSIndexPath = NSIndexPath(forRow: r, inSection: 0)
let cell: PAPFindFriendsCell? = self.tableView(self.tableView, cellForRowAtIndexPath: indexPath, object: user) as? PAPFindFriendsCell
cell!.followButton.selected = true
indexPaths.append(indexPath)
}
self.tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
let timer: NSTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(PAPFindFriendsViewController.followUsersTimerFired(_:)), userInfo: nil, repeats: false)
PAPUtility.followUsersEventually(self.objects as! [PFUser], block: { (succeeded, error) in
// note -- this block is called once for every user that is followed successfully. We use a timer to only execute the completion block once no more saveEventually blocks have been called in 2 seconds
timer.fireDate = NSDate(timeIntervalSinceNow: 2.0)
})
})
}
func unfollowAllFriendsButtonAction(sender: AnyObject) {
MBProgressHUD.showHUDAddedTo(UIApplication.sharedApplication().keyWindow, animated: true)
self.followStatus = PAPFindFriendsFollowStatus.FollowingNone
self.configureFollowAllButton()
let popTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.01 * Double(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue(), {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Follow All", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("followAllFriendsButtonAction:"))
var indexPaths: [NSIndexPath] = Array<NSIndexPath>(count: self.objects!.count, repeatedValue: NSIndexPath())
for r in 0 ..< self.objects!.count {
let user: PFObject = self.objects![r] as! PFObject
let indexPath: NSIndexPath = NSIndexPath(forRow: r, inSection: 0)
let cell: PAPFindFriendsCell = self.tableView(self.tableView, cellForRowAtIndexPath: indexPath, object: user) as! PAPFindFriendsCell
cell.followButton.selected = false
indexPaths.append(indexPath)
}
self.tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.None)
MBProgressHUD.hideAllHUDsForView(UIApplication.sharedApplication().keyWindow, animated: true)
PAPUtility.unfollowUsersEventually(self.objects as! [PFUser])
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
})
}
func shouldToggleFollowFriendForCell(cell: PAPFindFriendsCell) {
let cellUser: PFUser = cell.user!
if cell.followButton.selected {
// Unfollow
cell.followButton.selected = false
PAPUtility.unfollowUserEventually(cellUser)
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
} else {
// Follow
cell.followButton.selected = true
PAPUtility.followUserEventually(cellUser, block: { (succeeded, error) in
if error == nil {
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
} else {
cell.followButton.selected = false
}
})
}
}
func configureUnfollowAllButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Unfollow All", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPFindFriendsViewController.unfollowAllFriendsButtonAction(_:)))
}
func configureFollowAllButton() {
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Follow All", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(PAPFindFriendsViewController.followAllFriendsButtonAction(_:)))
}
func presentMailComposeViewController(recipient: String) {
// Create the compose email view controller
let composeEmailViewController = MFMailComposeViewController()
// Set the recipient to the selected email and a default text
composeEmailViewController.mailComposeDelegate = self
composeEmailViewController.setSubject("Join me on Anypic")
composeEmailViewController.setToRecipients([recipient])
composeEmailViewController.setMessageBody("<h2>Share your pictures, share your story.</h2><p><a href=\"http://anypic.org\">Anypic</a> is the easiest way to share photos with your friends. Get the app and share your fun photos with the world.</p><p><a href=\"http://anypic.org\">Anypic</a> is fully powered by <a href=\"http://parse.com\">Parse</a>.</p>", isHTML: true)
// Dismiss the current modal view controller and display the compose email one.
// Note that we do not animate them. Doing so would require us to present the compose
// mail one only *after* the address book is dismissed.
self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(composeEmailViewController, animated: false, completion: nil)
}
func presentMessageComposeViewController(recipient: String) {
// Create the compose text message view controller
let composeTextViewController = MFMessageComposeViewController()
// Send the destination phone number and a default text
composeTextViewController.messageComposeDelegate = self
composeTextViewController.recipients = [recipient]
composeTextViewController.body = "Check out Anypic! http://anypic.org"
// Dismiss the current modal view controller and display the compose text one.
// See previous use for reason why these are not animated.
self.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(composeTextViewController, animated: false, completion: nil)
}
func followUsersTimerFired(timer: NSTimer) {
self.tableView.reloadData()
NSNotificationCenter.defaultCenter().postNotificationName(PAPUtilityUserFollowingChangedNotification, object: nil)
}
}
|
cc0-1.0
|
37a68c5f0316c0a242205dce3ac3449d
| 49.193613 | 376 | 0.671929 | 5.433665 | false | false | false | false |
aijaz/icw1502
|
playgrounds/Week07.playground/Pages/Protocols.xcplaygroundpage/Sources/Rectangle.swift
|
1
|
1360
|
import Foundation
public struct Rectangle {
let topLeftCorner: Vertex
var size: Size
public let location: Vertex
public init (topLeftCorner: Vertex, width w: Double, height h: Double) {
self.topLeftCorner = topLeftCorner
self.size = Size(width: w, height: h)
location = Vertex(x: topLeftCorner.x + w/2, y: topLeftCorner.y + h/2)
}
mutating public func doubleArea() {
size = Size(width: size.width * 2, height: size.height)
}
}
extension Rectangle:Movable {
private init(topLeftCorner: Vertex, size: Size) {
self.topLeftCorner = topLeftCorner
self.size = size
location = Vertex(x: topLeftCorner.x + size.width/2,
y: topLeftCorner.y + size.height/2)
}
public func moveByX(deltaX: Double) -> Rectangle {
let movedTopLeftCorner = topLeftCorner.moveByX(deltaX)
return Rectangle(topLeftCorner: movedTopLeftCorner, size: size)
}
public func whereAmI() -> Vertex {
return topLeftCorner
}
}
extension Rectangle : CustomStringConvertible {
public var description: String {
return "\(size) at \(topLeftCorner)"
}
}
extension Rectangle : Equatable {}
public func ==(lhs: Rectangle, rhs: Rectangle) -> Bool {
return (lhs.size == rhs.size && lhs.topLeftCorner == rhs.topLeftCorner)
}
|
mit
|
1b6470b71bbb5cb23fd4928d855e9cfe
| 27.93617 | 77 | 0.645588 | 4.084084 | false | false | false | false |
mitochrome/complex-gestures-demo
|
apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
|
6
|
3206
|
//
// RxCollectionViewDataSourceProxy.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import UIKit
#if !RX_NO_MODULE
import RxSwift
#endif
let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet()
final class CollectionViewDataSourceNotSet
: NSObject
, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 0
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
rxAbstractMethod(message: dataSourceNotSet)
}
}
/// For more information take a look at `DelegateProxyType`.
open class RxCollectionViewDataSourceProxy
: DelegateProxy<UICollectionView, UICollectionViewDataSource>
, DelegateProxyType
, UICollectionViewDataSource {
/// Typed parent object.
public weak private(set) var collectionView: UICollectionView?
/// - parameter parentObject: Parent object for delegate proxy.
public init(parentObject: ParentObject) {
self.collectionView = parentObject
super.init(parentObject: parentObject, delegateProxy: RxCollectionViewDataSourceProxy.self)
}
// Register known implementations
public static func registerKnownImplementations() {
self.register { RxCollectionViewDataSourceProxy(parentObject: $0) }
}
private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet
// MARK: delegate
/// Required delegate method implementation.
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section)
}
/// Required delegate method implementation.
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath)
}
// MARK: proxy
/// For more information take a look at `DelegateProxyType`.
open class func setCurrentDelegate(_ delegate: UICollectionViewDataSource?, to object: ParentObject) {
object.dataSource = delegate
}
/// For more information take a look at `DelegateProxyType`.
open class func currentDelegate(for object: ParentObject) -> UICollectionViewDataSource? {
return object.dataSource
}
/// For more information take a look at `DelegateProxyType`.
open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) {
_requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet
super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate)
}
}
#endif
|
mit
|
9a1c6746ef31ca8c1b12a4ca9b6c7f2f
| 35.83908 | 141 | 0.751326 | 6.151631 | false | false | false | false |
simonnarang/Fandom-IOS
|
Fandomm/ViewController.swift
|
1
|
14211
|
//
// ViewController.swift
// Fandomm
//
// Created by weel Narang on 8/25/15.
// Copyright © 2015 Simon Narang. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
let redisClient:RedisClient = RedisClient(host:"pub-redis-17342.us-east-1-4.3.ec2.garantiadata.com", port:17342, loggingBlock:{(redisClient:AnyObject, message:String, severity:RedisLogSeverity) in
var debugString:String = message
debugString = debugString.stringByReplacingOccurrencesOfString("\r", withString: "\\r")
debugString = debugString.stringByReplacingOccurrencesOfString("\n", withString: "\\n")
print("Log (\(severity.rawValue)): \(debugString)")
})
//vars to be used
let defaults = NSUserDefaults.standardUserDefaults()
var realUsername = String()
var userFandoms = [AnyObject]()
var signUpCounter = 0
var number = Int()
var thearray = [AnyObject]()
//IBOUTLETS
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var nextButtonOutlet: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//set up text fields
self.username.delegate = self
self.password.delegate = self
//dissmiss keyboard if needed on tap
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
view.addGestureRecognizer(tap)
//lrange throgh fandoms now so later users have them
self.redisClient.lRange("thefandomfandom", start: 0, stop: 9999) { (array, error) -> Void in
if error != nil {
print("err(ViewController): couldnt lRange thefandomfandom: \(error)")
}else {
for fandommpost in array {
self.thearray.append(fandommpost as! String)
print("\(fandommpost)huu")
}
self.number = self.thearray.count
print("\(self.number)hiiiu")
}
}
}
//sign in/up alorithm
func singInUp() -> Void {
let passwordUsernameSwitchErrorAlertOne = UIAlertController (title: "😂Looks like you may have switched up your username and password😂", message: "if you are \(self.password.text!), want to login", preferredStyle: .Alert)
let passwordUsernameSwitchErrorAlertOneOkButton = UIAlertAction(title: "sure!", style: .Default) { (action) in
self.performSegueWithIdentifier("viewControllerToTBVC", sender: nil)
}
passwordUsernameSwitchErrorAlertOne.addAction(passwordUsernameSwitchErrorAlertOneOkButton)
let passwordUsernameSwitchErrorAlertOneNotMeButton = UIAlertAction(title: "thats not me let me try to sign in again", style: .Default) { (action) in}
passwordUsernameSwitchErrorAlertOne.addAction(passwordUsernameSwitchErrorAlertOneNotMeButton)
let networkErrorAlertTwo = UIAlertController(title: "😁Having some trouble recognizing usernames right now😁", message: "I can't reach the chest full of gold usernames... either your not connected to the internet or you need to update fandom over in the app store if not im already working on a fix so try again soon", preferredStyle: .Alert)
let networkErrorAlertTwoOkButton = UIAlertAction(title: "☹️Okay☹️", style: .Default) { (action) in}
networkErrorAlertTwo.addAction(networkErrorAlertTwoOkButton)
let networkErrorAlertOne = UIAlertController(title: "😁Having some trouble recognizing usernames right now😁", message: "Sorry about that... perhaps check the app store to see if you need to update fandom... if not I'm already working on a fix so try again soon", preferredStyle: .Alert)
let networkErrorAlertOneOkButton = UIAlertAction(title: "☹️Okay☹️", style: .Default) { (action) in
}
networkErrorAlertOne.addAction(networkErrorAlertOneOkButton)
let loginErrorAlertOne = UIAlertController(title: "😜Wrong password!😜", message: "try again \(self.username.text!)", preferredStyle: .Alert)
let loginErrorAlertOneOkButton = UIAlertAction(title: "Got it!", style: .Default) { (action) in
}
loginErrorAlertOne.addAction(loginErrorAlertOneOkButton)
let signInOrUpAlertOne = UIAlertController(title: "🤔Don't recongnize that username!🤔", message: "Do you want to sign up or use a different username? ", preferredStyle: .Alert)
let signInOrUpAlertOneSignUpButton = UIAlertAction(title: "sign up", style: .Default) { (action) in
self.redisClient.lPush(self.username.text!, values: [self.password.text!], completionHandler: { (int, error) -> Void in
if error != nil {
print("an error occured while attempting to sign up a user via lPush(PW/POSTS list)...")
print(error)
self.presentViewController(networkErrorAlertOne, animated: true) {}
}else{
print("there was no error appending a user acount to the redis db via lpush")
self.signUpCounter += 1
print("no error... signUpCounter is now at \(self.signUpCounter)")
}
})
self.redisClient.lPush("\(self.username.text!)followers", values: ["claire"], completionHandler: { (int, error) -> Void in
if error != nil {
print("an error occured while attempting to sign up a user via lPush(FOLLOWERS list)...")
print(error)
}else{
self.signUpCounter += 1
}
})
self.redisClient.lPush("\(self.username.text!)following", values: ["claire"], completionHandler: { (int, error) -> Void in
if error != nil {
print("an error occured while attempting to sign up a user via lPush(FOLLOWING list)...")
print(error)
}else{
self.signUpCounter += 1
}
})
self.redisClient.lPush("\(self.username.text!)fandoms", values: ["thefandomfandom"], completionHandler: { (int, error) -> Void in
if error != nil {
print("an error occured while attempting to sign up a user via lPush(FANDOMS list)...")
print(error)
}else{
self.signUpCounter += 1
}
})
if self.signUpCounter == 4 {
self.nextButtonOutlet.setTitle("LOADING", forState: .Normal)
self.performSegueWithIdentifier("viewControllerToTBVC", sender: nil)
self.nextButtonOutlet.setTitle("NEXT", forState: .Normal)
}else{
if self.signUpCounter == 0{
print("all 4 of the tasks acossiated with user signup failed")
self.presentViewController(networkErrorAlertOne, animated: true) {}
self.realUsername = self.username.text!
self.performSegueWithIdentifier("viewControllerToTBVC", sender: nil)
}else if self.signUpCounter == 1 {
print("3 of the tasks acossiated with user signup failed")
self.presentViewController(networkErrorAlertOne, animated: true) {}
self.realUsername = self.username.text!
}else if self.signUpCounter == 2 {
print("2 of the tasks acossiated with user signup failed")
self.presentViewController(networkErrorAlertOne, animated: true) {}
self.realUsername = self.username.text!
}else if self.signUpCounter == 3{
print("1 of the tasks acossiated with user signup failed")
self.presentViewController(networkErrorAlertOne, animated: true) {}
self.realUsername = self.username.text!
self.performSegueWithIdentifier("viewControllerToTBVC", sender: nil)
}else{
print("FATAL ERR// something wrong with signup counter")
self.presentViewController(networkErrorAlertOne, animated: true) {}
self.realUsername = self.username.text!
}
}
}
signInOrUpAlertOne.addAction(signInOrUpAlertOneSignUpButton)
let signInOrUpAlertOneSignInButton = UIAlertAction(title: "use different username", style: .Default) { (action) in
}
signInOrUpAlertOne.addAction(signInOrUpAlertOneSignInButton)
/*redisClient.auth("", completionHandler: { (string, error) -> Void in
if error == nil {
authenticated = (string == "OK")
print("authenticated")
}
print("error is \(error)")
if authenticated{
}else{
redisClient.quit { (string, error) -> Void in }
}
})*/
//check to see if username already exists
redisClient.exists(username.text!) { (int, error) -> Void in
//if it does exist, and there is no error continue to check is password is correct
if error == nil && int == 1 {
print("omggg!!! the redis db didnt give an error for no reason!!! it worked!!!")
self.realUsername = self.username.text!
self.redisClient.lRange(self.username.text!, start: 0, stop: 0, completionHandler: { (array, error) -> Void in
if array[0] as? String == self.password.text {
print("testOne")
self.realUsername = self.username.text!
self.redisClient.lRange("\(self.username.text!)fandoms", start: 0, stop: 99999999, completionHandler: { (array, error) -> Void in
print("getting fandoms to send to other view controllers")
for fandom in array {
self.userFandoms.append(fandom)
print("appended \(fandom) to userfandoms")
}
print("\(self.username.text!)fandoms")
print(array)
print("there is an error if \(self.userFandoms) != \(array) blub")
if self.userFandoms.count < 1 {
print("redis connection array not working")
print(self.userFandoms)
} else {
self.performSegueWithIdentifier("viewControllerToTBVC", sender: nil)
}
})
}else{
self.presentViewController(loginErrorAlertOne, animated: true) {}
}
})
}else if error == nil && int == 0 {
print("zerow")
self.redisClient.exists(self.password.text!, completionHandler: { (int, error) -> Void in
if error == nil && int == 1 {
self.redisClient.lRange(self.password.text!, start: 0, stop: 0, completionHandler: { (array, error) -> Void in
if array[0] as? String == self.username.text! {
self.presentViewController(passwordUsernameSwitchErrorAlertOne, animated: true) {}
self.realUsername = self.password.text!
}else{
self.presentViewController(signInOrUpAlertOne, animated: true) {}
}
})
}else{
self.presentViewController(signInOrUpAlertOne, animated: true) {}
}
})
}else{
if int != nil {
self.presentViewController(networkErrorAlertOne, animated: true) {}
print("same old redis error :p")
print(error)
}else{
self.presentViewController(networkErrorAlertTwo, animated: true) {}
}
}
}
}
//when next button @bottom hit calls signInUp function
@IBAction func nextButton(sender: AnyObject) {
singInUp()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let DestViewCont: TabBarViewController = segue.destinationViewController as! TabBarViewController
DestViewCont.usernameTwo = self.realUsername
DestViewCont.userFandoms = self.userFandoms
DestViewCont.number = self.number
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//dissmiss keyboard calles on tap
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//textField editing problems algorithm
func textFieldShouldReturn(textField: UITextField) -> Bool {
self.view.endEditing(true)
self.singInUp()
return false
}
}
|
unlicense
|
09110591db23fc2e915a7bb83b1ba2a0
| 52.651515 | 352 | 0.548362 | 5.365152 | false | false | false | false |
igorbarinov/powerball-helper
|
SwiftGifCommon/UIImage+Gif.swift
|
2
|
3658
|
//
// Gif.swift
// SwiftGif
//
// Created by Arne Bahlo on 07.06.14.
// Copyright (c) 2014 Arne Bahlo. All rights reserved.
//
import UIKit
import ImageIO
extension UIImage {
class func animatedImageWithData(data: NSData) -> UIImage? {
let source = CGImageSourceCreateWithData(data, nil)
let image = UIImage.animatedImageWithSource(source)
return image
}
class func delayForImageAtIndex(index: UInt, source: CGImageSourceRef) -> Double {
var delay = 0.1
// Get dictionaries
let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil)
let properties: NSDictionary = cfProperties // Make NSDictionary
var gifProperties : NSDictionary = properties[kCGImagePropertyGIFDictionary] as NSDictionary
// Get delay time
var number : AnyObject! = gifProperties[kCGImagePropertyGIFUnclampedDelayTime]
if number.doubleValue == 0 {
number = gifProperties[kCGImagePropertyGIFDelayTime]
}
delay = number as Double
if delay < 0.1 {
delay = 0.1 // Make sure they're not too fast
}
return delay
}
class func gcdForPair(var a: Int?, var _ b: Int?) -> Int {
// Check if one of them is nil
if b == nil || a == nil {
if b != nil {
return b!
} else if a != nil {
return a!
} else {
return 0
}
}
// Swap for modulo
if a < b {
var c = a
a = b
b = c
}
// Get greatest common divisor
var rest: Int
while true {
rest = a! % b!
if rest == 0 {
return b! // Found it
} else {
a = b
b = rest
}
}
}
class func gcdForArray(array: Array<Int>) -> Int {
if array.isEmpty {
return 1
}
var gcd = array[0]
for val in array {
gcd = UIImage.gcdForPair(val, gcd)
}
return gcd
}
class func animatedImageWithSource(source: CGImageSource) -> UIImage? {
let count = CGImageSourceGetCount(source)
var images = [CGImageRef]()
var delays = [Int]()
// Fill arrays
for i in 0..<count {
// Add image
images.append(CGImageSourceCreateImageAtIndex(source, i, nil))
// At it's delay in cs
var delaySeconds = UIImage.delayForImageAtIndex(UInt(i), source: source)
delays.append(Int(delaySeconds * 1000.0)) // Seconds to ms
}
// Calculate full duration
let duration: Int = {
var sum = 0
for val: Int in delays {
sum += val
}
return sum
}()
// Get frames
let gcd = gcdForArray(delays)
var frames = [UIImage]()
var frame: UIImage
var frameCount: Int
for i in 0..<count {
frame = UIImage(CGImage: images[Int(i)])
frameCount = Int(delays[Int(i)] / gcd)
for j in 0..<frameCount {
frames.append(frame)
}
}
// Heyhey
let animation = UIImage.animatedImageWithImages(frames, duration: Double(duration) / 1000.0)
return animation
}
}
|
mit
|
788acd2be20e0f68378eec22678a99c8
| 25.128571 | 100 | 0.485785 | 5.108939 | false | false | false | false |
nestproject/Padlock
|
PadlockTests/PadlockTests.swift
|
1
|
1075
|
import XCTest
import Padlock
import Nest
import Inquiline
func helloWorld(request:RequestType) -> ResponseType {
return Response(.Ok, body: "Hello world")
}
func isValidCredentials(username:String, password:String) -> Bool {
return username == "kyle" && password == "nest"
}
class PadlockTests: XCTestCase {
func testNoCredentials() {
let request = Request(method: "GET", path: "/")
let response = 🔒(isValidCredentials, application: helloWorld)(request)
XCTAssertEqual(response.statusLine, "401 UNAUTHORIZED")
}
func testInvalidCredentials() {
let request = Request(method: "GET", path: "/", headers:[("Authorization", "kyle secret")])
let response = 🔒(isValidCredentials, application: helloWorld)(request)
XCTAssertEqual(response.statusLine, "401 UNAUTHORIZED")
}
func testValidCredentials() {
let request = Request(method: "GET", path: "/", headers:[("Authorization", "kyle nest")])
let response = 🔒(isValidCredentials, application: helloWorld)(request)
XCTAssertEqual(response.statusLine, "200 OK")
}
}
|
bsd-2-clause
|
0f7d1171cf50687485c4f90752423c61
| 29.457143 | 95 | 0.709193 | 4.164063 | false | true | false | false |
csnu17/My-Blognone-apps
|
myblognone/Modules/About/User Interface/WireFrame/AboutWireFrame.swift
|
1
|
2302
|
//
// AboutWireFrame.swift
// myblognone
//
// Created by Kittisak Phetrungnapha on 12/25/2559.
// Copyright © 2559 Kittisak Phetrungnapha. All rights reserved.
//
import Foundation
import UIKit
class AboutWireFrame: AboutWireFrameProtocol {
static let AboutViewControllerIdentifier = "AboutViewController"
static let StoryboardIdentifier = "About"
private let emailForFeedback = "[email protected]"
private let appStoreUrl = "itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=1191248877&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software"
static func presentAboutModule(fromView view: AnyObject) {
let storyboard = UIStoryboard(name: StoryboardIdentifier, bundle: Bundle.main)
// Generating module components
let aboutView = storyboard.instantiateViewController(withIdentifier: AboutViewControllerIdentifier) as! AboutViewController
let presenter: AboutPresenterProtocol & AboutInteractorOutputProtocol = AboutPresenter()
let interactor: AboutInteractorInputProtocol = AboutInteractor()
let wireFrame: AboutWireFrameProtocol = AboutWireFrame()
let dataManager = AboutDataManager()
// Connecting
aboutView.presenter = presenter
presenter.view = aboutView
presenter.wireFrame = wireFrame
presenter.interactor = interactor
interactor.presenter = presenter
interactor.dataManager = dataManager
// Push
if let nav = view as? UINavigationController {
nav.pushViewController(aboutView, animated: true)
}
}
func openMailApp() {
guard let url = URL(string: "mailto:\(emailForFeedback)") else { return }
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
func openAppStore() {
guard let url = URL(string: appStoreUrl) else { return }
if #available(iOS 10, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
|
mit
|
58ea87953d48a93ad17bb47d12cf567b
| 34.953125 | 196 | 0.666232 | 5.07947 | false | false | false | false |
jacobwhite/firefox-ios
|
Shared/Extensions/URLExtensions.swift
|
1
|
18630
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private struct ETLDEntry: CustomStringConvertible {
let entry: String
var isNormal: Bool { return isWild || !isException }
var isWild: Bool = false
var isException: Bool = false
init(entry: String) {
self.entry = entry
self.isWild = entry.hasPrefix("*")
self.isException = entry.hasPrefix("!")
}
fileprivate var description: String {
return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }"
}
}
private typealias TLDEntryMap = [String: ETLDEntry]
private func loadEntriesFromDisk() -> TLDEntryMap? {
if let data = String.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: Bundle(identifier: "org.mozilla.Shared")!, encoding: .utf8, error: nil) {
let lines = data.components(separatedBy: "\n")
let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" }
var entries = TLDEntryMap()
for line in trimmedLines {
let entry = ETLDEntry(entry: line)
let key: String
if entry.isWild {
// Trim off the '*.' part of the line
key = String(line[line.index(line.startIndex, offsetBy: 2)...])
} else if entry.isException {
// Trim off the '!' part of the line
key = String(line[line.index(line.startIndex, offsetBy: 1)...])
} else {
key = line
}
entries[key] = entry
}
return entries
}
return nil
}
private var etldEntries: TLDEntryMap? = {
return loadEntriesFromDisk()
}()
// MARK: - Local Resource URL Extensions
extension URL {
public func allocatedFileSize() -> Int64 {
// First try to get the total allocated size and in failing that, get the file allocated size
return getResourceLongLongForKey(URLResourceKey.totalFileAllocatedSizeKey.rawValue)
?? getResourceLongLongForKey(URLResourceKey.fileAllocatedSizeKey.rawValue)
?? 0
}
public func getResourceValueForKey(_ key: String) -> Any? {
let resourceKey = URLResourceKey(key)
let keySet = Set<URLResourceKey>([resourceKey])
var val: Any?
do {
let values = try resourceValues(forKeys: keySet)
val = values.allValues[resourceKey]
} catch _ {
return nil
}
return val
}
public func getResourceLongLongForKey(_ key: String) -> Int64? {
return (getResourceValueForKey(key) as? NSNumber)?.int64Value
}
public func getResourceBoolForKey(_ key: String) -> Bool? {
return getResourceValueForKey(key) as? Bool
}
public var isRegularFile: Bool {
return getResourceBoolForKey(URLResourceKey.isRegularFileKey.rawValue) ?? false
}
public func lastComponentIsPrefixedBy(_ prefix: String) -> Bool {
return (pathComponents.last?.hasPrefix(prefix) ?? false)
}
}
// The list of permanent URI schemes has been taken from http://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml
private let permanentURISchemes = ["aaa", "aaas", "about", "acap", "acct", "cap", "cid", "coap", "coaps", "crid", "data", "dav", "dict", "dns", "example", "file", "ftp", "geo", "go", "gopher", "h323", "http", "https", "iax", "icap", "im", "imap", "info", "ipp", "ipps", "iris", "iris.beep", "iris.lwz", "iris.xpc", "iris.xpcs", "jabber", "ldap", "mailto", "mid", "msrp", "msrps", "mtqp", "mupdate", "news", "nfs", "ni", "nih", "nntp", "opaquelocktoken", "pkcs11", "pop", "pres", "reload", "rtsp", "rtsps", "rtspu", "service", "session", "shttp", "sieve", "sip", "sips", "sms", "snmp", "soap.beep", "soap.beeps", "stun", "stuns", "tag", "tel", "telnet", "tftp", "thismessage", "tip", "tn3270", "turn", "turns", "tv", "urn", "vemmi", "vnc", "ws", "wss", "xcon", "xcon-userid", "xmlrpc.beep", "xmlrpc.beeps", "xmpp", "z39.50r", "z39.50s"]
extension URL {
public func withQueryParams(_ params: [URLQueryItem]) -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)!
var items = (components.queryItems ?? [])
for param in params {
items.append(param)
}
components.queryItems = items
return components.url!
}
public func withQueryParam(_ name: String, value: String) -> URL {
var components = URLComponents(url: self, resolvingAgainstBaseURL: false)!
let item = URLQueryItem(name: name, value: value)
components.queryItems = (components.queryItems ?? []) + [item]
return components.url!
}
public func getQuery() -> [String: String] {
var results = [String: String]()
let keyValues = self.query?.components(separatedBy: "&")
if keyValues?.count ?? 0 > 0 {
for pair in keyValues! {
let kv = pair.components(separatedBy: "=")
if kv.count > 1 {
results[kv[0]] = kv[1]
}
}
}
return results
}
public var hostPort: String? {
if let host = self.host {
if let port = (self as NSURL).port?.int32Value {
return "\(host):\(port)"
}
return host
}
return nil
}
public var origin: String? {
guard isWebPage(includeDataURIs: false), let hostPort = self.hostPort, let scheme = scheme else {
return nil
}
return "\(scheme)://\(hostPort)"
}
/**
* Returns the second level domain (SLD) of a url. It removes any subdomain/TLD
*
* E.g., https://m.foo.com/bar/baz?noo=abc#123 => foo
**/
public var hostSLD: String {
guard let publicSuffix = self.publicSuffix, let baseDomain = self.baseDomain else {
return self.normalizedHost ?? self.absoluteString
}
return baseDomain.replacingOccurrences(of: ".\(publicSuffix)", with: "")
}
public var normalizedHostAndPath: String? {
return normalizedHost.flatMap { $0 + self.path }
}
public var absoluteDisplayString: String {
var urlString = self.absoluteString
// For http URLs, get rid of the trailing slash if the path is empty or '/'
if (self.scheme == "http" || self.scheme == "https") && (self.path == "/") && urlString.hasSuffix("/") {
urlString = String(urlString[..<urlString.index(urlString.endIndex, offsetBy: -1)])
}
// If it's basic http, strip out the string but leave anything else in
if urlString.hasPrefix("http://") {
return String(urlString[urlString.index(urlString.startIndex, offsetBy: 7)...])
} else {
return urlString
}
}
/// String suitable for displaying outside of the app, for example in notifications, were Data Detectors will
/// linkify the text and make it into a openable-in-Safari link.
public var absoluteDisplayExternalString: String {
return self.absoluteDisplayString.replacingOccurrences(of: ".", with: "\u{2024}")
}
public var displayURL: URL? {
if self.isReaderModeURL {
return self.decodeReaderModeURL?.havingRemovedAuthorisationComponents()
}
if self.isErrorPageURL {
return originalURLFromErrorURL?.displayURL
}
if !self.isAboutURL {
return self.havingRemovedAuthorisationComponents()
}
return nil
}
/**
Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix
with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain
would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc).
:returns: The base domain string for the given host name.
*/
public var baseDomain: String? {
guard !isIPv6, let host = host else { return nil }
// If this is just a hostname and not a FQDN, use the entire hostname.
if !host.contains(".") {
return host
}
return publicSuffixFromHost(host, withAdditionalParts: 1)
}
/**
* Returns just the domain, but with the same scheme, and a trailing '/'.
*
* E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/
*
* Any failure? Return this URL.
*/
public var domainURL: URL {
if let normalized = self.normalizedHost {
// Use NSURLComponents instead of NSURL since the former correctly preserves
// brackets for IPv6 hosts, whereas the latter escapes them.
var components = URLComponents()
components.scheme = self.scheme
components.port = self.port
components.host = normalized
components.path = "/"
return components.url ?? self
}
return self
}
public var normalizedHost: String? {
// Use components.host instead of self.host since the former correctly preserves
// brackets for IPv6 hosts, whereas the latter strips them.
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), var host = components.host, host != "" else {
return nil
}
if let range = host.range(of: "^(www|mobile|m)\\.", options: .regularExpression) {
host.replaceSubrange(range, with: "")
}
return host
}
/**
Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/.
For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk.
:returns: The public suffix for within the given hostname.
*/
public var publicSuffix: String? {
return host.flatMap { publicSuffixFromHost($0, withAdditionalParts: 0) }
}
public func isWebPage(includeDataURIs: Bool = true) -> Bool {
let schemes = includeDataURIs ? ["http", "https", "data"] : ["http", "https"]
return scheme.map { schemes.contains($0) } ?? false
}
// This helps find local urls that we do not want to show loading bars on.
// These utility pages should be invisible to the user
public var isLocalUtility: Bool {
guard self.isLocal else {
return false
}
let utilityURLs = ["/errors", "/about/sessionrestore", "/about/home", "/reader-mode"]
return utilityURLs.contains { self.path.hasPrefix($0) }
}
public var isLocal: Bool {
guard isWebPage(includeDataURIs: false) else {
return false
}
// iOS forwards hostless URLs (e.g., http://:6571) to localhost.
guard let host = host, !host.isEmpty else {
return true
}
return host.lowercased() == "localhost" || host == "127.0.0.1"
}
public var isIPv6: Bool {
return host?.contains(":") ?? false
}
/**
Returns whether the URL's scheme is one of those listed on the official list of URI schemes.
This only accepts permanent schemes: historical and provisional schemes are not accepted.
*/
public var schemeIsValid: Bool {
guard let scheme = scheme else { return false }
return permanentURISchemes.contains(scheme.lowercased())
}
public func havingRemovedAuthorisationComponents() -> URL {
guard var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) else {
return self
}
urlComponents.user = nil
urlComponents.password = nil
if let url = urlComponents.url {
return url
}
return self
}
}
// Extensions to deal with ReaderMode URLs
extension URL {
public var isReaderModeURL: Bool {
let scheme = self.scheme, host = self.host, path = self.path
return scheme == "http" && host == "localhost" && path == "/reader-mode/page"
}
public var decodeReaderModeURL: URL? {
if self.isReaderModeURL {
if let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems, queryItems.count == 1 {
if let queryItem = queryItems.first, let value = queryItem.value {
return URL(string: value)
}
}
}
return nil
}
public func encodeReaderModeURL(_ baseReaderModeURL: String) -> URL? {
if let encodedURL = absoluteString.addingPercentEncoding(withAllowedCharacters: .alphanumerics) {
if let aboutReaderURL = URL(string: "\(baseReaderModeURL)?url=\(encodedURL)") {
return aboutReaderURL
}
}
return nil
}
}
// Helpers to deal with ErrorPage URLs
extension URL {
public var isErrorPageURL: Bool {
if let host = self.host {
return self.scheme == "http" && host == "localhost" && path == "/errors/error.html"
}
return false
}
public var originalURLFromErrorURL: URL? {
let components = URLComponents(url: self, resolvingAgainstBaseURL: false)
if let queryURL = components?.queryItems?.find({ $0.name == "url" })?.value {
return URL(string: queryURL)
}
return nil
}
}
// Helpers to deal with About URLs
extension URL {
public var isAboutHomeURL: Bool {
if let urlString = self.getQuery()["url"]?.unescape(), isErrorPageURL {
let url = URL(string: urlString) ?? self
return url.aboutComponent == "home"
}
return self.aboutComponent == "home"
}
public var isAboutURL: Bool {
return self.aboutComponent != nil
}
/// If the URI is an about: URI, return the path after "about/" in the URI.
/// For example, return "home" for "http://localhost:1234/about/home/#panel=0".
public var aboutComponent: String? {
let aboutPath = "/about/"
guard let scheme = self.scheme, let host = self.host else {
return nil
}
if scheme == "http" && host == "localhost" && path.hasPrefix(aboutPath) {
return path.substring(from: aboutPath.endIndex)
}
return nil
}
}
//MARK: Private Helpers
private extension URL {
func publicSuffixFromHost( _ host: String, withAdditionalParts additionalPartCount: Int) -> String? {
if host.isEmpty {
return nil
}
// Check edge case where the host is either a single or double '.'.
if host.isEmpty || NSString(string: host).lastPathComponent == "." {
return ""
}
/**
* The following algorithm breaks apart the domain and checks each sub domain against the effective TLD
* entries from the effective_tld_names.dat file. It works like this:
*
* Example Domain: test.bbc.co.uk
* TLD Entry: bbc
*
* 1. Start off by checking the current domain (test.bbc.co.uk)
* 2. Also store the domain after the next dot (bbc.co.uk)
* 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks:
* i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches
* since it satisfies the wildcard requirement.
* ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then
* currentDomain is a valid TLD
* iii. If the entry we matched is an exception case, then the base domain is the part after the next dot
*
* On the next run through the loop, we set the new domain to check as the part after the next dot,
* update the next dot reference to be the string after the new next dot, and check the TLD entries again.
* If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the
* top domain level so we use it by default.
*/
let tokens = host.components(separatedBy: ".")
let tokenCount = tokens.count
var suffix: String?
var previousDomain: String? = nil
var currentDomain: String = host
for offset in 0..<tokenCount {
// Store the offset for use outside of this scope so we can add additional parts if needed
let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joined(separator: ".") : nil
if let entry = etldEntries?[currentDomain] {
if entry.isWild && (previousDomain != nil) {
suffix = previousDomain
break
} else if entry.isNormal || (nextDot == nil) {
suffix = currentDomain
break
} else if entry.isException {
suffix = nextDot
break
}
}
previousDomain = currentDomain
if let nextDot = nextDot {
currentDomain = nextDot
} else {
break
}
}
var baseDomain: String?
if additionalPartCount > 0 {
if let suffix = suffix {
// Take out the public suffixed and add in the additional parts we want.
let literalFromEnd: NSString.CompareOptions = [.literal, // Match the string exactly.
.backwards, // Search from the end.
.anchored] // Stick to the end.
let suffixlessHost = host.replacingOccurrences(of: suffix, with: "", options: literalFromEnd, range: nil)
let suffixlessTokens = suffixlessHost.components(separatedBy: ".").filter { $0 != "" }
let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount)
let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count]
let partsString = additionalParts.joined(separator: ".")
baseDomain = [partsString, suffix].joined(separator: ".")
} else {
return nil
}
} else {
baseDomain = suffix
}
return baseDomain
}
}
|
mpl-2.0
|
aac6763ef43b4c696464760ac2b20d20
| 37.491736 | 835 | 0.596618 | 4.429387 | false | false | false | false |
ashfurrow/yourfirstswiftapp
|
Coffee Timer/Coffee Timer/TimerListTableViewController.swift
|
1
|
10399
|
//
// TimerListTableViewController.swift
// Coffee Timer
//
// Created by Ash Furrow on 2015-01-10.
// Copyright (c) 2015 Ash Furrow. All rights reserved.
//
import UIKit
import CoreData
extension Array {
mutating func moveFrom(source: Int, toDestination destination: Int) {
let object = removeAtIndex(source)
insert(object, atIndex: destination)
}
}
class TimerListTableViewController: UITableViewController {
var userReorderingCells = false
lazy var fetchedResultsController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "TimerModel")
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: "type", ascending: true),
NSSortDescriptor(key: "displayOrder", ascending: true)
]
let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: appDelegate().coreDataStack.managedObjectContext, sectionNameKeyPath: "type", cacheName: nil)
controller.delegate = self
return controller
}()
enum TableSection: Int {
case Coffee = 0
case Tea
case NumberOfSections
}
override func viewDidLoad() {
super.viewDidLoad()
do {
try fetchedResultsController.performFetch()
} catch {
print("Error fetching: \(error)")
}
navigationItem.leftBarButtonItem = editButtonItem()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if presentedViewController != nil {
tableView.reloadData()
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections?[section]
return sectionInfo?.numberOfObjects ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let timerModel = timerModelForIndexPath(indexPath)
cell.textLabel?.text = timerModel.name
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == TableSection.Coffee.rawValue {
return NSLocalizedString("Coffees", comment: "Coffee section title")
} else { // Must be TableSection.Tea
return NSLocalizedString("Teas", comment: "Tea section title")
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
guard tableView.editing else { return }
let cell = tableView.cellForRowAtIndexPath(indexPath)
performSegueWithIdentifier("editDetail", sender: cell)
}
override func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == "copy:" {
return true
}
return false
}
override func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject!) {
let timerModel = timerModelForIndexPath(indexPath)
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = timerModel.name
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
userReorderingCells = true
// Grab the section and the TimerModels in the section
let sectionInfo = fetchedResultsController.sections?[sourceIndexPath.section]
var objectsInSection = sectionInfo?.objects ?? []
// Rearrange the order to match the user's actions
// Note: this doesn't move anything in Core Data, just our objectsInSection array
objectsInSection.moveFrom(sourceIndexPath.row, toDestination: destinationIndexPath.row)
// The models are now in the correct order.
// Update their displayOrder to match the new order.
for i in 0..<objectsInSection.count {
let model = objectsInSection[i] as? TimerModel
model?.displayOrder = Int32(i)
}
userReorderingCells = false
appDelegate().coreDataStack.save()
}
override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath {
// If the source and destination index paths are the same section,
// then return the proposed index path
if sourceIndexPath.section == proposedDestinationIndexPath.section {
return proposedDestinationIndexPath
}
// The sections are different, which we want to disallow.
if sourceIndexPath.section == TableSection.Coffee.rawValue {
// This is coming from the coffee section, so return
// the last index path in that section.
let sectionInfo = fetchedResultsController.sections?[TableSection.Coffee.rawValue]
let numberOfCoffeTimers = sectionInfo?.numberOfObjects ?? 0
return NSIndexPath(forItem: numberOfCoffeTimers - 1, inSection: 0)
} else { // Must be TableSection.Tea
// This is coming from the tea section, so return
// the first index path in that section.
return NSIndexPath(forItem: 0, inSection: 1)
}
}
// MARK: - Utility methods
func timerModelForIndexPath(indexPath: NSIndexPath) -> TimerModel {
return fetchedResultsController.objectAtIndexPath(indexPath) as! TimerModel
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let cell = sender as? UITableViewCell {
let indexPath = tableView.indexPathForCell(cell)!
let timerModel = timerModelForIndexPath(indexPath)
if segue.identifier == "pushDetail" {
let detailViewController = segue.destinationViewController as! TimerDetailViewController
detailViewController.timerModel = timerModel
} else if segue.identifier == "editDetail" {
let navigationController = segue.destinationViewController as! UINavigationController
let editViewController = navigationController.topViewController as! TimerEditViewController
editViewController.timerModel = timerModel
editViewController.delegate = self
}
} else if let _ = sender as? UIBarButtonItem {
if segue.identifier == "newTimer" {
let navigationController = segue.destinationViewController as! UINavigationController
let editViewController = navigationController.topViewController as! TimerEditViewController
editViewController.creatingNewTimer = true
editViewController.timerModel = NSEntityDescription.insertNewObjectForEntityForName("TimerModel", inManagedObjectContext: appDelegate().coreDataStack.managedObjectContext) as! TimerModel
editViewController.delegate = self
}
}
}
override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject?) -> Bool {
if identifier == "pushDetail" {
if tableView.editing {
return false
}
}
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let timer = timerModelForIndexPath(indexPath)
timer.managedObjectContext?.deleteObject(timer)
}
}
}
extension TimerListTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(controller: NSFetchedResultsController) {
tableView.beginUpdates()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.endUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
guard userReorderingCells == false else { return }
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
case .Move:
tableView.moveRowAtIndexPath(indexPath!, toIndexPath: newIndexPath!)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath!], withRowAnimation: .Automatic)
}
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
guard userReorderingCells == false else { return }
switch type {
case .Insert:
tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
case .Delete:
tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Automatic)
default: break
}
}
}
extension TimerListTableViewController: TimerEditViewControllerDelegate {
func timerEditViewControllerDidCancel(viewController: TimerEditViewController) {
if viewController.creatingNewTimer {
appDelegate().coreDataStack.managedObjectContext.deleteObject(viewController.timerModel)
}
}
func timerEditViewControllerDidSave(viewController: TimerEditViewController) {
appDelegate().coreDataStack.save()
}
}
|
mit
|
28fe11045e92b7aab2a8009608241ae6
| 38.241509 | 211 | 0.69199 | 6.038908 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/ViewRelated/Post/Scheduling/CalendarCollectionView.swift
|
1
|
16711
|
import Foundation
import JTAppleCalendar
enum CalendarCollectionViewStyle {
case month
case year
}
class CalendarCollectionView: WPJTACMonthView {
let calDataSource: CalendarDataSource
let style: CalendarCollectionViewStyle
init(calendar: Calendar,
style: CalendarCollectionViewStyle = .month,
startDate: Date? = nil,
endDate: Date? = nil) {
calDataSource = CalendarDataSource(
calendar: calendar,
style: style,
startDate: startDate,
endDate: endDate
)
self.style = style
super.init()
setup()
}
required init?(coder aDecoder: NSCoder) {
calDataSource = CalendarDataSource(calendar: Calendar.current, style: .month)
style = .month
super.init(coder: aDecoder)
setup()
}
private func setup() {
register(DateCell.self, forCellWithReuseIdentifier: DateCell.Constants.reuseIdentifier)
register(CalendarYearHeaderView.self,
forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
withReuseIdentifier: CalendarYearHeaderView.reuseIdentifier)
backgroundColor = .clear
switch style {
case .month:
scrollDirection = .horizontal
scrollingMode = .stopAtEachCalendarFrame
case .year:
scrollDirection = .vertical
allowsMultipleSelection = true
allowsRangedSelection = true
rangeSelectionMode = .continuous
minimumLineSpacing = 0
minimumInteritemSpacing = 0
cellSize = 50
}
showsHorizontalScrollIndicator = false
isDirectionalLockEnabled = true
calendarDataSource = calDataSource
calendarDelegate = calDataSource
}
/// VoiceOver scrollback workaround
/// When using VoiceOver, moving focus from the surrounding elements (usually the next month button) to the calendar DateCells, a
/// scrollback to 0 was triggered by the system. This appears to be expected (though irritating) behaviour with a paging UICollectionView.
/// The impact of this scrollback for the month view calendar (as used to schedule a post) is that the calendar jumps to 1951-01-01, with
/// the only way to navigate forwards being to tap the "next month" button repeatedly.
/// Ignoring these scrolls back to 0 when VoiceOver is in use prevents this issue, while not impacting other use of the calendar.
/// Similar behaviour sometimes occurs with the non-paging year view calendar (as used for activity log filtering) which is harder to reproduce,
/// but also remedied by this change.
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
if shouldPreventAccessibilityFocusScrollback(for: contentOffset) {
return
}
super.setContentOffset(contentOffset, animated: animated)
}
func shouldPreventAccessibilityFocusScrollback(for newContentOffset: CGPoint) -> Bool {
if UIAccessibility.isVoiceOverRunning {
switch style {
case .month:
return newContentOffset.x == 0 && contentOffset.x > 0
case .year:
return newContentOffset.y == 0 && contentOffset.y > 0
}
}
return false
}
}
class CalendarDataSource: JTACMonthViewDataSource {
var willScroll: ((DateSegmentInfo) -> Void)?
var didScroll: ((DateSegmentInfo) -> Void)?
var didSelect: ((Date?, Date?) -> Void)?
// First selected date
var firstDate: Date?
// End selected date
var endDate: Date?
private let calendar: Calendar
private let style: CalendarCollectionViewStyle
init(calendar: Calendar,
style: CalendarCollectionViewStyle,
startDate: Date? = nil,
endDate: Date? = nil) {
self.calendar = calendar
self.style = style
self.firstDate = startDate
self.endDate = endDate
}
func configureCalendar(_ calendar: JTACMonthView) -> ConfigurationParameters {
/// When style is year, display the last 20 years til this month
if style == .year {
var dateComponent = DateComponents()
dateComponent.year = -20
let startDate = Calendar.current.date(byAdding: dateComponent, to: Date())
let endDate = Date().endOfMonth
if let startDate = startDate, let endDate = endDate {
return ConfigurationParameters(startDate: startDate, endDate: endDate, calendar: self.calendar)
}
}
let startDate = Date.farPastDate
let endDate = Date.farFutureDate
return ConfigurationParameters(startDate: startDate, endDate: endDate, calendar: self.calendar)
}
}
extension CalendarDataSource: JTACMonthViewDelegate {
func calendar(_ calendar: JTACMonthView, cellForItemAt date: Date, cellState: CellState, indexPath: IndexPath) -> JTACDayCell {
let cell = calendar.dequeueReusableJTAppleCell(withReuseIdentifier: DateCell.Constants.reuseIdentifier, for: indexPath)
if let dateCell = cell as? DateCell {
configure(cell: dateCell, with: cellState)
}
return cell
}
func calendar(_ calendar: JTACMonthView, willDisplay cell: JTACDayCell, forItemAt date: Date, cellState: CellState, indexPath: IndexPath) {
configure(cell: cell, with: cellState)
}
func calendar(_ calendar: JTACMonthView, willScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
willScroll?(visibleDates)
}
func calendar(_ calendar: JTACMonthView, didScrollToDateSegmentWith visibleDates: DateSegmentInfo) {
didScroll?(visibleDates)
}
func calendar(_ calendar: JTACMonthView, didSelectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
if style == .year {
// If the date is in the future, bail out
if date > Date() {
return
}
if let firstDate = firstDate {
if let endDate = endDate {
// When tapping a selected firstDate or endDate reset the rest
if date == firstDate || date == endDate {
self.firstDate = date
self.endDate = nil
// Increase the range at the left side
} else if date < firstDate {
self.firstDate = date
// Increase the range at the right side
} else {
self.endDate = date
}
// When tapping a single selected date, deselect everything
} else if date == firstDate {
self.firstDate = nil
self.endDate = nil
// When selecting a second date
} else {
self.firstDate = min(firstDate, date)
endDate = max(firstDate, date)
}
// When selecting the first date
} else {
firstDate = date
}
// Monthly calendar only selects a single date
} else {
firstDate = date
}
didSelect?(firstDate, endDate)
UIView.performWithoutAnimation {
calendar.reloadItems(at: calendar.indexPathsForVisibleItems)
}
configure(cell: cell, with: cellState)
}
func calendar(_ calendar: JTACMonthView, didDeselectDate date: Date, cell: JTACDayCell?, cellState: CellState, indexPath: IndexPath) {
configure(cell: cell, with: cellState)
}
func calendarSizeForMonths(_ calendar: JTACMonthView?) -> MonthSize? {
return style == .year ? MonthSize(defaultSize: 50) : nil
}
func calendar(_ calendar: JTACMonthView, headerViewForDateRange range: (start: Date, end: Date), at indexPath: IndexPath) -> JTACMonthReusableView {
let date = range.start
let formatter = DateFormatter()
formatter.dateFormat = "MMMM yyyy"
let header = calendar.dequeueReusableJTAppleSupplementaryView(withReuseIdentifier: CalendarYearHeaderView.reuseIdentifier, for: indexPath)
(header as! CalendarYearHeaderView).titleLabel.text = formatter.string(from: date)
return header
}
private func configure(cell: JTACDayCell?, with state: CellState) {
let cell = cell as? DateCell
cell?.configure(with: state, startDate: firstDate, endDate: endDate, hideInOutDates: style == .year)
}
}
class DateCell: JTACDayCell {
struct Constants {
static let labelSize: CGFloat = 28
static let reuseIdentifier = "dateCell"
static var selectedColor: UIColor {
UIColor(light: .primary(.shade5), dark: .primary(.shade90))
}
}
let dateLabel = UILabel()
let leftPlaceholder = UIView()
let rightPlaceholder = UIView()
let dateFormatter = DateFormatter()
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup() {
dateLabel.translatesAutoresizingMaskIntoConstraints = false
dateLabel.textAlignment = .center
dateLabel.font = UIFont.preferredFont(forTextStyle: .callout)
// Show circle behind text for selected day
dateLabel.clipsToBounds = true
dateLabel.layer.cornerRadius = Constants.labelSize/2
addSubview(dateLabel)
NSLayoutConstraint.activate([
dateLabel.widthAnchor.constraint(equalToConstant: Constants.labelSize),
dateLabel.heightAnchor.constraint(equalTo: dateLabel.widthAnchor),
dateLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
dateLabel.centerXAnchor.constraint(equalTo: centerXAnchor)
])
leftPlaceholder.translatesAutoresizingMaskIntoConstraints = false
rightPlaceholder.translatesAutoresizingMaskIntoConstraints = false
addSubview(leftPlaceholder)
addSubview(rightPlaceholder)
NSLayoutConstraint.activate([
leftPlaceholder.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.6),
leftPlaceholder.heightAnchor.constraint(equalTo: dateLabel.heightAnchor),
leftPlaceholder.trailingAnchor.constraint(equalTo: centerXAnchor),
leftPlaceholder.centerYAnchor.constraint(equalTo: centerYAnchor)
])
NSLayoutConstraint.activate([
rightPlaceholder.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.5),
rightPlaceholder.heightAnchor.constraint(equalTo: dateLabel.heightAnchor),
rightPlaceholder.leadingAnchor.constraint(equalTo: centerXAnchor, constant: 0),
rightPlaceholder.centerYAnchor.constraint(equalTo: centerYAnchor)
])
bringSubviewToFront(dateLabel)
}
}
extension DateCell {
/// Configure the DateCell
///
/// - Parameters:
/// - state: the representation of the cell state
/// - startDate: the first Date selected
/// - endDate: the last Date selected
/// - hideInOutDates: a Bool to hide/display dates outside of the current month (filling the entire row)
/// - Returns: UIColor. Red in cases of error
func configure(with state: CellState,
startDate: Date? = nil,
endDate: Date? = nil,
hideInOutDates: Bool = false) {
dateLabel.text = state.text
dateFormatter.setLocalizedDateFormatFromTemplate("EEE MMM d, yyyy")
dateLabel.accessibilityLabel = dateFormatter.string(from: state.date)
dateLabel.accessibilityTraits = .button
var textColor: UIColor
if hideInOutDates && state.dateBelongsTo != .thisMonth {
isHidden = true
} else {
isHidden = false
}
// Reset state
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .clear
textColor = .text
dateLabel.accessibilityTraits = .button
if state.isSelected {
dateLabel.accessibilityTraits.insert(.selected)
}
switch position(for: state.date, startDate: startDate, endDate: endDate) {
case .middle:
textColor = .text
leftPlaceholder.backgroundColor = Constants.selectedColor
rightPlaceholder.backgroundColor = Constants.selectedColor
dateLabel.backgroundColor = .clear
case .left:
textColor = .white
dateLabel.backgroundColor = .primary
rightPlaceholder.backgroundColor = Constants.selectedColor
case .right:
textColor = .white
dateLabel.backgroundColor = .primary
leftPlaceholder.backgroundColor = Constants.selectedColor
case .full:
textColor = .textInverted
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .primary
case .none:
leftPlaceholder.backgroundColor = .clear
rightPlaceholder.backgroundColor = .clear
dateLabel.backgroundColor = .clear
if state.date > Date() {
textColor = .textSubtle
} else if state.dateBelongsTo == .thisMonth {
textColor = .text
} else {
textColor = .textSubtle
}
}
dateLabel.textColor = textColor
}
func position(for date: Date, startDate: Date?, endDate: Date?) -> SelectionRangePosition {
if let startDate = startDate, let endDate = endDate {
if date == startDate {
return .left
} else if date == endDate {
return .right
} else if date > startDate && date < endDate {
return .middle
}
} else if let startDate = startDate {
if date == startDate {
return .full
}
}
return .none
}
}
// MARK: - Year Header View
class CalendarYearHeaderView: JTACMonthReusableView {
static let reuseIdentifier = "CalendarYearHeaderView"
let titleLabel: UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
let stackView = UIStackView()
stackView.axis = .vertical
stackView.spacing = Constants.stackViewSpacing
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
pinSubviewToSafeArea(stackView)
stackView.addArrangedSubview(titleLabel)
titleLabel.font = .preferredFont(forTextStyle: .headline)
titleLabel.textAlignment = .center
titleLabel.textColor = Constants.titleColor
titleLabel.accessibilityTraits = .header
let weekdaysView = WeekdaysHeaderView(calendar: Calendar.current)
stackView.addArrangedSubview(weekdaysView)
stackView.setCustomSpacing(Constants.spacingAfterWeekdays, after: weekdaysView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private enum Constants {
static let stackViewSpacing: CGFloat = 16
static let spacingAfterWeekdays: CGFloat = 8
static let titleColor = UIColor(light: .gray(.shade70), dark: .textSubtle)
}
}
extension Date {
var startOfMonth: Date? {
return Calendar.current.date(from: Calendar.current.dateComponents([.year, .month], from: Calendar.current.startOfDay(for: self)))
}
var endOfMonth: Date? {
guard let startOfMonth = startOfMonth else {
return nil
}
return Calendar.current.date(byAdding: DateComponents(month: 1, day: -1), to: startOfMonth)
}
}
class WPJTACMonthView: JTACMonthView {
// Avoids content to scroll above/below the maximum/minimum size
override func setContentOffset(_ contentOffset: CGPoint, animated: Bool) {
let maxY = contentSize.height - frame.size.height
if contentOffset.y > maxY {
super.setContentOffset(CGPoint(x: contentOffset.x, y: maxY), animated: animated)
} else if contentOffset.y < 0 {
super.setContentOffset(CGPoint(x: contentOffset.x, y: 0), animated: animated)
} else {
super.setContentOffset(contentOffset, animated: animated)
}
}
}
|
gpl-2.0
|
64e8e613b2186106712e3531ed28b3e6
| 35.407407 | 152 | 0.634971 | 5.3785 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit
|
SwiftKit/ui/BQImagesPickView.swift
|
1
|
6291
|
//
// BQImagesPickView.swift
// swift-Test
//
// Created by MrBai on 2017/6/15.
// Copyright © 2017年 MrBai. All rights reserved.
//
import UIKit
enum ImagesPickType {
case one
case more
}
protocol ImagesPick {
func pickImage(img: UIImage)
func deleteImage(indexArr:[Int])
func pickMoreImage(imgs:[UIImage])
}
extension ImagesPick {
func pickImage(img: UIImage) {}
func deleteImage(indexArr:[Int]){}
func pickMoreImage(imgs:[UIImage]){}
}
class BQImagesPickView: UIView {
//MARK: - ***** Ivars *****
/// when addType is one can be used
var clipType: ClipSizeType = .none
var pickDelegate: ImagesPick?
var imageArr: [UIImage] {
get {
var imgs:[UIImage] = []
for imgView in self.imgViewArr {
imgs.append(imgView.image!)
}
return imgs
}
}
var spacing: CGFloat = 10 {
didSet {
self.adjsutSubView()
}
}
private var lineNum: Int = 0
private var addType: ImagesPickType = .one
private var imgWidth: CGFloat = 0
private var imgHeight: CGFloat = 0
private let addBtn: UIButton = UIButton(type: .custom)
private var imgViewArr: [UIImageView] = []
//MARK: - ***** Class Method *****
//MARK: - ***** initialize Method *****
convenience init(frame: CGRect, lineNum:Int = 4) {
self.init(frame: frame, addImage: nil, lineNum: lineNum)
}
convenience init(frame: CGRect, addImage:UIImage, addType: ImagesPickType, lineNum:Int = 4) {
self.init(frame: frame, addImage: addImage, lineNum: lineNum, addType: addType)
}
private init(frame: CGRect, addImage:UIImage? , lineNum:Int = 4, addType: ImagesPickType = .one) {
super.init(frame: frame)
self.lineNum = lineNum
self.addType = addType
if let image = addImage {
self.addBtn.setBackgroundImage(image, for: .normal)
}else {
self.addBtn.isHidden = true
}
self.initData()
self.initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - ***** public Method *****
func setUrls(imgs:[String]) {
self.clearImgs()
for str in imgs {
let imgView = self.creatImgView()
// imgView.setImage(urlStr: str)
}
self.adjsutSubView()
}
func setImgs(imgs:[UIImage]){
self.clearImgs()
for img in imgs {
let imgView = self.creatImgView()
imgView.image = img
}
self.adjsutSubView()
}
func clearImgs() {
for view in self.imgViewArr {
view.removeFromSuperview()
}
self.imgViewArr.removeAll()
self.adjsutSubView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
}
//MARK: - ***** private Method *****
private func initData() {
self.imgWidth = (self.bounds.width - self.spacing) / CGFloat(self.lineNum) - self.spacing
self.imgHeight = self.imgWidth
if self.addType == .one {
switch self.clipType {
case .twoScaleOne:
self.imgHeight = self.imgWidth * 0.5
case .threeScaleTwo:
self.imgHeight = self.imgHeight * 2 / 3
default:
break
}
}
}
private func initUI() {
self.backgroundColor = UIColor.white
self.addBtn.addTarget(self, action: #selector(addBtnAction), for: .touchUpInside)
self.addSubview(self.addBtn)
self.adjsutSubView()
}
private func adjsutSubView() {
let space = self.spacing
var frame: CGRect = CGRect.zero
for index in 0 ..< self.imgViewArr.count {
frame = CGRect(x: space + (self.imgWidth + space) * CGFloat(index % self.lineNum), y: space + CGFloat(index / self.lineNum) * (self.imgHeight + space), width: self.imgWidth, height: self.imgHeight)
self.imgViewArr[index].frame = frame
}
if !self.addBtn.isHidden {
let index = self.imgViewArr.count
frame = CGRect(x: space + (self.imgWidth + space) * CGFloat(index % self.lineNum), y: space + CGFloat(index / self.lineNum) * (self.imgHeight + space), width: self.imgWidth, height: self.imgHeight)
self.addBtn.frame = frame
}
self.sizeH = frame.maxY + space
}
private func creatImgView() -> UIImageView {
let imgView = UIImageView()
imgView.addTapGes {[weak self] (imgV) in
self?.tapImgAction(imgView: imgV as! UIImageView)
}
self.imgViewArr.append(imgView)
self.addSubview(imgView)
return imgView
}
private func tapImgAction(imgView:UIImageView) {
let index = self.imgViewArr.index(of: imgView)!
if self.addBtn.isHidden {
BQPhotoBrowserView.show(datas: self.imgViewArr, current: index)
}else {
BQShowImgsView.show(imgs: self.imgViewArr,current: index, deleteHandle: {[weak self] (deletArr) in
let arr = deletArr.sorted(by: {$0 > $1})
for index in arr {
self?.imgViewArr[index].removeFromSuperview()
self?.imgViewArr.remove(at: index)
}
self?.adjsutSubView()
if let delegate = self?.pickDelegate {
delegate.deleteImage(indexArr: arr)
}
})
}
}
//MARK: - ***** LoadData Method *****
//MARK: - ***** respond event Method *****
@objc private func addBtnAction() {
if self.addType == .one {
BQImagePicker.showPicker(type: self.clipType, handle: {[weak self] (image) in
if let delegate = self?.pickDelegate {
delegate.pickImage(img: image)
}
let imgView = self?.creatImgView()
imgView?.image = image
self?.adjsutSubView()
})
}else {
print("多选")
}
}
//MARK: - ***** Protocol *****
//MARK: - ***** create Method *****
}
|
apache-2.0
|
c1f39c9d0925e940807fea8cb08bb20e
| 31.225641 | 209 | 0.557447 | 4.200535 | false | false | false | false |
bignerdranch/Deferred
|
Tests/DeferredTests/FutureTests.swift
|
1
|
3774
|
//
// FutureTests.swift
// DeferredTests
//
// Created by Zachary Waldowski on 9/24/16.
// Copyright © 2016-2018 Big Nerd Ranch. Licensed under MIT.
//
import XCTest
import Dispatch
import Deferred
class FutureTests: XCTestCase {
static let allTests: [(String, (FutureTests) -> () throws -> Void)] = [
("testAnd", testAnd),
("testAllFilled", testAllFilled),
("testAllFilledEmptyCollection", testAllFilledEmptyCollection),
("testFirstFilled", testFirstFilled)
]
func testAnd() {
let toBeCombined1 = Deferred<Int>()
let toBeCombined2 = Deferred<String>()
let combined = toBeCombined1.and(toBeCombined2)
let expect = expectation(description: "paired deferred should be filled")
combined.upon(.main) { (value) in
XCTAssertEqual(value.0, 1)
XCTAssertEqual(value.1, "foo")
expect.fulfill()
}
XCTAssertFalse(combined.isFilled)
toBeCombined1.fill(with: 1)
XCTAssertFalse(combined.isFilled)
toBeCombined2.fill(with: "foo")
wait(for: [ expect ], timeout: shortTimeout)
}
func testAllFilled() {
var toBeCombined = [Deferred<Int>]()
for _ in 0 ..< 10 {
toBeCombined.append(Deferred())
}
let combined = toBeCombined.allFilled()
let outerExpect = expectation(description: "all results filled in")
let innerExpect = expectation(description: "paired deferred should be filled")
// skip first
for (value, toFill) in toBeCombined.enumerated().dropFirst() {
toFill.fill(with: value)
}
self.afterShortDelay {
XCTAssertFalse(combined.isFilled) // unfilled because d[0] is still unfilled
toBeCombined[0].fill(with: 0)
self.afterShortDelay {
XCTAssertTrue(combined.value == [Int](0 ..< toBeCombined.count))
innerExpect.fulfill()
}
outerExpect.fulfill()
}
wait(for: [ outerExpect, innerExpect ], timeout: shortTimeout)
}
func testAllFilledEmptyCollection() {
let deferred = EmptyCollection<Deferred<Int>>().allFilled()
XCTAssert(deferred.isFilled)
}
func testFirstFilled() {
let allDeferreds = (0 ..< 10).map { _ in Deferred<Int>() }
let winner = allDeferreds.firstFilled()
allDeferreds[3].fill(with: 3)
let outerExpect = expectation(description: "any is filled")
let innerExpect = expectation(description: "any is not changed")
self.afterShortDelay {
XCTAssertEqual(winner.value, 3)
allDeferreds[4].fill(with: 4)
self.afterShortDelay {
XCTAssertEqual(winner.value, 3)
innerExpect.fulfill()
}
outerExpect.fulfill()
}
wait(for: [ outerExpect, innerExpect ], timeout: shortTimeout)
}
func testEveryMapTransformerIsCalledMultipleTimes() {
let deferred = Deferred(filledWith: 1)
let everyExpectation = XCTestExpectation(description: "every is called each time the result is needed")
everyExpectation.expectedFulfillmentCount = 4
let doubled = deferred.every { (value) -> Int in
everyExpectation.fulfill()
return value * 2
}
let uponExpection = XCTestExpectation(description: "upon is called when filled")
uponExpection.expectedFulfillmentCount = 4
for _ in 0 ..< 4 {
doubled.upon { (value) in
XCTAssertEqual(value, 2)
uponExpection.fulfill()
}
}
wait(for: [ everyExpectation, uponExpection ], timeout: shortTimeout)
}
}
|
mit
|
f14997d9c74f0ab5270a5a3e62bb8422
| 29.184 | 111 | 0.604824 | 4.751889 | false | true | false | false |
jasperblues/GitHubFollowMeBack
|
GitHubFollowMeBack.swift
|
1
|
3006
|
#!/usr/bin/swift
import Foundation
import Foundation
open class GitHubSocialChecker : NSObject {
fileprivate var userName : String!
public init(userName : String!) {
self.userName = userName
super.init()
}
open func check() {
let followers = self.collectFromEndpoint("followers")
let following = self.collectFromEndpoint("following")
print("<========================================================")
print(NSString(format: "Follower stats for: %@", self.userName))
print("<========================================================")
print("Following, but not followed by:");
self.withCollection(following, reportMissingFrom: followers)
print("<end of report>")
print("");
print("Followed by, but not following:");
print("<========================================================")
self.withCollection(followers, reportMissingFrom: following)
print("<end of report>")
}
fileprivate func collectFromEndpoint(_ endpoint : String) -> Array<String> {
var collection : Array<String> = []
print(NSString(format: "Loading %@ . . . ", endpoint))
var page = 1
while (true) {
let urlString : String! = NSString(format: "https://api.github.com/users/%@/%@?per_page=100&page=%i",
self.userName, endpoint, page) as String
let url = URL(string: urlString)!
let data = try! Data(contentsOf: url)
do {
let results = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Array<Dictionary<String, AnyObject>>
if (results.count == 0) {
break;
}
for dictionary : Dictionary in results {
let login = dictionary["login"] as! String
collection.append(login)
}
page += 1
} catch let error as NSError {
print(error.localizedDescription)
exit(1)
}
}
print(NSString(format: "Counted %lu %@", collection.count, endpoint))
return collection
}
fileprivate func withCollection(_ collection : Array<String>, reportMissingFrom other : Array<String>) -> Void {
for userName in collection {
if other.filter({$0 == userName}).count == 0 {
print(userName)
}
}
}
}
let arguments : Array<String> = CommandLine.arguments;
if (arguments.count != 2) {
print("Usage: ./GitHubFollowMeBack.swift <userName>")
}
var checker = GitHubSocialChecker(userName: arguments[1])
checker.check()
|
apache-2.0
|
3e6aa0992b6b08beff5e3167a4e0a878
| 30.3125 | 176 | 0.496673 | 5.445652 | false | false | false | false |
younata/RSSClient
|
Tethys/Feeds/Viewing Feeds/RefreshControl.swift
|
1
|
7351
|
import UIKit
import CBGPromise
public protocol Refresher {
func refresh()
}
public protocol LowPowerDiviner {
var isLowPowerModeEnabled: Bool { get }
}
extension ProcessInfo: LowPowerDiviner {}
public enum RefreshControlStyle: Int, CustomStringConvertible {
case spinner = 0
case breakout = 1
public var description: String {
switch self {
case .spinner:
return NSLocalizedString("RefreshControlStyle_Spinner", comment: "")
case .breakout:
return NSLocalizedString("RefreshControlStyle_Breakout", comment: "")
}
}
public var accessibilityLabel: String {
switch self {
case .spinner:
return NSLocalizedString("RefreshControlStyle_Spinner_Accessibility", comment: "")
case .breakout:
return NSLocalizedString("RefreshControlStyle_Breakout_Accessibility", comment: "")
}
}
}
public final class RefreshControl: NSObject {
private let notificationCenter: NotificationCenter
private let scrollView: UIScrollView
private let mainQueue: OperationQueue
private let settingsRepository: SettingsRepository
fileprivate let refresher: Refresher
fileprivate let lowPowerDiviner: LowPowerDiviner
fileprivate var refreshControlStyle: RefreshControlStyle?
public private(set) var breakoutView: BreakOutToRefreshView?
public let spinner = UIRefreshControl()
public init(notificationCenter: NotificationCenter,
scrollView: UIScrollView,
mainQueue: OperationQueue,
settingsRepository: SettingsRepository,
refresher: Refresher,
lowPowerDiviner: LowPowerDiviner) {
self.notificationCenter = notificationCenter
self.scrollView = scrollView
self.mainQueue = mainQueue
self.settingsRepository = settingsRepository
self.refresher = refresher
self.lowPowerDiviner = lowPowerDiviner
super.init()
notificationCenter.addObserver(
self,
selector: #selector(RefreshControl.powerStateDidChange),
name: NSNotification.Name.NSProcessInfoPowerStateDidChange,
object: nil
)
self.spinner.addTarget(self, action: #selector(RefreshControl.beginRefresh), for: .valueChanged)
settingsRepository.addSubscriber(self)
self.powerStateDidChange()
}
deinit {
self.notificationCenter.removeObserver(self)
}
public func beginRefreshing(force: Bool = false) {
guard let refreshControlStyle = self.refreshControlStyle, !self.isRefreshing || force else { return }
switch refreshControlStyle {
case .breakout:
self.breakoutView?.beginRefreshing()
case .spinner:
self.spinner.beginRefreshing()
}
}
public func endRefreshing(force: Bool = false) {
guard self.isRefreshing || force else { return }
self.breakoutView?.endRefreshing()
self.spinner.endRefreshing()
}
public var isRefreshing: Bool {
return self.breakoutView?.isRefreshing == true ||
self.spinner.isRefreshing
}
public func updateSize(_ size: CGSize) {
guard let originalFrame = self.breakoutView?.frame else { return }
self.breakoutView?.frame = CGRect(x: originalFrame.origin.x, y: originalFrame.origin.y,
width: size.width, height: originalFrame.size.height)
self.breakoutView?.layoutSubviews()
}
public func updateTheme() {
guard let breakoutView = self.breakoutView else { return }
self.applyTheme(to: breakoutView)
}
@objc private func powerStateDidChange() {
self.mainQueue.addOperation {
let forcedStyle: RefreshControlStyle?
if self.lowPowerDiviner.isLowPowerModeEnabled {
forcedStyle = .spinner
} else {
forcedStyle = nil
}
self.changeRefreshStyle(forcedStyle: forcedStyle)
}
}
fileprivate func changeRefreshStyle(forcedStyle: RefreshControlStyle? = nil) {
let style = forcedStyle ?? self.settingsRepository.refreshControl
guard style != self.refreshControlStyle else { return }
switch style {
case .spinner:
self.switchInSpinner()
case .breakout:
self.switchInBreakoutToRefresh()
}
}
private func switchInBreakoutToRefresh() {
let breakoutView = self.newBreakoutControl(scrollView: self.scrollView)
self.breakoutView = breakoutView
self.scrollView.addSubview(breakoutView)
self.scrollView.refreshControl = nil
if self.isRefreshing {
self.endRefreshing(force: true)
breakoutView.beginRefreshing()
}
self.refreshControlStyle = .breakout
}
private func switchInSpinner() {
self.breakoutView?.removeFromSuperview()
self.breakoutView = nil
self.scrollView.refreshControl = self.spinner
if self.isRefreshing {
self.endRefreshing(force: true)
self.spinner.beginRefreshing()
}
self.refreshControlStyle = .spinner
}
@objc private func beginRefresh() {
self.refresher.refresh()
}
private func newBreakoutControl(scrollView: UIScrollView) -> BreakOutToRefreshView {
let refreshView = BreakOutToRefreshView(scrollView: scrollView)
refreshView.refreshDelegate = self
refreshView.paddleColor = UIColor.blue
refreshView.blockColors = [UIColor.darkGray, UIColor.gray, UIColor.lightGray]
self.applyTheme(to: refreshView)
return refreshView
}
private func applyTheme(to view: BreakOutToRefreshView) {
view.scenebackgroundColor = Theme.backgroundColor
view.textColor = Theme.textColor
view.ballColor = Theme.highlightColor
}
}
extension RefreshControl: SettingsRepositorySubscriber {
public func didChangeSetting(_ settingsRepository: SettingsRepository) {
self.powerStateDidChange()
}
}
extension RefreshControl: UIScrollViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
guard self.refreshControlStyle == .breakout else { return }
self.breakoutView?.scrollViewWillBeginDragging(scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard self.refreshControlStyle == .breakout else { return }
self.breakoutView?.scrollViewWillEndDragging(scrollView,
withVelocity: velocity,
targetContentOffset: targetContentOffset)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard self.refreshControlStyle == .breakout else { return }
self.breakoutView?.scrollViewDidScroll(scrollView)
}
}
extension RefreshControl: BreakOutToRefreshDelegate {
public func refreshViewDidRefresh(_ refreshView: BreakOutToRefreshView) {
self.refresher.refresh()
}
}
|
mit
|
b9ebae52746ffd9ee86e248c906b021e
| 32.875576 | 109 | 0.657598 | 5.401176 | false | false | false | false |
TonnyTao/HowSwift
|
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Skip.swift
|
8
|
5014
|
//
// Skip.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter count: The number of elements to skip before returning the remaining elements.
- returns: An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
public func skip(_ count: Int)
-> Observable<Element> {
SkipCount(source: self.asObservable(), count: count)
}
}
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<Element> {
SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// count version
final private class SkipCountSink<Observer: ObserverType>: Sink<Observer>, ObserverType {
typealias Element = Observer.Element
typealias Parent = SkipCount<Element>
let parent: Parent
var remaining: Int
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
self.remaining = parent.count
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if self.remaining <= 0 {
self.forwardOn(.next(value))
}
else {
self.remaining -= 1
}
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self.forwardOn(event)
self.dispose()
}
}
}
final private class SkipCount<Element>: Producer<Element> {
let source: Observable<Element>
let count: Int
init(source: Observable<Element>, count: Int) {
self.source = source
self.count = count
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = self.source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
// time version
final private class SkipTimeSink<Element, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == Element {
typealias Parent = SkipTime<Element>
let parent: Parent
// state
var open = false
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if self.open {
self.forwardOn(.next(value))
}
case .error:
self.forwardOn(event)
self.dispose()
case .completed:
self.forwardOn(event)
self.dispose()
}
}
func tick() {
self.open = true
}
func run() -> Disposable {
let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in
self.tick()
return Disposables.create()
}
let disposeSubscription = self.parent.source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
final private class SkipTime<Element>: Producer<Element> {
let source: Observable<Element>
let duration: RxTimeInterval
let scheduler: SchedulerType
init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) {
self.source = source
self.scheduler = scheduler
self.duration = duration
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
|
mit
|
ab1a16b709621e2877759ef5bd43fc32
| 30.727848 | 171 | 0.637941 | 4.815562 | false | false | false | false |
mohamede1945/quran-ios
|
UIKitExtension/CircleView.swift
|
2
|
2349
|
//
// CircleView.swift
// Quran
//
// Created by Mohamed Afifi on 4/22/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UIKit
open class CircleView: UIView {
@IBInspectable open var progress: CGFloat = 0.8 {
didSet {
updateLayers()
}
}
@IBInspectable open var emptyColor: UIColor = UIColor.red {
didSet {
updateLayers()
}
}
@IBInspectable open var fillColor: UIColor = UIColor.green {
didSet {
updateLayers()
}
}
private let emptyCircle = CAShapeLayer()
private let fillCircle = CAShapeLayer()
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
public override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
private func setUp() {
layer.addSublayer(emptyCircle)
layer.addSublayer(fillCircle)
fillCircle.fillColor = nil
fillCircle.transform = CATransform3DMakeRotation(-.pi / 2, 0, 0, 1)
}
open override func layoutSubviews() {
super.layoutSubviews()
updateLayers()
}
private func updateLayers() {
emptyCircle.frame = bounds
fillCircle.frame = bounds
// emtpy circle
// var circleBounds = bounds
emptyCircle.path = UIBezierPath(ovalIn: bounds).cgPath
emptyCircle.fillColor = emptyColor.cgColor
// fill circle
fillCircle.path = UIBezierPath(ovalIn: bounds.insetBy(dx: bounds.width / 4, dy: bounds.height / 4)).cgPath
fillCircle.strokeColor = fillColor.cgColor
fillCircle.lineWidth = bounds.width / 2
CALayer.withoutAnimation {
fillCircle.strokeEnd = progress
}
}
}
|
gpl-3.0
|
8785b3e02cb8ad73a061427b295078bd
| 26.313953 | 114 | 0.634738 | 4.570039 | false | false | false | false |
jjatie/Charts
|
Source/Charts/Formatters/IndexAxisValueFormatter.swift
|
1
|
931
|
//
// IndexAxisValueFormatter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
/// This formatter is used for passing an array of x-axis labels, on whole x steps.
open class IndexAxisValueFormatter: AxisValueFormatter {
public var values = [String]()
public init() {}
public init(values: [String]) {
self.values = values
}
public static func with(values: [String]) -> IndexAxisValueFormatter? {
return IndexAxisValueFormatter(values: values)
}
open func stringForValue(_ value: Double,
axis _: AxisBase?) -> String
{
let index = Int(value.rounded())
guard values.indices.contains(index), index == Int(value) else { return "" }
return values[index]
}
}
|
apache-2.0
|
ed0079d5fd9d2cd1e3af9591d6b9c960
| 25.6 | 84 | 0.644468 | 4.350467 | false | false | false | false |
ps2/rileylink_ios
|
MinimedKit/Messages/MySentryAlertMessageBody.swift
|
1
|
1718
|
//
// MySentryAlertMessageBody.swift
// Naterade
//
// Created by Nathan Racklyeft on 9/6/15.
// Copyright © 2015 Nathan Racklyeft. All rights reserved.
//
import Foundation
/**
Describes an alert message sent immediately from the pump to any paired MySentry devices
See: [MinimedRF Class](https://github.com/ps2/minimed_rf/blob/master/lib/minimed_rf/messages/alert.rb)
```
a2 594040 01 7c 65 0727070f0906 0175 4c
```
*/
public struct MySentryAlertMessageBody: DecodableMessageBody, DictionaryRepresentable {
public static let length = 10
public let alertType: MySentryAlertType?
public let alertDate: Date
private let rxData: Data
public init?(rxData: Data) {
guard rxData.count == type(of: self).length, let
alertDate = DateComponents(mySentryBytes: rxData.subdata(in: 2..<8)).date
else {
return nil
}
self.rxData = rxData
alertType = MySentryAlertType(rawValue: rxData[1])
self.alertDate = alertDate
}
public var txData: Data {
return rxData
}
public var dictionaryRepresentation: [String: Any] {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
return [
"alertDate": dateFormatter.string(from: alertDate),
"alertType": (alertType != nil ? String(describing: alertType!) : rxData.subdata(in: 1..<2).hexadecimalString),
"byte89": rxData.subdata(in: 8..<10).hexadecimalString
]
}
public var description: String {
return "MySentryAlert(\(String(describing: alertType)), \(alertDate))"
}
}
|
mit
|
05d008079e7ff0dfe8191387aa6a3000
| 26.253968 | 123 | 0.658125 | 4.002331 | false | false | false | false |
QuarkX/Quark
|
Sources/Quark/Core/Stream/Drain.swift
|
1
|
1953
|
public final class Drain : DataRepresentable, Stream {
var buffer: Data
public var closed = false
public var data: Data {
return buffer
}
public init(stream: InputStream, deadline: Double = .never) {
var inputBuffer = Data(count: 2048)
var outputBuffer = Data()
if stream.closed {
self.closed = true
}
while !stream.closed {
if let bytesRead = try? stream.read(into: &inputBuffer, deadline: deadline) {
if bytesRead == 0 {
break
}
inputBuffer.withUnsafeBytes {
outputBuffer.append($0, count: bytesRead)
}
} else {
break
}
}
self.buffer = outputBuffer
}
public init(buffer: Data = Data()) {
self.buffer = buffer
}
public convenience init(buffer: DataRepresentable) {
self.init(buffer: buffer.data)
}
public func close() {
closed = true
}
public func read(into targetBuffer: inout Data, length: Int, deadline: Double = .never) throws -> Int {
if closed && buffer.count == 0 {
throw StreamError.closedStream(data: Data())
}
if buffer.count == 0 {
return 0
}
if length >= buffer.count {
targetBuffer.replaceSubrange(0 ..< buffer.count, with: buffer)
let read = buffer.count
buffer = Data()
return read
}
targetBuffer.replaceSubrange(0 ..< length, with: buffer[0 ..< length])
buffer.removeFirst(length)
return length
}
public func write(_ data: Data, length: Int, deadline: Double = .never) throws -> Int {
data.withUnsafeBytes {
buffer.append($0, count: length)
}
return length
}
public func flush(deadline: Double = .never) throws {}
}
|
mit
|
294efd239ca898fdaf31b25c2659e061
| 24.697368 | 107 | 0.533026 | 4.810345 | false | false | false | false |
asurinsaka/swift_examples_2.1
|
ByteArray/ByteArray/ViewController.swift
|
1
|
1351
|
//
// ViewController.swift
// ByteArray
//
// Created by larryhou on 5/20/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
let bytes = ByteArray()
bytes.endian = .BIG_ENDIAN
bytes.writeBoolean(true)
bytes.writeUTF("侯坤峰")
bytes.writeDouble(M_PI)
bytes.writeUTF("侯坤峰")
bytes.writeUTF("侯坤峰")
bytes.writeUTF("侯坤峰")
bytes.writeUTF("侯坤峰")
print(bytes.position)
bytes.position = 0
print(bytes.readBoolean())
print(bytes.readUTF())
print(bytes.readDouble())
let data = ByteArray()
data.endian = bytes.endian
// bytes.position = 1
// bytes.readBytes(data, offset: 0, length: 11)
data.writeBytes(bytes, offset: 1, length: 11)
print(data.length)
data.position = 0
print(data.readUTF())
print(ByteArray.hexe(bytes, range: NSRange(location: 0, length: bytes.length)))
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
6bdbea8cf283608fd9ea31932c3c82fd
| 22.175439 | 87 | 0.566238 | 4.141066 | false | false | false | false |
fs/FSHelper
|
FSHelpersTests/Tests/Extensions/FSE+NSLayoutConstraint.swift
|
1
|
1296
|
//
// FSE+NSLayoutConstraint.swift
// FSHelpersTests
//
// Created by Timur Shafigullin on 05/01/2019.
// Copyright © 2019 FlatStack. All rights reserved.
//
import XCTest
@testable import FSHelpers
class FSE_NSLayoutConstraintTests: XCTestCase {
func testGetPreciseConstant() {
// arrange
let constant: CGFloat = 52
let constraint = NSLayoutConstraint(item: UIView(), attribute: .top, relatedBy: .equal, toItem: UIView(), attribute: .bottom, multiplier: 1, constant: constant)
let expectedPreciseConstant = Int(constant * UIScreen.main.scale)
// act
let preciseConstant = constraint.fs_preciseConstant
// assert
XCTAssertEqual(preciseConstant, expectedPreciseConstant)
}
func testSetPreciseConstant() {
// arrange
let constant = 52
let constraint = NSLayoutConstraint(item: UIView(), attribute: .top, relatedBy: .equal, toItem: UIView(), attribute: .bottom, multiplier: 1, constant: CGFloat(constant))
let expectedConstant = CGFloat(constant) / UIScreen.main.scale
// act
constraint.fs_preciseConstant = 52
// assert
XCTAssertEqual(constraint.constant, expectedConstant)
}
}
|
mit
|
e36715a2eda2759176f52f30e305beaf
| 29.833333 | 177 | 0.644788 | 4.796296 | false | true | false | false |
mohitathwani/swift-corelibs-foundation
|
Foundation/NSKeyedArchiver.swift
|
1
|
38282
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/// Archives created using the class method `archivedData(withRootObject:)` use this key
/// for the root object in the hierarchy of encoded objects. The `NSKeyedUnarchiver` class method
/// `unarchiveObject(with:)` looks for this root key as well.
public let NSKeyedArchiveRootObjectKey: String = "root"
internal let NSKeyedArchiveNullObjectReference = _NSKeyedArchiverUID(value: 0)
internal let NSKeyedArchiveNullObjectReferenceName: String = "$null"
internal let NSKeyedArchivePlistVersion = 100000
internal let NSKeyedArchiverSystemVersion : UInt32 = 2000
internal func escapeArchiverKey(_ key: String) -> String {
if key.hasPrefix("$") {
return "$" + key
} else {
return key
}
}
internal let NSPropertyListClasses : [AnyClass] = [
NSArray.self,
NSDictionary.self,
NSString.self,
NSData.self,
NSDate.self,
NSNumber.self
]
/// `NSKeyedArchiver`, a concrete subclass of `NSCoder`, provides a way to encode objects
/// (and scalar values) into an architecture-independent format that can be stored in a file.
/// When you archive a set of objects, the class information and instance variables for each object
/// are written to the archive. `NSKeyedArchiver`’s companion class, `NSKeyedUnarchiver`,
/// decodes the data in an archive and creates a set of objects equivalent to the original set.
///
/// A keyed archive differs from a non-keyed archive in that all the objects and values
/// encoded into the archive are given names, or keys. When decoding a non-keyed archive,
/// values have to be decoded in the same order in which they were encoded.
/// When decoding a keyed archive, because values are requested by name, values can be decoded
/// out of sequence or not at all. Keyed archives, therefore, provide better support
/// for forward and backward compatibility.
///
/// The keys given to encoded values must be unique only within the scope of the current
/// object being encoded. A keyed archive is hierarchical, so the keys used by object A
/// to encode its instance variables do not conflict with the keys used by object B,
/// even if A and B are instances of the same class. Within a single object,
/// however, the keys used by a subclass can conflict with keys used in its superclasses.
///
/// An `NSKeyedArchiver` object can write the archive data to a file or to a
/// mutable-data object (an instance of `NSMutableData`) that you provide.
open class NSKeyedArchiver : NSCoder {
struct ArchiverFlags : OptionSet {
let rawValue : UInt
init(rawValue : UInt) {
self.rawValue = rawValue
}
static let none = ArchiverFlags(rawValue: 0)
static let finishedEncoding = ArchiverFlags(rawValue : 1)
static let requiresSecureCoding = ArchiverFlags(rawValue: 2)
}
private class EncodingContext {
// the object container that is being encoded
var dict = Dictionary<String, Any>()
// the index used for non-keyed objects (encodeObject: vs encodeObject:forKey:)
var genericKey : UInt = 0
}
private static var _classNameMap = Dictionary<String, String>()
private static var _classNameMapLock = NSLock()
private var _stream : AnyObject
private var _flags = ArchiverFlags(rawValue: 0)
private var _containers : Array<EncodingContext> = [EncodingContext()]
private var _objects : Array<Any> = [NSKeyedArchiveNullObjectReferenceName]
private var _objRefMap : Dictionary<AnyHashable, UInt32> = [:]
private var _replacementMap : Dictionary<AnyHashable, Any> = [:]
private var _classNameMap : Dictionary<String, String> = [:]
private var _classes : Dictionary<String, _NSKeyedArchiverUID> = [:]
private var _cache : Array<_NSKeyedArchiverUID> = []
/// The archiver’s delegate.
open weak var delegate: NSKeyedArchiverDelegate?
/// The format in which the receiver encodes its data.
///
/// The available formats are `xml` and `binary`.
open var outputFormat = PropertyListSerialization.PropertyListFormat.binary {
willSet {
if outputFormat != PropertyListSerialization.PropertyListFormat.xml &&
outputFormat != PropertyListSerialization.PropertyListFormat.binary {
NSUnimplemented()
}
}
}
/// Returns an `NSData` object containing the encoded form of the object graph
/// whose root object is given.
///
/// - Parameter rootObject: The root of the object graph to archive.
/// - Returns: An `NSData` object containing the encoded form of the object graph
/// whose root object is rootObject. The format of the archive is
/// `NSPropertyListBinaryFormat_v1_0`.
open class func archivedData(withRootObject rootObject: Any) -> Data {
let data = NSMutableData()
let keyedArchiver = NSKeyedArchiver(forWritingWith: data)
keyedArchiver.encode(rootObject, forKey: NSKeyedArchiveRootObjectKey)
keyedArchiver.finishEncoding()
return data._swiftObject
}
/// Archives an object graph rooted at a given object by encoding it into a data object
/// then atomically writes the resulting data object to a file at a given path,
/// and returns a Boolean value that indicates whether the operation was successful.
///
/// - Parameters:
/// - rootObject: The root of the object graph to archive.
/// - path: The path of the file in which to write the archive.
/// - Returns: `true` if the operation was successful, otherwise `false`.
open class func archiveRootObject(_ rootObject: Any, toFile path: String) -> Bool {
var fd : Int32 = -1
var auxFilePath : String
var finishedEncoding : Bool = false
do {
(fd, auxFilePath) = try _NSCreateTemporaryFile(path)
} catch _ {
return false
}
defer {
do {
if finishedEncoding {
try _NSCleanupTemporaryFile(auxFilePath, path)
} else {
try FileManager.default.removeItem(atPath: auxFilePath)
}
} catch _ {
}
}
let writeStream = _CFWriteStreamCreateFromFileDescriptor(kCFAllocatorSystemDefault, fd)!
if !CFWriteStreamOpen(writeStream) {
return false
}
defer { CFWriteStreamClose(writeStream) }
let keyedArchiver = NSKeyedArchiver(output: writeStream)
keyedArchiver.encode(rootObject, forKey: NSKeyedArchiveRootObjectKey)
keyedArchiver.finishEncoding()
finishedEncoding = keyedArchiver._flags.contains(ArchiverFlags.finishedEncoding)
return finishedEncoding
}
public override convenience init() {
self.init(forWritingWith: NSMutableData())
}
private init(output: AnyObject) {
self._stream = output
super.init()
}
/// Returns the archiver, initialized for encoding an archive into a given a mutable-data object.
///
/// When you finish encoding data, you must invoke `finishEncoding()` at which point data
/// is filled. The format of the archive is `NSPropertyListBinaryFormat_v1_0`.
///
/// - Parameter data: The mutable-data object into which the archive is written.
public convenience init(forWritingWith data: NSMutableData) {
self.init(output: data)
}
private func _writeXMLData(_ plist : NSDictionary) -> Bool {
var success = false
if let data = self._stream as? NSMutableData {
let xml : CFData?
xml = _CFPropertyListCreateXMLDataWithExtras(kCFAllocatorSystemDefault, plist)
if let unwrappedXml = xml {
data.append(unwrappedXml._swiftObject)
success = true
}
} else {
success = CFPropertyListWrite(plist, self._stream as! CFWriteStream,
kCFPropertyListXMLFormat_v1_0, 0, nil) > 0
}
return success
}
private func _writeBinaryData(_ plist : NSDictionary) -> Bool {
return __CFBinaryPlistWriteToStream(plist, self._stream) > 0
}
/// Returns the encoded data for the archiver.
///
/// If encoding has not yet finished, invoking this property calls `finishEncoding()`
/// and returns the data. If you initialized the keyed archiver with a specific
/// mutable data instance, then that data is returned by the property after
/// `finishEncoding()` is called.
open var encodedData: Data {
if !_flags.contains(.finishedEncoding) {
finishEncoding()
}
return (_stream as! NSData)._swiftObject
}
/// Instructs the archiver to construct the final data stream.
///
/// No more values can be encoded after this method is called. You must call this method when finished.
open func finishEncoding() {
if _flags.contains(ArchiverFlags.finishedEncoding) {
return
}
var plist = Dictionary<String, Any>()
var success : Bool
plist["$archiver"] = NSStringFromClass(type(of: self))
plist["$version"] = NSKeyedArchivePlistVersion
plist["$objects"] = self._objects
plist["$top"] = self._containers[0].dict
if let unwrappedDelegate = self.delegate {
unwrappedDelegate.archiverWillFinish(self)
}
let nsPlist = plist._bridgeToObjectiveC()
if self.outputFormat == PropertyListSerialization.PropertyListFormat.xml {
success = _writeXMLData(nsPlist)
} else {
success = _writeBinaryData(nsPlist)
}
if let unwrappedDelegate = self.delegate {
unwrappedDelegate.archiverDidFinish(self)
}
if success {
let _ = self._flags.insert(ArchiverFlags.finishedEncoding)
}
}
/// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given
/// class are encoded with a given class name instead of their real class names.
///
/// When encoding, the class’s translation mapping is used only if no translation
/// is found first in an instance’s separate translation map.
///
/// - Parameters:
/// - codedName: The name of the class that `NSKeyedArchiver` uses in place of `cls`.
/// - cls: The class for which to set up a translation mapping.
open class func setClassName(_ codedName: String?, for cls: AnyClass) {
let clsName = String(describing: type(of: cls))
_classNameMapLock.synchronized {
_classNameMap[clsName] = codedName
}
}
/// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given
/// class are encoded with a given class name instead of their real class names.
///
/// When encoding, the receiver’s translation map overrides any translation
/// that may also be present in the class’s map.
///
/// - Parameters:
/// - codedName: The name of the class that the archiver uses in place of `cls`.
/// - cls: The class for which to set up a translation mapping.
open func setClassName(_ codedName: String?, for cls: AnyClass) {
let clsName = String(describing: type(of: cls))
_classNameMap[clsName] = codedName
}
open override var systemVersion: UInt32 {
return NSKeyedArchiverSystemVersion
}
open override var allowsKeyedCoding: Bool {
return true
}
private func _validateStillEncoding() -> Bool {
if self._flags.contains(ArchiverFlags.finishedEncoding) {
fatalError("Encoder already finished")
}
return true
}
private class func _supportsSecureCoding(_ objv : Any?) -> Bool {
var supportsSecureCoding : Bool = false
if let secureCodable = objv as? NSSecureCoding {
supportsSecureCoding = type(of: secureCodable).supportsSecureCoding
}
return supportsSecureCoding
}
private func _validateObjectSupportsSecureCoding(_ objv : Any?) {
if let objv = objv, self.requiresSecureCoding &&
!NSKeyedArchiver._supportsSecureCoding(objv) {
fatalError("Secure coding required when encoding \(objv)")
}
}
private func _createObjectRefCached(_ uid : UInt32) -> _NSKeyedArchiverUID {
if uid == 0 {
return NSKeyedArchiveNullObjectReference
} else if Int(uid) <= self._cache.count {
return self._cache[Int(uid) - 1]
} else {
let objectRef = _NSKeyedArchiverUID(value: uid)
self._cache.insert(objectRef, at: Int(uid) - 1)
return objectRef
}
}
/**
Return a new object identifier, freshly allocated if need be. A placeholder null
object is associated with the reference.
*/
private func _referenceObject(_ objv: Any?, conditional: Bool = false) -> _NSKeyedArchiverUID? {
var uid : UInt32?
if objv == nil {
return NSKeyedArchiveNullObjectReference
}
let value = _SwiftValue.store(objv)!
uid = self._objRefMap[value]
if uid == nil {
if conditional {
return nil // object has not been unconditionally encoded
}
uid = UInt32(self._objects.count)
self._objRefMap[value] = uid
self._objects.insert(NSKeyedArchiveNullObjectReferenceName, at: Int(uid!))
}
return _createObjectRefCached(uid!)
}
/**
Returns true if the object has already been encoded.
*/
private func _haveVisited(_ objv: Any?) -> Bool {
if objv == nil {
return true // always have a null reference
} else {
return self._objRefMap[_SwiftValue.store(objv)] != nil
}
}
/**
Get or create an object reference, and associate the object.
*/
private func _addObject(_ objv: Any?) -> _NSKeyedArchiverUID? {
let haveVisited = _haveVisited(objv)
let objectRef = _referenceObject(objv)
if !haveVisited {
_setObject(objv!, forReference: objectRef!)
}
return objectRef
}
private func _pushEncodingContext(_ encodingContext: EncodingContext) {
self._containers.append(encodingContext)
}
private func _popEncodingContext() {
self._containers.removeLast()
}
private var _currentEncodingContext : EncodingContext {
return self._containers.last!
}
/**
Associate an encoded object or reference with a key in the current encoding context
*/
private func _setObjectInCurrentEncodingContext(_ object : Any?, forKey key: String? = nil, escape: Bool = true) {
let encodingContext = self._containers.last!
var encodingKey : String
if key != nil {
if escape {
encodingKey = escapeArchiverKey(key!)
} else {
encodingKey = key!
}
} else {
encodingKey = _nextGenericKey()
}
if encodingContext.dict[encodingKey] != nil {
NSLog("*** NSKeyedArchiver warning: replacing existing value for key '\(encodingKey)'; probable duplication of encoding keys in class hierarchy")
}
encodingContext.dict[encodingKey] = object
}
/**
The generic key is used for objects that are encoded without a key. It is a per-encoding
context monotonically increasing integer prefixed with "$".
*/
private func _nextGenericKey() -> String {
let key = "$" + String(_currentEncodingContext.genericKey)
_currentEncodingContext.genericKey += 1
return key
}
/**
Update replacement object mapping
*/
private func replaceObject(_ object: Any, withObject replacement: Any?) {
if let unwrappedDelegate = self.delegate {
unwrappedDelegate.archiver(self, willReplace: object, with: replacement)
}
self._replacementMap[_SwiftValue.store(object)] = replacement
}
/**
Returns true if the type cannot be encoded directly (i.e. is a container type)
*/
private func _isContainer(_ objv: Any?) -> Bool {
// Note that we check for class equality rather than membership, because
// their mutable subclasses are as object references
guard let obj = objv else { return false }
if obj is String { return false }
guard let nsObject = obj as? NSObject else { return true }
return !(nsObject.classForCoder === NSString.self || nsObject.classForCoder === NSNumber.self || nsObject.classForCoder === NSData.self)
}
/**
Associates an object with an existing reference
*/
private func _setObject(_ objv: Any, forReference reference : _NSKeyedArchiverUID) {
let index = Int(reference.value)
self._objects[index] = objv
}
/**
Returns a dictionary describing class metadata for a class
*/
private func _classDictionary(_ clsv: AnyClass) -> Dictionary<String, Any> {
func _classNameForClass(_ clsv: AnyClass) -> String? {
var className : String?
className = classNameForClass(clsv)
if className == nil {
className = NSKeyedArchiver.classNameForClass(clsv)
}
return className
}
var classDict : [String:Any] = [:]
let className = NSStringFromClass(clsv)
let mappedClassName = _classNameForClass(clsv)
if mappedClassName != nil && mappedClassName != className {
// If we have a mapped class name, OS X only encodes the mapped name
classDict["$classname"] = mappedClassName
} else {
var classChain : [String] = []
var classIter : AnyClass? = clsv
classDict["$classname"] = className
repeat {
classChain.append(NSStringFromClass(classIter!))
classIter = _getSuperclass(classIter!)
} while classIter != nil
classDict["$classes"] = classChain
if let ns = clsv as? NSObject.Type {
let classHints = ns.classFallbacksForKeyedArchiver()
if !classHints.isEmpty {
classDict["$classhints"] = classHints
}
}
}
return classDict
}
/**
Return an object reference for a class
Because _classDictionary() returns a dictionary by value, and every
time we bridge to NSDictionary we get a new object (the hash code is
different), we maintain a private mapping between class name and
object reference to avoid redundantly encoding class metadata
*/
private func _classReference(_ clsv: AnyClass) -> _NSKeyedArchiverUID? {
let className = NSStringFromClass(clsv)
var classRef = self._classes[className] // keyed by actual class name
if classRef == nil {
let classDict = _classDictionary(clsv)
classRef = _addObject(classDict._bridgeToObjectiveC())
if let unwrappedClassRef = classRef {
self._classes[className] = unwrappedClassRef
}
}
return classRef
}
/**
Return the object replacing another object (if any)
*/
private func _replacementObject(_ object: Any?) -> Any? {
var objectToEncode : Any? = nil // object to encode after substitution
// nil cannot be mapped
if object == nil {
return nil
}
// check replacement cache
objectToEncode = self._replacementMap[object as! AnyHashable]
if objectToEncode != nil {
return objectToEncode
}
// object replaced by NSObject.replacementObject(for:)
// if it is replaced with nil, it cannot be further replaced
if let ns = objectToEncode as? NSObject {
objectToEncode = ns.replacementObject(for: self)
if objectToEncode == nil {
replaceObject(object!, withObject: nil)
return nil
}
}
if objectToEncode == nil {
objectToEncode = object
}
// object replaced by delegate. If the delegate returns nil, nil is encoded
if let unwrappedDelegate = self.delegate {
objectToEncode = unwrappedDelegate.archiver(self, willEncode: objectToEncode!)
replaceObject(object!, withObject: objectToEncode)
}
return objectToEncode
}
/**
Internal function to encode an object. Returns the object reference.
*/
private func _encodeObject(_ objv: Any?, conditional: Bool = false) -> NSObject? {
var object : Any? = nil // object to encode after substitution
var objectRef : _NSKeyedArchiverUID? // encoded object reference
let haveVisited : Bool
let _ = _validateStillEncoding()
haveVisited = _haveVisited(objv)
object = _replacementObject(objv)
// bridge value types
if let bridgedObject = object as? _ObjectBridgeable {
object = bridgedObject._bridgeToAnyObject()
}
objectRef = _referenceObject(object, conditional: conditional)
guard let unwrappedObjectRef = objectRef else {
// we can return nil if the object is being conditionally encoded
return nil
}
_validateObjectSupportsSecureCoding(object)
if !haveVisited {
var encodedObject : Any
if _isContainer(object) {
guard let codable = object as? NSCoding else {
fatalError("Object \(object) does not conform to NSCoding")
}
let innerEncodingContext = EncodingContext()
_pushEncodingContext(innerEncodingContext)
codable.encode(with: self)
let ns = object as? NSObject
let cls : AnyClass = ns?.classForKeyedArchiver ?? type(of: object!) as! AnyClass
_setObjectInCurrentEncodingContext(_classReference(cls), forKey: "$class", escape: false)
_popEncodingContext()
encodedObject = innerEncodingContext.dict
} else {
encodedObject = object!
}
_setObject(encodedObject, forReference: unwrappedObjectRef)
}
if let unwrappedDelegate = self.delegate {
unwrappedDelegate.archiver(self, didEncode: object)
}
return unwrappedObjectRef
}
/**
Encode an object and associate it with a key in the current encoding context.
*/
private func _encodeObject(_ objv: Any?, forKey key: String?, conditional: Bool = false) {
if let objectRef = _encodeObject(objv, conditional: conditional) {
_setObjectInCurrentEncodingContext(objectRef, forKey: key, escape: key != nil)
}
}
open override func encode(_ object: Any?) {
_encodeObject(object, forKey: nil)
}
open override func encodeConditionalObject(_ object: Any?) {
_encodeObject(object, forKey: nil, conditional: true)
}
/// Encodes a given object and associates it with a given key.
///
/// - Parameters:
/// - objv: The value to encode.
/// - key: The key with which to associate `objv`.
open override func encode(_ objv: Any?, forKey key: String) {
_encodeObject(objv, forKey: key, conditional: false)
}
/// Encodes a reference to a given object and associates it with a given key
/// only if it has been unconditionally encoded elsewhere in the archive with `encode(_:forKey:)`.
///
/// - Parameters:
/// - objv: The object to encode.
/// - key: The key with which to associate the encoded value.
open override func encodeConditionalObject(_ objv: Any?, forKey key: String) {
_encodeObject(objv, forKey: key, conditional: true)
}
open override func encodePropertyList(_ aPropertyList: Any) {
if !NSPropertyListClasses.contains(where: { $0 == type(of: aPropertyList) }) {
fatalError("Cannot encode non-property list type \(type(of: aPropertyList)) as property list")
}
encode(aPropertyList)
}
open func encodePropertyList(_ aPropertyList: Any, forKey key: String) {
if !NSPropertyListClasses.contains(where: { $0 == type(of: aPropertyList) }) {
fatalError("Cannot encode non-property list type \(type(of: aPropertyList)) as property list")
}
encode(aPropertyList, forKey: key)
}
open func _encodePropertyList(_ aPropertyList: Any, forKey key: String? = nil) {
let _ = _validateStillEncoding()
_setObjectInCurrentEncodingContext(aPropertyList, forKey: key)
}
internal func _encodeValue<T: NSObject>(_ objv: T, forKey key: String? = nil) where T: NSCoding {
_encodePropertyList(objv, forKey: key)
}
private func _encodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafeRawPointer) {
switch type {
case .ID:
let objectp = addr.assumingMemoryBound(to: Any.self)
encode(objectp.pointee)
case .Class:
let classp = addr.assumingMemoryBound(to: AnyClass.self)
encode(NSStringFromClass(classp.pointee)._bridgeToObjectiveC())
case .Char:
let charp = addr.assumingMemoryBound(to: CChar.self)
_encodeValue(NSNumber(value: charp.pointee))
case .UChar:
let ucharp = addr.assumingMemoryBound(to: UInt8.self)
_encodeValue(NSNumber(value: ucharp.pointee))
case .Int, .Long:
let intp = addr.assumingMemoryBound(to: Int32.self)
_encodeValue(NSNumber(value: intp.pointee))
case .UInt, .ULong:
let uintp = addr.assumingMemoryBound(to: UInt32.self)
_encodeValue(NSNumber(value: uintp.pointee))
case .LongLong:
let longlongp = addr.assumingMemoryBound(to: Int64.self)
_encodeValue(NSNumber(value: longlongp.pointee))
case .ULongLong:
let ulonglongp = addr.assumingMemoryBound(to: UInt64.self)
_encodeValue(NSNumber(value: ulonglongp.pointee))
case .Float:
let floatp = addr.assumingMemoryBound(to: Float.self)
_encodeValue(NSNumber(value: floatp.pointee))
case .Double:
let doublep = addr.assumingMemoryBound(to: Double.self)
_encodeValue(NSNumber(value: doublep.pointee))
case .Bool:
let boolp = addr.assumingMemoryBound(to: Bool.self)
_encodeValue(NSNumber(value: boolp.pointee))
case .CharPtr:
let charpp = addr.assumingMemoryBound(to: UnsafePointer<Int8>.self)
encode(NSString(utf8String: charpp.pointee))
default:
fatalError("NSKeyedArchiver.encodeValueOfObjCType: unknown type encoding ('\(type.rawValue)')")
}
}
open override func encodeValue(ofObjCType typep: UnsafePointer<Int8>, at addr: UnsafeRawPointer) {
guard let type = _NSSimpleObjCType(UInt8(typep.pointee)) else {
let spec = String(typep.pointee)
fatalError("NSKeyedArchiver.encodeValueOfObjCType: unsupported type encoding spec '\(spec)'")
}
if type == .StructBegin {
fatalError("NSKeyedArchiver.encodeValueOfObjCType: this archiver cannot encode structs")
} else if type == .ArrayBegin {
let scanner = Scanner(string: String(cString: typep))
scanner.scanLocation = 1 // advance past ObJCType
var count : Int = 0
guard scanner.scanInteger(&count) && count > 0 else {
fatalError("NSKeyedArchiver.encodeValueOfObjCType: array count is missing or zero")
}
guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else {
fatalError("NSKeyedArchiver.encodeValueOfObjCType: array type is missing")
}
encode(_NSKeyedCoderOldStyleArray(objCType: elementType, count: count, at: addr))
} else {
return _encodeValueOfObjCType(type, at: addr)
}
}
/// Encodes a given Boolean value and associates it with a given key.
///
/// - Parameters:
/// - boolv: The value to encode.
/// - key: The key with which to associate `boolv`.
open override func encode(_ boolv: Bool, forKey key: String) {
_encodeValue(NSNumber(value: boolv), forKey: key)
}
/// Encodes a given 32-bit integer value and associates it with a given key.
///
/// - Parameters:
/// - intv: The value to encode.
/// - key: The key with which to associate `intv`.
open override func encode(_ intv: Int32, forKey key: String) {
_encodeValue(NSNumber(value: intv), forKey: key)
}
/// Encodes a given 64-bit integer value and associates it with a given key.
///
/// - Parameters:
/// - intv: The value to encode.
/// - key: The key with which to associate `intv`.
open override func encode(_ intv: Int64, forKey key: String) {
_encodeValue(NSNumber(value: intv), forKey: key)
}
/// Encodes a given float value and associates it with a given key.
///
/// - Parameters:
/// - realv: The value to encode.
/// - key: The key with which to associate `realv`.
open override func encode(_ realv: Float, forKey key: String) {
_encodeValue(NSNumber(value: realv), forKey: key)
}
/// Encodes a given double value and associates it with a given key.
///
/// - Parameters:
/// - realv: The value to encode.
/// - key: The key with which to associate `realv`.
open override func encode(_ realv: Double, forKey key: String) {
_encodeValue(NSNumber(value: realv), forKey: key)
}
/// Encodes a given integer value and associates it with a given key.
///
/// - Parameters:
/// - intv: The value to encode.
/// - key: The key with which to associate `intv`.
open override func encode(_ intv: Int, forKey key: String) {
_encodeValue(NSNumber(value: intv), forKey: key)
}
open override func encode(_ data: Data) {
// this encodes as a reference to an NSData object rather than encoding inline
encode(data._nsObject)
}
/// Encodes a given number of bytes from a given C array of bytes and associates
/// them with the a given key.
///
/// - Parameters:
/// - bytesp: A C array of bytes to encode.
/// - lenv: The number of bytes from `bytesp` to encode.
/// - key: The key with which to associate the encoded value.
open override func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) {
// this encodes the data inline
let data = NSData(bytes: bytesp, length: lenv)
_encodeValue(data, forKey: key)
}
/**
Helper API for NSArray and NSDictionary that encodes an array of objects,
creating references as it goes
*/
internal func _encodeArrayOfObjects(_ objects : NSArray, forKey key : String) {
var objectRefs = [NSObject]()
objectRefs.reserveCapacity(objects.count)
for object in objects {
let objectRef = _encodeObject(_SwiftValue.store(object))!
objectRefs.append(objectRef)
}
_encodeValue(objectRefs._bridgeToObjectiveC(), forKey: key)
}
/// Indicates whether the archiver requires all archived classes to conform to `NSSecureCoding`.
///
/// If you set the receiver to require secure coding, it will cause a fatal error
/// if you attempt to archive a class which does not conform to `NSSecureCoding`.
open override var requiresSecureCoding: Bool {
get {
return _flags.contains(ArchiverFlags.requiresSecureCoding)
}
set {
if newValue {
let _ = _flags.insert(ArchiverFlags.requiresSecureCoding)
} else {
_flags.remove(ArchiverFlags.requiresSecureCoding)
}
}
}
/// Returns the class name with which `NSKeyedArchiver` encodes instances of a given class.
///
/// - Parameter cls: The class for which to determine the translation mapping.
/// - Returns: The class name with which `NSKeyedArchiver` encodes instances of `cls`.
/// Returns `nil` if `NSKeyedArchiver` does not have a translation mapping for `cls`.
open class func classNameForClass(_ cls: AnyClass) -> String? {
let clsName = String(reflecting: cls)
var mappedClass : String?
_classNameMapLock.synchronized {
mappedClass = _classNameMap[clsName]
}
return mappedClass
}
/// Returns the class name with which the archiver encodes instances of a given class.
///
/// - Parameter cls: The class for which to determine the translation mapping.
/// - Returns: The class name with which the receiver encodes instances of cls.
/// Returns `nil` if the archiver does not have a translation
/// mapping for `cls`. The class’s separate translation map is not searched.
open func classNameForClass(_ cls: AnyClass) -> String? {
let clsName = String(reflecting: cls)
return _classNameMap[clsName]
}
}
extension NSKeyedArchiverDelegate {
func archiver(_ archiver: NSKeyedArchiver, willEncode object: Any) -> Any? {
// Returning the same object is the same as doing nothing
return object
}
func archiver(_ archiver: NSKeyedArchiver, didEncode object: Any?) { }
func archiver(_ archiver: NSKeyedArchiver, willReplace object: Any?, with newObject: Any?) { }
func archiverWillFinish(_ archiver: NSKeyedArchiver) { }
func archiverDidFinish(_ archiver: NSKeyedArchiver) { }
}
/// The `NSKeyedArchiverDelegate` protocol defines the optional methods implemented
/// by delegates of `NSKeyedArchiver` objects.
public protocol NSKeyedArchiverDelegate : class {
/// Informs the delegate that `object` is about to be encoded.
///
/// This method is called after the original object may have replaced itself
/// with `replacementObject(for:)`.
///
/// This method is called whether or not the object is being encoded conditionally.
///
/// This method is not called for an object once a replacement mapping has been set up
/// for that object (either explicitly, or because the object has previously been encoded).
/// This method is also not called when `nil` is about to be encoded.
///
/// - Parameters:
/// - archiver: The archiver that invoked the method.
/// - object: The object that is about to be encoded.
/// - Returns: Either object or a different object to be encoded in its stead.
/// The delegate can also modify the coder state. If the delegate
/// returns `nil`, `nil` is encoded.
func archiver(_ archiver: NSKeyedArchiver, willEncode object: Any) -> Any?
/// Informs the delegate that a given object has been encoded.
///
/// The delegate might restore some state it had modified previously,
/// or use this opportunity to keep track of the objects that are encoded.
///
/// This method is not called for conditional objects until they are actually encoded (if ever).
///
/// - Parameters:
/// - archiver: The archiver that invoked the method.
/// - object: The object that has been encoded.
func archiver(_ archiver: NSKeyedArchiver, didEncode object: Any?)
/// Informs the delegate that one given object is being substituted for another given object.
///
/// This method is called even when the delegate itself is doing, or has done,
/// the substitution. The delegate may use this method if it is keeping track
/// of the encoded or decoded objects.
///
/// - Parameters:
/// - archiver: The archiver that invoked the method.
/// - object: The object being replaced in the archive.
/// - newObject: The object replacing `object` in the archive.
func archiver(_ archiver: NSKeyedArchiver, willReplace object: Any?, withObject newObject: Any?)
/// Notifies the delegate that encoding is about to finish.
///
/// - Parameter archiver: The archiver that invoked the method.
func archiverWillFinish(_ archiver: NSKeyedArchiver)
/// Notifies the delegate that encoding has finished.
///
/// - Parameter archiver: The archiver that invoked the method.
func archiverDidFinish(_ archiver: NSKeyedArchiver)
}
|
apache-2.0
|
3fe79e757463763be1ccea5f1e270534
| 37.96945 | 157 | 0.619708 | 4.904896 | false | false | false | false |
mwcurry/hehe
|
native/TVMLCatalog/AppDelegate.swift
|
1
|
2951
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
*/
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
// MARK: Properties
var window: UIWindow?
var appController: TVApplicationController?
//static let TVBaseURL = "http://hehesatv.cfapps.io/"
static let TVBaseURL = "http://localhost:8080/"
static let TVBootURL = "\(AppDelegate.TVBaseURL)app.js"
// MARK: UIApplication Overrides
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
/*
Create the TVApplicationControllerContext for this application
and set the properties that will be passed to the `App.onLaunch` function
in JavaScript.
*/
let appControllerContext = TVApplicationControllerContext()
/*
The JavaScript URL is used to create the JavaScript context for your
TVMLKit application. Although it is possible to separate your JavaScript
into separate files, to help reduce the launch time of your application
we recommend creating minified and compressed version of this resource.
This will allow for the resource to be retrieved and UI presented to
the user quickly.
*/
if let javaScriptURL = URL(string: AppDelegate.TVBootURL) {
appControllerContext.javaScriptApplicationURL = javaScriptURL
}
appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
// MARK: TVApplicationControllerDelegate
func appController(_ appController: TVApplicationController, didFinishLaunching options: [String: Any]?) {
print("\(#function) invoked with options: \(options)")
}
func appController(_ appController: TVApplicationController, didFail error: Error) {
print("\(#function) invoked with error: \(error)")
let title = "Error Launching Application"
let message = error.localizedDescription
let alertController = UIAlertController(title: title, message: message, preferredStyle:.alert )
self.appController?.navigationController.present(alertController, animated: true, completion: { () -> Void in
// ...
})
}
func appController(_ appController: TVApplicationController, didStop options: [String: Any]?) {
print("\(#function) invoked with options: \(options)")
}
}
|
mit
|
06533754c497b891f06942f366a43d8c
| 37.802632 | 144 | 0.67311 | 5.862823 | false | false | false | false |
yanif/circator
|
MetabolicCompass/Extensions/UIColor+Extended.swift
|
1
|
1226
|
//
// UIColor+Extended.swift
// MetabolicCompass
//
// Created by Inaiur on 5/11/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
public static func colorWithHex(hex6: UInt32, alpha: CGFloat = 1) -> UIColor {
let divisor = CGFloat(255)
let red = CGFloat((hex6 & 0xFF0000) >> 16) / divisor
let green = CGFloat((hex6 & 0x00FF00) >> 8) / divisor
let blue = CGFloat( hex6 & 0x0000FF ) / divisor
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
public static func colorWithHexString(rgb: String, alpha: CGFloat = 1) -> UIColor? {
guard rgb.hasPrefix("#") else {
return nil
}
guard let hexString: String = rgb.substringFromIndex(rgb.startIndex.advancedBy(1)),
var hexValue: UInt32 = 0
where NSScanner(string: hexString).scanHexInt(&hexValue) else {
return nil
}
switch (hexString.characters.count) {
case 6:
return UIColor.colorWithHex(hexValue, alpha: alpha)
default:
return nil
}
}
}
|
apache-2.0
|
2379a94322bfe8f471a7b5f7c488ea02
| 28.902439 | 91 | 0.578776 | 4.209622 | false | false | false | false |
ericastevens/WeatherApp
|
WeatherAppCodingChallenge/WeatherAppCodingChallenge/APIRequestManager.swift
|
1
|
864
|
//
// APIRequestManager.swift
// WeatherAppCodingChallenge
//
// Created by Erica Y Stevens on 8/3/17.
// Copyright © 2017 Erica Y Stevens. All rights reserved.
//
import Foundation
class APIRequestManager {
static let manager = APIRequestManager()
private init() {}
func getData(endpoint: URL, callback: @escaping (Data?) -> Void) {
let session = URLSession(configuration: URLSessionConfiguration.default)
var request = URLRequest(url: endpoint)
request.httpMethod = "GET"
session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil {
print("Error during DataTask Session: \(error!)")
}
guard let validData = data else { return }
callback(validData)
}.resume()
}
}
|
mit
|
6dfb6b93848b9b3ba5a567334080f3a6
| 27.766667 | 97 | 0.608343 | 4.542105 | false | true | false | false |
Jnosh/swift
|
test/Constraints/generics.swift
|
4
|
19900
|
// RUN: %target-typecheck-verify-swift
infix operator +++
protocol ConcatToAnything {
static func +++ <T>(lhs: Self, other: T)
}
func min<T : Comparable>(_ x: T, y: T) -> T {
if y < x { return y }
return x
}
func weirdConcat<T : ConcatToAnything, U>(_ t: T, u: U) {
t +++ u
t +++ 1
u +++ t // expected-error{{argument type 'U' does not conform to expected type 'ConcatToAnything'}}
}
// Make sure that the protocol operators don't get in the way.
var b1, b2 : Bool
_ = b1 != b2
extension UnicodeScalar {
func isAlpha2() -> Bool {
return (self >= "A" && self <= "Z") || (self >= "a" && self <= "z")
}
}
protocol P {
static func foo(_ arg: Self) -> Self
}
struct S : P {
static func foo(_ arg: S) -> S {
return arg
}
}
func foo<T : P>(_ arg: T) -> T {
return T.foo(arg)
}
// Associated types and metatypes
protocol SomeProtocol {
associatedtype SomeAssociated
}
func generic_metatypes<T : SomeProtocol>(_ x: T)
-> (T.Type, T.SomeAssociated.Type)
{
return (type(of: x), type(of: x).SomeAssociated.self)
}
// Inferring a variable's type from a call to a generic.
struct Pair<T, U> { } // expected-note 4 {{'T' declared as parameter to type 'Pair'}} expected-note {{'U' declared as parameter to type 'Pair'}}
func pair<T, U>(_ x: T, _ y: U) -> Pair<T, U> { }
var i : Int, f : Float
var p = pair(i, f)
// Conformance constraints on static variables.
func f1<S1 : Sequence>(_ s1: S1) {}
var x : Array<Int> = [1]
f1(x)
// Inheritance involving generics and non-generics.
class X {
func f() {}
}
class Foo<T> : X {
func g() { }
}
class Y<U> : Foo<Int> {
}
func genericAndNongenericBases(_ x: Foo<Int>, y: Y<()>) {
x.f()
y.f()
y.g()
}
func genericAndNongenericBasesTypeParameter<T : Y<()>>(_ t: T) {
t.f()
t.g()
}
protocol P1 {}
protocol P2 {}
func foo<T : P1>(_ t: T) -> P2 {
return t // expected-error{{return expression of type 'T' does not conform to 'P2'}}
}
func foo2(_ p1: P1) -> P2 {
return p1 // expected-error{{return expression of type 'P1' does not conform to 'P2'}}
}
// <rdar://problem/14005696>
protocol BinaryMethodWorkaround {
associatedtype MySelf
}
protocol Squigglable : BinaryMethodWorkaround {
}
infix operator ~~~
func ~~~ <T : Squigglable>(lhs: T, rhs: T) -> Bool where T.MySelf == T {
return true
}
extension UInt8 : Squigglable {
typealias MySelf = UInt8
}
var rdar14005696 : UInt8
_ = rdar14005696 ~~~ 5
// <rdar://problem/15168483>
public struct SomeIterator<C: Collection, Indices: Sequence>
: IteratorProtocol, Sequence
where C.Index == Indices.Iterator.Element {
var seq : C
var indices : Indices.Iterator
public typealias Element = C.Iterator.Element
public mutating func next() -> Element? {
fatalError()
}
public init(elements: C, indices: Indices) {
fatalError()
}
}
func f1<T>(seq: Array<T>) {
let x = (seq.indices).lazy.reversed()
SomeIterator(elements: seq, indices: x) // expected-warning{{unused}}
SomeIterator(elements: seq, indices: seq.indices.reversed()) // expected-warning{{unused}}
}
// <rdar://problem/16078944>
func count16078944<T>(_ x: Range<T>) -> Int { return 0 }
func test16078944 <T: Comparable>(lhs: T, args: T) -> Int {
return count16078944(lhs..<args) // don't crash
}
// <rdar://problem/22409190> QoI: Passing unsigned integer to ManagedBuffer elements.destroy()
class r22409190ManagedBuffer<Value, Element> {
final var value: Value { get {} set {}}
func withUnsafeMutablePointerToElements<R>(
_ body: (UnsafeMutablePointer<Element>) -> R) -> R {
}
}
class MyArrayBuffer<Element>: r22409190ManagedBuffer<UInt, Element> {
deinit {
self.withUnsafeMutablePointerToElements { elems -> Void in
elems.deinitialize(count: self.value) // expected-error {{cannot convert value of type 'UInt' to expected argument type 'Int'}}
}
}
}
// <rdar://problem/22459135> error: 'print' is unavailable: Please wrap your tuple argument in parentheses: 'print((...))'
func r22459135() {
func h<S : Sequence>(_ sequence: S) -> S.Iterator.Element
where S.Iterator.Element : FixedWidthInteger {
return 0
}
func g(_ x: Any) {}
func f(_ x: Int) {
g(h([3]))
}
func f2<TargetType: AnyObject>(_ target: TargetType, handler: @escaping (TargetType) -> ()) {
let _: (AnyObject) -> () = { internalTarget in
handler(internalTarget as! TargetType)
}
}
}
// <rdar://problem/19710848> QoI: Friendlier error message for "[] as Set"
// <rdar://problem/22326930> QoI: "argument for generic parameter 'Element' could not be inferred" lacks context
_ = [] as Set // expected-error {{generic parameter 'Element' could not be inferred in cast to 'Set<_>}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{14-14=<<#Element: Hashable#>>}}
//<rdar://problem/22509125> QoI: Error when unable to infer generic archetype lacks greatness
func r22509125<T>(_ a : T?) { // expected-note {{in call to function 'r22509125'}}
r22509125(nil) // expected-error {{generic parameter 'T' could not be inferred}}
}
// <rdar://problem/24267414> QoI: error: cannot convert value of type 'Int' to specified type 'Int'
struct R24267414<T> { // expected-note {{'T' declared as parameter to type 'R24267414'}}
static func foo() -> Int {}
}
var _ : Int = R24267414.foo() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{24-24=<Any>}}
// https://bugs.swift.org/browse/SR-599
func SR599<T: FixedWidthInteger>() -> T.Type { return T.self } // expected-note {{in call to function 'SR599'}}
_ = SR599() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/19215114> QoI: Poor diagnostic when we are unable to infer type
protocol Q19215114 {}
protocol P19215114 {}
// expected-note @+1 {{in call to function 'body9215114'}}
func body9215114<T: P19215114, U: Q19215114>(_ t: T) -> (_ u: U) -> () {}
func test9215114<T: P19215114, U: Q19215114>(_ t: T) -> (U) -> () {
//Should complain about not being able to infer type of U.
let f = body9215114(t) // expected-error {{generic parameter 'T' could not be inferred}}
return f
}
// <rdar://problem/21718970> QoI: [uninferred generic param] cannot invoke 'foo' with an argument list of type '(Int)'
class Whatever<A: Numeric, B: Numeric> { // expected-note 2 {{'A' declared as parameter to type 'Whatever'}}
static func foo(a: B) {}
static func bar() {}
}
Whatever.foo(a: 23) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}}
// <rdar://problem/21718955> Swift useless error: cannot invoke 'foo' with no arguments
Whatever.bar() // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{9-9=<<#A: Numeric#>, <#B: Numeric#>>}}
// <rdar://problem/27515965> Type checker doesn't enforce same-type constraint if associated type is Any
protocol P27515965 {
associatedtype R
func f() -> R
}
struct S27515965 : P27515965 {
func f() -> Any { return self }
}
struct V27515965 {
init<T : P27515965>(_ tp: T) where T.R == Float {}
}
func test(x: S27515965) -> V27515965 {
return V27515965(x) // expected-error {{generic parameter 'T' could not be inferred}}
}
protocol BaseProto {}
protocol SubProto: BaseProto {}
@objc protocol NSCopyish {
func copy() -> Any
}
struct FullyGeneric<Foo> {} // expected-note 11 {{'Foo' declared as parameter to type 'FullyGeneric'}} expected-note 1 {{generic type 'FullyGeneric' declared here}}
struct AnyClassBound<Foo: AnyObject> {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound'}} expected-note {{generic type 'AnyClassBound' declared here}}
struct AnyClassBound2<Foo> where Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassBound2'}}
struct ProtoBound<Foo: SubProto> {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound'}} expected-note {{generic type 'ProtoBound' declared here}}
struct ProtoBound2<Foo> where Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ProtoBound2'}}
struct ObjCProtoBound<Foo: NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound'}} expected-note {{generic type 'ObjCProtoBound' declared here}}
struct ObjCProtoBound2<Foo> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ObjCProtoBound2'}}
struct ClassBound<Foo: X> {} // expected-note {{generic type 'ClassBound' declared here}}
struct ClassBound2<Foo> where Foo: X {} // expected-note {{generic type 'ClassBound2' declared here}}
struct ProtosBound<Foo> where Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound'}} expected-note {{generic type 'ProtosBound' declared here}}
struct ProtosBound2<Foo: SubProto & NSCopyish> {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound2'}}
struct ProtosBound3<Foo: SubProto> where Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ProtosBound3'}}
struct AnyClassAndProtoBound<Foo> where Foo: AnyObject, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound'}}
struct AnyClassAndProtoBound2<Foo> where Foo: SubProto, Foo: AnyObject {} // expected-note {{'Foo' declared as parameter to type 'AnyClassAndProtoBound2'}}
struct ClassAndProtoBound<Foo> where Foo: X, Foo: SubProto {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtoBound'}}
struct ClassAndProtosBound<Foo> where Foo: X, Foo: SubProto, Foo: NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound'}}
struct ClassAndProtosBound2<Foo> where Foo: X, Foo: SubProto & NSCopyish {} // expected-note {{'Foo' declared as parameter to type 'ClassAndProtosBound2'}}
extension Pair {
init(first: T) {}
init(second: U) {}
var first: T { fatalError() }
var second: U { fatalError() }
}
func testFixIts() {
_ = FullyGeneric() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<Any>}}
_ = FullyGeneric<Any>()
_ = AnyClassBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<AnyObject>}}
_ = AnyClassBound<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}}
_ = AnyClassBound<AnyObject>()
_ = AnyClassBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<AnyObject>}}
_ = AnyClassBound2<Any>() // expected-error {{'Any' is not convertible to 'AnyObject'}}
_ = AnyClassBound2<AnyObject>()
_ = ProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{17-17=<<#Foo: SubProto#>>}}
_ = ProtoBound<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: SubProto#>>}}
_ = ProtoBound2<Any>() // expected-error {{type 'Any' does not conform to protocol 'SubProto'}}
_ = ObjCProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{21-21=<NSCopyish>}}
_ = ObjCProtoBound<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound<NSCopyish>()
_ = ObjCProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{22-22=<NSCopyish>}}
_ = ObjCProtoBound2<AnyObject>() // expected-error {{type 'AnyObject' does not conform to protocol 'NSCopyish'}}
_ = ObjCProtoBound2<NSCopyish>()
_ = ProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{18-18=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = ProtosBound3() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{19-19=<<#Foo: NSCopyish & SubProto#>>}}
_ = AnyClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{28-28=<<#Foo: SubProto & AnyObject#>>}}
_ = AnyClassAndProtoBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{29-29=<<#Foo: SubProto & AnyObject#>>}}
_ = ClassAndProtoBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<<#Foo: X & SubProto#>>}}
_ = ClassAndProtosBound() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<<#Foo: X & NSCopyish & SubProto#>>}}
_ = ClassAndProtosBound2() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{27-27=<<#Foo: X & NSCopyish & SubProto#>>}}
_ = Pair() // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, Any>}}
_ = Pair(first: S()) // expected-error {{generic parameter 'U' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<S, Any>}}
_ = Pair(second: S()) // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{11-11=<Any, S>}}
}
func testFixItClassBound() {
// We infer a single class bound for simple cases in expressions...
let x = ClassBound()
let x1: String = x // expected-error {{cannot convert value of type 'ClassBound<X>' to specified type 'String'}}
let y = ClassBound2()
let y1: String = y // expected-error {{cannot convert value of type 'ClassBound2<X>' to specified type 'String'}}
// ...but not in types.
let z1: ClassBound // expected-error {{reference to generic type 'ClassBound' requires arguments in <...>}} {{21-21=<X>}}
let z2: ClassBound2 // expected-error {{reference to generic type 'ClassBound2' requires arguments in <...>}} {{22-22=<X>}}
}
func testFixItCasting(x: Any) {
_ = x as! FullyGeneric // expected-error {{generic parameter 'Foo' could not be inferred in cast to 'FullyGeneric<_>'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
}
func testFixItContextualKnowledge() {
// FIXME: These could propagate backwards.
let _: Int = Pair().first // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
let _: Int = Pair().second // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any, Any>}}
}
func testFixItTypePosition() {
let _: FullyGeneric // expected-error {{reference to generic type 'FullyGeneric' requires arguments in <...>}} {{22-22=<Any>}}
let _: ProtoBound // expected-error {{reference to generic type 'ProtoBound' requires arguments in <...>}} {{20-20=<<#Foo: SubProto#>>}}
let _: ObjCProtoBound // expected-error {{reference to generic type 'ObjCProtoBound' requires arguments in <...>}} {{24-24=<NSCopyish>}}
let _: AnyClassBound // expected-error {{reference to generic type 'AnyClassBound' requires arguments in <...>}} {{23-23=<AnyObject>}}
let _: ProtosBound // expected-error {{reference to generic type 'ProtosBound' requires arguments in <...>}} {{21-21=<<#Foo: NSCopyish & SubProto#>>}}
}
func testFixItNested() {
_ = Array<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{25-25=<Any>}}
_ = [FullyGeneric]() // expected-error {{generic parameter 'Foo' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{20-20=<Any>}}
_ = FullyGeneric<FullyGeneric>() // expected-error {{generic parameter 'Foo' could not be inferred}}
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric,
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric // FIXME: We could diagnose both of these, but we don't.
>()
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric<Any>,
FullyGeneric
>()
_ = Pair< // expected-error {{generic parameter 'Foo' could not be inferred}}
FullyGeneric,
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}} {{17-17=<Any>}}
FullyGeneric<Any>
>()
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric()
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric<Any>(),
FullyGeneric() // expected-note {{explicitly specify the generic arguments to fix this issue}}
)
_ = pair( // expected-error {{generic parameter 'Foo' could not be inferred}} {{none}}
FullyGeneric(), // expected-note {{explicitly specify the generic arguments to fix this issue}}
FullyGeneric<Any>()
)
}
// rdar://problem/26845038
func occursCheck26845038(a: [Int]) {
_ = Array(a)[0]
}
// rdar://problem/29633747
extension Array where Element: Hashable {
public func trimmed(_ elements: [Element]) -> SubSequence {
return []
}
}
func rdar29633747(characters: String.CharacterView) {
let _ = Array(characters).trimmed(["("])
}
// Null pointer dereference in noteArchetypeSource()
class GenericClass<A> {}
// expected-note@-1 {{'A' declared as parameter to type 'GenericClass'}}
func genericFunc<T>(t: T) {
_ = [T: GenericClass] // expected-error {{generic parameter 'A' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 2 {{type 'T' does not conform to protocol 'Hashable'}}
}
struct SR_3525<T> {}
func sr3525_arg_int(_: inout SR_3525<Int>) {}
func sr3525_arg_gen<T>(_: inout SR_3525<T>) {}
func sr3525_1(t: SR_3525<Int>) {
let _ = sr3525_arg_int(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_2(t: SR_3525<Int>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
func sr3525_3<T>(t: SR_3525<T>) {
let _ = sr3525_arg_gen(&t) // expected-error {{cannot pass immutable value as inout argument: 't' is a 'let' constant}}
}
class testStdlibType {
let _: Array // expected-error {{reference to generic type 'Array' requires arguments in <...>}} {{15-15=<Any>}}
}
|
apache-2.0
|
7f2c95035a2e1153540596d06c577998
| 43.419643 | 219 | 0.686935 | 3.846154 | false | false | false | false |
ldt25290/MyInstaMap
|
MyInstaMap/Constants.swift
|
1
|
793
|
//
// Constants.swift
// MyInstaMap
//
// Created by DucTran on 9/3/17.
// Copyright © 2017 User. All rights reserved.
//
import Foundation
class Constants {
// MARK: List of Constants
static let LOCATION_BASE_ENDPOINT = "https://instagram.com/"
static let AUTH_ENDPOINT = "https://api.instagram.com/oauth/authorize/"
static let CLIENT_ID = "7179d974f29d414d8f596b8d0cff796c"
static let PARAM_DISTANCE = 5000
static let REDIRECT_URI = "http://localhost"
static let APP_NETWORK_ERROR_MESSAGE = "The Internet connection appears to be Offline."
static let LOGOUT_ADDRESS = "https://instagram.com/accounts/logout"
static let API_URL = "https://api.instagram.com/v1"
static let ERROR_MSG_KEY = "Error"
static let RESPONSE_DATA_KEY = "Data"
}
|
mit
|
b2a58c70cb9883362ce2bef339481b6b
| 32 | 91 | 0.695707 | 3.399142 | false | false | false | false |
cuappdev/eatery
|
Eatery/Views/Eateries/CampusMenuInfoView.swift
|
1
|
3174
|
//
// MenuInfoView.swift
// Eatery
//
// Created by William Ma on 10/15/19.
// Copyright © 2019 CUAppDev. All rights reserved.
//
import CoreLocation
import Hero
import UIKit
class CampusMenuInfoView: UIView, MenuInfoView {
private let statusLabel = UILabel()
private let hoursLabel = UILabel()
private let locationLabel = UILabel()
private let distanceLabel = UILabel()
var statusHero: HeroExtension<UILabel> {
return statusLabel.hero
}
var hoursHero: HeroExtension<UILabel> {
return hoursLabel.hero
}
var locationHero: HeroExtension<UILabel> {
return locationLabel.hero
}
var distanceHero: HeroExtension<UILabel> {
return distanceLabel.hero
}
override init(frame: CGRect) {
super.init(frame: frame)
statusLabel.isOpaque = false
statusLabel.textColor = .eateryBlue
statusLabel.font = .systemFont(ofSize: 14, weight: .semibold)
addSubview(statusLabel)
statusLabel.snp.makeConstraints { make in
make.top.equalToSuperview().inset(16)
make.leading.equalToSuperview().inset(16)
}
hoursLabel.isOpaque = false
hoursLabel.textColor = .gray
hoursLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
addSubview(hoursLabel)
hoursLabel.snp.makeConstraints { make in
make.centerY.equalTo(statusLabel)
make.leading.equalTo(statusLabel.snp.trailing).offset(2)
}
locationLabel.isOpaque = false
locationLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
locationLabel.textColor = .gray
addSubview(locationLabel)
locationLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().offset(16)
make.top.equalTo(statusLabel.snp.bottom).offset(8)
make.bottom.equalToSuperview().inset(16)
}
distanceLabel.isOpaque = false
distanceLabel.textColor = .gray
distanceLabel.font = UIFont.systemFont(ofSize: 14, weight: .medium)
addSubview(distanceLabel)
distanceLabel.snp.makeConstraints { make in
make.leading.greaterThanOrEqualTo(hoursLabel.snp.trailing)
make.trailing.equalToSuperview().inset(16)
make.top.equalToSuperview().inset(16)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configure(eatery: Eatery, userLocation: CLLocation?) {
guard let eatery = eatery as? CampusEatery else {
return
}
let presentation = eatery.currentPresentation()
statusLabel.text = presentation.statusText
statusLabel.textColor = presentation.statusColor
hoursLabel.text = presentation.nextEventText
locationLabel.text = eatery.address
if let userLocation = userLocation {
let miles = userLocation.distance(from: eatery.location).converted(to: .miles).value
distanceLabel.text = "\(Double(round(10 * miles) / 10)) mi"
} else {
distanceLabel.text = "-- mi"
}
}
}
|
mit
|
1ac21120f6ee1c83471620881f803287
| 30.107843 | 96 | 0.646391 | 4.764264 | false | false | false | false |
GianniCarlo/Audiobook-Player
|
BookPlayer/Settings/SettingsViewController.swift
|
1
|
12851
|
//
// SettingsViewController.swift
// BookPlayer
//
// Created by Gianni Carlo on 5/29/17.
// Copyright © 2017 Tortuga Power. All rights reserved.
//
import BookPlayerKit
import DeviceKit
import IntentsUI
import MessageUI
import SafariServices
import Themeable
import UIKit
protocol IntentSelectionDelegate: AnyObject {
func didSelectIntent(_ intent: INIntent)
}
class SettingsViewController: UITableViewController, MFMailComposeViewControllerDelegate, TelemetryProtocol {
@IBOutlet weak var autoplayLibrarySwitch: UISwitch!
@IBOutlet weak var disableAutolockSwitch: UISwitch!
@IBOutlet weak var autolockDisabledOnlyWhenPoweredSwitch: UISwitch!
@IBOutlet weak var autolockDisabledOnlyWhenPoweredLabel: UILabel!
@IBOutlet weak var themeLabel: UILabel!
@IBOutlet weak var appIconLabel: UILabel!
var iconObserver: NSKeyValueObservation!
enum SettingsSection: Int {
case plus = 0, theme, playback, storage, autoplay, autolock, siri, support, credits
}
let lastPlayedShortcutPath = IndexPath(row: 0, section: 6)
let sleepTimerShortcutPath = IndexPath(row: 1, section: 6)
let supportSection: Int = 7
let githubLinkPath = IndexPath(row: 0, section: 7)
let supportEmailPath = IndexPath(row: 1, section: 7)
var version: String = "0.0.0"
var build: String = "0"
var supportEmail = "[email protected]"
var appVersion: String {
return "\(self.version)-\(self.build)"
}
var systemVersion: String {
return "\(UIDevice.current.systemName) \(UIDevice.current.systemVersion)"
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "settings_title".localized
setUpTheming()
let userDefaults = UserDefaults(suiteName: Constants.ApplicationGroupIdentifier)
self.appIconLabel.text = userDefaults?.string(forKey: Constants.UserDefaults.appIcon.rawValue) ?? "Default"
self.iconObserver = UserDefaults.standard.observe(\.userSettingsAppIcon) { _, _ in
self.appIconLabel.text = userDefaults?.string(forKey: Constants.UserDefaults.appIcon.rawValue) ?? "Default"
}
if UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) {
self.donationMade()
} else {
NotificationCenter.default.addObserver(self, selector: #selector(self.donationMade), name: .donationMade, object: nil)
}
self.autoplayLibrarySwitch.addTarget(self, action: #selector(self.autoplayToggleDidChange), for: .valueChanged)
self.disableAutolockSwitch.addTarget(self, action: #selector(self.disableAutolockDidChange), for: .valueChanged)
self.autolockDisabledOnlyWhenPoweredSwitch.addTarget(self, action: #selector(self.autolockOnlyWhenPoweredDidChange), for: .valueChanged)
// Set initial switch positions
self.autoplayLibrarySwitch.setOn(UserDefaults.standard.bool(forKey: Constants.UserDefaults.autoplayEnabled.rawValue), animated: false)
self.disableAutolockSwitch.setOn(UserDefaults.standard.bool(forKey: Constants.UserDefaults.autolockDisabled.rawValue), animated: false)
self.autolockDisabledOnlyWhenPoweredSwitch.setOn(UserDefaults.standard.bool(forKey: Constants.UserDefaults.autolockDisabledOnlyWhenPowered.rawValue), animated: false)
self.autolockDisabledOnlyWhenPoweredSwitch.isEnabled = UserDefaults.standard.bool(forKey: Constants.UserDefaults.autolockDisabled.rawValue)
self.autolockDisabledOnlyWhenPoweredLabel.isEnabled = UserDefaults.standard.bool(forKey: Constants.UserDefaults.autolockDisabled.rawValue)
guard
let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String,
let build = Bundle.main.infoDictionary!["CFBundleVersion"] as? String
else {
return
}
self.version = version
self.build = build
}
@objc func donationMade() {
self.tableView.reloadData()
}
@objc func autoplayToggleDidChange() {
UserDefaults.standard.set(self.autoplayLibrarySwitch.isOn, forKey: Constants.UserDefaults.autoplayEnabled.rawValue)
self.sendSignal(.autoplayLibraryAction, with: ["isOn": "\(self.autoplayLibrarySwitch.isOn)"])
}
@objc func disableAutolockDidChange() {
UserDefaults.standard.set(self.disableAutolockSwitch.isOn, forKey: Constants.UserDefaults.autolockDisabled.rawValue)
self.autolockDisabledOnlyWhenPoweredSwitch.isEnabled = self.disableAutolockSwitch.isOn
self.autolockDisabledOnlyWhenPoweredLabel.isEnabled = self.disableAutolockSwitch.isOn
self.sendSignal(.disableAutolockAction, with: ["isOn": "\(self.disableAutolockSwitch.isOn)"])
}
@objc func autolockOnlyWhenPoweredDidChange() {
UserDefaults.standard.set(self.autolockDisabledOnlyWhenPoweredSwitch.isOn, forKey: Constants.UserDefaults.autolockDisabledOnlyWhenPowered.rawValue)
self.sendSignal(.disableAutolockOnPowerAction, with: ["isOn": "\(self.autolockDisabledOnlyWhenPoweredSwitch.isOn)"])
}
@IBAction func done(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
guard indexPath.section == 0 else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
guard !UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) else { return 0 }
return 102
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard section == 0, UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) else {
return super.tableView(tableView, heightForHeaderInSection: section)
}
return CGFloat.leastNormalMagnitude
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
guard section == 0, UserDefaults.standard.bool(forKey: Constants.UserDefaults.donationMade.rawValue) else {
return super.tableView(tableView, heightForFooterInSection: section)
}
return CGFloat.leastNormalMagnitude
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath as IndexPath, animated: true)
switch indexPath {
case self.supportEmailPath:
self.sendSupportEmail()
case self.githubLinkPath:
self.showProjectOnGitHub()
case self.lastPlayedShortcutPath:
self.showLastPlayedShortcut()
case self.sleepTimerShortcutPath:
self.showSleepTimerShortcut()
default: break
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard let settingsSection = SettingsSection(rawValue: section) else {
return super.tableView(tableView, titleForFooterInSection: section)
}
switch settingsSection {
case .theme:
return "settings_appearance_title".localized
case .playback:
return "settings_playback_title".localized
case .storage:
return "settings_storage_title".localized
case .siri:
return "settings_siri_title".localized
case .support:
return "settings_support_title".localized
default:
return super.tableView(tableView, titleForHeaderInSection: section)
}
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let settingsSection = SettingsSection(rawValue: section) else {
return super.tableView(tableView, titleForFooterInSection: section)
}
switch settingsSection {
case .autoplay:
return "settings_autoplay_description".localized
case .autolock:
return "settings_autolock_description".localized
case .support:
return "BookPlayer \(self.appVersion) - \(self.systemVersion)"
default:
return super.tableView(tableView, titleForFooterInSection: section)
}
}
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header = view as? UITableViewHeaderFooterView
header?.textLabel?.textColor = self.themeProvider.currentTheme.secondaryColor
}
override func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let footer = view as? UITableViewHeaderFooterView
footer?.textLabel?.textColor = self.themeProvider.currentTheme.secondaryColor
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
func showLastPlayedShortcut() {
let intent = INPlayMediaIntent()
guard let shortcut = INShortcut(intent: intent) else { return }
let vc = INUIAddVoiceShortcutViewController(shortcut: shortcut)
vc.delegate = self
self.present(vc, animated: true, completion: nil)
self.sendSignal(.lastPlayedSiriShortcutAction, with: nil)
}
func showSleepTimerShortcut() {
self.sendSignal(.sleepTimerSiriShortcutAction, with: nil)
let intent = SleepTimerIntent()
intent.option = .unknown
let shortcut = INShortcut(intent: intent)!
let vc = INUIAddVoiceShortcutViewController(shortcut: shortcut)
vc.delegate = self
self.present(vc, animated: true, completion: nil)
}
@IBAction func sendSupportEmail() {
self.sendSignal(.emailSupportAction, with: nil)
let device = Device.current
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([self.supportEmail])
mail.setSubject("I need help with BookPlayer \(self.version)-\(self.build)")
mail.setMessageBody("<p>Hello BookPlayer Crew,<br>I have an issue concerning BookPlayer \(self.appVersion) on my \(device) running \(self.systemVersion)</p><p>When I try to…</p>", isHTML: true)
self.present(mail, animated: true)
} else {
let debugInfo = "BookPlayer \(self.appVersion)\n\(device) - \(self.systemVersion)"
let message = "settings_support_compose_description".localized
let alert = UIAlertController(title: "settings_support_compose_title".localized, message: "\(message) \(self.supportEmail)\n\n\(debugInfo)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "settings_support_compose_copy".localized, style: .default, handler: { _ in
UIPasteboard.general.string = "\(self.supportEmail)\n\(debugInfo)"
}))
alert.addAction(UIAlertAction(title: "ok_button".localized, style: .cancel, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
func showProjectOnGitHub() {
let url = URL(string: "https://github.com/GianniCarlo/Audiobook-Player")
let safari = SFSafariViewController(url: url!)
safari.dismissButtonStyle = .close
self.present(safari, animated: true)
self.sendSignal(.githubScreen, with: nil)
}
}
extension SettingsViewController: INUIAddVoiceShortcutViewControllerDelegate {
func addVoiceShortcutViewControllerDidCancel(_ controller: INUIAddVoiceShortcutViewController) {
self.dismiss(animated: true, completion: nil)
}
func addVoiceShortcutViewController(_ controller: INUIAddVoiceShortcutViewController, didFinishWith voiceShortcut: INVoiceShortcut?, error: Error?) {
self.dismiss(animated: true, completion: nil)
}
}
extension SettingsViewController: IntentSelectionDelegate {
func didSelectIntent(_ intent: INIntent) {
let shortcut = INShortcut(intent: intent)!
let vc = INUIAddVoiceShortcutViewController(shortcut: shortcut)
vc.delegate = self
self.present(vc, animated: true, completion: nil)
}
}
extension SettingsViewController: Themeable {
func applyTheme(_ theme: Theme) {
self.themeLabel.text = theme.title
self.tableView.backgroundColor = theme.systemGroupedBackgroundColor
self.tableView.separatorColor = theme.systemGroupedBackgroundColor
self.tableView.reloadData()
self.overrideUserInterfaceStyle = theme.useDarkVariant
? UIUserInterfaceStyle.dark
: UIUserInterfaceStyle.light
}
}
|
gpl-3.0
|
779279abe77c357d85d0448797461c94
| 40.579288 | 205 | 0.706336 | 4.857467 | false | false | false | false |
am0oma/shared
|
C-ObjC-Swift/Performance_Console/Performance_Console/main.swift
|
1
|
806
|
//
// main.swift
// Performance_Console
//
// Created by Gian Luigi Romita on 11/06/14.
// Copyright (c) 2014 Gian Luigi Romita. All rights reserved.
//
import Foundation
let num_elements : NSInteger = 1000000
Performance_ObjCtoCPlusPlus.sortArrayCPlusPlus(num_elements)
Performance_ObjectiveC.sortArrayObjC(num_elements)
//println("Hello, World!")
var int_array = [Int](count: num_elements, repeatedValue: 0)
for i in 0...(num_elements-1) {
int_array[i] = random()
}
// Put the code you want to measure the time of here.
let start : NSDate = NSDate()
let sorted_array = sorted(int_array, <)
let end : NSDate = NSDate()
let executionTime : NSTimeInterval = end.timeIntervalSinceDate(start)
println("swift executionTime: \(executionTime) seconds for \(num_elements) elements. \n");
|
mit
|
e3f69c54da2ac012a49f500540d56093
| 22.705882 | 90 | 0.717122 | 3.400844 | false | false | false | false |
soffes/Cache
|
Sources/Cache/AnyCache.swift
|
1
|
1020
|
public struct AnyCache<Element>: Cache {
// MARK: - Properties
private let _get: (String, @escaping (Element?) -> Void) -> ()
private let _set: (String, Element, (() -> Void)?) -> ()
private let _remove: (String, (() -> Void)?) -> ()
private let _removeAll: ((() -> Void)?) -> ()
// MARK: - Initializers
public init<C: Cache>(_ cache: C) where Element == C.Element {
_get = { cache.get(key: $0, completion: $1) }
_set = { cache.set(key: $0, value: $1, completion: $2) }
_remove = { cache.remove(key: $0, completion: $1) }
_removeAll = { cache.removeAll(completion: $0) }
}
// MARK: - Cache
public func get(key: String, completion: @escaping ((Element?) -> Void)) {
_get(key, completion)
}
public func set(key: String, value: Element, completion: (() -> Void)? = nil) {
_set(key, value, completion)
}
public func remove(key: String, completion: (() -> Void)? = nil) {
_remove(key, completion)
}
public func removeAll(completion: (() -> Void)? = nil) {
_removeAll(completion)
}
}
|
mit
|
987cb5e8d696089298775054d435d91f
| 27.333333 | 80 | 0.597059 | 3.026706 | false | false | false | false |
saketh93/SlideMenu
|
SlideMenu/MenuViewController.swift
|
1
|
4213
|
//
// MenuViewController.swift
// SlideMenu
//
// Created by Saketh Manemala on 28/06/17.
// Copyright © 2017 Saketh. All rights reserved.
//
import UIKit
protocol MenuViewControllerDelegate {
func forSideMenuCollapse()
}
class MenuViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var delegate : MenuViewControllerDelegate?
var contr : ContainerViewController?
var profileImageView : UIImageView?
var profileLabel : UILabel?
var emailIdLabel : UILabel?
var menuList = ["Profile","Books","Electronics","Fashion","Settings","Help" ]
var menuImageList = ["Profile.png","Books.png","Electronics.png","Fashion.png","Settings.png","Help.png"]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension MenuViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return menuList.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell")! as UITableViewCell
if indexPath.row == 0 {
cell.imageView?.tintColor = UIColor.black
cell.imageView?.image = imageWithImage(UIImage(named: menuImageList[indexPath.row])!, scaledToSize: CGSize(width: 50, height: 50))
cell.textLabel?.text = menuList[indexPath.row]
cell.textLabel?.font = UIFont (name: "Helvetica Neue", size: 15)
cell.detailTextLabel?.text = "[email protected]"
} else{
cell.imageView?.tintColor = UIColor.black
cell.imageView?.image = imageWithImage(UIImage(named: menuImageList[indexPath.row])!, scaledToSize: CGSize(width: 20, height: 20))
cell.textLabel?.text = menuList[indexPath.row]
cell.textLabel?.font = UIFont (name: "Helvetica Neue", size: 15)
cell.detailTextLabel?.text = nil
}
return cell
}
}
// Mark: Table View Delegate
extension MenuViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedIndex = indexPath.row
let storyBoard :UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
switch selectedIndex {
case 0:
break
case 1:
let booksVC = storyBoard.instantiateViewController(withIdentifier: "BooksViewController")
self.navigationController?.pushViewController(booksVC, animated: true)
break
case 2:
let electronicsVC = storyBoard.instantiateViewController(withIdentifier: "ElectronicsViewController")
self.navigationController?.pushViewController(electronicsVC, animated: true)
break
case 3:
let fashionVC = storyBoard.instantiateViewController(withIdentifier: "FashionViewController")
self.navigationController?.pushViewController(fashionVC, animated: true)
break
case 4:
break
case 5:
break
case 6:
break
default:
break
}
delegate?.forSideMenuCollapse()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
return 120
}
else{
return 45
}
}
}
|
mit
|
e6747fc419f916e2b24afa91a0586d9a
| 32.696 | 142 | 0.644587 | 5.11165 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/Pods/RealmSwift/RealmSwift/Migration.swift
|
23
|
8967
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
The type of a migration block used to migrate a Realm.
- parameter migration: A `Migration` object used to perform the migration. The migration object allows you to
enumerate and alter any existing objects which require migration.
- parameter oldSchemaVersion: The schema version of the Realm being migrated.
*/
public typealias MigrationBlock = (_ migration: Migration, _ oldSchemaVersion: UInt64) -> Void
/// An object class used during migrations.
public typealias MigrationObject = DynamicObject
/**
A block type which provides both the old and new versions of an object in the Realm. Object
properties can only be accessed using subscripting.
- parameter oldObject: The object from the original Realm (read-only).
- parameter newObject: The object from the migrated Realm (read-write).
*/
public typealias MigrationObjectEnumerateBlock = (_ oldObject: MigrationObject?, _ newObject: MigrationObject?) -> Void
/**
Returns the schema version for a Realm at a given local URL.
- parameter fileURL: Local URL to a Realm file.
- parameter encryptionKey: 64-byte key used to encrypt the file, or `nil` if it is unencrypted.
- throws: An `NSError` that describes the problem.
*/
public func schemaVersionAtURL(_ fileURL: URL, encryptionKey: Data? = nil) throws -> UInt64 {
var error: NSError?
let version = RLMRealm.__schemaVersion(at: fileURL, encryptionKey: encryptionKey, error: &error)
guard version != RLMNotVersioned else {
throw error!
}
return version
}
extension Realm {
/**
Performs the given Realm configuration's migration block on a Realm at the given path.
This method is called automatically when opening a Realm for the first time and does not need to be called
explicitly. You can choose to call this method to control exactly when and how migrations are performed.
- parameter configuration: The Realm configuration used to open and migrate the Realm.
*/
public static func performMigration(for configuration: Realm.Configuration = Realm.Configuration.defaultConfiguration) throws {
try RLMRealm.performMigration(for: configuration.rlmConfiguration)
}
}
/**
`Migration` instances encapsulate information intended to facilitate a schema migration.
A `Migration` instance is passed into a user-defined `MigrationBlock` block when updating the version of a Realm. This
instance provides access to the old and new database schemas, the objects in the Realm, and provides functionality for
modifying the Realm during the migration.
*/
public final class Migration {
// MARK: Properties
/// The old schema, describing the Realm before applying a migration.
public var oldSchema: Schema { return Schema(rlmMigration.oldSchema) }
/// The new schema, describing the Realm after applying a migration.
public var newSchema: Schema { return Schema(rlmMigration.newSchema) }
internal var rlmMigration: RLMMigration
// MARK: Altering Objects During a Migration
/**
Enumerates all the objects of a given type in this Realm, providing both the old and new versions of each object.
Properties on an object can be accessed using subscripting.
- parameter objectClassName: The name of the `Object` class to enumerate.
- parameter block: The block providing both the old and new versions of an object in this Realm.
*/
public func enumerateObjects(ofType typeName: String, _ block: MigrationObjectEnumerateBlock) {
rlmMigration.enumerateObjects(typeName) { oldObject, newObject in
block(unsafeBitCast(oldObject, to: MigrationObject.self),
unsafeBitCast(newObject, to: MigrationObject.self))
}
}
/**
Creates and returns an `Object` of type `className` in the Realm being migrated.
The `value` argument is used to populate the object. It can be a key-value coding compliant object, an array or
dictionary returned from the methods in `NSJSONSerialization`, or an `Array` containing one element for each
managed property. An exception will be thrown if any required properties are not present and those properties were
not defined with default values.
When passing in an `Array` as the `value` argument, all properties must be present, valid and in the same order as
the properties defined in the model.
- parameter className: The name of the `Object` class to create.
- parameter value: The value used to populate the created object.
- returns: The newly created object.
*/
@discardableResult
public func create(_ typeName: String, value: Any = [:]) -> MigrationObject {
return unsafeBitCast(rlmMigration.createObject(typeName, withValue: value), to: MigrationObject.self)
}
/**
Deletes an object from a Realm during a migration.
It is permitted to call this method from within the block passed to `enumerate(_:block:)`.
- parameter object: An object to be deleted from the Realm being migrated.
*/
public func delete(_ object: MigrationObject) {
rlmMigration.delete(object.unsafeCastToRLMObject())
}
/**
Deletes the data for the class with the given name.
All objects of the given class will be deleted. If the `Object` subclass no longer exists in your program, any
remaining metadata for the class will be removed from the Realm file.
- parameter objectClassName: The name of the `Object` class to delete.
- returns: A Boolean value indicating whether there was any data to delete.
*/
@discardableResult
public func deleteData(forType typeName: String) -> Bool {
return rlmMigration.deleteData(forClassName: typeName)
}
/**
Renames a property of the given class from `oldName` to `newName`.
- parameter className: The name of the class whose property should be renamed. This class must be present
in both the old and new Realm schemas.
- parameter oldName: The old name for the property to be renamed. There must not be a property with this name in
the class as defined by the new Realm schema.
- parameter newName: The new name for the property to be renamed. There must not be a property with this name in
the class as defined by the old Realm schema.
*/
public func renameProperty(onType typeName: String, from oldName: String, to newName: String) {
rlmMigration.renameProperty(forClass: typeName, oldName: oldName, newName: newName)
}
internal init(_ rlmMigration: RLMMigration) {
self.rlmMigration = rlmMigration
}
}
// MARK: Private Helpers
internal func accessorMigrationBlock(_ migrationBlock: @escaping MigrationBlock) -> RLMMigrationBlock {
return { migration, oldVersion in
// set all accessor classes to MigrationObject
for objectSchema in migration.oldSchema.objectSchema {
objectSchema.accessorClass = MigrationObject.self
// isSwiftClass is always `false` for object schema generated
// from the table, but we need to pretend it's from a swift class
// (even if it isn't) for the accessors to be initialized correctly.
objectSchema.isSwiftClass = true
}
for objectSchema in migration.newSchema.objectSchema {
objectSchema.accessorClass = MigrationObject.self
}
// run migration
migrationBlock(Migration(migration), oldVersion)
}
}
// MARK: Unavailable
extension Migration {
@available(*, unavailable, renamed: "enumerateObjects(ofType:_:)")
public func enumerate(_ objectClassName: String, _ block: MigrationObjectEnumerateBlock) { fatalError() }
@available(*, unavailable, renamed: "deleteData(forType:)")
public func deleteData(_ objectClassName: String) -> Bool {
fatalError()
}
@available(*, unavailable, renamed: "renameProperty(onType:from:to:)")
public func renamePropertyForClass(_ className: String, oldName: String, newName: String) { fatalError() }
}
|
mit
|
ba244f4e1b1554c9816b7e9f7fbc7411
| 41.29717 | 131 | 0.70068 | 5.026345 | false | false | false | false |
MorganCabral/swiftrekt-ios-app-dev-challenge-2015
|
app-dev-challenge/app-dev-challenge/PlayerPortraitSprite.swift
|
1
|
5307
|
//
// PlayerPortraitSprite.swift
// app-dev-challenge
//
// Created by Morgan Cabral on 2/7/15.
// Copyright (c) 2015 Team SwiftRekt. All rights reserved.
//
import UIKit
import AVFoundation
import Foundation
extension UIImage {
func getPixelColor(pos: CGPoint)-> UIColor {
var pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
var data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4
var r = CGFloat(data[pixelInfo])/255
var g = CGFloat(data[pixelInfo+1])/255
var b = CGFloat(data[pixelInfo+2])/255
var a = CGFloat(data[pixelInfo+3])/255
return UIColor(red: r, green: g, blue: b, alpha: a)
}
}
/*
* Sprite which is responsible for displaying the local player's
* image along with some kind of metronome-esque thing for when
* to cast a spell.
*/
public class PlayerPortraitSprite {
@IBOutlet weak var previewView: UIView!
@IBOutlet weak var capturedImage: UIImageView!
@IBOutlet weak var takePhotoButton: UIButton!
var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
func viewWillAppear(animated: Bool) {
captureSession = AVCaptureSession()
captureSession!.sessionPreset = AVCaptureSessionPresetPhoto
var backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error: NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if error == nil && captureSession!.canAddInput(input) {
captureSession!.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession!.canAddOutput(stillImageOutput) {
captureSession!.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer!.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer!.connection?.videoOrientation = AVCaptureVideoOrientation.Portrait
previewView.layer.addSublayer(previewLayer)
captureSession!.startRunning()
}
}
}
func viewDidAppear(animated: Bool) {
previewLayer!.frame = previewView.bounds
}
@IBAction func didPressTakePhoto(sender: AnyObject) {
if let videoConnection = stillImageOutput!.connectionWithMediaType(AVMediaTypeVideo) {
videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait
stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: {(sampleBuffer, error) in
if (sampleBuffer != nil) {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProviderCreateWithCFData(imageData)
var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
let rowCount = image!.size.width;
let columnCount = image!.size.height;
let center = CGPoint(x: columnCount/2, y: rowCount/2)
let imageColor = image!.getPixelColor(center)
// Dump RGBA values
var redval: CGFloat = 0
var greenval: CGFloat = 0
var blueval: CGFloat = 0
var alphaval: CGFloat = 0
imageColor.getRed(&redval, green: &greenval, blue: &blueval, alpha: &alphaval)
let total = redval + greenval + blueval
let avg = Float(total/3);
if( Float(redval) >= avg
&& (Float(greenval)+Float(blueval)<(avg*2)
&& Float(greenval)<(avg)))
{//red
self.capturedImage.image = image
}
else if( Float(blueval) < avg && (Float(greenval)+Float(redval)>=(avg*2)) )
{//yellow
self.capturedImage.image = image
}
else if( Float(blueval) >= avg && (Float(greenval)+Float(redval)<(avg*2)))
{//blue
self.capturedImage.image = image
}
else if( Float(greenval) >= avg && (Float(redval)+Float(blueval)<(avg*2)))
{//green
self.capturedImage.image = image
}
}
})
}
}
@IBAction func didPressTakeAnother(sender: AnyObject) {
captureSession!.startRunning()
}
}
|
mit
|
f5433fb000caf9bd4357438d4c779796
| 39.212121 | 137 | 0.573582 | 5.633758 | false | false | false | false |
MFaarkrog/Apply
|
Example/Apply/styling/StylingStylesheet.swift
|
1
|
4005
|
//
// StylingStylesheet.swift
// Apply
//
// Created by Morten Faarkrog on 6/7/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import Apply
import Foundation
struct Stylesheet {
internal static var current = Stylesheet.default
private static var currentThemeIndex = 0
private static let themes = [Stylesheet.default, Stylesheet.fun]
// MARK: -
internal static func toggleTheme() {
currentThemeIndex += 1
if currentThemeIndex >= themes.count {
currentThemeIndex = 0
}
Stylesheet.current = Stylesheet.themes[currentThemeIndex]
}
// MARK: - Default styles
private static let roundedViewStyle = UIViewStyle<UIView> {
$0.apply(cornerRadius: 10)
.apply(clipsToBounds: true)
}
private static let solidButtonSizeStyle = UIViewStyle<UIButton> {
$0.widthAnchor.constraint(equalToConstant: 200).isActive = true
$0.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
// MARK: - Themes
private static var `default`: Theme {
let colors = Theme.Colors(
primary: .black,
secondary: .darkGray,
text: .black,
textAlt: .white,
background: .white,
backgroundAlt: UIColor.darkGray
)
let fonts = Theme.Fonts(
title: UIFont.systemFont(ofSize: 22),
subtitle: UIFont.systemFont(ofSize: 16),
h1: UIFont.boldSystemFont(ofSize: 16),
h2: UIFont.boldSystemFont(ofSize: 15),
body: UIFont.systemFont(ofSize: 15)
)
let styles = Theme.Styles(
titleLabel: UIViewStyle<UILabel> {
$0.apply(font: fonts.title)
.apply(textColor: colors.text)
.apply(textAlignment: .center)
},
subtitleLabel: UIViewStyle<UILabel> {
$0.apply(font: fonts.subtitle)
.apply(textColor: colors.text)
.apply(textAlignment: .center)
.apply(numberOfLines: 0)
},
primaryActionButton: UIViewStyle<UIButton> {
$0.apply(titleFont: fonts.h1)
.apply(titleColor: colors.textAlt)
.apply(backgroundColor: colors.primary)
.apply(style: solidButtonSizeStyle)
.apply(cornerRadius: 50/2)
},
secondaryActionButton: UIViewStyle<UIButton> {
$0.apply(titleFont: fonts.h2)
.apply(titleColor: colors.secondary)
},
roundedViewStyle: roundedViewStyle,
solidButtonSizeStyle: solidButtonSizeStyle
)
return Theme(colors: colors, fonts: fonts, styles: styles)
}
private static var fun: Theme {
let colors = Theme.Colors(
primary: .red,
secondary: .orange,
text: .blue,
textAlt: .yellow,
background: .white,
backgroundAlt: .darkGray
)
let fonts = Theme.Fonts(
title: UIFont.systemFont(ofSize: 25),
subtitle: UIFont.systemFont(ofSize: 17),
h1: UIFont.boldSystemFont(ofSize: 17),
h2: UIFont.boldSystemFont(ofSize: 15),
body: UIFont.systemFont(ofSize: 15)
)
let styles = Theme.Styles(
titleLabel: UIViewStyle<UILabel> {
$0.apply(font: fonts.title)
.apply(textColor: colors.primary)
.apply(textAlignment: .center)
},
subtitleLabel: UIViewStyle<UILabel> {
$0.apply(font: fonts.subtitle)
.apply(textColor: colors.text)
.apply(textAlignment: .center)
.apply(numberOfLines: 0)
},
primaryActionButton: UIViewStyle<UIButton> {
$0.apply(titleFont: fonts.h1)
.apply(titleColor: colors.textAlt)
.apply(backgroundColor: colors.primary)
.apply(style: solidButtonSizeStyle)
.apply(cornerRadius: 50/2)
},
secondaryActionButton: UIViewStyle<UIButton> {
$0.apply(titleFont: fonts.h2)
.apply(titleColor: colors.secondary)
},
roundedViewStyle: roundedViewStyle,
solidButtonSizeStyle: solidButtonSizeStyle
)
return Theme(colors: colors, fonts: fonts, styles: styles)
}
}
|
mit
|
c0f12768997928a6ed2e28030d683589
| 27.805755 | 67 | 0.634366 | 4.201469 | false | false | false | false |
nkirby/Humber
|
_lib/HMGithub/_src/Data/DataController+UserFollowing.swift
|
1
|
1543
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import RealmSwift
import HMCore
// =======================================================
public protocol GithubAccountFollowingDataProviding {
func currentAccountFollowing() -> [GithubUserModel]
func saveAccountFollowing(userResponses responses: [GithubUserResponse], write: Bool)
}
extension DataController: GithubAccountFollowingDataProviding {
internal func currentAccountObjFollowing() -> List<GithubUser>? {
return self.currentAccountObj?.followingUsers
}
public func currentAccountFollowing() -> [GithubUserModel] {
return self.currentAccountObjFollowing()?.map { return GithubUserModel(object: $0) } ?? []
}
public func saveAccountFollowing(userResponses responses: [GithubUserResponse], write: Bool = true) {
let block = {
guard let following = self.currentAccountObjFollowing() else {
return
}
following.removeAll()
for response in responses {
self.saveUser(response: response, write: false)
if let user = self.userObj(userID: response.userID) {
following.append(user)
}
}
}
if write {
self.withRealmTransaction(block)
} else {
block()
}
}
}
|
mit
|
ab51c90635ac2778305092cf3146bc23
| 29.86 | 105 | 0.535321 | 5.844697 | false | false | false | false |
nkirby/Humber
|
_lib/HMGithub/_src/Login/GithubLoginAPI.swift
|
1
|
5434
|
// =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import UIKit
import ReactiveCocoa
import Alamofire
import Janus
import HMCore
public struct GithubLoginRequest {
public let state: String
public let requestURL: String
internal init?(clientID: String, redirectURI: String) {
let uuid = NSUUID().UUIDString
self.state = uuid
guard let redirectURI = redirectURI.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) else {
return nil
}
let urlString = "https://github.com/login/oauth/authorize?client_id=\(clientID)&redirect_uri=\(redirectURI)&scope=user,repo&state=\(uuid)"
self.requestURL = urlString
}
}
public enum GithubLoginError: ErrorType {
case Unknown
case UnableToLogin
}
public protocol GithubLoginRequestProviding {
var loginSignal: Signal<Bool, GithubLoginError> { get }
func createLoginRequest() throws -> GithubLoginRequest
}
public protocol GithubLoginURLHandling {
func handleOpenURL(url url: NSURL) -> Bool
}
public final class GithubLoginAPI: NSObject, GithubLoginRequestProviding, GithubLoginURLHandling {
public let loginSignal: Signal<Bool, GithubLoginError>
private let loginObserver: Observer<Bool, GithubLoginError>
private var currentRequest: GithubLoginRequest?
public override init() {
let (signal, observer) = Signal<Bool, GithubLoginError>.pipe()
self.loginSignal = signal
self.loginObserver = observer
super.init()
}
public func createLoginRequest() throws -> GithubLoginRequest {
let keys = Keys()
let clientID = keys.value(key: StoredKey.GithubClientID, type: String.self)
let redirectURI = keys.value(key: StoredKey.GithubRedirectURI, type: String.self)
guard let request = GithubLoginRequest(clientID: clientID, redirectURI: redirectURI) else {
throw GithubLoginError.Unknown
}
self.currentRequest = request
return request
}
public func handleOpenURL(url url: NSURL) -> Bool {
guard let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false),
let query = components.queryItems else {
return false
}
if !url.absoluteString.containsString("://authorize?") {
return false
}
for item in query {
if item.name.lowercaseString == "code" {
self.getOAuthToken(code: item.value!)
return true
}
}
return false
}
private func getOAuthToken(code code: String) {
let keys = Keys()
let clientID = keys.value(key: StoredKey.GithubClientID, type: String.self)
let clientSecret = keys.value(key: StoredKey.GithubClientSecret, type: String.self)
let redirectURI = keys.value(key: StoredKey.GithubRedirectURI, type: String.self)
guard let state = self.currentRequest?.state else {
self.loginObserver.sendFailed(.Unknown)
return
}
let params = [
"client_id": clientID,
"client_secret": clientSecret,
"redirectURI": redirectURI,
"state": state,
"code": code
]
let headers = [
"Accept": "application/json"
]
let request = Alamofire.Manager.sharedInstance.request(.POST, "https://github.com/login/oauth/access_token", parameters: params, encoding: ParameterEncoding.URL, headers: headers)
request.responseJSON { response in
switch response.result {
case .Success(let value):
if let dict = value as? JSONDictionary, let token = JSONParser.model(GithubOAuthToken.self).from(dict) {
let query = GithubKeychainStoreQuery()
KeychainStore().saveKeychainItem(token.keychainItem, forQuery: query)
self.getUserInfo(token: token)
return
}
default:
break
}
self.loginObserver.sendFailed(.UnableToLogin)
}
}
private func getUserInfo(token token: GithubOAuthToken) {
let headers = [
"Accept": "application/vnd.github.v3+json",
"Authorization": "token \(token.accessToken)"
]
let request = Alamofire.Manager.sharedInstance.request(.GET, "https://api.github.com/user", parameters: nil, encoding: ParameterEncoding.URL, headers: headers)
request.responseJSON { response in
switch response.result {
case .Success(let value):
if let dict = value as? JSONDictionary, let obj = JSONParser.model(GithubUserResponse.self).from(dict) {
self.loginObserver.sendNext(true)
ServiceController.sharedController.login(userID: obj.userID)
return
}
default:
break
}
self.loginObserver.sendFailed(.UnableToLogin)
}
}
}
|
mit
|
cd7981a9fc9d6bc224c4243ce7ae5bab
| 33.176101 | 187 | 0.586308 | 5.245174 | false | false | false | false |
yangchenghu/actor-platform
|
actor-apps/app-ios/ActorApp/View/GroupPhotoCell.swift
|
11
|
2294
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupPhotoCell: CommonCell {
// MARK: -
// MARK: Public vars
var groupNameLabel: UILabel!
var groupAvatarView: AvatarView!
private let shadow = UIImageView()
// MARK: -
// MARK: Constructors
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
groupAvatarView = AvatarView(frameSize: Int(contentView.bounds.width), type: .Square, placeholderImage: UIImage())
groupAvatarView.backgroundColor = MainAppTheme.chat.profileBgTint
groupAvatarView.clipsToBounds = true
contentView.addSubview(groupAvatarView)
shadow.image = UIImage(named: "CardTop3")
contentView.addSubview(shadow)
groupNameLabel = UILabel()
groupNameLabel.backgroundColor = UIColor.clearColor()
groupNameLabel.textColor = MainAppTheme.text.bigAvatarPrimary
groupNameLabel.font = UIFont.systemFontOfSize(20.0)
groupNameLabel.text = " "
groupNameLabel.sizeToFit()
groupNameLabel.clipsToBounds = false
contentView.addSubview(groupNameLabel)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
// MARK: Setters
func setGroupName(groupName: String) {
groupNameLabel.text = groupName
setNeedsLayout()
}
// MARK: -
// MARK: Getters
func groupName() -> String {
return groupNameLabel.text!
}
// MARK: -
// MARK: Layout subviews
override func layoutSubviews() {
super.layoutSubviews()
groupAvatarView.frame = CGRect(x: 0.0, y: -1.0, width: contentView.bounds.width, height: contentView.bounds.height + 1.0)
let groupNameLabelWidth = contentView.bounds.size.width - 30.0
groupNameLabel.frame = CGRect(x: 15.0, y: contentView.bounds.height - 33, width: groupNameLabelWidth, height: groupNameLabel.bounds.size.height)
shadow.frame = CGRect(x: 0, y: contentView.bounds.height - 6, width: contentView.bounds.width, height: 6)
}
}
|
mit
|
017758445863d29db5ccd697a27f351b
| 30.013514 | 152 | 0.640802 | 4.662602 | false | false | false | false |
xu6148152/binea_project_for_ios
|
ListerforAppleWatchiOSandOSX/Swift/ListerKit/ListUtilities.swift
|
1
|
10258
|
/*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
The `ListUtilities` class provides a suite of convenience methods for interacting with `List` objects and their associated files.
*/
import Foundation
/// An internal queue to the `ListUtilities` class that is used for `NSFileCoordinator` callbacks.
private let listUtilitiesQueue = NSOperationQueue()
public class ListUtilities {
// MARK: Properties
public class var localDocumentsDirectory: NSURL {
let documentsURL = sharedApplicationGroupContainer.URLByAppendingPathComponent("Documents", isDirectory: true)
var error: NSError?
// This will return `true` for success if the directory is successfully created, or already exists.
let success = NSFileManager.defaultManager().createDirectoryAtURL(documentsURL, withIntermediateDirectories: true, attributes: nil, error: &error)
if success {
return documentsURL
}
else {
fatalError("The shared application group documents directory doesn't exist and could not be created. Error: \(error!.localizedDescription)")
}
}
private class var sharedApplicationGroupContainer: NSURL {
let containerURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(AppConfiguration.ApplicationGroups.primary)
if containerURL == nil {
fatalError("The shared application group container is unavailable. Check your entitlements and provisioning profiles for this target. Details on proper setup can be found in the PDFs referenced from the README.")
}
return containerURL!
}
// MARK: List Handling Methods
public class func copyInitialLists() {
let defaultListURLs = NSBundle.mainBundle().URLsForResourcesWithExtension(AppConfiguration.listerFileExtension, subdirectory: "") as [NSURL]
for url in defaultListURLs {
copyURLToDocumentsDirectory(url)
}
}
public class func copyTodayList() {
let url = NSBundle.mainBundle().URLForResource(AppConfiguration.localizedTodayDocumentName, withExtension: AppConfiguration.listerFileExtension)!
copyURLToDocumentsDirectory(url)
}
public class func migrateLocalListsToCloud() {
let defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(defaultQueue) {
let fileManager = NSFileManager.defaultManager()
// Note the call to URLForUbiquityContainerIdentifier(_:) should be on a background queue.
if let cloudDirectoryURL = fileManager.URLForUbiquityContainerIdentifier(nil) {
let documentsDirectoryURL = cloudDirectoryURL.URLByAppendingPathComponent("Documents")
let localDocumentURLs = fileManager.contentsOfDirectoryAtURL(ListUtilities.localDocumentsDirectory, includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil) as? [NSURL]
if let localDocumentURLs = localDocumentURLs {
for URL in localDocumentURLs {
if URL.pathExtension == AppConfiguration.listerFileExtension {
self.makeItemUbiquitousAtURL(URL, documentsDirectoryURL: documentsDirectoryURL)
}
}
}
}
}
}
// MARK: Convenience
private class func makeItemUbiquitousAtURL(sourceURL: NSURL, documentsDirectoryURL: NSURL) {
let destinationFileName = sourceURL.lastPathComponent!
let fileManager = NSFileManager()
let destinationURL = documentsDirectoryURL.URLByAppendingPathComponent(destinationFileName)
if fileManager.isUbiquitousItemAtURL(destinationURL) ||
fileManager.fileExistsAtPath(destinationURL.path!) {
// If the file already exists in the cloud, remove the local version and return.
removeListAtURL(sourceURL, completionHandler: nil)
return
}
let defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(defaultQueue) {
fileManager.setUbiquitous(true, itemAtURL: sourceURL, destinationURL: destinationURL, error: nil)
return
}
}
class func readListAtURL(url: NSURL, completionHandler: (List?, NSError?) -> Void) {
let fileCoordinator = NSFileCoordinator()
// `url` may be a security scoped resource.
let successfulSecurityScopedResourceAccess = url.startAccessingSecurityScopedResource()
let readingIntent = NSFileAccessIntent.readingIntentWithURL(url, options: .WithoutChanges)
fileCoordinator.coordinateAccessWithIntents([readingIntent], queue: listUtilitiesQueue) { accessError in
if accessError != nil {
if successfulSecurityScopedResourceAccess {
url.stopAccessingSecurityScopedResource()
}
completionHandler(nil, accessError)
return
}
// Local variables that will be used as parameters to `completionHandler`.
var deserializedList: List?
var readError: NSError?
if let contents = NSData(contentsOfURL: readingIntent.URL, options: .DataReadingUncached, error: &readError) {
deserializedList = NSKeyedUnarchiver.unarchiveObjectWithData(contents) as? List
assert(deserializedList != nil, "The provided URL must correspond to a `List` object.")
}
if successfulSecurityScopedResourceAccess {
url.stopAccessingSecurityScopedResource()
}
completionHandler(deserializedList, readError)
}
}
class func createList(list: List, atURL url: NSURL, completionHandler: (NSError? -> Void)? = nil) {
let fileCoordinator = NSFileCoordinator()
let writingIntent = NSFileAccessIntent.writingIntentWithURL(url, options: .ForReplacing)
fileCoordinator.coordinateAccessWithIntents([writingIntent], queue: listUtilitiesQueue) { accessError in
if accessError != nil {
completionHandler?(accessError)
return
}
var error: NSError?
let seralizedListData = NSKeyedArchiver.archivedDataWithRootObject(list)
let success = seralizedListData.writeToURL(writingIntent.URL, options: .DataWritingAtomic, error: &error)
if success {
let fileAttributes = [NSFileExtensionHidden: true]
NSFileManager.defaultManager().setAttributes(fileAttributes, ofItemAtPath: writingIntent.URL.path!, error: nil)
}
completionHandler?(error)
}
}
class func removeListAtURL(url: NSURL, completionHandler: (NSError? -> Void)? = nil) {
let fileCoordinator = NSFileCoordinator()
// `url` may be a security scoped resource.
let successfulSecurityScopedResourceAccess = url.startAccessingSecurityScopedResource()
let writingIntent = NSFileAccessIntent.writingIntentWithURL(url, options: .ForDeleting)
fileCoordinator.coordinateAccessWithIntents([writingIntent], queue: listUtilitiesQueue) { accessError in
if accessError != nil {
completionHandler?(accessError)
return
}
let fileManager = NSFileManager()
var error: NSError?
fileManager.removeItemAtURL(writingIntent.URL, error: &error)
if successfulSecurityScopedResourceAccess {
url.stopAccessingSecurityScopedResource()
}
completionHandler?(error)
}
}
// MARK: Convenience
private class func copyURLToDocumentsDirectory(url: NSURL) {
let toURL = ListUtilities.localDocumentsDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
let fileCoordinator = NSFileCoordinator()
var error: NSError?
if NSFileManager().fileExistsAtPath(toURL.path!) {
// If the file already exists, don't attempt to copy the version from the bundle.
return
}
// `url` may be a security scoped resource.
let successfulSecurityScopedResourceAccess = url.startAccessingSecurityScopedResource()
let movingIntent = NSFileAccessIntent.writingIntentWithURL(url, options: .ForMoving)
let replacingIntent = NSFileAccessIntent.writingIntentWithURL(toURL, options: .ForReplacing)
fileCoordinator.coordinateAccessWithIntents([movingIntent, replacingIntent], queue: listUtilitiesQueue) { accessError in
if accessError != nil {
println("Couldn't move file: \(movingIntent.URL) to: \(replacingIntent.URL) error: \(accessError.localizedDescription).")
return
}
var success = false
let fileManager = NSFileManager()
success = fileManager.copyItemAtURL(movingIntent.URL, toURL: replacingIntent.URL, error: &error)
if success {
let fileAttributes = [NSFileExtensionHidden: true]
fileManager.setAttributes(fileAttributes, ofItemAtPath: replacingIntent.URL.path!, error: nil)
}
if successfulSecurityScopedResourceAccess {
url.stopAccessingSecurityScopedResource()
}
if !success {
// An error occured when moving `url` to `toURL`. In your app, handle this gracefully.
println("Couldn't move file: \(url) to: \(toURL).")
}
}
}
}
|
mit
|
c2a21aac94bca9989d7ac5648afe3d7b
| 41.912134 | 224 | 0.63592 | 6.054309 | false | false | false | false |
dabing1022/AlgorithmRocks
|
DataStructureAlgorithm/Playground/DataStructureAlgorithm.playground/Pages/ListNode.xcplaygroundpage/Contents.swift
|
1
|
1872
|
//: [Previous](@previous)
class Node<T: Equatable> {
var value: T?
var next: Node? = nil
init () {
}
init(val: T?) {
self.value = val
}
convenience init(val: T?, next: Node?) {
self.init(val: val)
self.next = next
}
}
class LinkedList<T: Equatable> {
var head = Node<T>()
func insert(value: T) {
if (self.head.value == nil) {
self.head.value = value
} else {
var lastNode = self.head
while (lastNode.next != nil) {
lastNode = lastNode.next!
}
let newNode = Node<T>(val: value, next: nil)
lastNode.next = newNode
}
}
func remove(value: T) {
if (self.head.value == value) {
self.head = self.head.next!
}
if (self.head.value != nil) {
var node = self.head
var preNode = Node<T>()
while (node.value != value && node.next != nil) {
preNode = node
node = node.next!
}
if (node.value == value) {
if (node.next != nil) {
preNode.next = node.next
} else {
preNode.next = nil
}
}
}
}
func printAllKeys() {
var current = self.head
while (current.next != nil) {
print("value is \(current.value)")
current = current.next!
}
print("value is \(current.value)")
}
}
var myLinkedList = LinkedList<Int>()
myLinkedList.insert(10)
myLinkedList.insert(20)
myLinkedList.insert(30)
myLinkedList.insert(40)
myLinkedList.insert(50)
myLinkedList.insert(60)
myLinkedList.printAllKeys()
myLinkedList.remove(30)
myLinkedList.printAllKeys()
//: [Next](@next)
|
mit
|
52d61af7ddbf2bbf0c02089413f212b8
| 22.696203 | 61 | 0.481838 | 3.924528 | false | false | false | false |
ProfileCreator/ProfileCreator
|
ProfileCreator/Highlightr/Pod/Classes/CodeAttributedString.swift
|
1
|
6668
|
//
// CodeAttributedString.swift
// Pods
//
// Created by Illanes, J.P. on 4/19/16.
//
//
import Foundation
#if os(OSX)
import AppKit
#endif
/// Highlighting Delegate
@objc public protocol HighlightDelegate
{
/**
If this method returns *false*, the highlighting process will be skipped for this range.
- parameter range: NSRange
- returns: Bool
*/
@objc optional func shouldHighlight(_ range:NSRange) -> Bool
/**
Called after a range of the string was highlighted, if there was an error **success** will be *false*.
- parameter range: NSRange
- parameter success: Bool
*/
@objc optional func didHighlight(_ range:NSRange, success: Bool)
}
/// NSTextStorage subclass. Can be used to dynamically highlight code.
open class CodeAttributedString : NSTextStorage
{
/// Internal Storage
let stringStorage = NSTextStorage()
/// Highlightr instace used internally for highlighting. Use this for configuring the theme.
public let highlightr: Highlightr
/// This object will be notified before and after the highlighting.
open var highlightDelegate : HighlightDelegate?
/**
Initialize the CodeAttributedString
- parameter highlightr: The highlightr instance to use. Defaults to `Highlightr()`.
*/
public init(highlightr: Highlightr = Highlightr()!)
{
self.highlightr = highlightr
super.init()
setupListeners()
}
/// Initialize the CodeAttributedString
public override init() {
self.highlightr = Highlightr()!
super.init()
setupListeners()
}
/// Initialize the CodeAttributedString
required public init?(coder aDecoder: NSCoder)
{
self.highlightr = Highlightr()!
super.init(coder: aDecoder)
setupListeners()
}
#if os(OSX)
/// Initialize the CodeAttributedString
required public init?(pasteboardPropertyList propertyList: Any, ofType type: NSPasteboard.PasteboardType)
{
self.highlightr = Highlightr()!
super.init(pasteboardPropertyList: propertyList, ofType: type)
setupListeners()
}
#endif
/// Language syntax to use for highlighting. Providing nil will disable highlighting.
open var language : String?
{
didSet
{
highlight(NSMakeRange(0, stringStorage.length))
}
}
/// Returns a standard String based on the current one.
open override var string: String
{
get
{
return stringStorage.string
}
}
/**
Returns the attributes for the character at a given index.
- parameter location: Int
- parameter range: NSRangePointer
- returns: Attributes
*/
open override func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [AttributedStringKey : Any]
{
return stringStorage.attributes(at: location, effectiveRange: range)
}
/**
Replaces the characters at the given range with the provided string.
- parameter range: NSRange
- parameter str: String
*/
open override func replaceCharacters(in range: NSRange, with str: String)
{
stringStorage.replaceCharacters(in: range, with: str)
self.edited(TextStorageEditActions.editedCharacters, range: range, changeInLength: (str as NSString).length - range.length)
}
/**
Sets the attributes for the characters in the specified range to the given attributes.
- parameter attrs: [String : AnyObject]
- parameter range: NSRange
*/
open override func setAttributes(_ attrs: [AttributedStringKey : Any]?, range: NSRange)
{
stringStorage.setAttributes(attrs, range: range)
self.edited(TextStorageEditActions.editedAttributes, range: range, changeInLength: 0)
}
/// Called internally everytime the string is modified.
open override func processEditing()
{
super.processEditing()
if language != nil {
if self.editedMask.contains(.editedCharacters)
{
let string = (self.string as NSString)
let range = string.paragraphRange(for: editedRange)
highlight(range)
}
}
}
func highlight(_ range: NSRange)
{
if(language == nil)
{
return;
}
if let highlightDelegate = highlightDelegate
{
let shouldHighlight : Bool? = highlightDelegate.shouldHighlight?(range)
if(shouldHighlight != nil && !shouldHighlight!)
{
return;
}
}
let string = (self.string as NSString)
let line = string.substring(with: range)
DispatchQueue.global().async
{
let tmpStrg = self.highlightr.highlight(line, as: self.language!)
DispatchQueue.main.async(execute: {
//Checks to see if this highlighting is still valid.
if((range.location + range.length) > self.stringStorage.length)
{
self.highlightDelegate?.didHighlight?(range, success: false)
return;
}
if(tmpStrg?.string != self.stringStorage.attributedSubstring(from: range).string)
{
self.highlightDelegate?.didHighlight?(range, success: false)
return;
}
self.beginEditing()
tmpStrg?.enumerateAttributes(in: NSMakeRange(0, (tmpStrg?.length)!), options: [], using: { (attrs, locRange, stop) in
var fixedRange = NSMakeRange(range.location+locRange.location, locRange.length)
fixedRange.length = (fixedRange.location + fixedRange.length < string.length) ? fixedRange.length : string.length-fixedRange.location
fixedRange.length = (fixedRange.length >= 0) ? fixedRange.length : 0
self.stringStorage.setAttributes(attrs, range: fixedRange)
})
self.endEditing()
self.edited(TextStorageEditActions.editedAttributes, range: range, changeInLength: 0)
self.highlightDelegate?.didHighlight?(range, success: true)
})
}
}
func setupListeners()
{
highlightr.themeChanged =
{ _ in
self.highlight(NSMakeRange(0, self.stringStorage.length))
}
}
}
|
mit
|
ee27ac7f261ddb051f33e50d075fb688
| 29.87037 | 153 | 0.59988 | 5.093965 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor
|
TranslationEditor/USXBookFinder.swift
|
1
|
1437
|
//
// USXBookFinder.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 13.4.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import Foundation
// This parser finds and interprets the book elements from an usx document
class USXBookFinder: NSObject, XMLParserDelegate
{
// ATTRIBUTES ----------------
// Code + identifier
private(set) var collectedBookInfo = [(String, String)]()
private var openBookCode: String?
private var collectedIdentifier = ""
// IMPLEMENTED METHODS --------
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:])
{
guard elementName.lowercased() == "book" else
{
return
}
guard let code = attributeDict["code"] else
{
print("ERROR: Book element without code attribute")
return
}
openBookCode = code
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?)
{
guard let openBookCode = openBookCode else
{
return
}
guard elementName.lowercased() == "book" else
{
return
}
collectedBookInfo.add((openBookCode, collectedIdentifier))
self.openBookCode = nil
collectedIdentifier = ""
}
func parser(_ parser: XMLParser, foundCharacters string: String)
{
if openBookCode != nil
{
collectedIdentifier += string
}
}
}
|
mit
|
63f39ec7693602b2ef6e760124d21568
| 21.092308 | 174 | 0.690111 | 3.809019 | false | false | false | false |
tonyli508/ObjectStorage
|
ObjectStorage/ObjectStorage/CoreData/StorageProviderService.swift
|
1
|
13080
|
//
// CoreDataService.swift
// ObjectStorage
//
// Created by Li Jiantang on 12/05/2015.
// Copyright (c) 2015 Carma. All rights reserved.
//
import Foundation
import CoreData
/// United protocol for append object to NSOrderedSet and NSSet
protocol AppendableSet: class {
func addObject(object: AnyObject)
}
// make NSmutableOrderedSet appendable, will be very useful for ordered CoreData objects
extension NSMutableOrderedSet: AppendableSet {
}
// make NSMutableSet appendable
extension NSMutableSet: AppendableSet {
}
/**
@class StorageProviderService
@abstract Storage Privder using CoreData to store all the datas
*/
class StorageProviderService: ObjectStorageProviderService, DataConverter {
// Core data store
private var coreDataStore: CoreDataStore
private let coreDataModelFileName: String
private let bundle: NSBundle
/// core data helper
private lazy var coreDataHelper: CoreDataHelper = {
var coreDataHelper = CoreDataHelper(cdstore: self.coreDataStore)
return coreDataHelper
}()
/**
Init StoreProviderService with CoreData model file name and NSBundle
- parameter coreDataModelFileName: CoreData model file name (without extention name)
- parameter inBundle: NSBundle, indicate where the file in
*/
init(coreDataModelFileName: String, inBundle: NSBundle = NSBundle.mainBundle()) {
self.coreDataModelFileName = coreDataModelFileName
self.bundle = inBundle
self.coreDataStore = CoreDataStore(storeName: coreDataModelFileName, inBundle: inBundle)
}
typealias T = NSManagedObject
// MARK: - helper functions
/**
Convert Model to json dictionary
- parameter model: Model
- returns: json dictionary
*/
func convert(model: NSManagedObject) -> [String : AnyObject] {
let entity = model.entity
var dict = [String: AnyObject]()
for (name, _) in entity.attributesByName {
dict[name] = model.valueForKey(name)
}
for (name, _) in entity.relationshipsByName {
if let submodel = model.valueForKey(name) as? NSManagedObject {
dict[name] = self.convert(submodel)
} else if let array = model.valueForKey(name) as? NSSet {
convertSet(array, forDictionary: &dict, usingName: name)
} else if let array = model.valueForKey(name) as? NSOrderedSet {
convertSet(array, forDictionary: &dict, usingName: name)
}
}
return dict
}
/**
Convert SequenceType to Array, and add array to dictionary using give name
- parameter array: SequenceType
- parameter forDictionary: dictionary that will add array to
- parameter usingName: key name for the array in dictionary
*/
private func convertSet<T: SequenceType>(array: T, inout forDictionary: [String: AnyObject], usingName: String) {
var newArray = [AnyObject]()
for obj in array {
if let obj = obj as? NSManagedObject {
newArray.append(self.convert(obj))
}
}
forDictionary[usingName] = newArray
}
/**
Verify current model if structure is good for storage service
- parameter model: Model
- returns: Bool, is valid or not
*/
private func verify(model: Model) -> Bool {
if coreDataHelper.backgroundContext == nil || coreDataHelper.managedObjectContext == nil || model.isDataValid() == false {
return false
}
return true
}
/**
Set attributes from json to NSManagedObject
- parameter json: json dictionary
- parameter destination: NSManagedObject
*/
private func setAttributesFrom(json: [String: AnyObject], To destination: NSManagedObject) {
for (name, _) in destination.entity.attributesByName {
let key = name
if let value: AnyObject = json[key] {
destination.setValue(value, forKey: key)
}
}
}
/**
Set relationships from json to NSManagedObject
- parameter json: json dictionary
- parameter destination: NSManagedObject
*/
private func setRelationshipsFrom(json: [String: AnyObject], To destination: NSManagedObject) {
for (name, relationshipDesc) in destination.entity.relationshipsByName {
let key = name
if let relateJson = json[key] as? [String: AnyObject] {
if let entityDesc = relationshipDesc.destinationEntity {
var managedObject = destination.valueForKey(key) as? NSManagedObject
if managedObject == nil {
managedObject = NSManagedObject(entity: entityDesc, insertIntoManagedObjectContext: coreDataHelper.backgroundContext!)
}
setAllPropertiesFrom(relateJson, To: managedObject!)
destination.setValue(managedObject!, forKey: key)
}
} else if let relateJson = json[key] as? [AnyObject] {
if let entityDesc = relationshipDesc.destinationEntity {
var array: AppendableSet
if relationshipDesc.ordered {
array = destination.mutableOrderedSetValueForKey(key)
} else {
array = destination.mutableSetValueForKey(key)
}
for subJson in relateJson {
if let subJson = subJson as? [String: AnyObject] {
let managedObject = NSManagedObject(entity: entityDesc, insertIntoManagedObjectContext: coreDataHelper.backgroundContext!)
setAllPropertiesFrom(subJson, To: managedObject)
array.addObject(managedObject)
}
}
destination.setValue(array, forKey: key)
}
}
}
}
// set all properties from json to managedObject, include attributes and relationships
private func setAllPropertiesFrom(json: [String: AnyObject], To destination: NSManagedObject) {
setAttributesFrom(json, To: destination)
setRelationshipsFrom(json, To: destination)
}
// MARK: - CURD functions
/**
create new model data
- parameter model: Model
- returns: Bool, if model created or not
*/
func create(model: Model) -> Bool {
if !verify(model) {
return false
}
let newData: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(model.identifier.modelName, inManagedObjectContext: coreDataHelper.backgroundContext!)
let json = model.toJSON()
self.setAllPropertiesFrom(json, To: newData)
coreDataHelper.saveContext(coreDataHelper.backgroundContext!)
print("Inserted new data for \(model) ")
return true
}
/**
read model data
- parameter model: Model
- returns: Model with original type
*/
func read<T: Model>(model: T) -> T? {
if !verify(model) {
return nil
}
let fReq = NSFetchRequest(entityName: model.identifier.modelName)
let query = model.getQuery()
if !query.isEmpty {
fReq.predicate = NSPredicate(format: query)
}
print("identifier: \(model.identifier.modelName), query: \(query)")
fReq.returnsObjectsAsFaults = false
if let result = try? coreDataHelper.managedObjectContext!.executeFetchRequest(fReq) {
for resultItem in result {
let resData = resultItem as! NSManagedObject
print("Fetched core data for \(model.identifier.modelName) with query \(query) sucess, model: \(resData)")
return model.fromJSON(self.convert(resData)) as? T
}
}
return nil
}
/**
udapte existing model data
- parameter model: Model
- returns: Bool, whether updated or not
*/
func update(model: Model) -> Bool {
return update(model, ignoreEmptyValues: false)
}
/**
update existing model data but ignore empty values like empty string, array or dictionary
- parameter model: Model
- returns: Bool, whether updated or not
*/
func updateIgnoreEmptyValues(model: Model) -> Bool {
return update(model, ignoreEmptyValues: true)
}
/**
update existing model data with setting ignore empty values like empty string
- parameter model: Model
- parameter ignoreEmptyValues: ignore empty values flag, like empty string, array or dictionary
- returns: Bool, whether updated or not
*/
private func update(model: Model, ignoreEmptyValues: Bool) -> Bool {
if !verify(model) {
return false
}
let fReq: NSFetchRequest = NSFetchRequest(entityName: model.identifier.modelName)
let query = model.getQuery()
if !query.isEmpty {
fReq.predicate = NSPredicate(format: query)
}
print("identifier: \(model.identifier.modelName), query: \(query)")
fReq.returnsObjectsAsFaults = false
guard let result = try? coreDataHelper.backgroundContext!.executeFetchRequest(fReq) where result.count > 0 else {
print("Update core data for \(model.identifier.modelName) with query \(query) failed")
return false
}
let storedData : NSManagedObject = result.first as! NSManagedObject
var json = model.toJSON()
if ignoreEmptyValues {
json = removeEmptyValues(json)
}
setAllPropertiesFrom(json, To: storedData)
print("json: \(json)")
coreDataHelper.saveContext(coreDataHelper.backgroundContext!)
return true
}
/**
Remove empty values from json object
- parameter json: json object [String: AnyObject]
- returns: [String: AnyObject]
*/
private func removeEmptyValues(json: [String: AnyObject]) -> [String: AnyObject] {
var jsonDict = json
let keys = json.keys
for key in keys {
let jsonValue = json[key]
if jsonValue == nil || jsonValue&.isEmpty || isEmptyArray(jsonValue) || isEmptyDictionary(jsonValue) {
jsonDict.removeValueForKey(key)
}
}
return jsonDict
}
// check if json value is an empty array
private func isEmptyArray(jsonValue: AnyObject?) -> Bool {
return jsonValue == nil || (jsonValue! is [AnyObject]) && (jsonValue! as! [AnyObject]).count == 0
}
// check if json value is an empty dictionary
private func isEmptyDictionary(jsonValue: AnyObject?) -> Bool {
return jsonValue == nil || (jsonValue! is [String: AnyObject]) && (jsonValue! as! [String: AnyObject]).count == 0
}
/**
delete model data
- parameter model: Model
- returns: Bool
*/
func delete(model: Model) -> Bool {
if !verify(model) {
return false
}
let fReq: NSFetchRequest = NSFetchRequest(entityName: model.identifier.modelName)
let query = model.getQuery()
if !query.isEmpty {
fReq.predicate = NSPredicate(format: query)
}
fReq.returnsObjectsAsFaults = false
if let result = try? coreDataHelper.backgroundContext!.executeFetchRequest(fReq) {
for resultItem in result {
let data = resultItem as! NSManagedObject
coreDataHelper.backgroundContext!.deleteObject(data)
print("Delete core data \(model.identifier.modelName) \(query) ")
}
coreDataHelper.saveContext(coreDataHelper.backgroundContext!)
}
return true
}
// MARK: - clean up
//clear all model datas
func clear() {
coreDataStore.removeModelData()
coreDataStore = CoreDataStore(storeName: coreDataModelFileName, inBundle: bundle)
coreDataHelper = CoreDataHelper(cdstore: self.coreDataStore)
}
}
|
mit
|
61376513c3fe1953dd08d56232916402
| 31.298765 | 178 | 0.578746 | 5.509688 | false | false | false | false |
iossocket/BabyMoment
|
BabyMoment/DoubleMomentCell.swift
|
1
|
1661
|
//
// DoubleMomentCell.swift
// BabyMoment
//
// Created by Xueliang Zhu on 8/25/16.
// Copyright © 2016 kotlinchina. All rights reserved.
//
import UIKit
class DoubleMomentCell: UITableViewCell, UITextFieldDelegate {
@IBOutlet weak var day: UILabel!
@IBOutlet weak var yearMonth: UILabel!
@IBOutlet weak var time: UILabel!
@IBOutlet weak var heroImage: UIImageView!
@IBOutlet weak var secondImage: UIImageView!
@IBOutlet weak var timeAgo: UILabel!
@IBOutlet weak var textField: UITextField!
var saveAction: ((content: String) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
textField.delegate = self
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
saveAction?(content: textField.text ?? "")
textField.resignFirstResponder()
return true
}
func setDate(date: NSDate) {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd"
day.text = formatter.stringFromDate(date)
formatter.dateFormat = "yyyy.MM"
yearMonth.text = formatter.stringFromDate(date)
let birday:String = NSUserDefaults.standardUserDefaults()
.stringForKey("kBirthday")!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let birdayDate:NSDate = dateFormatter.dateFromString(birday)!
let oldText:String = date.howOld(birdayDate)
time.text = oldText;
}
func setUploadedAt(date: NSDate) {
let timeAgoText:String = date.timeAgoSinceNow()
timeAgo.text = timeAgoText
}
}
|
mit
|
6d34202770dfbd860b05087a9d7b58cc
| 29.181818 | 69 | 0.653012 | 4.623955 | false | false | false | false |
omochi/numsw
|
Sources/numsw/NDArray/NDArrayArithmeticAccelerate.swift
|
1
|
9102
|
#if os(iOS) || os(OSX)
import Accelerate
// unary
public prefix func -(arg: NDArray<Float>) -> NDArray<Float> {
return unaryMinusAccelerate(arg)
}
public prefix func -(arg: NDArray<Double>) -> NDArray<Double> {
return unaryMinusAccelerate(arg)
}
// NDArray and scalar
public func +(lhs: NDArray<Float>, rhs: Float) -> NDArray<Float> {
return addAccelerate(lhs, rhs)
}
public func +(lhs: Float, rhs: NDArray<Float>) -> NDArray<Float> {
return addAccelerate(rhs, lhs)
}
public func +(lhs: NDArray<Double>, rhs: Double) -> NDArray<Double> {
return addAccelerate(lhs, rhs)
}
public func +(lhs: Double, rhs: NDArray<Double>) -> NDArray<Double> {
return addAccelerate(rhs, lhs)
}
public func -(lhs: NDArray<Float>, rhs: Float) -> NDArray<Float> {
return addAccelerate(lhs, -rhs)
}
public func -(lhs: Float, rhs: NDArray<Float>) -> NDArray<Float> {
return addAccelerate(-rhs, lhs)
}
public func -(lhs: NDArray<Double>, rhs: Double) -> NDArray<Double> {
return addAccelerate(lhs, -rhs)
}
public func -(lhs: Double, rhs: NDArray<Double>) -> NDArray<Double> {
return addAccelerate(-rhs, lhs)
}
public func *(lhs: NDArray<Float>, rhs: Float) -> NDArray<Float> {
return multiplyAccelerate(lhs, rhs)
}
public func *(lhs: Float, rhs: NDArray<Float>) -> NDArray<Float> {
return multiplyAccelerate(rhs, lhs)
}
public func *(lhs: NDArray<Double>, rhs: Double) -> NDArray<Double> {
return multiplyAccelerate(lhs, rhs)
}
public func *(lhs: Double, rhs: NDArray<Double>) -> NDArray<Double> {
return multiplyAccelerate(rhs, lhs)
}
public func /(lhs: NDArray<Float>, rhs: Float) -> NDArray<Float> {
return divideAccelerate(lhs, rhs)
}
public func /(lhs: Float, rhs: NDArray<Float>) -> NDArray<Float> {
return divideAccelerate(lhs, rhs)
}
public func /(lhs: NDArray<Double>, rhs: Double) -> NDArray<Double> {
return divideAccelerate(lhs, rhs)
}
public func /(lhs: Double, rhs: NDArray<Double>) -> NDArray<Double> {
return divideAccelerate(lhs, rhs)
}
// NDArray and NDArray
public func +(lhs: NDArray<Float>, rhs: NDArray<Float>) -> NDArray<Float> {
return addAccelerate(lhs, rhs)
}
public func +(lhs: NDArray<Double>, rhs: NDArray<Double>) -> NDArray<Double> {
return addAccelerate(lhs, rhs)
}
public func -(lhs: NDArray<Float>, rhs: NDArray<Float>) -> NDArray<Float> {
return subtractAccelerate(lhs, rhs)
}
public func -(lhs: NDArray<Double>, rhs: NDArray<Double>) -> NDArray<Double> {
return subtractAccelerate(lhs, rhs)
}
public func *(lhs: NDArray<Float>, rhs: NDArray<Float>) -> NDArray<Float> {
return multiplyAccelerate(lhs, rhs)
}
public func *(lhs: NDArray<Double>, rhs: NDArray<Double>) -> NDArray<Double> {
return multiplyAccelerate(lhs, rhs)
}
public func /(lhs: NDArray<Float>, rhs: NDArray<Float>) -> NDArray<Float> {
return divideAccelerate(lhs, rhs)
}
public func /(lhs: NDArray<Double>, rhs: NDArray<Double>) -> NDArray<Double> {
return divideAccelerate(lhs, rhs)
}
// unary
private func applyVDspFunc<T>(_ arg: NDArray<T>,
_ vDspFunc: (UnsafePointer<T>, vDSP_Stride, UnsafeMutablePointer<T>, vDSP_Stride, vDSP_Length)->Void) -> NDArray<T> {
let out = UnsafeMutablePointer<T>.allocate(capacity: arg.elements.count)
defer { out.deallocate(capacity: arg.elements.count) }
vDspFunc(arg.elements, 1,
out, 1, vDSP_Length(arg.elements.count))
return NDArray(shape: arg.shape,
elements: Array(UnsafeBufferPointer(start: out, count: arg.elements.count)))
}
func unaryMinusAccelerate(_ arg: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(arg, vDSP_vneg)
}
func unaryMinusAccelerate(_ arg: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(arg, vDSP_vnegD)
}
// NDArray and scalar
private func applyVDspFunc<T>(_ lhs: NDArray<T>,
_ rhs: T,
_ vDspFunc: (UnsafePointer<T>, vDSP_Stride, UnsafePointer<T>, UnsafeMutablePointer<T>, vDSP_Stride, vDSP_Length)->Void) -> NDArray<T> {
let out = UnsafeMutablePointer<T>.allocate(capacity: lhs.elements.count)
defer { out.deallocate(capacity: lhs.elements.count) }
var rhs = rhs
vDspFunc(lhs.elements, 1,
&rhs,
out, 1, vDSP_Length(lhs.elements.count))
return NDArray(shape: lhs.shape,
elements: Array(UnsafeBufferPointer(start: out, count: lhs.elements.count)))
}
private func applyVDspFunc<T>(_ lhs: T,
_ rhs: NDArray<T>,
_ vDspFunc: (UnsafePointer<T>, UnsafePointer<T>, vDSP_Stride, UnsafeMutablePointer<T>, vDSP_Stride, vDSP_Length)->Void) -> NDArray<T> {
let out = UnsafeMutablePointer<T>.allocate(capacity: rhs.elements.count)
defer { out.deallocate(capacity: rhs.elements.count) }
var lhs = lhs
vDspFunc(&lhs,
rhs.elements, 1,
out, 1, vDSP_Length(rhs.elements.count))
return NDArray(shape: rhs.shape,
elements: Array(UnsafeBufferPointer(start: out, count: rhs.elements.count)))
}
func addAccelerate(_ lhs: NDArray<Float>, _ rhs: Float) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_vsadd)
}
func addAccelerate(_ lhs: NDArray<Double>, _ rhs: Double) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_vsaddD)
}
func multiplyAccelerate(_ lhs: NDArray<Float>, _ rhs: Float) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_vsmul)
}
func multiplyAccelerate(_ lhs: NDArray<Double>, _ rhs: Double) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_vsmulD)
}
func divideAccelerate(_ lhs: NDArray<Float>, _ rhs: Float) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_vsdiv)
}
func divideAccelerate(_ lhs: Float, _ rhs: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_svdiv)
}
func divideAccelerate(_ lhs: NDArray<Double>, _ rhs: Double) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_vsdivD)
}
func divideAccelerate(_ lhs: Double, _ rhs: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_svdivD)
}
// NDArray and NDArray
private func applyVDspFunc<T>(_ lhs: NDArray<T>,
_ rhs: NDArray<T>,
_ vDspFunc: (UnsafePointer<T>, vDSP_Stride, UnsafePointer<T>, vDSP_Stride, UnsafeMutablePointer<T>, vDSP_Stride, vDSP_Length)->Void) -> NDArray<T> {
precondition(lhs.shape == rhs.shape, "Two NDArrays have incompatible shape.")
let out = UnsafeMutablePointer<T>.allocate(capacity: lhs.elements.count)
defer { out.deallocate(capacity: lhs.elements.count) }
vDspFunc(lhs.elements, 1,
rhs.elements, 1,
out, 1,
vDSP_Length(lhs.elements.count))
return NDArray(shape: lhs.shape,
elements: Array(UnsafeBufferPointer(start: out, count: lhs.elements.count)))
}
func addAccelerate(_ lhs: NDArray<Float>, _ rhs: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_vadd)
}
func addAccelerate(_ lhs: NDArray<Double>, _ rhs: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_vaddD)
}
func subtractAccelerate(_ lhs: NDArray<Float>, _ rhs: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(rhs, lhs, vDSP_vsub)
}
func subtractAccelerate(_ lhs: NDArray<Double>, _ rhs: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(rhs, lhs, vDSP_vsubD)
}
func multiplyAccelerate(_ lhs: NDArray<Float>, _ rhs: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(lhs, rhs, vDSP_vmul)
}
func multiplyAccelerate(_ lhs: NDArray<Double>, _ rhs: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(lhs, rhs, vDSP_vmulD)
}
func divideAccelerate(_ lhs: NDArray<Float>, _ rhs: NDArray<Float>) -> NDArray<Float> {
return applyVDspFunc(rhs, lhs, vDSP_vdiv)
}
func divideAccelerate(_ lhs: NDArray<Double>, _ rhs: NDArray<Double>) -> NDArray<Double> {
return applyVDspFunc(rhs, lhs, vDSP_vdivD)
}
#endif
|
mit
|
aa829f47d13d8806ab42e7348c69f544
| 34.834646 | 179 | 0.588552 | 4.068842 | false | false | false | false |
hooman/swift
|
stdlib/public/core/VarArgs.swift
|
3
|
23427
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A type whose instances can be encoded, and appropriately passed, as
/// elements of a C `va_list`.
///
/// You use this protocol to present a native Swift interface to a C "varargs"
/// API. For example, a program can import a C API like the one defined here:
///
/// ~~~c
/// int c_api(int, va_list arguments)
/// ~~~
///
/// To create a wrapper for the `c_api` function, write a function that takes
/// `CVarArg` arguments, and then call the imported C function using the
/// `withVaList(_:_:)` function:
///
/// func swiftAPI(_ x: Int, arguments: CVarArg...) -> Int {
/// return withVaList(arguments) { c_api(x, $0) }
/// }
///
/// Swift only imports C variadic functions that use a `va_list` for their
/// arguments. C functions that use the `...` syntax for variadic arguments
/// are not imported, and therefore can't be called using `CVarArg` arguments.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Note: Declaring conformance to the `CVarArg` protocol for types defined
/// outside the standard library is not supported.
public protocol CVarArg {
// Note: the protocol is public, but its requirement is stdlib-private.
// That's because there are APIs operating on CVarArg instances, but
// defining conformances to CVarArg outside of the standard library is
// not supported.
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
var _cVarArgEncoding: [Int] { get }
}
/// Floating point types need to be passed differently on x86_64
/// systems. CoreGraphics uses this to make CGFloat work properly.
public // SPI(CoreGraphics)
protocol _CVarArgPassedAsDouble: CVarArg {}
/// Some types require alignment greater than Int on some architectures.
public // SPI(CoreGraphics)
protocol _CVarArgAligned: CVarArg {
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
var _cVarArgAlignment: Int { get }
}
#if !_runtime(_ObjC)
/// Some pointers require an alternate object to be retained. The object
/// that is returned will be used with _cVarArgEncoding and held until
/// the closure is complete. This is required since autoreleased storage
/// is not available on all platforms.
public protocol _CVarArgObject: CVarArg {
/// Returns the alternate object that should be encoded.
var _cVarArgObject: CVarArg { get }
}
#endif
#if arch(x86_64)
@usableFromInline
internal let _countGPRegisters = 6
// Note to future visitors concerning the following SSE register count.
//
// AMD64-ABI section 3.5.7 says -- as recently as v0.99.7, Nov 2014 -- to make
// room in the va_list register-save area for 16 SSE registers (XMM0..15). This
// may seem surprising, because the calling convention of that ABI only uses the
// first 8 SSE registers for argument-passing; why save the other 8?
//
// According to a comment in X86_64ABIInfo::EmitVAArg, in clang's TargetInfo,
// the AMD64-ABI spec is itself in error on this point ("NOTE: 304 is a typo").
// This comment (and calculation) in clang has been there since varargs support
// was added in 2009, in rev be9eb093; so if you're about to change this value
// from 8 to 16 based on reading the spec, probably the bug you're looking for
// is elsewhere.
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 2
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + _countFPRegisters * _fpRegisterWords
#elseif arch(s390x)
@usableFromInline
internal let _countGPRegisters = 16
@usableFromInline
internal let _registerSaveWords = _countGPRegisters
#elseif arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows))
// ARM Procedure Call Standard for aarch64. (IHI0055B)
// The va_list type may refer to any parameter in a parameter list may be in one
// of three memory locations depending on its type and position in the argument
// list :
// 1. GP register save area x0 - x7
// 2. 128-bit FP/SIMD register save area q0 - q7
// 3. Stack argument area
@usableFromInline
internal let _countGPRegisters = 8
@usableFromInline
internal let _countFPRegisters = 8
@usableFromInline
internal let _fpRegisterWords = 16 / MemoryLayout<Int>.size
@usableFromInline
internal let _registerSaveWords = _countGPRegisters + (_countFPRegisters * _fpRegisterWords)
#endif
#if arch(s390x)
@usableFromInline
internal typealias _VAUInt = CUnsignedLongLong
@usableFromInline
internal typealias _VAInt = Int64
#else
@usableFromInline
internal typealias _VAUInt = CUnsignedInt
@usableFromInline
internal typealias _VAInt = Int32
#endif
/// Invokes the given closure with a C `va_list` argument derived from the
/// given array of arguments.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withVaList(_:_:)`. Do not store or return the pointer for
/// later use.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameters:
/// - args: An array of arguments to convert to a C `va_list` pointer.
/// - body: A closure with a `CVaListPointer` parameter that references the
/// arguments passed as `args`. If `body` has a return value, that value
/// is also used as the return value for the `withVaList(_:)` function.
/// The pointer argument is valid only for the duration of the function's
/// execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // c-abi
public func withVaList<R>(_ args: [CVarArg],
_ body: (CVaListPointer) -> R) -> R {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
return _withVaList(builder, body)
}
/// Invoke `body` with a C `va_list` argument derived from `builder`.
@inlinable // c-abi
internal func _withVaList<R>(
_ builder: __VaListBuilder,
_ body: (CVaListPointer) -> R
) -> R {
let result = body(builder.va_list())
_fixLifetime(builder)
return result
}
#if _runtime(_ObjC)
// Excluded due to use of dynamic casting and Builtin.autorelease, neither
// of which correctly work without the ObjC Runtime right now.
// See rdar://problem/18801510
/// Returns a `CVaListPointer` that is backed by autoreleased storage, built
/// from the given array of arguments.
///
/// You should prefer `withVaList(_:_:)` instead of this function. In some
/// uses, such as in a `class` initializer, you may find that the language
/// rules do not allow you to use `withVaList(_:_:)` as intended.
///
/// If you need to pass an optional pointer as a `CVarArg` argument, use the
/// `Int(bitPattern:)` initializer to interpret the optional pointer as an
/// `Int` value, which has the same C variadic calling conventions as a pointer
/// on all supported platforms.
///
/// - Parameter args: An array of arguments to convert to a C `va_list`
/// pointer.
/// - Returns: A pointer that can be used with C functions that take a
/// `va_list` argument.
@inlinable // c-abi
public func getVaList(_ args: [CVarArg]) -> CVaListPointer {
let builder = __VaListBuilder()
for a in args {
builder.append(a)
}
// FIXME: Use some Swift equivalent of NS_RETURNS_INNER_POINTER if we get one.
Builtin.retain(builder)
Builtin.autorelease(builder)
return builder.va_list()
}
#endif
@inlinable // c-abi
public func _encodeBitsAsWords<T>(_ x: T) -> [Int] {
let result = [Int](
repeating: 0,
count: (MemoryLayout<T>.size + MemoryLayout<Int>.size - 1) / MemoryLayout<Int>.size)
_internalInvariant(!result.isEmpty)
var tmp = x
// FIXME: use UnsafeMutablePointer.assign(from:) instead of memcpy.
_memcpy(dest: UnsafeMutablePointer(result._baseAddressIfContiguous!),
src: UnsafeMutablePointer(Builtin.addressof(&tmp)),
size: UInt(MemoryLayout<T>.size))
return result
}
// CVarArg conformances for the integer types. Everything smaller
// than an Int32 must be promoted to Int32 or CUnsignedInt before
// encoding.
// Signed types
extension Int: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension Bool: CVarArg {
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self ? 1:0))
}
}
extension Int64: CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension Int32: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int16: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
extension Int8: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAInt(self))
}
}
// Unsigned types
extension UInt: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UInt64: CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
extension UInt32: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt16: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension UInt8: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(_VAUInt(self))
}
}
extension OpaquePointer: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafePointer: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
extension UnsafeMutablePointer: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#if _runtime(_ObjC)
extension AutoreleasingUnsafeMutablePointer: CVarArg {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
}
#endif
extension Float: _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(Double(self))
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: Double(self))
}
}
extension Double: _CVarArgPassedAsDouble, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // c-abi
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // c-abi
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
extension Float80: CVarArg, _CVarArgAligned {
/// Transform `self` into a series of machine words that can be
/// appropriately interpreted by C varargs.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgEncoding: [Int] {
return _encodeBitsAsWords(self)
}
/// Returns the required alignment in bytes of
/// the value returned by `_cVarArgEncoding`.
@inlinable // FIXME(sil-serialize-all)
public var _cVarArgAlignment: Int {
// FIXME: alignof differs from the ABI alignment on some architectures
return MemoryLayout.alignment(ofValue: self)
}
}
#endif
#if (arch(x86_64) && !os(Windows)) || arch(s390x) || (arch(arm64) && !(os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Windows)))
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
#if arch(x86_64) || arch(s390x)
@frozen // c-abi
@usableFromInline
internal struct Header {
@inlinable // c-abi
internal init() {}
@usableFromInline // c-abi
internal var gp_offset = CUnsignedInt(0)
@usableFromInline // c-abi
internal var fp_offset =
CUnsignedInt(_countGPRegisters * MemoryLayout<Int>.stride)
@usableFromInline // c-abi
internal var overflow_arg_area: UnsafeMutablePointer<Int>?
@usableFromInline // c-abi
internal var reg_save_area: UnsafeMutablePointer<Int>?
}
#endif
@usableFromInline // c-abi
internal var gpRegistersUsed = 0
@usableFromInline // c-abi
internal var fpRegistersUsed = 0
#if arch(x86_64) || arch(s390x)
@usableFromInline // c-abi
final // Property must be final since it is used by Builtin.addressof.
internal var header = Header()
#endif
@usableFromInline // c-abi
internal var storage: ContiguousArray<Int>
#if !_runtime(_ObjC)
@usableFromInline // c-abi
internal var retainer = [CVarArg]()
#endif
@inlinable // c-abi
internal init() {
// prepare the register save area
storage = ContiguousArray(repeating: 0, count: _registerSaveWords)
}
@inlinable // c-abi
deinit {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
#if !_runtime(_ObjC)
var arg = arg
// We may need to retain an object that provides a pointer value.
if let obj = arg as? _CVarArgObject {
arg = obj._cVarArgObject
retainer.append(arg)
}
#endif
var encoded = arg._cVarArgEncoding
#if arch(x86_64) || arch(arm64)
let isDouble = arg is _CVarArgPassedAsDouble
if isDouble && fpRegistersUsed < _countFPRegisters {
#if arch(arm64)
var startIndex = fpRegistersUsed * _fpRegisterWords
#else
var startIndex = _countGPRegisters
+ (fpRegistersUsed * _fpRegisterWords)
#endif
for w in encoded {
storage[startIndex] = w
startIndex += 1
}
fpRegistersUsed += 1
}
else if encoded.count == 1
&& !isDouble
&& gpRegistersUsed < _countGPRegisters {
#if arch(arm64)
let startIndex = ( _fpRegisterWords * _countFPRegisters) + gpRegistersUsed
#else
let startIndex = gpRegistersUsed
#endif
storage[startIndex] = encoded[0]
gpRegistersUsed += 1
}
else {
for w in encoded {
storage.append(w)
}
}
#elseif arch(s390x)
if gpRegistersUsed < _countGPRegisters {
for w in encoded {
storage[gpRegistersUsed] = w
gpRegistersUsed += 1
}
} else {
for w in encoded {
storage.append(w)
}
}
#endif
}
@inlinable // c-abi
internal func va_list() -> CVaListPointer {
#if arch(x86_64) || arch(s390x)
header.reg_save_area = storage._baseAddress
header.overflow_arg_area
= storage._baseAddress + _registerSaveWords
return CVaListPointer(
_fromUnsafeMutablePointer: UnsafeMutableRawPointer(
Builtin.addressof(&self.header)))
#elseif arch(arm64)
let vr_top = storage._baseAddress + (_fpRegisterWords * _countFPRegisters)
let gr_top = vr_top + _countGPRegisters
return CVaListPointer(__stack: gr_top,
__gr_top: gr_top,
__vr_top: vr_top,
__gr_off: -64,
__vr_off: -128)
#endif
}
}
#else
/// An object that can manage the lifetime of storage backing a
/// `CVaListPointer`.
// NOTE: older runtimes called this _VaListBuilder. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
@_fixed_layout
@usableFromInline // c-abi
final internal class __VaListBuilder {
@inlinable // c-abi
internal init() {}
@inlinable // c-abi
internal func append(_ arg: CVarArg) {
#if !_runtime(_ObjC)
var arg = arg
// We may need to retain an object that provides a pointer value.
if let obj = arg as? _CVarArgObject {
arg = obj._cVarArgObject
retainer.append(arg)
}
#endif
// Write alignment padding if necessary.
// This is needed on architectures where the ABI alignment of some
// supported vararg type is greater than the alignment of Int, such
// as non-iOS ARM. Note that we can't use alignof because it
// differs from ABI alignment on some architectures.
#if (arch(arm) && !os(iOS)) || arch(arm64_32)
if let arg = arg as? _CVarArgAligned {
let alignmentInWords = arg._cVarArgAlignment / MemoryLayout<Int>.size
let misalignmentInWords = count % alignmentInWords
if misalignmentInWords != 0 {
let paddingInWords = alignmentInWords - misalignmentInWords
appendWords([Int](repeating: -1, count: paddingInWords))
}
}
#endif
// Write the argument's value itself.
appendWords(arg._cVarArgEncoding)
}
// NB: This function *cannot* be @inlinable because it expects to project
// and escape the physical storage of `__VaListBuilder.alignedStorageForEmptyVaLists`.
// Marking it inlinable will cause it to resiliently use accessors to
// project `__VaListBuilder.alignedStorageForEmptyVaLists` as a computed
// property.
@usableFromInline // c-abi
internal func va_list() -> CVaListPointer {
// Use Builtin.addressof to emphasize that we are deliberately escaping this
// pointer and assuming it is safe to do so.
let emptyAddr = UnsafeMutablePointer<Int>(
Builtin.addressof(&__VaListBuilder.alignedStorageForEmptyVaLists))
return CVaListPointer(_fromUnsafeMutablePointer: storage ?? emptyAddr)
}
// Manage storage that is accessed as Words
// but possibly more aligned than that.
// FIXME: this should be packaged into a better storage type
@inlinable // c-abi
internal func appendWords(_ words: [Int]) {
let newCount = count + words.count
if newCount > allocated {
let oldAllocated = allocated
let oldStorage = storage
let oldCount = count
allocated = max(newCount, allocated * 2)
let newStorage = allocStorage(wordCount: allocated)
storage = newStorage
// count is updated below
if let allocatedOldStorage = oldStorage {
newStorage.moveInitialize(from: allocatedOldStorage, count: oldCount)
deallocStorage(wordCount: oldAllocated, storage: allocatedOldStorage)
}
}
let allocatedStorage = storage!
for word in words {
allocatedStorage[count] = word
count += 1
}
}
@inlinable // c-abi
internal func rawSizeAndAlignment(
_ wordCount: Int
) -> (Builtin.Word, Builtin.Word) {
return ((wordCount * MemoryLayout<Int>.stride)._builtinWordValue,
requiredAlignmentInBytes._builtinWordValue)
}
@inlinable // c-abi
internal func allocStorage(wordCount: Int) -> UnsafeMutablePointer<Int> {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
let rawStorage = Builtin.allocRaw(rawSize, rawAlignment)
return UnsafeMutablePointer<Int>(rawStorage)
}
@usableFromInline // c-abi
internal func deallocStorage(
wordCount: Int,
storage: UnsafeMutablePointer<Int>
) {
let (rawSize, rawAlignment) = rawSizeAndAlignment(wordCount)
Builtin.deallocRaw(storage._rawValue, rawSize, rawAlignment)
}
@inlinable // c-abi
deinit {
if let allocatedStorage = storage {
deallocStorage(wordCount: allocated, storage: allocatedStorage)
}
}
// FIXME: alignof differs from the ABI alignment on some architectures
@usableFromInline // c-abi
internal let requiredAlignmentInBytes = MemoryLayout<Double>.alignment
@usableFromInline // c-abi
internal var count = 0
@usableFromInline // c-abi
internal var allocated = 0
@usableFromInline // c-abi
internal var storage: UnsafeMutablePointer<Int>?
#if !_runtime(_ObjC)
@usableFromInline // c-abi
internal var retainer = [CVarArg]()
#endif
internal static var alignedStorageForEmptyVaLists: Double = 0
}
#endif
|
apache-2.0
|
709ee56e5b3c23a82727ce64aa984f1e
| 31.90309 | 135 | 0.691211 | 4.097779 | false | false | false | false |
lorentey/swift
|
stdlib/public/core/DictionaryVariant.swift
|
7
|
13312
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// This protocol is only used for compile-time checks that
/// every buffer type implements all required operations.
internal protocol _DictionaryBuffer {
associatedtype Key
associatedtype Value
associatedtype Index
var startIndex: Index { get }
var endIndex: Index { get }
func index(after i: Index) -> Index
func index(forKey key: Key) -> Index?
var count: Int { get }
func contains(_ key: Key) -> Bool
func lookup(_ key: Key) -> Value?
func lookup(_ index: Index) -> (key: Key, value: Value)
func key(at index: Index) -> Key
func value(at index: Index) -> Value
}
extension Dictionary {
@usableFromInline
@frozen
internal struct _Variant {
@usableFromInline
internal var object: _BridgeStorage<__RawDictionaryStorage>
@inlinable
@inline(__always)
init(native: __owned _NativeDictionary<Key, Value>) {
self.object = _BridgeStorage(native: native._storage)
}
@inlinable
@inline(__always)
init(dummy: Void) {
#if arch(i386) || arch(arm)
self.init(native: _NativeDictionary())
#else
self.object = _BridgeStorage(taggedPayload: 0)
#endif
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
init(cocoa: __owned __CocoaDictionary) {
self.object = _BridgeStorage(objC: cocoa.object)
}
#endif
}
}
extension Dictionary._Variant {
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var guaranteedNative: Bool {
return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0
}
#endif
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
return object.isUniquelyReferencedUnflaggedNative()
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var isNative: Bool {
if guaranteedNative { return true }
return object.isUnflaggedNative
}
#endif
@usableFromInline @_transparent
internal var asNative: _NativeDictionary<Key, Value> {
get {
return _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)
}
set {
self = .init(native: newValue)
}
_modify {
var native = _NativeDictionary<Key, Value>(object.unflaggedNativeInstance)
self = .init(dummy: ())
defer { object = .init(native: native._storage) }
yield &native
}
}
#if _runtime(_ObjC)
@inlinable
internal var asCocoa: __CocoaDictionary {
return __CocoaDictionary(object.objCInstance)
}
#endif
/// Reserves enough space for the specified number of elements to be stored
/// without reallocating additional storage.
internal mutating func reserveCapacity(_ capacity: Int) {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
let capacity = Swift.max(cocoa.count, capacity)
self = .init(native: _NativeDictionary(cocoa, capacity: capacity))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.reserveCapacity(capacity, isUnique: isUnique)
}
/// The number of elements that can be stored without expanding the current
/// storage.
///
/// For bridged storage, this is equal to the current count of the
/// collection, since any addition will trigger a copy of the elements into
/// newly allocated storage. For native storage, this is the element count
/// at which adding any more elements will exceed the load factor.
@inlinable
internal var capacity: Int {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.capacity
}
}
extension Dictionary._Variant: _DictionaryBuffer {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias Index = Dictionary<Key, Value>.Index
@inlinable
internal var startIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.startIndex)
}
#endif
return asNative.startIndex
}
@inlinable
internal var endIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.endIndex)
}
#endif
return asNative.endIndex
}
@inlinable
internal func index(after index: Index) -> Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.index(after: index._asCocoa))
}
#endif
return asNative.index(after: index)
}
@inlinable
internal func formIndex(after index: inout Index) {
#if _runtime(_ObjC)
guard isNative else {
let isUnique = index._isUniquelyReferenced()
asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique)
return
}
#endif
index = asNative.index(after: index)
}
@inlinable
@inline(__always)
internal func index(forKey key: Key) -> Index? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
guard let index = asCocoa.index(forKey: cocoaKey) else { return nil }
return Index(_cocoa: index)
}
#endif
return asNative.index(forKey: key)
}
@inlinable
internal var count: Int {
@inline(__always)
get {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.count
}
}
@inlinable
@inline(__always)
func contains(_ key: Key) -> Bool {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
return asCocoa.contains(cocoaKey)
}
#endif
return asNative.contains(key)
}
@inlinable
@inline(__always)
func lookup(_ key: Key) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
guard let cocoaValue = asCocoa.lookup(cocoaKey) else { return nil }
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return asNative.lookup(key)
}
@inlinable
@inline(__always)
func lookup(_ index: Index) -> (key: Key, value: Value) {
#if _runtime(_ObjC)
guard isNative else {
let (cocoaKey, cocoaValue) = asCocoa.lookup(index._asCocoa)
let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self)
let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self)
return (nativeKey, nativeValue)
}
#endif
return asNative.lookup(index)
}
@inlinable
@inline(__always)
func key(at index: Index) -> Key {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = asCocoa.key(at: index._asCocoa)
return _forceBridgeFromObjectiveC(cocoaKey, Key.self)
}
#endif
return asNative.key(at: index)
}
@inlinable
@inline(__always)
func value(at index: Index) -> Value {
#if _runtime(_ObjC)
guard isNative else {
let cocoaValue = asCocoa.value(at: index._asCocoa)
return _forceBridgeFromObjectiveC(cocoaValue, Value.self)
}
#endif
return asNative.value(at: index)
}
}
extension Dictionary._Variant {
@inlinable
internal subscript(key: Key) -> Value? {
@inline(__always)
get {
return lookup(key)
}
@inline(__always)
_modify {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa, capacity: cocoa.count + 1)
self = .init(native: native)
yield &native[key, isUnique: true]
return
}
#endif
let isUnique = isUniquelyReferenced()
yield &asNative[key, isUnique: isUnique]
}
}
}
extension Dictionary._Variant {
/// Same as find(_:), except assume a corresponding key/value pair will be
/// inserted if it doesn't already exist, and mutated if it does exist. When
/// this function returns, the storage is guaranteed to be native, uniquely
/// held, and with enough capacity for a single insertion (if the key isn't
/// already in the dictionary.)
@inlinable
@inline(__always)
internal mutating func mutatingFind(
_ key: Key
) -> (bucket: _NativeDictionary<Key, Value>.Bucket, found: Bool) {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa, capacity: cocoa.count + 1)
let result = native.mutatingFind(key, isUnique: true)
self = .init(native: native)
return result
}
#endif
let isUnique = isUniquelyReferenced()
return asNative.mutatingFind(key, isUnique: isUnique)
}
@inlinable
@inline(__always)
internal mutating func ensureUniqueNative() -> _NativeDictionary<Key, Value> {
#if _runtime(_ObjC)
guard isNative else {
let native = _NativeDictionary<Key, Value>(asCocoa)
self = .init(native: native)
return native
}
#endif
let isUnique = isUniquelyReferenced()
if !isUnique {
asNative.copy()
}
return asNative
}
@inlinable
internal mutating func updateValue(
_ value: __owned Value,
forKey key: Key
) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
// Make sure we have space for an extra element.
let cocoa = asCocoa
var native = _NativeDictionary<Key, Value>(
cocoa,
capacity: cocoa.count + 1)
let result = native.updateValue(value, forKey: key, isUnique: true)
self = .init(native: native)
return result
}
#endif
let isUnique = self.isUniquelyReferenced()
return asNative.updateValue(value, forKey: key, isUnique: isUnique)
}
@inlinable
internal mutating func setValue(_ value: __owned Value, forKey key: Key) {
#if _runtime(_ObjC)
if !isNative {
// Make sure we have space for an extra element.
let cocoa = asCocoa
self = .init(native: _NativeDictionary<Key, Value>(
cocoa,
capacity: cocoa.count + 1))
}
#endif
let isUnique = self.isUniquelyReferenced()
asNative.setValue(value, forKey: key, isUnique: isUnique)
}
@inlinable
@_semantics("optimize.sil.specialize.generic.size.never")
internal mutating func remove(at index: Index) -> Element {
// FIXME(performance): fuse data migration and element deletion into one
// operation.
let native = ensureUniqueNative()
let bucket = native.validatedBucket(for: index)
return asNative.uncheckedRemove(at: bucket, isUnique: true)
}
@inlinable
internal mutating func removeValue(forKey key: Key) -> Value? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaKey = _bridgeAnythingToObjectiveC(key)
let cocoa = asCocoa
guard cocoa.lookup(cocoaKey) != nil else { return nil }
var native = _NativeDictionary<Key, Value>(cocoa)
let (bucket, found) = native.find(key)
_precondition(found, "Bridging did not preserve equality")
let old = native.uncheckedRemove(at: bucket, isUnique: true).value
self = .init(native: native)
return old
}
#endif
let (bucket, found) = asNative.find(key)
guard found else { return nil }
let isUnique = isUniquelyReferenced()
return asNative.uncheckedRemove(at: bucket, isUnique: isUnique).value
}
@inlinable
@_semantics("optimize.sil.specialize.generic.size.never")
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if !keepCapacity {
self = .init(native: _NativeDictionary())
return
}
guard count > 0 else { return }
#if _runtime(_ObjC)
guard isNative else {
self = .init(native: _NativeDictionary(capacity: asCocoa.count))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.removeAll(isUnique: isUnique)
}
}
extension Dictionary._Variant {
/// Returns an iterator over the `(Key, Value)` pairs.
///
/// - Complexity: O(1).
@inlinable
@inline(__always)
__consuming internal func makeIterator() -> Dictionary<Key, Value>.Iterator {
#if _runtime(_ObjC)
guard isNative else {
return Dictionary.Iterator(_cocoa: asCocoa.makeIterator())
}
#endif
return Dictionary.Iterator(_native: asNative.makeIterator())
}
}
extension Dictionary._Variant {
@inlinable
internal func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> _NativeDictionary<Key, T> {
#if _runtime(_ObjC)
guard isNative else {
return try asCocoa.mapValues(transform)
}
#endif
return try asNative.mapValues(transform)
}
@inlinable
internal mutating func merge<S: Sequence>(
_ keysAndValues: __owned S,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows where S.Element == (Key, Value) {
#if _runtime(_ObjC)
guard isNative else {
var native = _NativeDictionary<Key, Value>(asCocoa)
try native.merge(
keysAndValues,
isUnique: true,
uniquingKeysWith: combine)
self = .init(native: native)
return
}
#endif
let isUnique = isUniquelyReferenced()
try asNative.merge(
keysAndValues,
isUnique: isUnique,
uniquingKeysWith: combine)
}
}
|
apache-2.0
|
9ea06e1dc00d837f84d7abf4c70d2a59
| 26.334702 | 80 | 0.660382 | 4.134161 | false | false | false | false |
GoogleCloudPlatform/ios-docs-samples
|
natural-language/swift/NaturalLanguage/NaturalLanguageService.swift
|
1
|
7551
|
//
// Copyright 2019 Google Inc. 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.
//
import Foundation
import googleapis
import AVFoundation
import AuthLibrary
import Firebase
class NaturalLanguageService {
private var client : LanguageService = LanguageService(host: ApplicationConstants.Host)
private var writer : GRXBufferedPipe = GRXBufferedPipe()
private var call : GRPCProtoCall!
static let sharedInstance = NaturalLanguageService()
var authToken: String = ""
func getDeviceID(callBack: @escaping (String)->Void) {
InstanceID.instanceID().instanceID { (result, error) in
if let error = error {
print("Error fetching remote instance ID: \(error)")
callBack( "")
} else if let result = result {
print("Remove instance ID token: \(result.token)")
callBack( result.token)
} else {
callBack( "")
}
}
}
func textToSentiment(text:String, completionHandler: @escaping (_ documentResponse: AnalyzeSentimentResponse, _ entityResponse: AnalyzeEntitySentimentResponse) -> Void) {
let documet: Document = Document()
documet.content = text
documet.type = Document_Type.plainText
let analyzeSentiment = AnalyzeSentimentRequest()
analyzeSentiment.document = documet
call = client.rpcToAnalyzeSentiment(with: analyzeSentiment) { (analyzeSentimentResponse, error) in
if error != nil {
print(error?.localizedDescription ?? "No error description available")
return
}
guard let response = analyzeSentimentResponse else {
print("No response received")
return
}
print("analyzeSentimentResponse\(response)")
self.textToEntitySentimentAnalysis(document: documet, analyzeSentimentResponse: response, completionHandler: completionHandler)
}
self.call.requestHeaders.setObject(NSString(string:authToken), forKey:NSString(string:"Authorization"))
// if the API key has a bundle ID restriction, specify the bundle ID like this
self.call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier"))
print("HEADERS:\(String(describing: call.requestHeaders))")
call.start()
}
func textToEntitySentimentAnalysis(document: Document, analyzeSentimentResponse: AnalyzeSentimentResponse, completionHandler: @escaping (_ documentResponse: AnalyzeSentimentResponse, _ entityResponse: AnalyzeEntitySentimentResponse) -> Void) {
let analyzeEntitySentiment = AnalyzeEntitySentimentRequest()
analyzeEntitySentiment.document = document
call = client.rpcToAnalyzeEntitySentiment(with: analyzeEntitySentiment, handler: { (analyzeEntitySentimentResponse, error) in
if error != nil {
print(error?.localizedDescription ?? "No error description available")
return
}
guard let response = analyzeEntitySentimentResponse else {
print("No response received")
return
}
print("analyzeSentimentResponse\(response)")
completionHandler(analyzeSentimentResponse, response)
})
self.call.requestHeaders.setObject(NSString(string:authToken), forKey:NSString(string:"Authorization"))
// if the API key has a bundle ID restriction, specify the bundle ID like this
self.call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier"))
print("HEADERS:\(String(describing: call.requestHeaders))")
call.start()
}
func textToEntity(text:String, completionHandler: @escaping (_ response: AnalyzeEntitiesResponse) -> Void) {
let documet: Document = Document()
documet.content = text
documet.type = Document_Type.plainText
let analyzeEntity = AnalyzeEntitiesRequest()
analyzeEntity.document = documet
call = client.rpcToAnalyzeEntities(with: analyzeEntity) { (analyzeEntitiesResponse, error) in
if error != nil {
print(error?.localizedDescription ?? "No error description available")
return
}
guard let response = analyzeEntitiesResponse else {
print("No response received")
return
}
print("analyzeEntitiesResponse\(response)")
completionHandler(response)
}
self.call.requestHeaders.setObject(NSString(string:authToken), forKey:NSString(string:"Authorization"))
// if the API key has a bundle ID restriction, specify the bundle ID like this
self.call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier"))
print("HEADERS:\(String(describing: call.requestHeaders))")
call.start()
}
func textToSyntax(text:String, completionHandler: @escaping (_ response: AnalyzeSyntaxResponse) -> Void) {
let documet: Document = Document()
documet.content = text
documet.type = Document_Type.plainText
let analyzeSyntax = AnalyzeSyntaxRequest()
analyzeSyntax.document = documet
call = client.rpcToAnalyzeSyntax(with: analyzeSyntax) { (analyzeSyntaxResponse, error) in
if error != nil {
print(error?.localizedDescription ?? "No error description available")
return
}
guard let response = analyzeSyntaxResponse else {
print("No response received")
return
}
print("analyzeSyntaxResponse\(response)")
completionHandler(response)
}
self.call.requestHeaders.setObject(NSString(string:authToken), forKey:NSString(string:"Authorization"))
// if the API key has a bundle ID restriction, specify the bundle ID like this
self.call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier"))
print("HEADERS:\(String(describing: call.requestHeaders))")
call.start()
}
func textToCategory(text:String, completionHandler: @escaping (_ response: ClassifyTextResponse) -> Void) {
let documet: Document = Document()
documet.content = text
documet.type = Document_Type.plainText
let classifyText = ClassifyTextRequest()
classifyText.document = documet
call = client.rpcToClassifyText(with: classifyText) { (classifyTextResponse, error) in
print("classifyTextResponse : \(String(describing: classifyTextResponse))")
if error != nil {
print(error?.localizedDescription ?? "No error description available")
return
}
guard let response = classifyTextResponse else {
print("No response received")
return
}
print("classifyTextResponse\(response)")
completionHandler(response)
}
self.call.requestHeaders.setObject(NSString(string:authToken), forKey:NSString(string:"Authorization"))
// if the API key has a bundle ID restriction, specify the bundle ID like this
self.call.requestHeaders.setObject(NSString(string:Bundle.main.bundleIdentifier!), forKey:NSString(string:"X-Ios-Bundle-Identifier"))
print("HEADERS:\(String(describing: call.requestHeaders))")
call.start()
}
}
|
apache-2.0
|
7ea84afa4b6dbb3eb5b07c5b02e113ee
| 40.718232 | 245 | 0.722156 | 4.731203 | false | false | false | false |
smaltby/Canary
|
iOS/Canary/Canary/AppDelegate.swift
|
1
|
3546
|
import UIKit
let appDelegate = UIApplication.shared.delegate as! AppDelegate
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, SPTAudioStreamingDelegate {
var window: UIWindow?
var session: SPTSession?
var player: SPTAudioStreamingController?
let kClientId = "3e189d315fa64c97abdeaf9f855815e3"
let kCallbackURL = "canary://callback"
let kSessionUserDefaultsKey = "SpotifySession"
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
print("Hello World in Swift")
// Set variables necessary for authentication
SPTAuth.defaultInstance().clientID = kClientId
SPTAuth.defaultInstance().redirectURL = URL(string:kCallbackURL)
SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope]
SPTAuth.defaultInstance().sessionUserDefaultsKey = kSessionUserDefaultsKey
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
// Ask SPTAuth if the URL given is a Spotify authentication callback
print("The URL: \(url)")
if SPTAuth.defaultInstance().canHandle(url) {
SPTAuth.defaultInstance().handleAuthCallback(withTriggeredAuthURL: url) { error, session in
// This is the callback that'll be triggered when auth is completed (or fails).
if error != nil {
print("*** Auth error: \(error!)")
return
}
else {
SPTAuth.defaultInstance().session = session
}
NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "sessionUpdated"), object: self)
}
}
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:.
}
}
|
mit
|
ec1a7e6c5b3c9cbd0319c519a0216d27
| 46.918919 | 285 | 0.751551 | 4.817935 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/SpeechToTextV1/Models/Corpus.swift
|
1
|
3042
|
/**
* (C) Copyright IBM Corp. 2017, 2020.
*
* 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
/**
Information about a corpus from a custom language model.
*/
public struct Corpus: Codable, Equatable {
/**
The status of the corpus:
* `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the
corpus.
* `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new
resources or to train the custom model.
* `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the
failure.
*/
public enum Status: String {
case analyzed = "analyzed"
case beingProcessed = "being_processed"
case undetermined = "undetermined"
}
/**
The name of the corpus.
*/
public var name: String
/**
The total number of words in the corpus. The value is `0` while the corpus is being processed.
*/
public var totalWords: Int
/**
_For custom models that are based on previous-generation models_, the number of OOV words extracted from the
corpus. The value is `0` while the corpus is being processed.
_For custom models that are based on next-generation models_, no OOV words are extracted from corpora, so the value
is always `0`.
*/
public var outOfVocabularyWords: Int
/**
The status of the corpus:
* `analyzed`: The service successfully analyzed the corpus. The custom model can be trained with data from the
corpus.
* `being_processed`: The service is still analyzing the corpus. The service cannot accept requests to add new
resources or to train the custom model.
* `undetermined`: The service encountered an error while processing the corpus. The `error` field describes the
failure.
*/
public var status: String
/**
If the status of the corpus is `undetermined`, the following message: `Analysis of corpus 'name' failed. Please try
adding the corpus again by setting the 'allow_overwrite' flag to 'true'`.
*/
public var error: String?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case name = "name"
case totalWords = "total_words"
case outOfVocabularyWords = "out_of_vocabulary_words"
case status = "status"
case error = "error"
}
}
|
apache-2.0
|
b3cbfd21fb9e2c4288708271aaa1a3d8
| 35.650602 | 120 | 0.687705 | 4.37069 | false | false | false | false |
alexzatsepin/omim
|
iphone/Maps/UI/Reviews/ReviewsViewController.swift
|
3
|
2123
|
@objc(MWMReviewsViewController)
final class ReviewsViewController: MWMTableViewController {
private let viewModel: MWMReviewsViewModelProtocol
@objc init(viewModel: MWMReviewsViewModelProtocol) {
self.viewModel = viewModel
super.init(nibName: toString(type(of: self)), bundle: nil)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
registerCells()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.refresh()
}
private func registerCells() {
[UGCYourReviewCell.self, UGCReviewCell.self].forEach {
tableView.register(cellClass: $0)
}
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return viewModel.numberOfReviews()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellModel = viewModel.review(with: indexPath.row)
switch cellModel {
case let cellModel as UGCYourReview:
let cell = tableView.dequeueReusableCell(withCellClass: UGCYourReviewCell.self, indexPath: indexPath) as! UGCYourReviewCell
cell.config(yourReview: cellModel,
isExpanded: viewModel.isExpanded(cellModel),
onUpdate: { [weak self] in
guard let self = self else { return }
self.viewModel.markExpanded(cellModel)
self.tableView.refresh()
})
return cell
case let cellModel as UGCReview:
let cell = tableView.dequeueReusableCell(withCellClass: UGCReviewCell.self, indexPath: indexPath) as! UGCReviewCell
cell.config(review: cellModel,
isExpanded: viewModel.isExpanded(cellModel),
onUpdate: { [weak self] in
guard let self = self else { return }
self.viewModel.markExpanded(cellModel)
self.tableView.refresh()
})
return cell
default: assert(false)
}
return UITableViewCell()
}
}
|
apache-2.0
|
515e20887c89a4ae01903e7f69e50f4e
| 33.803279 | 129 | 0.663683 | 5.018913 | false | false | false | false |
Breinify/brein-api-library-ios
|
BreinifyApiTests/api/TestLocation.swift
|
1
|
2416
|
//
// Created by Marco Recchioni
// Copyright (c) 2020 Breinify. All rights reserved.
//
import UIKit
import XCTest
@testable import BreinifyApi
class TestLocation: XCTestCase {
typealias apiSuccess = (_ result: BreinResult?) -> Void
typealias apiFailure = (_ error: NSDictionary?) -> Void
let validApiKey = "41B2-F48C-156A-409A-B465-317F-A0B4-E0E8"
let validApiKeyWithSecret = "CA8A-8D28-3408-45A8-8E20-8474-06C0-8548"
let validSecret = "lmcoj4k27hbbszzyiqamhg=="
let breinUser = BreinUser(email: "[email protected]")
let breinCategory = "home"
var breinConfig: BreinConfig!
override func setUp() {
super.setUp()
breinConfig = BreinConfig(validApiKeyWithSecret, secret: validSecret,
breinEngineType: .URLSession)
// set configuration
Breinify.setConfig(breinConfig)
}
override func tearDown() {
let when = DispatchTime.now() + 15 // wait 15 seconds
DispatchQueue.main.asyncAfter(deadline: when) {
Breinify.shutdown()
super.tearDown()
}
}
// test case how to use the activity api
func testWithLocation() {
let successBlock: apiSuccess = { (result: BreinResult?) -> Void in
print("Api Success : result is: \(String(describing: result))")
}
let failureBlock: apiFailure = { (error: NSDictionary?) -> Void in
XCTFail("Api Failure : error is: \(String(describing: error))")
}
// set additional user information
breinUser.setFirstName("Toni")
.setLastName("Maroni")
BreinLocationManager().fetchWithCompletion { location, error in
// fetch location or an error
if location != nil {
print(location!)
let locationInfo = ""
// invoke activity call
do {
try Breinify.activity(self.breinUser,
activityType: "checkOut",
"services",
locationInfo,
successBlock,
failureBlock)
} catch {
XCTFail("Error is: \(error.localizedDescription)")
}
} else if let err = error {
XCTFail(err.localizedDescription)
}
}
}
}
|
mit
|
fb8ca34a632fb270e9c5021599e304dd
| 28.108434 | 77 | 0.559603 | 4.376812 | false | true | false | false |
Reflejo/ClosureKit
|
Sources/LambdaKit/CLLocationManager+LambdaKit.swift
|
2
|
5602
|
//
// CLLocationManager+LambdaKit.swift
// Created by Martin Conte Mac Donell on 3/31/15.
//
// Copyright (c) 2015 Lyft (http://lyft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreLocation
public typealias LKCoreLocationHandler = (LKLocationOrError) -> Void
// A global var to produce a unique address for the assoc object handle
private var associatedEventHandle: UInt8 = 0
/// CLLocationManager with closure callback.
///
/// Note that when using startUpdatingLocation(handler) you need to use the counterpart
/// `stopUpdatingLocationHandler` or you'll leak memory.
///
/// Example:
///
/// ```swift let
/// locationManager = CLLocationManager()
/// locationManager.starUpdatingLocation { location in
/// print("Location: \(location)")
/// }
/// locationManager.stopUpdatingLocationHandler()
/// ```
///
/// WARNING: You cannot use closures *and* set a delegate at the same time. Setting a delegate will prevent
/// closures for being called and setting a closure will overwrite the delegate property.
/// An enum that will represent either a location or an error with corresponding associated values.
///
/// - Location: A location as reported by Core Location.
/// - Error: An error coming from Core Location, for example when location service usage is denied.
public enum LKLocationOrError {
case location(CLLocation)
case error(NSError)
}
extension CLLocationManager: CLLocationManagerDelegate {
private var closureWrapper: ClosureWrapper? {
get {
return objc_getAssociatedObject(self, &associatedEventHandle) as? ClosureWrapper
}
set {
objc_setAssociatedObject(self, &associatedEventHandle, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Starts monitoring GPS location changes and call the given closure for each change.
///
/// - parameter completion: A closure that will be called passing as the first argument the device's
/// location.
public func startUpdatingLocation(_ completion: @escaping LKCoreLocationHandler) {
self.closureWrapper = ClosureWrapper(handler: completion)
self.delegate = self
self.startUpdatingLocation()
if let location = self.location {
completion(.location(location))
}
}
/// Stops monitoring GPS location changes and cleanup.
public func stopUpdatingLocationHandler() {
self.stopUpdatingLocation()
self.closureWrapper = nil
self.delegate = nil
}
/// Request the current location which is reported in the completion handler.
///
/// - parameter completion: A closure that will be called with the device's current location.
@available(iOS 9, *)
public func requestLocation(_ completion: @escaping LKCoreLocationHandler) {
self.closureWrapper = ClosureWrapper(handler: completion)
self.delegate = self
self.requestLocation()
if let location = self.location {
completion(.location(location))
}
}
#if !os(watchOS)
/// Starts monitoring significant location changes and call the given closure for each change.
///
/// - parameter completion: A closure that will be called passing as the first argument the device's
/// location.
public func startMonitoringSignificantLocationChanges(_ completion: @escaping LKCoreLocationHandler) {
self.closureWrapper = ClosureWrapper(handler: completion)
self.delegate = self
self.startMonitoringSignificantLocationChanges()
}
/// Stops monitoring GPS location changes and cleanup.
public func stopMonitoringSignificantLocationChangesHandler() {
self.stopMonitoringSignificantLocationChanges()
self.closureWrapper = nil
self.delegate = nil
}
#endif
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let handler = self.closureWrapper?.handler, let location = manager.location {
handler(.location(location))
}
}
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.closureWrapper?.handler(.error(error as NSError))
}
}
// MARK: - Private Classes
fileprivate final class ClosureWrapper {
fileprivate var handler: LKCoreLocationHandler
fileprivate init(handler: @escaping LKCoreLocationHandler) {
self.handler = handler
}
}
|
mit
|
3c1f9eec2844b178a63acf98a2a1b390
| 38.450704 | 107 | 0.705105 | 5.006256 | false | false | false | false |
onmyway133/Github.swift
|
Carthage/Checkouts/Sugar/Source/Shared/Extensions/NSDate+Compare.swift
|
1
|
1471
|
import Foundation
extension NSDate : Comparable {}
public func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 < rhs.timeIntervalSince1970
}
public func <= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 <= rhs.timeIntervalSince1970
}
public func >= (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 >= rhs.timeIntervalSince1970
}
public func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSince1970 > rhs.timeIntervalSince1970
}
// MARK: - Components
public extension NSDate {
public func components(unit: NSCalendarUnit, retrieval: NSDateComponents -> Int) -> Int {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(unit, fromDate: self)
return retrieval(components)
}
public var second: Int {
return components(.Second) {
return $0.second
}
}
public var minute: Int {
return components(.Minute) {
return $0.minute
}
}
public var hour: Int {
return components(.Hour) {
return $0.hour
}
}
public var day: Int {
return components(.Day) {
return $0.day
}
}
public var month: Int {
return components(.Month) {
return $0.month
}
}
public var year: Int {
return components(.Year) {
return $0.year
}
}
public var weekday: Int {
return components(.Weekday) {
return $0.weekday
}
}
}
|
mit
|
04cf5ec83dad1b9cf92b0075376d435d
| 19.150685 | 91 | 0.64378 | 4.074792 | false | false | false | false |
YMXian/YMCore
|
YMCore/Async/BlockDefinition.swift
|
1
|
721
|
//
// BlockDefinition.swift
// YMCore
//
// Created by Yanke Guo on 16/1/31.
// Copyright © 2016年 Juxian(Beijing) Technology Co., Ltd. All rights reserved.
//
import Foundation
/// Block accepts nothing and returns nothing
public typealias VoidBlock = () -> Void
/// Block returns a Bool
public typealias BoolBlock = () -> Bool
/// Block returns a NSComparisonResult
public typealias CompareBlock = ()-> NSComparisonResult
/// Block accepts a NSError? and returns nothing, suitable for a callback
public typealias ErrorCallbackBlock = (NSError?) -> Void
/// Block accetps a ErrorCallbackBlock and returns nothing, suitable for a async operation
public typealias OperationBlock = (ErrorCallbackBlock) -> Void
|
mit
|
50522cfa4c54fb36dbe6c708a0c9c396
| 28.916667 | 90 | 0.746518 | 4.27381 | false | false | false | false |
lucascarletti/Pruuu
|
Pods/Sync/Source/Sync/NSManagedObject+Sync.swift
|
1
|
25800
|
import CoreData
extension NSManagedObject {
/**
Using objectID to fetch an NSManagedObject from a NSManagedContext is quite unsafe,
and has unexpected behaviour most of the time, although it has gotten better throught
the years, it's a simple method with not many moving parts.
Copy in context gives you a similar behaviour, just a bit safer.
- parameter context: The context where the NSManagedObject will be taken
- returns: A NSManagedObject copied in the provided context.
*/
func sync_copyInContext(_ context: NSManagedObjectContext) -> NSManagedObject {
guard let entityName = self.entity.name else { fatalError("Couldn't find entity name") }
let localPrimaryKey = value(forKey: self.entity.sync_localPrimaryKey())
guard let copiedObject = context.safeObject(entityName, localPrimaryKey: localPrimaryKey, parent: nil, parentRelationshipName: nil) else { fatalError("Couldn't fetch a safe object from entityName: \(entityName) localPrimaryKey: \(String(describing: localPrimaryKey))") }
return copiedObject
}
/**
Syncs the entity using the received dictionary, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter dictionary: The JSON with the changes to be applied to the entity.
- parameter parent: The parent of the entity, optional since many entities are orphans.
- parameter dataStack: The DataStack instance.
*/
func sync_fill(with dictionary: [String: Any], parent: NSManagedObject?, parentRelationship: NSRelationshipDescription?, context: NSManagedObjectContext, operations: Sync.OperationOptions, shouldContinueBlock: (() -> Bool)?, objectJSONBlock: ((_ objectJSON: [String: Any]) -> [String: Any])?) {
hyp_fill(with: dictionary)
for relationship in entity.sync_relationships() {
let suffix = relationship.isToMany ? "_ids" : "_id"
let constructedKeyName = relationship.name.hyp_snakeCase() + suffix
let keyName = relationship.customKey ?? constructedKeyName
if relationship.isToMany {
var children: Any?
if keyName.contains(".") {
if let deepMappingRootkey = keyName.components(separatedBy: ".").first {
if let rootObject = dictionary[deepMappingRootkey] as? [String: Any] {
if let deepMappingLeaveKey = keyName.components(separatedBy: ".").last {
children = rootObject[deepMappingLeaveKey]
}
}
}
} else {
children = dictionary[keyName]
}
if let localPrimaryKey = children, localPrimaryKey is Array < String> || localPrimaryKey is Array < Int> || localPrimaryKey is NSNull {
sync_toManyRelationshipUsingIDsInsteadOfDictionary(relationship, localPrimaryKey: localPrimaryKey)
} else {
try! sync_toManyRelationship(relationship, dictionary: dictionary, parent: parent, parentRelationship: parentRelationship, context: context, operations: operations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
}
} else {
var destinationIsParentSuperEntity = false
if let parent = parent, let destinationEntityName = relationship.destinationEntity?.name {
if let parentSuperEntityName = parent.entity.superentity?.name {
destinationIsParentSuperEntity = destinationEntityName == parentSuperEntityName
}
}
var parentRelationshipIsTheSameAsCurrentRelationship = false
if let parentRelationship = parentRelationship {
parentRelationshipIsTheSameAsCurrentRelationship = parentRelationship.inverseRelationship == relationship
}
var child: Any?
if keyName.contains(".") {
if let deepMappingRootkey = keyName.components(separatedBy: ".").first {
if let rootObject = dictionary[deepMappingRootkey] as? [String: Any] {
if let deepMappingLeaveKey = keyName.components(separatedBy: ".").last {
child = rootObject[deepMappingLeaveKey]
}
}
}
} else {
child = dictionary[keyName]
}
if let parent = parent, parentRelationshipIsTheSameAsCurrentRelationship || destinationIsParentSuperEntity {
let currentValueForRelationship = self.value(forKey: relationship.name)
let newParentIsDifferentThanCurrentValue = parent.isEqual(currentValueForRelationship) == false
if newParentIsDifferentThanCurrentValue {
self.setValue(parent, forKey: relationship.name)
}
} else if let localPrimaryKey = child, localPrimaryKey is NSString || localPrimaryKey is NSNumber || localPrimaryKey is NSNull {
sync_toOneRelationshipUsingIDInsteadOfDictionary(relationship, localPrimaryKey: localPrimaryKey)
} else {
sync_toOneRelationship(relationship, dictionary: dictionary, context: context, operations: operations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
}
}
}
}
/**
Syncs relationships where only the ids are present, for example if your model is: User <<->> Tags (a user has many tags and a tag belongs to many users),
and your tag has a users_ids, it will try to sync using those ID instead of requiring you to provide the entire users list inside each tag.
- parameter relationship: The relationship to be synced.
- parameter localPrimaryKey: The localPrimaryKey of the relationship to be synced, usually an array of strings or numbers.
*/
func sync_toManyRelationshipUsingIDsInsteadOfDictionary(_ relationship: NSRelationshipDescription, localPrimaryKey: Any) {
guard let managedObjectContext = managedObjectContext else { fatalError("managedObjectContext not found") }
guard let destinationEntity = relationship.destinationEntity else { fatalError("destinationEntity not found in relationship: \(relationship)") }
guard let destinationEntityName = destinationEntity.name else { fatalError("entityName not found in entity: \(destinationEntity)") }
if localPrimaryKey is NSNull {
if value(forKey: relationship.name) != nil {
setValue(nil, forKey: relationship.name)
}
} else {
guard let remoteItems = localPrimaryKey as? NSArray else { return }
let localRelationship: NSSet
if relationship.isOrdered {
let value = self.value(forKey: relationship.name) as? NSOrderedSet ?? NSOrderedSet()
localRelationship = value.set as NSSet
} else {
localRelationship = self.value(forKey: relationship.name) as? NSSet ?? NSSet()
}
let localItems = localRelationship.value(forKey: destinationEntity.sync_localPrimaryKey()) as? NSSet ?? NSSet()
let deletedItems = NSMutableArray(array: localItems.allObjects)
let removedRemoteItems = remoteItems as? [Any] ?? [Any]()
deletedItems.removeObjects(in: removedRemoteItems)
let insertedItems = remoteItems.mutableCopy() as? NSMutableArray ?? NSMutableArray()
insertedItems.removeObjects(in: localItems.allObjects)
guard insertedItems.count > 0 || deletedItems.count > 0 || (insertedItems.count == 0 && deletedItems.count == 0 && relationship.isOrdered) else { return }
let request = NSFetchRequest<NSFetchRequestResult>(entityName: destinationEntityName)
let fetchedObjects = try? managedObjectContext.fetch(request) as? [NSManagedObject] ?? [NSManagedObject]()
guard let objects = fetchedObjects else { return }
for safeObject in objects {
let currentID = safeObject.value(forKey: safeObject.entity.sync_localPrimaryKey())!
for inserted in insertedItems {
if (currentID as AnyObject).isEqual(inserted) {
if relationship.isOrdered {
let relatedObjects = mutableOrderedSetValue(forKey: relationship.name)
if !relatedObjects.contains(safeObject) {
relatedObjects.add(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
} else {
let relatedObjects = mutableSetValue(forKey: relationship.name)
if !relatedObjects.contains(safeObject) {
relatedObjects.add(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
}
}
}
for deleted in deletedItems {
if (currentID as AnyObject).isEqual(deleted) {
if relationship.isOrdered {
let relatedObjects = mutableOrderedSetValue(forKey: relationship.name)
if relatedObjects.contains(safeObject) {
relatedObjects.remove(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
} else {
let relatedObjects = mutableSetValue(forKey: relationship.name)
if relatedObjects.contains(safeObject) {
relatedObjects.remove(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
}
}
}
}
if relationship.isOrdered {
for safeObject in objects {
let currentID = safeObject.value(forKey: safeObject.entity.sync_localPrimaryKey())!
let remoteIndex = remoteItems.index(of: currentID)
let relatedObjects = self.mutableOrderedSetValue(forKey: relationship.name)
let currentIndex = relatedObjects.index(of: safeObject)
if currentIndex != remoteIndex {
relatedObjects.moveObjects(at: IndexSet(integer: currentIndex), to: remoteIndex)
}
}
}
}
}
/**
Syncs the entity's to-many relationship, it will also sync the childs of this relationship.
- parameter relationship: The relationship to be synced.
- parameter dictionary: The JSON with the changes to be applied to the entity.
- parameter parent: The parent of the entity, optional since many entities are orphans.
- parameter dataStack: The DataStack instance.
*/
func sync_toManyRelationship(_ relationship: NSRelationshipDescription, dictionary: [String: Any], parent: NSManagedObject?, parentRelationship: NSRelationshipDescription?, context: NSManagedObjectContext, operations: Sync.OperationOptions, shouldContinueBlock: (() -> Bool)?, objectJSONBlock: ((_ objectJSON: [String: Any]) -> [String: Any])?) throws {
var children: [[String: Any]]?
let childrenIsNull = (relationship.customKey as Any?) is NSNull || dictionary[relationship.name.hyp_snakeCase()] is NSNull || dictionary[relationship.name] is NSNull
if childrenIsNull {
children = [[String: Any]]()
if value(forKey: relationship.name) != nil {
setValue(nil, forKey: relationship.name)
}
} else {
if let customRelationshipName = relationship.customKey {
if customRelationshipName.contains(".") {
if let deepMappingRootKey = customRelationshipName.components(separatedBy: ".").first {
if let rootObject = dictionary[deepMappingRootKey] as? [String: Any] {
if let deepMappingLeaveKey = customRelationshipName.components(separatedBy: ".").last {
children = rootObject[deepMappingLeaveKey] as? [[String: Any]]
}
}
}
} else {
children = dictionary[customRelationshipName] as? [[String: Any]]
}
} else if let result = dictionary[relationship.name.hyp_snakeCase()] as? [[String: Any]] {
children = result
} else if let result = dictionary[relationship.name] as? [[String: Any]] {
children = result
}
}
let inverseIsToMany = relationship.inverseRelationship?.isToMany ?? false
guard let managedObjectContext = managedObjectContext else { abort() }
guard let destinationEntity = relationship.destinationEntity else { abort() }
guard let childEntityName = destinationEntity.name else { abort() }
if let children = children {
let childIDs = (children as NSArray).value(forKey: destinationEntity.sync_remotePrimaryKey())
if childIDs is NSNull {
if value(forKey: relationship.name) != nil {
setValue(nil, forKey: relationship.name)
}
} else {
guard let destinationEntityName = destinationEntity.name else { fatalError("entityName not found in entity: \(destinationEntity)") }
if let remoteItems = childIDs as? NSArray {
let localRelationship: NSSet
if relationship.isOrdered {
let value = self.value(forKey: relationship.name) as? NSOrderedSet ?? NSOrderedSet()
localRelationship = value.set as NSSet
} else {
localRelationship = self.value(forKey: relationship.name) as? NSSet ?? NSSet()
}
let localItems = localRelationship.value(forKey: destinationEntity.sync_localPrimaryKey()) as? NSSet ?? NSSet()
let deletedItems = NSMutableArray(array: localItems.allObjects)
let removedRemoteItems = remoteItems as? [Any] ?? [Any]()
deletedItems.removeObjects(in: removedRemoteItems)
let request = NSFetchRequest<NSFetchRequestResult>(entityName: destinationEntityName)
var safeLocalObjects: [NSManagedObject]?
if deletedItems.count > 0 {
safeLocalObjects = try managedObjectContext.fetch(request) as? [NSManagedObject] ?? [NSManagedObject]()
for safeObject in safeLocalObjects! {
let currentID = safeObject.value(forKey: safeObject.entity.sync_localPrimaryKey())!
for deleted in deletedItems {
if (currentID as AnyObject).isEqual(deleted) {
if relationship.isOrdered {
let relatedObjects = mutableOrderedSetValue(forKey: relationship.name)
if relatedObjects.contains(safeObject) {
relatedObjects.remove(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
} else {
let relatedObjects = mutableSetValue(forKey: relationship.name)
if relatedObjects.contains(safeObject) {
relatedObjects.remove(safeObject)
setValue(relatedObjects, forKey: relationship.name)
}
}
}
}
}
}
if relationship.isOrdered {
let objects: [NSManagedObject]
if let safeLocalObjects = safeLocalObjects {
objects = safeLocalObjects
} else {
objects = try managedObjectContext.fetch(request) as? [NSManagedObject] ?? [NSManagedObject]()
}
for safeObject in objects {
let currentID = safeObject.value(forKey: safeObject.entity.sync_localPrimaryKey())!
let remoteIndex = remoteItems.index(of: currentID)
let relatedObjects = self.mutableOrderedSetValue(forKey: relationship.name)
let currentIndex = relatedObjects.index(of: safeObject)
if currentIndex != remoteIndex && currentIndex != NSNotFound {
relatedObjects.moveObjects(at: IndexSet(integer: currentIndex), to: remoteIndex)
}
}
}
}
}
var childPredicate: NSPredicate?
let manyToMany = inverseIsToMany && relationship.isToMany
var childOperations = operations
if manyToMany {
childOperations.remove(.delete)
if ((childIDs as Any) as AnyObject).count > 0 {
guard let entity = NSEntityDescription.entity(forEntityName: childEntityName, in: managedObjectContext) else { fatalError() }
guard let childIDsObject = childIDs as? NSObject else { fatalError() }
childPredicate = NSPredicate(format: "ANY %K IN %@", entity.sync_localPrimaryKey(), childIDsObject)
}
} else {
guard let inverseEntityName = relationship.inverseRelationship?.name else { fatalError() }
childPredicate = NSPredicate(format: "%K = %@", inverseEntityName, self)
}
try Sync.changes(children, inEntityNamed: childEntityName, predicate: childPredicate, parent: self, parentRelationship: relationship, inContext: managedObjectContext, operations: childOperations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
} else {
var destinationIsParentSuperEntity = false
if let parent = parent, let destinationEntityName = relationship.destinationEntity?.name {
if let parentSuperEntityName = parent.entity.superentity?.name {
destinationIsParentSuperEntity = destinationEntityName == parentSuperEntityName
}
}
var parentRelationshipIsTheSameAsCurrentRelationship = false
if let parentRelationship = parentRelationship {
parentRelationshipIsTheSameAsCurrentRelationship = parentRelationship.inverseRelationship == relationship
}
if let parent = parent, parentRelationshipIsTheSameAsCurrentRelationship || destinationIsParentSuperEntity {
if relationship.isOrdered {
let relatedObjects = mutableOrderedSetValue(forKey: relationship.name)
if !relatedObjects.contains(parent) {
relatedObjects.add(parent)
setValue(relatedObjects, forKey: relationship.name)
}
} else {
let relatedObjects = mutableSetValue(forKey: relationship.name)
if !relatedObjects.contains(parent) {
relatedObjects.add(parent)
setValue(relatedObjects, forKey: relationship.name)
}
}
}
}
}
/**
Syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter relationship: The relationship to be synced.
- parameter localPrimaryKey: The localPrimaryKey of the relationship to be synced, usually a number or an integer.
- parameter dataStack: The DataStack instance.
*/
func sync_toOneRelationshipUsingIDInsteadOfDictionary(_ relationship: NSRelationshipDescription, localPrimaryKey: Any) {
guard let managedObjectContext = self.managedObjectContext else { fatalError("managedObjectContext not found") }
guard let destinationEntity = relationship.destinationEntity else { fatalError("destinationEntity not found in relationship: \(relationship)") }
guard let destinationEntityName = destinationEntity.name else { fatalError("entityName not found in entity: \(destinationEntity)") }
if localPrimaryKey is NSNull {
if value(forKey: relationship.name) != nil {
setValue(nil, forKey: relationship.name)
}
} else if let safeObject = managedObjectContext.safeObject(destinationEntityName, localPrimaryKey: localPrimaryKey, parent: self, parentRelationshipName: relationship.name) {
let currentRelationship = value(forKey: relationship.name)
if currentRelationship == nil || !(currentRelationship! as AnyObject).isEqual(safeObject) {
setValue(safeObject, forKey: relationship.name)
}
} else {
print("Trying to sync a \(self.entity.name!) \(self) with a \(destinationEntityName) with ID \(localPrimaryKey), didn't work because \(destinationEntityName) doesn't exist. Make sure the \(destinationEntityName) exists before proceeding.")
}
}
/**
Syncs the entity's to-one relationship, it will also sync the child of this entity.
- parameter relationship: The relationship to be synced.
- parameter dictionary: The JSON with the changes to be applied to the entity.
- parameter dataStack: The DataStack instance.
*/
func sync_toOneRelationship(_ relationship: NSRelationshipDescription, dictionary: [String: Any], context: NSManagedObjectContext, operations: Sync.OperationOptions, shouldContinueBlock: (() -> Bool)?, objectJSONBlock: ((_ objectJSON: [String: Any]) -> [String: Any])?) {
var filteredObjectDictionary: [String: Any]?
if let customRelationshipName = relationship.customKey {
if customRelationshipName.contains(".") {
if let deepMappingRootKey = customRelationshipName.components(separatedBy: ".").first {
if let rootObject = dictionary[deepMappingRootKey] as? [String: Any] {
if let deepMappingLeaveKey = customRelationshipName.components(separatedBy: ".").last {
filteredObjectDictionary = rootObject[deepMappingLeaveKey] as? [String: Any]
}
}
}
} else {
filteredObjectDictionary = dictionary[customRelationshipName] as? [String: Any]
}
} else if let result = dictionary[relationship.name.hyp_snakeCase()] as? [String: Any] {
filteredObjectDictionary = result
} else if let result = dictionary[relationship.name] as? [String: Any] {
filteredObjectDictionary = result
}
if let toOneObjectDictionary = filteredObjectDictionary {
guard let managedObjectContext = self.managedObjectContext else { return }
guard let destinationEntity = relationship.destinationEntity else { return }
guard let entityName = destinationEntity.name else { return }
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext) else { return }
let localPrimaryKey = toOneObjectDictionary[entity.sync_remotePrimaryKey()]
let object = managedObjectContext.safeObject(entityName, localPrimaryKey: localPrimaryKey, parent: self, parentRelationshipName: relationship.name) ?? NSEntityDescription.insertNewObject(forEntityName: entityName, into: managedObjectContext)
object.sync_fill(with: toOneObjectDictionary, parent: self, parentRelationship: relationship, context: context, operations: operations, shouldContinueBlock: shouldContinueBlock, objectJSONBlock: objectJSONBlock)
let currentRelationship = self.value(forKey: relationship.name)
if currentRelationship == nil || !(currentRelationship! as AnyObject).isEqual(object) {
setValue(object, forKey: relationship.name)
}
} else {
let currentRelationship = self.value(forKey: relationship.name)
if currentRelationship != nil {
setValue(nil, forKey: relationship.name)
}
}
}
}
|
mit
|
3c2ef6872b2ae47c35010e7343acbc65
| 59.992908 | 357 | 0.603915 | 5.959806 | false | false | false | false |
certainly/Caculator
|
Cassini/Cassini/DemoURL.swift
|
1
|
790
|
//
// DemoURL.swift
// Cassini
//
// Created by certainly on 2017/3/28.
// Copyright © 2017年 certainly. All rights reserved.
//
import Foundation
struct DemoURL
{
static let stanford = URL(string: "http://stanford.edu/about/images/intro_about.jpg")
static var NASA: Dictionary<String,URL> = {
let NASAURLStrings = [
"Cassini" : "http://www.jpl.nasa.gov/images/cassini/20090202/pia03883-full.jpg",
"Earth" : "http://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg",
"Saturn" : "http://www.nasa.gov/sites/default/files/saturn_collage.jpg"
]
var urls = Dictionary<String,URL>()
for (key, value) in NASAURLStrings {
urls[key] = URL(string: value)
}
return urls
}()
}
|
mit
|
d40c0c658ee0d7dc6172ab4961575057
| 28.148148 | 92 | 0.611182 | 3.306723 | false | false | false | false |
wess/Cargo
|
Sources/resource/json.swift
|
2
|
1552
|
import Foundation
public protocol JSONResource {
var json:[String:Any] { get }
var jsonString:String { get }
}
public extension JSONResource where Self : Resource {
private func convertProperties() -> [String:Any] {
return properties.reduce([:]) { current, next in
var _current = current
if let property = next.1 as? Property {
_current[next.0] = property.value
} else if let relationship = next.1 as? Relationship {
_current[next.0] = convertRelationships(relationship)
}
return _current
}
}
private func convertRelationships(_ relationship:Relationship<Resource>) -> [String:Any] {
return relationship.list.reduce([:]) { current, next in
var _current = current
for (name, value) in next.properties {
if let property = value as? Property {
_current[name] = property.value
}
else if let rel = value as? Relationship {
_current[name] = convertRelationships(rel)
}
}
return _current
}
}
public var json:[String:Any] {
return [:]
}
public var jsonString:String {
do {
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
guard let jsonString = String(data: data, encoding: .utf8) else { fatalError("Unable to convert json dictionary to string") }
return jsonString
} catch {
fatalError("Unable to encode resource's json dictionary")
}
return ""
}
}
|
mit
|
2eeea49fc779e53bf23f8826a99f90a4
| 26.22807 | 132 | 0.61018 | 4.524781 | false | false | false | false |
ahoppen/swift
|
test/Constraints/members.swift
|
3
|
25957
|
// RUN: %target-typecheck-verify-swift -swift-version 5
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
_ = x.f0(i)
x.f0(i).f1(i)
g0(X.f1) // expected-error{{cannot reference 'mutating' method as function value}}
_ = x.f0(x.f2(1))
_ = x.f0(1).f2(i)
_ = yf.f0(1)
_ = yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{cannot reference 'mutating' method as function value}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{enum case 'none' cannot be used as an instance member}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In {
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
static func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : UnavailMember { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{for-in loop requires 'S22490787' to conform to 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'none'}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
// SR-2193: QoI: better diagnostic when a decl exists, but is not a type
enum SR_2193_Error: Error {
case Boom
}
do {
throw SR_2193_Error.Boom
} catch let e as SR_2193_Error.Boom { // expected-error {{enum case 'Boom' is not a member type of 'SR_2193_Error'}}
}
// rdar://problem/25341015
extension Sequence {
func r25341015_1() -> Int {
return max(1, 2) // expected-error {{use of 'max' refers to instance method rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}}
}
}
class C_25341015 {
static func baz(_ x: Int, _ y: Int) {}
func baz() {}
func qux() {
baz(1, 2) // expected-error {{static member 'baz' cannot be used on instance of type 'C_25341015'}} {{5-5=C_25341015.}}
}
}
struct S_25341015 {
static func foo(_ x: Int, y: Int) {}
func foo(z: Int) {}
func bar() {
foo(1, y: 2) // expected-error {{static member 'foo' cannot be used on instance of type 'S_25341015'}} {{5-5=S_25341015.}}
}
}
func r25341015() {
func baz(_ x: Int, _ y: Int) {}
class Bar {
func baz() {}
func qux() {
baz(1, 2) // expected-error {{use of 'baz' refers to instance method rather than local function 'baz'}}
}
}
}
func r25341015_local(x: Int, y: Int) {}
func r25341015_inner() {
func r25341015_local() {}
r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}}
}
// rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely
func foo_32854314() -> Double {
return 42
}
func bar_32854314() -> Int {
return 0
}
extension Array where Element == Int {
func foo() {
let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func foo(_ x: Int, _ y: Double) {
let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func bar() {
let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
}
// Crash in diagnoseImplicitSelfErrors()
struct Aardvark {
var snout: Int
mutating func burrow() {
dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}}
}
func dig(_: inout Int, _: Int) {}
}
func rdar33914444() {
struct A {
enum R<E: Error> {
case e(E) // expected-note {{'e' declared here}}
}
struct S {
enum E: Error {
case e1
}
let e: R<E>
}
}
_ = A.S(e: .e1)
// expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}}
}
// SR-5324: Better diagnostic when instance member of outer type is referenced from nested type
struct Outer {
var outer: Int
struct Inner {
var inner: Int
func sum() -> Int {
return inner + outer
// expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}}
}
}
}
// rdar://problem/39514009 - don't crash when trying to diagnose members with special names
print("hello")[0] // expected-error {{value of type '()' has no subscripts}}
func rdar40537782() {
class A {}
class B : A {
override init() {}
func foo() -> A { return A() }
}
struct S<T> {
init(_ a: T...) {}
}
func bar<T>(_ t: T) {
_ = S(B(), .foo(), A()) // expected-error {{type 'A' has no member 'foo'}}
}
}
func rdar36989788() {
struct A<T> {
func foo() -> A<T> {
return self
}
}
func bar<T>(_ x: A<T>) -> (A<T>, A<T>) {
return (x.foo(), x.undefined()) // expected-error {{value of type 'A<T>' has no member 'undefined'}}
}
}
func rdar46211109() {
struct MyIntSequenceStruct: Sequence {
struct Iterator: IteratorProtocol {
var current = 0
mutating func next() -> Int? {
return current + 1
}
}
func makeIterator() -> Iterator {
return Iterator()
}
}
func foo<E, S: Sequence>(_ type: E.Type) -> S? where S.Element == E {
return nil
}
let _: MyIntSequenceStruct? = foo(Int.Self)
// expected-error@-1 {{type 'Int' has no member 'Self'}}
}
class A {}
enum B {
static func foo() {
bar(A()) // expected-error {{instance member 'bar' cannot be used on type 'B'}}
}
func bar(_: A) {}
}
class C {
static func foo() {
bar(0) // expected-error {{instance member 'bar' cannot be used on type 'C'}}
}
func bar(_: Int) {}
}
class D {
static func foo() {}
func bar() {
foo() // expected-error {{static member 'foo' cannot be used on instance of type 'D'}}
}
}
func rdar_48114578() {
struct S<T> {
var value: T
static func valueOf<T>(_ v: T) -> S<T> {
return S<T>(value: v)
}
}
typealias A = (a: [String]?, b: Int)
func foo(_ a: [String], _ b: Int) -> S<A> {
let v = (a, b)
return .valueOf(v)
}
func bar(_ a: [String], _ b: Int) -> S<A> {
return .valueOf((a, b)) // Ok
}
}
struct S_Min {
var xmin: Int = 42
}
func xmin(_: Int, _: Float) -> Int { return 0 }
func xmin(_: Float, _: Int) -> Int { return 0 }
extension S_Min : CustomStringConvertible {
public var description: String {
return "\(xmin)" // Ok
}
}
// rdar://problem/50679161
func rdar50679161() {
struct Point {}
struct S {
var w, h: Point
}
struct Q {
init(a: Int, b: Int) {}
init(a: Point, b: Point) {}
}
func foo() {
_ = { () -> Void in
// Missing `.self` or `init` is not diagnosed here because there are errors in
// `if let` statement and `MiscDiagnostics` only run if the body is completely valid.
var foo = S
if let v = Int?(1) {
var _ = Q(
a: v + foo.w,
// expected-error@-1 {{instance member 'w' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
b: v + foo.h
// expected-error@-1 {{instance member 'h' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
)
}
}
_ = { () -> Void in
var foo = S
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
print(foo)
}
}
}
func rdar_50467583_and_50909555() {
if #available(macOS 11.3, iOS 14.5, tvOS 14.5, watchOS 7.4, *) {
// rdar://problem/50467583
let _: Set = [Int][] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Set'}}
// expected-error@-1 {{no exact matches in call to subscript}}
// expected-note@-2 {{found candidate with type '(Int) -> Int'}}
// expected-note@-3 {{found candidate with type '(Range<Int>) -> ArraySlice<Int>'}}
// expected-note@-4 {{found candidate with type '((UnboundedRange_) -> ()) -> ArraySlice<Int>'}}
}
// rdar://problem/50909555
struct S {
static subscript(x: Int, y: Int) -> Int { // expected-note {{'subscript(_:_:)' declared here}}
return 1
}
}
func test(_ s: S) {
s[1] // expected-error {{static member 'subscript' cannot be used on instance of type 'S'}} {{5-6=S}}
// expected-error@-1 {{missing argument for parameter #2 in call}} {{8-8=, <#Int#>}}
}
}
// SR-9396 (rdar://problem/46427500) - Nonsensical error message related to constrained extensions
struct SR_9396<A, B> {}
extension SR_9396 where A == Bool { // expected-note {{where 'A' = 'Int'}}
func foo() {}
}
func test_sr_9396(_ s: SR_9396<Int, Double>) {
s.foo() // expected-error {{referencing instance method 'foo()' on 'SR_9396' requires the types 'Int' and 'Bool' be equivalent}}
}
// rdar://problem/34770265 - Better diagnostic needed for constrained extension method call
extension Dictionary where Key == String { // expected-note {{where 'Key' = 'Int'}}
func rdar_34770265_key() {}
}
extension Dictionary where Value == String { // expected-note {{where 'Value' = 'Int'}}
func rdar_34770265_val() {}
}
func test_34770265(_ dict: [Int: Int]) {
dict.rdar_34770265_key()
// expected-error@-1 {{referencing instance method 'rdar_34770265_key()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
dict.rdar_34770265_val()
// expected-error@-1 {{referencing instance method 'rdar_34770265_val()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
}
// SR-12672
_ = [.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Any] = [.e] // expected-error {{type 'Any' has no member 'e'}}
_ = [1 :.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
_ = [.e: 1] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Int: Any] = [1 : .e] // expected-error {{type 'Any' has no member 'e'}}
let _ : (Int, Any) = (1, .e) // expected-error {{type 'Any' has no member 'e'}}
_ = (1, .e) // expected-error {{cannot infer contextual base in reference to member 'e'}}
// SR-13359
typealias Pair = (Int, Int)
func testSR13359(_ pair: (Int, Int), _ alias: Pair, _ void: Void, labeled: (a: Int, b: Int)) {
_ = pair[0] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.0'?}} {{11-14=.0}}
_ = pair[1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.1'?}} {{11-14=.1}}
_ = pair[2] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[100] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair["string"] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[-1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[1, 1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = void[0] // expected-error {{value of type 'Void' has no subscripts}}
// Other representations of literals
_ = pair[0x00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[0b00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = alias[0] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.0'?}} {{12-15=.0}}
_ = alias[1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.1'?}} {{12-15=.1}}
_ = alias[2] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[100] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias["string"] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[-1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[1, 1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[0x00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[0b00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
// Labeled tuple base
_ = labeled[0] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.0'?}} {{14-17=.0}}
_ = labeled[1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.1'?}} {{14-17=.1}}
_ = labeled[2] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[100] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled["string"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[-1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[1, 1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[0x00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[0b00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
// Suggesting use label access
_ = labeled["a"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.a'?}} {{14-19=.a}}
_ = labeled["b"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.b'?}} {{14-19=.b}}
_ = labeled["c"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[""] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
}
// rdar://problem/66891544 - incorrect diagnostic ("type is ambiguous") when base type of a reference cannot be determined
func rdar66891544() {
func foo<T>(_: T, defaultT: T? = nil) {}
func foo<U>(_: U, defaultU: U? = nil) {}
foo(.bar) // expected-error {{cannot infer contextual base in reference to member 'bar'}}
}
// rdar://55369704 - extraneous diagnostics produced in combination with missing/misspelled members
func rdar55369704() {
struct S {
}
func test(x: Int, s: S) {
_ = x - Int(s.value) // expected-error {{value of type 'S' has no member 'value'}}
}
}
// SR-14533
struct SR14533 {
var xs: [Int]
}
func fSR14533(_ s: SR14533) {
for (x1, x2) in zip(s.xs, s.ys) {
// expected-error@-1{{value of type 'SR14533' has no member 'ys'}}
}
}
// rdar://92358570
class SomeClassBound {}
protocol ClassBoundProtocol: SomeClassBound {
}
struct RDAR92358570<Element> {}
extension RDAR92358570 where Element : SomeClassBound {
// expected-note@-1 2 {{where 'Element' = 'any ClassBoundProtocol', 'SomeClassBound' = 'AnyObject'}}
// expected-note@-2 2 {{where 'Element' = 'any SomeClassBound & ClassBoundProtocol', 'SomeClassBound' = 'AnyObject'}}
func doSomething() {}
static func doSomethingStatically() {}
}
func rdar92358570(_ x: RDAR92358570<ClassBoundProtocol>, _ y: RDAR92358570<SomeClassBound & ClassBoundProtocol>) {
x.doSomething() // expected-error {{referencing instance method 'doSomething()' on 'RDAR92358570' requires that 'any ClassBoundProtocol' inherit from 'AnyObject'}}
RDAR92358570<ClassBoundProtocol>.doSomethingStatically() // expected-error {{referencing static method 'doSomethingStatically()' on 'RDAR92358570' requires that 'any ClassBoundProtocol' inherit from 'AnyObject'}}
y.doSomething() // expected-error {{referencing instance method 'doSomething()' on 'RDAR92358570' requires that 'any SomeClassBound & ClassBoundProtocol' inherit from 'AnyObject'}}
RDAR92358570<SomeClassBound & ClassBoundProtocol>.doSomethingStatically() // expected-error {{referencing static method 'doSomethingStatically()' on 'RDAR92358570' requires that 'any SomeClassBound & ClassBoundProtocol' inherit from 'AnyObject'}}
}
|
apache-2.0
|
f6b5afba356bdb90f95df98936edc119
| 32.406692 | 248 | 0.648804 | 3.589187 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Route and directions/Find closest facility to an incident (interactive)/FindClosestFacilityInteractiveViewController.swift
|
1
|
6185
|
//
// Copyright © 2020 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import ArcGIS
class FindClosestFacilityInteractiveViewController: UIViewController {
@IBOutlet var mapView: AGSMapView! {
didSet {
// Initialize the map.
let map = AGSMap(basemapStyle: .arcGISStreets)
mapView.map = map
mapView.setViewpoint(AGSViewpoint(latitude: 32.727, longitude: -117.1750, scale: 144447.638572))
mapView.touchDelegate = self
// Create symbols and graphics to add to the graphic overlays.
mapView.graphicsOverlays.add(makeFacilitiesOverlay())
mapView.graphicsOverlays.add(incidentGraphicsOverlay)
}
}
// Create a closest facility task from the network service URL.
private let closestFacilityTask: AGSClosestFacilityTask = {
let networkServiceURL = URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility")!
return AGSClosestFacilityTask(url: networkServiceURL)
}()
// Create a graphic overlay to the map.
private var incidentGraphicsOverlay = AGSGraphicsOverlay()
// Create graphics to represent the route.
private let routeSymbol = AGSSimpleLineSymbol(style: .solid, color: .blue, width: 2.0)
// Create an array of facilities in the area.
private var facilities = [
AGSFacility(point: AGSPoint(x: -1.3042129900625112E7, y: 3860127.9479775648, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3042193400557665E7, y: 3862448.873041752, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3046882875518233E7, y: 3862704.9896770366, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3040539754780494E7, y: 3862924.5938606677, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3042571225655518E7, y: 3858981.773018156, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3039784633928463E7, y: 3856692.5980474586, spatialReference: .webMercator())),
AGSFacility(point: AGSPoint(x: -1.3049023883956768E7, y: 3861993.789732541, spatialReference: .webMercator()))
]
// Create the graphics and add them to the graphics overlay
func makeFacilitiesOverlay() -> AGSGraphicsOverlay {
let facilitySymbolURL = URL(string: "https://static.arcgis.com/images/Symbols/SafetyHealth/Hospital.png")!
let facilitySymbol = AGSPictureMarkerSymbol(url: facilitySymbolURL)
facilitySymbol.height = 30
facilitySymbol.width = 30
let graphicsOverlay = AGSGraphicsOverlay()
graphicsOverlay.graphics.addObjects(from: facilities.map { AGSGraphic(geometry: $0.geometry, symbol: facilitySymbol) })
return graphicsOverlay
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FindClosestFacilityInteractiveViewController"]
}
}
// MARK: - AGSGeoViewTouchDelegate
extension FindClosestFacilityInteractiveViewController: AGSGeoViewTouchDelegate {
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// Find the closest facilities with the default parameters.
closestFacilityTask.defaultClosestFacilityParameters { [weak self] (parameters, error) in
guard let self = self else { return }
if let parameters = parameters {
parameters.setFacilities(self.facilities)
// Create a symbol for the incident.
let incidentSymbol = AGSSimpleMarkerSymbol(style: .cross, color: .black, size: 20)
// Remove previous graphics.
self.incidentGraphicsOverlay.graphics.removeAllObjects()
// Create a point and graphics for the incident.
let graphic = AGSGraphic(geometry: mapPoint, symbol: incidentSymbol)
self.incidentGraphicsOverlay.graphics.add(graphic)
// Set the incident for the parameters.
parameters.setIncidents([AGSIncident(point: mapPoint)])
self.closestFacilityTask.solveClosestFacility(with: parameters) { [weak self] (result, error) in
guard let self = self else { return }
if let result = result {
// Get the ranked list of closest facilities.
let rankedList = result.rankedFacilityIndexes(forIncidentIndex: 0)
// Get the facility closest to the incident.
let closestFacility = rankedList?.first as! Int
// Calculate the route based on the closest facility and chosen incident.
let route = result.route(forFacilityIndex: closestFacility, incidentIndex: 0)
// Display the route graphics.
self.incidentGraphicsOverlay.graphics.add(AGSGraphic(geometry: route?.routeGeometry, symbol: self.routeSymbol))
} else if let error = error {
self.presentAlert(error: error)
}
}
} else if let error = error {
self.presentAlert(error: error)
}
}
}
}
|
apache-2.0
|
89ca8f4a908ed0e8b6e6b028f35c0a7e
| 49.688525 | 157 | 0.650065 | 4.660136 | false | false | false | false |
huonw/swift
|
test/SILGen/owned.swift
|
3
|
1494
|
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
// see shared.swift for thunks/conversions between __shared and __owned.
class RefAggregate {}
struct ValueAggregate { let x = RefAggregate() }
// CHECK-LABEL: sil hidden @$S5owned0A10_arguments7trivial5value3refySin_AA14ValueAggregateVnAA03RefG0CntF : $@convention(thin) (Int, @owned ValueAggregate, @owned RefAggregate) -> () {
func owned_arguments(trivial : __owned Int, value : __owned ValueAggregate, ref : __owned RefAggregate) {
let t = trivial
let v = value
let r = ref
}
struct Foo {
var x: ValueAggregate
// CHECK-LABEL: sil hidden @$S5owned3FooV20methodOwnedArguments7trivial5value3refySin_AA14ValueAggregateVnAA03RefJ0CntF : $@convention(method) (Int, @owned ValueAggregate, @owned RefAggregate, @guaranteed Foo) -> () {
func methodOwnedArguments(trivial : __owned Int, value : __owned ValueAggregate, ref : __owned RefAggregate) {
let t = trivial
let v = value
let r = ref
}
}
// rdar://problem/38390524
// CHECK-LABEL: sil hidden @$S5owned19oneUnnamedArgument1yyAA14ValueAggregateVnF : $@convention(thin) (@owned ValueAggregate) -> () {
func oneUnnamedArgument1(_: __owned ValueAggregate) {}
// CHECK-LABEL: sil hidden @$S5owned19oneUnnamedArgument2yyAA12RefAggregateCnF : $@convention(thin) (@owned RefAggregate) -> () {
func oneUnnamedArgument2(_: __owned RefAggregate) {}
|
apache-2.0
|
309f79274e198a01968bad262e7c42ea
| 48.8 | 221 | 0.727577 | 3.753769 | false | false | false | false |
5calls/ios
|
FiveCalls/FiveCalls/ReportOutcomeOperation.swift
|
1
|
2191
|
//
// ReportOutcomeOperation.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/4/17.
// Copyright © 2017 5calls. All rights reserved.
//
import Foundation
class ReportOutcomeOperation : BaseOperation {
//Input properties
var log: ContactLog
var outcome: Outcome
//Output properties
var httpResponse: HTTPURLResponse?
var error: Error?
init(log: ContactLog, outcome: Outcome) {
self.log = log
self.outcome = outcome
}
override func execute() {
let config = URLSessionConfiguration.default
let session = URLSessionProvider.buildSession(configuration: config)
let url = URL(string: "https://api.5calls.org/v1/report")!
// rather than avoiding network calls during debug,
// indicate they shouldn't be included in counts
let via: String
#if DEBUG
via = "test"
#else
via = "ios"
#endif
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
if let authToken = SessionManager.shared.idToken {
request.setValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
}
let query = "result=\(outcome.label)&contactid=\(log.contactId)&issueid=\(log.issueId)&phone=\(log.phone)&via=\(via)"
guard let data = query.data(using: .utf8) else {
print("error creating HTTP POST body")
return
}
request.httpBody = data
let task = session.dataTask(with: request) { (data, response, error) in
if let e = error {
self.error = e
} else {
let http = response as! HTTPURLResponse
self.httpResponse = http
if let _ = data, http.statusCode == 200 {
print("sent report successfully")
var logs = ContactLogs.load()
logs.markReported(self.log)
logs.save()
}
}
self.finish()
}
task.resume()
}
}
|
mit
|
cb0acc0464cb95d336833074b0419734
| 29.84507 | 125 | 0.569406 | 4.66951 | false | true | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/TakeOrder/器械信息/View/OMSMetailTableView.swift
|
1
|
10719
|
//
// OMSMetailTableView.swift
// OMS-WH
//
// Created by xuech on 2017/9/7.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class OMSMetailTableView: UITableView {
var orderDetailModel : DealOrderInfoModel?{
didSet{
sOType = orderDetailModel?.sOType ?? ""
//备货订单无法编辑
if sOType == SoTypeName.OPER && sOType != ""{
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 64))
let addBtn = UIButton("散件", titleColor: kAppearanceColor, target:self, action: #selector(addCompent))
addBtn.setImage(UIImage(named:"ab_add"), for: UIControlState.normal)
addBtn.frame = CGRect(x: (kScreenWidth-100)/2, y: 8, width: 100, height: 28)
footerView.addSubview(addBtn)
self.tableFooterView = footerView
}
}
}
var parsentViewController :UIViewController?
//编辑物料后返回的数据
fileprivate var prdouctLines = CommonDataManager.getData().prdouctLines {
didSet{
if prdouctLines.count > 0 {
self.reloadData()
}
}
}
fileprivate var viewModel = OMSBrandViewModel()
fileprivate var sOType = ""
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setupUI()
NotificationCenter.default.addObserver(self, selector: #selector(productLineSelected), name: NSNotification.Name.ProductLinesSelected, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(editProductLine), name: NSNotification.Name.EditProductLine, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(finishedAddProductLine), name: NSNotification.Name.FinishedAddProductLine, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(finishedAddTemplate), name: NSNotification.Name.FinishedAddTemplate, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:新增物料
@objc func finishedAddProductLine(notification :Notification) {
CommonDataManager.getData().prdouctLines = prdouctLines
if let status = orderDetailModel?.statusValue {
if Int(status) > 60 && orderDetailModel?.instrumentType == .addGoodslist{
let notificationData = notification.userInfo as? [String:AnyObject]
if let notificationData = notificationData {
let wsNoteList = notificationData["wsNoteList"] as? [[String:String]]
let addMoreGoods = AddMoreGoodsViewController()
addMoreGoods.orderDetailModel = orderDetailModel
addMoreGoods.wsNoteList = wsNoteList
parsentViewController?.navigationController?.pushViewController(addMoreGoods, animated: true)
}
}else{
parsentViewController?.navigationController?.popViewController(animated: true)
}
}
}
//MARK:模版添加完成
@objc func finishedAddTemplate(notification :Notification) {
let notificationData = notification.userInfo as? [String:AnyObject]
if let notificationData = notificationData {
guard let dictoryArray = notificationData["FinishedAddTemplate"] as? [MedMaterialList] else { return }
guard let result = viewModel.templateNotificationData(medMaterialList: dictoryArray, orialData: prdouctLines) else { return }
prdouctLines = result
CommonDataManager.getData().prdouctLines = prdouctLines
}
}
//MARK:编辑物料
@objc func editProductLine(notification :Notification) {
let notificationData = notification.userInfo as? [String:AnyObject]
if let notificationData = notificationData {
guard let dictoryArray = notificationData["EditProductLine"] as? TempleProlns else { return }
guard let index = notificationData["index"] as? IndexPath else { return }
guard let model = dictoryArray.medMaterialList else { return }
guard var prolnsArray = prdouctLines[index.section].prolns else { return }
guard let medMaterialList = prolnsArray[index.row - 1].medMaterialList else { return }
if medMaterialList.count > 0 {
prolnsArray[index.row - 1].medMaterialList! = model
}
CommonDataManager.getData().prdouctLines = prdouctLines
self.reloadData()
}
}
//MARK:把新添加的散件添加到原数据中
@objc func productLineSelected(notification :Notification) {
let notificationData = notification.userInfo as? [String:AnyObject]
if let notificationData = notificationData {
guard let dictoryArray = notificationData["ProductLinesSelected"] as? [[String:AnyObject]] else { return }
guard let result = viewModel.notificationData(dictoryArray: dictoryArray, templeData: prdouctLines) else { return }
prdouctLines = result
CommonDataManager.getData().prdouctLines = prdouctLines
self.reloadData()
}
}
//MARK: private method
private func setupUI() {
self.delegate = self
self.dataSource = self
self.isHidden = true
self.rowHeight = 44
self.contentInset = UIEdgeInsetsMake(0, 0, 90, 0)
self.tableFooterView = UIView()
self.separatorStyle = .singleLine
}
@objc func addCompent() {
let brand = ChooseBrandViewController()
brand.orderDetailDataReload(dLOrgCode: orderDetailModel?.sOCreateByOrgCode, oIOrgCode: orderDetailModel?.sOOIOrgCode)
parsentViewController?.navigationController?.pushViewController(brand, animated: true)
}
}
extension OMSMetailTableView : UITableViewDataSource,UITableViewDelegate{
func numberOfSections(in tableView: UITableView) -> Int{
return prdouctLines.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let prolnsArray = prdouctLines[section].prolns else { return 0 }
return prolnsArray.count + 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let product = prdouctLines[indexPath.section]
guard let prolnsArray = product.prolns else { return UITableViewCell() }
if indexPath.row == 0 {
let cell = BrandTableViewCell.loadFromNib()
cell.brandLB.text = "\(product.medBrandName) 产品线:\(prolnsArray.count)条"
return cell
}else{
let cell = ProlnsTableViewCell.loadFromNib("ProlnsTableViewCell")
let index = prolnsArray[indexPath.row - 1]
cell.configueModel(model: index)
cell.delegate = self
if sOType == SoTypeName.INSTK && !sOType.isBlank {
cell.switchBtn.isEnabled = false
}
// cell.switchBtn.addTarget(self, action: #selector(switchEvent), for: UIControlEvents.valueChanged)
return cell
}
}
// @objc func switchEvent(_ sender: UISwitch){
// }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath.row != 0 {
if let product = prdouctLines[indexPath.section].prolns{
let prductln = product[indexPath.row - 1]
let editMedterial = EditMedterialsViewController()
editMedterial.prdouctLines = prdouctLines
editMedterial.prductln = prductln
editMedterial.orderDetail = orderDetailModel
editMedterial.index = indexPath
parsentViewController?.navigationController?.pushViewController(editMedterial, animated: true)
}
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 5
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if sOType == SoTypeName.OPER{
return true
}
return false
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCellEditingStyle.delete{
if indexPath.row == 0{
Method.getMethod().alertShow(title: "提示", message: "是否删除此品牌", controller: parsentViewController, cancelMethod: {
}, confirmMethod: {
self.beginUpdates()
let set = NSIndexSet(index: indexPath.section) as IndexSet
self.deleteSections(set, with: .right)
self.prdouctLines.remove(at: indexPath.section)
CommonDataManager.getData().prdouctLines = self.prdouctLines
self.endUpdates()
})
}else{
Method.getMethod().alertShow(title: "提示", message: "是否删除此产品线", controller: parsentViewController, cancelMethod: {
}, confirmMethod: {
guard var prolnsArray = self.prdouctLines[indexPath.section].prolns else { return }
prolnsArray.remove(at: indexPath.row - 1)
self.prdouctLines[indexPath.section].prolns = prolnsArray
if prolnsArray.count == 0 {
self.prdouctLines.remove(at: indexPath.section)
}
CommonDataManager.getData().prdouctLines = self.prdouctLines
self.reloadData()
})
}
}
}
}
extension OMSMetailTableView : ProlnsTableViewCellDelegate{
func modifyModel(currentCell: ProlnsTableViewCell, model: TempleProlns?) {
if let templeProlns = model,let indexPath = self.indexPath(for: currentCell) {
let product = prdouctLines[indexPath.section]
guard var prolnsArray = product.prolns else { return }
prolnsArray[indexPath.row - 1] = templeProlns
self.reloadData()
}
}
}
|
mit
|
a3305391c434c7ab050973052719d3db
| 41.296 | 160 | 0.625497 | 4.791119 | false | false | false | false |
DavdRoman/Popsicle
|
PopsicleDemo/PageScrollView.swift
|
1
|
1519
|
//
// PageScrollView.swift
// Popsicle
//
// Created by David Román Aguirre on 04/11/15.
// Copyright © 2015 David Román Aguirre. All rights reserved.
//
import UIKit
class FirstPageView: UIView {
@IBOutlet weak var label: UILabel?
@IBOutlet weak var imageView: UIImageView?
}
class SecondPageView: UIView {
@IBOutlet weak var label: UILabel?
}
class ThirdPageView: UIView {
@IBOutlet weak var label1: UILabel?
@IBOutlet weak var label2: UILabel?
}
class FourthPageView: UIView {
@IBOutlet weak var label: UILabel?
}
class PageScrollView: DRPageScrollView {
let firstPageView: FirstPageView
let secondPageView: SecondPageView
let thirdPageView: ThirdPageView
let fourthPageView: FourthPageView
override init(frame: CGRect) {
let views = UIView.viewsByClassInNibNamed("PageViews")
self.firstPageView = views["PopsicleDemo.FirstPageView"] as! FirstPageView
self.secondPageView = views["PopsicleDemo.SecondPageView"] as! SecondPageView
self.thirdPageView = views["PopsicleDemo.ThirdPageView"] as! ThirdPageView
self.fourthPageView = views["PopsicleDemo.FourthPageView"] as! FourthPageView
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToSuperview() {
if self.superview != nil {
for pv in [firstPageView, secondPageView, thirdPageView, fourthPageView] {
self.addPageWithHandler { pageView in
pageView.addSubview(pv)
pv.pinToSuperviewEdges()
}
}
}
}
}
|
mit
|
79ef952acabb5e0a4298c3f9911886ac
| 25.137931 | 79 | 0.751319 | 3.558685 | false | false | false | false |
el-hoshino/NotAutoLayout
|
Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/CenterMiddleBottom.Individual.swift
|
1
|
1389
|
//
// CenterMiddleBottom.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct CenterMiddleBottom {
let center: LayoutElement.Horizontal
let middle: LayoutElement.Vertical
let bottom: LayoutElement.Vertical
}
}
// MARK: - Make Frame
extension IndividualProperty.CenterMiddleBottom {
private func makeFrame(center: Float, middle: Float, bottom: Float, width: Float) -> Rect {
let x = center - width.half
let height = (bottom - middle).double
let y = bottom - height
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Width
extension IndividualProperty.CenterMiddleBottom: LayoutPropertyCanStoreWidthToEvaluateFrameType {
public func evaluateFrame(width: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let center = self.center.evaluated(from: parameters)
let middle = self.middle.evaluated(from: parameters)
let bottom = self.bottom.evaluated(from: parameters)
let height = (bottom - middle).double
let width = width.evaluated(from: parameters, withTheOtherAxis: .height(height))
return self.makeFrame(center: center, middle: middle, bottom: bottom, width: width)
}
}
|
apache-2.0
|
5deb2673fcfb57058b7a0aee6dc09624
| 23.105263 | 115 | 0.724891 | 3.881356 | false | false | false | false |
badoo/Chatto
|
ChattoAdditions/sources/Chat Items/PhotoMessages/PhotoMessageModel.swift
|
1
|
2272
|
/*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import Chatto
public protocol PhotoMessageModelProtocol: DecoratedMessageModelProtocol, ContentEquatableChatItemProtocol {
var image: UIImage { get }
var imageSize: CGSize { get }
}
open class PhotoMessageModel<MessageModelT: MessageModelProtocol>: PhotoMessageModelProtocol {
public var messageModel: MessageModelProtocol {
return self._messageModel
}
public let _messageModel: MessageModelT // Can't make messageModel: MessageModelT: https://gist.github.com/diegosanchezr/5a66c7af862e1117b556
public let image: UIImage
public let imageSize: CGSize
public var canReply: Bool { self.messageModel.canReply }
public init(messageModel: MessageModelT, imageSize: CGSize, image: UIImage) {
self._messageModel = messageModel
self.imageSize = imageSize
self.image = image
}
public func hasSameContent(as anotherItem: ChatItemProtocol) -> Bool {
guard let anotherMessageModel = anotherItem as? PhotoMessageModel else { return false }
return self.image == anotherMessageModel.image
&& self.imageSize == anotherMessageModel.imageSize
}
}
|
mit
|
1858af597fb4c78934f95026850797ed
| 43.54902 | 145 | 0.763204 | 4.773109 | false | false | false | false |
miranda-ng/miranda-ng
|
protocols/Telegram/tdlib/td/example/swift/src/main.swift
|
1
|
5871
|
//
// Copyright Aliaksei Levin ([email protected]), Arseny Smirnov ([email protected]) 2014-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
import Foundation
// TDLib Client Swift binding
class TdClient {
typealias Client = UnsafeMutableRawPointer
var client = td_json_client_create()!
let tdlibMainLoop = DispatchQueue(label: "TDLib")
let tdlibQueryQueue = DispatchQueue(label: "TDLibQuery")
var queryF = Dictionary<Int64, (Dictionary<String,Any>)->()>()
var updateF: ((Dictionary<String,Any>)->())?
var queryId: Int64 = 0
func queryAsync(query: [String: Any], f: ((Dictionary<String,Any>)->())? = nil) {
tdlibQueryQueue.async {
var newQuery = query
if f != nil {
let nextQueryId = self.queryId + 1
newQuery["@extra"] = nextQueryId
self.queryF[nextQueryId] = f
self.queryId = nextQueryId
}
td_json_client_send(self.client, to_json(newQuery))
}
}
func querySync(query: [String: Any]) -> Dictionary<String,Any> {
let semaphore = DispatchSemaphore(value:0)
var result = Dictionary<String,Any>()
queryAsync(query: query) {
result = $0
semaphore.signal()
}
semaphore.wait()
return result
}
init() {
}
deinit {
td_json_client_destroy(client)
}
func run(updateHandler: @escaping (Dictionary<String,Any>)->()) {
updateF = updateHandler
tdlibMainLoop.async { [weak self] in
while (true) {
if let s = self {
if let res = td_json_client_receive(s.client, 10) {
let event = String(cString: res)
s.queryResultAsync(event)
}
} else {
break
}
}
}
}
private func queryResultAsync(_ result: String) {
tdlibQueryQueue.async {
let json = try? JSONSerialization.jsonObject(with: result.data(using: .utf8)!, options:[])
if let dictionary = json as? [String:Any] {
if let extra = dictionary["@extra"] as? Int64 {
let index = self.queryF.index(forKey: extra)!
self.queryF[index].value(dictionary)
self.queryF.remove(at: index)
} else {
self.updateF!(dictionary)
}
}
}
}
}
func to_json(_ obj: Any) -> String {
do {
let obj = try JSONSerialization.data(withJSONObject: obj)
return String(data: obj, encoding: .utf8)!
} catch {
return ""
}
}
// An example of usage
td_set_log_verbosity_level(1);
var client = TdClient()
func myReadLine() -> String {
while (true) {
if let line = readLine() {
return line
}
}
}
func updateAuthorizationState(authorizationState: Dictionary<String, Any>) {
switch(authorizationState["@type"] as! String) {
case "authorizationStateWaitTdlibParameters":
client.queryAsync(query:[
"@type":"setTdlibParameters",
"parameters":[
"database_directory":"tdlib",
"use_message_database":true,
"use_secret_chats":true,
"api_id":94575,
"api_hash":"a3406de8d171bb422bb6ddf3bbd800e2",
"system_language_code":"en",
"device_model":"Desktop",
"system_version":"Unknown",
"application_version":"1.0",
"enable_storage_optimizer":true
]
]);
case "authorizationStateWaitEncryptionKey":
client.queryAsync(query: ["@type":"checkDatabaseEncryptionKey", "key":"cucumber"])
case "authorizationStateWaitPhoneNumber":
print("Enter your phone: ")
let phone = myReadLine()
client.queryAsync(query:["@type":"setAuthenticationPhoneNumber", "phone_number":phone], f:checkAuthenticationError)
case "authorizationStateWaitCode":
var first_name: String = ""
var last_name: String = ""
var code: String = ""
if let is_registered = authorizationState["is_registered"] as? Bool, is_registered {
} else {
print("Enter your first name: ")
first_name = myReadLine()
print("Enter your last name: ")
last_name = myReadLine()
}
print("Enter (SMS) code: ")
code = myReadLine()
client.queryAsync(query:["@type":"checkAuthenticationCode", "code":code, "first_name":first_name, "last_name":last_name], f:checkAuthenticationError)
case "authorizationStateWaitPassword":
print("Enter password: ")
let password = myReadLine()
client.queryAsync(query:["@type":"checkAuthenticationPassword", "password":password], f:checkAuthenticationError)
case "authorizationStateReady":
()
default:
assert(false, "TODO: Unknown authorization state");
}
}
func checkAuthenticationError(error: Dictionary<String, Any>) {
if (error["@type"] as! String == "error") {
client.queryAsync(query:["@type":"getAuthorizationState"], f:updateAuthorizationState)
}
}
client.run {
let update = $0
print(update)
if update["@type"] as! String == "updateAuthorizationState" {
updateAuthorizationState(authorizationState: update["authorization_state"] as! Dictionary<String, Any>)
}
}
while true {
sleep(1)
}
|
gpl-2.0
|
7b571f3d06963f36598f016f80174194
| 31.983146 | 161 | 0.556123 | 4.29795 | false | false | false | false |
abertelrud/swift-package-manager
|
IntegrationTests/Package.swift
|
2
|
738
|
// swift-tools-version:5.4
import PackageDescription
let package = Package(
name: "IntegrationTests",
targets: [
.testTarget(name: "IntegrationTests", dependencies: [
.product(name: "SwiftToolsSupport-auto", package: "swift-tools-support-core"),
.product(name: "TSCTestSupport", package: "swift-tools-support-core")
]),
]
)
import class Foundation.ProcessInfo
if ProcessInfo.processInfo.environment["SWIFTCI_USE_LOCAL_DEPS"] == nil {
package.dependencies += [
.package(url: "https://github.com/apple/swift-tools-support-core.git", .branch("main")),
]
} else {
package.dependencies += [
.package(name: "swift-tools-support-core", path: "../TSC"),
]
}
|
apache-2.0
|
ad6eee18de09249e7022bae243647572
| 28.52 | 96 | 0.643631 | 3.765306 | false | true | false | false |
Coledunsby/TwitterClient
|
TwitterClient/LocalTweetProvider.swift
|
1
|
2179
|
//
// LocalTweetProvider.swift
// TwitterClient
//
// Created by Cole Dunsby on 2017-06-20.
// Copyright © 2017 Cole Dunsby. All rights reserved.
//
import RxSwift
import SwiftRandom
private extension Date {
/// Return a random date between two dates
///
/// - Parameters:
/// - startDate: the start date (min)
/// - endDate: the end date (max)
/// - Returns: a random date between the start and end date
static func random(startDate: Date, endDate: Date) -> Date {
let startTimeInterval = startDate.timeIntervalSince1970
let endTimeInterval = endDate.timeIntervalSince1970
let difference = endTimeInterval - startTimeInterval
let random = TimeInterval.random(0, difference)
return Date(timeIntervalSince1970: startTimeInterval + random)
}
}
struct LocalTweetFetcher: TweetFetching {
private let user: User
init(user: User) {
self.user = user
}
/// Return a random number (at least 1) of new random tweets after the last cached tweet and before the current date
func fetch() -> Single<[Tweet]> {
let lastTweet = user.lastTweet
let newTweets = (0 ..< Int.random(1, 5))
.map { _ -> Tweet in
let tweet = Tweet.random(withUser: user)
tweet.date = Date.random(startDate: lastTweet?.date ?? Date.randomWithinDaysBeforeToday(30), endDate: Date())
return tweet
}
.sorted(by: { $0.date < $1.date })
return Single
.just(newTweets)
.simulateNetworkDelay()
}
}
struct LocalTweetPoster: TweetPosting {
private let user: User
init(user: User) {
self.user = user
}
func post(_ text: String) -> Single<Tweet> {
return Single
.just(Tweet(user: user, message: text))
.simulateNetworkDelay()
}
}
struct LocalTweetProvider: TweetProviding {
let fetcher: TweetFetching
let poster: TweetPosting
init(user: User) {
fetcher = LocalTweetFetcher(user: user)
poster = LocalTweetPoster(user: user)
}
}
|
mit
|
962872df3159ae37c98d62c4f4374c23
| 26.56962 | 125 | 0.605601 | 4.356 | false | false | false | false |
badoo/Chatto
|
ChattoApp/ChattoApp/Source/Chat Items/Content Aware Input /ContentAwareInputItem.swift
|
1
|
6145
|
/*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 ChattoAdditions
open class ContentAwareInputItem {
public var textInputHandler: ((String) -> Void)?
let buttonAppearance: TabInputButtonAppearance
public init(tabInputButtonAppearance: TabInputButtonAppearance = ContentAwareInputItem.createDefaultButtonAppearance()) {
self.buttonAppearance = tabInputButtonAppearance
self.customInputView.onAction = { [weak self] (text) in
self?.textInputHandler?(text)
}
}
public static func createDefaultButtonAppearance() -> TabInputButtonAppearance {
let images: [UIControlStateWrapper: UIImage] = [
UIControlStateWrapper(state: .normal): UIImage(named: "custom-icon-unselected", in: Bundle(for: ContentAwareInputItem.self), compatibleWith: nil)!,
UIControlStateWrapper(state: .selected): UIImage(named: "custom-icon-selected", in: Bundle(for: ContentAwareInputItem.self), compatibleWith: nil)!,
UIControlStateWrapper(state: .highlighted): UIImage(named: "custom-icon-selected", in: Bundle(for: ContentAwareInputItem.self), compatibleWith: nil)!
]
return TabInputButtonAppearance(images: images, size: nil)
}
var customInputView: CustomInputView = {
return CustomInputView(frame: .zero)
}()
lazy fileprivate var internalTabView: TabInputButton = {
return TabInputButton.makeInputButton(withAppearance: self.buttonAppearance, accessibilityID: "text.chat.input.view")
}()
open var selected = false {
didSet {
self.internalTabView.isSelected = self.selected
}
}
}
// MARK: - ChatInputItemProtocol
extension ContentAwareInputItem: ChatInputItemProtocol {
public var shouldSaveDraftMessage: Bool {
return false
}
public var supportsExpandableState: Bool {
return true
}
public var expandedStateTopMargin: CGFloat {
return 140.0
}
public var presentationMode: ChatInputItemPresentationMode {
return .customView
}
public var showsSendButton: Bool {
return false
}
public var inputView: UIView? {
return self.customInputView
}
public var tabView: UIView {
return self.internalTabView
}
public func handleInput(_ input: AnyObject) {
if let text = input as? String {
self.textInputHandler?(text)
}
}
}
class CustomInputView: UIView {
var onAction: ((String) -> Void)?
private var label: UILabel!
private var textField: UITextField!
private var button: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor(white: 0.98, alpha: 1.0)
self.commonInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
private func commonInit() {
let textField = UITextField(frame: .zero)
textField.translatesAutoresizingMaskIntoConstraints = false
textField.textAlignment = .center
textField.borderStyle = .roundedRect
textField.text = "Try me"
self.textField = textField
let label = UILabel(frame: .zero)
label.translatesAutoresizingMaskIntoConstraints = false
label.textAlignment = .center
label.numberOfLines = 2
label.textColor = UIColor(white: 0.15, alpha: 1.0)
label.text = "Just a custom content view with text field and button."
self.label = label
let button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: #selector(onTap(_:)), for: .touchUpInside)
button.setTitle("Send Message", for: .normal)
self.button = button
self.addSubview(label)
self.addSubview(textField)
self.addSubview(button)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: self.centerXAnchor),
label.leftAnchor.constraint(equalTo: self.leftAnchor),
label.rightAnchor.constraint(equalTo: self.rightAnchor),
label.heightAnchor.constraint(equalToConstant: 50.0),
label.topAnchor.constraint(equalTo: self.topAnchor, constant: 12.0),
textField.leftAnchor.constraint(equalTo: self.leftAnchor),
textField.rightAnchor.constraint(equalTo: self.rightAnchor),
textField.heightAnchor.constraint(equalToConstant: 50.0),
textField.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 12.0),
button.centerXAnchor.constraint(equalTo: self.centerXAnchor),
button.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 12.0)
])
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.endEditing(true)
}
@objc
private func onTap(_ sender: Any) {
self.onAction?(self.textField.text ?? "Nothing to send")
self.endEditing(true)
}
}
|
mit
|
8a7942e7ada7e6a798cc68a96437c1d6
| 36.242424 | 161 | 0.692107 | 4.85387 | false | false | false | false |
roambotics/swift
|
stdlib/public/Concurrency/ContinuousClock.swift
|
2
|
5476
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 Swift
/// A clock that measures time that always increments but does not stop
/// incrementing while the system is asleep.
///
/// `ContinuousClock` can be considered as a stopwatch style time. The frame of
/// reference of the `Instant` may be bound to process launch, machine boot or
/// some other locally defined reference point. This means that the instants are
/// only comparable locally during the execution of a program.
///
/// This clock is suitable for high resolution measurements of execution.
@available(SwiftStdlib 5.7, *)
public struct ContinuousClock {
/// A continuous point in time used for `ContinuousClock`.
public struct Instant: Codable, Sendable {
internal var _value: Swift.Duration
internal init(_value: Swift.Duration) {
self._value = _value
}
}
public init() { }
}
@available(SwiftStdlib 5.7, *)
extension Clock where Self == ContinuousClock {
/// A clock that measures time that always increments but does not stop
/// incrementing while the system is asleep.
///
/// try await Task.sleep(until: .now + .seconds(3), clock: .continuous)
///
@available(SwiftStdlib 5.7, *)
public static var continuous: ContinuousClock { return ContinuousClock() }
}
@available(SwiftStdlib 5.7, *)
extension ContinuousClock: Clock {
/// The current continuous instant.
public var now: ContinuousClock.Instant {
ContinuousClock.now
}
/// The minimum non-zero resolution between any two calls to `now`.
public var minimumResolution: Swift.Duration {
var seconds = Int64(0)
var nanoseconds = Int64(0)
_getClockRes(
seconds: &seconds,
nanoseconds: &nanoseconds,
clock: _ClockID.continuous.rawValue)
return .seconds(seconds) + .nanoseconds(nanoseconds)
}
/// The current continuous instant.
public static var now: ContinuousClock.Instant {
var seconds = Int64(0)
var nanoseconds = Int64(0)
_getTime(
seconds: &seconds,
nanoseconds: &nanoseconds,
clock: _ClockID.continuous.rawValue)
return ContinuousClock.Instant(_value:
.seconds(seconds) + .nanoseconds(nanoseconds))
}
#if !SWIFT_STDLIB_TASK_TO_THREAD_MODEL_CONCURRENCY
/// Suspend task execution until a given deadline within a tolerance.
/// If no tolerance is specified then the system may adjust the deadline
/// to coalesce CPU wake-ups to more efficiently process the wake-ups in
/// a more power efficient manner.
///
/// If the task is canceled before the time ends, this function throws
/// `CancellationError`.
///
/// This function doesn't block the underlying thread.
public func sleep(
until deadline: Instant, tolerance: Swift.Duration? = nil
) async throws {
let (seconds, attoseconds) = deadline._value.components
let nanoseconds = attoseconds / 1_000_000_000
try await Task._sleep(until:seconds, nanoseconds,
tolerance: tolerance,
clock: .continuous)
}
#else
@available(SwiftStdlib 5.7, *)
@available(*, unavailable, message: "Unavailable in task-to-thread concurrency model")
public func sleep(
until deadline: Instant, tolerance: Swift.Duration? = nil
) async throws {
fatalError("Unavailable in task-to-thread concurrency model")
}
#endif
}
@available(SwiftStdlib 5.7, *)
extension ContinuousClock.Instant: InstantProtocol {
public static var now: ContinuousClock.Instant { ContinuousClock.now }
public func advanced(by duration: Swift.Duration) -> ContinuousClock.Instant {
return ContinuousClock.Instant(_value: _value + duration)
}
public func duration(to other: ContinuousClock.Instant) -> Swift.Duration {
other._value - _value
}
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
public static func == (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Bool {
return lhs._value == rhs._value
}
public static func < (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Bool {
return lhs._value < rhs._value
}
@_alwaysEmitIntoClient
@inlinable
public static func + (
_ lhs: ContinuousClock.Instant, _ rhs: Swift.Duration
) -> ContinuousClock.Instant {
lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func += (
_ lhs: inout ContinuousClock.Instant, _ rhs: Swift.Duration
) {
lhs = lhs.advanced(by: rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (
_ lhs: ContinuousClock.Instant, _ rhs: Swift.Duration
) -> ContinuousClock.Instant {
lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func -= (
_ lhs: inout ContinuousClock.Instant, _ rhs: Swift.Duration
) {
lhs = lhs.advanced(by: .zero - rhs)
}
@_alwaysEmitIntoClient
@inlinable
public static func - (
_ lhs: ContinuousClock.Instant, _ rhs: ContinuousClock.Instant
) -> Swift.Duration {
rhs.duration(to: lhs)
}
}
|
apache-2.0
|
41c1512eb64ef264ddbfb7dabbd874cb
| 30.291429 | 88 | 0.676954 | 4.254856 | false | false | false | false |
brentsimmons/Frontier
|
BeforeTheRename/UserTalk/UserTalk/Node/ParamHeaderNode.swift
|
1
|
744
|
//
// ParamHeaderNode.swift
// UserTalk
//
// Created by Brent Simmons on 5/5/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import FrontierData
final class ParamHeaderNode: CodeTreeNode {
// on (foo, bar, baz=3*9, nerf="well", dill=pick.le())
let operation: CodeTreeOperation = .paramHeaderOp
let textPosition: TextPosition
let name: String?
let defaultValueExpression: CodeTreeNode?
init(_ textPosition: TextPosition, name: String, defaultValueExpression: CodeTreeNode?) {
self.textPosition = textPosition
self.name = name
self.defaultValueExpression = defaultValueExpression
}
func evaluate(_ stack: Stack, _ breakOperation: inout CodeTreeOperation) throws -> Value {
}
}
|
gpl-2.0
|
1a4e74a752df83ebd967b3badfdc3429
| 22.967742 | 91 | 0.741588 | 3.733668 | false | false | false | false |
Harry-L/5-3-1
|
ios-charts-master/Charts/Classes/Components/ChartLegend.swift
|
4
|
17128
|
//
// ChartLegend.swift
// Charts
//
// Created by Daniel Cohen Gindi on 24/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
public class ChartLegend: ChartComponentBase
{
@objc
public enum ChartLegendPosition: Int
{
case RightOfChart
case RightOfChartCenter
case RightOfChartInside
case LeftOfChart
case LeftOfChartCenter
case LeftOfChartInside
case BelowChartLeft
case BelowChartRight
case BelowChartCenter
case AboveChartLeft
case AboveChartRight
case AboveChartCenter
case PiechartCenter
}
@objc
public enum ChartLegendForm: Int
{
case Square
case Circle
case Line
}
@objc
public enum ChartLegendDirection: Int
{
case LeftToRight
case RightToLeft
}
/// the legend colors array, each color is for the form drawn at the same index
public var colors = [UIColor?]()
// the legend text array. a nil label will start a group.
public var labels = [String?]()
internal var _extraColors = [UIColor?]()
internal var _extraLabels = [String?]()
/// colors that will be appended to the end of the colors array after calculating the legend.
public var extraColors: [UIColor?] { return _extraColors; }
/// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group.
public var extraLabels: [String?] { return _extraLabels; }
/// Are the legend labels/colors a custom value or auto calculated? If false, then it's auto, if true, then custom.
///
/// **default**: false (automatic legend)
private var _isLegendCustom = false
public var position = ChartLegendPosition.BelowChartLeft
public var direction = ChartLegendDirection.LeftToRight
public var font: UIFont = UIFont.systemFontOfSize(10.0)
public var textColor = UIColor.blackColor()
public var form = ChartLegendForm.Square
public var formSize = CGFloat(8.0)
public var formLineWidth = CGFloat(1.5)
public var xEntrySpace = CGFloat(6.0)
public var yEntrySpace = CGFloat(0.0)
public var formToTextSpace = CGFloat(5.0)
public var stackSpace = CGFloat(3.0)
public var calculatedLabelSizes = [CGSize]()
public var calculatedLabelBreakPoints = [Bool]()
public var calculatedLineSizes = [CGSize]()
public override init()
{
super.init()
self.xOffset = 5.0
self.yOffset = 4.0
}
public init(colors: [UIColor?], labels: [String?])
{
super.init()
self.colors = colors
self.labels = labels
}
public init(colors: [NSObject], labels: [NSObject])
{
super.init()
self.colorsObjc = colors
self.labelsObjc = labels
}
public func getMaximumEntrySize(font: UIFont) -> CGSize
{
var maxW = CGFloat(0.0)
var maxH = CGFloat(0.0)
var labels = self.labels
for (var i = 0; i < labels.count; i++)
{
if (labels[i] == nil)
{
continue
}
let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: font])
if (size.width > maxW)
{
maxW = size.width
}
if (size.height > maxH)
{
maxH = size.height
}
}
return CGSize(
width: maxW + formSize + formToTextSpace,
height: maxH
)
}
public func getLabel(index: Int) -> String?
{
return labels[index]
}
public func getFullSize(labelFont: UIFont) -> CGSize
{
var width = CGFloat(0.0)
var height = CGFloat(0.0)
var labels = self.labels
for (var i = 0, count = labels.count; i < count; i++)
{
if (labels[i] != nil)
{
// make a step to the left
if (colors[i] != nil)
{
width += formSize + formToTextSpace
}
let size = (labels[i] as NSString!).sizeWithAttributes([NSFontAttributeName: labelFont])
width += size.width
height += size.height
if (i < count - 1)
{
width += xEntrySpace
height += yEntrySpace
}
}
else
{
width += formSize + stackSpace
if (i < count - 1)
{
width += stackSpace
}
}
}
return CGSize(width: width, height: height)
}
public var neededWidth = CGFloat(0.0)
public var neededHeight = CGFloat(0.0)
public var textWidthMax = CGFloat(0.0)
public var textHeightMax = CGFloat(0.0)
/// flag that indicates if word wrapping is enabled
/// this is currently supported only for: `BelowChartLeft`, `BelowChartRight`, `BelowChartCenter`.
/// note that word wrapping a legend takes a toll on performance.
/// you may want to set maxSizePercent when word wrapping, to set the point where the text wraps.
///
/// **default**: false
public var wordWrapEnabled = false
/// if this is set, then word wrapping the legend is enabled.
public var isWordWrapEnabled: Bool { return wordWrapEnabled }
/// The maximum relative size out of the whole chart view in percent.
/// If the legend is to the right/left of the chart, then this affects the width of the legend.
/// If the legend is to the top/bottom of the chart, then this affects the height of the legend.
/// If the legend is the center of the piechart, then this defines the size of the rectangular bounds out of the size of the "hole".
///
/// **default**: 0.95 (95%)
public var maxSizePercent: CGFloat = 0.95
public func calculateDimensions(labelFont labelFont: UIFont, viewPortHandler: ChartViewPortHandler)
{
if (position == .RightOfChart
|| position == .RightOfChartCenter
|| position == .LeftOfChart
|| position == .LeftOfChartCenter
|| position == .PiechartCenter)
{
let maxEntrySize = getMaximumEntrySize(labelFont)
let fullSize = getFullSize(labelFont)
neededWidth = maxEntrySize.width
neededHeight = fullSize.height
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
}
else if (position == .BelowChartLeft
|| position == .BelowChartRight
|| position == .BelowChartCenter
|| position == .AboveChartLeft
|| position == .AboveChartRight
|| position == .AboveChartCenter)
{
var labels = self.labels
var colors = self.colors
let labelCount = labels.count
let labelLineHeight = labelFont.lineHeight
let formSize = self.formSize
let formToTextSpace = self.formToTextSpace
let xEntrySpace = self.xEntrySpace
let stackSpace = self.stackSpace
let wordWrapEnabled = self.wordWrapEnabled
let contentWidth: CGFloat = viewPortHandler.contentWidth
// Prepare arrays for calculated layout
if (calculatedLabelSizes.count != labelCount)
{
calculatedLabelSizes = [CGSize](count: labelCount, repeatedValue: CGSize())
}
if (calculatedLabelBreakPoints.count != labelCount)
{
calculatedLabelBreakPoints = [Bool](count: labelCount, repeatedValue: false)
}
calculatedLineSizes.removeAll(keepCapacity: true)
// Start calculating layout
let labelAttrs = [NSFontAttributeName: labelFont]
var maxLineWidth: CGFloat = 0.0
var currentLineWidth: CGFloat = 0.0
var requiredWidth: CGFloat = 0.0
var stackedStartIndex: Int = -1
for (var i = 0; i < labelCount; i++)
{
let drawingForm = colors[i] != nil
calculatedLabelBreakPoints[i] = false
if (stackedStartIndex == -1)
{
// we are not stacking, so required width is for this label only
requiredWidth = 0.0
}
else
{
// add the spacing appropriate for stacked labels/forms
requiredWidth += stackSpace
}
// grouped forms have null labels
if (labels[i] != nil)
{
calculatedLabelSizes[i] = (labels[i] as NSString!).sizeWithAttributes(labelAttrs)
requiredWidth += drawingForm ? formToTextSpace + formSize : 0.0
requiredWidth += calculatedLabelSizes[i].width
}
else
{
calculatedLabelSizes[i] = CGSize()
requiredWidth += drawingForm ? formSize : 0.0
if (stackedStartIndex == -1)
{
// mark this index as we might want to break here later
stackedStartIndex = i
}
}
if (labels[i] != nil || i == labelCount - 1)
{
let requiredSpacing = currentLineWidth == 0.0 ? 0.0 : xEntrySpace
if (!wordWrapEnabled || // No word wrapping, it must fit.
currentLineWidth == 0.0 || // The line is empty, it must fit.
(contentWidth - currentLineWidth >= requiredSpacing + requiredWidth)) // It simply fits
{
// Expand current line
currentLineWidth += requiredSpacing + requiredWidth
}
else
{ // It doesn't fit, we need to wrap a line
// Add current line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
// Start a new line
calculatedLabelBreakPoints[stackedStartIndex > -1 ? stackedStartIndex : i] = true
currentLineWidth = requiredWidth
}
if (i == labelCount - 1)
{ // Add last line size to array
calculatedLineSizes.append(CGSize(width: currentLineWidth, height: labelLineHeight))
maxLineWidth = max(maxLineWidth, currentLineWidth)
}
}
stackedStartIndex = labels[i] != nil ? -1 : stackedStartIndex
}
let maxEntrySize = getMaximumEntrySize(labelFont)
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
neededWidth = maxLineWidth
neededHeight = labelLineHeight * CGFloat(calculatedLineSizes.count) +
yEntrySpace * CGFloat(calculatedLineSizes.count == 0 ? 0 : (calculatedLineSizes.count - 1))
}
else
{
let maxEntrySize = getMaximumEntrySize(labelFont)
let fullSize = getFullSize(labelFont)
/* RightOfChartInside, LeftOfChartInside */
neededWidth = fullSize.width
neededHeight = maxEntrySize.height
textWidthMax = maxEntrySize.width
textHeightMax = maxEntrySize.height
}
}
/// MARK: - Custom legend
/// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend.
/// (if the legend has already been calculated, you will need to call notifyDataSetChanged() to let the changes take effect)
public func setExtra(colors colors: [UIColor?], labels: [String?])
{
self._extraLabels = labels
self._extraColors = colors
}
/// Sets a custom legend's labels and colors arrays.
/// The colors count should match the labels count.
/// * Each color is for the form drawn at the same index.
/// * A nil label will start a group.
/// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form.
/// This will disable the feature that automatically calculates the legend labels and colors from the datasets.
/// Call `resetCustom(...)` to re-enable automatic calculation (and then `notifyDataSetChanged()` is needed).
public func setCustom(colors colors: [UIColor?], labels: [String?])
{
self.labels = labels
self.colors = colors
_isLegendCustom = true
}
/// Calling this will disable the custom legend labels (set by `setLegend(...)`). Instead, the labels will again be calculated automatically (after `notifyDataSetChanged()` is called).
public func resetCustom()
{
_isLegendCustom = false
}
/// **default**: false (automatic legend)
/// - returns: true if a custom legend labels and colors has been set
public var isLegendCustom: Bool
{
return _isLegendCustom
}
/// MARK: - ObjC compatibility
/// colors that will be appended to the end of the colors array after calculating the legend.
public var extraColorsObjc: [NSObject] { return ChartUtils.bridgedObjCGetUIColorArray(swift: _extraColors); }
/// labels that will be appended to the end of the labels array after calculating the legend. a nil label will start a group.
public var extraLabelsObjc: [NSObject] { return ChartUtils.bridgedObjCGetStringArray(swift: _extraLabels); }
/// the legend colors array, each color is for the form drawn at the same index
/// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s)
public var colorsObjc: [NSObject]
{
get { return ChartUtils.bridgedObjCGetUIColorArray(swift: colors); }
set { self.colors = ChartUtils.bridgedObjCGetUIColorArray(objc: newValue); }
}
// the legend text array. a nil label will start a group.
/// (ObjC bridging functions, as Swift 1.2 does not bridge optionals in array to `NSNull`s)
public var labelsObjc: [NSObject]
{
get { return ChartUtils.bridgedObjCGetStringArray(swift: labels); }
set { self.labels = ChartUtils.bridgedObjCGetStringArray(objc: newValue); }
}
/// colors and labels that will be appended to the end of the auto calculated colors and labels after calculating the legend.
/// (if the legend has already been calculated, you will need to call `notifyDataSetChanged()` to let the changes take effect)
public func setExtra(colors colors: [NSObject], labels: [NSObject])
{
if (colors.count != labels.count)
{
fatalError("ChartLegend:setExtra() - colors array and labels array need to be of same size")
}
self._extraLabels = ChartUtils.bridgedObjCGetStringArray(objc: labels)
self._extraColors = ChartUtils.bridgedObjCGetUIColorArray(objc: colors)
}
/// Sets a custom legend's labels and colors arrays.
/// The colors count should match the labels count.
/// * Each color is for the form drawn at the same index.
/// * A nil label will start a group.
/// * A nil color will avoid drawing a form, and a clearColor will leave a space for the form.
/// This will disable the feature that automatically calculates the legend labels and colors from the datasets.
/// Call `resetLegendToAuto(...)` to re-enable automatic calculation, and then if needed - call `notifyDataSetChanged()` on the chart to make it refresh the data.
public func setCustom(colors colors: [NSObject], labels: [NSObject])
{
if (colors.count != labels.count)
{
fatalError("ChartLegend:setCustom() - colors array and labels array need to be of same size")
}
self.labelsObjc = labels
self.colorsObjc = colors
_isLegendCustom = true
}
}
|
mit
|
e8fce8881d33798b7d3c9a9fb7f64968
| 36.561404 | 188 | 0.570645 | 5.425404 | false | false | false | false |
austinzmchen/guildOfWarWorldBosses
|
GoWWorldBosses/ViewControllers/WBSettingsViewController.swift
|
1
|
4202
|
//
// WBSettingsViewController.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2016-09-13.
// Copyright © 2016 Austin Chen. All rights reserved.
//
import UIKit
private struct WBSettingsItem {
var title: String
var subtitle: String
var segueId: String
}
class WBSettingsViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBAction func doneButtonTapped(_ sender: AnyObject) {
self.navigationController?.dismiss(animated: true, completion: nil)
}
var isNotificationTurnedOnInSettings = true
fileprivate var settingItems: [WBSettingsItem] = []
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
tableView.delegate = self
tableView.dataSource = self
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settingItems = [WBSettingsItem(title: "Notifications", subtitle: "", segueId: ""),
WBSettingsItem(title: "About", subtitle: AppConfiguration.appVersion(), segueId: "pushToAboutVC"),
WBSettingsItem(title: "Help", subtitle: "", segueId: "")]
if WBKeyStore.isAccountAvailable {
settingItems.insert(WBSettingsItem(title: "API Key", subtitle: "", segueId: "pushToAPIKeyVC"), at: 1)
}
tableView.reloadData()
}
func appDidBecomeActive() {
guard let settings = UIApplication.shared.currentUserNotificationSettings, settings.types != UIUserNotificationType() else
{
isNotificationTurnedOnInSettings = false
self.tableView.reloadData()
return
}
isNotificationTurnedOnInSettings = true
self.tableView.reloadData()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "pushToAPIKeyVC" {
let vc = segue.destination
vc.title = "API Key"
}
}
}
extension WBSettingsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return settingItems.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if settingItems[indexPath.row].title == "Notifications" {
return 71.5
} else {
return 50.0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if indexPath.row == 0 {
let noteCell = tableView.dequeueReusableCell(withIdentifier: "noteCell") as! WBSettingsNotificationTableViewCell
noteCell.toggleSwitch.isOn = isNotificationTurnedOnInSettings
cell = noteCell
} else {
let settingsCell = tableView.dequeueReusableCell(withIdentifier: "settingsCell") as! WBSettingsTableViewCell
let settingsitem = settingItems[indexPath.row]
settingsCell.mainLabel.text = settingsitem.title
settingsCell.subLabel.text = settingsitem.subtitle
settingsCell.separaterView.isHidden = (indexPath.row + 1 == settingItems.count)
cell = settingsCell
}
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == 0 {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
} else if indexPath.row + 1 == settingItems.count {
UIApplication.shared.openURL(URL(string: "mailto:[email protected]")!)
} else {
let settingsitem = settingItems[indexPath.row]
self.performSegue(withIdentifier: settingsitem.segueId, sender: nil)
}
tableView.deselectRow(at: indexPath, animated: true)
}
}
|
mit
|
69087ca545a293d29876e6ccf564b573
| 36.176991 | 166 | 0.649607 | 5.180025 | false | false | false | false |
aipeople/PokeIV
|
PokeIV/TouchSensingView.swift
|
1
|
3423
|
//
// TouchSensingView.swift
// PokeIV
//
// Created by aipeople on 8/15/16.
// Github: https://github.com/aipeople/PokeIV
// Copyright © 2016 su. All rights reserved.
//
import UIKit
class TouchSensingView : UIView {
// MARK : - Properties
var touchOutSideCallBack: ((sensingView: TouchSensingView) -> ())?
var touchEndedCallBack: ((sensingView: TouchSensingView) -> ())?
var ignoredViews = [UIView]()
var sensingBeforeTouchEvent = true
private var isPassingTouch = false
// MARK: - Life Cycle
init() {
super.init(frame: CGRectZero)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Methods
func isTouchsNeedToBePassedThrough(touches: Set<UITouch>) -> Bool {
if self.ignoredViews.count <= 0 {
return false
}
for touch in touches {
for ignoredView in self.ignoredViews {
let point = touch.locationInView(ignoredView)
if !CGRectContainsPoint(ignoredView.bounds, point) {
return false
}
}
}
return true
}
// MARK: - Evnets
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let hitView = super.hitTest(point, withEvent: event)
if hitView == self {
for ignoredView in self.ignoredViews {
let rect = self.convertRect(ignoredView.bounds, fromView: ignoredView)
if CGRectContainsPoint(rect, point) {
return nil
}
}
if self.sensingBeforeTouchEvent {
self.touchOutSideCallBack?(sensingView: self)
return nil
} else {
return self
}
}
return hitView;
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if self.isTouchsNeedToBePassedThrough(touches) {
self.nextResponder()?.touchesBegan(touches, withEvent: event)
self.isPassingTouch = true
} else {
self.isPassingTouch = false
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if self.isPassingTouch {
self.nextResponder()?.touchesMoved(touches, withEvent: event)
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if self.isPassingTouch {
self.nextResponder()?.touchesEnded(touches, withEvent: event)
} else {
self.touchEndedCallBack?(sensingView: self)
}
self.isPassingTouch = false
}
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if self.isPassingTouch {
self.nextResponder()?.touchesCancelled(touches, withEvent: event)
} else {
self.touchEndedCallBack?(sensingView: self)
}
self.isPassingTouch = false
}
}
|
gpl-3.0
|
b31fbd30648483b677aa1b8ad5a6706b
| 23.978102 | 87 | 0.5263 | 5.169184 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/GroupVideoView.swift
|
1
|
5225
|
//
// GroupVideoView.swift
// Telegram
//
// Created by Mikhail Filimonov on 11.01.2021.
// Copyright © 2021 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import SwiftSignalKit
final class GroupVideoView: View {
private let videoViewContainer: View
let videoView: PresentationCallVideoView
var gravity: CALayerContentsGravity = .resizeAspect
var initialGravity: CALayerContentsGravity? = nil
private var validLayout: CGSize?
private var videoAnimator: DisplayLinkAnimator?
private var isMirrored: Bool = false {
didSet {
CATransaction.begin()
if isMirrored {
let rect = self.videoViewContainer.bounds
var fr = CATransform3DIdentity
fr = CATransform3DTranslate(fr, rect.width / 2, 0, 0)
fr = CATransform3DScale(fr, -1, 1, 1)
fr = CATransform3DTranslate(fr, -(rect.width / 2), 0, 0)
self.videoViewContainer.layer?.sublayerTransform = fr
} else {
self.videoViewContainer.layer?.sublayerTransform = CATransform3DIdentity
}
CATransaction.commit()
}
}
var tapped: (() -> Void)?
init(videoView: PresentationCallVideoView) {
self.videoViewContainer = View()
self.videoView = videoView
super.init()
self.videoViewContainer.addSubview(self.videoView.view)
self.addSubview(self.videoViewContainer)
videoView.setOnOrientationUpdated({ [weak self] _, _ in
guard let strongSelf = self else {
return
}
if let size = strongSelf.validLayout {
strongSelf.updateLayout(size: size, transition: .immediate)
}
})
videoView.setOnIsMirroredUpdated({ [weak self] isMirrored in
self?.isMirrored = isMirrored
})
// videoView.setIsPaused(true);
}
override func mouseDown(with event: NSEvent) {
super.mouseDown(with: event)
}
override var mouseDownCanMoveWindow: Bool {
return true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(frame frameRect: NSRect) {
fatalError("init(frame:) has not been implemented")
}
func setVideoContentMode(_ contentMode: CALayerContentsGravity, animated: Bool) {
self.gravity = contentMode
self.validLayout = nil
let transition: ContainedViewLayoutTransition = animated ? .animated(duration: 0.3, curve: .easeOut) : .immediate
self.updateLayout(size: frame.size, transition: transition)
}
override func layout() {
super.layout()
updateLayout(size: frame.size, transition: .immediate)
}
func updateLayout(size: CGSize, transition: ContainedViewLayoutTransition) {
guard self.validLayout != size else {
return
}
self.validLayout = size
var videoRect: CGRect = .zero
videoRect = focus(size)
transition.updateFrame(view: self.videoViewContainer, frame: videoRect)
if transition.isAnimated {
let videoView = self.videoView
videoView.renderToSize(self.videoView.view.frame.size, true)
videoView.setIsPaused(true)
transition.updateFrame(view: videoView.view, frame: videoRect, completion: { [weak videoView] _ in
videoView?.renderToSize(videoRect.size, false)
videoView?.setIsPaused(false)
})
} else {
transition.updateFrame(view: videoView.view, frame: videoRect)
}
for subview in self.videoView.view.subviews {
transition.updateFrame(view: subview, frame: videoRect.size.bounds)
}
var fr = CATransform3DIdentity
if isMirrored {
let rect = videoRect
fr = CATransform3DTranslate(fr, rect.width / 2, 0, 0)
fr = CATransform3DScale(fr, -1, 1, 1)
fr = CATransform3DTranslate(fr, -(rect.width / 2), 0, 0)
}
switch transition {
case .immediate:
self.videoViewContainer.layer?.sublayerTransform = fr
case let .animated(duration, curve):
let animation = CABasicAnimation(keyPath: "sublayerTransform")
animation.fromValue = self.videoViewContainer.layer?.presentation()?.sublayerTransform ?? self.videoViewContainer.layer?.sublayerTransform ?? CATransform3DIdentity
animation.toValue = fr
animation.timingFunction = .init(name: curve.timingFunction)
animation.duration = duration
self.videoViewContainer.layer?.add(animation, forKey: "sublayerTransform")
self.videoViewContainer.layer?.sublayerTransform = fr
}
}
override func viewDidMoveToSuperview() {
if superview == nil {
didRemoveFromSuperview?()
}
}
var didRemoveFromSuperview: (()->Void)? = nil
}
|
gpl-2.0
|
345bd9df949d111870fb513e9c82a92d
| 32.273885 | 175 | 0.603369 | 5.131631 | false | false | false | false |
NitWitStudios/NWSExtensions
|
NWSExtensions/Classes/Array+Extensions.swift
|
1
|
587
|
//
// Array+Extensions.swift
// Bobblehead-TV
//
// Created by James Hickman on 7/28/16.
// Copyright © 2016 NitWit Studios. All rights reserved.
//
import Foundation
public extension Array
{
mutating func removeObject<U: Equatable>(_ object: U) {
var index: Int?
for (idx, objectToCompare) in self.enumerated() {
if let to = objectToCompare as? U {
if object == to {
index = idx
}
}
}
if(index != nil) {
self.remove(at: index!)
}
}
}
|
mit
|
5e476ef2ca1fed958db479be262d0593
| 20.703704 | 59 | 0.508532 | 3.986395 | false | false | false | false |
andypiper/TweetJSON
|
TweetJSON/AppDelegate.swift
|
1
|
3021
|
//
// AppDelegate.swift
// TweetJSON
//
// Created by Andy Piper on 13/06/2017.
// Copyright © 2017 Andy Piper. All rights reserved.
//
import UIKit
import TwitterKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var consumer_key: String = ""
var consumer_secret: String = ""
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Fabric.with([Crashlytics.self])
// grab app keys from Twitter.plist in app bundle
// avoids having to have that file in source control...
if let url = Bundle.main.url(forResource:"Twitter", withExtension: "plist") {
do {
let data = try Data(contentsOf:url)
let swiftDictionary = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as! [String:Any]
consumer_key = swiftDictionary["consumer_key"] as! String
consumer_secret = swiftDictionary["consumer_secret"] as! String
} catch {
print(error)
}
}
Twitter.sharedInstance().start(withConsumerKey:consumer_key, consumerSecret:consumer_secret)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
apache-2.0
|
5e6c7a60a67e1522297b1dc9c61cd5a2
| 43.411765 | 285 | 0.710596 | 5.364121 | false | false | false | false |
asaday/EzHTTP
|
Sources/EzHTTP/ObjectDecoder.swift
|
1
|
12768
|
//
// ObjDecoder.swift
// EzHTTP
//
import Foundation
public typealias ObjectDecoderConverter = ((_ path: [CodingKey], _ container: [String: Any]) -> Any?)
public class ObjectDecoder: Decoder {
var converter: ObjectDecoderConverter?
var useThrow = false
public var codingPath: [CodingKey] = []
public var userInfo: [CodingUserInfoKey: Any] = [:]
var container: Any = NSNull()
public init(converter: ObjectDecoderConverter? = nil) {
self.converter = converter
}
func throwDecodingError(_ e: DecodingError) throws {
if useThrow { throw e }
}
public func decode<T: Decodable>(_ type: T.Type, from value: Any) throws -> T {
var src = value
if let s = src as? String { src = s.data(using: .utf8) ?? Data() }
if let d = src as? Data { src = try JSONSerialization.jsonObject(with: d, options: []) }
if let a = src as? AnyCodable { src = a.value }
container = src
return try decodeValue(container, type: type)
}
public func optionalDecode<T: Decodable>(_ type: T.Type, from value: Any?) -> T? {
guard let v = value else { return nil }
do { return try decode(type, from: v) }
catch { return nil }
}
public func forceDecode<T: Decodable>(_ type: T.Type, from value: Any?) -> T {
if let v = optionalDecode(type, from: value) { return v }
return try! decodeValue(NSNull(), type: type)
}
public func forceInitialize<T: Decodable>(_ type: T.Type) -> T {
return try! decodeValue(NSNull(), type: type)
}
public func singleValueContainer() throws -> SingleValueDecodingContainer {
return self
}
public func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard let v = container as? [Any] else {
try throwDecodingError(DecodingError.valueNotFound([Any].self, DecodingError.Context(codingPath: codingPath, debugDescription: "not array")))
return UnkeyDC(decoder: self, container: [])
}
return UnkeyDC(decoder: self, container: v)
}
public func container<Key>(keyedBy _: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard let v = container as? [String: Any] else {
try throwDecodingError(DecodingError.typeMismatch([String: Any].self, DecodingError.Context(codingPath: codingPath, debugDescription: "no key")))
return KeyedDecodingContainer(KeyDCP<Key>(decoder: self, container: [:]))
}
return KeyedDecodingContainer(KeyDCP<Key>(decoder: self, container: v))
}
func copy(with value: Any) -> ObjectDecoder {
let d = ObjectDecoder()
d.container = value
d.codingPath = codingPath
d.userInfo = userInfo
d.useThrow = useThrow
d.converter = converter
return d
}
func decodeValue<T>(_ value: Any, type: T.Type) throws -> T where T: Decodable {
return try (unbox(value: value, type: type) as? T) ?? type.init(from: copy(with: value))
}
// for array
struct UnkeyDC: UnkeyedDecodingContainer {
let decoder: ObjectDecoder
var codingPath: [CodingKey] { return decoder.codingPath }
var count: Int? { return container.count }
var isAtEnd: Bool { return currentIndex >= container.count }
var currentIndex: Int = 0
let container: [Any]
init(decoder: ObjectDecoder, container: [Any]) {
self.decoder = decoder
self.container = container
}
mutating func popValue() throws -> Any {
if isAtEnd {
try decoder.throwDecodingError(DecodingError.valueNotFound(Any.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Unkeyed at end")))
}
let value = container[currentIndex]
currentIndex += 1
return value
}
mutating func decodeNil() throws -> Bool {
decoder.codingPath.append(CodingKeys(intValue: currentIndex)!)
defer { decoder.codingPath.removeLast() }
if try popValue() is NSNull { return true }
currentIndex -= 1
return false
}
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
decoder.codingPath.append(CodingKeys(intValue: currentIndex)!)
defer { decoder.codingPath.removeLast() }
return try decoder.decodeValue(popValue(), type: type)
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
return try superDecoder().container(keyedBy: type)
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
return try superDecoder().unkeyedContainer()
}
mutating func superDecoder() throws -> Decoder {
return try decoder.copy(with: popValue())
}
}
// for dictionary
struct KeyDCP<Key: CodingKey>: KeyedDecodingContainerProtocol {
let decoder: ObjectDecoder
var codingPath: [CodingKey] { return decoder.codingPath }
var allKeys: [Key] { return container.keys.compactMap { Key(stringValue: $0) } }
let container: [String: Any]
init(decoder: ObjectDecoder, container: [String: Any]) {
self.decoder = decoder
self.container = container
}
func getValue(key: Key) throws -> Any {
var ov: Any?
if let c = decoder.converter?(codingPath, container) { ov = c }
else { ov = container[key.stringValue] }
guard let v = ov else {
try decoder.throwDecodingError(DecodingError.keyNotFound(key, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "No value associated with key")))
return NSNull() // dont throw no key
}
return v
}
func contains(_ key: Key) -> Bool {
return container.keys.contains(key.stringValue)
}
func decodeNil(forKey key: Key) throws -> Bool {
decoder.codingPath.append(key)
defer { decoder.codingPath.removeLast() }
return try getValue(key: key) is NSNull
}
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
decoder.codingPath.append(key)
defer { decoder.codingPath.removeLast() }
return try decoder.decodeValue(getValue(key: key), type: type)
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> where NestedKey: CodingKey {
return try superDecoder(forKey: key).container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try superDecoder(forKey: key).unkeyedContainer()
}
func superDecoder() throws -> Decoder {
return try superDecoder(forKey: Key(stringValue: "super")!)
}
func superDecoder(forKey key: Key) throws -> Decoder {
return try decoder.copy(with: getValue(key: key))
}
}
}
// for single value
extension ObjectDecoder: SingleValueDecodingContainer {
public func decodeNil() -> Bool { return container is NSNull }
public func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
return try decodeValue(container, type: type)
}
}
extension ObjectDecoder {
func decodeNumber(_ value: Any) throws -> NSNumber {
if let v = value as? NSNumber { return v }
if let v = value as? Int { return NSNumber(value: v) }
if let s = value as? String {
if s.lowercased() == "true" { return NSNumber(value: true) }
if s.lowercased() == "false" { return NSNumber(value: false) }
if let v = Int(s) { return NSNumber(value: v) }
}
try throwDecodingError(DecodingError.typeMismatch(Int.self, DecodingError.Context(codingPath: codingPath, debugDescription: "decode number")))
return 0 // default
}
func decodeString(_ value: Any) throws -> String {
if let v = value as? String { return v }
if let v = value as? NSNumber { return v.stringValue }
try throwDecodingError(DecodingError.typeMismatch(String.self, DecodingError.Context(codingPath: codingPath, debugDescription: "decode number")))
return "" // default
}
func dateFormat(_ s: String) -> Date? {
if #available(iOS 10.0, tvOS 10.0, macOS 10.12, *) {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter.date(from: s)
} else {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.timeZone = TimeZone(secondsFromGMT: 0)
return formatter.date(from: s)
}
}
func unbox<T>(value: Any, type: T.Type) throws -> Any? {
switch type {
case is Int.Type: return try decodeNumber(value).intValue
case is Float.Type: return try decodeNumber(value).floatValue
case is Double.Type: return try decodeNumber(value).doubleValue
case is Bool.Type: return try decodeNumber(value).boolValue
case is Int8.Type: return try decodeNumber(value).int8Value
case is Int16.Type: return try decodeNumber(value).int16Value
case is Int32.Type: return try decodeNumber(value).int32Value
case is Int64.Type: return try decodeNumber(value).int64Value
case is UInt.Type: return try decodeNumber(value).uintValue
case is UInt8.Type: return try decodeNumber(value).uint8Value
case is UInt16.Type: return try decodeNumber(value).uint16Value
case is UInt32.Type: return try decodeNumber(value).uint32Value
case is UInt64.Type: return try decodeNumber(value).uint64Value
case is String.Type: return try decodeString(value)
case is URL.Type:
return try (URL(string: decodeString(value)) ?? URL(fileURLWithPath: "none"))
case is Data.Type:
if let d = value as? Data { return d }
if let s = value as? String { return Data(base64Encoded: s) }
case is Date.Type:
if let d = value as? Date { return d }
if let s = value as? String, let d = dateFormat(s) { return d }
if let n = value as? Int { return Date(timeIntervalSince1970: TimeInterval(n)) }
default: break
}
if !useThrow {
if type is AnyCodable.Type { return AnyCodable(value) }
}
if let v = value as? T { return v }
return nil
}
}
extension Decoder {
public func tes<T: RawRepresentable>(_ def: T) throws -> T where T.RawValue == String {
return try T(rawValue: singleValueContainer().decode(String.self)) ?? def
}
public func es<T: RawRepresentable>(_ def: T) -> T where T.RawValue == String {
return (try? tes(def)) ?? def
}
}
struct CodingKeys: CodingKey {
var stringValue: String
var intValue: Int?
init?(intValue: Int) { stringValue = "\(intValue)"; self.intValue = intValue }
init?(stringValue: String) { self.stringValue = stringValue }
}
public struct AnyCodable: Codable {
var value: Any
public init(_ value: Any) { self.value = value }
public init(from decoder: Decoder) throws {
if let container = try? decoder.container(keyedBy: CodingKeys.self) {
var result: [String: Any] = [:]
try container.allKeys.forEach { (key) throws in
result[key.stringValue] = try container.decode(AnyCodable.self, forKey: key).value
}
value = result
return
}
if var container = try? decoder.unkeyedContainer() {
var result: [Any] = []
while !container.isAtEnd { result.append(try container.decode(AnyCodable.self).value) }
value = result
return
}
if let container = try? decoder.singleValueContainer() {
if let v = try? container.decode(Int.self) { value = v; return }
if let v = try? container.decode(Double.self) { value = v; return }
if let v = try? container.decode(Bool.self) { value = v; return }
if let v = try? container.decode(String.self) { value = v; return }
if let v = try? container.decode([AnyCodable].self) { value = v; return }
if let v = try? container.decode([String: AnyCodable].self) { value = v; return }
}
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "can not decode"))
}
public func encode(to encoder: Encoder) throws {
if let array = value as? [Any] {
var container = encoder.unkeyedContainer()
for value in array {
let decodable = AnyCodable(value)
try container.encode(decodable)
}
return
}
if let dictionary = value as? [String: Any] {
var container = encoder.container(keyedBy: CodingKeys.self)
for (key, value) in dictionary {
let codingKey = CodingKeys(stringValue: key)!
let decodable = AnyCodable(value)
try container.encode(decodable, forKey: codingKey)
}
return
}
var container = encoder.singleValueContainer()
if let intVal = value as? Int { try container.encode(intVal); return }
if let doubleVal = value as? Double { try container.encode(doubleVal); return }
if let boolVal = value as? Bool { try container.encode(boolVal); return }
if let stringVal = value as? String { try container.encode(stringVal); return }
throw EncodingError.invalidValue(value, EncodingError.Context(codingPath: encoder.codingPath, debugDescription: "can not encode"))
}
}
extension Decoder {
func sv() throws -> String {
return try singleValueContainer().decode(String.self)
}
}
public class ObjectEncoder: JSONEncoder {
public override init() {
super.init()
dateEncodingStrategy = .custom { d, encoder in
var container = encoder.singleValueContainer()
try container.encode(Int(d.timeIntervalSince1970))
}
}
}
|
mit
|
d8c48e8a91ade994a48523d9b07154e8
| 34.270718 | 171 | 0.707707 | 3.662651 | false | false | false | false |
clwm01/RTKitDemo
|
RCToolsDemo/UIVerticalLabel.swift
|
2
|
2423
|
//
// VerticalLUILabel.swift
// RCToolsDemo
// Inspired by: 夕阳沉幕 http://blog.sina.com.cn/s/blog_87533a0801016tmj.html
// Created by Apple on 10/16/15.
// Copyright (c) 2015 rexcao. All rights reserved.
//
import UIKit
// From top to bottom, then from right to left to write text.
class UIVerticalLabel: UILabel {
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let viewHeight = self.frame.size.height
let viewWidth = self.frame.size.width
var x: CGFloat, y: CGFloat
let width = self.font.pointSize + 1
let height = self.font.pointSize + 1
// let width = self.attributedText.size().width
// let height = self.attributedText.size().height
let startX: CGFloat = viewWidth - width
let startY: CGFloat = 0
var drawStr = self.text!
// Number of charachters in every vertical line.
let charNumber = Int(floor(Float(viewHeight / height)))
// Number of lines.(this line is vertical direction)
let actualLineNumber = Int(floor(Float(viewWidth / width)))
// Number of lines expected.
let expectedLineNumber = Int(ceil(Float(drawStr.characters.count / charNumber)))
if expectedLineNumber >= actualLineNumber {
let startIndex = drawStr.startIndex.advancedBy(0)
let endIndex = drawStr.startIndex.advancedBy(actualLineNumber * charNumber)
let range = startIndex..<endIndex
// drawStr = drawStr.substringToIndex(endIndex)
drawStr = drawStr.substringWithRange(range)
}
for i in 0 ..< drawStr.characters.count {
x = startX - floor(CGFloat(i/charNumber))*width
y = startY + CGFloat(i%charNumber)*height
let charFrame = CGRectMake(x, y, width, height)
let range = drawStr.startIndex.advancedBy(i)..<drawStr.startIndex.advancedBy(i+1)
let str = NSString(string: drawStr.substringWithRange(range))
var attribs: [String: AnyObject] = NSDictionary() as! [String : AnyObject]
attribs[NSFontAttributeName] = self.font
str.drawInRect(charFrame, withAttributes: attribs)
}
}
}
|
mit
|
f17cddf5781c0467155a835b27ce254f
| 38.590164 | 93 | 0.6294 | 4.406934 | false | false | false | false |
sarvex/SwiftRecepies
|
Extensions/Adding New Photo Editing Capabilities to the Photos App/PosterizeExtension/PhotoEditingViewController.swift
|
1
|
5386
|
//
// PhotoEditingViewController.swift
// PosterizeExtension
//
// Created by vandad on 217//14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import Photos
import PhotosUI
import OpenGLES
class PhotoEditingViewController: UIViewController,
PHContentEditingController {
/* An image view on the screen that first shows the original
image to the user and after we are done applying our edits to the image,
it will show the edited image */
@IBOutlet weak var imageView: UIImageView!
/* The input that we will be given by the system */
var input: PHContentEditingInput!
/* We give our edits to the user in this way */
var output: PHContentEditingOutput!
/* The name of the image filter that we will apply to the input image */
let filterName = "CIColorPosterize"
/* These two values are our way of telling the Photos framework about
the identifier of the changes that we are going to make to the photo */
let editFormatIdentifier = NSBundle.mainBundle().bundleIdentifier!
/* Just an application specific editing version */
let editFormatVersion = "0.1"
/* A queue that will execute our edits in the background */
let operationQueue = NSOperationQueue()
let shouldShowCancelConfirmation: Bool = true
/* This turns an image into its NSData representation */
func dataFromCiImage(image: CIImage) -> NSData{
let glContext = EAGLContext(API: .OpenGLES2)
let context = CIContext(EAGLContext: glContext)
let imageRef = context.createCGImage(image, fromRect: image.extent())
let image = UIImage(CGImage: imageRef, scale: 1.0, orientation: .Up)
return UIImageJPEGRepresentation(image, 1.0)
}
/* This takes the input and converts it to the output. The output
has our posterized content saved inside it */
func posterizedImageForInput(input: PHContentEditingInput) ->
PHContentEditingOutput{
/* Get the required information from the asset */
let url = input.fullSizeImageURL
let orientation = input.fullSizeImageOrientation
/* Retrieve an instance of CIImage to apply our filter to */
let inputImage =
CIImage(contentsOfURL: url,
options: nil).imageByApplyingOrientation(orientation)
/* Apply the filter to our image */
let filter = CIFilter(name: filterName)
filter.setDefaults()
filter.setValue(inputImage, forKey: kCIInputImageKey)
let outputImage = filter.outputImage
/* Get the data of our edited image */
let editedImageData = dataFromCiImage(outputImage)
/* The results of editing our image are encapsulated here */
let output = PHContentEditingOutput(contentEditingInput: input)
/* Here we are saving our edited image to the URL that is dictated
by the content editing output class */
editedImageData.writeToURL(output.renderedContentURL,
atomically: true)
output.adjustmentData =
PHAdjustmentData(formatIdentifier: editFormatIdentifier,
formatVersion: editFormatVersion,
data: filterName.dataUsingEncoding(NSUTF8StringEncoding,
allowLossyConversion: false))
return output
}
/* We just want to work with the original image */
func canHandleAdjustmentData(adjustmentData: PHAdjustmentData?) -> Bool {
return false
}
/* This is a closure that we will submit to our operation queue */
func editingOperation(){
output = posterizedImageForInput(input)
dispatch_async(dispatch_get_main_queue(), {[weak self] in
let strongSelf = self!
let data = NSData(contentsOfURL: strongSelf.output.renderedContentURL,
options: .DataReadingMappedIfSafe,
error: nil)
let image = UIImage(data: data!)
strongSelf.imageView.image = image
})
}
func startContentEditingWithInput(
contentEditingInput: PHContentEditingInput?,
placeholderImage: UIImage) {
imageView.image = placeholderImage
input = contentEditingInput
/* Start the editing in the background */
let block = NSBlockOperation(block: editingOperation)
operationQueue.addOperation(block)
}
func finishContentEditingWithCompletionHandler(
completionHandler: ((PHContentEditingOutput!) -> Void)!) {
/* Report our output */
completionHandler(output)
}
/* The user cancelled the editing process */
func cancelContentEditing() {
/* Make sure we stop our operation here */
operationQueue.cancelAllOperations()
}
}
|
isc
|
aaa7a0a61a5f53498ee881452af8b055
| 33.748387 | 83 | 0.704419 | 4.909754 | false | false | false | false |
kwonye/calcupad
|
Calcupad/Calculator.swift
|
2
|
1196
|
//
// Calculator.swift
// Calcupad
//
// Created by Will Kwon on 9/1/16.
// Copyright © 2016 Will Kwon. All rights reserved.
//
import UIKit
class Calculator: NSObject {
let plus = "+"
let minus = "-"
let multiply = "×"
let divide = "÷"
var previousValue: Double?
var currentValue: Double?
var currentOperator: String?
var solution: Double?
func solveEquation() -> Double? {
solution = solveEquation(previousValue, secondValue: currentValue, currentOperator: currentOperator)
return solution
}
func solveEquation(_ firstValue: Double?, secondValue: Double?, currentOperator: String?) -> Double? {
guard let firstValue = firstValue, let secondValue = secondValue, let currentOperator = currentOperator else {
return nil
}
switch currentOperator {
case plus:
return firstValue + secondValue
case minus:
return firstValue - secondValue
case multiply:
return firstValue * secondValue
case divide:
return firstValue / secondValue
default:
return nil
}
}
}
|
mit
|
6e857a8ffc45a6f22b6e6ce08e54131c
| 25.511111 | 118 | 0.604359 | 5.186957 | false | false | false | false |
gregomni/swift
|
test/SILOptimizer/sroa_unreferenced_members.swift
|
9
|
389
|
// RUN: %target-swift-frontend -enable-copy-propagation=requested-passes-only -enable-lexical-lifetimes=false -sdk %S/Inputs -O -emit-sil -I %S/Inputs -enable-source-import -primary-file %s | %FileCheck %s
import gizmo
// CHECK: ModifyStruct
// CHECK: = alloc_stack $Drill
// CHECK: ret
func ModifyStruct(inDrill : Drill) -> Int32 {
var D : Drill = inDrill
D.x += 3
return D.x
}
|
apache-2.0
|
752b748bdded4c9661598baf19e4964b
| 31.416667 | 205 | 0.696658 | 2.924812 | false | false | false | false |
MrAlek/Swiftalytics
|
Example/ScreenTracking.swift
|
1
|
3614
|
//
// ScreenTracking.swift
//
// Created by Alek Åström on 2015-02-14.
// Copyright (c) 2015 Alek Åström. (https://github.com/MrAlek)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Swiftalytics
struct ScreenTracking {
static func setup() {
AuthorsViewController.self >> "Authors (start)"
QuoteViewController.self >> { "Quote: "+$0.author.name }
NewQuoteViewController.self >> .navigationTitle
RandomQuoteViewController.computedPageName<<
}
}
extension UIViewController {
class func initializeClass() {
struct Static {
static var token: Int = 0
}
// make sure this isn't a subclass
if self !== UIViewController.self {
return
}
swizzling(self)
}
@objc func swiftalytics_viewDidAppear(_ animated: Bool) {
self.swiftalytics_viewDidAppear(animated)
if let name = Swiftalytics.trackingName(for: self) {
// Report to your analytics service
print("Tracked view controller: "+name)
}
}
}
fileprivate let swizzling: (UIViewController.Type) -> () = { viewController in
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
let swizzledSelector = #selector(UIViewController.swiftalytics_viewDidAppear(_:))
let originalMethod = class_getInstanceMethod(viewController, originalSelector)
let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)
let didAddMethod = class_addMethod(viewController, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!))
if didAddMethod {
class_replaceMethod(viewController, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
} else {
method_exchangeImplementations(originalMethod!, swizzledMethod!);
}
}
postfix operator <<
private postfix func <<<T: UIViewController>(trackClassFunction: @escaping ((T) -> () -> String)) {
Swiftalytics.setTrackingName(for: trackClassFunction)
}
private func >> <T: UIViewController>(left: T.Type, right: @autoclosure () -> String) {
Swiftalytics.setTrackingName(for: left, name: right)
}
private func >> <T: UIViewController>(left: T.Type, right: TrackingNameType) {
Swiftalytics.setTrackingName(for: left, trackingType: right)
}
private func >> <T: UIViewController>(left: T.Type, right: @escaping ((T) -> String)) {
Swiftalytics.setTrackingName(for: left, nameFunction: right)
}
|
mit
|
f8bcc0109ca34209ad6e45c31392357d
| 38.23913 | 156 | 0.710803 | 4.658065 | false | false | false | false |
johnno1962c/swift-corelibs-foundation
|
Foundation/String.swift
|
6
|
3075
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
extension String : _ObjectTypeBridgeable {
public typealias _ObjectType = NSString
public func _bridgeToObjectiveC() -> _ObjectType {
return NSString(self)
}
static public func _forceBridgeFromObjectiveC(_ source: _ObjectType, result: inout String?) {
result = _unconditionallyBridgeFromObjectiveC(source)
}
@discardableResult
static public func _conditionallyBridgeFromObjectiveC(_ source: _ObjectType, result: inout String?) -> Bool {
if type(of: source) == NSString.self || type(of: source) == NSMutableString.self {
result = source._storage
} else if type(of: source) == _NSCFString.self {
let cf = unsafeBitCast(source, to: CFString.self)
let str = CFStringGetCStringPtr(cf, CFStringEncoding(kCFStringEncodingUTF8))
if str != nil {
result = String(cString: str!)
} else {
let length = CFStringGetLength(cf)
let buffer = UnsafeMutablePointer<UniChar>.allocate(capacity: length)
CFStringGetCharacters(cf, CFRangeMake(0, length), buffer)
let str = String._fromCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: buffer, count: length))
buffer.deinitialize(count: length)
buffer.deallocate(capacity: length)
result = str
}
} else if type(of: source) == _NSCFConstantString.self {
let conststr = unsafeDowncast(source, to: _NSCFConstantString.self)
let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: conststr._ptr, count: Int(conststr._length)))
result = str
} else {
let len = source.length
var characters = [unichar](repeating: 0, count: len)
result = characters.withUnsafeMutableBufferPointer() { (buffer: inout UnsafeMutableBufferPointer<unichar>) -> String? in
source.getCharacters(buffer.baseAddress!, range: NSMakeRange(0, len))
return String._fromCodeUnitSequence(UTF16.self, input: buffer)
}
}
return result != nil
}
static public func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectType?) -> String {
if let object = source {
var value: String?
_conditionallyBridgeFromObjectiveC(object, result: &value)
return value!
} else {
return ""
}
}
}
|
apache-2.0
|
7ac7e9b751ab1b44fc27a18f925895c2
| 42.928571 | 141 | 0.594472 | 5.329289 | false | false | false | false |
apple/swift-nio-ssl
|
Tests/NIOSSLTests/NIOSSLALPNTest.swift
|
1
|
5621
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import XCTest
@_implementationOnly import CNIOBoringSSL
import NIOCore
import NIOPosix
import NIOTLS
import NIOSSL
class NIOSSLALPNTest: XCTestCase {
static var cert: NIOSSLCertificate!
static var key: NIOSSLPrivateKey!
override class func setUp() {
super.setUp()
let (cert, key) = generateSelfSignedCert()
NIOSSLIntegrationTest.cert = cert
NIOSSLIntegrationTest.key = key
}
private func configuredSSLContextWithAlpnProtocols(protocols: [String]) throws -> NIOSSLContext {
var config = TLSConfiguration.makeServerConfiguration(
certificateChain: [.certificate(NIOSSLIntegrationTest.cert)],
privateKey: .privateKey(NIOSSLIntegrationTest.key)
)
config.trustRoots = .certificates([NIOSSLIntegrationTest.cert])
config.applicationProtocols = protocols
return try NIOSSLContext(configuration: config)
}
private func assertNegotiatedProtocol(protocol: String?,
serverContext: NIOSSLContext,
clientContext: NIOSSLContext) throws {
let group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
defer {
XCTAssertNoThrow(try group.syncShutdownGracefully())
}
let completionPromise: EventLoopPromise<ByteBuffer> = group.next().makePromise()
let serverHandler = EventRecorderHandler<TLSUserEvent>()
let serverChannel = try serverTLSChannel(context: serverContext,
handlers: [serverHandler, PromiseOnReadHandler(promise: completionPromise)],
group: group)
defer {
XCTAssertNoThrow(try serverChannel.close().wait())
}
let clientChannel = try clientTLSChannel(context: clientContext,
preHandlers: [],
postHandlers: [],
group: group,
connectingTo: serverChannel.localAddress!)
defer {
XCTAssertNoThrow(try clientChannel.close().wait())
}
var originalBuffer = clientChannel.allocator.buffer(capacity: 5)
originalBuffer.writeString("Hello")
try clientChannel.writeAndFlush(originalBuffer).wait()
_ = try completionPromise.futureResult.wait()
let expectedEvents: [EventRecorderHandler<TLSUserEvent>.RecordedEvents] = [
.Registered,
.Active,
.UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: `protocol`)),
.Read,
.ReadComplete
]
XCTAssertEqual(expectedEvents, serverHandler.events)
}
func testBasicALPNNegotiation() throws {
let context: NIOSSLContext
context = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]))
XCTAssertNoThrow(try assertNegotiatedProtocol(protocol: "h2", serverContext: context, clientContext: context))
}
func testBasicALPNNegotiationPrefersServerPriority() throws {
let serverCtx: NIOSSLContext
let clientCtx: NIOSSLContext
serverCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]))
clientCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["http/1.1", "h2"]))
XCTAssertNoThrow(try assertNegotiatedProtocol(protocol: "h2", serverContext: serverCtx, clientContext: clientCtx))
}
func testBasicALPNNegotiationNoOverlap() throws {
let serverCtx: NIOSSLContext
let clientCtx: NIOSSLContext
serverCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]))
clientCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["spdy/3", "webrtc"]))
XCTAssertNoThrow(try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx))
}
func testBasicALPNNegotiationNotOfferedByClient() throws {
let serverCtx: NIOSSLContext
let clientCtx: NIOSSLContext
serverCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]))
clientCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: []))
XCTAssertNoThrow(try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx))
}
func testBasicALPNNegotiationNotSupportedByServer() throws {
let serverCtx: NIOSSLContext
let clientCtx: NIOSSLContext
serverCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: []))
clientCtx = try assertNoThrowWithValue(configuredSSLContextWithAlpnProtocols(protocols: ["h2", "http/1.1"]))
XCTAssertNoThrow(try assertNegotiatedProtocol(protocol: nil, serverContext: serverCtx, clientContext: clientCtx))
}
}
|
apache-2.0
|
e6f624de94d7988e77a51d9eb3589228
| 43.611111 | 125 | 0.653976 | 5.338082 | false | true | false | false |
fedepo/phoneid_iOS
|
Example/phoneid_iOS/swift/CustomExampleViewController.swift
|
2
|
2119
|
//
// CustomExampleViewController.swift
// phoneid_iOS
//
// Created by Alyona on 4/6/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import phoneid_iOS
class CustomExampleViewController: UIViewController {
// Use PhoneIdLoginWorkflowManager as alternative way to start login flow from your code
let flowManager = PhoneIdLoginWorkflowManager()
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var customLoginButton: UIButton!
var details:DetailsViewController!
var phoneNumberE164:String?
@IBAction func presentFromCustomButton(_ sender: AnyObject) {
flowManager.startLoginFlow(initialPhoneNumerE164:phoneNumberE164,
startAnimatingProgress: {self.activityIndicator.startAnimating()},
stopAnimationProgress: {self.activityIndicator.stopAnimating()})
}
@IBAction func dismiss(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
details.presetNumber.addTarget(self,
action: #selector(CustomExampleViewController.presetNumberChanged(_:)),
for:.editingChanged)
details.switchUserPresetNumber.addTarget(self,
action: #selector(CustomExampleViewController.presetNumberSwitchChanged(_:)),
for:.valueChanged)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "details" {
details = segue.destination as? DetailsViewController
}
}
@objc func presetNumberChanged(_ sender:UITextField){
phoneNumberE164 = details.switchUserPresetNumber.isOn ? sender.text : ""
}
@objc func presetNumberSwitchChanged(_ sender:UISwitch){
phoneNumberE164 = sender.isOn ? details.presetNumber.text : ""
}
}
|
apache-2.0
|
18b08f42e6f336fc6d235cea2613e2d2
| 31.584615 | 126 | 0.626062 | 5.472868 | false | false | false | false |
swift-tweets/tweetup-kit
|
Tests/TweetupKitTests/TweetTests.swift
|
1
|
8380
|
import XCTest
@testable import TweetupKit
class TweetTests: XCTestCase {
func testInit() {
do {
let result = try! Tweet(body: "Twinkle, twinkle, little star,\nHow I wonder what you are!")
XCTAssertEqual(result.body, "Twinkle, twinkle, little star,\nHow I wonder what you are!")
}
do { // empty (0)
_ = try Tweet(body: "")
XCTFail()
} catch TweetInitializationError.empty {
} catch {
XCTFail()
}
do { // 1
let result = try! Tweet(body: "A")
XCTAssertEqual(result.body, "A")
}
do { // 140
let result = try! Tweet(body: "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789")
XCTAssertEqual(result.body, "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789")
}
do { // too long (141)
_ = try Tweet(body: "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789X")
XCTFail()
} catch let TweetInitializationError.tooLong(body, attachment, length) {
XCTAssertEqual(body, "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B123456789C123456789D123456789X")
XCTAssertNil(attachment)
XCTAssertEqual(length, 141)
} catch {
XCTFail()
}
do { // too long with a `.code`
_ = try Tweet(body: "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B1234X", attachment: .code(Code(language: .swift, fileName: "hello.swift", body: "let name = \"Swift\"\nprint(\"Hello \\(name)!\")")))
XCTFail()
} catch let TweetInitializationError.tooLong(body, attachment, length) {
XCTAssertEqual(body, "0123456789112345678921234567893123456789412345678951234567896123456789712345678981234567899123456789A123456789B1234X")
guard let attachment = attachment else { XCTFail(); return }
switch attachment {
case let .code(code):
XCTAssertEqual(code.language, .swift)
XCTAssertEqual(code.fileName, "hello.swift")
XCTAssertEqual(code.body, "let name = \"Swift\"\nprint(\"Hello \\(name)!\")")
case .image(_):
XCTFail()
}
XCTAssertEqual(length, 141)
} catch {
XCTFail()
}
do { // Swift.org as a URL
_ = try Tweet(body: "まず Swift.org の Compiler and Standard Library を見てみました。\n> Semantic analysis includes type inference ...\nhttps://swift.org/compiler-stdlib/#compiler-architecture (6/10) #swtws")
XCTFail()
} catch let TweetInitializationError.tooLong(body, attachment, length) {
XCTAssertEqual(body, "まず Swift.org の Compiler and Standard Library を見てみました。\n> Semantic analysis includes type inference ...\nhttps://swift.org/compiler-stdlib/#compiler-architecture (6/10) #swtws")
XCTAssertNil(attachment)
XCTAssertEqual(length, 153)
} catch {
XCTFail()
}
}
func testDescription() {
do {
let tweet = try! Tweet(body: "Twinkle, twinkle, little star,\nHow I wonder what you are!")
let result = tweet.description
XCTAssertEqual(result, "Twinkle, twinkle, little star,\nHow I wonder what you are!")
}
do {
let tweet = try! Tweet(body: "Up above the world so high,\nLike a diamond in the sky.", attachment: .code(Code(language: .swift, fileName: "hello.swift", body: "let name = \"Swift\"\nprint(\"Hello \\(name)!\")")))
let result = tweet.description
XCTAssertEqual(result, "Up above the world so high,\nLike a diamond in the sky.\n\n```swift:hello.swift\nlet name = \"Swift\"\nprint(\"Hello \\(name)!\")\n```")
}
do {
let tweet = try! Tweet(body: "Twinkle, twinkle, little star,\nHow I wonder what you are!", attachment: .image(Image(alternativeText: "", source: .local("path/to/image.png"))))
let result = tweet.description
XCTAssertEqual(result, "Twinkle, twinkle, little star,\nHow I wonder what you are!\n\n")
}
}
func testLength() {
do {
let tweet = try! Tweet(body: "A")
let result = tweet.length
XCTAssertEqual(result, 1)
}
do { // new lines
let tweet = try! Tweet(body: "A\nB\nC")
let result = tweet.length
XCTAssertEqual(result, 5)
}
do { // Japanese
let tweet = try! Tweet(body: "あいうえお山川空")
let result = tweet.length
XCTAssertEqual(result, 8)
}
do { // 16 for Twitter, 1 for Swift
let tweet = try! Tweet(body: "🇬🇧🇨🇦🇫🇷🇩🇪🇮🇹🇯🇵🇷🇺🇺🇸")
let result = tweet.length
XCTAssertEqual(result, 16)
}
do { // http
let tweet = try! Tweet(body: "http://qaleido.space")
let result = tweet.length
XCTAssertEqual(result, 23)
}
do { // https
let tweet = try! Tweet(body: "https://swift-tweets.github.io")
let result = tweet.length
XCTAssertEqual(result, 23)
}
do { // mixed
let tweet = try! Tweet(body: "Twinkle, twinkle, little star, http://qaleido.space How I wonder what you are! https://swift-tweets.github.io/?foo=bar&baz=qux#tweeters")
let result = tweet.length
XCTAssertEqual(result, 105)
}
do { // with a `.code`
let tweet = try! Tweet(body: "Up above the world so high,\nLike a diamond in the sky.", attachment: .code(Code(language: .swift, fileName: "hello.swift", body: "let name = \"Swift\"\nprint(\"Hello \\(name)!\")")))
let result = tweet.length
XCTAssertEqual(result, 79)
}
do { // with a `.image`
let tweet = try! Tweet(body: "Twinkle, twinkle, little star,\nHow I wonder what you are!", attachment: .image(Image(alternativeText: "", source: .local("path/to/image.png"))))
let result = tweet.length
XCTAssertEqual(result, 57)
}
}
func testUrlPattern() {
do {
let string = "Twinkle, twinkle, little star, http://qaleido.space How I wonder what you are! https://swift-tweets.github.io/?foo=bar&baz=qux#tweeters"
let results = Tweet.urlPattern.matches(in: string)
XCTAssertEqual(results.count, 2)
do {
let result = results[0]
XCTAssertEqual((string as NSString).substring(with: result.range(at: 2)), "http://qaleido.space")
}
do {
let result = results[1]
XCTAssertEqual((string as NSString).substring(with: result.range(at: 2)), "https://swift-tweets.github.io/?foo=bar&baz=qux#tweeters")
}
}
do {
let string = "まず Swift.org の Compiler and Standard Library を見てみました。\n> Semantic analysis includes type inference ...\nhttps://swift.org/compiler-stdlib/#compiler-architecture (6/10) #swtws"
let results = Tweet.urlPattern.matches(in: string)
XCTAssertEqual(results.count, 2)
do {
let result = results[0]
XCTAssertEqual((string as NSString).substring(with: result.range(at: 2)), "Swift.org")
}
do {
let result = results[1]
XCTAssertEqual((string as NSString).substring(with: result.range(at: 2)), "https://swift.org/compiler-stdlib/#compiler-architecture")
}
}
}
}
|
mit
|
0deb16acfd9e0e0278b15c30da83b4a0
| 44.32967 | 277 | 0.580364 | 4.308094 | false | false | false | false |
sora0077/LayoutKit
|
LayoutKitDemo/MenuViewController.swift
|
1
|
4109
|
//
// MenuViewController.swift
// LayoutKit
//
// Created by 林 達也 on 2015/01/21.
// Copyright (c) 2015年 林 達也. All rights reserved.
//
import UIKit
import LayoutKit
class MenuViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// TableRowProtocol
// Do any additional setup after loading the view.
self.nextResponder()
self.tableView.controller = TableController(responder: self)
if let c = self.tableView.controller {
c.sections[0].footer = NormalSection<UITableViewHeaderFooterView>(title: "footer", height: 10)
c.sections[0].append(
MenuRow<UITableViewCell.StyleDefault>(title: "セルの大量追加・削除・置換") { [unowned self] in
self.segueAction("ViewController")
}
)
c.sections[0].append(
MenuRow<UITableViewCell.StyleDefault>(title: "セルの追加読み込み"){ [unowned self] in
self.segueAction("TimelineViewController") {
if let vc = $0 as? TimelineViewController {
vc.uiType = .Invisible
}
}
}
)
c.sections[0].append(
MenuRow<UITableViewCell.StyleDefault>(title: "セルの追加読み込み UI付き"){ [unowned self] in
self.segueAction("TimelineViewController") {
if let vc = $0 as? TimelineViewController {
vc.uiType = .UI
}
}
}
)
c.sections[0].append(
UITableView.StyleDefaultRow(text: "test")
)
c.sections[0].append(
UITableView.StyleValue1Row(text: "test", detailText: "aa")
)
c.sections[0].append(
UITableView.StyleValue2Row(text: "test", detailText: "aa")
)
c.sections[0].append(
UITableView.StyleSubtitleRow(text: "test", detailText: "aa")
)
let s = TableSection()
c.append(s)
s.append(
MenuRow<UITableViewCell.StyleDefault>(title: "セルの追加読み込み UI付き"){ [unowned self] in
self.segueAction("TimelineViewController") {
if let vc = $0 as? TimelineViewController {
vc.uiType = .UI
}
}
}
)
let delay = 3.0 * Double(NSEC_PER_SEC)
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(when, dispatch_get_main_queue()) {
println("aaaaaaa")
s.footer = NormalSection<UITableViewHeaderFooterView>(title: "footer", height: 40)
}
}
self.tableView.controller.invalidate()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func segueAction(identifier: String, _ block: ((UIViewController) -> Void)? = nil) {
let next = self.storyboard?.instantiateViewControllerWithIdentifier(identifier) as! UIViewController
self.navigationController?.pushViewController(next, animated: true)
block?(next)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension MenuViewController: UIScrollViewDelegate {
func scrollViewDidScroll(scrollView: UIScrollView) {
println(scrollView.contentOffset)
}
}
|
mit
|
177a5883fe935c1e044533981ee58226
| 32.680672 | 108 | 0.553032 | 4.97764 | false | false | false | false |
e78l/swift-corelibs-foundation
|
TestFoundation/FixtureValues.swift
|
1
|
15839
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// Please keep this import statement as-is; this file is also used by the GenerateTestFixtures project, which doesn't have TestImports.swift.
#if DEPLOYMENT_RUNTIME_SWIFT && (os(macOS) || os(iOS) || os(watchOS) || os(tvOS))
import SwiftFoundation
#else
import Foundation
#endif
// -----
extension Calendar {
static var neutral: Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
calendar.locale = NSLocale.system
return calendar
}
}
enum Fixtures {
static let mutableAttributedString = TypedFixture<NSMutableAttributedString>("NSMutableAttributedString") {
let string = NSMutableAttributedString(string: "0123456789")
// Should have: .xyyzzxyx.
let attrs1: [NSAttributedString.Key: Any] = [.init("Font"): "Helvetica", .init("Size"): 123]
let attrs2: [NSAttributedString.Key: Any] = [.init("Font"): "Times", .init("Size"): 456]
let attrs3NS = attrs2 as NSDictionary
let attrs3Maybe: [NSAttributedString.Key: Any]?
if let attrs3Swift = attrs3NS as? [String: Any] {
attrs3Maybe = Dictionary(attrs3Swift.map { (NSAttributedString.Key($0.key), $0.value) }, uniquingKeysWith: { $1 })
} else {
attrs3Maybe = nil
}
let attrs3 = try attrs3Maybe.unwrapped()
string.setAttributes(attrs1, range: NSMakeRange(1, string.length - 2))
string.setAttributes(attrs2, range: NSMakeRange(2, 2))
string.setAttributes(attrs3, range: NSMakeRange(4, 2))
string.setAttributes(attrs2, range: NSMakeRange(8, 1))
return string
}
static let attributedString = TypedFixture<NSAttributedString>("NSAttributedString") {
return NSAttributedString(attributedString: try Fixtures.mutableAttributedString.make())
}
// ===== ByteCountFormatter =====
static let byteCountFormatterDefault = TypedFixture<ByteCountFormatter>("ByteCountFormatter-Default") {
return ByteCountFormatter()
}
static let byteCountFormatterAllFieldsSet = TypedFixture<ByteCountFormatter>("ByteCountFormatter-AllFieldsSet") {
let f = ByteCountFormatter()
f.allowedUnits = [.useBytes, .useKB]
f.countStyle = .decimal
f.formattingContext = .beginningOfSentence
f.zeroPadsFractionDigits = true
f.includesCount = true
f.allowsNonnumericFormatting = false
f.includesUnit = false
f.includesCount = false
f.isAdaptive = false
return f
}
// ===== DateIntervalFormatter =====
static let dateIntervalFormatterDefault = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-Default") {
let dif = DateIntervalFormatter()
let calendar = Calendar.neutral
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
return dif
}
static let dateIntervalFormatterValuesSetWithoutTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithoutTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateStyle = .long
dif.timeStyle = .none
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
static let dateIntervalFormatterValuesSetWithTemplate = TypedFixture<DateIntervalFormatter>("DateIntervalFormatter-ValuesSetWithTemplate") {
let dif = DateIntervalFormatter()
var calendar = Calendar.neutral
calendar.locale = Locale(identifier: "ja-JP")
dif.calendar = calendar
dif.timeZone = calendar.timeZone
dif.locale = calendar.locale
dif.dateTemplate = "dd mm yyyy HH:MM"
dif.timeZone = TimeZone(secondsFromGMT: 60 * 60)
return dif
}
// ===== ISO8601DateFormatter =====
static let iso8601FormatterDefault = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-Default") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
return idf
}
static let iso8601FormatterOptionsSet = TypedFixture<ISO8601DateFormatter>("ISO8601DateFormatter-OptionsSet") {
let idf = ISO8601DateFormatter()
idf.timeZone = Calendar.neutral.timeZone
idf.formatOptions = [ .withDay, .withWeekOfYear, .withMonth, .withTimeZone, .withColonSeparatorInTimeZone, .withDashSeparatorInDate ]
return idf
}
// ===== NSTextCheckingResult =====
static let textCheckingResultSimpleRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-SimpleRegex") {
let string = "aaa"
let regexp = try NSRegularExpression(pattern: "aaa", options: [])
let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped()
return result
}
static let textCheckingResultExtendedRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ExtendedRegex") {
let string = "aaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a)))))", options: [])
let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped()
return result
}
static let textCheckingResultComplexRegex = TypedFixture<NSTextCheckingResult>("NSTextCheckingResult-ComplexRegex") {
let string = "aaaaaaaaa"
let regexp = try NSRegularExpression(pattern: "a(a(a(a(a(a(a(a(a))))))))", options: [])
let result = try regexp.matches(in: string, range: NSRange(string.startIndex ..< string.endIndex, in: string)).first.unwrapped()
return result
}
// ===== NSIndexSet =====
static let indexSetEmpty = TypedFixture<NSIndexSet>("NSIndexSet-Empty") {
return NSIndexSet(indexesIn: NSMakeRange(0, 0))
}
static let indexSetOneRange = TypedFixture<NSIndexSet>("NSIndexSet-OneRange") {
return NSIndexSet(indexesIn: NSMakeRange(0, 50))
}
static let indexSetManyRanges = TypedFixture<NSIndexSet>("NSIndexSet-ManyRanges") {
let indexSet = NSMutableIndexSet()
indexSet.add(in: NSMakeRange(0, 50))
indexSet.add(in: NSMakeRange(100, 50))
indexSet.add(in: NSMakeRange(1000, 50))
indexSet.add(in: NSMakeRange(Int.max - 50, 50))
return indexSet.copy() as! NSIndexSet
}
static let mutableIndexSetEmpty = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-Empty") {
return (try Fixtures.indexSetEmpty.make()).mutableCopy() as! NSMutableIndexSet
}
static let mutableIndexSetOneRange = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-OneRange") {
return (try Fixtures.indexSetOneRange.make()).mutableCopy() as! NSMutableIndexSet
}
static let mutableIndexSetManyRanges = TypedFixture<NSMutableIndexSet>("NSMutableIndexSet-ManyRanges") {
return (try Fixtures.indexSetManyRanges.make()).mutableCopy() as! NSMutableIndexSet
}
// ===== NSSet, NSMutableSet =====
static let setOfNumbers = TypedFixture<NSSet>("NSSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSSet(array: numbers)
}
static let setEmpty = TypedFixture<NSSet>("NSSet-Empty") {
return NSSet()
}
static let mutableSetOfNumbers = TypedFixture<NSMutableSet>("NSMutableSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableSet(array: numbers)
}
static let mutableSetEmpty = TypedFixture<NSMutableSet>("NSMutableSet-Empty") {
return NSMutableSet()
}
// ===== NSCharacterSet, NSMutableCharacterSet =====
static let characterSetEmpty = TypedFixture<NSCharacterSet>("NSCharacterSet-Empty") {
return NSCharacterSet()
}
static let characterSetRange = TypedFixture<NSCharacterSet>("NSCharacterSet-Range") {
return NSCharacterSet(range: NSMakeRange(0, 255))
}
static let characterSetString = TypedFixture<NSCharacterSet>("NSCharacterSet-String") {
return NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
}
static let characterSetBitmap = TypedFixture<NSCharacterSet>("NSCharacterSet-Bitmap") {
let someSet = NSCharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz")
return NSCharacterSet(bitmapRepresentation: someSet.bitmapRepresentation)
}
static let characterSetBuiltin = TypedFixture<NSCharacterSet>("NSCharacterSet-Builtin") {
return NSCharacterSet.alphanumerics as NSCharacterSet
}
// ===== NSOrderedSet, NSMutableOrderedSet =====
static let orderedSetOfNumbers = TypedFixture<NSOrderedSet>("NSOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSOrderedSet(array: numbers)
}
static let orderedSetEmpty = TypedFixture<NSOrderedSet>("NSOrderedSet-Empty") {
return NSOrderedSet()
}
static let mutableOrderedSetOfNumbers = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Numbers") {
let numbers = [1, 2, 3, 4, 5].map { NSNumber(value: $0) }
return NSMutableOrderedSet(array: numbers)
}
static let mutableOrderedSetEmpty = TypedFixture<NSMutableOrderedSet>("NSMutableOrderedSet-Empty") {
return NSMutableOrderedSet()
}
// ===== Fixture list =====
static let _listOfAllFixtures: [AnyFixture] = [
AnyFixture(Fixtures.mutableAttributedString),
AnyFixture(Fixtures.attributedString),
AnyFixture(Fixtures.byteCountFormatterDefault),
AnyFixture(Fixtures.byteCountFormatterAllFieldsSet),
AnyFixture(Fixtures.dateIntervalFormatterDefault),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithTemplate),
AnyFixture(Fixtures.dateIntervalFormatterValuesSetWithoutTemplate),
AnyFixture(Fixtures.iso8601FormatterDefault),
AnyFixture(Fixtures.iso8601FormatterOptionsSet),
AnyFixture(Fixtures.textCheckingResultSimpleRegex),
AnyFixture(Fixtures.textCheckingResultExtendedRegex),
AnyFixture(Fixtures.textCheckingResultComplexRegex),
AnyFixture(Fixtures.indexSetEmpty),
AnyFixture(Fixtures.indexSetOneRange),
AnyFixture(Fixtures.indexSetManyRanges),
AnyFixture(Fixtures.mutableIndexSetEmpty),
AnyFixture(Fixtures.mutableIndexSetOneRange),
AnyFixture(Fixtures.mutableIndexSetManyRanges),
AnyFixture(Fixtures.setOfNumbers),
AnyFixture(Fixtures.setEmpty),
AnyFixture(Fixtures.mutableSetOfNumbers),
AnyFixture(Fixtures.mutableSetEmpty),
AnyFixture(Fixtures.characterSetEmpty),
AnyFixture(Fixtures.characterSetRange),
AnyFixture(Fixtures.characterSetString),
AnyFixture(Fixtures.characterSetBitmap),
AnyFixture(Fixtures.characterSetBuiltin),
AnyFixture(Fixtures.orderedSetOfNumbers),
AnyFixture(Fixtures.orderedSetEmpty),
AnyFixture(Fixtures.mutableOrderedSetOfNumbers),
AnyFixture(Fixtures.mutableOrderedSetEmpty),
]
// This ensures that we do not have fixtures with duplicate identifiers:
static var all: [AnyFixture] {
return Array(Fixtures.allFixturesByIdentifier.values)
}
static var allFixturesByIdentifier: [String: AnyFixture] = {
let keysAndValues = Fixtures._listOfAllFixtures.map { ($0.identifier, $0) }
return Dictionary(keysAndValues, uniquingKeysWith: { _, _ in fatalError("No two keys should be the same in fixtures. Double-check keys in FixtureValues.swift to make sure they're all unique.") })
}()
}
// -----
// Support for the above:
enum FixtureVariant: String, CaseIterable {
case macOS10_14 = "macOS-10.14"
func url(fixtureRepository: URL) -> URL {
return URL(fileURLWithPath: self.rawValue, relativeTo: fixtureRepository)
}
}
protocol Fixture {
associatedtype ValueType
var identifier: String { get }
func make() throws -> ValueType
var supportsSecureCoding: Bool { get }
}
struct TypedFixture<ValueType: NSObject & NSCoding>: Fixture {
var identifier: String
private var creationHandler: () throws -> ValueType
init(_ identifier: String, creationHandler: @escaping () throws -> ValueType) {
self.identifier = identifier
self.creationHandler = creationHandler
}
func make() throws -> ValueType {
return try creationHandler()
}
var supportsSecureCoding: Bool {
let kind: Any.Type
if let made = try? make() {
kind = type(of: made)
} else {
kind = ValueType.self
}
return (kind as? NSSecureCoding.Type)?.supportsSecureCoding == true
}
}
struct AnyFixture: Fixture {
var identifier: String
private var creationHandler: () throws -> NSObject & NSCoding
let supportsSecureCoding: Bool
init<T: Fixture>(_ fixture: T) {
self.identifier = fixture.identifier
self.creationHandler = { return try fixture.make() as! (NSObject & NSCoding) }
self.supportsSecureCoding = fixture.supportsSecureCoding
}
func make() throws -> NSObject & NSCoding {
return try creationHandler()
}
}
enum FixtureError: Error {
case noneFound
}
extension Fixture where ValueType: NSObject & NSCoding {
func load(fixtureRepository: URL, variant: FixtureVariant) throws -> ValueType? {
let data = try Data(contentsOf: url(inFixtureRepository: fixtureRepository, variant: variant))
let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
unarchiver.requiresSecureCoding = self.supportsSecureCoding
unarchiver.decodingFailurePolicy = .setErrorAndReturn
let value = unarchiver.decodeObject(of: ValueType.self, forKey: NSKeyedArchiveRootObjectKey)
if let error = unarchiver.error {
throw error
}
return value
}
func url(inFixtureRepository fixtureRepository: URL, variant: FixtureVariant) -> URL {
return variant.url(fixtureRepository: fixtureRepository)
.appendingPathComponent(identifier)
.appendingPathExtension("archive")
}
func loadEach(fixtureRepository: URL, handler: (ValueType, FixtureVariant) throws -> Void) throws {
var foundAny = false
for variant in FixtureVariant.allCases {
let fileURL = url(inFixtureRepository: fixtureRepository, variant: variant)
guard (try? fileURL.checkResourceIsReachable()) == true else { continue }
foundAny = true
if let value = try load(fixtureRepository: fixtureRepository, variant: variant) {
try handler(value, variant)
}
}
guard foundAny else { throw FixtureError.noneFound }
}
}
|
apache-2.0
|
b54a9f6320c820e69d26be2acba10bd6
| 37.258454 | 203 | 0.665825 | 5.058767 | false | false | false | false |
AaronMT/firefox-ios
|
Client/Frontend/EnhancedTrackingProtection/ETPCoverSheetViewController.swift
|
5
|
8297
|
/* 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 SnapKit
import Shared
import Leanplum
/* The layout for ETP Cover Sheet
|----------------|
| Done|
| |
| Image |
| [Centre] | (Top View)
| |
|Title Multiline |
| |
|Description |
|Multiline |
| |
|----------------|
| |
| [Button] |
| [Button] | (Bottom View)
|----------------|
*/
class ETPCoverSheetViewController: UIViewController {
// Public constants
let viewModel = ETPViewModel()
static let theme = BuiltinThemeName(rawValue: ThemeManager.instance.current.name) ?? .normal
// Private vars
private var fxTextThemeColour: UIColor {
// For dark theme we want to show light colours and for light we want to show dark colours
return ETPCoverSheetViewController.theme == .dark ? .white : .black
}
private var fxBackgroundThemeColour: UIColor {
return ETPCoverSheetViewController.theme == .dark ? .black : .white
}
private var doneButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.SettingsSearchDoneButton, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .regular)
button.setTitleColor(UIColor.systemBlue, for: .normal)
return button
}()
private lazy var topImageView: UIImageView = {
let imgView = UIImageView(image: viewModel.etpCoverSheetmodel?.titleImage)
imgView.contentMode = .scaleAspectFit
imgView.clipsToBounds = true
return imgView
}()
private lazy var titleLabel: UILabel = {
let label = UILabel()
label.text = viewModel.etpCoverSheetmodel?.titleText
label.textColor = fxTextThemeColour
label.font = UIFont.boldSystemFont(ofSize: 18)
label.textAlignment = .left
label.numberOfLines = 0
return label
}()
private lazy var descriptionLabel: UILabel = {
let label = UILabel()
label.text = viewModel.etpCoverSheetmodel?.descriptionText
label.textColor = fxTextThemeColour
label.font = UIFont.systemFont(ofSize: 18)
label.textAlignment = .left
label.numberOfLines = 0
return label
}()
private lazy var goToSettingsButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.CoverSheetETPSettingsButton, for: .normal)
button.titleLabel?.font = UpdateViewControllerUX.StartBrowsingButton.font
button.layer.cornerRadius = UpdateViewControllerUX.StartBrowsingButton.cornerRadius
button.setTitleColor(.white, for: .normal)
button.backgroundColor = UpdateViewControllerUX.StartBrowsingButton.colour
return button
}()
private lazy var startBrowsingButton: UIButton = {
let button = UIButton()
button.setTitle(Strings.StartBrowsingButtonTitle, for: .normal)
button.titleLabel?.font = UpdateViewControllerUX.StartBrowsingButton.font
button.setTitleColor(UIColor.Photon.Blue50, for: .normal)
button.backgroundColor = .clear
return button
}()
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
initialViewSetup()
}
func initialViewSetup() {
self.view.backgroundColor = fxBackgroundThemeColour
// Initialize
self.view.addSubview(topImageView)
self.view.addSubview(doneButton)
self.view.addSubview(titleLabel)
self.view.addSubview(descriptionLabel)
self.view.addSubview(goToSettingsButton)
self.view.addSubview(startBrowsingButton)
// Constraints
setupTopView()
setupBottomView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
private func setupTopView() {
// Done button target setup
doneButton.addTarget(self, action: #selector(dismissAnimated), for: .touchUpInside)
// Done button constraints setup
// This button is located at top right hence top, right and height
doneButton.snp.makeConstraints { make in
make.top.equalTo(view.snp.topMargin).offset(UpdateViewControllerUX.DoneButton.paddingTop)
make.right.equalToSuperview().inset(UpdateViewControllerUX.DoneButton.paddingRight)
make.height.equalTo(UpdateViewControllerUX.DoneButton.height)
}
// The top imageview constraints setup
topImageView.snp.makeConstraints { make in
make.left.equalToSuperview()
make.right.equalToSuperview()
make.top.equalTo(doneButton.snp.bottom).offset(10)
make.bottom.equalTo(goToSettingsButton.snp.top).offset(-200)
make.height.lessThanOrEqualTo(100)
}
// Top title label constraints setup
titleLabel.snp.makeConstraints { make in
make.bottom.equalTo(descriptionLabel.snp.top).offset(-5)
make.left.right.equalToSuperview().inset(20)
}
// Description title label constraints setup
descriptionLabel.snp.makeConstraints { make in
make.bottom.equalTo(goToSettingsButton.snp.top).offset(-40)
make.left.right.equalToSuperview().inset(20)
}
}
private func setupBottomView() {
// Bottom start button constraints
goToSettingsButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(UpdateViewControllerUX.StartBrowsingButton.edgeInset)
make.bottom.equalTo(startBrowsingButton.snp.top).offset(-16)
make.height.equalTo(UpdateViewControllerUX.StartBrowsingButton.height)
}
// Bottom goto settings button
goToSettingsButton.addTarget(self, action: #selector(goToSettings), for: .touchUpInside)
// Bottom start button constraints
startBrowsingButton.snp.makeConstraints { make in
make.left.right.equalToSuperview().inset(UpdateViewControllerUX.StartBrowsingButton.edgeInset)
let h = view.frame.height
// On large iPhone screens, bump this up from the bottom
let offset: CGFloat = UIDevice.current.userInterfaceIdiom == .pad ? 20 : (h > 800 ? 60 : 20)
make.bottom.equalTo(view.safeArea.bottom).inset(offset)
make.height.equalTo(UpdateViewControllerUX.StartBrowsingButton.height)
}
// Bottom start browsing target setup
startBrowsingButton.addTarget(self, action: #selector(startBrowsing), for: .touchUpInside)
}
// Button Actions
@objc private func dismissAnimated() {
self.dismiss(animated: true, completion: nil)
LeanPlumClient.shared.track(event: .dismissedETPCoverSheet)
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissedETPCoverSheet)
}
@objc private func goToSettings() {
viewModel.goToSettings?()
LeanPlumClient.shared.track(event: .dismissETPCoverSheetAndGoToSettings)
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissETPCoverSheetAndGoToSettings)
}
@objc private func startBrowsing() {
viewModel.startBrowsing?()
LeanPlumClient.shared.track(event: .dismissETPCoverSheetAndStartBrowsing)
TelemetryWrapper.recordEvent(category: .action, method: .press, object: .dismissUpdateCoverSheetAndStartBrowsing)
}
}
// UIViewController setup to keep it in portrait mode
extension ETPCoverSheetViewController {
override var shouldAutorotate: Bool {
return false
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
// This actually does the right thing on iPad where the modally
// presented version happily rotates with the iPad orientation.
return .portrait
}
}
|
mpl-2.0
|
f833a0c58716ce1110d6196a22ab62c8
| 38.698565 | 121 | 0.661805 | 4.974221 | false | false | false | false |
qinting513/SwiftNote
|
HandyJSONDemo-JSON转模型工具!/HandyJSONDemo/NSObject+Parse.swift
|
1
|
2354
|
//
// NSObject+Parse.swift
// HandyJSONDemo
//
// Created by Qinting on 2016/11/14.
// Copyright © 2016年 QT. All rights reserved.
//
import Foundation
extension NSObject {
/** 只支持属性全部是 string 类型的模型,当某个属性是 NSDictionary 或者 Array 时, json[key].stringValue 会崩溃 */
func parseData(json:JSON) {
let dic = json.dictionaryValue as NSDictionary
let keyArr:Array<String> = dic.allKeys as! Array<String>
var propertyArr:Array<String> = []
let hMirror = Mirror(reflecting: self)
for case let (label?, _) in hMirror.children {
propertyArr.append(label)
}
for property in propertyArr {
for key in keyArr {
if key == property {
self.setValue(json[key].stringValue, forKey: key)
}
}
}
}
func parseData(json:JSON,arrayValues:Array<String>?=nil) {
let dic = json.dictionaryValue as NSDictionary
let keyArr:Array<String> = dic.allKeys as! Array<String>
var propertyArr:Array<String> = []
let hMirror = Mirror(reflecting: self)
for case let (label?, _) in hMirror.children {
propertyArr.append(label)
}
for property in propertyArr {
for key in keyArr {
if key == property {
for value in arrayValues! {
if value == property {
self.setValue(json[value].arrayValue, forKey: value)
return
}
}
self.setValue(json[key].stringValue, forKey: key)
}
}
}
}
/** 支持任意类型 */
func parseData(dic:NSDictionary) {
print(dic)
let keyArr:Array<String> = dic.allKeys as! Array<String>
var propertyArr:Array<String> = []
let hMirror = Mirror(reflecting: self)
for case let (label?, _) in hMirror.children {
propertyArr.append(label)
}
for property in propertyArr {
for key in keyArr {
if key == property {
self.setValue(dic[key], forKey: key)
}
}
}
}
}
|
apache-2.0
|
c0dc7b0e5e438a5b300fb480e6cdfab0
| 29.932432 | 90 | 0.512888 | 4.505906 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.