repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
yaslab/ZipArchive.swift
Sources/ZipModel/EndOfCentralDirectoryRecord.swift
1
3951
// // EndOfCentralDirectoryRecord.swift // ZipArchive // // Created by Yasuhiro Hatta on 2017/12/28. // Copyright © 2017 yaslab. All rights reserved. // import struct Foundation.Data import ZipIO public struct EndOfCentralDirectoryRecord { /// number of this disk public var diskNumber: UInt16 /// number of the disk with the start of the central directory public var startDiskNumber: UInt16 /// total number of entries in the central directory on this disk public var entryCount: UInt16 /// total number of entries in the central directory public var totalEntryCount: UInt16 /// size of the central directory public var centralDirectorySize: UInt32 /// offset of start of central directory with respect to the starting disk number public var centralDirectoryOffset: UInt32 /// .ZIP file comment public var comment: Data public init(diskNumber: UInt16, startDiskNumber: UInt16, entryCount: UInt16, totalEntryCount: UInt16, centralDirectorySize: UInt32, centralDirectoryOffset: UInt32, comment: Data) { self.diskNumber = diskNumber self.startDiskNumber = startDiskNumber self.entryCount = entryCount self.totalEntryCount = totalEntryCount self.centralDirectorySize = centralDirectorySize self.centralDirectoryOffset = centralDirectoryOffset self.comment = comment } } extension EndOfCentralDirectoryRecord { public init?(stream: InputStream) { guard let signature = Signature(rawValue: stream.read(UInt32.self)), signature == .endOfCentralDirectory else { return nil } self.diskNumber = stream.read(UInt16.self) self.startDiskNumber = stream.read(UInt16.self) self.entryCount = stream.read(UInt16.self) self.totalEntryCount = stream.read(UInt16.self) self.centralDirectorySize = stream.read(UInt32.self) self.centralDirectoryOffset = stream.read(UInt32.self) let commentLength = stream.read(UInt16.self) self.comment = stream.read(count: Int(commentLength)) } } extension EndOfCentralDirectoryRecord { public func write(to stream: OutputStream, encoding: String.Encoding) { stream.write(UInt32.self, Signature.endOfCentralDirectory.rawValue) stream.write(UInt16.self, diskNumber) stream.write(UInt16.self, startDiskNumber) stream.write(UInt16.self, entryCount) stream.write(UInt16.self, totalEntryCount) stream.write(UInt32.self, centralDirectorySize) stream.write(UInt32.self, centralDirectoryOffset) stream.write(UInt16.self, UInt16(comment.count)) if comment.count > 0 { _ = stream.write(data: comment) } } } extension EndOfCentralDirectoryRecord { public static func search(_ stream: RandomAccessInputStream) -> EndOfCentralDirectoryRecord? { guard stream.seek(offset: 0, origin: .end) else { return nil } let bufferSize = Int(Swift.min(stream.tell(), Int64(Int16.max))) if bufferSize < 22 { return nil } guard stream.seek(offset: -Int64(bufferSize), origin: .end) else { return nil } let buffer = stream.read(count: bufferSize) for i in (3 ..< buffer.count).reversed() { if buffer[i] == 0x06 && buffer[i - 1] == 0x05 && buffer[i - 2] == 0x4b && buffer[i - 3] == 0x50 { let memory = ReadOnlyMemoryStream(data: buffer) _ = memory.seek(offset: Int64(i - 3), origin: .begin) return EndOfCentralDirectoryRecord(stream: memory) } } return nil } }
mit
af3c165d8bd794e85f2bab796be2df70
30.854839
109
0.624051
4.561201
false
false
false
false
elliottminns/blackfish
Sources/Blackfire/HTTPRequest.swift
2
1856
import Foundation public class HTTPRequest { public let method: HTTPMethod public let headers: [String: String] public let body: String public let query: [String: Any] public let path: String public let httpProtocol: String var connection: Connection? public init(headers: [String: String], method: HTTPMethod, body: String, path: String, httpProtocol: String) { self.headers = headers self.body = body self.method = method self.httpProtocol = httpProtocol let pathComps = path.components(separatedBy: "?") self.path = pathComps.first ?? "/" var query: [String: Any] = [:] if pathComps.count > 1 { pathComps.last?.components(separatedBy: "&") .flatMap { (keypair) -> (key: String, value: String)? in let comps = keypair.components(separatedBy: "=") guard let first = comps.first, let last = comps.last else { return nil } return (key: first, value: last) }.forEach { if (query[$0.key] is Array<Any>) { query[$0.key] = (query[$0.key] as! Array<Any>) + [$0.value] } else if (query[$0.key] is String) { guard let value = query[$0.key] else { query[$0.key] = $0.value return } query[$0.key] = [value, $0.value] } else { query[$0.key] = $0.value } } } self.query = query } }
apache-2.0
24d22669a510e2ffb78adc69ade3c989
29.933333
83
0.440733
4.93617
false
false
false
false
53ningen/SL4Swift
SL4Swift/LogLevel.swift
1
1115
import Foundation public struct LogLevel { public let level: Int public let code: String public let displayName: String public static let Trace = LogLevel(level: 10, code: "trace", displayName: "TRACE") public static let Debug = LogLevel(level: 20, code: "debug", displayName: "DEBUG") public static let Info = LogLevel(level: 30, code: "info" , displayName: "INFO") public static let Warn = LogLevel(level: 40, code: "warn" , displayName: "WARN") public static let Error = LogLevel(level: 50, code: "error", displayName: "ERROR") private init(level: Int, code: String, displayName: String) { self.level = level self.code = code self.displayName = displayName } } extension LogLevel: Printable { public var description: String { return "LogLevel{level: \(level),code:\(code),displayName:\(displayName)}" } } extension LogLevel: Equatable {} public func ==(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.level == rhs.level && lhs.code == rhs.code && lhs.displayName == rhs.displayName }
mit
c447e8d668ba838359d70145cc1a015a
31.794118
86
0.647534
4.160448
false
false
false
false
ArnavChawla/InteliChat
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/QueryRelationsFilter.swift
1
1979
/** * 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 /** QueryRelationsFilter. */ public struct QueryRelationsFilter: Encodable { /// A list of relation types to include or exclude from the query. public var relationTypes: QueryFilterType? /// A list of entity types to include or exclude from the query. public var entityTypes: QueryFilterType? /// A comma-separated list of document IDs to include in the query. public var documentIds: [String]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case relationTypes = "relation_types" case entityTypes = "entity_types" case documentIds = "document_ids" } /** Initialize a `QueryRelationsFilter` with member variables. - parameter relationTypes: A list of relation types to include or exclude from the query. - parameter entityTypes: A list of entity types to include or exclude from the query. - parameter documentIds: A comma-separated list of document IDs to include in the query. - returns: An initialized `QueryRelationsFilter`. */ public init(relationTypes: QueryFilterType? = nil, entityTypes: QueryFilterType? = nil, documentIds: [String]? = nil) { self.relationTypes = relationTypes self.entityTypes = entityTypes self.documentIds = documentIds } }
mit
d8498e627d4b1f3f396eb65b5fd024ba
36.339623
123
0.717029
4.570439
false
false
false
false
PartiuUFAL/partiuufal-ios
#PartiuUfal/#PartiuUfal/Classes/Ride/Driver/PUDriverRideViewController.swift
1
1605
// // PUDriverRideViewController.swift // #PartiuUfal // // Created by Rubens Pessoa on 05/08/17. // Copyright © 2017 Rubens Pessoa. All rights reserved. // import UIKit import MapKit class PUDriverRideViewController: UIViewController { var targetName: String? var targetLocation: CLLocationCoordinate2D? var ride: PURide? @IBOutlet weak var mapView: MKMapView! init(targetName: String!, targetLocation: CLLocationCoordinate2D!) { super.init(nibName: "PUDriverRideViewController", bundle: nil) self.targetName = targetName self.targetLocation = targetLocation } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupLocation() createRide() } func createRide() { ride = PURide() ride?.driver = PUUser.current() ride?.passengers = [] ride?.targetName = targetName ride?.isActive = NSNumber(booleanLiteral: true) ride?.saveInBackground { (success, error) in if success { print("Salvou corrida com sucesso") } else { print(error!.localizedDescription) } } } func setupNavigationBar() { self.title = "Carona" self.navigationController?.navigationBar.tintColor = UIColor.black } func setupLocation() { PULocationManager.shared.setup(mapView, centerMapOnUserLocation: true) } }
agpl-3.0
f9fb57ec9364632784915a3742c7ebdf
25.295082
78
0.624065
4.649275
false
false
false
false
airander/redis-framework
Redis-Framework/Redis-Framework/RedisClient+Strings.swift
1
24288
// // RedisClient+Strings.swift // Redis-Framework // // Copyright (c) 2015, Eric Orion Anderson // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this // list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation public enum RedisSetType:String { case `default` = "N/A" case onlySetIfKeyDoesNotAlreadyExist = "NX" case onlySetIfKeyAlreadyExists = "XX" } public enum RedisBitOpType:String { case and = "AND" case or = "OR" case xor = "XOR" case not = "NOT" } public enum RedisBitType:String { case zero = "0" case one = "1" } extension RedisClient { /// APPEND key value /// /// If key already exists and is a string, this command appends the value at the end of the string. /// If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. /// /// - returns: Integer reply: the length of the string after the append operation. public func append(string:String, toKey key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("APPEND \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: string))", completionHandler: completionHandler) } /// BITCOUNT key [start end] /// /// Count the number of set bits (population counting) in a string. /// By default all the bytes contained in the string are examined. It is possible to specify the counting operation only in an interval passing the additional arguments start and end. /// Like for the GETRANGE command start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, -2 is the penultimate, and so forth. /// Non-existent keys are treated as empty strings, so the command will return zero. /// /// - returns: Integer reply: The number of bits set to 1. public func bitCount(key:String, range:(start:Int, end:Int)? = nil, completionHandler:@escaping RedisCommandIntegerBlock) { var command:String = "BITCOUNT \(RESPUtilities.respString(from: key))" if range != nil { command = command + " \(range!.start) \(range!.end)" } self.send(command, completionHandler: completionHandler) } /// BITOP operation destkey key [key ...] /// /// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key. /// The BITOP command supports four bitwise operations: AND, OR, XOR and NOT, thus the valid forms to call the command are: /// BITOP AND destkey srckey1 srckey2 srckey3 ... srckeyN /// BITOP OR destkey srckey1 srckey2 srckey3 ... srckeyN /// BITOP XOR destkey srckey1 srckey2 srckey3 ... srckeyN /// BITOP NOT destkey srckey /// As you can see NOT is special as it only takes an input key, because it performs inversion of bits so it only makes sense as an unary operator. /// The result of the operation is always stored at destkey. /// /// Handling of strings with different lengths /// When an operation is performed between strings having different lengths, all the strings shorter than the longest string in the set are treated as if they were zero-padded up to the length of the longest string. /// The same holds true for non-existent keys, that are considered as a stream of zero bytes up to the length of the longest string. /// /// - returns: Integer reply: The size of the string stored in the destination key, that is equal to the size of the longest input string. public func bitOp(bitOpType:RedisBitOpType, destinationKey:String, keys:[String], completionHandler:@escaping RedisCommandIntegerBlock) { var command = "BITOP \(bitOpType.rawValue) \(RESPUtilities.respString(from: destinationKey))" for key in keys { command = command + " \(RESPUtilities.respString(from: key))" } self.send(command, completionHandler: completionHandler) } /// BITPOS key bit [start] [end] /// /// Return the position of the first bit set to 1 or 0 in a string. /// The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, /// the second byte's most significant bit is at position 8, and so forth. /// The same bit position convention is followed by GETBIT and SETBIT. /// By default, all the bytes contained in the string are examined. It is possible to look for bits only in a specified interval passing the additional arguments /// start and end (it is possible to just pass start, the operation will assume that the end is the last byte of the string. However there are semantical /// differences as explained later). The range is interpreted as a range of bytes and not a range of bits, so start=0 and end=2 means to look at the first three bytes. /// Note that bit positions are returned always as absolute values starting from bit zero even when start and end are used to specify a range. /// Like for the GETRANGE command start and end can contain negative values in order to index bytes starting from the end of the string, where -1 is the last byte, /// -2 is the penultimate, and so forth. /// Non-existent keys are treated as empty strings. /// /// - returns: Integer reply: The command returns the position of the first bit set to 1 or 0 according to the request. If we look for set bits (the bit argument is 1) and the string is empty or composed of just zero bytes, -1 is returned. If we look for clear bits (the bit argument is 0) and the string only contains bit set to 1, the function returns the first bit not part of the string on the right. So if the string is three bytes set to the value 0xff the command BITPOS key 0 will return 24, since up to bit 23 all the bits are 1. Basically, the function considers the right of the string as padded with zeros if you look for clear bits and specify no range or the start argument only. However, this behavior changes if you are looking for clear bits and specify a range with both start and end. If no clear bit is found in the specified range, the function returns -1 as the user specified a clear range and there are no 0 bits in that range. public func bitPos(key:String, bitType:RedisBitType, rangeOfBytes range:(start:Int, end:Int?) = (0, nil), completionHandler:@escaping RedisCommandIntegerBlock) { var command:String = "BITPOS \(RESPUtilities.respString(from: key)) \(bitType.rawValue) \(range.start)" if let rangeEnd:Int = range.end { command = command + " \(rangeEnd)" } self.send(command, completionHandler: completionHandler) } /// DECR key /// /// Decrements the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers. /// See INCR for extra information on increment/decrement operations. /// /// - returns: Integer reply: the value of key after the decrement public func decr(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("DECR \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// DECRBY key decrement /// /// Decrements the number stored at key by decrement. If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. /// This operation is limited to 64 bit signed integers. /// See INCR for extra information on increment/decrement operations. /// /// - returns: Integer reply: the value of key after the decrement public func decr(key:String, decrement:UInt, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("DECRBY \(RESPUtilities.respString(from: key)) \(decrement)", completionHandler: completionHandler) } /// GET key /// /// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values. /// /// - returns: Bulk string reply: the value of key, or nil when key does not exist. public func get(key:String, completionHandler:@escaping RedisCommandStringBlock) { self.send("GET \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// GETBIT key offset /// /// Returns the bit value at offset in the string value stored at key. /// When offset is beyond the string length, the string is assumed to be a contiguous space with 0 bits. /// When key does not exist it is assumed to be an empty string, so offset is always out of range and the value is also assumed to be a contiguous space with 0 bits. /// /// - returns: Integer reply: the bit value stored at offset. public func getBit(key:String, offset:UInt, completionHandler:@escaping ((_ bit:RedisBitType?, _ error:NSError?)->Void)) { self.send("GETBIT \(RESPUtilities.respString(from: key)) \(offset)", completionHandler: { (int: Int?, error) -> Void in if error != nil { completionHandler(nil, error) } else { var bit:RedisBitType if int ?? 0 > 0 { bit = RedisBitType.one } else { bit = RedisBitType.zero } completionHandler(bit, nil) } }) } /// GETRANGE key start end /// /// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). /// Negative offsets can be used in order to provide an offset starting from the end of the string. So -1 means the last character, -2 the penultimate and so forth. /// The function handles out of range requests by limiting the resulting range to the actual length of the string. /// /// - returns: Bulk string reply public func getRange(key:String, range:(start:Int, end:Int), completionHandler:@escaping RedisCommandStringBlock) { self.send("GETRANGE \(RESPUtilities.respString(from: key)) \(range.start) \(range.end)", completionHandler: completionHandler) } /// GETSET key value /// /// Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value. /// GETSET can be used together with INCR for counting with atomic reset. For example: a process may call INCR against the key mycounter every /// time some event occurs, but from time to time we need to get the value of the counter and reset it to zero atomically. /// /// - returns: Bulk string reply: the old value stored at key, or nil when key did not exist. public func getSet(key:String, value:String, completionHandler:@escaping RedisCommandStringBlock) { self.send("GETSET \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: value))", completionHandler: completionHandler) } /// INCR key /// /// Increments the number stored at key by one. If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers. /// /// - returns: Integer reply: the value of key after the increment public func incr(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("INCR \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } /// INCRBY key increment /// /// Increments the number stored at key by increment. If the key does not exist, it is set to 0 before performing the operation. /// An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. This operation is limited to 64 bit signed integers. /// See INCR for extra information on increment/decrement operations. /// /// - returns: Integer reply: the value of key after the increment public func incr(key:String, increment:UInt, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("INCRBY \(RESPUtilities.respString(from: key)) \(increment)", completionHandler: completionHandler) } /// INCRBYFLOAT key increment /// /// Increment the string representing a floating point number stored at key by the specified increment. If the key does not exist, /// it is set to 0 before performing the operation. An error is returned if one of the following conditions occur: /// The key contains a value of the wrong type (not a string). /// The current key content or the specified increment are not parsable as a double precision floating point number. /// If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string. /// Both the value already contained in the string key and the increment argument can be optionally provided in exponential notation, however the value computed /// after the increment is stored consistently in the same format, that is, an integer number followed (if needed) by a dot, and a variable number of digits /// representing the decimal part of the number. Trailing zeroes are always removed. /// The precision of the output is fixed at 17 digits after the decimal point regardless of the actual internal precision of the computation. /// /// - returns: Bulk string reply: the value of key after the increment. public func incrFloat(key:String, increment:Double, completionHandler:@escaping RedisCommandStringBlock) { self.send("INCRBYFLOAT \(RESPUtilities.respString(from: key)) \(increment)", completionHandler: completionHandler) } /// MGET key [key ...] /// /// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. /// Because of this, the operation never fails. /// /// - returns: Array reply: list of values at the specified keys. public func mGet(keys:[String], completionHandler:@escaping RedisCommandArrayBlock) { var command = "MGET" for key in keys { command = command + " \(RESPUtilities.respString(from: key))" } self.send(command, completionHandler: completionHandler) } /// MSET key value [key value ...] /// /// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. /// See MSETNX if you don't want to overwrite existing values. /// MSET is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged. /// /// - returns: Simple string reply: always OK since MSET can't fail. public func mSet(keys:[String], values:[AnyObject], completionHandler:@escaping RedisCommandStringBlock) { var command:String = "MSET" for(index, key) in keys.enumerated() { let value:AnyObject = values[index] if value is String { command = command + " \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: value as! String))" } else if value is Int { command = command + " \(RESPUtilities.respString(from: key)) \(value as! Int))" } } self.send(command, completionHandler: completionHandler) } /// MSETNX key value [key value ...] /// /// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists. /// Because of this semantic MSETNX can be used in order to set different keys representing different fields of an unique logic object in /// a way that ensures that either all the fields or none at all are set. /// MSETNX is atomic, so all given keys are set at once. It is not possible for clients to see that some of the keys were updated while others are unchanged. /// /// - returns: Integer reply, specifically: 1 if the all the keys were set. 0 if no key was set (at least one key already existed). public func mSetNX(keys:[String], values:[AnyObject], completionHandler:@escaping RedisCommandIntegerBlock) { var command:String = "MSETNX" for(index, key) in keys.enumerated() { let value:AnyObject = values[index] if value is String { command = command + " \(RESPUtilities.respString(from: key)) \(RESPUtilities.respString(from: value as! String))" } else if value is Int { command = command + " \(RESPUtilities.respString(from: key)) \(value as! Int))" } } self.send(command, completionHandler: completionHandler) } // PSETEX key milliseconds value // // PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds. // // NOTE: Not to be implemented, included functionality in similar SET method below /// SET key value [EX seconds] [PX milliseconds] [NX|XX] /// /// - returns: Simple string reply: OK if SET was executed correctly. Null reply: a Null Bulk Reply is returned if the SET operation was not performed becase the user specified the NX or XX option but the condition was not met. public func set(key:String, value:String, seconds:Int? = nil, milliseconds:Int? = nil, setType:RedisSetType = .default, completionHandler:@escaping RedisCommandStringBlock) { var command:String = "SET " + RESPUtilities.respString(from: key) + " " + RESPUtilities.respString(from: value) if let expireTimeInSeconds = seconds { command = command + " EX \(expireTimeInSeconds)" } if let expireTimeInMilliseconds = milliseconds { command = command + " PX \(expireTimeInMilliseconds)" } switch(setType) { case .onlySetIfKeyDoesNotAlreadyExist: command = command + " \(RedisSetType.onlySetIfKeyDoesNotAlreadyExist.rawValue)" case .onlySetIfKeyAlreadyExists: command = command + " \(RedisSetType.onlySetIfKeyAlreadyExists.rawValue)" default: break } self.send(command, completionHandler: completionHandler) } /// SETBIT key offset value /// /// Sets or clears the bit at offset in the string value stored at key. /// The bit is either set or cleared depending on value, which can be either 0 or 1. When key does not exist, a new string value is created. The string is grown to make sure it can hold a bit at offset. The offset argument is required to be greater than or equal to 0, and smaller than 232 (this limits bitmaps to 512MB). When the string at key is grown, added bits are set to 0. /// /// Warning: When setting the last possible bit (offset equal to 232 -1) and the string value stored at key does not yet hold a string value, or holds a small string value, Redis needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting bit number 232 -1 (512MB allocation) takes ~300ms, setting bit number 230 -1 (128MB allocation) takes ~80ms, setting bit number 228 -1 (32MB allocation) takes ~30ms and setting bit number 226 -1 (8MB allocation) takes ~8ms. Note that once this first allocation is done, subsequent calls to SETBIT for the same key will not have the allocation overhead. /// /// - returns: Integer reply: the original bit value stored at offset. public func setBit(key:String, offset:UInt, value:RedisBitType, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("SETBIT \(RESPUtilities.respString(from: key)) \(offset) \(value.rawValue)", completionHandler: completionHandler) } // SETEX key seconds value // Set the value and expiration of a key // NOTE: Not to be implemented, included functionality in similar SET method above // SETNX key value // Set the value of a key, only if the key does not exist // NOTE: Not to be implemented, included functionality in similar SET method above /// SETRANGE key offset value /// /// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset. /// /// Note that the maximum offset that you can set is 229 -1 (536870911), as Redis Strings are limited to 512 megabytes. If you need to grow beyond this size, you can use multiple keys. /// /// Warning: When setting the last possible byte and the string value stored at key does not yet hold a string value, or holds a small string value, Redis needs to allocate all intermediate memory which can block the server for some time. On a 2010 MacBook Pro, setting byte number 536870911 (512MB allocation) takes ~300ms, setting byte number 134217728 (128MB allocation) takes ~80ms, setting bit number 33554432 (32MB allocation) takes ~30ms and setting bit number 8388608 (8MB allocation) takes ~8ms. Note that once this first allocation is done, subsequent calls to SETRANGE for the same key will not have the allocation overhead. /// /// - returns: Integer reply: the length of the string after it was modified by the command. public func setRange(key:String, offset:Int, value:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("SETRANGE \(RESPUtilities.respString(from: key)) \(offset) \(RESPUtilities.respString(from: value))", completionHandler: completionHandler) } /// STRLEN key /// /// Returns the length of the string value stored at key. An error is returned when key holds a non-string value. /// /// - returns: Integer reply: the length of the string at key, or 0 when key does not exist. public func strlen(key:String, completionHandler:@escaping RedisCommandIntegerBlock) { self.send("STRLEN \(RESPUtilities.respString(from: key))", completionHandler: completionHandler) } }
bsd-2-clause
e110d2f705b50648351fd55b98267a44
64.466307
955
0.700799
4.505287
false
false
false
false
JunDang/SwiftFoundation
Sources/SwiftFoundation/JSON.swift
1
6401
// // JSON.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 6/28/15. // Copyright © 2015 PureSwift. All rights reserved. // /// [JavaScript Object Notation](json.org) public struct JSON { public typealias Array = [JSON.Value] public typealias Object = [String: JSON.Value] /// JSON value type. /// Guarenteed to be valid JSON if root value is array or object. public enum Value: RawRepresentable, Equatable, CustomStringConvertible { case Null /// JSON value is a String Value case String(StringValue) /// JSON value is a Number Value (specific subtypes) case Number(JSON.Number) /// JSON value is an Array of other JSON values case Array(JSONArray) /// JSON value a JSON object case Object(JSONObject) // MARK: - Extract Values public var arrayValue: JSON.Array? { switch self { case let .Array(value): return value default: return nil } } public var objectValue: JSON.Object? { switch self { case let .Object(value): return value default: return nil } } } // MARK: - JSON Number public enum Number: RawRepresentable, Equatable, CustomStringConvertible { case Boolean(Bool) case Integer(Int) case Double(DoubleValue) } } // MARK: - RawRepresentable public extension JSON.Value { var rawValue: Any { switch self { case .Null: return SwiftFoundation.Null() case .String(let string): return string case .Number(let number): return number.rawValue case .Array(let array): return array.rawValues case .Object(let dictionary): var dictionaryValue = [StringValue: Any](minimumCapacity: dictionary.count) for (key, value) in dictionary { dictionaryValue[key] = value.rawValue } return dictionaryValue } } init?(rawValue: Any) { guard (rawValue as? SwiftFoundation.Null) == nil else { self = .Null return } if let string = rawValue as? Swift.String { self = .String(string) return } if let number = JSON.Number(rawValue: rawValue) { self = .Number(number) return } if let rawArray = rawValue as? [Any], let jsonArray: [JSON.Value] = JSON.Value.fromRawValues(rawArray) { self = .Array(jsonArray) return } if let rawDictionary = rawValue as? [Swift.String: Any] { var jsonObject = [StringValue: JSONValue](minimumCapacity: rawDictionary.count) for (key, rawValue) in rawDictionary { guard let jsonValue = JSON.Value(rawValue: rawValue) else { return nil } jsonObject[key] = jsonValue } self = .Object(jsonObject) return } return nil } } public extension JSON.Number { public var rawValue: Any { switch self { case .Boolean(let value): return value case .Integer(let value): return value case .Double(let value): return value } } public init?(rawValue: Any) { if let value = rawValue as? Bool { self = .Boolean(value); return } if let value = rawValue as? Int { self = .Integer(value); return } if let value = rawValue as? DoubleValue { self = .Double(value); return } return nil } } // MARK: - CustomStringConvertible public extension JSON.Value { public var description: Swift.String { return "\(rawValue)" } } public extension JSON.Number { public var description: String { return "\(rawValue)" } } // MARK: Equatable public func ==(lhs: JSON.Value, rhs: JSON.Value) -> Bool { switch (lhs, rhs) { case (.Null, .Null): return true case let (.String(leftValue), .String(rightValue)): return leftValue == rightValue case let (.Number(leftValue), .Number(rightValue)): return leftValue == rightValue case let (.Array(leftValue), .Array(rightValue)): return leftValue == rightValue case let (.Object(leftValue), .Object(rightValue)): return leftValue == rightValue default: return false } } public func ==(lhs: JSON.Number, rhs: JSON.Number) -> Bool { switch (lhs, rhs) { case let (.Boolean(leftValue), .Boolean(rightValue)): return leftValue == rightValue case let (.Integer(leftValue), .Integer(rightValue)): return leftValue == rightValue case let (.Double(leftValue), .Double(rightValue)): return leftValue == rightValue default: return false } } // MARK: - Protocol /// Type can be converted to JSON. public protocol JSONEncodable { /// Encodes the reciever into JSON. func toJSON() -> JSON.Value } /// Type can be converted from JSON. public protocol JSONDecodable { /// Decodes the reciever from JSON. init?(JSONValue: JSON.Value) } /// Type can be converted from JSON according to parameters. public protocol JSONParametrizedDecodable { typealias JSONDecodingParameters /// Decodes the reciever from JSON according to the specified parameters. init?(JSONValue: JSON.Value, parameters: JSONDecodingParameters) } // Typealiases due to compiler error public typealias JSONValue = JSON.Value public typealias JSONArray = [JSONValue] public typealias JSONObject = [String: JSONValue] public typealias StringValue = String public typealias FloatValue = Float public typealias DoubleValue = Double public typealias NullValue = Null
mit
47cd06bfee0174760dcd17bb27c0ee8a
23.902724
112
0.553281
5.22449
false
false
false
false
HJliu1123/LearningNotes-LHJ
April/Xbook/Xbook/login/HJRegisterViewController.swift
1
2091
// // HJRegisterViewController.swift // Xbook // // Created by liuhj on 16/3/10. // Copyright © 2016年 liuhj. All rights reserved. // import UIKit class HJRegisterViewController: UIViewController { @IBOutlet weak var topLayout: NSLayoutConstraint! @IBOutlet weak var userName: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var email: UITextField! override func viewDidLoad() { super.viewDidLoad() XKeyBoard.registerKeyBoardHide(self) XKeyBoard.registerKeyBoardShow(self) } @IBAction func register(sender: AnyObject) { let user = AVUser() user.username = self.userName.text user.password = self.password.text user.email = self.email.text user.signUpInBackgroundWithBlock { (success, error) -> Void in if success { ProgressHUD.showSuccess("注册成功,请验证邮箱!") self.dismissViewControllerAnimated(true, completion: { () -> Void in }) } else { if error.code == 125 { ProgressHUD.showError("邮箱不合法!") } else if error.code == 203 { ProgressHUD.showError("邮箱已注册!") } else if error.code == 202 { ProgressHUD.showError("用户名已存在!") } else { ProgressHUD.showError("注册失败!") } } } } func keyboardWillHideNotification(notification : NSNotification) { UIView.animateWithDuration(0.3) { () -> Void in self.topLayout.constant = 8 self.view.layoutIfNeeded() } } func keyboardWillShowNotification(notification : NSNotification) { UIView.animateWithDuration(0.3) { () -> Void in self.topLayout.constant = -150 self.view.layoutIfNeeded() } } }
apache-2.0
c852fb880ee959fd35b0268f21211916
25.906667
84
0.540634
5.21447
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/StatisticRowItem.swift
1
12738
// // StatisticRowItem.swift // Telegram // // Created by Mikhail Filimonov on 24.02.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import GraphUI import GraphCore import SwiftSignalKit public enum ChartItemType { case lines case twoAxis case pie case area case bars case step case twoAxisStep case hourlyStep case twoAxisHourlyStep case twoAxis5MinStep } class StatisticRowItem: GeneralRowItem { let collection: ChartsCollection let controller: BaseChartController init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, collection: ChartsCollection, viewType: GeneralViewType, type: ChartItemType, getDetailsData: @escaping (Date, @escaping (String?) -> Void) -> Void) { self.collection = collection let controller: BaseChartController switch type { case .lines: controller = GeneralLinesChartController(chartsCollection: collection) controller.isZoomable = false case .twoAxis: controller = TwoAxisLinesChartController(chartsCollection: collection) controller.isZoomable = false case .pie: controller = PercentPieChartController(chartsCollection: collection) case .area: controller = PercentPieChartController(chartsCollection: collection, initiallyZoomed: false) case .bars: controller = StackedBarsChartController(chartsCollection: collection) controller.isZoomable = false case .step: controller = StepBarsChartController(chartsCollection: collection) case .twoAxisStep: controller = TwoAxisStepBarsChartController(chartsCollection: collection) case .hourlyStep: controller = StepBarsChartController(chartsCollection: collection, hourly: true) controller.isZoomable = false case .twoAxisHourlyStep: let stepController = TwoAxisStepBarsChartController(chartsCollection: collection) stepController.hourly = true controller = stepController controller.isZoomable = false case .twoAxis5MinStep: let stepController = TwoAxisStepBarsChartController(chartsCollection: collection) stepController.min5 = true controller = stepController controller.isZoomable = false } controller.getDetailsData = { date, completion in let signal:Signal<ChartsCollection?, NoError> = Signal { subscriber -> Disposable in var cancelled: Bool = false getDetailsData(date, { detailsData in if let detailsData = detailsData, let data = detailsData.data(using: .utf8), !cancelled { ChartsDataManager.readChart(data: data, extraCopiesCount: 0, sync: true, success: { collection in if !cancelled { subscriber.putNext(collection) subscriber.putCompletion() } }) { error in if !cancelled { subscriber.putNext(nil) subscriber.putCompletion() } } } else { if !cancelled { subscriber.putNext(nil) subscriber.putCompletion() } } }) return ActionDisposable { cancelled = true } } _ = showModalProgress(signal: signal, for: context.window).start(next: { collection in completion(collection) }) } self.controller = controller super.init(initialSize, stableId: stableId, viewType: viewType) _ = makeSize(initialSize.width, oldWidth: 0) } private var graphHeight: CGFloat = 0 override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) graphHeight = self.controller.height(for: blockWidth - (viewType.innerInset.left + viewType.innerInset.right)) + viewType.innerInset.bottom + viewType.innerInset.top return true } override var height: CGFloat { return graphHeight } override func viewClass() -> AnyClass { return StatisticRowView.self } override var instantlyResize: Bool { return false } } class StatisticRowView: TableRowView { private let chartView: ChartStackSection = ChartStackSection() private let containerView = GeneralRowContainerView(frame: NSZeroRect) required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(self.containerView) self.containerView.addSubview(chartView) } override func updateMouse() { super.updateMouse() chartView.updateMouse() } private var chartTheme: ChartTheme { let chartTheme = (theme.colors.isDark ? ChartTheme.defaultNightTheme : ChartTheme.defaultDayTheme) return ChartTheme(chartTitleColor: theme.colors.text, actionButtonColor: theme.colors.accent, chartBackgroundColor: theme.colors.background, chartLabelsColor: theme.colors.grayText, chartHelperLinesColor: chartTheme.chartHelperLinesColor, chartStrongLinesColor: chartTheme.chartStrongLinesColor, barChartStrongLinesColor: chartTheme.barChartStrongLinesColor, chartDetailsTextColor: theme.colors.grayText, chartDetailsArrowColor: theme.colors.grayText, chartDetailsViewColor: theme.colors.grayBackground, rangeViewFrameColor: chartTheme.rangeViewFrameColor, rangeViewTintColor: theme.colors.grayForeground.withAlphaComponent(0.4), rangeViewMarkerColor: chartTheme.rangeViewTintColor, rangeCropImage: chartTheme.rangeCropImage) } override var backdorColor: NSColor { return chartTheme.chartBackgroundColor } override func updateColors() { guard let item = item as? StatisticRowItem else { return } self.backgroundColor = item.viewType.rowBackground self.containerView.backgroundColor = backdorColor } override func layout() { super.layout() guard let item = item as? StatisticRowItem else { return } self.containerView.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - item.blockWidth) / 2), item.inset.top, item.blockWidth, frame.height - item.inset.bottom - item.inset.top) self.containerView.setCorners(item.viewType.corners) chartView.frame = NSMakeRect(item.viewType.innerInset.left, item.viewType.innerInset.top, self.containerView.frame.width - item.viewType.innerInset.left - item.viewType.innerInset.right, self.containerView.frame.height - item.viewType.innerInset.top - item.viewType.innerInset.bottom) chartView.layout() } private var first: Bool = true override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? StatisticRowItem else { return } layout() chartView.setup(controller: item.controller, title: "Test") chartView.apply(theme: chartTheme, strings: ChartStrings(zoomOut: strings().graphZoomOut, total: strings().graphTotal), animated: false) if first { chartView.layer?.animateAlpha(from: 0, to: 1, duration: 0.25) } first = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class StatisticLoadingRowItem: GeneralRowItem { fileprivate let errorTextLayout: TextViewLayout? init(_ initialSize: NSSize, stableId: AnyHashable, error: String?) { let height: CGFloat = 308 + GeneralViewType.singleItem.innerInset.bottom + GeneralViewType.singleItem.innerInset.top + 30 if let error = error { self.errorTextLayout = TextViewLayout.init(.initialize(string: error, color: theme.colors.grayText, font: .normal(.text))) } else { self.errorTextLayout = nil } super.init(initialSize, height: height, stableId: stableId, viewType: .singleItem) _ = self.makeSize(initialSize.width) } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) errorTextLayout?.measure(width: blockWidth - viewType.innerInset.left - viewType.innerInset.right) return true } override func viewClass() -> AnyClass { return StatisticLoadingRowView.self } override var instantlyResize: Bool { return false } } class StatisticLoadingRowView: TableRowView { private let containerView = GeneralRowContainerView(frame: NSZeroRect) private var errorView: TextView? private var progressIndicator: ProgressIndicator? required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(self.containerView) } override var backdorColor: NSColor { return theme.colors.background } override func updateColors() { guard let item = item as? StatisticLoadingRowItem else { return } self.backgroundColor = item.viewType.rowBackground self.containerView.backgroundColor = backdorColor } override func layout() { super.layout() guard let item = item as? StatisticLoadingRowItem else { return } self.containerView.frame = NSMakeRect(floorToScreenPixels(backingScaleFactor, (frame.width - item.blockWidth) / 2), item.inset.top, item.blockWidth, frame.height - item.inset.bottom - item.inset.top) self.containerView.setCorners(item.viewType.corners) errorView?.center() progressIndicator?.center() } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? StatisticLoadingRowItem else { return } if let error = item.errorTextLayout { if self.errorView == nil { self.errorView = TextView() self.errorView?.isSelectable = false self.containerView.addSubview(self.errorView!) self.errorView?.center() if animated { self.errorView?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } if animated { if let progress = self.progressIndicator { self.progressIndicator = nil progress.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak progress] _ in progress?.removeFromSuperview() }) } } else { self.progressIndicator?.removeFromSuperview() self.progressIndicator = nil } self.errorView?.update(error) } else { if self.progressIndicator == nil { self.progressIndicator = ProgressIndicator(frame: NSMakeRect(0, 0, 30, 30)) self.containerView.addSubview(self.progressIndicator!) self.errorView?.center() if animated { self.progressIndicator?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) } } if animated { self.progressIndicator?.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) if let errorView = self.errorView { self.errorView = nil errorView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false, completion: { [weak errorView] _ in errorView?.removeFromSuperview() }) } } else { self.errorView?.removeFromSuperview() self.errorView = nil } } needsLayout = true } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
11adfa29c23fde4adf690af46d4459bb
38.311728
733
0.613096
5.217943
false
false
false
false
StanZabroda/Hydra
Pods/HanekeSwift/Haneke/NSFileManager+Haneke.swift
5
2333
// // NSFileManager+Haneke.swift // Haneke // // Created by Hermes Pique on 8/26/14. // Copyright (c) 2014 Haneke. All rights reserved. // import Foundation extension NSFileManager { func enumerateContentsOfDirectoryAtPath(path : String, orderedByProperty property : String, ascending : Bool, usingBlock block : (NSURL, Int, inout Bool) -> Void ) { let directoryURL = NSURL(fileURLWithPath: path) // if directoryURL == nil { return } do { let contents = try self.contentsOfDirectoryAtURL(directoryURL, includingPropertiesForKeys: [property], options: NSDirectoryEnumerationOptions()) let sortedContents = contents.sort({(URL1 : NSURL, URL2 : NSURL) -> Bool in // Maybe there's a better way to do this. See: http://stackoverflow.com/questions/25502914/comparing-anyobject-in-swift var value1 : AnyObject? do { try URL1.getResourceValue(&value1, forKey: property) } catch _ { return true } var value2 : AnyObject? do { try URL2.getResourceValue(&value2, forKey: property) } catch _ { return false } if let string1 = value1 as? String, let string2 = value2 as? String { return ascending ? string1 < string2 : string2 < string1 } if let date1 = value1 as? NSDate, let date2 = value2 as? NSDate { return ascending ? date1 < date2 : date2 < date1 } if let number1 = value1 as? NSNumber, let number2 = value2 as? NSNumber { return ascending ? number1 < number2 : number2 < number1 } return false }) for (i, v) in sortedContents.enumerate() { var stop : Bool = false block(v, i, &stop) if stop { break } } } catch { Log.error("Failed to list directory", error) } } } func < (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } func < (lhs: NSNumber, rhs: NSNumber) -> Bool { return lhs.compare(rhs) == NSComparisonResult.OrderedAscending }
mit
70c4c7e70c1d369f01d45487c0174840
33.308824
169
0.558508
4.722672
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/TabBadgeItem.swift
1
5421
// // TabBadgeItem.swift // TelegramMac // // Created by keepcoder on 05/01/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import SwiftSignalKit import TelegramCore private final class AvatarTabContainer : View { private let avatar = AvatarControl(font: .avatar(12)) private var selected: Bool = false private let circle: View = View() required init(frame frameRect: NSRect) { super.init(frame: frameRect) avatar.setFrameSize(frameRect.size) avatar.userInteractionEnabled = false circle.setFrameSize(frameRect.size) circle.layer?.cornerRadius = frameRect.height / 2 circle.layer?.borderWidth = 1.33 circle.layer?.borderColor = theme.colors.accentIcon.cgColor addSubview(circle) addSubview(avatar) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setPeer(account: Account, peer: Peer?) { avatar.setPeer(account: account, peer: peer) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) circle.layer?.borderColor = theme.colors.accentIcon.cgColor } override func layout() { super.layout() avatar.center() } func setSelected(_ selected: Bool, animated: Bool) { self.selected = selected circle.change(opacity: selected ? 1 : 0, animated: animated, duration: 0.4, timingFunction: .spring) avatar.setFrameSize(frame.size) if animated { let from: CGFloat = selected ? 1 : 24 / frame.height let to: CGFloat = selected ? 24 / frame.height : 1 avatar.layer?.animateScaleSpring(from: from, to: to, duration: 0.3, removeOnCompletion: false, bounce: false, completion: { completed in }) if selected { circle.layer?.animateScaleSpring(from: 0.5, to: 1.0, duration: 0.3, bounce: false) } else { circle.layer?.animateScaleSpring(from: 1.0, to: 0.5, duration: 0.3, removeOnCompletion: false, bounce: false) } } else { if selected { avatar.setFrameSize(NSMakeSize(24, 24)) } else { avatar.setFrameSize(frame.size) } } needsLayout = true } } class TabBadgeItem: TabItem { private let context:AccountContext init(_ context: AccountContext, controller:ViewController, image: CGImage, selectedImage: CGImage, longHoverHandler:((Control)->Void)? = nil) { self.context = context super.init(image: image, selectedImage: selectedImage, controller: controller, subNode:GlobalBadgeNode(context.account, sharedContext: context.sharedContext, dockTile: true, view: View(), removeWhenSidebar: true), longHoverHandler: longHoverHandler) } override func withUpdatedImages(_ image: CGImage, _ selectedImage: CGImage) -> TabItem { return TabBadgeItem(context, controller: self.controller, image: image, selectedImage: selectedImage, longHoverHandler: self.longHoverHandler) } } class TabAllBadgeItem: TabItem { private let context:AccountContext private let disposable = MetaDisposable() private var peer: Peer? init(_ context: AccountContext, image: CGImage, selectedImage: CGImage, controller:ViewController, subNode:Node? = nil, longHoverHandler:((Control)->Void)? = nil) { self.context = context super.init(image: image, selectedImage: selectedImage, controller: controller, subNode:GlobalBadgeNode(context.account, sharedContext: context.sharedContext, collectAllAccounts: true, view: View(), applyFilter: false), longHoverHandler: longHoverHandler) } deinit { disposable.dispose() } override func withUpdatedImages(_ image: CGImage, _ selectedImage: CGImage) -> TabItem { return TabAllBadgeItem(context, image: image, selectedImage: selectedImage, controller: self.controller, subNode: self.subNode, longHoverHandler: self.longHoverHandler) } override func makeView() -> NSView { let context = self.context let semaphore = DispatchSemaphore(value: 0) var isMultiple = true _ = (context.sharedContext.activeAccounts |> take(1)).start(next: { accounts in isMultiple = accounts.accounts.count > 1 semaphore.signal() }) semaphore.wait() if !isMultiple { return super.makeView() } let view = AvatarTabContainer(frame: NSMakeRect(0, 0, 30, 30)) /* |> distinctUntilChanged(isEqual: { lhs, rhs -> Bool in return lhs?.smallProfileImage != rhs?.smallProfileImage }) */ disposable.set((context.account.postbox.peerView(id: context.account.peerId) |> map { $0.peers[$0.peerId] } |> deliverOnMainQueue).start(next: { [weak view] peer in view?.setPeer(account: context.account, peer: peer) })) return view } override func setSelected(_ selected: Bool, for view: NSView, animated: Bool) { (view as? AvatarTabContainer)?.setSelected(selected, animated: animated) super.setSelected(selected, for: view, animated: animated) } }
gpl-2.0
268c4e45c603861cabed890191a9fe92
37.169014
262
0.647601
4.640411
false
false
false
false
L-Zephyr/Drafter
Sources/Drafter/Generator/DotGenerator.swift
1
5842
// // Generator.swift // Mapper // // Created by LZephyr on 2017/9/26. // Copyright © 2017年 LZephyr. All rights reserved. // import Foundation /// 遍历AST并生成dot class DotGenerator { // MARK: - Public /// 在当前位置生成类图 /// /// - Parameters: /// - clsNodes: 类型节点数据 /// - protocols: 协议节点数据 /// - filePath: 路径,作为结果图片命名的前缀 @discardableResult static func generate(classes clsNodes: [ClassNode], protocols: [ProtocolNode], filePath: String) -> String { let dot = DotGenerator() var nodesSet = Set<String>() dot.begin(name: "Inheritance") // class node for cls in clsNodes { // 类节点 if !nodesSet.contains(cls.className) { nodesSet.insert(cls.className) dot.append(cls, label: "\(cls.className)") } for proto in cls.protocols { if !nodesSet.contains(proto) { nodesSet.insert(proto) dot.append(proto, label: "<<protocol>>\n\(proto)") } dot.point(from: cls, to: proto, emptyArrow: true, dashed: true) } // 父类 if let superCls = cls.superCls { if !nodesSet.contains(superCls) { nodesSet.insert(superCls) dot.append(superCls, label: superCls) } dot.point(from: cls, to: superCls, emptyArrow: true) } } // 剩余的Protocol for proto in protocols { if !nodesSet.contains(proto.name) { nodesSet.insert(proto.name) dot.append(proto, label: "<<protocol>>\n\(proto.name)") } } dot.end() return dot.create(file: filePath) } /// 在当前位置生成调用关系图 /// /// - Parameters: /// - methods: 方法节点 /// - filePath: 源代码文件的路径 @discardableResult static func generate(_ methods: [MethodNode], filePath: String) -> String { // 生成Dot描述 let dot = DotGenerator() dot.begin(name: "CallGraph") var nodesSet = Set<Int>() var relationSet = Set<String>() // 避免重复连线 for method in methods { // 添加节点定义 if !nodesSet.contains(method.hashValue) { dot.append(method, label: method.description) nodesSet.insert(method.hashValue) } for invoke in method.invokes { if !nodesSet.contains(invoke.hashValue) { // 优先显示详细的信息 if let index = methods.index(where: { $0.hashValue == invoke.hashValue }) { dot.append(methods[index], label: methods[index].description) nodesSet.insert(methods[index].hashValue) } else { dot.append(invoke, label: invoke.description) nodesSet.insert(invoke.hashValue) } } let relation = "\(method.hashValue)\(invoke.hashValue)" if !relationSet.contains(relation) && method.hashValue != invoke.hashValue { dot.point(from: method, to: invoke) relationSet.insert(relation) } } } dot.end() return dot.create(file: filePath) } // MARK: - Private fileprivate var dot: String = "" fileprivate func create(file filePath: String) -> String { // 写入文件 let filename = URL(fileURLWithPath: filePath).lastPathComponent let dotFile = "./\(filename).dot" let target = "./\(filename).png" // 创建Dot文件 if FileManager.default.fileExists(atPath: dotFile) { try? FileManager.default.removeItem(at: URL(fileURLWithPath: dotFile)) } _ = FileManager.default.createFile(atPath: dotFile, contents: dot.data(using: .utf8), attributes: nil) // 生成png Executor.execute("dot", "-T", "png", dotFile, "-o", "\(target)", help: "Make sure Graphviz is successfully installed.") // 删除.dot文件 try? FileManager.default.removeItem(at: URL(fileURLWithPath: dotFile)) return target } } // MARK: - Dot Generate Method fileprivate extension DotGenerator { func begin(name: String) { dot.append(contentsOf: "digraph \(name) { node [shape=\"record\"];") } func end() { dot.append(contentsOf: "}") } func append<T: Hashable>(_ node: T, label: String) { var escaped = label escaped = escaped.replacingOccurrences(of: "<", with: "\\<") escaped = escaped.replacingOccurrences(of: ">", with: "\\>") escaped = escaped.replacingOccurrences(of: "->", with: "\\-\\>") dot.append(contentsOf: "\(node.hashValue) [label=\"\(escaped)\"];") } func point<T: Hashable, A: Hashable>(from: T, to: A, emptyArrow: Bool = false, dashed: Bool = false) { var style = "" if emptyArrow { style.append(contentsOf: "arrowhead = \"empty\" ") } if dashed { style.append(contentsOf: "style=\"dashed\"") } if !style.isEmpty { dot.append(contentsOf: "\(from.hashValue)->\(to.hashValue)[\(style)];") } else { dot.append(contentsOf: "\(from.hashValue)->\(to.hashValue);") } } }
mit
e97c630eb3c8f35e182e2aa140cc961b
30.914773
127
0.509703
4.415881
false
false
false
false
jmcalister1/iOS-Calculator
ClassCalculator/ClassCalculator/CalculatorCPU.swift
1
3049
// // CalculatorCPU.swift // ClassCalculator // // Created by Joshua McAlister on 1/24/17. // Copyright © 2017 Harding University. All rights reserved. // import Foundation func divide(op1:Double, op2:Double) -> Double { return op1 / op2 } func multiply(op1:Double, op2:Double) -> Double { return op1 * op2 } func subtract(op1:Double, op2:Double) -> Double { return op1 - op2 } func add(op1:Double, op2:Double) -> Double { return op1 + op2 } class CalculatorCPU { private var accumulator:Double = 0.0 var description:String = " " struct PendingBinaryOperation { var binaryFunction: (Double,Double) -> Double var firstOperand: Double } private var pending: PendingBinaryOperation? var isPartialResult: Bool { get { return pending != nil } } func setOperand(operand:Double) { accumulator = operand } func performOperation(symbol:String) { switch symbol { case "C": accumulator = 0.0 description = " " pending = nil case "±": accumulator *= -1.0 case "%": accumulator /= 100.0 case "÷": description += " ÷ " performEquals() pending = PendingBinaryOperation(binaryFunction:divide, firstOperand: accumulator) case "×": description += " × " performEquals() pending = PendingBinaryOperation(binaryFunction:multiply, firstOperand: accumulator) case "-": description += " - " performEquals() pending = PendingBinaryOperation(binaryFunction:subtract, firstOperand: accumulator) case "+": description += " + " performEquals() pending = PendingBinaryOperation(binaryFunction:add, firstOperand: accumulator) case "=": performEquals() case "sin": description = "sin(" + description + ")" performEquals() accumulator = sin(accumulator) case "cos": description = "cos(" + description + ")" performEquals() accumulator = cos(accumulator) case "tan": description = "tan(" + description + ")" performEquals() accumulator = tan(accumulator) case "√": description = "√(" + description + ")" performEquals() accumulator = sqrt(accumulator) case "x²": description = "(" + description + ")²" performEquals() accumulator = pow(accumulator, 2) case "π": accumulator = M_PI default: break } } private func performEquals() { if pending != nil { accumulator = pending!.binaryFunction(pending!.firstOperand, accumulator) pending = nil } } var result:Double { get { return accumulator } } }
mit
15e38787fcb6fa73fae59a12844a06d3
25.4
96
0.540843
4.736349
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/IdentityStore/IdentityStore_Shapes.swift
1
15609
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import Foundation import SotoCore extension IdentityStore { // MARK: Enums // MARK: Shapes public struct DescribeGroupRequest: AWSEncodableShape { /// The identifier for a group in the identity store. public let groupId: String /// The globally unique identifier for the identity store, such as d-1234567890. In this example, d- is a fixed prefix, and 1234567890 is a randomly generated string which contains number and lower case letters. This value is generated at the time that a new identity store is created. public let identityStoreId: String public init(groupId: String, identityStoreId: String) { self.groupId = groupId self.identityStoreId = identityStoreId } public func validate(name: String) throws { try self.validate(self.groupId, name: "groupId", parent: name, max: 47) try self.validate(self.groupId, name: "groupId", parent: name, min: 1) try self.validate(self.groupId, name: "groupId", parent: name, pattern: "^([0-9a-f]{10}-|)[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$") try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, max: 12) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, min: 1) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, pattern: "^d-[0-9a-f]{10}$") } private enum CodingKeys: String, CodingKey { case groupId = "GroupId" case identityStoreId = "IdentityStoreId" } } public struct DescribeGroupResponse: AWSDecodableShape { /// Contains the group’s display name value. The length limit is 1024 characters. This value can consist of letters, accented characters, symbols, numbers, punctuation, tab, new line, carriage return, space and non breaking space in this attribute. The characters “&lt;&gt;;:%” are excluded. This value is specified at the time the group is created and stored as an attribute of the group object in the identity store. public let displayName: String /// The identifier for a group in the identity store. public let groupId: String public init(displayName: String, groupId: String) { self.displayName = displayName self.groupId = groupId } private enum CodingKeys: String, CodingKey { case displayName = "DisplayName" case groupId = "GroupId" } } public struct DescribeUserRequest: AWSEncodableShape { /// The globally unique identifier for the identity store, such as d-1234567890. In this example, d- is a fixed prefix, and 1234567890 is a randomly generated string which contains number and lower case letters. This value is generated at the time that a new identity store is created. public let identityStoreId: String /// The identifier for a user in the identity store. public let userId: String public init(identityStoreId: String, userId: String) { self.identityStoreId = identityStoreId self.userId = userId } public func validate(name: String) throws { try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, max: 12) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, min: 1) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, pattern: "^d-[0-9a-f]{10}$") try self.validate(self.userId, name: "userId", parent: name, max: 47) try self.validate(self.userId, name: "userId", parent: name, min: 1) try self.validate(self.userId, name: "userId", parent: name, pattern: "^([0-9a-f]{10}-|)[A-Fa-f0-9]{8}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{4}-[A-Fa-f0-9]{12}$") } private enum CodingKeys: String, CodingKey { case identityStoreId = "IdentityStoreId" case userId = "UserId" } } public struct DescribeUserResponse: AWSDecodableShape { /// The identifier for a user in the identity store. public let userId: String /// Contains the user’s username value. The length limit is 128 characters. This value can consist of letters, accented characters, symbols, numbers and punctuation. The characters “&lt;&gt;;:%” are excluded. This value is specified at the time the user is created and stored as an attribute of the user object in the identity store. public let userName: String public init(userId: String, userName: String) { self.userId = userId self.userName = userName } private enum CodingKeys: String, CodingKey { case userId = "UserId" case userName = "UserName" } } public struct Filter: AWSEncodableShape { /// The attribute path used to specify which attribute name to search. Length limit is 255 characters. For example, UserName is a valid attribute path for the ListUsers API, and DisplayName is a valid attribute path for the ListGroups API. public let attributePath: String /// Represents the data for an attribute. Each attribute value is described as a name-value pair. public let attributeValue: String public init(attributePath: String, attributeValue: String) { self.attributePath = attributePath self.attributeValue = attributeValue } public func validate(name: String) throws { try self.validate(self.attributePath, name: "attributePath", parent: name, max: 255) try self.validate(self.attributePath, name: "attributePath", parent: name, min: 1) try self.validate(self.attributePath, name: "attributePath", parent: name, pattern: "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}  ]+") try self.validate(self.attributeValue, name: "attributeValue", parent: name, max: 1024) try self.validate(self.attributeValue, name: "attributeValue", parent: name, min: 1) try self.validate(self.attributeValue, name: "attributeValue", parent: name, pattern: "[\\p{L}\\p{M}\\p{S}\\p{N}\\p{P}\\t\\n\\r  ]+") } private enum CodingKeys: String, CodingKey { case attributePath = "AttributePath" case attributeValue = "AttributeValue" } } public struct Group: AWSDecodableShape { /// Contains the group’s display name value. The length limit is 1024 characters. This value can consist of letters, accented characters, symbols, numbers, punctuation, tab, new line, carriage return, space and non breaking space in this attribute. The characters “&lt;&gt;;:%” are excluded. This value is specified at the time the group is created and stored as an attribute of the group object in the identity store. public let displayName: String /// The identifier for a group in the identity store. public let groupId: String public init(displayName: String, groupId: String) { self.displayName = displayName self.groupId = groupId } private enum CodingKeys: String, CodingKey { case displayName = "DisplayName" case groupId = "GroupId" } } public struct ListGroupsRequest: AWSEncodableShape { /// A list of Filter objects, which is used in the ListUsers and ListGroups request. public let filters: [Filter]? /// The globally unique identifier for the identity store, such as d-1234567890. In this example, d- is a fixed prefix, and 1234567890 is a randomly generated string which contains number and lower case letters. This value is generated at the time that a new identity store is created. public let identityStoreId: String /// The maximum number of results to be returned per request, which is used in the ListUsers and ListGroups request to specify how many results to return in one page. The length limit is 50 characters. public let maxResults: Int? /// The pagination token used for the ListUsers and ListGroups APIs. This value is generated by the identity store service and is returned in the API response if the total results are more than the size of one page, and when this token is used in the API request to search for the next page. public let nextToken: String? public init(filters: [Filter]? = nil, identityStoreId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.identityStoreId = identityStoreId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, max: 12) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, min: 1) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, pattern: "^d-[0-9a-f]{10}$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 65535) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[-a-zA-Z0-9+=/:]*") } private enum CodingKeys: String, CodingKey { case filters = "Filters" case identityStoreId = "IdentityStoreId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListGroupsResponse: AWSDecodableShape { /// A list of Group objects in the identity store. public let groups: [Group] /// The pagination token used for the ListUsers and ListGroups APIs. This value is generated by the identity store service and is returned in the API response if the total results are more than the size of one page, and when this token is used in the API request to search for the next page. public let nextToken: String? public init(groups: [Group], nextToken: String? = nil) { self.groups = groups self.nextToken = nextToken } private enum CodingKeys: String, CodingKey { case groups = "Groups" case nextToken = "NextToken" } } public struct ListUsersRequest: AWSEncodableShape { /// A list of Filter objects, which is used in the ListUsers and ListGroups request. public let filters: [Filter]? /// The globally unique identifier for the identity store, such as d-1234567890. In this example, d- is a fixed prefix, and 1234567890 is a randomly generated string which contains number and lower case letters. This value is generated at the time that a new identity store is created. public let identityStoreId: String /// The maximum number of results to be returned per request, which is used in the ListUsers and ListGroups request to specify how many results to return in one page. The length limit is 50 characters. public let maxResults: Int? /// The pagination token used for the ListUsers and ListGroups APIs. This value is generated by the identity store service and is returned in the API response if the total results are more than the size of one page, and when this token is used in the API request to search for the next page. public let nextToken: String? public init(filters: [Filter]? = nil, identityStoreId: String, maxResults: Int? = nil, nextToken: String? = nil) { self.filters = filters self.identityStoreId = identityStoreId self.maxResults = maxResults self.nextToken = nextToken } public func validate(name: String) throws { try self.filters?.forEach { try $0.validate(name: "\(name).filters[]") } try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, max: 12) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, min: 1) try self.validate(self.identityStoreId, name: "identityStoreId", parent: name, pattern: "^d-[0-9a-f]{10}$") try self.validate(self.maxResults, name: "maxResults", parent: name, max: 50) try self.validate(self.maxResults, name: "maxResults", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, max: 65535) try self.validate(self.nextToken, name: "nextToken", parent: name, min: 1) try self.validate(self.nextToken, name: "nextToken", parent: name, pattern: "^[-a-zA-Z0-9+=/:]*") } private enum CodingKeys: String, CodingKey { case filters = "Filters" case identityStoreId = "IdentityStoreId" case maxResults = "MaxResults" case nextToken = "NextToken" } } public struct ListUsersResponse: AWSDecodableShape { /// The pagination token used for the ListUsers and ListGroups APIs. This value is generated by the identity store service and is returned in the API response if the total results are more than the size of one page, and when this token is used in the API request to search for the next page. public let nextToken: String? /// A list of User objects in the identity store. public let users: [User] public init(nextToken: String? = nil, users: [User]) { self.nextToken = nextToken self.users = users } private enum CodingKeys: String, CodingKey { case nextToken = "NextToken" case users = "Users" } } public struct User: AWSDecodableShape { /// The identifier for a user in the identity store. public let userId: String /// Contains the user’s username value. The length limit is 128 characters. This value can consist of letters, accented characters, symbols, numbers and punctuation. The characters “&lt;&gt;;:%” are excluded. This value is specified at the time the user is created and stored as an attribute of the user object in the identity store. public let userName: String public init(userId: String, userName: String) { self.userId = userId self.userName = userName } private enum CodingKeys: String, CodingKey { case userId = "UserId" case userName = "UserName" } } }
apache-2.0
ad8f3928245c82ae685bb310816f2a79
54.258865
426
0.6518
4.532577
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/ViewModels/Listable.swift
1
1377
// // Listable.swift // Inbbbox // // Created by Radoslaw Szeja on 14/12/15. // Copyright © 2015 Netguru Sp. z o.o. All rights reserved. // import Foundation protocol Listable { associatedtype ListType var count: Int { get } init(_ items: [ListType]) subscript(index: Int) -> ListType { get } mutating func add(_ item: ListType, atIndex index: Int) mutating func remove(_ index: Int) -> ListType func itemize(_ closure: (_ index: Int, _ item: ListType) -> ()) } // MARK: List class List<T> : Listable { var count: Int { return items.count } var items: [T] required init(_ items: [T]) { self.items = items } subscript(index: Int) -> T { return items[index] } func add(_ item: T, atIndex index: Int) { items.insert(item, at: index) } func remove(_ index: Int) -> T { return items.remove(at: index) } func itemize(_ closure: (_ index: Int, _ item: T) -> ()) { for (index, item) in items.enumerated() { closure(index, item) } } } // MARK: Section class Section<T: Equatable> : List<T>, Equatable { var title: String? required init(_ items: [T]) { super.init(items) } } func ==<T: Equatable>(lhs: Section<T>, rhs: Section<T>) -> Bool { return lhs.title == rhs.title && lhs.items == rhs.items }
gpl-3.0
c4df6191ebd0b81f8cb909488d4f6378
18.111111
67
0.571221
3.422886
false
false
false
false
sammyd/VT_InAppPurchase
prototyping/GreenGrocer/GreenGrocer/AdContainerViewController.swift
4
2942
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import StoreKit class AdContainerViewController: UIViewController, DataStoreOwner, IAPContainer { @IBOutlet weak var adView: UIView! @IBOutlet weak var containerView: UIView! var dataStore: DataStore? { didSet { passDataStoreToChildren() } } var iapHelper: IAPHelper? { didSet { updateIAPHelper() } } private var adRemovalProduct: SKProduct? override func viewDidLoad() { super.viewDidLoad() passDataStoreToChildren() passIAPHelperToChildren() NSNotificationCenter.defaultCenter().addObserver(self, selector: "handlePurchaseNotification:", name: IAPHelper.IAPHelperPurchaseNotification, object: nil) } } extension AdContainerViewController { @IBAction func handleRemoveAdsPressed(sender: AnyObject) { if let adRemovalProduct = adRemovalProduct { iapHelper?.buyProduct(adRemovalProduct) } } func handlePurchaseNotification(notification: NSNotification) { if let productID = notification.object as? String where productID == GreenGrocerPurchase.AdRemoval.productId { setAdsAsRemoved(true) } } private func setAdsAsRemoved(removed: Bool, animated: Bool = true) { dispatch_async(dispatch_get_main_queue()) { if animated { UIView.animateWithDuration(0.7) { self.adView.hidden = removed } } else { self.adView.hidden = removed } } } private func updateIAPHelper() { passIAPHelperToChildren() guard let iapHelper = iapHelper else { return } adRemovalProduct = iapHelper.availableProducts.filter { $0.productIdentifier == GreenGrocerPurchase.AdRemoval.productId }.first setAdsAsRemoved(iapHelper.purchasedProductIdentifiers.contains(GreenGrocerPurchase.AdRemoval.productId), animated: false) } }
mit
71210726e5d6408a891d6d1d5735dcfd
31.688889
159
0.730795
4.533128
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/Onboarding2/OnboardingPageViewController+Pages.swift
1
19981
// // OnboardingPageViewController+Pages.swift // Slide for Reddit // // Created by Jonathan Cole on 9/15/20. // Copyright © 2020 Haptic Apps. All rights reserved. // import Anchorage import AVKit import reddift import Then import UIKit /** ViewController for a single page in the OnboardingPageViewController. Describes a splash screen with animated background. */ class OnboardingSplashPageViewController: UIViewController { let text: String let subText: String let image: UIImage var textView = UILabel() var subTextView = UILabel() var imageView = UIImageView() var baseView = UIView() var shouldMove = true var gradientSet = false let bubbles = UIScreen.main.bounds.height / 30 var lanes = [Int](repeating: 0, count: Int(UIScreen.main.bounds.height / 30)) init(text: String, subText: String, image: UIImage) { self.text = text self.subText = subText self.image = image super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.setupConstriants() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.setupMovingViews() self.view.clipsToBounds = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) UIView.animate(withDuration: 1) { self.baseView.alpha = 0 } completion: { (_) in self.stopMoving() } } func stopMoving() { shouldMove = false } func setupMovingViews() { gradientSet = false baseView.removeFromSuperview() baseView = UIView() view.addSubview(baseView) baseView.centerAnchors == self.view.centerAnchors baseView.widthAnchor == CGFloat(bubbles) * 30 baseView.heightAnchor == CGFloat(bubbles) * 30 for i in 0..<Int(bubbles) { if i % 2 == 0 { self.lanes[i] = 2 continue } let movingView = PreviewSubredditView(frame: CGRect.zero) baseView.addSubview(movingView) movingView.setFrame(getInitialFrame(for: movingView, in: i)) movingView.alpha = 0 movingView.tag = i self.lanes[i] += 1 DispatchQueue.main.asyncAfter(deadline: .now() + Double(Int.random(in: 0...6))) { movingView.alpha = 1 self.moveView(view: movingView, chosenLane: i) } } let radians = -30 / 180.0 * CGFloat.pi baseView.transform = CGAffineTransform(rotationAngle: radians) baseView.alpha = 0.4 view.bringSubviewToFront(imageView) view.bringSubviewToFront(textView) view.bringSubviewToFront(subTextView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !gradientSet { gradientSet = true let gradientMaskLayer = CAGradientLayer() gradientMaskLayer.frame = self.view.bounds gradientMaskLayer.shadowRadius = 50 gradientMaskLayer.shadowPath = CGPath(roundedRect: self.view.bounds.insetBy(dx: 0, dy: 0), cornerWidth: 0, cornerHeight: 0, transform: nil) gradientMaskLayer.shadowOpacity = 1 gradientMaskLayer.shadowOffset = CGSize.zero gradientMaskLayer.shadowColor = ColorUtil.theme.foregroundColor.cgColor view.layer.mask = gradientMaskLayer } } func getInitialFrame(for view: PreviewSubredditView, in lane: Int) -> CGRect { print("Lane is \(CGRect(x: CGFloat(bubbles * 30), y: CGFloat(lane) * 30, width: 200, height: 30))") return CGRect(x: CGFloat(bubbles * 30), y: CGFloat(lane) * 30, width: 200, height: 30) } func getFinalFrame(for view: PreviewSubredditView, in lane: Int) -> CGRect { return CGRect(x: -1 * 200, y: CGFloat(lane) * 30, width: view.frame.size.width, height: 30) } func moveView(view: PreviewSubredditView, chosenLane: Int) { let time = Int.random(in: 5...10) UIView.animate(withDuration: Double(time), delay: 0, options: .curveLinear, animations: { () -> Void in view.frame = self.getFinalFrame(for: view, in: chosenLane) }, completion: { [weak self] (Bool) -> Void in guard let self = self else { return } if self.shouldMove { view.randomizeColors() self.lanes[chosenLane] -= 1 var emptyIndexes = [Int]() for i in 0..<self.lanes.count { if self.lanes[i] < 1 { emptyIndexes.append(i) } } let newLane = emptyIndexes.randomItem ?? 0 self.lanes[newLane] += 1 view.setFrame(self.getInitialFrame(for: view, in: newLane)) self.moveView(view: view, chosenLane: newLane) } else { view.removeFromSuperview() } }) } func setupViews() { let newTitle = NSMutableAttributedString(string: text.split("\n").first ?? "", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)]) newTitle.append(NSAttributedString(string: "\n")) newTitle.append(NSMutableAttributedString(string: text.split("\n").last ?? "", attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 30)])) self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 30) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.numberOfLines = 0 $0.attributedText = newTitle } self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText } self.imageView = UIImageView(image: image).then { $0.contentMode = .scaleAspectFill $0.layer.cornerRadius = 25 $0.clipsToBounds = true } self.view.addSubviews(imageView, textView, subTextView) } func setupConstriants() { textView.horizontalAnchors == self.view.horizontalAnchors + 32 textView.bottomAnchor == self.imageView.topAnchor - 40 imageView.centerAnchors == self.view.centerAnchors imageView.widthAnchor == 100 imageView.heightAnchor == 100 subTextView.horizontalAnchors == self.view.horizontalAnchors + 32 subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.image = UIImage() super.init(coder: coder) } } class PreviewSubredditView: UIView { var bubble = UIView() var label = UIView() var toSetFrame = CGRect.zero var frameSet = false override func layoutSubviews() { super.layoutSubviews() if !frameSet { frameSet = true self.frame = toSetFrame } } override init(frame: CGRect) { super.init(frame: frame) setupViews() setupConstraints() randomizeColors() self.translatesAutoresizingMaskIntoConstraints = false } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func randomizeColors() { let seed = Int.random(in: 0...100) if seed < 30 { self.bubble.backgroundColor = ColorUtil.theme.fontColor self.label.backgroundColor = ColorUtil.theme.fontColor self.label.alpha = 0.6 } else if seed < 50 { self.bubble.backgroundColor = GMColor.green500Color() self.label.backgroundColor = GMColor.green500Color() self.label.alpha = 0.6 } else if seed < 60 { self.bubble.backgroundColor = GMColor.red500Color() self.label.backgroundColor = GMColor.red500Color() self.label.alpha = 0.6 } else if seed < 70 { self.bubble.backgroundColor = GMColor.orange500Color() self.label.backgroundColor = GMColor.orange500Color() self.label.alpha = 0.6 } else if seed < 80 { self.bubble.backgroundColor = GMColor.yellow500Color() self.label.backgroundColor = GMColor.yellow500Color() self.label.alpha = 0.6 } else if seed < 90 { self.bubble.backgroundColor = GMColor.purple500Color() self.label.backgroundColor = GMColor.purple500Color() self.label.alpha = 0.6 } else { self.bubble.backgroundColor = GMColor.blue500Color() self.label.backgroundColor = GMColor.blue500Color() self.label.alpha = 0.6 } } func setFrame(_ frame: CGRect) { self.frame = frame self.toSetFrame = frame } func setupViews() { bubble = UIView().then { $0.clipsToBounds = true } } func setupConstraints() { self.addSubviews(bubble, label) let size = Int.random(in: 5...10) let scale = CGFloat(5) / CGFloat(size) bubble.widthAnchor == 30 * scale bubble.heightAnchor == 30 * scale bubble.layer.cornerRadius = 15 * scale label.widthAnchor == CGFloat(Int.random(in: 40...150)) * scale label.heightAnchor == 25 * scale label.layer.cornerRadius = 5 * scale label.clipsToBounds = true label.leftAnchor == bubble.rightAnchor + 8 * scale label.centerYAnchor == bubble.centerYAnchor } } /** ViewController for a single page in the OnboardingPageViewController. Describes a single feature with text and an image. */ class OnboardingFeaturePageViewController: UIViewController { let text: String let subText: String let image: UIImage var textView = UILabel() var subTextView = UILabel() var imageView = UIImageView() init(text: String, subText: String, image: UIImage) { self.text = text self.subText = subText self.image = image super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() self.setupViews() self.setupConstriants() } func setupViews() { self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 20) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = text } self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText } self.imageView = UIImageView(image: image).then { $0.contentMode = .scaleAspectFill $0.layer.cornerRadius = 25 $0.clipsToBounds = true } self.view.addSubviews(imageView, textView, subTextView) } func setupConstriants() { textView.horizontalAnchors == self.view.horizontalAnchors + 16 textView.topAnchor == self.view.safeTopAnchor + 8 imageView.centerAnchors == self.view.centerAnchors imageView.widthAnchor == 100 imageView.heightAnchor == 100 subTextView.horizontalAnchors == self.view.horizontalAnchors + 16 subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.image = UIImage() super.init(coder: coder) } } /** ViewController for a single page in the OnboardingPageViewController. Describes the app's latest changelog. */ class OnboardingChangelogPageViewController: UIViewController { let link: Link init(link: Link) { self.link = link super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.link = Link(id: "") super.init(coder: coder) } } /** ViewController for a single page in the OnboardingPageViewController. Describes the app's latest changelog as Strings. */ class OnboardingHardcodedChangelogPageViewController: UIViewController { let paragraphs: [String: String] let order: [String] let subButton = UILabel() let body = UIScrollView() let content = UILabel() var sizeSet = false init(order: [String], paragraphs: [String: String]) { self.paragraphs = paragraphs self.order = order super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.paragraphs = [:] self.order = [] super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !sizeSet { sizeSet = true self.content.preferredMaxLayoutWidth = self.body.frame.size.width - 16 self.content.sizeToFit() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func setupViews() { let attributedChangelog = NSMutableAttributedString() for paragraph in order { attributedChangelog.append(NSAttributedString(string: paragraph, attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 20)])) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: paragraphs[paragraph]!, attributes: [NSAttributedString.Key.foregroundColor: ColorUtil.theme.fontColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])) attributedChangelog.append(NSAttributedString(string: "\n")) attributedChangelog.append(NSAttributedString(string: "\n")) } content.numberOfLines = 0 content.attributedText = attributedChangelog body.addSubview(content) self.view.addSubviews(body, subButton) subButton.backgroundColor = GMColor.orange500Color() subButton.textColor = .white subButton.layer.cornerRadius = 20 subButton.clipsToBounds = true subButton.textAlignment = .center subButton.font = UIFont.boldSystemFont(ofSize: 20) subButton.text = "Awesome!" } func setupConstraints() { body.horizontalAnchors == self.view.horizontalAnchors + 32 body.bottomAnchor == self.subButton.topAnchor - 4 body.topAnchor == self.view.topAnchor + 4 content.edgeAnchors == body.edgeAnchors self.subButton.bottomAnchor == self.view.bottomAnchor - 8 self.subButton.horizontalAnchors == self.view.horizontalAnchors + 8 self.subButton.alpha = 0 //Hide for now self.subButton.heightAnchor == 0 } } /** ViewController for a single page in the OnboardingPageViewController. Shows a video with a given resource name. */ class OnboardingVideoPageViewController: UIViewController { let text: String let subText: String let video: String var textView = UILabel() var subTextView = UILabel() var videoPlayer = AVPlayer() let videoContainer = UIView() let aspectRatio: Float var layer: AVPlayerLayer? var frameSet = false init(text: String, subText: String, video: String, aspectRatio: Float) { self.text = text self.subText = subText self.video = video self.aspectRatio = aspectRatio super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { self.text = "" self.subText = "" self.video = "" self.aspectRatio = 1 super.init(coder: coder) } override func viewDidLoad() { super.viewDidLoad() setupViews() setupConstraints() startVideos() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } func setupViews() { self.textView = UILabel().then { $0.font = UIFont.boldSystemFont(ofSize: 20) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = text $0.numberOfLines = 0 } self.view.addSubview(textView) self.view.addSubview(videoContainer) self.subTextView = UILabel().then { $0.font = UIFont.systemFont(ofSize: 15) $0.textColor = ColorUtil.theme.fontColor $0.textAlignment = .center $0.text = subText $0.numberOfLines = 0 } self.view.addSubview(subTextView) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if !frameSet { frameSet = true layer?.frame = videoContainer.bounds } } func setupConstraints() { textView.horizontalAnchors == self.view.horizontalAnchors + 16 textView.topAnchor == self.view.safeTopAnchor + 8 videoContainer.topAnchor == textView.bottomAnchor + 32 videoContainer.bottomAnchor == self.subTextView.topAnchor - 32 videoContainer.widthAnchor == self.videoContainer.heightAnchor * aspectRatio videoContainer.centerXAnchor == self.view.centerXAnchor subTextView.bottomAnchor == self.view.safeBottomAnchor - 8 subTextView.horizontalAnchors == self.view.horizontalAnchors + 16 } func startVideos() { let bundle = Bundle.main if let videoPath = bundle.path(forResource: video, ofType: "mp4") { videoPlayer = AVPlayer(url: URL(fileURLWithPath: videoPath)) layer = AVPlayerLayer(player: videoPlayer) layer!.needsDisplayOnBoundsChange = true layer!.videoGravity = .resizeAspect layer!.cornerRadius = 20 layer!.masksToBounds = true videoContainer.layer.addSublayer(layer!) videoContainer.clipsToBounds = true videoContainer.layer.masksToBounds = true videoContainer.layer.cornerRadius = 20 videoPlayer.play() videoPlayer.actionAtItemEnd = .none NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: videoPlayer.currentItem) } } deinit { NotificationCenter.default.removeObserver(self) } @objc func playerItemDidReachEnd(notification: Notification) { if let playerItem = notification.object as? AVPlayerItem { playerItem.seek(to: CMTime.zero, completionHandler: nil) } } }
apache-2.0
4c5d25dcbf368e3a42c6187ba444d8ed
31.700491
232
0.602302
4.871982
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Control/ModelFetchSpecification.swift
1
3155
// // ModelFetchSpecification.swift // ZeeQL // // Created by Helge Hess on 06/03/17. // Copyright © 2017 ZeeZide GmbH. All rights reserved. // public struct ModelFetchSpecification : FetchSpecification { // TODO: This is a little funky now because we refer to Entity. It should be // a protocol. public var entity : Entity? public var _entityName : String? public var entityName : String? { if let e = entity { return e.name } if let n = _entityName { return n } return nil } public var fetchAttributeNames : [ String ]? public var qualifier : Qualifier? public var sortOrderings : [ SortOrdering ]? public var fetchLimit : Int? public var fetchOffset : Int? public var hints = [ String : Any ]() public var usesDistinct = false public var locksObjects = false public var deep = false public var fetchesRawRows = false public var fetchesReadOnly = false public var requiresAllQualifierBindingVariables = false public var prefetchingRelationshipKeyPathes : [ String ]? public init(entityName : String? = nil, qualifier : Qualifier? = nil, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil) { self._entityName = entityName self.qualifier = qualifier self.sortOrderings = sortOrderings self.fetchLimit = limit } public init(entity : Entity, qualifier : Qualifier? = nil, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil) { self.entity = entity self.qualifier = qualifier self.sortOrderings = sortOrderings self.fetchLimit = limit } public init(entity : Entity, _ q : String, sortOrderings : [ SortOrdering ]? = nil, limit : Int? = nil, prefetch : [ String ]? = nil) { self.entity = entity self.qualifier = qualifierWith(format: q) self.sortOrderings = sortOrderings self.fetchLimit = limit self.prefetchingRelationshipKeyPathes = prefetch } public init(fetchSpecification fs: FetchSpecification) { entity = fs.entity fetchAttributeNames = fs.fetchAttributeNames qualifier = fs.qualifier sortOrderings = fs.sortOrderings fetchLimit = fs.fetchLimit fetchOffset = fs.fetchOffset usesDistinct = fs.usesDistinct locksObjects = fs.locksObjects deep = fs.deep fetchesRawRows = fs.fetchesRawRows fetchesReadOnly = fs.fetchesReadOnly hints = fs.hints requiresAllQualifierBindingVariables = fs.requiresAllQualifierBindingVariables prefetchingRelationshipKeyPathes = fs.prefetchingRelationshipKeyPathes if let mfs = fs as? ModelFetchSpecification { _entityName = mfs._entityName } } }
apache-2.0
3c3fa12e5508e5497f1e6b2bf253080f
33.282609
78
0.58402
4.645066
false
false
false
false
slavapestov/swift
stdlib/public/core/Bool.swift
2
2906
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Bool Datatype and Supporting Operators //===----------------------------------------------------------------------===// /// A value type whose instances are either `true` or `false`. public struct Bool { internal var _value: Builtin.Int1 /// Default-initialize Boolean value to `false`. @_transparent public init() { let zero: Int8 = 0 self._value = Builtin.trunc_Int8_Int1(zero._value) } @_transparent internal init(_ v: Builtin.Int1) { self._value = v } } extension Bool : _BuiltinBooleanLiteralConvertible, BooleanLiteralConvertible { @_transparent public init(_builtinBooleanLiteral value: Builtin.Int1) { self._value = value } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self = value } } extension Bool : BooleanType { @_transparent @warn_unused_result public func _getBuiltinLogicValue() -> Builtin.Int1 { return _value } /// Identical to `self`. @_transparent public var boolValue: Bool { return self } /// Construct an instance representing the same logical value as /// `value`. public init<T : BooleanType>(_ value: T) { self = value.boolValue } } extension Bool : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self ? "true" : "false" } } // This is a magic entry point known to the compiler. @_transparent public // COMPILER_INTRINSIC func _getBool(v: Builtin.Int1) -> Bool { return Bool(v) } @_transparent extension Bool : Equatable, Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`. /// /// - Note: the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. public var hashValue: Int { return self ? 1 : 0 } } //===----------------------------------------------------------------------===// // Operators //===----------------------------------------------------------------------===// // Unary logical complement. @_transparent @warn_unused_result public prefix func !(a: Bool) -> Bool { return Bool(Builtin.xor_Int1(a._value, true._value)) } @_transparent @warn_unused_result public func ==(lhs: Bool, rhs: Bool) -> Bool { return Bool(Builtin.cmp_eq_Int1(lhs._value, rhs._value)) }
apache-2.0
7b0c5108c58427674a89cc27dc82852f
27.490196
80
0.589814
4.463902
false
false
false
false
grayunicorn/Quiz
Quiz/Core Data/QuizAnswer+CoreDataProperties.swift
1
1168
// // QuizAnswer+CoreDataProperties.swift // Quiz // // Created by Adam Eberbach on 11/9/17. // Copyright © 2017 Adam Eberbach. All rights reserved. // // import Foundation import CoreData extension QuizAnswer { @nonobjc public class func fetchRequest() -> NSFetchRequest<QuizAnswer> { return NSFetchRequest<QuizAnswer>(entityName: "QuizAnswer") } @NSManaged public var isCorrect: Bool @NSManaged public var text: String? @NSManaged public var question: QuizQuestion? } // MARK:- convenience functions extension QuizAnswer { // create and return a new QuizAnswer with its text and true or false status class func createWithText(text: String, isCorrect: String?, inContext: NSManagedObjectContext) -> QuizAnswer { let answer = NSEntityDescription.insertNewObject(forEntityName: kManagedObjectIdentifier, into: inContext) as! QuizAnswer answer.text = text // isCorrect string must be both non-optional and equal to T or t to make this a true answer if let isCorrect = isCorrect, isCorrect == "T" { answer.isCorrect = true } else { answer.isCorrect = false } return answer } }
bsd-3-clause
d8f67ebfc0da346d62b0627c682644ce
26.785714
125
0.712082
4.471264
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Models/CountryStatsRecordValue+CoreDataClass.swift
2
2525
import Foundation import CoreData public class CountryStatsRecordValue: StatsRecordValue { } extension StatsTopCountryTimeIntervalData: TimeIntervalStatsRecordValueConvertible { var recordPeriodType: StatsRecordPeriodType { return StatsRecordPeriodType(remoteStatus: period) } var date: Date { return periodEndDate } func statsRecordValues(in context: NSManagedObjectContext) -> [StatsRecordValue] { var mappedCountries: [StatsRecordValue] = countries.map { let value = CountryStatsRecordValue(context: context) value.countryCode = $0.code value.countryName = $0.name value.viewsCount = Int64($0.viewsCount) return value } let otherAndTotalCount = OtherAndTotalViewsCountStatsRecordValue(context: context, otherCount: otherViewsCount, totalCount: totalViewsCount) mappedCountries.append(otherAndTotalCount) return mappedCountries } init?(statsRecordValues: [StatsRecordValue]) { guard let firstParent = statsRecordValues.first?.statsRecord, let period = StatsRecordPeriodType(rawValue: firstParent.period), let date = firstParent.date, let otherAndTotalCount = statsRecordValues.compactMap({ $0 as? OtherAndTotalViewsCountStatsRecordValue }).first else { return nil } let countries: [StatsCountry] = statsRecordValues .compactMap { $0 as? CountryStatsRecordValue } .compactMap { guard let code = $0.countryCode, let name = $0.countryName else { return nil } return StatsCountry(name: name, code: code, viewsCount: Int($0.viewsCount)) } self = StatsTopCountryTimeIntervalData(period: period.statsPeriodUnitValue, periodEndDate: date as Date, countries: countries, totalViewsCount: Int(otherAndTotalCount.totalCount), otherViewsCount: Int(otherAndTotalCount.otherCount)) } static var recordType: StatsRecordType { return .countryViews } }
gpl-2.0
79df41552d0417b9e742575a33de6ed3
33.589041
123
0.565545
6.203931
false
false
false
false
dehesa/Metal
shaders/Sources/Common/Renderer.swift
1
5662
import Foundation import MetalKit import simd final class Renderer: NSObject, MTKViewDelegate { private let _metal: (view: MTKView, device: MTLDevice, queue: MTLCommandQueue) private let _pikachu: (mesh: MTKMesh, descriptor: MTLVertexDescriptor, texture: MTLTexture) private var _textures: (color: MTLTexture, depth: MTLTexture) private var _state: (main: MTLRenderPipelineState, post: MTLRenderPipelineState, depthStencil: MTLDepthStencilState) /// Designated initializer for the Pikachu renderer. /// - param device: Metal device where the mesh buffers, texture, and render pipelines will be created. /// - param view: MetalKit view being driven by this renderer. init(device: MTLDevice, view: MTKView) { self._metal = (view, device, device.makeCommandQueue()!) self._pikachu = Loader.loadPikachu(to: device) self._textures = Loader.makeOffScreenTargets(for: device, size: view.convertToBacking(view.drawableSize)) let library = Loader.loadLibrary(to: device) let renderState = Loader.makeRenderStates(for: device, library: library, meshDescriptor: _pikachu.descriptor, view: view) let depthState = device.makeDepthStencilState(descriptor: MTLDepthStencilDescriptor().set { $0.depthCompareFunction = .less $0.isDepthWriteEnabled = true })! self._state = (renderState.main, renderState.post, depthState) super.init() } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { let previousSize = CGSize(width: self._textures.color.width, height: self._textures.color.height) if previousSize != size { self._textures = Loader.makeOffScreenTargets(for: self._metal.device, size: size) } } func draw(in view: MTKView) { guard let commandBuffer = self._metal.queue.makeCommandBuffer() else { return } self._mainPass(commandBuffer: commandBuffer, aspectRatio: Float(view.drawableSize.width / view.drawableSize.height)) self._postPass(commandBuffer: commandBuffer, view: view) guard let drawable = view.currentDrawable else { return } commandBuffer.present(drawable) commandBuffer.commit() } } private extension Renderer { /// Uniform structure for the main render pass. struct _Uniforms { let modelViewMatrix: float4x4 let projectionMatrix: float4x4 } /// Main passing, which clears the screen to a "whitish" color and draw the pikachu with a bit of zoom out and in the center. /// The outcome of this pass is a texture with the size of the window with the pikachu right in the center. /// - parameter commandBuffer: Metal Command Buffer hosting all render passes. /// - parameter aspectRatio: Aspect ratio for the post render pass. func _mainPass(commandBuffer: MTLCommandBuffer, aspectRatio: Float) { let mainPassDescriptor = MTLRenderPassDescriptor().set { $0.colorAttachments[0].setUp { (attachment) in attachment.texture = self._textures.color attachment.clearColor = MTLClearColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1) attachment.loadAction = .clear attachment.storeAction = .store } $0.depthAttachment.setUp { (attachment) in attachment.texture = self._textures.depth attachment.clearDepth = 1.0 attachment.loadAction = .clear attachment.storeAction = .dontCare } } guard let mainEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: mainPassDescriptor) else { return } mainEncoder.setUp { $0.setRenderPipelineState(self._state.main) $0.setDepthStencilState(self._state.depthStencil) $0.setFragmentTexture(_pikachu.texture, index: 0) for (index, vertexBuffer) in self._pikachu.mesh.vertexBuffers.enumerated() { $0.setVertexBuffer(vertexBuffer.buffer, offset: vertexBuffer.offset, index: index) } let modelTransform = float4x4(translationBy: SIMD3<Float>(0, -1.1, 0)) * float4x4(scaleBy: Float(1 / 4.5)) let cameraTransform = float4x4(translationBy: SIMD3<Float>(0, 0, -4)) let projectionMatrix = float4x4(perspectiveProjectionFov: .pi / 6, aspectRatio: aspectRatio, nearZ: 0.1, farZ: 100) var uniforms = _Uniforms(modelViewMatrix: cameraTransform * modelTransform, projectionMatrix: projectionMatrix) $0.setVertexBytes(&uniforms, length: MemoryLayout.size(ofValue: uniforms), index: 1) let submesh = self._pikachu.mesh.submeshes[0] let indexBuffer = submesh.indexBuffer $0.drawIndexedPrimitives(type: submesh.primitiveType, indexCount: submesh.indexCount, indexType: submesh.indexType, indexBuffer: indexBuffer.buffer, indexBufferOffset: indexBuffer.offset) } mainEncoder.endEncoding() } /// Post-processing render pass where the fragment shaders will take place. /// - parameter commandBuffer: Metal Command Buffer hosting all render passes. /// - parameter view: MetalKit view hosting the final framebuffer. func _postPass(commandBuffer: MTLCommandBuffer, view: MTKView) { guard let postPassDescriptor = view.currentRenderPassDescriptor, let postEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: postPassDescriptor) else { return } postEncoder.setUp { $0.setRenderPipelineState(self._state.post) $0.setFragmentTexture(self._textures.color, index: 0) let vertexData: [Float] = [-1, -1, 0, 1, -1, 1, 0, 0, 1, -1, 1, 1, 1, 1, 1, 0] $0.setVertexBytes(vertexData, length: 16*4, index: 0) $0.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4) } postEncoder.endEncoding() } }
mit
5f95efe7041a0d4d28e186f8a9affb9e
47.393162
193
0.709113
4.322137
false
false
false
false
WalletOne/P2P
P2PCoreTests/CoreNetworkManagerTests.swift
1
1835
// // P2PCoreTestsNetworkManager.swift // P2P_iOS // // Created by Vitaliy Kuzmenko on 03/08/2017. // Copyright © 2017 Wallet One. All rights reserved. // import XCTest class CoreNetworkManagerTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. P2PCore.setPlatform(id: "testplatform", signatureKey: "TestPlatformSignatureKey") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testApiSignatureBuilding() { let url = URLComposer.default.beneficiariesPaymentTools("alinakuzmenko") let timeStamp = "2017-08-14T12:09:11" let bodyAsString = "" let signature = P2PCore.default.networkManager.makeSignature(url: url, timeStamp: timeStamp, requestBody: bodyAsString) XCTAssertEqual(signature, "I5ioVRCeta6BALmnjGZY+tve6PNmmQSPLnDkpJzP8Zc=") } func testWebViewSignature() { let timestamp = "2017-08-03T13:08:15" let items: [(key: String, value: String)] = [ ("PhoneNumber", "79287654321"), ("PlatformBeneficiaryId", "alinakuzmenko"), ("PlatformId", "testplatform"), ("RedirectToPaymentToolAddition", "true"), ("ReturnUrl", "http://p2p-success-link-new-paymentTool"), ("Timestamp", timestamp), ("Title", "Alina Kuzmenko"), ] let signature = P2PCore.default.networkManager.makeSignatureForWeb(parameters: items) XCTAssertEqual(signature, "Mltf/M8LieoFmi8urPz3qZQfIl36xGZ0P7bCQavGxnU=") } }
mit
7c146a493933ccf8a7ec5b653799dddc
31.75
127
0.62759
3.969697
false
true
false
false
shvets/TVSetKit
Sources/ios/VideoPlayerController.swift
1
6121
import AVFoundation import UIKit import AVKit open class VideoPlayerController: AVPlayerViewController, ReusableController { public static let SegueIdentifier = "Video Player" //class VideoPlayerController: UIViewController, AVPlayerViewControllerDelegate { //let playerViewController: AVPlayerViewController? = AVPlayerViewController() var localizer = Localizer("com.rubikon.TVSetKit", bundleClass: TVSetKit.self) var params = [String: Any]() var navigator: MediaItemsNavigator? var mode: String? var playVideo: Bool = false var items: [Item] = [] var mediaItem: Item? var receiver: UIViewController? var getMediaUrl: ((MediaItem) throws -> URL?)! var getRequestHeaders: ((MediaItem) -> [String : String])! override open func viewDidLoad() { super.viewDidLoad() navigator = MediaItemsNavigator(items) #if os(tvOS) let doubleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapPressed(_:))) doubleTapRecognizer.numberOfTapsRequired = 2 self.view.addGestureRecognizer(doubleTapRecognizer) #endif _ = [UISwipeGestureRecognizer.Direction.right, .left, .up, .down].map({ direction in let recognizer = UISwipeGestureRecognizer(target: self, action: #selector(self.swiped(_:))) recognizer.direction = direction self.view.addGestureRecognizer(recognizer) }) if playVideo { play() } } override open func viewWillDisappear(_ animated: Bool) { if let mediaItem = mediaItem { notifyMediaItemChange(mediaItem) } } func notifyMediaItemChange(_ mediaItem: Item) { let nc = NotificationCenter.default nc.post(name: NSNotification.Name( rawValue: "mediaItem"), object: nil, userInfo: [ "id" : mediaItem.id as Any, "receiver": receiver as Any ]) } @objc func doubleTapPressed(_ gesture: UITapGestureRecognizer) { if preparePreviousMediaItem() { play() } } @objc func swiped(_ gesture: UISwipeGestureRecognizer) { #if os(iOS) switch gesture.direction { case UISwipeGestureRecognizer.Direction.up: if prepareNextMediaItem() { play() } case UISwipeGestureRecognizer.Direction.down: if preparePreviousMediaItem() { play() } default: break } #endif #if os(tvOS) switch gesture.direction { case UISwipeGestureRecognizer.Direction.up: if prepareNextMediaItem() { play() } default: break } #endif } func preparePreviousMediaItem() -> Bool { if let currentId = mediaItem?.id { let previousId = navigator?.getPreviousId(currentId) if previousId != currentId { let previousItem = navigator?.items?.filter { item in item.id == previousId }.first mediaItem = previousItem } return previousId != currentId } else { return false } } func prepareNextMediaItem() -> Bool { if let currentId = mediaItem?.id { let nextId = navigator?.getNextId(currentId) if nextId != currentId { let nextItem = navigator?.items?.filter { item in item.id == nextId }.first mediaItem = nextItem } return nextId != currentId } else { return false } } func play() { var mediaUrl: URL? do { mediaUrl = try getMediaUrl(mediaItem as! MediaItem) } catch let e { print("Error: \(e)") } if let url = mediaUrl, let name = mediaItem?.name { let description: String if let mediaItem = mediaItem as? MediaItem { description = mediaItem.description ?? name } else { description = name } // let headers = getRequestHeaders(mediaItem as! MediaItem) // // print(headers) let asset = AVURLAsset(url: url) //, options: ["AVURLAssetHTTPHeaderFieldsKey": headers]) let playerItem = AVPlayerItem(asset: asset) #if os(tvOS) playerItem.externalMetadata = externalMetaData(title: name, description: description) #endif // playerViewController?.delegate = self player = AVPlayer(playerItem: playerItem) // playerViewController?.player = player let overlayView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 200)) overlayView.addSubview(UIImageView(image: UIImage(named: "tv-watermark"))) self.contentOverlayView?.addSubview(overlayView) //playerViewController?.contentOverlayView?.addSubview(overlayView) player?.play() //self.present(playerViewController!, animated: false) { // /* // Begin playing the media as soon as the controller has // been presented. // */ // player.play() // } } else { let title = localizer.localize("Cannot Find Source") let message = localizer.localize("Cannot Find Source") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let closeAction = UIAlertAction(title: "Close", style: .default) { _ in // redirect to previous page } alertController.addAction(closeAction) present(alertController, animated: false, completion: nil) } } // MARK: Meta data private func externalMetaData(title: String, description: String) -> [AVMetadataItem] { let titleItem = AVMutableMetadataItem() titleItem.identifier = AVMetadataIdentifier.commonIdentifierTitle titleItem.value = title as NSString titleItem.extendedLanguageTag = "und" let descriptionItem = AVMutableMetadataItem() descriptionItem.identifier = AVMetadataIdentifier.commonIdentifierDescription descriptionItem.value = description as NSString descriptionItem.extendedLanguageTag = "und" return [titleItem, descriptionItem] } }
mit
1ac7dec51cdebdd0ef28a161b9cbd7f4
25.729258
114
0.633066
5.025452
false
false
false
false
LawrenceHan/iOS-project-playground
iOSRACSwift/Pods/ReactiveCocoa/ReactiveCocoa/Swift/Signal.swift
25
54346
import Result /// A push-driven stream that sends Events over time, parameterized by the type /// of values being sent (`Value`) and the type of failure that can occur (`Error`). /// If no failures should be possible, NoError can be specified for `Error`. /// /// An observer of a Signal will see the exact same sequence of events as all /// other observers. In other words, events will be sent to all observers at the /// same time. /// /// Signals are generally used to represent event streams that are already “in /// progress,” like notifications, user input, etc. To represent streams that /// must first be _started_, see the SignalProducer type. /// /// Signals do not need to be retained. A Signal will be automatically kept /// alive until the event stream has terminated. public final class Signal<Value, Error: ErrorType> { public typealias Observer = ReactiveCocoa.Observer<Value, Error> private let atomicObservers: Atomic<Bag<Observer>?> = Atomic(Bag()) /// Initializes a Signal that will immediately invoke the given generator, /// then forward events sent to the given observer. /// /// The disposable returned from the closure will be automatically disposed /// if a terminating event is sent to the observer. The Signal itself will /// remain alive until the observer is released. public init(@noescape _ generator: Observer -> Disposable?) { /// Used to ensure that events are serialized during delivery to observers. let sendLock = NSLock() sendLock.name = "org.reactivecocoa.ReactiveCocoa.Signal" let generatorDisposable = SerialDisposable() /// When set to `true`, the Signal should interrupt as soon as possible. let interrupted = Atomic(false) let observer = Observer { event in if case .Interrupted = event { // Normally we disallow recursive events, but // Interrupted is kind of a special snowflake, since it // can inadvertently be sent by downstream consumers. // // So we'll flag Interrupted events specially, and if it // happened to occur while we're sending something else, // we'll wait to deliver it. interrupted.value = true if sendLock.tryLock() { self.interrupt() sendLock.unlock() generatorDisposable.dispose() } } else { if let observers = (event.isTerminating ? self.atomicObservers.swap(nil) : self.atomicObservers.value) { sendLock.lock() for observer in observers { observer.action(event) } let shouldInterrupt = !event.isTerminating && interrupted.value if shouldInterrupt { self.interrupt() } sendLock.unlock() if event.isTerminating || shouldInterrupt { // Dispose only after notifying observers, so disposal logic // is consistently the last thing to run. generatorDisposable.dispose() } } } } generatorDisposable.innerDisposable = generator(observer) } /// A Signal that never sends any events to its observers. public static var never: Signal { return self.init { _ in nil } } /// Creates a Signal that will be controlled by sending events to the given /// observer. /// /// The Signal will remain alive until a terminating event is sent to the /// observer. public static func pipe() -> (Signal, Observer) { var observer: Observer! let signal = self.init { innerObserver in observer = innerObserver return nil } return (signal, observer) } /// Interrupts all observers and terminates the stream. private func interrupt() { if let observers = self.atomicObservers.swap(nil) { for observer in observers { observer.sendInterrupted() } } } /// Observes the Signal by sending any future events to the given observer. If /// the Signal has already terminated, the observer will immediately receive an /// `Interrupted` event. /// /// Returns a Disposable which can be used to disconnect the observer. Disposing /// of the Disposable will have no effect on the Signal itself. public func observe(observer: Observer) -> Disposable? { var token: RemovalToken? atomicObservers.modify { observers in guard var observers = observers else { return nil } token = observers.insert(observer) return observers } if let token = token { return ActionDisposable { self.atomicObservers.modify { observers in guard var observers = observers else { return nil } observers.removeValueForToken(token) return observers } } } else { observer.sendInterrupted() return nil } } } public protocol SignalType { /// The type of values being sent on the signal. typealias Value /// The type of error that can occur on the signal. If errors aren't possible /// then `NoError` can be used. typealias Error: ErrorType /// Extracts a signal from the receiver. var signal: Signal<Value, Error> { get } /// Observes the Signal by sending any future events to the given observer. func observe(observer: Signal<Value, Error>.Observer) -> Disposable? } extension Signal: SignalType { public var signal: Signal { return self } } extension SignalType { /// Convenience override for observe(_:) to allow trailing-closure style /// invocations. public func observe(action: Signal<Value, Error>.Observer.Action) -> Disposable? { return observe(Observer(action)) } /// Observes the Signal by invoking the given callback when `next` events are /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callbacks. Disposing of the Disposable will have no effect on the Signal /// itself. public func observeNext(next: Value -> ()) -> Disposable? { return observe(Observer(next: next)) } /// Observes the Signal by invoking the given callback when a `completed` event is /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. public func observeCompleted(completed: () -> ()) -> Disposable? { return observe(Observer(completed: completed)) } /// Observes the Signal by invoking the given callback when a `failed` event is /// received. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. public func observeFailed(error: Error -> ()) -> Disposable? { return observe(Observer(failed: error)) } /// Observes the Signal by invoking the given callback when an `interrupted` event is /// received. If the Signal has already terminated, the callback will be invoked /// immediately. /// /// Returns a Disposable which can be used to stop the invocation of the /// callback. Disposing of the Disposable will have no effect on the Signal /// itself. public func observeInterrupted(interrupted: () -> ()) -> Disposable? { return observe(Observer(interrupted: interrupted)) } /// Maps each value in the signal to a new value. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func map<U>(transform: Value -> U) -> Signal<U, Error> { return Signal { observer in return self.observe { event in observer.action(event.map(transform)) } } } /// Maps errors in the signal to a new error. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func mapError<F>(transform: Error -> F) -> Signal<Value, F> { return Signal { observer in return self.observe { event in observer.action(event.mapError(transform)) } } } /// Catches any failure that may occur on the input signal, mapping to a new producer /// that starts in its place. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> { return Signal { observer in let serialDisposable = SerialDisposable() serialDisposable.innerDisposable = self.observe { event in switch event { case let .Next(value): observer.sendNext(value) case let .Failed(error): handler(error).startWithSignal { signal, signalDisposable in serialDisposable.innerDisposable = signalDisposable signal.observe(observer) } case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } return serialDisposable } } /// Preserves only the values of the signal that pass the given predicate. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func filter(predicate: Value -> Bool) -> Signal<Value, Error> { return Signal { observer in return self.observe { (event: Event<Value, Error>) -> () in if case let .Next(value) = event { if predicate(value) { observer.sendNext(value) } } else { observer.action(event) } } } } } /// Describes how multiple producers should be joined together. public enum FlattenStrategy: Equatable { /// The producers should be merged, so that any value received on any of the /// input producers will be forwarded immediately to the output producer. /// /// The resulting producer will complete only when all inputs have completed. case Merge /// The producers should be concatenated, so that their values are sent in the /// order of the producers themselves. /// /// The resulting producer will complete only when all inputs have completed. case Concat /// Only the events from the latest input producer should be considered for /// the output. Any producers received before that point will be disposed of. /// /// The resulting producer will complete only when the producer-of-producers and /// the latest producer has completed. case Latest } extension SignalType where Value: SignalType, Error == Value.Error { /// Flattens the inner signals sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner signal emits an error, the returned /// signal will forward that error immediately. /// /// `Interrupted` events on inner signals will be treated like `Completed` /// events on inner signals. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { return self.map(SignalProducer.init).flatten(strategy) } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Flattens the inner producers sent upon `signal` (into a single signal of /// values), according to the semantics of the given strategy. /// /// If `signal` or an active inner producer fails, the returned signal will /// forward that failure immediately. /// /// `Interrupted` events on inner producers will be treated like `Completed` /// events on inner producers. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> { switch strategy { case .Merge: return self.merge() case .Concat: return self.concat() case .Latest: return self.switchToLatest() } } } extension SignalType { /// Maps each event from `signal` to a new producer, then flattens the /// resulting producers (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created producers fail, the returned signal /// will forward that failure immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } /// Maps each event from `signal` to a new signal, then flattens the /// resulting signals (into a signal of values), according to the /// semantics of the given strategy. /// /// If `signal` or any of the created signals emit an error, the returned /// signal will forward that error immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> { return map(transform).flatten(strategy) } } extension SignalType { /// Merges the given signals into a single `Signal` that will emit all values /// from each of them, and complete when all of them have completed. public static func merge<S: SequenceType where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<Value, Error> { let producer = SignalProducer<Signal<Value, Error>, Error>(values: signals) var result: Signal<Value, Error>! producer.startWithSignal { (signal, _) in result = signal.flatten(.Merge) } return result } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Returns a signal which sends all the values from producer signal emitted from /// `signal`, waiting until each inner producer completes before beginning to /// send the values from the next inner producer. /// /// If any of the inner producers fail, the returned signal will forward /// that failure immediately /// /// The returned signal completes only when `signal` and all producers /// emitted from `signal` complete. @warn_unused_result(message="Did you forget to call `observe` on the signal?") private func concat() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer in let disposable = CompositeDisposable() let state = ConcatState(observer: observer, disposable: disposable) disposable += self.observe { event in switch event { case let .Next(value): state.enqueueSignalProducer(value.producer) case let .Failed(error): observer.sendFailed(error) case .Completed: // Add one last producer to the queue, whose sole job is to // "turn out the lights" by completing `observer`. state.enqueueSignalProducer(SignalProducer.empty.on(completed: { observer.sendCompleted() })) case .Interrupted: observer.sendInterrupted() } } return disposable } } } private final class ConcatState<Value, Error: ErrorType> { /// The observer of a started `concat` producer. let observer: Signal<Value, Error>.Observer /// The top level disposable of a started `concat` producer. let disposable: CompositeDisposable /// The active producer, if any, and the producers waiting to be started. let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([]) init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable) { self.observer = observer self.disposable = disposable } func enqueueSignalProducer(producer: SignalProducer<Value, Error>) { if disposable.disposed { return } var shouldStart = true queuedSignalProducers.modify { (var queue) in // An empty queue means the concat is idle, ready & waiting to start // the next producer. shouldStart = queue.isEmpty queue.append(producer) return queue } if shouldStart { startNextSignalProducer(producer) } } func dequeueSignalProducer() -> SignalProducer<Value, Error>? { if disposable.disposed { return nil } var nextSignalProducer: SignalProducer<Value, Error>? queuedSignalProducers.modify { (var queue) in // Active producers remain in the queue until completed. Since // dequeueing happens at completion of the active producer, the // first producer in the queue can be removed. if !queue.isEmpty { queue.removeAtIndex(0) } nextSignalProducer = queue.first return queue } return nextSignalProducer } /// Subscribes to the given signal producer. func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) { signalProducer.startWithSignal { signal, disposable in let handle = self.disposable.addDisposable(disposable) signal.observe { event in switch event { case .Completed, .Interrupted: handle.remove() if let nextSignalProducer = self.dequeueSignalProducer() { self.startNextSignalProducer(nextSignalProducer) } default: self.observer.action(event) } } } } } extension SignalType where Value: SignalProducerType, Error == Value.Error { /// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer /// added earlier. Returns a Signal that will forward events from the inner producers as they arrive. @warn_unused_result(message="Did you forget to call `start` on the producer?") private func merge() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { relayObserver in let inFlight = Atomic(1) let decrementInFlight: () -> () = { let orig = inFlight.modify { $0 - 1 } if orig == 1 { relayObserver.sendCompleted() } } let disposable = CompositeDisposable() self.observe { event in switch event { case let .Next(producer): producer.startWithSignal { innerSignal, innerDisposable in inFlight.modify { $0 + 1 } let handle = disposable.addDisposable(innerDisposable) innerSignal.observe { event in switch event { case .Completed, .Interrupted: if event.isTerminating { handle.remove() } decrementInFlight() default: relayObserver.action(event) } } } case let .Failed(error): relayObserver.sendFailed(error) case .Completed: decrementInFlight() case .Interrupted: relayObserver.sendInterrupted() } } return disposable } } /// Returns a signal that forwards values from the latest signal sent on /// `signal`, ignoring values sent on previous inner signal. /// /// An error sent on `signal` or the latest inner signal will be sent on the /// returned signal. /// /// The returned signal completes when `signal` and the latest inner /// signal have both completed. @warn_unused_result(message="Did you forget to call `observe` on the signal?") private func switchToLatest() -> Signal<Value.Value, Error> { return Signal<Value.Value, Error> { observer in let disposable = CompositeDisposable() let latestInnerDisposable = SerialDisposable() disposable.addDisposable(latestInnerDisposable) let state = Atomic(LatestState<Value, Error>()) self.observe { event in switch event { case let .Next(innerProducer): innerProducer.startWithSignal { innerSignal, innerDisposable in state.modify { (var state) in // When we replace the disposable below, this prevents the // generated Interrupted event from doing any work. state.replacingInnerSignal = true return state } latestInnerDisposable.innerDisposable = innerDisposable state.modify { (var state) in state.replacingInnerSignal = false state.innerSignalComplete = false return state } innerSignal.observe { event in switch event { case .Interrupted: // If interruption occurred as a result of a new producer // arriving, we don't want to notify our observer. let original = state.modify { (var state) in if !state.replacingInnerSignal { state.innerSignalComplete = true } return state } if !original.replacingInnerSignal && original.outerSignalComplete { observer.sendCompleted() } case .Completed: let original = state.modify { (var state) in state.innerSignalComplete = true return state } if original.outerSignalComplete { observer.sendCompleted() } default: observer.action(event) } } } case let .Failed(error): observer.sendFailed(error) case .Completed: let original = state.modify { (var state) in state.outerSignalComplete = true return state } if original.innerSignalComplete { observer.sendCompleted() } case .Interrupted: observer.sendInterrupted() } } return disposable } } } private struct LatestState<Value, Error: ErrorType> { var outerSignalComplete: Bool = false var innerSignalComplete: Bool = true var replacingInnerSignal: Bool = false } extension SignalType where Value: OptionalType { /// Unwraps non-`nil` values and forwards them on the returned signal, `nil` /// values are dropped. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func ignoreNil() -> Signal<Value.Wrapped, Error> { return filter { $0.optional != nil }.map { $0.optional! } } } extension SignalType { /// Returns a signal that will yield the first `count` values from `self` @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func take(count: Int) -> Signal<Value, Error> { precondition(count >= 0) return Signal { observer in if count == 0 { observer.sendCompleted() return nil } var taken = 0 return self.observe { event in if case let .Next(value) = event { if taken < count { taken++ observer.sendNext(value) } if taken == count { observer.sendCompleted() } } else { observer.action(event) } } } } } /// A reference type which wraps an array to avoid copying it for performance and /// memory usage optimization. private final class CollectState<Value> { var values: [Value] = [] func append(value: Value) -> Self { values.append(value) return self } } extension SignalType { /// Returns a signal that will yield an array of values when `self` completes. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func collect() -> Signal<[Value], Error> { return self .reduce(CollectState()) { $0.append($1) } .map { $0.values } } /// Forwards all events onto the given scheduler, instead of whichever /// scheduler they originally arrived upon. public func observeOn(scheduler: SchedulerType) -> Signal<Value, Error> { return Signal { observer in return self.observe { event in scheduler.schedule { observer.action(event) } } } } } private final class CombineLatestState<Value> { var latestValue: Value? var completed = false } extension SignalType { private func observeWithStates<U>(signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ onBothNext: () -> (), _ onFailed: Error -> (), _ onBothCompleted: () -> (), _ onInterrupted: () -> ()) -> Disposable? { return self.observe { event in switch event { case let .Next(value): lock.lock() signalState.latestValue = value if otherState.latestValue != nil { onBothNext() } lock.unlock() case let .Failed(error): onFailed(error) case .Completed: lock.lock() signalState.completed = true if otherState.completed { onBothCompleted() } lock.unlock() case .Interrupted: onInterrupted() } } } /// Combines the latest value of the receiver with the latest value from /// the given signal. /// /// The returned signal will not send a value until both inputs have sent /// at least one value each. If either signal is interrupted, the returned signal /// will also be interrupted. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> { return Signal { observer in let lock = NSLock() lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith" let signalState = CombineLatestState<Value>() let otherState = CombineLatestState<U>() let onBothNext = { () -> () in observer.sendNext((signalState.latestValue!, otherState.latestValue!)) } let onFailed = observer.sendFailed let onBothCompleted = observer.sendCompleted let onInterrupted = observer.sendInterrupted let disposable = CompositeDisposable() disposable += self.observeWithStates(signalState, otherState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted) disposable += otherSignal.observeWithStates(otherState, signalState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted) return disposable } } /// Delays `Next` and `Completed` events by the given interval, forwarding /// them on the given scheduler. /// /// `Failed` and `Interrupted` events are always scheduled immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> { precondition(interval >= 0) return Signal { observer in return self.observe { event in switch event { case .Failed, .Interrupted: scheduler.schedule { observer.action(event) } default: let date = scheduler.currentDate.dateByAddingTimeInterval(interval) scheduler.scheduleAfter(date) { observer.action(event) } } } } } /// Returns a signal that will skip the first `count` values, then forward /// everything afterward. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func skip(count: Int) -> Signal<Value, Error> { precondition(count >= 0) if count == 0 { return signal } return Signal { observer in var skipped = 0 return self.observe { event in if case .Next = event where skipped < count { skipped++ } else { observer.action(event) } } } } /// Treats all Events from `self` as plain values, allowing them to be manipulated /// just like any other value. /// /// In other words, this brings Events “into the monad.” /// /// When a Completed or Failed event is received, the resulting signal will send /// the Event itself and then complete. When an Interrupted event is received, /// the resulting signal will send the Event itself and then interrupt. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func materialize() -> Signal<Event<Value, Error>, NoError> { return Signal { observer in return self.observe { event in observer.sendNext(event) switch event { case .Interrupted: observer.sendInterrupted() case .Completed, .Failed: observer.sendCompleted() case .Next: break } } } } } extension SignalType where Value: EventType, Error == NoError { /// The inverse of materialize(), this will translate a signal of `Event` /// _values_ into a signal of those events themselves. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func dematerialize() -> Signal<Value.Value, Value.Error> { return Signal<Value.Value, Value.Error> { observer in return self.observe { event in switch event { case let .Next(innerEvent): observer.action(innerEvent.event) case .Failed: fatalError("NoError is impossible to construct") case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } } extension SignalType { /// Injects side effects to be performed upon the specified signal events. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func on(event event: (Event<Value, Error> -> ())? = nil, failed: (Error -> ())? = nil, completed: (() -> ())? = nil, interrupted: (() -> ())? = nil, terminated: (() -> ())? = nil, disposed: (() -> ())? = nil, next: (Value -> ())? = nil) -> Signal<Value, Error> { return Signal { observer in let disposable = CompositeDisposable() _ = disposed.map(disposable.addDisposable) disposable += signal.observe { receivedEvent in event?(receivedEvent) switch receivedEvent { case let .Next(value): next?(value) case let .Failed(error): failed?(error) case .Completed: completed?() case .Interrupted: interrupted?() } if receivedEvent.isTerminating { terminated?() } observer.action(receivedEvent) } return disposable } } } private struct SampleState<Value> { var latestValue: Value? = nil var signalCompleted: Bool = false var samplerCompleted: Bool = false } extension SignalType { /// Forwards the latest value from `signal` whenever `sampler` sends a Next /// event. /// /// If `sampler` fires before a value has been observed on `signal`, nothing /// happens. /// /// Returns a signal that will send values from `signal`, sampled (possibly /// multiple times) by `sampler`, then complete once both input signals have /// completed, or interrupt if either input signal is interrupted. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func sampleOn(sampler: Signal<(), NoError>) -> Signal<Value, Error> { return Signal { observer in let state = Atomic(SampleState<Value>()) let disposable = CompositeDisposable() disposable += self.observe { event in switch event { case let .Next(value): state.modify { (var st) in st.latestValue = value return st } case let .Failed(error): observer.sendFailed(error) case .Completed: let oldState = state.modify { (var st) in st.signalCompleted = true return st } if oldState.samplerCompleted { observer.sendCompleted() } case .Interrupted: observer.sendInterrupted() } } disposable += sampler.observe { event in switch event { case .Next: if let value = state.value.latestValue { observer.sendNext(value) } case .Completed: let oldState = state.modify { (var st) in st.samplerCompleted = true return st } if oldState.signalCompleted { observer.sendCompleted() } case .Interrupted: observer.sendInterrupted() default: break } } return disposable } } /// Forwards events from `self` until `trigger` sends a Next or Completed /// event, at which point the returned signal will complete. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func takeUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> { return Signal { observer in let disposable = CompositeDisposable() disposable += self.observe(observer) disposable += trigger.observe { event in switch event { case .Next, .Completed: observer.sendCompleted() case .Failed, .Interrupted: break } } return disposable } } /// Does not forward any values from `self` until `trigger` sends a Next or /// Completed event, at which point the returned signal behaves exactly like /// `signal`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func skipUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> { return Signal { observer in let disposable = SerialDisposable() disposable.innerDisposable = trigger.observe { event in switch event { case .Next, .Completed: disposable.innerDisposable = self.observe(observer) case .Failed, .Interrupted: break } } return disposable } } /// Forwards events from `self` with history: values of the returned signal /// are a tuple whose first member is the previous value and whose second member /// is the current value. `initial` is supplied as the first member when `self` /// sends its first value. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combinePrevious(initial: Value) -> Signal<(Value, Value), Error> { return scan((initial, initial)) { previousCombinedValues, newValue in return (previousCombinedValues.1, newValue) } } /// Like `scan`, but sends only the final value and then immediately completes. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> { // We need to handle the special case in which `signal` sends no values. // We'll do that by sending `initial` on the output signal (before taking // the last value). let (scannedSignalWithInitialValue, outputSignalObserver) = Signal<U, Error>.pipe() let outputSignal = scannedSignalWithInitialValue.takeLast(1) // Now that we've got takeLast() listening to the piped signal, send that initial value. outputSignalObserver.sendNext(initial) // Pipe the scanned input signal into the output signal. scan(initial, combine).observe(outputSignalObserver) return outputSignal } /// Aggregates `selfs`'s values into a single combined value. When `self` emits /// its first value, `combine` is invoked with `initial` as the first argument and /// that emitted value as the second argument. The result is emitted from the /// signal returned from `scan`. That result is then passed to `combine` as the /// first argument when the next value is emitted, and so on. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> { return Signal { observer in var accumulator = initial return self.observe { event in observer.action(event.map { value in accumulator = combine(accumulator, value) return accumulator }) } } } } extension SignalType where Value: Equatable { /// Forwards only those values from `self` which are not duplicates of the /// immedately preceding value. The first value is always forwarded. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func skipRepeats() -> Signal<Value, Error> { return skipRepeats(==) } } extension SignalType { /// Forwards only those values from `self` which do not pass `isRepeat` with /// respect to the previous value. The first value is always forwarded. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> Signal<Value, Error> { return self .map(Optional.init) .combinePrevious(nil) .filter { a, b in if let a = a, b = b where isRepeat(a, b) { return false } else { return true } } .map { $0.1! } } /// Does not forward any values from `self` until `predicate` returns false, /// at which point the returned signal behaves exactly like `signal`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func skipWhile(predicate: Value -> Bool) -> Signal<Value, Error> { return Signal { observer in var shouldSkip = true return self.observe { event in switch event { case let .Next(value): shouldSkip = shouldSkip && predicate(value) if !shouldSkip { fallthrough } default: observer.action(event) } } } } /// Forwards events from `self` until `replacement` begins sending events. /// /// Returns a signal which passes through `Next`, `Failed`, and `Interrupted` /// events from `signal` until `replacement` sends an event, at which point the /// returned signal will send that event and switch to passing through events /// from `replacement` instead, regardless of whether `self` has sent events /// already. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func takeUntilReplacement(replacement: Signal<Value, Error>) -> Signal<Value, Error> { return Signal { observer in let disposable = CompositeDisposable() let signalDisposable = self.observe { event in switch event { case .Completed: break case .Next, .Failed, .Interrupted: observer.action(event) } } disposable += signalDisposable disposable += replacement.observe { event in signalDisposable?.dispose() observer.action(event) } return disposable } } /// Waits until `self` completes and then forwards the final `count` values /// on the returned signal. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func takeLast(count: Int) -> Signal<Value, Error> { return Signal { observer in var buffer: [Value] = [] buffer.reserveCapacity(count) return self.observe { event in switch event { case let .Next(value): // To avoid exceeding the reserved capacity of the buffer, we remove then add. // Remove elements until we have room to add one more. while (buffer.count + 1) > count { buffer.removeAtIndex(0) } buffer.append(value) case let .Failed(error): observer.sendFailed(error) case .Completed: for bufferedValue in buffer { observer.sendNext(bufferedValue) } observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } /// Forwards any values from `self` until `predicate` returns false, /// at which point the returned signal will complete. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func takeWhile(predicate: Value -> Bool) -> Signal<Value, Error> { return Signal { observer in return self.observe { event in if case let .Next(value) = event where !predicate(value) { observer.sendCompleted() } else { observer.action(event) } } } } } private struct ZipState<Value> { var values: [Value] = [] var completed = false var isFinished: Bool { return values.isEmpty && completed } } extension SignalType { /// Zips elements of two signals into pairs. The elements of any Nth pair /// are the Nth elements of the two input signals. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zipWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> { return Signal { observer in let states = Atomic(ZipState<Value>(), ZipState<U>()) let disposable = CompositeDisposable() let flush = { () -> () in var originalStates: (ZipState<Value>, ZipState<U>)! states.modify { states in originalStates = states var updatedStates = states let extractCount = min(states.0.values.count, states.1.values.count) updatedStates.0.values.removeRange(0 ..< extractCount) updatedStates.1.values.removeRange(0 ..< extractCount) return updatedStates } while !originalStates.0.values.isEmpty && !originalStates.1.values.isEmpty { let left = originalStates.0.values.removeAtIndex(0) let right = originalStates.1.values.removeAtIndex(0) observer.sendNext((left, right)) } if originalStates.0.isFinished || originalStates.1.isFinished { observer.sendCompleted() } } let onFailed = { observer.sendFailed($0) } let onInterrupted = { observer.sendInterrupted() } disposable += self.observe { event in switch event { case let .Next(value): states.modify { (var states) in states.0.values.append(value) return states } flush() case let .Failed(error): onFailed(error) case .Completed: states.modify { (var states) in states.0.completed = true return states } flush() case .Interrupted: onInterrupted() } } disposable += otherSignal.observe { event in switch event { case let .Next(value): states.modify { (var states) in states.1.values.append(value) return states } flush() case let .Failed(error): onFailed(error) case .Completed: states.modify { (var states) in states.1.completed = true return states } flush() case .Interrupted: onInterrupted() } } return disposable } } /// Applies `operation` to values from `self` with `Success`ful results /// forwarded on the returned signal and `Failure`s sent as `Failed` events. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func attempt(operation: Value -> Result<(), Error>) -> Signal<Value, Error> { return attemptMap { value in return operation(value).map { return value } } } /// Applies `operation` to values from `self` with `Success`ful results mapped /// on the returned signal and `Failure`s sent as `Failed` events. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func attemptMap<U>(operation: Value -> Result<U, Error>) -> Signal<U, Error> { return Signal { observer in self.observe { event in switch event { case let .Next(value): operation(value).analysis(ifSuccess: { value in observer.sendNext(value) }, ifFailure: { error in observer.sendFailed(error) }) case let .Failed(error): observer.sendFailed(error) case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } /// Throttle values sent by the receiver, so that at least `interval` /// seconds pass between each, then forwards them on the given scheduler. /// /// If multiple values are received before the interval has elapsed, the /// latest value is the one that will be passed on. /// /// If the input signal terminates while a value is being throttled, that value /// will be discarded and the returned signal will terminate immediately. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> { precondition(interval >= 0) return Signal { observer in let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState()) let schedulerDisposable = SerialDisposable() let disposable = CompositeDisposable() disposable.addDisposable(schedulerDisposable) disposable += self.observe { event in if case let .Next(value) = event { var scheduleDate: NSDate! state.modify { (var state) in state.pendingValue = value let proposedScheduleDate = state.previousDate?.dateByAddingTimeInterval(interval) ?? scheduler.currentDate scheduleDate = proposedScheduleDate.laterDate(scheduler.currentDate) return state } schedulerDisposable.innerDisposable = scheduler.scheduleAfter(scheduleDate) { let previousState = state.modify { (var state) in if state.pendingValue != nil { state.pendingValue = nil state.previousDate = scheduleDate } return state } if let pendingValue = previousState.pendingValue { observer.sendNext(pendingValue) } } } else { schedulerDisposable.innerDisposable = scheduler.schedule { observer.action(event) } } } return disposable } } } private struct ThrottleState<Value> { var previousDate: NSDate? = nil var pendingValue: Value? = nil } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> { return a.combineLatestWith(b) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> { return combineLatest(a, b) .combineLatestWith(c) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> { return combineLatest(a, b, c) .combineLatestWith(d) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> { return combineLatest(a, b, c, d) .combineLatestWith(e) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> { return combineLatest(a, b, c, d, e) .combineLatestWith(f) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> { return combineLatest(a, b, c, d, e, f) .combineLatestWith(g) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> { return combineLatest(a, b, c, d, e, f, g) .combineLatestWith(h) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> { return combineLatest(a, b, c, d, e, f, g, h) .combineLatestWith(i) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> { return combineLatest(a, b, c, d, e, f, g, h, i) .combineLatestWith(j) .map(repack) } /// Combines the values of all the given signals, in the manner described by /// `combineLatestWith`. No events will be sent if the sequence is empty. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> { var generator = signals.generate() if let first = generator.next() { let initial = first.map { [$0] } return GeneratorSequence(generator).reduce(initial) { signal, next in signal.combineLatestWith(next).map { $0.0 + [$0.1] } } } return .never } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> { return a.zipWith(b) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> { return zip(a, b) .zipWith(c) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> { return zip(a, b, c) .zipWith(d) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> { return zip(a, b, c, d) .zipWith(e) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> { return zip(a, b, c, d, e) .zipWith(f) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> { return zip(a, b, c, d, e, f) .zipWith(g) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> { return zip(a, b, c, d, e, f, g) .zipWith(h) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> { return zip(a, b, c, d, e, f, g, h) .zipWith(i) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> { return zip(a, b, c, d, e, f, g, h, i) .zipWith(j) .map(repack) } /// Zips the values of all the given signals, in the manner described by /// `zipWith`. No events will be sent if the sequence is empty. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func zip<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> { var generator = signals.generate() if let first = generator.next() { let initial = first.map { [$0] } return GeneratorSequence(generator).reduce(initial) { signal, next in signal.zipWith(next).map { $0.0 + [$0.1] } } } return .never } extension SignalType { /// Forwards events from `self` until `interval`. Then if signal isn't completed yet, /// fails with `error` on `scheduler`. /// /// If the interval is 0, the timeout will be scheduled immediately. The signal /// must complete synchronously (or on a faster scheduler) to avoid the timeout. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> { precondition(interval >= 0) return Signal { observer in let disposable = CompositeDisposable() let date = scheduler.currentDate.dateByAddingTimeInterval(interval) disposable += scheduler.scheduleAfter(date) { observer.sendFailed(error) } disposable += self.observe(observer) return disposable } } } extension SignalType where Error == NoError { /// Promotes a signal that does not generate failures into one that can. /// /// This does not actually cause failures to be generated for the given signal, /// but makes it easier to combine with other signals that may fail; for /// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc. @warn_unused_result(message="Did you forget to call `observe` on the signal?") public func promoteErrors<F: ErrorType>(_: F.Type) -> Signal<Value, F> { return Signal { observer in return self.observe { event in switch event { case let .Next(value): observer.sendNext(value) case .Failed: fatalError("NoError is impossible to construct") case .Completed: observer.sendCompleted() case .Interrupted: observer.sendInterrupted() } } } } }
mit
2f8666efc91bbf00922e331a1e1ddaf4
31.951486
341
0.680199
3.722987
false
false
false
false
JohnCoates/Aerial
Resources/MainUI/First time setup/RecapViewController.swift
1
1134
// // RecapViewController.swift // Aerial // // Created by Guillaume Louel on 12/08/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Cocoa class RecapViewController: NSViewController { @IBOutlet var imageDial: NSImageView! @IBOutlet var imageFav: NSImageView! @IBOutlet var imageHide: NSImageView! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. imageDial.image = Aerial.helper.getSymbol("dial")?.tinting(with: .secondaryLabelColor) imageFav.image = Aerial.helper.getSymbol("star")?.tinting(with: .secondaryLabelColor) imageHide.image = Aerial.helper.getSymbol("eye.slash")?.tinting(with: .secondaryLabelColor) } @IBAction func checkFAQ(_ sender: Any) { let workspace = NSWorkspace.shared let url = URL(string: "https://aerialscreensaver.github.io/faq.html")! workspace.open(url) } @IBAction func checkJoshHal(_ sender: Any) { let workspace = NSWorkspace.shared let url = URL(string: "https://www.jetsoncreative.com/aerial")! workspace.open(url) } }
mit
89197cfddcea67af5f1a0229ed5ab031
31.371429
99
0.674316
4.003534
false
false
false
false
nathawes/swift
test/SILOptimizer/pointer_conversion_objc.swift
9
2848
// RUN: %target-swift-frontend -module-name pointer_conversion -emit-sil -O %s | %FileCheck %s // REQUIRES: optimized_stdlib // REQUIRES: objc_interop // REQUIRES: swift_stdlib_asserts // Opaque, unoptimizable functions to call. @_silgen_name("takesConstRawPointer") func takesConstRawPointer(_ x: UnsafeRawPointer) @_silgen_name("takesOptConstRawPointer") func takesOptConstRawPointer(_ x: UnsafeRawPointer?) @_silgen_name("takesMutableRawPointer") func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) @_silgen_name("takesOptMutableRawPointer") func takesOptMutableRawPointer(_ x: UnsafeMutableRawPointer?) // Opaque function for generating values @_silgen_name("get") func get<T>() -> T // The purpose of these tests is to make sure the storage is never released // before the call to the opaque function. // CHECK-LABEL: sil @$s18pointer_conversion17testOptionalArrayyyF public func testOptionalArray() { let array: [Int]? = get() takesOptConstRawPointer(array) // CHECK: bb0: // CHECK: switch_enum {{.*}}, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // CHECK: [[SOME_BB]]( // CHECK: cond_br {{%.*}}, {{bb[0-9]+}}, [[CHECK_BB:bb[0-9]+]] // CHECK: [[CHECK_BB]]: // CHECK: cond_br {{%.*}}, [[CHECK_BB_2:bb[0-9]+]], {{bb[0-9]+}} // CHECK: [[CHECK_BB_2]]: // CHECK: [[OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.some!enumelt, // CHECK-NEXT: [[POINTER:%.+]] = struct $UnsafeRawPointer ( // CHECK-NEXT: [[DEP_POINTER:%.+]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]] : $Optional<AnyObject> // CHECK-NEXT: [[OPT_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt, [[DEP_POINTER]] // CHECK-NEXT: br [[CALL_BRANCH:bb[0-9]+]]([[OPT_POINTER]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>) // CHECK: [[CALL_BRANCH]]([[OPT_POINTER:%.+]] : $Optional<UnsafeRawPointer>, [[OWNER:%.+]] : $Optional<AnyObject>): // CHECK-NOT: release // CHECK-NEXT: [[DEP_OPT_POINTER:%.+]] = mark_dependence [[OPT_POINTER]] : $Optional<UnsafeRawPointer> on [[OWNER]] : $Optional<AnyObject> // CHECK: [[FN:%.+]] = function_ref @takesOptConstRawPointer // CHECK-NEXT: apply [[FN]]([[DEP_OPT_POINTER]]) // CHECK-NOT: release // CHECK-NOT: {{^bb[0-9]+:}} // CHECK: release_value {{%.+}} : $Optional<Array<Int>> // CHECK-NEXT: [[EMPTY:%.+]] = tuple () // CHECK-NEXT: return [[EMPTY]] // CHECK: [[NONE_BB]]: // CHECK-NEXT: [[NO_POINTER:%.+]] = enum $Optional<UnsafeRawPointer>, #Optional.none!enumelt // CHECK-NEXT: [[NO_OWNER:%.+]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK-NEXT: br [[CALL_BRANCH]]([[NO_POINTER]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>) } // CHECK-LABEL: end sil function '$s18pointer_conversion17testOptionalArrayyyF'
apache-2.0
dece971380f6bf34038c873309c76da7
46.466667
140
0.662219
3.655969
false
true
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/Views/Cell/StrategyCell.swift
1
2382
// // IndexViewCell.swift // travelMapMvvm // // Created by green on 15/8/26. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import UIKit import ReactiveCocoa /** * 攻略Cell */ class StrategyCell: UITableViewCell, ReactiveView { // 攻略图片 @IBOutlet private weak var strategyPic: UIImageView! // 攻略名称 @IBOutlet private weak var strategyNameL: UILabel! // 攻略创建日期 @IBOutlet private weak var dateL: UILabel! // 攻略访问量 @IBOutlet private weak var visiteNumL: UILabel! // 小编头像 @IBOutlet private weak var authorHeadC: GCircleControl! // 小编名称 @IBOutlet private weak var authorNameL: UILabel! private var authorImageViewModel = ImageViewModel(urlString: nil) private var strategyImageViewModel = ImageViewModel(urlString: nil, defaultImage:UIImage(named: "defaultImage.jpg")!) // MARK: - init override func awakeFromNib() { super.awakeFromNib() selectionStyle = UITableViewCellSelectionStyle.None strategyPic.layer.masksToBounds = true strategyPic.layer.cornerRadius = 8 // Observe RACObserve(authorImageViewModel, "image") ~> RAC(authorHeadC,"image") RACObserve(strategyImageViewModel, "image") ~> RAC(strategyPic,"image") self.rac_prepareForReuseSignal.subscribeNext { (any:AnyObject!) -> Void in self.authorHeadC.image = UIImage() self.strategyPic.image = nil } } // MARK: - ReactiveView func bindViewModel(viewModel: AnyObject) { if let viewModel = viewModel as? StrategyModel { strategyNameL.text = viewModel.title dateL.text = viewModel.createTime visiteNumL.text = viewModel.visitNumber == nil ? "" : "\(viewModel.visitNumber!)" authorNameL.text = viewModel.author // 加载攻略图片 strategyImageViewModel.urlString = viewModel.picUrl strategyImageViewModel.downloadImageCommand.execute(nil) // 加载小编头像图片 authorImageViewModel.urlString = viewModel.authorPicUrl authorImageViewModel.downloadImageCommand.execute(nil) } } }
apache-2.0
7aabae2a04cfcca8d3b9b41f55bf46b0
28.410256
121
0.625109
4.720165
false
false
false
false
PANDA-Guide/PandaGuideApp
Carthage/Checkouts/SwiftTweaks/SwiftTweaks/EdgeInsetsTweakTemplate.swift
1
1657
// // EdgeInsetsTweakTemplate.swift // SwiftTweaks // // Created by Bryan Clark on 4/8/16. // Copyright © 2016 Khan Academy. All rights reserved. // import Foundation /// A shortcut to create UIEdgeInsets using Tweaks. public struct EdgeInsetsTweakTemplate: TweakGroupTemplateType { public let collectionName: String public let groupName: String public let top: Tweak<CGFloat> public let left: Tweak<CGFloat> public let bottom: Tweak<CGFloat> public let right: Tweak<CGFloat> public var tweakCluster: [AnyTweak] { return [top, left, bottom, right].map(AnyTweak.init) } private static let edgeInsetDefaultParameters = SignedNumberTweakDefaultParameters<CGFloat>(defaultValue: 0, minValue: 0, maxValue: nil, stepSize: 1.0) public init( _ collectionName: String, _ groupName: String, defaultValue: UIEdgeInsets? = nil ) { self.collectionName = collectionName self.groupName = groupName func createInsetTweak(_ tweakName: String, customDefaultValue: CGFloat?) -> Tweak<CGFloat> { return Tweak( collectionName: collectionName, groupName: groupName, tweakName: tweakName, defaultParameters: EdgeInsetsTweakTemplate.edgeInsetDefaultParameters, customDefaultValue: customDefaultValue ) } self.top = createInsetTweak("Top", customDefaultValue: defaultValue?.top) self.left = createInsetTweak("Left", customDefaultValue: defaultValue?.left) self.bottom = createInsetTweak("Bottom", customDefaultValue: defaultValue?.bottom) self.right = createInsetTweak("Right", customDefaultValue: defaultValue?.right) } }
gpl-3.0
cf31bbb100ee73c9404ab2ad21541dfd
29.666667
152
0.722222
4.3125
false
false
false
false
ouyanghaiyong/Study_swift
DouYuZB/DouYuZB/Classes/Main/HYMainViewController.swift
1
2050
// // HYMainViewController.swift // DouYuZB // // Created by ouyang on 2017/2/13. // Copyright © 2017年 ouyang. All rights reserved. // import UIKit class HYMainViewController: UITabBarController { override class func initialize() { var attrs = [String: NSObject]() attrs[NSForegroundColorAttributeName] = UIColor.init(red: 87, green: 206, blue: 138, alpha: 1) // 设置tabBar字体颜色 UITabBarItem.appearance().setTitleTextAttributes(attrs, for:.selected) } override func viewDidLoad() { super.viewDidLoad() addChildVCs() } func addChildVCs() -> Void { setupChildController("首页", image: "ddd", selectImage: "ddd", controller: HYHomeViewController.init()) setupChildController("关注", image: "ddd", selectImage: "ddd", controller: HYFollowViewController.init()) setupChildController("直播", image: "ddd", selectImage: "ddd", controller: HYLiveViewController.init()) setupChildController("个人中心", image: "ddd", selectImage: "ddd", controller: HYProfileViewController.init()) } fileprivate func setupChildController(_ title:String, image:String, selectImage:String,controller:UIViewController) { controller.tabBarItem.title = title controller.navigationItem.title = title controller.tabBarItem.selectedImage = UIImage.init(named: selectImage) controller.tabBarItem.image = UIImage.init(named: image) let naviController = HYNavigationViewController.init(rootViewController: controller) addChildViewController(naviController) } /* // 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. } */ }
mit
af9a0a6a10b2cf1e72bedac489ab4bdf
33.741379
121
0.674938
4.890777
false
false
false
false
polishedcode/tasty-imitation-keyboard
Keyboard/LanguageDefinition.swift
1
8404
// // LanguageDefinition.swift // TastyImitationKeyboard // // Created by Simon Corston-Oliver on 7/11/15. // Copyright © 2015 Apple. All rights reserved. // import Foundation // The housekeeping information that defines a language: // the name of the language, the characters required to type that language etc. // // Note that the language information says nothing about keyboard layout and doesn't attempt an exhaustive listing of the kbds that // could be used to type the language. We can determine programmatically elsewhere if a kbd contains all the necessary chars. open class LanguageDefinition { // The ISO 639-1 language code. // REVIEW What to do about languages that don't have an ISO 639-1 code? fileprivate let _langCode : String // Name of the language in English fileprivate let _englishName : String // Name of the language in that language's native script fileprivate let _nativeName : String // The name of the JSON keyboard definition file for the default keyboard for this language fileprivate let _defaultKbd : String // Special symbols that this language uses within what we will consider to be words e.g. apostrophe for English means // that we will consider "dog's" to be a single word. Similarly the middle dot in Catalan etc. fileprivate let _internalPunc : Set<String> init(langCode: String, englishName: String, nativeName: String, defaultKbd: String, internalPunc: [String]) { self._langCode = langCode self._englishName = englishName self._nativeName = nativeName self._defaultKbd = defaultKbd self._internalPunc = Set<String>(internalPunc) } var LangCode : String { get { return self._langCode } } var EnglishName : String { get { return self._englishName } } var NativeName : String { get { return self._nativeName } } var DefaultKbdName : String { get { return self._defaultKbd } } var DescriptiveName : String { get { return EnglishName + "/" + NativeName } } var InternalPunc : Set<String> { get { return self._internalPunc } } // Default English language definition to be used in case of an emergency // e.g. failing to load language definitions from the JSON language definition file. class fileprivate func EnglishLanguageDefinition() -> LanguageDefinition { return LanguageDefinition( langCode: "EN", englishName: "English", nativeName: "English", defaultKbd: "QWERTY", internalPunc: ["-", "'"]) } } // Get and validate the current language to use // If what we think is the current language has been disabled in settings, we need to pick another language func CurrentLanguageCode() -> String { return UserDefaults.standard.string(forKey: kActiveLanguageCode) ?? EnabledLanguageCodes()[0] } func CurrentLanguageDefinition() -> LanguageDefinition? { return LanguageDefinitions.Singleton().langCodeToDefinition[CurrentLanguageCode()] } // Make the look up key for checking in user defaults which layout to use for language func languageKeyboardLayout(_ langCode: String) -> String { return langCode + "_layout" } func getKeyboardLayoutNameForLanguageCode(_ langCode: String) -> String { let lookUpKey = languageKeyboardLayout(langCode) return UserDefaults.standard.string(forKey: lookUpKey) ?? LanguageDefinitions.Singleton().KeyboardFileForLanguageCode(langCode) ?? "QWERTY" } func setKeyboardLayoutNameForLanguageCode(_ langCode: String, layout: String) { let lookUpKey = languageKeyboardLayout(langCode) return UserDefaults.standard.set(layout, forKey: lookUpKey) } func setDefaultKeyboardLayoutNameForLanguageCode(_ langCode: String, layout: String) { let lookUpKey = languageKeyboardLayout(langCode) let currentValue = UserDefaults.standard.string(forKey: lookUpKey) if currentValue == nil { setKeyboardLayoutNameForLanguageCode(langCode, layout: layout) } } func langCodeEnabledKey (_ langCode: String) -> String { return langCode + "_Enabled" } func getLanguageCodeEnabled(_ langCode: String) -> Bool { return UserDefaults.standard.bool(forKey: langCodeEnabledKey(langCode)) } func setLanguageCodeEnabled(_ langCode: String, value: Bool) { return UserDefaults.standard.set(value, forKey: langCodeEnabledKey(langCode)) } func EnabledLanguageCodes() -> [String] { var enabledCodes: [String] = [] let defs = LanguageDefinitions.Singleton().definitions for definition in defs { let key = definition.LangCode if getLanguageCodeEnabled(key) { enabledCodes.append(key) } } // Make sure at least one language is always enabled if enabledCodes.count == 0 { enabledCodes.append("EN") } return enabledCodes } // class var not yet supported so make it global private var _Singleton: LanguageDefinitions? = nil // Define the set of languages currently supported open class LanguageDefinitions { open var definitions : [LanguageDefinition] = [] open var langCodeToDefinition: [String : LanguageDefinition] = [:] fileprivate func extractLanguageDefinitions(_ allDefinitions: NSDictionary) { if let languages = allDefinitions["languages"] as? NSArray { for language2 in languages { let language = language2 as! NSDictionary if let languageProperties = language["language"] as? NSDictionary { if let englishName = languageProperties["englishName"] as? String, let nativeName = languageProperties["nativeName"] as? String, let defaultKbd = languageProperties["defaultKbd"] as? String, let internalPunc = languageProperties["internalPunc"] as? [String], let langCode = languageProperties["langCode"] as? String { let definition = LanguageDefinition( langCode: langCode, englishName: englishName, nativeName: nativeName, defaultKbd: defaultKbd, internalPunc: internalPunc) self.definitions.append(definition) self.langCodeToDefinition[definition.LangCode] = definition setDefaultKeyboardLayoutNameForLanguageCode(definition.LangCode, layout: definition.DefaultKbdName) } } } } else { makeDefaultLangDefinitions() } } // If we can't process the langauge definition file for some reason make sure we at least define English fileprivate func makeDefaultLangDefinitions() { definitions = [LanguageDefinition.EnglishLanguageDefinition()] langCodeToDefinition["EN"] = definitions[0] } init(jsonFileName : String) { if let languageDefinitions = loadJSON("LanguageDefinitions") { self.extractLanguageDefinitions(languageDefinitions) } else { makeDefaultLangDefinitions() } } func LanguageNames() -> [String] { var names : [String] = [] for languageDefinition in definitions { names.append(languageDefinition.DescriptiveName) } return names } func LangCodes() -> [String] { return langCodeToDefinition.keys.sorted() } func DescriptiveNameForLangCode(_ langCode: String) -> String { return self.langCodeToDefinition[langCode]?.DescriptiveName ?? "UNKNOWN" } func KeyboardFileForLanguageCode(_ langCode: String) -> String? { for lang in self.definitions { if lang.LangCode == langCode { return lang.DefaultKbdName } } return nil } class func Singleton() -> LanguageDefinitions { if _Singleton == nil { _Singleton = LanguageDefinitions(jsonFileName: "LanguageDefinitions") } return _Singleton! } }
bsd-3-clause
962faf0e2167392e9d46905b40565881
30.00738
143
0.644175
4.896853
false
false
false
false
h-n-y/BigNerdRanch-SwiftProgramming
chapter-21/SilverChallenge.playground/Contents.swift
1
1968
//: Playground - noun: a place where people can play import Cocoa typealias Velocity = Double extension Velocity { var kph: Velocity { return self * 1.60934 } var mph: Velocity { return self } } protocol VehicleType { var topSpeed: Velocity { get } var numberOfDoors: Int { get } var hasFlatbed: Bool { get } } struct Car { let make: String let model: String let year: Int let color: String let nickname: String var gasLevel: Double { willSet { precondition(newValue <= 1.0 && newValue >= 0.0, "New value must be between 0 and 1.") } } } extension Car: VehicleType { var topSpeed: Velocity { return 180 } var numberOfDoors: Int { return 4 } var hasFlatbed: Bool { return false } } extension Car { init(carMake: String, carModel: String, carYear: Int) { self.init(make: carMake, model: carModel, year: carYear, color: "Black", nickname: "N/A", gasLevel: 1.0 ) } } var c = Car(carMake: "Ford", carModel: "Fusion", carYear: 2013) extension Car { enum CarKind: CustomStringConvertible { case Coupe, Sedan var description: String { switch self { case .Coupe: return "Coupe" case .Sedan: return "Sedan" } } } var kind: CarKind { if numberOfDoors == 2 { return .Coupe } else { return .Sedan } } } c.kind.description extension Car { mutating func emptyGas(amount: Double) { precondition(gasLevel - amount >= 0, "Amount to remove ( \(amount) ) must be less than or equal to current gas level ( \(gasLevel) )") gasLevel -= amount } mutating func fillGas() { gasLevel = 1.0 } } c.emptyGas(0.3) c.gasLevel c.fillGas() c.gasLevel
mit
c9f4a6e9328c1d076e8757dd6a0edc73
16.415929
142
0.547764
3.920319
false
false
false
false
X140Yu/Lemon
Lemon/Library/View/FollowButton.swift
1
3266
import UIKit import RxSwift import RxCocoa enum FollowButtonState { case unfollow case following case busy } class FollowButton: UIButton { private let loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) public let bag = DisposeBag() public var username: String? { didSet { guard let u = username else { return } GitHubProvider .request(.FollowStatus(name: u)) .subscribe(onSuccess: { (res) in if res.statusCode == 204 { self.currentState.value = .following } else { self.currentState.value = .unfollow } }).addDisposableTo(bag) } } var currentState = Variable<FollowButtonState>(.busy) override init(frame: CGRect) { super.init(frame: frame) setup() } func update(_ state: FollowButtonState) { loadingIndicator.stopAnimating() loadingIndicator.isHidden = true switch state { case .following: setTitle("Following", for: .normal) setTitleColor(UIColor.white, for: .normal) setBackgroundImage(UIColor.lmGithubBlue.image(), for: .normal) setBackgroundImage(UIColor.lmGithubBlue.image(), for: .highlighted) case .unfollow: setTitle("Follow", for: .normal) setTitleColor(UIColor.lmGithubBlue, for: .normal) setBackgroundImage(UIColor.white.image(), for: .normal) setBackgroundImage(UIColor.white.image(), for: .highlighted) case .busy: setTitle("", for: .normal) loadingIndicator.isHidden = false loadingIndicator.startAnimating() } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } @objc func handleTouch() { guard let u = username else { return } switch self.currentState.value { case .busy: return case .following: self.currentState.value = .busy GitHubProvider .request(.UnFollowUser(name: u)) .subscribe(onSuccess: { (res) in if res.statusCode == 204 { self.currentState.value = .unfollow } else { self.currentState.value = .following } }, onError: { error in self.currentState.value = .following }).addDisposableTo(bag) case .unfollow: self.currentState.value = .busy GitHubProvider .request(.FollowUser(name: u)) .subscribe(onSuccess: { (res) in if res.statusCode == 204 { self.currentState.value = .following } else { self.currentState.value = .unfollow } }, onError: { error in self.currentState.value = .unfollow }).addDisposableTo(bag) } } func setup() { layer.cornerRadius = 7 layer.masksToBounds = true layer.borderWidth = 1 layer.borderColor = UIColor.lmGithubBlue.cgColor titleLabel?.font = UIFont.systemFont(ofSize: 16) addSubview(loadingIndicator) loadingIndicator.center = CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0) addTarget(self, action: #selector(handleTouch), for: .touchUpInside) currentState.asDriver().drive(onNext: { [weak self] state in self?.update(state) }).addDisposableTo(bag) currentState.value = .busy } }
gpl-3.0
6b34f656c7e184bdf21e1c5ce69aea7c
26.445378
92
0.633497
4.4375
false
false
false
false
gfx/Swift-JsonSerializer
JsonSerializerTests/JsonParserTests.swift
2
4706
// // JsonParserTests.swift // JsonSerializer // // Created by Fuji Goro on 2014/09/08. // Copyright (c) 2014 Fuji Goro. All rights reserved. // import XCTest class JsonDeserializerTests: XCTestCase { func testEmptyArray() { let json = try! Json.deserialize("[]") XCTAssertEqual(json.description, "[]") } func testEmptyArrayWithSpaces() { let json = try! Json.deserialize(" [ ] ") XCTAssertEqual(json.description, "[]") } func testArray() { let json = try! Json.deserialize("[true,false,null]") XCTAssertEqual(json.description, "[true,false,null]") } func testArrayWithSpaces() { let json = try! Json.deserialize("[ true , false , null ]") XCTAssertEqual(json.description, "[true,false,null]") } func testEmptyObject() { let json = try! Json.deserialize("{}") XCTAssertEqual(json.description, "{}") } func testEmptyObjectWithSpace() { let json = try! Json.deserialize(" { } ") XCTAssertEqual(json.description, "{}") } func testObject() { let json = try! Json.deserialize("{\"foo\":[\"bar\",\"baz\"]}") XCTAssertEqual(json.description, "{\"foo\":[\"bar\",\"baz\"]}") } func testObjectWithWhiteSpaces() { let json = try! Json.deserialize(" { \"foo\" : [ \"bar\" , \"baz\" ] } ") XCTAssertEqual(json.description, "{\"foo\":[\"bar\",\"baz\"]}") } func testString() { let json = try! Json.deserialize("[\"foo [\\t] [\\r] [\\n]] [\\\\] bar\"]") XCTAssertEqual(json.description, "[\"foo [\\t] [\\r] [\\n]] [\\\\] bar\"]") } func testStringWithMyltiBytes() { let json = try! Json.deserialize("[\"こんにちは\"]") XCTAssertEqual(json[0]!.stringValue, "こんにちは") XCTAssertEqual(json.description, "[\"こんにちは\"]") } func testStringWithMyltiUnicodeScalars() { let json = try! Json.deserialize("[\"江戸前🍣\"]") XCTAssertEqual(json[0]!.stringValue!, "江戸前🍣") XCTAssertEqual(json[0]!.description, "\"江戸前🍣\"") XCTAssertEqual(json.description, "[\"江戸前🍣\"]") } func testNumberOfInt() { let json = try! Json.deserialize("[0, 10, 234]") XCTAssertEqual(json.description, "[0,10,234]") } func testNumberOfFloat() { let json = try! Json.deserialize("[3.14, 0.035]") XCTAssertEqual(json.description, "[3.14,0.035]") } func testNumberOfExponent() { let json = try! Json.deserialize("[1e2, 1e-2, 3.14e+01]") XCTAssertEqual(json[0]!.intValue, 100) XCTAssertEqual(json[1]!.doubleValue, 0.01) XCTAssertEqual("\(json[2]!.doubleValue!)", "31.4") } func testUnicodeEscapeSequences() { let json = try! Json.deserialize("[\"\\u003c \\u003e\"]") XCTAssertEqual(json[0]!.stringValue!, "< >") } func testUnicodeEscapeSequencesWith32bitsUnicodeScalar() { let json = try! Json.deserialize("[\"\\u0001\\uF363\"]") XCTAssertEqual(json[0]!.stringValue, "\u{0001F363}") } func testUnicodeEscapeSequencesWithTwo16bitsUnicodeScalar() { let json = try! Json.deserialize("[\"\\u00015\\uF363\"]") XCTAssertEqual(json[0]!.stringValue, "\u{0001}5\u{F363}") } func testTwitterJson() { let json = try! Json.deserialize(complexJsonExample("tweets")) XCTAssertEqual(json["statuses"]![0]!["id_str"]!.stringValue, "250075927172759552") } func testStackexchangeJson() { let json = try! Json.deserialize(complexJsonExample("stackoverflow-items")) XCTAssertEqual(json["items"]![0]!["view_count"]!.intValue, 18711) } func testPerformanceExampleWithNSData() { let jsonSource = complexJsonExample("tweets") self.measureBlock { let _ = try! Json.deserialize(jsonSource) } } func testPerformanceExampleWithString() { let jsonSource = String(data: complexJsonExample("tweets"), encoding: NSUTF8StringEncoding)! self.measureBlock { let _ = try! Json.deserialize(jsonSource) } } func testPerformanceExampleInJSONSerialization() { let jsonSource = complexJsonExample("tweets") self.measureBlock { let _: AnyObject? = try! NSJSONSerialization .JSONObjectWithData(jsonSource, options: .MutableContainers) } } func complexJsonExample(name: String) -> NSData { let bundle = NSBundle(forClass: self.dynamicType) let path = bundle.pathForResource(name, ofType: "json")! return NSData(contentsOfFile: path)! } }
apache-2.0
e648fd5424ed8b364b868f25208b0d34
31.222222
100
0.59806
4.153984
false
true
false
false
kak-ios-codepath/everest
Everest/Everest/Controllers/ActionDetail/CreateMomentViewController.swift
1
17518
// // CreateMomentViewController.swift // Everest // // Created by Kavita Gaitonde on 10/13/17. // Copyright © 2017 Kavita Gaitonde. All rights reserved. // import UIKit import MapKit import FacebookShare import MBProgressHUD class CreateMomentViewController: UIViewController, UITextViewDelegate, UITextFieldDelegate { @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var cancelButton: UIButton! // @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var shareToFBLabel: UILabel! @IBOutlet weak var shareFBSwitch: UISwitch! // @IBOutlet weak var actionTitle: UILabel! @IBOutlet weak var momentTitle: UITextField! @IBOutlet weak var momentDetails: UITextView! // @IBOutlet weak var addPhotoLabel: UILabel! // @IBOutlet weak var photoBtn: UIButton! @IBOutlet weak var mapView: MKMapView! // @IBOutlet weak var mapImageView: UIImageView! // @IBOutlet weak var mapBtn: UIButton! @IBOutlet weak var publishButton: UIButton! @IBOutlet weak var momentImageView: UIImageView! fileprivate var selectedImage: UIImage! fileprivate var isEditMode: Bool = false var moment: Moment! var actionId: String! var momentCoordinate: CLLocationCoordinate2D! var geoLocation: [String : String]? var location: String? var isTakingPic = false var shareOnFB = false var shareOnTwitter = false var picsUrl: [String]? var addedDetails = false override func viewDidLoad() { super.viewDidLoad() momentTitle.layer.cornerRadius = 10 momentTitle.layer.masksToBounds = true momentDetails.layer.cornerRadius = 10 momentDetails.layer.masksToBounds = true self.momentDetails.delegate = self self.momentTitle.delegate = self if moment != nil { //edit mode //ERROR should never happen if moment.userId == User.currentUser?.id { dismiss(animated: true, completion: nil) } isEditMode = true addedDetails = true self.actionId = moment.actId self.momentTitle.text = moment.title self.momentDetails.text = moment.details self.location = moment.location if let geoLoc = moment.geoLocation { self.geoLocation = geoLoc if let lat = self.geoLocation?["lat"], let doubleLat = Double(lat) { if let lon = self.geoLocation?["lon"], let doubleLon = Double(lon) { self.momentCoordinate = CLLocationCoordinate2D(latitude: doubleLat, longitude: doubleLon) let region = MKCoordinateRegion(center: momentCoordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.mapView.setRegion(region, animated: true) // self.mapImageView.isHidden = true self.addAnnotationAtCoordinate(coordinates: ["lat": momentCoordinate.latitude, "lon": momentCoordinate.longitude], title: "") } } } self.location = moment.location if let pics = moment.picUrls { self.momentImageView.setImageWith(URL(string: pics[0])!) self.momentImageView.clipsToBounds = true self.momentImageView.contentMode = .scaleAspectFill self.picsUrl = pics } self.publishButton.titleLabel?.text = "Save" self.cancelButton.isHidden = true self.navigationItem.title = "Edit a moment" } else { //create mode isEditMode = false self.publishButton.titleLabel?.text = "Publish" self.navigationItem.title = "Add a moment" } // self.actionTitle.text = MainManager.shared.availableActs[actionId]?.title if let loc = self.location { self.locationLabel.text = loc } else { self.locationLabel.text = "" } self.mapView.isUserInteractionEnabled = true self.momentImageView.isUserInteractionEnabled = true var tapGesture1 = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped)) self.mapView.addGestureRecognizer(tapGesture1) tapGesture1 = UITapGestureRecognizer(target: self, action: #selector(mapViewTapped)) //self.mapImageView.addGestureRecognizer(tapGesture1) let tapGesture2 = UITapGestureRecognizer(target: self, action: #selector(momentImageViewTapped)) self.momentImageView.addGestureRecognizer(tapGesture2) // if User.currentUser?.isFacebookUser() == false { // shareFBSwitch.isHidden = true // shareToFBLabel.isHidden = true // } } override func viewDidAppear(_ animated: Bool) { NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) NotificationCenter.default.removeObserver(self) } func mapViewTapped(gestureRecognizer: UIGestureRecognizer) { if momentCoordinate == nil { self.goToMapViewController() } else { let alertController = UIAlertController(title: "", message: "Change the location?", preferredStyle: UIAlertControllerStyle.actionSheet) let yesAction = UIAlertAction(title: "Yes", style: .default , handler: { (action:UIAlertAction!) in self.goToMapViewController() }) alertController.addAction(yesAction) let noAction = UIAlertAction(title: "Cancel", style: .cancel , handler: { (action:UIAlertAction!) in }) alertController.addAction(noAction) let deleteAction = UIAlertAction(title: "Delete", style: .destructive , handler: { (action:UIAlertAction!) in self.momentCoordinate = nil self.location = nil self.locationLabel.text = "" self.geoLocation = nil // self.mapImageView.isHidden = false }) alertController.addAction(deleteAction) self.present(alertController, animated: true, completion:nil) } } func addAnnotationAtCoordinate(coordinates:[String:Double], title: String) { let annotation = MKPointAnnotation() annotation.coordinate = CLLocationCoordinate2D(latitude: coordinates["lat"]!, longitude: coordinates["lon"]!) mapView.addAnnotation(annotation) annotation.title = "\(title)" self.mapView.addAnnotation(annotation) } func goToMapViewController() { let storyboard = UIStoryboard.init(name: "UserProfile", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "MapViewController") as! MapViewController if self.momentCoordinate != nil { vc.momentCoordinate = self.momentCoordinate } vc.selectedMap = { (mapView: MKMapView, momentCoordinate: CLLocationCoordinate2D, location: String?) in self.momentCoordinate = momentCoordinate let region = MKCoordinateRegion(center: momentCoordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) self.mapView.setRegion(region, animated: true) // self.mapImageView.isHidden = true self.location = location if let loc = self.location { self.locationLabel.text = loc } else { self.locationLabel.text = "" } self.geoLocation = ["lat": String(momentCoordinate.latitude), "lon": String(momentCoordinate.longitude)] self.addAnnotationAtCoordinate(coordinates: ["lat": momentCoordinate.latitude, "lon": momentCoordinate.longitude], title: "") } self.present(vc, animated: true, completion: nil) } func momentImageViewTapped(gestureRecognizer: UIGestureRecognizer) { if selectedImage == nil { let alertController = UIAlertController(title: "Select Image", message: "How would you like to select an image to upload?", preferredStyle: UIAlertControllerStyle.actionSheet) let cameraAction = UIAlertAction(title: "Camera", style: .default , handler: { (action:UIAlertAction!) in if UIImagePickerController.isSourceTypeAvailable(.camera) { let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = false vc.modalPresentationStyle = .fullScreen vc.sourceType = .camera vc.cameraCaptureMode = .photo self.present(vc, animated: true, completion: nil) } }) alertController.addAction(cameraAction) let photoLibraryAction = UIAlertAction(title: "PhotoLibrary", style: .default, handler: { (action:UIAlertAction!) in let vc = UIImagePickerController() vc.delegate = self vc.allowsEditing = false vc.modalPresentationStyle = .fullScreen vc.sourceType = .photoLibrary self.present(vc, animated: true, completion: nil) }) alertController.addAction(photoLibraryAction) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action:UIAlertAction!) in }) alertController.addAction(cancelAction) // Present Alert self.present(alertController, animated: true, completion:nil) } else { let alertController = UIAlertController(title: "", message: "Change photo?", preferredStyle: UIAlertControllerStyle.actionSheet) let yesAction = UIAlertAction(title: "Yes", style: .default , handler: { (action:UIAlertAction!) in self.selectedImage = nil self.momentImageViewTapped(gestureRecognizer: gestureRecognizer) }) alertController.addAction(yesAction) let noAction = UIAlertAction(title: "Cancel", style: .cancel , handler: { (action:UIAlertAction!) in }) alertController.addAction(noAction) let deleteAction = UIAlertAction(title: "Delete", style: .destructive , handler: { (action:UIAlertAction!) in self.momentImageView.image = UIImage(named: "addImage") self.selectedImage = nil }) alertController.addAction(deleteAction) self.present(alertController, animated: true, completion:nil) } } @IBAction func shareFBAction(_ sender: UISwitch) { if User.currentUser?.isFacebookUser() == true { self.shareOnFB = sender.isOn } } @IBAction func handleTapGesture(_ sender: AnyObject) { self.momentDetails.resignFirstResponder() self.momentTitle.resignFirstResponder() } @IBAction func handleCancel(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } @IBAction func onMomentFinished(_ sender: UIButton) { if !addedDetails || momentTitle.text == nil || (momentTitle.text?.characters.count)! == 0 || momentDetails.text == nil || (momentDetails.text?.characters.count)! == 0 { let alertController = UIAlertController(title: "Error", message: "Please add title and details for your moment", preferredStyle: UIAlertControllerStyle.alert) let okAction = UIAlertAction(title: "OK", style: .cancel, handler: { (action:UIAlertAction!) in }) alertController.addAction(okAction) // Present Alert self.present(alertController, animated: true, completion:nil) return } //update image to storage MBProgressHUD.showAdded(to: self.view, animated: true) self.publishButton.isUserInteractionEnabled = false if selectedImage != nil { if let imageData = UIImagePNGRepresentation(selectedImage) as Data? { FireBaseManager.shared.uploadImage(data: imageData) { (folderAndFileName, imageUrl, error) in if imageUrl != nil { self.picsUrl = [imageUrl!] self.momentImageView.setImageWith(URL(string: imageUrl!)!) self.momentImageView.clipsToBounds = true self.momentImageView.contentMode = .scaleAspectFill } self.submitData() } } else { self.submitData() } } else { self.submitData() } } func submitData() { let title = momentTitle.text! let details = momentDetails.text! self.moment = Moment(title: title, details: details, actId: self.actionId, userId: (User.currentUser?.id)!, profilePhotoUrl: User.currentUser?.profilePhotoUrl, userName: (User.currentUser?.name)!, timestamp: "\(Date())", picUrls: self.picsUrl, geoLocation: self.geoLocation, location: self.location) MainManager.shared.createMoment(actId: self.actionId, moment: self.moment, newMoment: isEditMode ? false : true){_ in MBProgressHUD.hide(for: self.view, animated: true) self.publishButton.isUserInteractionEnabled = true if self.shareOnFB { var url:URL! if self.picsUrl != nil { url = URL(string: (self.picsUrl?[0])!) } else { let category = MainManager.shared.availableActs[self.actionId]?.category let categoryObj = MainManager.shared.availableCategories.filter( { return $0.title == category } ).first if let imageUrl = categoryObj?.imageUrl { url = URL(string: imageUrl) } } var content = LinkShareContent.init(url: url, title: title, description: details) content.quote = "I did it!" let shareDialog = ShareDialog(content: content) shareDialog.mode = .native shareDialog.failsOnInvalidData = true shareDialog.completion = { result in // Handle share results print (result) if self.isEditMode { _ = self.navigationController?.popViewController(animated: true) } else { self.dismiss(animated: true, completion: nil) } } try! shareDialog.show() } else { if self.isEditMode { _ = self.navigationController?.popViewController(animated: true) } else { self.dismiss(animated: true, completion: nil) } } } } // MARK: - TextField Delegate func textFieldDidBeginEditing(_ textField: UITextField) { if textField.isFirstResponder == true { textField.placeholder = nil } } // MARK: - TextView Delegate func textViewDidBeginEditing(_: UITextView) { self.addedDetails = true self.momentDetails.text = "" self.momentDetails.textColor = UIColor.darkGray } func textViewDidEndEditing(_: UITextView) { } func keyboardWillShow(notification:NSNotification){ var userInfo = notification.userInfo! var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) // var contentInset:UIEdgeInsets = self.scrollView.contentInset // contentInset.bottom = keyboardFrame.size.height // self.scrollView.contentInset = contentInset } func keyboardWillHide(notification:NSNotification){ // let contentInset:UIEdgeInsets = UIEdgeInsets.zero // self.scrollView.contentInset = contentInset } } //MARK:- Image Picker delegate extension CreateMomentViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { isTakingPic = true let originalImage = info[UIImagePickerControllerOriginalImage] as? UIImage guard let reducedSizeImage = originalImage?.resized(withPercentage: 0.3) else {return} selectedImage = reducedSizeImage self.momentImageView.alpha = 0 self.momentImageView.clipsToBounds = true self.momentImageView.image = selectedImage self.momentImageView.contentMode = .scaleAspectFill self.momentImageView.setRoundedCorner(radius: 5) UIView.animate(withDuration: 0.3, animations: { self.momentImageView.alpha = 1 }) dismiss(animated: true, completion: nil) } }
apache-2.0
9dadf2a3f40ad35c23b5276590f6ca07
43.915385
307
0.617743
5.292145
false
false
false
false
maicki/plank
Sources/Core/JSRuntimeFile.swift
1
1506
// // JSRuntimeFile.swift // plank // // Created by Michael Schneider // // import Foundation /* Runtime file with helper types */ struct JSRuntimeFile: FileGenerator { static func runtimeImports() -> String { return JSIR.fileImportStmt("PlankDate, PlankURI", "runtime.flow") } var fileName: String { return "runtime.flow.js" } var indent: Int { return 2 } func renderContent() -> String { return [ "export type $Object<V> = { +[key: string]: V }", "export type _$Values<V, O: $Object<V>> = V", "export type $Values<O: Object> = _$Values<*, O>", "export type PlankDate = string", "export type PlankURI = string" ].map { $0 + ";" } .joined(separator: "\n") } func renderFile() -> String { let output = ( [self.renderCommentHeader()] + [self.renderContent()] ) .map { $0.trimmingCharacters(in: CharacterSet.whitespaces) } .filter { $0 != "" } .joined(separator: "\n\n") return output } } extension JSRuntimeFile { func renderCommentHeader() -> String { let header = [ "// @flow", "//", "// \(self.fileName)", "// Autogenerated by plank", "//", "// DO NOT EDIT - EDITS WILL BE OVERWRITTEN", "// @generated", "//" ] return header.joined(separator: "\n") } }
apache-2.0
9509ac9cdd7fd725cd86867620de52c8
23.290323
73
0.501992
3.973615
false
false
false
false
mudphone/SwiftPhoenixClient
Sources/Channel.swift
1
2880
// // Channel.swift // SwiftPhoenixClient // import Swift public class Channel { var bindings: [Binding] = [] var topic: String? var message: Message? var callback: ((Any) -> Void?) weak var socket: Socket? /** Initializes a new Channel mapping to a server-side channel - parameter topic: String topic for given channel - parameter message: Message object containing message to send - parameter callback: Function to pass along with the channel instance - parameter socket: Socket for websocket connection - returns: Channel */ init(topic: String, message: Message, callback: @escaping ((Any) -> Void), socket: Socket) { (self.topic, self.message, self.callback, self.socket) = (topic, message, { callback($0) }, socket) reset() } /** Removes existing bindings */ func reset() { bindings = [] } /** Assigns Binding events to the channel bindings array - parameter event: String event name - parameter callback: Function to run on event */ public func on(event: String, callback: @escaping ((Any) -> Void)) { bindings.append(Binding(event: event, callback: { callback($0) })) } /** Determine if a topic belongs in this channel - parameter topic: String topic name for comparison - returns: Boolean */ func isMember(topic: String) -> Bool { return self.topic == topic } /** Removes an event binding from this cahnnel - parameter event: String event name */ func off(event: String) { var newBindings: [Binding] = [] for binding in bindings { if binding.event != event { newBindings.append(Binding(event: binding.event, callback: binding.callback)) } } bindings = newBindings } /** Triggers an event on this channel - parameter triggerEvent: String event name - parameter msg: Message to pass into event callback */ func trigger(triggerEvent: String, msg: Message) { for binding in bindings { if binding.event == triggerEvent { binding.callback(msg) } } } /** Sends and event and message through the socket - parameter event: String event name - parameter message: Message payload */ func send(event: String, message: Message) { print("conn sending") let payload = Payload(topic: topic!, event: event, message: message) socket?.send(data: payload) } /** Leaves the socket - parameter message: Message to pass to the Socket#leave function */ func leave(message: Message) { if let sock = socket { sock.leave(topic: topic!, message: message) } reset() } }
mit
ee8e9321248286583314da7b52c3d94e
27.514851
107
0.597917
4.593301
false
false
false
false
natecook1000/swift
test/SILGen/synthesized_conformance_struct.swift
2
6338
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-silgen %s -swift-version 4 | %FileCheck -check-prefix CHECK -check-prefix CHECK-FRAGILE %s // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-silgen %s -swift-version 4 -enable-resilience | %FileCheck -check-prefix CHECK -check-prefix CHECK-RESILIENT %s struct Struct<T> { var x: T } // CHECK-LABEL: struct Struct<T> { // CHECK: @sil_stored var x: T { get set } // CHECK: init(x: T) // CHECK: enum CodingKeys : CodingKey { // CHECK: case x // CHECK: var stringValue: String { get } // CHECK: init?(stringValue: String) // CHECK: var intValue: Int? { get } // CHECK: init?(intValue: Int) // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_enum_equals(_ a: Struct<T>.CodingKeys, _ b: Struct<T>.CodingKeys) -> Bool // CHECK-RESILIENT: static func == (a: Struct<T>.CodingKeys, b: Struct<T>.CodingKeys) -> Bool // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK: } // CHECK-LABEL: extension Struct : Equatable where T : Equatable { // CHECK-FRAGILE: @_implements(Equatable, ==(_:_:)) static func __derived_struct_equals(_ a: Struct<T>, _ b: Struct<T>) -> Bool // CHECK-RESILIENT: static func == (a: Struct<T>, b: Struct<T>) -> Bool // CHECK: } // CHECK-LABEL: extension Struct : Hashable where T : Hashable { // CHECK: var hashValue: Int { get } // CHECK: func hash(into hasher: inout Hasher) // CHECK: } // CHECK-LABEL: extension Struct : Decodable & Encodable where T : Decodable, T : Encodable { // CHECK: init(from decoder: Decoder) throws // CHECK: func encode(to encoder: Encoder) throws // CHECK: } extension Struct: Equatable where T: Equatable {} // CHECK-FRAGILE-LABEL: // static Struct<A>.__derived_struct_equals(_:_:) // CHECK-FRAGILE-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASQRzlE010__derived_C7_equalsySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Struct<T>, @in_guaranteed Struct<T>, @thin Struct<T>.Type) -> Bool { // CHECK-RESILIENT-LABEL: // static Struct<A>.== infix(_:_:) // CHECK-RESILIENT-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASQRzlE2eeoiySbACyxG_AEtFZ : $@convention(method) <T where T : Equatable> (@in_guaranteed Struct<T>, @in_guaranteed Struct<T>, @thin Struct<T>.Type) -> Bool { extension Struct: Hashable where T: Hashable {} // CHECK-LABEL: // Struct<A>.hashValue.getter // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASHRzlE9hashValueSivg : $@convention(method) <T where T : Hashable> (@in_guaranteed Struct<T>) -> Int { // CHECK-LABEL: // Struct<A>.hash(into:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASHRzlE4hash4intoys6HasherVz_tF : $@convention(method) <T where T : Hashable> (@inout Hasher, @in_guaranteed Struct<T>) -> () { extension Struct: Codable where T: Codable {} // CHECK-LABEL: // Struct<A>.init(from:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASeRzSERzlE4fromACyxGs7Decoder_p_tKcfC : $@convention(method) <T where T : Decodable, T : Encodable> (@in Decoder, @thin Struct<T>.Type) -> (@out Struct<T>, @error Error) // CHECK-LABEL: // Struct<A>.encode(to:) // CHECK-NEXT: sil hidden @$S30synthesized_conformance_struct6StructVAASeRzSERzlE6encode2toys7Encoder_p_tKF : $@convention(method) <T where T : Decodable, T : Encodable> (@in_guaranteed Encoder, @in_guaranteed Struct<T>) -> @error Error { // Witness tables // CHECK-LABEL: sil_witness_table hidden <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct { // CHECK-NEXT: method #Equatable."=="!1: <Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool : @$S30synthesized_conformance_struct6StructVyxGSQAASQRzlSQ2eeoiySbx_xtFZTW // protocol witness for static Equatable.== infix(_:_:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Equatable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Hashable> Struct<T>: Hashable module synthesized_conformance_struct { // CHECK-NEXT: base_protocol Equatable: <T where T : Equatable> Struct<T>: Equatable module synthesized_conformance_struct // CHECK-NEXT: method #Hashable.hashValue!getter.1: <Self where Self : Hashable> (Self) -> () -> Int : @$S30synthesized_conformance_struct6StructVyxGSHAASHRzlSH9hashValueSivgTW // protocol witness for Hashable.hashValue.getter in conformance <A> Struct<A> // CHECK-NEXT: method #Hashable.hash!1: <Self where Self : Hashable> (Self) -> (inout Hasher) -> () : @$S30synthesized_conformance_struct6StructVyxGSHAASHRzlSH4hash4intoys6HasherVz_tFTW // protocol witness for Hashable.hash(into:) in conformance <A> Struct<A> // CHECK-NEXT: method #Hashable._rawHashValue!1: <Self where Self : Hashable> (Self) -> ((UInt64, UInt64)) -> Int : @$S30synthesized_conformance_struct6StructVyxGSHAASHRzlSH13_rawHashValue4seedSis6UInt64V_AHt_tFTW // protocol witness for Hashable._rawHashValue(seed:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Hashable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Decodable module synthesized_conformance_struct { // CHECK-NEXT: method #Decodable.init!allocator.1: <Self where Self : Decodable> (Self.Type) -> (Decoder) throws -> Self : @$S30synthesized_conformance_struct6StructVyxGSeAASeRzSERzlSe4fromxs7Decoder_p_tKcfCTW // protocol witness for Decodable.init(from:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: } // CHECK-LABEL: sil_witness_table hidden <T where T : Decodable, T : Encodable> Struct<T>: Encodable module synthesized_conformance_struct { // CHECK-NEXT: method #Encodable.encode!1: <Self where Self : Encodable> (Self) -> (Encoder) throws -> () : @$S30synthesized_conformance_struct6StructVyxGSEAASeRzSERzlSE6encode2toys7Encoder_p_tKFTW // protocol witness for Encodable.encode(to:) in conformance <A> Struct<A> // CHECK-NEXT: conditional_conformance (T: Decodable): dependent // CHECK-NEXT: conditional_conformance (T: Encodable): dependent // CHECK-NEXT: }
apache-2.0
05a689d4b6964335f1026dd71ee9ea6f
76.292683
298
0.72089
3.469075
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/SelectivePrivacySettingsController.swift
1
35992
// // SelectivePrivacySettingsController.swift // Telegram // // Created by keepcoder on 02/05/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Postbox enum SelectivePrivacySettingsKind { case presence case groupInvitations case voiceCalls case profilePhoto case forwards case phoneNumber case voiceMessages } private enum SelectivePrivacySettingType { case everybody case contacts case nobody init(_ setting: SelectivePrivacySettings) { switch setting { case .disableEveryone: self = .nobody case .enableContacts: self = .contacts case .enableEveryone: self = .everybody } } } enum SelectivePrivacySettingsPeerTarget { case main case callP2P } private final class SelectivePrivacySettingsControllerArguments { let context: AccountContext let updateType: (SelectivePrivacySettingType) -> Void let openEnableFor: (SelectivePrivacySettingsPeerTarget) -> Void let openDisableFor: (SelectivePrivacySettingsPeerTarget) -> Void let p2pMode: (SelectivePrivacySettingType) -> Void let updatePhoneDiscovery:(Bool)->Void init(context: AccountContext, updateType: @escaping (SelectivePrivacySettingType) -> Void, openEnableFor: @escaping (SelectivePrivacySettingsPeerTarget) -> Void, openDisableFor: @escaping (SelectivePrivacySettingsPeerTarget) -> Void, p2pMode: @escaping(SelectivePrivacySettingType) -> Void, updatePhoneDiscovery:@escaping(Bool)->Void) { self.context = context self.updateType = updateType self.openEnableFor = openEnableFor self.openDisableFor = openDisableFor self.updatePhoneDiscovery = updatePhoneDiscovery self.p2pMode = p2pMode } } private enum SelectivePrivacySettingsSection: Int32 { case setting case peers } private func stringForUserCount(_ count: Int) -> String { if count == 0 { return strings().privacySettingsControllerAddUsers } else { return strings().privacySettingsControllerUserCountCountable(count) } } private enum SelectivePrivacySettingsEntry: TableItemListNodeEntry { case settingHeader(Int32, String, GeneralViewType) case everybody(Int32, Bool, GeneralViewType) case contacts(Int32, Bool, GeneralViewType) case nobody(Int32, Bool, GeneralViewType) case p2pAlways(Int32, Bool, GeneralViewType) case p2pContacts(Int32, Bool, GeneralViewType) case p2pNever(Int32, Bool, GeneralViewType) case p2pHeader(Int32, String, GeneralViewType) case p2pDesc(Int32, String, GeneralViewType) case settingInfo(Int32, String, GeneralViewType) case disableFor(Int32, String, Int, GeneralViewType) case enableFor(Int32, String, Int, GeneralViewType) case p2pDisableFor(Int32, String, Int, GeneralViewType) case p2pEnableFor(Int32, String, Int, GeneralViewType) case p2pPeersInfo(Int32, GeneralViewType) case phoneDiscoveryHeader(Int32, String, GeneralViewType) case phoneDiscoveryEverybody(Int32, String, Bool, GeneralViewType) case phoneDiscoveryMyContacts(Int32, String, Bool, GeneralViewType) case phoneDiscoveryInfo(Int32, String, GeneralViewType) case peersInfo(Int32, GeneralViewType) case section(Int32) var stableId: Int32 { switch self { case .settingHeader: return 0 case .everybody: return 1 case .contacts: return 2 case .nobody: return 3 case .settingInfo: return 4 case .disableFor: return 5 case .enableFor: return 6 case .peersInfo: return 7 case .p2pHeader: return 8 case .p2pAlways: return 9 case .p2pContacts: return 10 case .p2pNever: return 11 case .p2pDesc: return 12 case .p2pDisableFor: return 13 case .p2pEnableFor: return 14 case .p2pPeersInfo: return 15 case .phoneDiscoveryHeader: return 16 case .phoneDiscoveryEverybody: return 17 case .phoneDiscoveryMyContacts: return 18 case .phoneDiscoveryInfo: return 19 case .section(let sectionId): return (sectionId + 1) * 1000 - sectionId } } var index:Int32 { switch self { case .settingHeader(let sectionId, _, _): return (sectionId * 1000) + stableId case .everybody(let sectionId, _, _): return (sectionId * 1000) + stableId case .contacts(let sectionId, _, _): return (sectionId * 1000) + stableId case .nobody(let sectionId, _, _): return (sectionId * 1000) + stableId case .settingInfo(let sectionId, _, _): return (sectionId * 1000) + stableId case .disableFor(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .enableFor(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .peersInfo(let sectionId, _): return (sectionId * 1000) + stableId case .p2pAlways(let sectionId, _, _): return (sectionId * 1000) + stableId case .p2pContacts(let sectionId, _, _): return (sectionId * 1000) + stableId case .p2pNever(let sectionId, _, _): return (sectionId * 1000) + stableId case .p2pHeader(let sectionId, _, _): return (sectionId * 1000) + stableId case .p2pDesc(let sectionId, _, _): return (sectionId * 1000) + stableId case .p2pDisableFor(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .p2pEnableFor(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .p2pPeersInfo(let sectionId, _): return (sectionId * 1000) + stableId case .phoneDiscoveryHeader(let sectionId, _, _): return (sectionId * 1000) + stableId case .phoneDiscoveryEverybody(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .phoneDiscoveryMyContacts(let sectionId, _, _, _): return (sectionId * 1000) + stableId case .phoneDiscoveryInfo(let sectionId, _, _): return (sectionId * 1000) + stableId case .section(let sectionId): return (sectionId + 1) * 1000 - sectionId } } static func <(lhs: SelectivePrivacySettingsEntry, rhs: SelectivePrivacySettingsEntry) -> Bool { return lhs.index < rhs.index } func item(_ arguments: SelectivePrivacySettingsControllerArguments, initialSize: NSSize) -> TableRowItem { switch self { case let .settingHeader(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case let .everybody(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerEverbody, type: .selectable(value), viewType: viewType, action: { arguments.updateType(.everybody) }) case let .contacts(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerMyContacts, type: .selectable(value), viewType: viewType, action: { arguments.updateType(.contacts) }) case let .nobody(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerNobody, type: .selectable(value), viewType: viewType, action: { arguments.updateType(.nobody) }) case let .p2pHeader(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case let .p2pAlways(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerP2pAlways, type: .selectable(value), viewType: viewType, action: { arguments.p2pMode(.everybody) }) case let .p2pContacts(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerP2pContacts, type: .selectable(value), viewType: viewType, action: { arguments.p2pMode(.contacts) }) case let .p2pNever(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsControllerP2pNever, type: .selectable(value), viewType: viewType, action: { arguments.p2pMode(.nobody) }) case let .p2pDesc(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case let .settingInfo(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case let .disableFor(_, title, count, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .context(stringForUserCount(count)), viewType: viewType, action: { arguments.openDisableFor(.main) }) case let .enableFor(_, title, count, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .context(stringForUserCount(count)), viewType: viewType, action: { arguments.openEnableFor(.main) }) case let .peersInfo(_, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: strings().privacySettingsControllerPeerInfo, viewType: viewType) case let .p2pDisableFor(_, title, count, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .context(stringForUserCount(count)), viewType: viewType, action: { arguments.openDisableFor(.callP2P) }) case let .p2pEnableFor(_, title, count, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .context(stringForUserCount(count)), viewType: viewType, action: { arguments.openEnableFor(.callP2P) }) case let .p2pPeersInfo(_, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: strings().privacySettingsControllerPeerInfo, viewType: viewType) case let .phoneDiscoveryHeader(_, title, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: title, viewType: viewType) case let .phoneDiscoveryEverybody(_, title, selected, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .selectable(selected), viewType: viewType, action: { arguments.updatePhoneDiscovery(true) }) case let .phoneDiscoveryMyContacts(_, title, selected, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: title, type: .selectable(selected), viewType: viewType, action: { arguments.updatePhoneDiscovery(false) }) case let .phoneDiscoveryInfo(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case .section: return GeneralRowItem(initialSize, height: 30, stableId: stableId, viewType: .separator) } } } private struct SelectivePrivacySettingsControllerState: Equatable { let setting: SelectivePrivacySettingType let enableFor: [PeerId: SelectivePrivacyPeer] let disableFor: [PeerId: SelectivePrivacyPeer] let saving: Bool let callP2PMode: SelectivePrivacySettingType? let callP2PEnableFor: [PeerId: SelectivePrivacyPeer] let callP2PDisableFor: [PeerId: SelectivePrivacyPeer] let phoneDiscoveryEnabled: Bool? init(setting: SelectivePrivacySettingType, enableFor: [PeerId: SelectivePrivacyPeer], disableFor: [PeerId: SelectivePrivacyPeer], saving: Bool, callP2PMode: SelectivePrivacySettingType?, callP2PEnableFor: [PeerId: SelectivePrivacyPeer], callP2PDisableFor: [PeerId: SelectivePrivacyPeer], phoneDiscoveryEnabled: Bool?) { self.setting = setting self.enableFor = enableFor self.disableFor = disableFor self.saving = saving self.callP2PMode = callP2PMode self.callP2PEnableFor = callP2PEnableFor self.callP2PDisableFor = callP2PDisableFor self.phoneDiscoveryEnabled = phoneDiscoveryEnabled } func withUpdatedSetting(_ setting: SelectivePrivacySettingType) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedEnableFor(_ enableFor: [PeerId: SelectivePrivacyPeer]) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedDisableFor(_ disableFor: [PeerId: SelectivePrivacyPeer]) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedSaving(_ saving: Bool) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedCallP2PMode(_ mode: SelectivePrivacySettingType) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: mode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedCallP2PEnableFor(_ enableFor: [PeerId: SelectivePrivacyPeer]) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: enableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedCallP2PDisableFor(_ disableFor: [PeerId: SelectivePrivacyPeer]) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: disableFor, phoneDiscoveryEnabled: self.phoneDiscoveryEnabled) } func withUpdatedPhoneDiscoveryEnabled(_ phoneDiscoveryEnabled: Bool?) -> SelectivePrivacySettingsControllerState { return SelectivePrivacySettingsControllerState(setting: self.setting, enableFor: self.enableFor, disableFor: self.disableFor, saving: self.saving, callP2PMode: self.callP2PMode, callP2PEnableFor: self.callP2PEnableFor, callP2PDisableFor: self.callP2PDisableFor, phoneDiscoveryEnabled: phoneDiscoveryEnabled) } } private func selectivePrivacySettingsControllerEntries(kind: SelectivePrivacySettingsKind, state: SelectivePrivacySettingsControllerState) -> [SelectivePrivacySettingsEntry] { var entries: [SelectivePrivacySettingsEntry] = [] var sectionId:Int32 = 1 entries.append(.section(sectionId)) sectionId += 1 let settingTitle: String let settingInfoText: String? let disableForText: String let enableForText: String switch kind { case .presence: settingTitle = strings().privacySettingsControllerLastSeenHeader settingInfoText = strings().privacySettingsControllerLastSeenDescription disableForText = strings().privacySettingsControllerNeverShareWith enableForText = strings().privacySettingsControllerAlwaysShareWith case .groupInvitations: settingTitle = strings().privacySettingsControllerGroupHeader settingInfoText = strings().privacySettingsControllerGroupDescription disableForText = strings().privacySettingsControllerNeverAllow enableForText = strings().privacySettingsControllerAlwaysAllow case .voiceCalls: settingTitle = strings().privacySettingsControllerPhoneCallHeader settingInfoText = strings().privacySettingsControllerPhoneCallDescription disableForText = strings().privacySettingsControllerNeverAllow enableForText = strings().privacySettingsControllerAlwaysAllow case .voiceMessages: settingTitle = strings().privacySettingsControllerVoiceMessagesHeader settingInfoText = strings().privacySettingsControllerVoiceMessagesDescription disableForText = strings().privacySettingsControllerNeverAllow enableForText = strings().privacySettingsControllerAlwaysAllow case .profilePhoto: settingTitle = strings().privacySettingsControllerProfilePhotoWhoCanSeeMyPhoto settingInfoText = strings().privacySettingsControllerProfilePhotoCustomHelp disableForText = strings().privacySettingsControllerNeverShareWith enableForText = strings().privacySettingsControllerAlwaysShareWith case .forwards: settingTitle = strings().privacySettingsControllerForwardsWhoCanForward settingInfoText = strings().privacySettingsControllerForwardsCustomHelp disableForText = strings().privacySettingsControllerNeverAllow enableForText = strings().privacySettingsControllerAlwaysAllow case .phoneNumber: if state.setting == .nobody { settingInfoText = nil } else { settingInfoText = strings().privacySettingsControllerPhoneNumberCustomHelp } settingTitle = strings().privacySettingsControllerPhoneNumberWhoCanSeePhoneNumber disableForText = strings().privacySettingsControllerNeverShareWith enableForText = strings().privacySettingsControllerAlwaysShareWith } entries.append(.settingHeader(sectionId, settingTitle, .textTopItem)) entries.append(.everybody(sectionId, state.setting == .everybody, .firstItem)) switch kind { case .presence, .voiceCalls, .forwards, .phoneNumber: entries.append(.contacts(sectionId, state.setting == .contacts, .innerItem)) entries.append(.nobody(sectionId, state.setting == .nobody, .lastItem)) default: entries.append(.contacts(sectionId, state.setting == .contacts, .lastItem)) } if let settingInfoText = settingInfoText { entries.append(.settingInfo(sectionId, settingInfoText, .textBottomItem)) } entries.append(.section(sectionId)) sectionId += 1 if case .phoneNumber = kind, state.setting == .nobody { entries.append(.phoneDiscoveryHeader(sectionId, strings().privacyPhoneNumberSettingsDiscoveryHeader, .textTopItem)) entries.append(.phoneDiscoveryEverybody(sectionId, strings().privacySettingsControllerEverbody, state.phoneDiscoveryEnabled != false, .firstItem)) entries.append(.phoneDiscoveryMyContacts(sectionId, strings().privacySettingsControllerMyContacts, state.phoneDiscoveryEnabled == false, .lastItem)) entries.append(.phoneDiscoveryInfo(sectionId, strings().privacyPhoneNumberSettingsCustomDisabledHelp, .textBottomItem)) entries.append(.section(sectionId)) sectionId += 1 } switch state.setting { case .everybody: entries.append(.disableFor(sectionId, disableForText, countForSelectivePeers(state.disableFor), .singleItem)) case .contacts: entries.append(.disableFor(sectionId, disableForText, countForSelectivePeers(state.disableFor), .firstItem)) entries.append(.enableFor(sectionId, enableForText, countForSelectivePeers(state.enableFor), .lastItem)) case .nobody: entries.append(.enableFor(sectionId, enableForText, countForSelectivePeers(state.enableFor), .singleItem)) } entries.append(.peersInfo(sectionId, .textBottomItem)) if let callSettings = state.callP2PMode { switch kind { case .voiceCalls: entries.append(.section(sectionId)) sectionId += 1 entries.append(.p2pHeader(sectionId, strings().privacySettingsControllerP2pHeader, .textTopItem)) entries.append(.p2pAlways(sectionId, callSettings == .everybody, .firstItem)) entries.append(.p2pContacts(sectionId, callSettings == .contacts, .innerItem)) entries.append(.p2pNever(sectionId, callSettings == .nobody, .lastItem)) entries.append(.p2pDesc(sectionId, strings().privacySettingsControllerP2pDesc, .textBottomItem)) entries.append(.section(sectionId)) sectionId += 1 switch callSettings { case .everybody: entries.append(.p2pDisableFor(sectionId, disableForText, countForSelectivePeers(state.callP2PDisableFor), .singleItem)) case .contacts: entries.append(.p2pDisableFor(sectionId, disableForText, countForSelectivePeers(state.callP2PDisableFor), .firstItem)) entries.append(.p2pEnableFor(sectionId, enableForText, countForSelectivePeers(state.callP2PEnableFor), .lastItem)) case .nobody: entries.append(.p2pEnableFor(sectionId, enableForText, countForSelectivePeers(state.callP2PEnableFor), .singleItem)) } entries.append(.p2pPeersInfo(sectionId, .textBottomItem)) default: break } } entries.append(.section(sectionId)) sectionId += 1 return entries } fileprivate func prepareTransition(left:[SelectivePrivacySettingsEntry], right: [SelectivePrivacySettingsEntry], initialSize:NSSize, arguments:SelectivePrivacySettingsControllerArguments) -> TableUpdateTransition { let (removed, inserted, updated) = proccessEntriesWithoutReverse(left, right: right) { entry -> TableRowItem in return entry.item(arguments, initialSize: initialSize) } return TableUpdateTransition(deleted: removed, inserted: inserted, updated: updated, animated: true) } class SelectivePrivacySettingsController: TableViewController { private let kind: SelectivePrivacySettingsKind private let current: SelectivePrivacySettings private let updated: (SelectivePrivacySettings, SelectivePrivacySettings?, Bool?) -> Void private var savePressed:(()->Void)? private let callSettings: SelectivePrivacySettings? private let phoneDiscoveryEnabled: Bool? init(_ context: AccountContext, kind: SelectivePrivacySettingsKind, current: SelectivePrivacySettings, callSettings: SelectivePrivacySettings? = nil, phoneDiscoveryEnabled: Bool?, updated: @escaping (SelectivePrivacySettings, SelectivePrivacySettings?, Bool?) -> Void) { self.kind = kind self.current = current self.updated = updated self.phoneDiscoveryEnabled = phoneDiscoveryEnabled self.callSettings = callSettings super.init(context) } override func viewDidLoad() { super.viewDidLoad() let context = self.context let kind = self.kind let current = self.current let updated = self.updated let initialSize = self.atomicSize let previous:Atomic<[SelectivePrivacySettingsEntry]> = Atomic(value: []) var initialEnableFor: [PeerId: SelectivePrivacyPeer] = [:] var initialDisableFor: [PeerId: SelectivePrivacyPeer] = [:] switch current { case let .disableEveryone(enableFor): initialEnableFor = enableFor case let .enableContacts(enableFor, disableFor): initialEnableFor = enableFor initialDisableFor = disableFor case let .enableEveryone(disableFor): initialDisableFor = disableFor } var initialCallP2PEnableFor: [PeerId: SelectivePrivacyPeer] = [:] var initialCallP2PDisableFor: [PeerId: SelectivePrivacyPeer] = [:] if let callCurrent = callSettings { switch callCurrent { case let .disableEveryone(enableFor): initialCallP2PEnableFor = enableFor initialCallP2PDisableFor = [:] case let .enableContacts(enableFor, disableFor): initialCallP2PEnableFor = enableFor initialCallP2PDisableFor = disableFor case let .enableEveryone(disableFor): initialCallP2PEnableFor = [:] initialCallP2PDisableFor = disableFor } } let initialState = SelectivePrivacySettingsControllerState(setting: SelectivePrivacySettingType(current), enableFor: initialEnableFor, disableFor: initialDisableFor, saving: false, callP2PMode: callSettings != nil ? SelectivePrivacySettingType(callSettings!) : nil, callP2PEnableFor: initialCallP2PEnableFor, callP2PDisableFor: initialCallP2PDisableFor, phoneDiscoveryEnabled: phoneDiscoveryEnabled) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((SelectivePrivacySettingsControllerState) -> SelectivePrivacySettingsControllerState) -> Void = { f in statePromise.set(stateValue.modify { f($0) }) } var dismissImpl: (() -> Void)? var pushControllerImpl: ((ViewController) -> Void)? let actionsDisposable = DisposableSet() let updateSettingsDisposable = MetaDisposable() // actionsDisposable.add(updateSettingsDisposable) let arguments = SelectivePrivacySettingsControllerArguments(context: context, updateType: { type in updateState { $0.withUpdatedSetting(type) } }, openEnableFor: { target in let title: String switch kind { case .presence: title = strings().privacySettingsControllerAlwaysShare case .groupInvitations: title = strings().privacySettingsControllerAlwaysAllow case .voiceCalls: title = strings().privacySettingsControllerAlwaysAllow case .profilePhoto: title = strings().privacySettingsControllerAlwaysShare case .forwards: title = strings().privacySettingsControllerAlwaysAllow case .phoneNumber: title = strings().privacySettingsControllerAlwaysShareWith case .voiceMessages: title = strings().privacySettingsControllerAlwaysAllow } var peerIds:[PeerId: SelectivePrivacyPeer] = [:] updateState { state in peerIds = state.enableFor return state } pushControllerImpl?(SelectivePrivacySettingsPeersController(context, title: title, initialPeers: peerIds, updated: { updatedPeerIds in updateState { state in switch target { case .main: var disableFor = state.disableFor for (key, _) in updatedPeerIds { disableFor.removeValue(forKey: key) } return state.withUpdatedEnableFor(updatedPeerIds).withUpdatedDisableFor(disableFor) case .callP2P: var callP2PDisableFor = state.callP2PDisableFor //var disableFor = state.disableFor for (key, _) in updatedPeerIds { callP2PDisableFor.removeValue(forKey: key) } return state.withUpdatedCallP2PEnableFor(updatedPeerIds).withUpdatedCallP2PDisableFor(callP2PDisableFor) } } })) }, openDisableFor: { target in let title: String switch kind { case .presence: title = strings().privacySettingsControllerNeverShareWith case .groupInvitations: title = strings().privacySettingsControllerNeverAllow case .voiceCalls: title = strings().privacySettingsControllerNeverAllow case .voiceMessages: title = strings().privacySettingsControllerNeverAllow case .profilePhoto: title = strings().privacySettingsControllerNeverShareWith case .forwards: title = strings().privacySettingsControllerNeverAllow case .phoneNumber: title = strings().privacySettingsControllerNeverShareWith } var peerIds:[PeerId: SelectivePrivacyPeer] = [:] updateState { state in peerIds = state.disableFor return state } pushControllerImpl?(SelectivePrivacySettingsPeersController(context, title: title, initialPeers: peerIds, updated: { updatedPeerIds in updateState { state in switch target { case .main: var enableFor = state.enableFor for (key, _) in updatedPeerIds { enableFor.removeValue(forKey: key) } return state.withUpdatedDisableFor(updatedPeerIds).withUpdatedEnableFor(enableFor) case .callP2P: var callP2PEnableFor = state.callP2PEnableFor for (key, _) in updatedPeerIds { callP2PEnableFor.removeValue(forKey: key) } return state.withUpdatedCallP2PDisableFor(updatedPeerIds).withUpdatedCallP2PEnableFor(callP2PEnableFor) } } })) }, p2pMode: { mode in updateState { state in return state.withUpdatedCallP2PMode(mode) } }, updatePhoneDiscovery: { value in updateState { state in return state.withUpdatedPhoneDiscoveryEnabled(value) } }) savePressed = { var wasSaving = false var settings: SelectivePrivacySettings? var callSettings: SelectivePrivacySettings? var phoneDiscoveryEnabled: Bool? = nil updateState { state in phoneDiscoveryEnabled = state.phoneDiscoveryEnabled wasSaving = state.saving switch state.setting { case .everybody: settings = SelectivePrivacySettings.enableEveryone(disableFor: state.disableFor) case .contacts: settings = SelectivePrivacySettings.enableContacts(enableFor: state.enableFor, disableFor: state.disableFor) case .nobody: settings = SelectivePrivacySettings.disableEveryone(enableFor: state.enableFor) } if let mode = state.callP2PMode { switch mode { case .everybody: callSettings = SelectivePrivacySettings.enableEveryone(disableFor: state.callP2PDisableFor) case .contacts: callSettings = SelectivePrivacySettings.enableContacts(enableFor: state.callP2PEnableFor, disableFor: state.callP2PDisableFor) case .nobody: callSettings = SelectivePrivacySettings.disableEveryone(enableFor: state.callP2PEnableFor) } } return state.withUpdatedSaving(true) } if let settings = settings, !wasSaving { let type: UpdateSelectiveAccountPrivacySettingsType switch kind { case .presence: type = .presence case .groupInvitations: type = .groupInvitations case .voiceCalls: type = .voiceCalls case .profilePhoto: type = .profilePhoto case .forwards: type = .forwards case .phoneNumber: type = .phoneNumber case .voiceMessages: type = .voiceMessages } var updatePhoneDiscoverySignal: Signal<Void, NoError> = Signal.complete() if let phoneDiscoveryEnabled = phoneDiscoveryEnabled { updatePhoneDiscoverySignal = context.engine.privacy.updatePhoneNumberDiscovery(value: phoneDiscoveryEnabled) } let basic = context.engine.privacy.updateSelectiveAccountPrivacySettings(type: type, settings: settings) updateSettingsDisposable.set(combineLatest(queue: .mainQueue(), updatePhoneDiscoverySignal, basic).start(completed: { updateState { state in return state.withUpdatedSaving(false) } updated(settings, callSettings, phoneDiscoveryEnabled) dismissImpl?() })) } } let signal = statePromise.get() |> deliverOnMainQueue |> map { [weak self] state -> TableUpdateTransition in let title: String switch kind { case .presence: title = strings().privacySettingsLastSeen case .groupInvitations: title = strings().privacySettingsGroups case .voiceCalls: title = strings().privacySettingsVoiceCalls case .profilePhoto: title = strings().privacySettingsProfilePhoto case .forwards: title = strings().privacySettingsForwards case .phoneNumber: title = strings().privacySettingsPhoneNumber case .voiceMessages: title = strings().privacySettingsVoiceMessages } self?.setCenterTitle(title) let entries = selectivePrivacySettingsControllerEntries(kind: kind, state: state) return prepareTransition(left: previous.swap(entries), right: entries, initialSize: initialSize.modify{$0}, arguments: arguments) } |> afterDisposed { actionsDisposable.dispose() } genericView.merge(with: signal) readyOnce() pushControllerImpl = { [weak self] c in self?.navigationController?.push(c) } dismissImpl = { [weak self] in if self?.navigationController?.controller == self { self?.navigationController?.back() } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func didRemovedFromStack() { super.didRemovedFromStack() savePressed?() } }
gpl-2.0
10172077f1d063b1f215a2503f2fef51
48.235294
407
0.671918
4.916132
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleViewController+Sharing.swift
1
2982
extension ArticleViewController { func shareArticle() { themesPresenter.dismissReadingThemesPopoverIfActive(from: self) webView.wmf_getSelectedText({ [weak self] selectedText in guard let self = self else { return } self.shareArticle(with: selectedText) }) } func shareArticle(with selectedText: String?) { var activities: [UIActivity] = [] let readingListActivity = addToReadingListActivity(with: self, eventLogAction: { self.readingListsFunnel.logArticleSaveInCurrentArticle(self.articleURL) }) activities.append(readingListActivity) if let text = selectedText, !text.isEmpty { let shareAFactActivity = CustomShareActivity(title: "Share-a-fact", imageName: "share-a-fact", action: { self.shareFunnel?.logHighlight() self.shareAFact(with: text) }) activities.append(shareAFactActivity) } guard let vc = sharingActivityViewController(with: selectedText, button: toolbarController.shareButton, shareFunnel: shareFunnel, customActivities: activities) else { return } present(vc, animated: true) } func sharingActivityViewController(with textSnippet: String?, button: UIBarButtonItem, shareFunnel: WMFShareFunnel?, customActivities: [UIActivity]?) -> ShareActivityController? { shareFunnel?.logShareButtonTappedResulting(inSelection: textSnippet) let vc: ShareActivityController let textActivitySource = WMFArticleTextActivitySource(article: article, shareText: textSnippet) if let customActivities = customActivities, !customActivities.isEmpty { vc = ShareActivityController(customActivities: customActivities, article: article, textActivitySource: textActivitySource) } else { vc = ShareActivityController(article: article, textActivitySource: textActivitySource) } vc.popoverPresentationController?.barButtonItem = button return vc } func shareAFact(with text: String) { guard let shareViewController = ShareViewController(text: text, article: article, theme: theme) else { return } present(shareViewController, animated: true) } func addToReadingListActivity(with presenter: UIViewController, eventLogAction: @escaping () -> Void) -> UIActivity { let addToReadingListActivity = AddToReadingListActivity { let vc = AddArticlesToReadingListViewController(with: self.dataStore, articles: [self.article], theme: self.theme) vc.eventLogAction = eventLogAction let nc = WMFThemeableNavigationController(rootViewController: vc, theme: self.theme) nc.setNavigationBarHidden(true, animated: false) presenter.present(nc, animated: true) } return addToReadingListActivity } }
mit
9b99b7ef5b32176692e1e7445c512d58
44.876923
183
0.677733
5.213287
false
false
false
false
rebe1one/alertcontroller
Source/WMAlertController.swift
1
17880
/* * Copyright 2017 the original author or authors. * * 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 open class WMAlertController: UIViewController, StackedViewDelegate { public var backgroundView: UIView! var alertView: RoundView! public var scrollView: UIScrollView! public var contentStack: StackedView! public var buttonStackSeparator: UIView! public var buttonStack: StackedView! var buttonSeparators: [UIView]! var loadingView: LoadingView! public var customView: UIView? public var customViewInsets: UIEdgeInsets = UIEdgeInsets.zero public var titleLabel: UILabel? public var messageLabel: UILabel? public var message: String? public var loading: Bool = false { didSet { if loading { alertView.bringSubviewToFront(loadingView) loadingView.isHidden = false loadingView.activityIndicator.startAnimating() } else { alertView.sendSubviewToBack(loadingView) loadingView.isHidden = true loadingView.activityIndicator.stopAnimating() } } } public var actions = [WMAlertAction]() var style: WMAlertStyle = WMAlertStyle.dark func setStyle(_ style: WMAlertStyle) { self.style = style } public var decoration: WMAlertDecoration = .none public init(title: String?, message: String?, style: WMAlertStyle = .dark, decoration: WMAlertDecoration = .none) { super.init(nibName: nil, bundle: nil) self.title = title self.message = message self.setStyle(style) self.decoration = decoration self.modalPresentationStyle = .overFullScreen self.modalTransitionStyle = .crossDissolve registerForKeyboardNotification() self.initViews() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) registerForKeyboardNotification() self.initViews() } func initViews() { backgroundView = UIView() alertView = RoundView() loadingView = LoadingView() scrollView = UIScrollView() contentStack = StackedView() contentStack.delegate = self buttonStack = StackedView(direction: .horizontal) buttonStack.delegate = self buttonStackSeparator = UIView() buttonSeparators = [UIView]() if let _ = self.title { titleLabel = UILabel() titleLabel?.textAlignment = .center } if let _ = self.message { messageLabel = UILabel() messageLabel?.textAlignment = .center } } open func didInitViews() { // used by subclasses to initialize a custom view } var alertVerticalCenterConstraint: NSLayoutConstraint? var alertVerticalMarginConstraints: [NSLayoutConstraint]? var scrollViewHeightConstraint: NSLayoutConstraint? var alertViewMargin: CGFloat = 25 func layoutViews() { backgroundView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(backgroundView) self.view.constrainSubviewToSize(backgroundView) layoutAlertView() loadingView.translatesAutoresizingMaskIntoConstraints = false loadingView.isHidden = true alertView.addSubview(loadingView) alertView.constrainSubviewToSize(loadingView) scrollView.translatesAutoresizingMaskIntoConstraints = false alertView.addSubview(scrollView) contentStack.translatesAutoresizingMaskIntoConstraints = false contentStack.clipsToBounds = false scrollView.addSubview(contentStack) scrollView.constrainSubviewToSize(contentStack) NSLayoutConstraint.activate([ scrollView.widthAnchor.constraint(equalTo: contentStack.widthAnchor), scrollView.heightAnchor.constraint(equalTo: contentStack.heightAnchor) ]) switch decoration { case .none: alertView.constrainSubviewToSize(scrollView, insets: UIEdgeInsets.zero) default: alertView.constrainSubviewToSize( scrollView, insets: UIEdgeInsets(top: circleSize / 2, left: 0, bottom: 0, right: 0) ) setupCircleView() } setupDefaultLabels() // custom stuff if let customView = self.customView { contentStack.addSubview(customView) } if actions.count > 0 { setupButtons() constrainAlertViewWithButtons() } } fileprivate func layoutAlertView() { alertView.translatesAutoresizingMaskIntoConstraints = false alertView.clipsToBounds = false view.addSubview(alertView) view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|-margin-[alertView]-margin-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: ["margin": alertViewMargin], views: ["alertView": alertView!] ) ) let centerConstraint = NSLayoutConstraint( item: alertView!, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0 ) alertVerticalCenterConstraint = centerConstraint view.addConstraint(centerConstraint) } fileprivate func constrainAlertViewWithButtons() { let bottomConstraints = alertView.constraints.filter { (constraint) -> Bool in return constraint.secondItem === scrollView && constraint.firstAttribute == .bottom } for constraint in bottomConstraints { constraint.isActive = false } alertView.addConstraints(NSLayoutConstraint.constraints( withVisualFormat: "V:[scrollView]-0-[buttonStackSeparator]-0-[buttonStack]-0-|", options: [.alignAllLeft, .alignAllRight], metrics: nil, views: [ "scrollView": scrollView!, "buttonStackSeparator": buttonStackSeparator!, "buttonStack": buttonStack! ])) } fileprivate func setupButtons() { buttonStackSeparator.translatesAutoresizingMaskIntoConstraints = false _ = buttonStackSeparator.addHeightConstraint(constant: 0.5) alertView.addSubview(buttonStackSeparator) buttonStack.translatesAutoresizingMaskIntoConstraints = false alertView.addSubview(buttonStack) let direction: StackedViewDirection = actions.count > 2 ? .vertical : .horizontal buttonStack.direction = direction for action in actions { let button = createButton(forAction: action) if buttonStack.subviews.count > 0 { let separator = UIView() separator.translatesAutoresizingMaskIntoConstraints = false if direction == .horizontal { _ = separator.addWidthConstraint(constant: 0.5) } else { _ = separator.addHeightConstraint(constant: 0.5) } buttonSeparators.append(separator) buttonStack.addSubview(separator) } buttonStack.addSubview(button) } if actions.count == 2, let button1 = buttonStack.subviews.first, let button2 = buttonStack.subviews.last, buttonStack.subviews.count == 3 { NSLayoutConstraint.activate( [NSLayoutConstraint( item: button1, attribute: .width, relatedBy: .equal, toItem: button2, attribute: .width, multiplier: 1, constant: 0) ] ) } } let circleView = UIView() var circleSize: CGFloat = 110 fileprivate func setupCircleView() { circleView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(circleView) view.addConstraint(NSLayoutConstraint( item: circleView, attribute: .centerX, relatedBy: .equal, toItem: alertView, attribute: .centerX, multiplier: 1, constant: 0) ) view.addConstraint(NSLayoutConstraint( item: circleView, attribute: .centerY, relatedBy: .equal, toItem: alertView, attribute: .top, multiplier: 1, constant: 0) ) _ = circleView.addHeightConstraint(constant: circleSize) _ = circleView.addWidthConstraint(constant: circleSize) let borderWidth: CGFloat = 15 circleView.layer.cornerRadius = circleSize / 2 circleView.backgroundColor = UIColor.white circleView.clipsToBounds = true circleView.layer.borderWidth = borderWidth circleView.layer.borderColor = UIColor.white.cgColor let iconImage = WMAlertIconStyleKit.imageOfCheckmark let circleIconView = UIImageView(image: iconImage.withRenderingMode(.alwaysTemplate)) circleIconView.tintColor = UIColor.darkMint() circleIconView.backgroundColor = UIColor.clear circleIconView.layer.cornerRadius = (circleSize - borderWidth - borderWidth) / 2 circleIconView.translatesAutoresizingMaskIntoConstraints = false circleView.addSubview(circleIconView) circleView.constrainSubviewToSize( circleIconView, insets: UIEdgeInsets( top: borderWidth, left: borderWidth, bottom: borderWidth, right: borderWidth ) ) } fileprivate func setupDefaultLabels() { if let titleLabel = titleLabel, let title = self.title { if let titleAttributes = style.titleAttributes { let attributedString = NSAttributedString(string: title, attributes: titleAttributes) titleLabel.attributedText = attributedString } else { titleLabel.text = title } contentStack.addSubview(titleLabel) } if let messageLabel = messageLabel, let message = self.message { if let messageAttributes = style.messageAttributes { let attributedString = NSAttributedString(string: message, attributes: messageAttributes) messageLabel.attributedText = attributedString } else { messageLabel.text = message } contentStack.addSubview(messageLabel) } } override open func viewDidLoad() { super.viewDidLoad() self.presentingViewController?.view.endEditing(true) layoutViews() applyStyle() } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if alertView.frame.height > view.bounds.height - (alertViewMargin * 2) { scrollViewHeightConstraint?.isActive = false let marginConstraints = NSLayoutConstraint.constraints( withVisualFormat: "V:|-margin-[alertView]-margin-|", options: NSLayoutConstraint.FormatOptions(rawValue: 0), metrics: ["margin": alertViewMargin], views: ["alertView": alertView!] ) alertVerticalMarginConstraints = marginConstraints view.addConstraints(marginConstraints) view.setNeedsUpdateConstraints() view.layoutIfNeeded() } } func applyStyle() { backgroundView.backgroundColor = style.overlayBackgroundColor alertView.backgroundColor = style.backgroundColor alertView.cornerRadius = style.cornerRadius titleLabel?.font = style.titleFont titleLabel?.textColor = style.titleTextColor titleLabel?.numberOfLines = style.titleNumberOfLines messageLabel?.font = style.messageFont messageLabel?.textColor = style.messageTextColor messageLabel?.numberOfLines = style.messageNumberOfLines buttonStackSeparator.backgroundColor = style.separatorColor for separator in buttonSeparators { separator.backgroundColor = style.separatorColor } } public func addAction(_ action: WMAlertAction) { actions.append(action) action.alert = self } public func actionWithTitle(_ title: String) -> WMAlertAction? { for action in actions { if action.title == title { return action } } return nil } func prepareForPresentation() { layoutViews() applyStyle() } fileprivate func createButton(forAction action: WMAlertAction) -> UIButton { let button = UIButton() button.setTitleColor(UIColor.oceanBlue(), for: UIControl.State()) button.setTitle(action.title, for: UIControl.State()) button.titleLabel?.font = UIFont.semiboldSystemFontOfSize(14) button.addTarget(action, action: #selector(WMAlertAction.performAction), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false _ = button.addHeightConstraint(constant: 44) button.sizeToFit() return button } // MARK: StackedViewDelegate public func stackedView(_ stackedView: StackedView, spacingForView view: UIView) -> UIEdgeInsets { if stackedView === contentStack { if view === titleLabel { if decoration == .none { return UIEdgeInsets(top: 25, left: 27, bottom: 0, right: 27) } else { return UIEdgeInsets(top: 5, left: 27, bottom: 0, right: 27) } } else if view === messageLabel { return UIEdgeInsets(top: 15, left: 27, bottom: 30, right: 27) } else if view === customView { return customViewInsets } } return UIEdgeInsets.zero } // MARK: Keyboard Stuff var isKeyboardShown: Bool = false var keyboardHeight: CGFloat = 0 func registerForKeyboardNotification() { NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil ) } var maximumScrollViewHeightConstraint: NSLayoutConstraint? @objc func keyboardWillShow(_ notification: Foundation.Notification) { if let info = notification.userInfo, let keyboardFrame = (info[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue { keyboardHeight = keyboardFrame.height } let maxHeight = view.bounds.height - keyboardHeight if let constraints = self.alertVerticalMarginConstraints { for constraint in constraints { constraint.isActive = false } } if alertView.frame.height > maxHeight { alertVerticalCenterConstraint?.constant = -(keyboardHeight / 2) scrollViewHeightConstraint?.isActive = false maximumScrollViewHeightConstraint = scrollView.addHeightConstraint(constant: maxHeight) animateLayoutChange() } else { alertVerticalCenterConstraint?.constant = -(keyboardHeight / 2) animateLayoutChange() } isKeyboardShown = true } @objc func keyboardWillHide(_ notification: Foundation.Notification) { keyboardHeight = 0 isKeyboardShown = false alertVerticalCenterConstraint?.constant = 0 maximumScrollViewHeightConstraint?.isActive = false scrollViewHeightConstraint?.isActive = true if let constraints = self.alertVerticalMarginConstraints { for constraint in constraints { constraint.isActive = true } } animateLayoutChange() } deinit { NotificationCenter.default.removeObserver(self) } fileprivate func animateLayoutChange() { self.view.setNeedsUpdateConstraints() UIView.animate({ self.view.layoutIfNeeded() }) } override open var supportedInterfaceOrientations : UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } override open var shouldAutorotate : Bool { return false } }
apache-2.0
7c066cfce4ba992a1f50b9473e2bbcdc
34.058824
139
0.609116
6.034425
false
false
false
false
chamander/Sampling-Reactive
Source/Models/City.swift
2
524
// Copyright © 2016 Gavan Chan. All rights reserved. import Argo import Curry import Runes struct City { typealias Identifier = Int typealias Name = String let identifier: Identifier let name: Name } extension City: Decodable { static func decode(_ json: JSON) -> Decoded<City> { let identifier: Decoded<Identifier> = json <| "id" let name: Decoded<Name> = json <| "name" let initialiser: ((Identifier) -> (Name) -> City) = curry(City.init) return initialiser <^> identifier <*> name } }
mit
f44d58182c3f69e91f8caf146bb3833c
20.791667
72
0.671128
3.932331
false
false
false
false
TwilioDevEd/twiliochat-swift
twiliochat/LoginViewController.swift
1
3521
import UIKit class LoginViewController: UIViewController { @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! // MARK: - Injectable Properties var alertDialogControllerClass = AlertDialogController.self var MessagingClientClass = MessagingManager.self // MARK: - Initialization var textFieldFormHandler: TextFieldFormHandler! override func viewDidLoad() { super.viewDidLoad() initializeTextFields() } func initializeTextFields() { let textFields: [UITextField] = [usernameTextField] textFieldFormHandler = TextFieldFormHandler(withTextFields: textFields, topContainer: view) textFieldFormHandler.delegate = self } func resetFirstResponderOnSignUpModeChange() { self.view.layoutSubviews() if let index = self.textFieldFormHandler.firstResponderIndex { if (index > 1) { textFieldFormHandler.setTextFieldAtIndexAsFirstResponder(index: 1) } else { textFieldFormHandler.resetScroll() } } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) textFieldFormHandler.cleanUp() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Actions @IBAction func loginButtonTouched(_ sender: UIButton) { loginUser() } // MARK: - Login func loginUser() { if (validUserData()) { view.isUserInteractionEnabled = false activityIndicator.startAnimating() let MessagingManager = MessagingClientClass.sharedManager() if let username = usernameTextField.text { MessagingManager.loginWithUsername(username: username, completion: handleResponse) } } } func validUserData() -> Bool { if let usernameEmpty = usernameTextField.text?.isEmpty, !usernameEmpty { return true } showError(message: "All fields are required") return false } func showError(message:String) { alertDialogControllerClass.showAlertWithMessage(message: message, title: nil, presenter: self) } func handleResponse(succeeded: Bool, error: NSError?) { DispatchQueue.main.async { self.activityIndicator.stopAnimating() if let error = error, !succeeded { self.showError(message: error.localizedDescription) } self.view.isUserInteractionEnabled = true } } // MARK: - Style override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if (UI_USER_INTERFACE_IDIOM() == .pad) { return .all } return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .portrait } } // MARK: - TextFieldFormHandlerDelegate extension LoginViewController : TextFieldFormHandlerDelegate { func textFieldFormHandlerDoneEnteringData(handler: TextFieldFormHandler) { loginUser() } }
mit
a00b231f941afdbd0e88c5f8441f6e6e
28.588235
102
0.636751
5.791118
false
false
false
false
bigscreen/mangindo-ios
Mangindo/Common/AppColor.swift
1
544
// // AppColor.swift // Mangindo // // Created by Gallant Pratama on 4/21/17. // Copyright © 2017 Gallant Pratama. All rights reserved. // import Foundation import UIKit class AppColor { static let blackPrimary = UIColor(red: 33, green: 33, blue: 33) static let blackPrimaryDark = UIColor(red: 22, green: 22, blue: 22) static let grey = UIColor(red: 206, green: 206, blue: 206) static let greyLight = UIColor(red: 244, green: 244, blue: 244) static let greyDark = UIColor(red: 188, green: 188, blue: 188) }
mit
504b791c410c6dbff8e842c8b250d77f
26.15
71
0.668508
3.290909
false
false
false
false
nunosans/currency
Currency/UI Classes/CalculatorClearButton.swift
1
2084
// // CalculatorClearButton.swift // Currency // // Created by Nuno Coelho Santos on 29/04/2016. // Copyright © 2016 Nuno Coelho Santos. All rights reserved. // import Foundation import UIKit class CalculatorClearButton: UIButton { let borderColor: CGColor! = UIColor(red:0.85, green:0.85, blue:0.85, alpha:1.00).cgColor let normalStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0).cgColor let highlightStateColor: CGColor! = UIColor(red:0, green:0, blue:0, alpha:0.08).cgColor required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setImage(UIImage(named: "buttonClearIconHighlighted.png"), for: .highlighted) self.layer.borderWidth = 0.25 self.layer.borderColor = borderColor self.layer.masksToBounds = true self.backgroundColor = UIColor(cgColor: normalStateColor) } override var isHighlighted: Bool { get { return super.isHighlighted } set { if newValue { let fadeIn = CABasicAnimation(keyPath: "backgroundColor") fadeIn.fromValue = normalStateColor fadeIn.toValue = highlightStateColor fadeIn.duration = 0.12 fadeIn.autoreverses = false fadeIn.repeatCount = 1 self.layer.add(fadeIn, forKey: "fadeIn") self.backgroundColor = UIColor(cgColor: highlightStateColor) } else { let fadeOut = CABasicAnimation(keyPath: "backgroundColor") fadeOut.fromValue = highlightStateColor fadeOut.toValue = normalStateColor fadeOut.duration = 0.12 fadeOut.autoreverses = false fadeOut.repeatCount = 1 self.layer.add(fadeOut, forKey: "fadeOut") self.backgroundColor = UIColor(cgColor: normalStateColor) } super.isHighlighted = newValue } } }
mit
d514ac0ae64e73e96d94890b9d4ca627
33.147541
92
0.585694
4.832947
false
false
false
false
GuiminChu/HishowZone-iOS
HiShow/Features/Topics/TopicItemCell.swift
1
4607
// // TopicItemCell.swift // HishowZone // // Created by Chu Guimin on 16/9/6. // Copyright © 2016年 Chu Guimin. All rights reserved. // import UIKit import Kingfisher //protocol TapImageViewDelegate { // func tapImageView(_ images: [SKPhoto]) //} extension UIView { private func kt_addCorner(radius: CGFloat, borderWidth: CGFloat, backgroundColor: UIColor, borderColor: UIColor) { let image = kt_drawRectWithRoundedCorner(radius: radius, borderWidth: borderWidth, backgroundColor: backgroundColor, borderColor: borderColor) let imageView = UIImageView(image: image) self.insertSubview(imageView, at: 0) } private func kt_drawRectWithRoundedCorner(radius: CGFloat, borderWidth: CGFloat, backgroundColor: UIColor, borderColor: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, true, UIScreen.main.scale) let context = UIGraphicsGetCurrentContext() context?.setAlpha(1) context?.setFillColor(backgroundColor.cgColor) context?.fill(self.bounds) let maskPath = UIBezierPath.init(roundedRect: self.bounds.insetBy(dx: 1, dy: 1), cornerRadius: radius) context?.setStrokeColor(borderColor.cgColor) maskPath.stroke() maskPath.lineWidth = borderWidth context?.addPath(maskPath.cgPath) context?.drawPath(using: .fillStroke) let output = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return output! } func cornerRadius(_ radius: CGFloat, borderWidth: CGFloat = 0, backgroundColor: UIColor = .clear, borderColor: UIColor = .clear) { self.kt_addCorner(radius: radius, borderWidth: borderWidth, backgroundColor: backgroundColor, borderColor: borderColor) } } final class TopicItemCell: UITableViewCell { // MARK: - Properties @IBOutlet weak var avatarImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var topicImageView: UIImageView! @IBOutlet weak var likeCountLabel: UILabel! // var images = [SKPhoto]() // var delegate: TapImageViewDelegate? @IBOutlet weak var containerView: UIView! var didSelectUser: ((_ cell: TopicItemCell) -> Void)? // MARK: - View Life Cycle override func awakeFromNib() { super.awakeFromNib() // Initialization code let avatarGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(didTapAvatar(_:))) avatarImageView.addGestureRecognizer(avatarGestureRecognizer) selectionStyle = .none containerView.cornerRadius(10) } override func prepareForReuse() { super.prepareForReuse() topicImageView.image = nil avatarImageView.image = nil } func configure(_ topicInfo: Topic) { nameLabel.text = topicInfo.author.name titleLabel.text = topicInfo.title likeCountLabel.text = "\(topicInfo.likeCount!)" if let photoAlt = topicInfo.photos.first?.alt, let url = URL(string: photoAlt) { topicImageView.kf.setImage(with: url, options: [KingfisherOptionsInfoItem.transition(ImageTransition.fade(0.25))]) } if let urlString = topicInfo.author.avatar, let url = URL(string: urlString) { let optionsInfo = [KingfisherOptionsInfoItem.transition(ImageTransition.fade(0.25)), KingfisherOptionsInfoItem.processor(RoundCornerImageProcessor(cornerRadius: 16))] avatarImageView.kf.setImage(with: url, options: optionsInfo) // avatarImageView.navi_setAvatar(RoundAvatar(avatarURL: url, avatarStyle: picoAvatarStyle), withFadeTransitionDuration: 0.25) } // for topicPhotoInfo in topicInfo.photos { // let photo = SKPhoto.photoWithImageURL(topicPhotoInfo.alt!) // photo.shouldCachePhotoURLImage = false // images.append(photo) // } } @objc func didTapAvatar(_ recognizer: UITapGestureRecognizer) { didSelectUser?(self) } }
mit
2f662b90a23ae453742432ec3b8b5fcc
36.430894
137
0.612294
5.347271
false
false
false
false
sundeepgupta/butterfly
butterfly/Constants.swift
1
361
public struct Constants { public static let storyboardName = "Main" public static let signOutNotificationName = "userSignedOut" public static let resetNotificationName = "reset" } public struct Keys { public static let email = "emailKey" public static let errorHash = "errorHashKey" public static let errorMessage = "errrorMessageKey" }
mit
cbd763c3f568d7422072936337e8c028
31.909091
63
0.745152
4.628205
false
false
false
false
ttlock/iOS_TTLock_Demo
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUPeripheralSelector.swift
3
2291
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import CoreBluetooth /// The default selector. Selects the first device with Legacy or Secure DFU Service UUID in the advertising packet. @objc open class DFUPeripheralSelector : NSObject, DFUPeripheralSelectorDelegate { open func select(_ peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber, hint name: String? = nil) -> Bool { // peripheral.name may be cached, use the name from advertising data if let name = name, let localName = advertisementData[CBAdvertisementDataLocalNameKey] as? String { return localName == name } return true } open func filterBy(hint dfuServiceUUID: CBUUID) -> [CBUUID]? { return [dfuServiceUUID] } }
mit
5856d0125c6ccd071d4b2417638d30bc
56.275
145
0.756875
5.057395
false
false
false
false
LawrenceHan/Games
SpriteKitPhysicsTest.playground/Contents.swift
1
3951
//: Playground - noun: a place where people can play import UIKit import SpriteKit import XCPlayground let sceneView = SKView(frame: CGRect(x: 0, y: 0, width: 480, height: 320)) let scene = SKScene(size: CGSize(width: 480, height: 320)) scene.physicsWorld.gravity = CGVector(dx: 0, dy: 0) scene.physicsBody = SKPhysicsBody(edgeLoopFromRect: scene.frame) sceneView.showsFPS = true sceneView.showsPhysics = true sceneView.presentScene(scene) XCPlaygroundPage.currentPage.liveView = sceneView let square = SKSpriteNode(imageNamed: "square") square.name = "shape" square.position = CGPoint(x: scene.size.width * 0.25, y: scene.size.height * 0.50) let circle = SKSpriteNode(imageNamed: "circle") circle.name = "shape" circle.position = CGPoint(x: scene.size.width * 0.50, y: scene.size.height * 0.50) let triangle = SKSpriteNode(imageNamed: "triangle") triangle.name = "shape" triangle.position = CGPoint(x: scene.size.width * 0.75, y: scene.size.height * 0.50) let l = SKSpriteNode(imageNamed: "L") l.name = "shape" l.position = CGPoint(x: scene.size.width * 0.5, y: scene.size.height * 0.75) l.physicsBody = SKPhysicsBody(texture: l.texture!, size: l.size) scene.addChild(l) scene.addChild(square) scene.addChild(circle) scene.addChild(triangle) circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.size.width/2) circle.physicsBody!.dynamic = false circle.runAction( SKAction.repeatActionForever( SKAction.sequence([ SKAction.moveToX(circle.size.width/2, duration: 2), SKAction.moveToX(scene.size.width - circle.size.width/2, duration: 2)])) ) square.physicsBody = SKPhysicsBody(rectangleOfSize: square.frame.size) var trianglePath = CGPathCreateMutable() CGPathMoveToPoint(trianglePath, nil, -triangle.size.width/2, -triangle.size.height/2) CGPathAddLineToPoint(trianglePath, nil, triangle.size.width/2, -triangle.size.height/2) CGPathAddLineToPoint(trianglePath, nil, 0, triangle.size.height/2) CGPathAddLineToPoint(trianglePath, nil, -triangle.size.width/2, -triangle.size.height/2) triangle.physicsBody = SKPhysicsBody(polygonFromPath: trianglePath) func spawnSand() { let sand = SKSpriteNode(imageNamed: "sand") sand.position = CGPoint(x: random(min: 0.0, max: scene.size.width), y: scene.size.height - sand.size.height) sand.physicsBody = SKPhysicsBody(circleOfRadius: sand.size.width/2) sand.name = "sand" scene.addChild(sand) sand.physicsBody!.restitution = 1.0 sand.physicsBody!.density = 20.0 } func shake() { scene.enumerateChildNodesWithName("sand") { node, _ in node.physicsBody!.applyImpulse(CGVector(dx: 0, dy: random(min: 20, max: 40))) } } delay(seconds: 2.0) { scene.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8) scene.runAction( SKAction.repeatAction( SKAction.sequence([ SKAction.runBlock(spawnSand), SKAction.waitForDuration(0.1) ]), count: 100)) delay(seconds: 12, completion: shake) } var blowingRight = true var windForce = CGVector(dx: 50, dy: 0) NSTimer.scheduledTimerWithTimeInterval(0.05, target: scene, selector: Selector("windWithTimer:"), userInfo: nil, repeats: true) NSTimer.scheduledTimerWithTimeInterval(3.0, target: scene, selector: Selector("switchWindDirection:"), userInfo: nil, repeats: true) extension SKScene { func windWithTimer(timer: NSTimer) { // TODO: apply force to all bodies enumerateChildNodesWithName("sand") { (node, _) in node.physicsBody!.applyForce(windForce) } enumerateChildNodesWithName("shape") { (node, _) in node.physicsBody!.applyForce(windForce) } } func switchWindDirection(timer: NSTimer) { blowingRight = !blowingRight windForce = CGVector(dx: blowingRight ? 50 : -50, dy: 0) } }
mit
291d1ad531a39d05c72b8b1d7e29f01a
34.276786
132
0.687927
3.759277
false
false
false
false
toggl/superday
teferiTests/Mocks/MockSelectedDateService.swift
1
709
@testable import teferi import RxSwift import Foundation class MockSelectedDateService : SelectedDateService { // MARK: Fields var currentlySelectedDateVariable = Variable(Date()) // MARK: Initializers init() { currentlySelectedDateObservable = currentlySelectedDateVariable .asObservable() .distinctUntilChanged({ $0.differenceInDays(toDate: $1) == 0 }) } // MARK: Properties let currentlySelectedDateObservable : Observable<Date> var currentlySelectedDate : Date { get { return self.currentlySelectedDateVariable.value } set(value) { currentlySelectedDateVariable.value = value } } }
bsd-3-clause
18b2b2c918cb5d17027a86ed65fe9d2b
26.269231
79
0.664316
5.175182
false
false
false
false
arvindhsukumar/PredicateEditor
Example/Pods/SeedStackViewController/StackViewController/SeparatorView.swift
1
2761
// // SeparatorView.swift // StackViewController // // Created by Indragie Karunaratne on 2016-04-12. // Copyright © 2016 Seed Platform, Inc. All rights reserved. // import UIKit /// A customizable separator view that can be displayed in horizontal and /// vertical orientations. public class SeparatorView: UIView { private var sizeConstraint: NSLayoutConstraint? /// The thickness of the separator. This is equivalent to the height for /// a horizontal separator and the width for a vertical separator. public var separatorThickness: CGFloat = 1.0 { didSet { sizeConstraint?.constant = separatorThickness setNeedsDisplay() } } /// The inset of the separator from the left (MinX) edge for a horizontal /// separator and from the bottom (MaxY) edge for a vertical separator. public var separatorInset: CGFloat = 15.0 { didSet { setNeedsDisplay() } } /// The color of the separator public var separatorColor = UIColor(white: 0.90, alpha: 1.0) { didSet { setNeedsDisplay() } } /// The axis (horizontal or vertical) of the separator public var axis = UILayoutConstraintAxis.Horizontal { didSet { updateSizeConstraint() } } /// Initializes the receiver for display on the specified axis. public init(axis: UILayoutConstraintAxis) { self.axis = axis super.init(frame: CGRectZero) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func updateSizeConstraint() { sizeConstraint?.active = false let layoutAttribute: NSLayoutAttribute = { switch axis { case .Horizontal: return .Height case .Vertical: return .Width } }() sizeConstraint = NSLayoutConstraint( item: self, attribute: layoutAttribute, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: separatorThickness ) sizeConstraint?.active = true } private func commonInit() { backgroundColor = .clearColor() updateSizeConstraint() } public override func drawRect(rect: CGRect) { guard separatorThickness > 0 else { return } let edge: CGRectEdge = { switch axis { case .Horizontal: return .MinXEdge case .Vertical: return .MaxYEdge } }() let (_, separatorRect) = bounds.divide(separatorInset, fromEdge: edge) separatorColor.setFill() UIRectFill(separatorRect) } }
mit
9ef074739ca782ea0cb1d4a3a15d6f37
29.666667
78
0.611957
5.227273
false
false
false
false
abaca100/Nest
iOS-NestDK/Array+Sorting.swift
1
2407
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: The `Array+Sorting` extension allows for easy sorting of HomeKit objects. */ import HomeKit /// A protocol for objects which have a property called `name`. protocol Nameable { var name: String { get } } /* All of these HomeKit objects have names and can conform to this protocol without modification. */ extension HMHome: Nameable {} extension HMAccessory: Nameable {} extension HMRoom: Nameable {} extension HMZone: Nameable {} extension HMActionSet: Nameable {} extension HMService: Nameable {} extension HMServiceGroup: Nameable {} extension HMTrigger: Nameable {} extension CollectionType where Generator.Element: Nameable { /** Generates a new array from the original collection, sorted by localized name. - returns: New array sorted by localized name. */ func sortByLocalizedName() -> [Generator.Element] { return sort { return $0.name.localizedCompare($1.name) == .OrderedAscending } } } extension CollectionType where Generator.Element: HMActionSet { /** Generates a new array from the original collection, sorted by built-in first, then user-defined sorted by localized name. - returns: New array sorted by localized name. */ func sortByTypeAndLocalizedName() -> [HMActionSet] { return sort { (actionSet1, actionSet2) -> Bool in if actionSet1.isBuiltIn != actionSet2.isBuiltIn { // If comparing a built-in and a user-defined, the built-in is ranked first. return actionSet1.isBuiltIn } else if actionSet1.isBuiltIn && actionSet2.isBuiltIn { // If comparing two built-ins, we follow a standard ranking let firstIndex = HMActionSet.Constants.builtInActionSetTypes.indexOf(actionSet1.actionSetType) ?? NSNotFound let secondIndex = HMActionSet.Constants.builtInActionSetTypes.indexOf(actionSet2.actionSetType) ?? NSNotFound return firstIndex < secondIndex } else { // If comparing two user-defines, sort by localized name. return actionSet1.name.localizedCompare(actionSet2.name) == .OrderedAscending } } } }
apache-2.0
f38ed2bab2ce61d4d966c41079d6ae4f
34.367647
125
0.661538
4.59847
false
false
false
false
JudoPay/JudoKit
Source/JudoPayInputField.swift
1
12862
// // JudoPayInputField.swift // JudoKit // // Copyright (c) 2016 Alternative Payments Ltd // // 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 fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } /** The JudoPayInputField is a UIView subclass that is used to help to validate and visualize common information related to payments. This class delivers the common ground for the UI and UX. Text fields can either be used in a side-by-side motion (title on the left and input text field on the right) or with a floating title that floats to the top as soon as a user starts entering their details. It is not recommended to use this class directly but rather use the subclasses of JudoPayInputField that are also provided in judoKit as this class does not do any validation which are necessary for making any kind of transaction. */ open class JudoPayInputField: UIView, UITextFieldDelegate, ErrorAnimatable { /// The delegate for the input field validation methods open var delegate: JudoPayInputDelegate? /// the theme of the current judoKit session open var theme: Theme internal final let textField: FloatingTextField = FloatingTextField() internal lazy var logoContainerView: UIView = UIView() let redBlock = UIView() let hintLabel = UILabel() var hasRedBlockBeenLaiedout = false // MARK: Initializers /** Designated Initializer for JudoPayInputField - parameter theme: the theme to use - returns: a JudoPayInputField instance */ public init(theme: Theme) { self.theme = theme super.init(frame: CGRect.zero) self.setupView() } /** Designated Initializer for JudoPayInputField - parameter frame: the frame of the input view - returns: a JudoPayInputField instance */ override public init(frame: CGRect) { self.theme = Theme() super.init(frame: CGRect.zero) self.setupView() } /** Required initializer set as convenience to trigger the designated initializer that contains all necessary initialization methods - parameter aDecoder: decoder is ignored - returns: a JudoPayInputField instance */ convenience required public init?(coder aDecoder: NSCoder) { self.init(frame: CGRect.zero) } override open func layoutSubviews() { if !self.hasRedBlockBeenLaiedout && self.frame.size.height == self.theme.inputFieldHeight { super.layoutSubviews() self.redBlockAsUnactive() self.hasRedBlockBeenLaiedout = true } } /** Helper method to initialize the view */ func setupView() { self.redBlock.backgroundColor = self.theme.getErrorColor() self.redBlock.autoresizingMask = .flexibleWidth self.backgroundColor = self.theme.getInputFieldBackgroundColor() self.clipsToBounds = true self.translatesAutoresizingMaskIntoConstraints = false self.textField.delegate = self self.textField.keyboardType = .numberPad self.textField.keepBaseline = true self.textField.titleYPadding = 0.0 self.addSubview(self.textField) self.addSubview(self.redBlock) self.hintLabel.translatesAutoresizingMaskIntoConstraints = false self.hintLabel.font = UIFont.systemFont(ofSize: 12) self.addSubview(self.hintLabel) self.textField.translatesAutoresizingMaskIntoConstraints = false self.textField.textColor = self.theme.getInputFieldTextColor() self.textField.tintColor = self.theme.tintColor self.textField.font = UIFont.boldSystemFont(ofSize: 16) self.textField.addTarget(self, action: #selector(JudoInputType.textFieldDidChangeValue(_:)), for: .editingChanged) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[text(40)]", options: .alignAllLastBaseline, metrics: nil, views: ["text":textField])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[hintLabel]|", options: .alignAllLastBaseline, metrics: nil, views: ["hintLabel":hintLabel])) self.setActive(false) textField.attributedPlaceholder = NSAttributedString(string: title(), attributes: [.foregroundColor: theme.getPlaceholderTextColor()]) if self.containsLogo() { let logoView = self.logoView()! logoView.frame = CGRect(x: 0, y: 0, width: 46, height: 30) self.addSubview(self.logoContainerView) self.logoContainerView.translatesAutoresizingMaskIntoConstraints = false self.logoContainerView.clipsToBounds = true self.logoContainerView.layer.cornerRadius = 2 self.logoContainerView.addSubview(logoView) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-(3.5)-[logo(30)]", options: .alignAllLastBaseline, metrics: nil, views: ["logo":self.logoContainerView])) self.logoContainerView.addConstraint(NSLayoutConstraint(item: self.logoContainerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 30.0)) } let visualFormat = self.containsLogo() ? "|-13-[text][logo(46)]-13-|" : "|-13-[text]-13-|" let views: [String:UIView] = ["text": textField, "logo": self.logoContainerView] self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: visualFormat, options: .directionLeftToRight, metrics: nil, views: views)) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-13-[hintLabel]-13-|", options: .directionLeftToRight, metrics: nil, views: ["hintLabel":self.hintLabel])) } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return false } // MARK: Helpers /** In the case of an updated card logo, this method animates the change */ open func updateCardLogo() { let logoView = self.logoView()! logoView.frame = CGRect(x: 0, y: 0, width: 46, height: 30) if let oldLogoView = self.logoContainerView.subviews.first as? CardLogoView { if oldLogoView.type != logoView.type { UIView.transition(from: self.logoContainerView.subviews.first!, to: logoView, duration: 0.3, options: .transitionFlipFromBottom, completion: nil) } } self.textField.attributedPlaceholder = self.placeholder() } /** Set current object as active text field visually - parameter isActive: Boolean stating whether textfield has become active or inactive */ open func setActive(_ isActive: Bool) { self.textField.alpha = isActive ? 1.0 : 0.5 self.logoContainerView.alpha = isActive ? 1.0 : 0.5 self.hintLabel.text = "" if isActive { self.redBlockAsActive() } else { self.redBlockAsUnactive() } } /** Method that dismisses the error generated in the `errorAnmiation:` method */ open func dismissError() { if self.theme.getErrorColor().isEqual(self.redBlock.backgroundColor) { self.setActive(true) self.hintLabel.textColor = self.theme.getInputFieldHintTextColor() self.textField.textColor = self.theme.getInputFieldTextColor() self.hintLabel.text = "" } } /** Delegate method when text field did begin editing - parameter textField: The `UITextField` that has begun editing */ open func textFieldDidBeginEditing(_ textField: UITextField) { self.setActive(true) self.delegate?.judoPayInputDidChangeText(self) } /** Delegate method when text field did end editing - parameter textField: the `UITextField` that has ended editing */ open func textFieldDidEndEditing(_ textField: UITextField) { self.setActive(textField.text?.count > 0) } } extension JudoPayInputField: JudoInputType { /** Checks if the receiving input field has content that is valid - returns: true if valid input */ public func isValid() -> Bool { return false } /** Helper call for delegate method */ public func didChangeInputText() { self.delegate?.judoPayInputDidChangeText(self) } /** Subclassed method that is called when text field content was changed - parameter textField: the textfield of which the content has changed */ public func textFieldDidChangeValue(_ textField: UITextField) { self.dismissError() // Method for subclassing } /** The placeholder string for the current input field - returns: an Attributed String that is the placeholder of the receiver */ public func placeholder() -> NSAttributedString? { return nil } /** Boolean indicating whether the receiver has to show a logo - returns: true if inputField shows a Logo */ public func containsLogo() -> Bool { return false } /** If the receiving input field contains a logo, this method returns Some - returns: an optional CardLogoView */ public func logoView() -> CardLogoView? { return nil } /** Title of the receiver input field - returns: a string that is the title of the receiver */ public func title() -> String { return "" } /** Width of the title - returns: width of the title */ public func titleWidth() -> Int { return 50 } /** Hint label text - returns: string that is shown as a hint when user resides in a inputField for more than 5 seconds */ public func hintLabelText() -> String { return "" } public func displayHint(message: String) { self.hintLabel.text = message self.hintLabel.textColor = self.theme.getInputFieldHintTextColor() } public func displayError(message: String) { self.hintLabel.text = message self.hintLabel.textColor = self.theme.getErrorColor() } private func setRedBlockFrameAndBackgroundColor(height: CGFloat, backgroundColor: UIColor) { self.redBlock.backgroundColor = backgroundColor let yPosition:CGFloat = self.frame.size.height == 50 ? 4 : 22; self.redBlock.frame = CGRect(x: 13.0, y: self.frame.size.height - yPosition, width: self.frame.size.width - 26.0, height: height) } func redBlockAsError() { self.setRedBlockFrameAndBackgroundColor(height: 2.0, backgroundColor: self.theme.getErrorColor()) } func redBlockAsUnactive() { self.setRedBlockFrameAndBackgroundColor(height: 0.5, backgroundColor: self.theme.getInputFieldBorderColor().withAlphaComponent(0.5)) } func redBlockAsActive() { self.setRedBlockFrameAndBackgroundColor(height: 0.5, backgroundColor: self.theme.getInputFieldBorderColor().withAlphaComponent(1.0)) } }
mit
0c145a4e89ac46cc749cb07a29158bc8
33.762162
394
0.654719
4.853585
false
false
false
false
ahoppen/swift
test/Generics/same_type_constraints.swift
6
9566
// RUN: %target-typecheck-verify-swift -swift-version 4 -warn-redundant-requirements protocol Fooable { associatedtype Foo var foo: Foo { get } } protocol Barrable { associatedtype Bar: Fooable var bar: Bar { get } } struct X {} struct Y: Fooable { typealias Foo = X var foo: X { return X() } } struct Z: Barrable { typealias Bar = Y var bar: Y { return Y() } } protocol TestSameTypeRequirement { func foo<F1: Fooable>(_ f: F1) where F1.Foo == X } struct SatisfySameTypeRequirement : TestSameTypeRequirement { func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {} } protocol TestSameTypeAssocTypeRequirement { associatedtype Assoc func foo<F1: Fooable>(_ f: F1) where F1.Foo == Assoc } struct SatisfySameTypeAssocTypeRequirement : TestSameTypeAssocTypeRequirement { typealias Assoc = X func foo<F2: Fooable>(_ f: F2) where F2.Foo == X {} } struct SatisfySameTypeAssocTypeRequirementDependent<T> : TestSameTypeAssocTypeRequirement { typealias Assoc = T func foo<F3: Fooable>(_ f: F3) where F3.Foo == T {} } // Pulled in from old standard library to keep the following test // (LazySequenceOf) valid. public struct GeneratorOf<T> : IteratorProtocol, Sequence { /// Construct an instance whose `next()` method calls `nextElement`. public init(_ nextElement: @escaping () -> T?) { self._next = nextElement } /// Construct an instance whose `next()` method pulls its results /// from `base`. public init<I : IteratorProtocol>(_ base: I) where I.Element == T { var base = base self._next = { base.next() } } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. public mutating func next() -> T? { return _next() } /// `GeneratorOf<T>` is also a `Sequence`, so it `generate`\ s /// a copy of itself public func makeIterator() -> GeneratorOf { return self } let _next: () -> T? } // rdar://problem/19009056 public struct LazySequenceOf<S : Sequence, A> : Sequence where S.Iterator.Element == A { public func makeIterator() -> GeneratorOf<A> { return GeneratorOf<A>({ return nil }) } public subscript(i : A) -> A { return i } } public func iterate<A>(_ f : @escaping (A) -> A) -> (_ x : A) -> LazySequenceOf<Iterate<A>, A>? { return { x in nil } } public final class Iterate<A> : Sequence { typealias IteratorProtocol = IterateGenerator<A> public func makeIterator() -> IterateGenerator<A> { return IterateGenerator<A>() } } public final class IterateGenerator<A> : IteratorProtocol { public func next() -> A? { return nil } } // rdar://problem/18475138 public protocol Observable : class { associatedtype Output func addObserver(_ obj : @escaping (Output) -> Void) } public protocol Bindable : class { associatedtype Input func foo() } class SideEffect<In> : Bindable { typealias Input = In func foo() { } } struct Composed<Left: Bindable, Right: Observable> where Left.Input == Right.Output {} infix operator <- : AssignmentPrecedence func <- < Right >(lhs: @escaping (Right.Output) -> Void, rhs: Right) -> Composed<SideEffect<Right>, Right>? { return nil } // rdar://problem/17855378 struct Pair<T, U> { typealias Type_ = (T, U) } protocol Seq { associatedtype Element func zip<OtherSeq: Seq, ResultSeq: Seq> (_ otherSeq: OtherSeq) -> ResultSeq where ResultSeq.Element == Pair<Element, OtherSeq.Element>.Type_ } // rdar://problem/18435371 extension Dictionary { func multiSubscript<S : Sequence>(_ seq: S) -> [Value?] where S.Iterator.Element == Key { var result = [Value?]() for seqElt in seq { result.append(self[seqElt]) } return result } } // rdar://problem/19245317 protocol P { associatedtype T: P } struct S<A: P> { init<Q: P>(_ q: Q) where Q.T == A {} } // rdar://problem/19371678 protocol Food { } class Grass : Food { } protocol Animal { associatedtype EdibleFood:Food func eat(_ f:EdibleFood) } class Cow : Animal { func eat(_ f: Grass) { } } struct SpecificAnimal<F:Food> : Animal { typealias EdibleFood=F let _eat:(_ f:F) -> () init<A:Animal>(_ selfie:A) where A.EdibleFood == F { _eat = { selfie.eat($0) } } func eat(_ f:F) { _eat(f) } } // rdar://problem/18803556 struct Something<T> { var items: [T] = [] } extension Something { init<S : Sequence>(_ s: S) where S.Iterator.Element == T { for item in s { items.append(item) } } } // rdar://problem/18120419 func TTGenWrap<T, I : IteratorProtocol>(_ iterator: I) where I.Element == (T,T) { var iterator = iterator _ = iterator.next() } func IntIntGenWrap<I : IteratorProtocol>(_ iterator: I) where I.Element == (Int,Int) { var iterator = iterator _ = iterator.next() } func GGWrap<I1 : IteratorProtocol, I2 : IteratorProtocol>(_ i1: I1, _ i2: I2) where I1.Element == I2.Element { var i1 = i1 var i2 = i2 _ = i1.next() _ = i2.next() } func testSameTypeTuple(_ a: Array<(Int,Int)>, s: ArraySlice<(Int,Int)>) { GGWrap(a.makeIterator(), s.makeIterator()) TTGenWrap(a.makeIterator()) IntIntGenWrap(s.makeIterator()) } // rdar://problem/20256475 protocol FooProtocol { associatedtype Element func getElement() -> Element } protocol Bar { associatedtype Foo : FooProtocol func getFoo() -> Foo mutating func extend<C : FooProtocol>(_ elements: C) where C.Element == Foo.Element } // rdar://problem/21620908 protocol P1 { } protocol P2Base { } protocol P2 : P2Base { associatedtype Q : P1 func getQ() -> Q } struct XP1<T : P2Base> : P1 { func wibble() { } } func sameTypeParameterizedConcrete<C : P2>(_ c: C) where C.Q == XP1<C> { c.getQ().wibble() } // rdar://problem/21621421 protocol P3 { associatedtype AssocP3 : P1 } protocol P4 { associatedtype AssocP4 : P3 } struct X1 : P1 { } struct X3 : P3 { typealias AssocP3 = X1 } func foo<C : P4>(_ c: C) where C.AssocP4 == X3 {} struct X4 : P4 { typealias AssocP4 = X3 } func testFoo(_ x3: X4) { foo(x3) } // rdar://problem/21625478 struct X6<T> { } protocol P6 { } protocol P7 { associatedtype AssocP7 } protocol P8 { associatedtype AssocP8 : P7 associatedtype AssocOther } func testP8<C : P8>(_ c: C) where C.AssocOther == X6<C.AssocP8.AssocP7> {} // setGenericSignature() was getting called twice here struct Ghost<T> {} protocol Timewarp { associatedtype Wormhole } struct Teleporter<A, B> where A : Timewarp, A.Wormhole == Ghost<B> {} struct Beam {} struct EventHorizon : Timewarp { typealias Wormhole = Ghost<Beam> } func activate<T>(_ t: T) {} activate(Teleporter<EventHorizon, Beam>()) // rdar://problem/29288428 class C {} protocol P9 { associatedtype A } struct X7<T: P9> where T.A : C { } extension X7 where T.A == Int { } // expected-error {{no type for 'T.A' can satisfy both 'T.A : _NativeClass' and 'T.A == Int}} // expected-error@-1 {{no type for 'T.A' can satisfy both 'T.A : C' and 'T.A == Int'}} struct X8<T: C> { } extension X8 where T == Int { } // expected-error {{no type for 'T' can satisfy both 'T : _NativeClass' and 'T == Int'}} // expected-error@-1 {{no type for 'T' can satisfy both 'T : C' and 'T == Int'}} protocol P10 { associatedtype A associatedtype B associatedtype C associatedtype D associatedtype E } protocol P11: P10 where A == B { } func intracomponent<T: P11>(_: T) where T.A == T.B { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.B'}} func intercomponentSameComponents<T: P10>(_: T) where T.A == T.B, T.B == T.A { } // expected-warning{{redundant same-type constraint 'T.B' == 'T.A'}} func intercomponentMoreThanSpanningTree<T: P10>(_: T) where T.A == T.B, T.B == T.C, T.D == T.E, T.D == T.B, T.E == T.B // expected-warning{{redundant same-type constraint 'T.E' == 'T.B'}} { } func trivialRedundancy<T: P10>(_: T) where T.A == T.A { } // expected-warning{{redundant same-type constraint 'T.A' == 'T.A'}} struct X11<T: P10> where T.A == T.B { } func intracomponentInferred<T>(_: X11<T>) where T.A == T.B { } // Suppress redundant same-type constraint warnings from result types. struct StructTakingP1<T: P1> { } func resultTypeSuppress<T: P1>() -> StructTakingP1<T> { return StructTakingP1() } // Check directly-concrete same-type constraints typealias NotAnInt = Double extension X11 where NotAnInt == Int { } // expected-error@-1{{generic signature requires types 'NotAnInt' (aka 'Double') and 'Int' to be the same}} // rdar://45307061 - dropping delayed same-type constraints when merging // equivalence classes protocol FakeIterator { associatedtype Element } protocol FakeSequence { associatedtype Iterator : FakeIterator associatedtype Element where Iterator.Element == Element } protocol ObserverType { associatedtype E } struct Bad<S: FakeSequence, O> where S.Element : ObserverType, S.Element.E == O {} func good<S: FakeSequence, O>(_: S, _: O) where S.Element : ObserverType, O == S.Element.E { _ = Bad<S, O>() } func bad<S: FakeSequence, O>(_: S, _: O) where S.Element : ObserverType, O == S.Iterator.Element.E { _ = Bad<S, O>() } func ugly<S: FakeSequence, O>(_: S, _: O) where S.Element : ObserverType, O == S.Iterator.Element.E, O == S.Element.E { // expected-warning@-1 {{redundant same-type constraint 'O' == 'S.Element.E'}} _ = Bad<S, O>() }
apache-2.0
d8f0755fd8141da0c3ff78e45c59dc15
22.218447
127
0.647188
3.268193
false
false
false
false
goRestart/restart-backend-app
Sources/FluentStorage/Model/Gender/GenderDiskModel.swift
1
952
import FluentProvider extension GenderDiskModel { static var name: String = "gender" struct Field { static let value = "value" } } final class GenderDiskModel: Entity { var storage = Storage() var value: String init(value: String) { self.value = value } init(row: Row) throws { value = try row.get(Field.value) id = try row.get(idKey) } func makeRow() throws -> Row { var row = Row() try row.set(Field.value, value) try row.set(idKey, id) return row } } // MARK: - Preparations extension GenderDiskModel: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { creator in creator.id() creator.string(Field.value) } } static func revert(_ database: Database) throws { try database.delete(self) } }
gpl-3.0
4385fd84a8701074cc64b2095fbac464
18.04
54
0.561975
4.157205
false
false
false
false
ninotoshi/violettyne
ios/violettyne/MapViewController.swift
1
3924
import UIKit class MapViewController: UIViewController, CLLocationManagerDelegate, GMSMapViewDelegate { let locationManager = CLLocationManager() @IBOutlet weak var mapView: GMSMapView! /// current location var location: CLLocation? var neighbors: [User: GMSMarker] = [:] override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() mapView.myLocationEnabled = true mapView.settings.myLocationButton = true mapView.delegate = self Socket.onReceiveLocation = {userID, latitude, longitude in let neighbor = User(id: userID) neighbor.name = userID.substringToIndex(userID.startIndex.advancedBy(6)) // TODO dispatch_async(dispatch_get_main_queue()) { let position = CLLocationCoordinate2DMake(latitude, longitude) if let marker = self.neighbors[neighbor] { marker.position = position } else { let marker = GMSMarker(position: position) marker.icon = GMSMarker.markerImageWithColor(UIColor.greenColor()) marker.userData = NSKeyedArchiver.archivedDataWithRootObject(neighbor) marker.map = self.mapView self.neighbors[neighbor] = marker } } } Socket.getCurrentLocation = {() in return self.location } } // CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.AuthorizedWhenInUse { locationManager.distanceFilter = 10 // meters locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters locationManager.startUpdatingLocation() } } // CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let newLocation = locations.last { if let oldLocation = self.location { if newLocation.coordinate.longitude == oldLocation.coordinate.longitude && newLocation.coordinate.latitude == oldLocation.coordinate.latitude { return } } else { mapView.camera = GMSCameraPosition.cameraWithTarget(newLocation.coordinate, zoom: 16) mapView.animateToLocation(newLocation.coordinate) } self.location = newLocation Socket.updateLocation() } } // GMSMapViewDelegate func mapView(mapView: GMSMapView!, idleAtCameraPosition position: GMSCameraPosition!) { } // GMSMapViewDelegate func mapView(mapView: GMSMapView!, didTapMarker marker: GMSMarker!) -> Bool { self.performSegueWithIdentifier("showMessageTable", sender: marker) return true } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBarHidden = true super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.navigationController?.navigationBarHidden = false } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let controller = segue.destinationViewController as? MessageTableViewController { if let marker = sender as? GMSMarker { if let userData = marker.userData as? NSData { if let neighbor = NSKeyedUnarchiver.unarchiveObjectWithData(userData) as? User { controller.neighbor = neighbor } } } } } }
mit
4a156d3f7dcd8ff592d037777d2dca8f
39.040816
159
0.626656
6.339257
false
false
false
false
louisdh/lioness
Sources/Lioness/AST/Nodes/FunctionPrototypeNode.swift
1
1011
// // PrototypeNode.swift // Lioness // // Created by Louis D'hauwe on 09/10/2016. // Copyright © 2016 - 2017 Silver Fox. All rights reserved. // import Foundation public struct FunctionPrototypeNode: ASTNode { public let name: String public let argumentNames: [String] public let returns: Bool public init(name: String, argumentNames: [String] = [], returns: Bool = false) { self.name = name self.argumentNames = argumentNames self.returns = returns } // TODO: make ASTNode protocol without compile function? (and make one with compile func) public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody { return [] } public var childNodes: [ASTNode] { return [] } public var description: String { return "FunctionPrototypeNode(name: \(name), argumentNames: \(argumentNames), returns: \(returns))" } public var nodeDescription: String? { return "Function Prototype" } public var descriptionChildNodes: [ASTChildNode] { return [] } }
mit
d8e4039151dfd903182fceb252a25cfb
21.954545
101
0.711881
3.620072
false
false
false
false
LedgerHQ/ledger-wallet-ios
ledger-wallet-ios/Views/Custom/AlertController.swift
1
3661
// // AlertController.swift // ledger-wallet-ios // // Created by Nicolas Bigot on 16/02/2015. // Copyright (c) 2015 Ledger. All rights reserved. // import UIKit class AlertController: NSObject { enum Style { case Alert case ActionSheet } class Action { enum Style { case Default case Destructive case Cancel } typealias Handler = (Action) -> Void let title: String let style: Style private let handler: Handler? init(title: String, style: Style, handler: Handler?) { self.title = title self.style = style self.handler = handler } private class func UIAlertActionForStyle(style: Style) -> UIAlertActionStyle { switch style { case .Cancel: return .Cancel case .Destructive: return .Destructive default: return .Default } } } let style: Style let title: String? let message: String? private var actions: [Action] = [] private var alertController: UIAlertController! = nil private var alertView: UIAlertView! = nil private static var sharedControllers: [UIAlertView: AlertController] = [:] class func usesSystemAlertController() -> Bool { return NSClassFromString("UIAlertController") != nil } init(title: String?, message: String?) { self.title = title self.message = message self.style = .Alert } func addAction(action: Action) { actions.append(action) } func presentFromViewController(viewController: BaseViewController, animated: Bool) { if AlertController.usesSystemAlertController() { // ios >= 8 alertController = UIAlertController(title: title, message: message, preferredStyle: AlertController.UIAlertControllerStyleForStyle(style)) for action in actions { let alertAction = UIAlertAction(title: action.title, style: Action.UIAlertActionForStyle(action.style), handler: action.handler == nil ? nil : { _ in (action.handler?(action))! }) alertController.addAction(alertAction) } viewController.presentViewController(alertController, animated: animated, completion: nil) } else { // ios < 8 alertView = UIAlertView() alertView.delegate = self alertView.title = title ?? "" alertView.message = message alertView.alertViewStyle = .Default for action in actions { alertView.addButtonWithTitle(action.title) } alertView.show() // add to shared pool AlertController.sharedControllers[alertView] = self } } private class func UIAlertControllerStyleForStyle(style: Style) -> UIAlertControllerStyle { switch style { case .ActionSheet: return .ActionSheet default: return .Alert } } } extension AlertController: UIAlertViewDelegate { // MARK: - UIAlertView delegate func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { // call handler let alertController = AlertController.sharedControllers[alertView] let action = alertController?.actions[buttonIndex] action?.handler?(action!) // remove from shared pool AlertController.sharedControllers[alertView] = nil } }
mit
f4687299d0dbc08263841070cb4c1836
29.256198
165
0.591642
5.496997
false
false
false
false
blokadaorg/blokada
ios/App/Model/NotificationModel.swift
1
1774
// // This file is part of Blokada. // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import UserNotifications let NOTIF_ACC_EXP = "accountExpired" let NOTIF_LEASE_EXP = "plusLeaseExpired" let NOTIF_PAUSE = "pauseTimeout" func mapNotificationToUser(_ id: String) -> UNMutableNotificationContent { if id == NOTIF_ACC_EXP { let content = UNMutableNotificationContent() content.title = L10n.notificationAccHeader content.subtitle = L10n.notificationAccSubtitle content.body = L10n.notificationAccBody content.sound = .default return content } else if id == NOTIF_LEASE_EXP { let content = UNMutableNotificationContent() content.title = L10n.notificationLeaseHeader content.subtitle = L10n.notificationVpnExpiredSubtitle content.body = L10n.notificationGenericBody content.sound = .default return content } else if id == NOTIF_PAUSE { let content = UNMutableNotificationContent() content.title = L10n.notificationPauseHeader content.subtitle = L10n.notificationPauseSubtitle content.body = L10n.notificationPauseBody content.sound = .default return content } else { let content = UNMutableNotificationContent() content.title = L10n.notificationGenericHeader content.subtitle = L10n.notificationGenericSubtitle content.body = L10n.notificationGenericBody content.sound = .default return content } }
mpl-2.0
2abaa32e9912ac91beeeef35489cd665
34.46
74
0.693175
4.241627
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01076-swift-lexer-getlocforendoftoken.swift
1
1017
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck class w<r>: c { init(g: r) { struct t : o { } q t<where n.v == t<v : o u m : v { } struct c<e> { } } struct e : f { } func i<g : g, e : f where e.f == g> (c: e) { } func i<h : f where h.f == c> (c: h) { } class a<f : g, g : g where f.f == g> { } protocol g { } struct c<h : g> : g { typealias e = a<c<h>, f> protocol b { } struct c { func e() { docol t { } protocol d : t { } protocol g : t { } }) } protocol e { } struct m<v : e> { } protocol n { g == o>(n: m<v>) { } } struct e<v> { } struct d<x> : e { func d(d: d.p) { } } class e<v : e> { } class A<T : A> { } func c<d { enum c { func e var _ = e } } protocol a {
apache-2.0
fc9d5756c9c9a49d3e4141a048fcf408
14.409091
79
0.580138
2.415677
false
false
false
false
knutnyg/picnic
picnic/viewControllers/MenuViewController.swift
1
12772
// // MenuViewController.swift // picnic // // Created by Knut Nygaard on 4/7/15. // Copyright (c) 2015 Knut Nygaard. All rights reserved. // import Foundation import UIKit import BButton import StoreKit class MenuViewController : UIViewController, SKPaymentTransactionObserver{ var gpsButton:BButton! var countrySetup:BButton! var instructionAutomaticLabel:UILabel! var instructionManualLabel:UILabel! var userModel:UserModel! var delegate:ConverterViewController! var backButton:UIButton! var aboutButton:UIButton! var pointButton:BButton! var houseButton:BButton! var removeAdsButton:BButton! var removeAdsProduct:SKProduct? var backButtonItem:UIBarButtonItem! var aboutButtonItem:UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() self.view.backgroundColor = UIColor.white NotificationCenter.default.addObserver(self, selector: "backButtonPressed:", name: NSNotification.Name(rawValue: "backPressed"), object: nil) NotificationCenter.default.addObserver(self, selector: "setupComplete:", name: NSNotification.Name(rawValue: "setupComplete"), object: nil) instructionAutomaticLabel = createLabel("Let Picnic guess where you are:") instructionManualLabel = createLabel("or you decide:") gpsButton = createBButton(" Automatic setup") gpsButton.addTarget(self, action: #selector(MenuViewController.autoSetupPressed(_:)), for: UIControlEvents.touchUpInside) pointButton = createBButton(" Set location") pointButton.addAwesomeIcon(FAIcon.FALocationArrow, beforeTitle: true) pointButton.addTarget(self, action: #selector(MenuViewController.pointPressed(_:)), for: UIControlEvents.touchUpInside) houseButton = createBButton(" Set home") houseButton.addAwesomeIcon(FAIcon.FAHome, beforeTitle: true) houseButton.addTarget(self, action: #selector(MenuViewController.housePressed(_:)), for: UIControlEvents.touchUpInside) removeAdsButton = createBButton("Temp") removeAdsButton.isHidden = true if !userModel.skipAds { if let product = userModel.removeAdProduct { removeAdsButton.isHidden = false removeAdsButton.setType(BButtonType.inverse) removeAdsButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 15) removeAdsButton.addTarget(self, action: #selector(MenuViewController.removeAdsPressed(_:)), for: UIControlEvents.touchUpInside) let formatter = NumberFormatter() formatter.numberStyle = NumberFormatter.Style.currency formatter.locale = product.priceLocale removeAdsButton.setTitle("Remove Ads: \(formatter.string(from: product.price)!)", for: UIControlState()) } } setActiveButtonStyle() view.addSubview(instructionAutomaticLabel) view.addSubview(instructionManualLabel) view.addSubview(gpsButton) view.addSubview(pointButton) view.addSubview(houseButton) view.addSubview(removeAdsButton) let views = ["gps":gpsButton, "instructionsAuto":instructionAutomaticLabel, "instructionsManual":instructionManualLabel, "pointButton":pointButton, "houseButton":houseButton, "removeAdsButton":removeAdsButton] as [String : Any] let screenHeight = view.bounds.height let marginTop = Int((screenHeight - 24 - 160) / 2) - 66 self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(marginTop)-[instructionsAuto]-[gps(40)]-40-[instructionsManual]-[pointButton(40)]-18-[houseButton(40)]-51-[removeAdsButton(45)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[instructionsAuto]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[instructionsAuto]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) view.addConstraint(NSLayoutConstraint(item: houseButton.titleLabel!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 115)) view.addConstraint(NSLayoutConstraint(item: pointButton.titleLabel!, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 115)) view.addConstraint(NSLayoutConstraint(item: instructionManualLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: gpsButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 180)) view.addConstraint(NSLayoutConstraint(item: gpsButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: pointButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: pointButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 145)) view.addConstraint(NSLayoutConstraint(item: houseButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: houseButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 145)) view.addConstraint(NSLayoutConstraint(item: removeAdsButton, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: removeAdsButton, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)) } override func viewDidAppear(_ animated: Bool) { SKPaymentQueue.default().add(self) } override func viewDidDisappear(_ animated: Bool) { SKPaymentQueue.default().remove(self) } func createReloadButton() -> UIButton{ let button = UIButton(type: UIButtonType.system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("Reload", for: UIControlState()) button.titleLabel!.font = UIFont(name:"Helvetica", size:30) return button } func parseResult(_ dict:Dictionary<String, Dictionary<String,String>>) -> [String:OfflineEntry]{ var resultDict:[String:OfflineEntry] = [:] for key in dict.keys { let value = (dict[key]!["value"]! as NSString).doubleValue let from = dict[key]!["unit_from"]! let to = dict[key]!["unit_to"]! let timestamp = dict[key]!["timestamp"]! resultDict[key] = OfflineEntry(timeStamp: dateFromUTCString(timestamp), unit_from: from, unit_to: to, value: value) } return resultDict } func setupNavigationBar() { let font = UIFont(name: "Verdana", size: 22)! let attributes: [String:AnyObject] = [NSFontAttributeName: font, NSForegroundColorAttributeName: UIColor.white] navigationItem.title = "Menu" navigationController?.navigationBar.titleTextAttributes = attributes let verticalOffset = 3 as CGFloat; navigationController?.navigationBar.setTitleVerticalPositionAdjustment(verticalOffset, for: UIBarMetrics.default) backButton = createfontAwesomeButton("\u{f060}") backButton.addTarget(self, action: #selector(MenuViewController.back(_:)), for: UIControlEvents.touchUpInside) backButtonItem = UIBarButtonItem(customView: backButton) navigationItem.leftBarButtonItem = backButtonItem aboutButton = createfontAwesomeButton("\u{f128}") aboutButton.addTarget(self, action: #selector(MenuViewController.about(_:)), for: UIControlEvents.touchUpInside) aboutButtonItem = UIBarButtonItem(customView: aboutButton) navigationItem.rightBarButtonItem = aboutButtonItem } func back(_: UIEvent) { navigationController?.popViewController(animated: true) } func about(_:UIEvent) { let alertController = UIAlertController(title: "About Picnic", message: "Exchange rate data is provided by various sources with public-facing APIs. Data is refreshed approximately every 24h. \n\nRates are never 100% accurate and should never be relied on for serious financial decisions.", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)) self.present(alertController, animated: true, completion: nil) } func setupButtonPressed(_ sender:UIButton!){ let vc = CountrySelectorViewController(userModel: self.userModel, selectorType: CountrySelectorType.home_COUNTRY) vc.delegate = self navigationController?.pushViewController(vc, animated: true) } func autoSetupPressed(_ sender:UIButton!){ userModel.overrideGPSLocale = nil userModel.overrideLogicalLocale = nil navigationController?.popViewController(animated: true) } func pointPressed(_ sender:UIButton){ let vc = CountrySelectorViewController(userModel: userModel, selectorType: CountrySelectorType.gps) navigationController?.pushViewController(vc, animated: true) } func housePressed(_ sender:UIButton){ let vc = CountrySelectorViewController(userModel: userModel, selectorType: CountrySelectorType.home_COUNTRY) navigationController?.pushViewController(vc, animated: true) } func createBButton(_ title:String) -> BButton{ let button = BButton() button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(title, for: UIControlState()) button.setType(BButtonType.info) return button } func setActiveButtonStyle() { if userModel.overrideGPSLocale != nil { pointButton.setType(BButtonType.success) } if userModel.overrideLogicalLocale != nil { houseButton.setType(BButtonType.success) } if !userModel.isManualSetupActive() { gpsButton.setType(BButtonType.success) gpsButton.addAwesomeIcon(FAIcon.FACheck, beforeTitle: true) } } /* ---- Remove Ads ---- */ func removeAdsPressed(_ sender:UIButton){ if let product = userModel.removeAdProduct { let payment = SKPayment(product: product) SKPaymentQueue.default().add(payment) } } func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]){ for transaction in transactions { let trans = transaction switch trans.transactionState { case .purchased: unlockFeature() SKPaymentQueue.default().finishTransaction(trans) case .failed: SKPaymentQueue.default().finishTransaction(trans) default: break } } } func unlockFeature(){ userModel.skipAds = true } /* ---- Initializers ---- */ init(userModel:UserModel) { super.init(nibName: nil, bundle: nil) self.userModel = userModel } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
bsd-2-clause
1309711b4481198a4eb547a1a7fb6ca0
48.123077
343
0.69809
5.198209
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01662-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift
1
1572
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck } } } var d : P { for c == [[T>) struct d: e? = b: (z: String { } struct Q<B : 1]() -> (true } } } } b.h: a : Any, U) -> Any) class A : AnyObject.count][1]](A } case .c : A> U) -> { protocol c { typealias A { } case C) { func b, V>(true { } struct c<U) -> { } func a: A>? { } class A typealias d typealias f = { var f = { extension NSSet { func f(A.E == i<T -> ([0.C<S { enum A = [c<T> <S { func c(c: U, B() -> { init(A<c) -> (false) init() { c: X.f = i<T where k.startIndex)!.e: a { private class A { let g = F } self, V, A { func e: T, self.d where H.advance(_ = b: String { class B = h: T>) { } } protocol b { init(") typealias A { e : A<T.d>: B<f == c) { protocol d = c> { } } () -> { enum S<T] as Boolean, Any) { class A<T where l..init(_ = b() struct e where T> : end) } } } } var e, g: b = Int) { return NSData() } func b func a""\() { protocol c == "ab" } func a<T>() init(T, x } init <S : Boolean) func g<U : Bool) { enum a: NSObject { func d: A where f, Any, y: [B, (A.Iterator.C(seq: AnyObject) } 0] = ") func i: A"].init() typealias e = g(""")) i<T>(object1, e class B == b("ab"""\(n: C<T where T: d = c() -> Any) ->) func b.init() class func c: c<f = { c, b =
apache-2.0
409d4b1b6942940b4baca3994d2ebd2f
17.068966
79
0.571247
2.46395
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/Items/Responses/DeltaResponse.swift
1
2909
// // DeltaResponse.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 15.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Class that encapsulates chat update respnonce, requested from a server. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class DeltaResponse { // MARK: - Constants // Raw values equal to field names received in responses from server. private enum JSONField: String { case deltaList = "deltaList" case fullUpdate = "fullUpdate" case revision = "revision" } // MARK: - Properties private lazy var deltaList = [DeltaItem]() private var fullUpdate: FullUpdate? private var revision: Int64? // MARK: - Initialization init(jsonDictionary: [String: Any?]) { if let revision = jsonDictionary[JSONField.revision.rawValue] as? Int64 { self.revision = revision } if let fullUpdateValue = jsonDictionary[JSONField.fullUpdate.rawValue] as? [String: Any?] { fullUpdate = FullUpdate(jsonDictionary: fullUpdateValue) } if let deltaItemArray = jsonDictionary[JSONField.deltaList.rawValue] as? [Any] { for arrayItem in deltaItemArray { if let arrayItem = arrayItem as? [String: Any?] { if let deltaItem = DeltaItem(jsonDictionary: arrayItem) { deltaList.append(deltaItem) } } } } } // MARK: - Methods func getRevision() -> Int64? { return revision } func getFullUpdate() -> FullUpdate? { return fullUpdate } func getDeltaList() -> [DeltaItem]? { return deltaList } }
mit
95800e8a73b19432673f81b60704c7b4
32.813953
99
0.653714
4.487654
false
false
false
false
luispadron/GradePoint
GradePoint/Models/Main/Rubric.swift
1
1106
// // Rubric.swift // GradePoint // // Created by Luis Padron on 10/23/16. // Copyright © 2016 Luis Padron. All rights reserved. // import Foundation import RealmSwift class Rubric: Object { // MARK: - Properties @objc dynamic var id = UUID().uuidString @objc dynamic var name = "" @objc dynamic var weight: Double = 0.0 class var pointsRubric: Rubric { let rubric = Rubric(name: "Assignments", weight: 100) return rubric } // MARK: - Initializers convenience init(name: String, weight: Double) { self.init() self.name = name self.weight = weight } // MARK: - Overrides override class func primaryKey() -> String? { return "id" } override func isEqual(_ object: Any?) -> Bool { guard let rubric = object as? Rubric else { return false } return rubric.name == self.name && rubric.weight == self.weight } override func copy() -> Any { let r = Rubric(name: self.name, weight: self.weight) r.id = self.id return r } }
apache-2.0
c54062dc1862dc8da803965118f57857
21.55102
71
0.58009
3.932384
false
false
false
false
cpmpercussion/microjam
chirpey/ChirpPlayer.swift
1
4300
// // Player.swift // microjam // // Created by Henrik Brustad on 18/08/2017. // Copyright © 2017 Charles Martin. All rights reserved. // import UIKit import Repeat /// Enabled classes to receive updates on the playback state of ChirpPlayers and ChirpRecorders. protocol PlayerDelegate { /// Called when playback starts. func playbackStarted() /// Called when playback is completed. func playbackEnded() /// Called at each timestep (0.01s) during playback func playbackStep(_ time: Double) } /// Plays back one or more ChirpViews class ChirpPlayer: NSObject { /// Maximum playback time of any player (or recording) var maxPlayerTime = 5.0 /// Stores whether the player is currently playing. var isPlaying = false /// Array of timers used for currently playing performance. var timers = [Repeater]() /// Array of ChirpViews used for loaded performances. var chirpViews = [ChirpView]() /// Stores whether views have been loaded. (Maybe only used in ChirpRecorder?) var viewsAreLoaded = false /// Overall playback timer for displaying progress bar etc. var progressTimer: Repeater? /// Current progress through playback. var progress = 0.0 /// Stores delegate to inform them about start/stop events and current progress. var delegate: PlayerDelegate? /// Dispatch Queue for the playback events var touchPlaybackQueue = DispatchQueue(label: QueueLabels.touchPlayback) /// Dispatch Queue for timer var perfTimerQueue = DispatchQueue(label: QueueLabels.performanceTimer) /// Description of the ChirpPlayer with it's first ChirpPerformance. override var description: String { guard let perfString = chirpViews.first?.performance?.description else { return "ChirpPlayer-NoPerformance" } return "ChirpPlayer-" + perfString } /// Play a particular ChirpView's performance func play(chirp: ChirpView) { for touch in chirp.performance!.performanceData { timers.append( Repeater.once(after: .seconds(touch.time), queue: touchPlaybackQueue) { timer in chirp.play(touch: touch) } ) } } /// Convenience initialiser for creating a ChirpPlayer with an array of ChirpPerformances convenience init(withArrayOfPerformances performanceArray: [ChirpPerformance]) { let dummyFrame = CGRect.zero self.init() for perf in performanceArray { let chirp = ChirpView(with: dummyFrame, andPerformance: perf) chirpViews.append(chirp) } } /// Start playback. func play() { if !isPlaying { isPlaying = true timers = [Repeater]() for chirp in chirpViews { chirp.prepareToPlaySounds() play(chirp: chirp) } //print("ChirpPlayer: Playing back: \(timers.count) touch events.") startProgressTimer() } } /// Start the progress timer. func startProgressTimer() { self.delegate?.playbackStarted() // tell delegate the progress timer has started. progressTimer = Repeater.every(.seconds(0.01), count: 502, queue: perfTimerQueue) { timer in self.step() } progressTimer?.onStateChanged = { (timer,newState) in if newState == .finished { self.stop() } } } /// Move one time step (0.01s) through the progress timer. func step() { progress += 0.01 self.delegate!.playbackStep(progress) if progress > maxPlayerTime { DispatchQueue.main.async { self.delegate!.playbackEnded() } } } /// Stop playback and reset timers. func stop() { if isPlaying { isPlaying = false if let timer = progressTimer { timer.removeAllObservers(thenStop: true) progress = 0.0 for t in timers { t.removeAllObservers(thenStop: true) } for chirp in chirpViews { chirp.setImage() } } } } }
mit
389f95aeb47439fabe65b091c4647ae2
31.816794
101
0.604327
4.539599
false
false
false
false
rhwood/roster-decoder
Tests/RosterTests.swift
1
4247
// // RosterTests.swift // Roster DecoderTests // // Created by Randall Wood on 1/15/19. // Copyright © 2019 Alexandria Software. All rights reserved. // import UIKit import XCTest @testable import Roster_Decoder class RosterTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInitDataValid() { do { let path = Bundle(for: type(of: self)).url(forResource: "rosterValidLong", withExtension: "xml") let data = try Data(contentsOf: path!) let roster = try Roster(data: data) XCTAssert(roster.entries.count == 35, "Roster has 35 entries") XCTAssert(roster.name == "roster.xml", "Roster name is default") XCTAssertNil(roster.profile, "Roster from data has no profile") XCTAssertNil(roster.rosterDir, "Roster from data has no directory") XCTAssertNil(roster.xml, "Roster from data has no XML element") XCTAssertFalse(roster.containsIcons, "Roster has no displayable icons") } catch { XCTFail("Test could not be set up correctly") } } func testInitDataInvalidSchema() { let path = Bundle(for: type(of: self)).url(forResource: "rosterInvalidSchema", withExtension: "xml") var data: Data? do { data = try Data(contentsOf: path!) } catch { XCTFail("Test could not be set up correctly") } XCTAssertThrowsError(try Roster(data: data!), "Invalid schema passes") { (error) in XCTAssertEqual(error as? ProfileError, ProfileError.invalidRoster, "Error thrown not expected type") } } func testInitDataInvalidXML() { let path = Bundle(for: type(of: self)).url(forResource: "rosterInvalidXML", withExtension: "xml") var data: Data? do { data = try Data(contentsOf: path!) } catch { XCTFail("Test could not be set up correctly") } XCTAssertThrowsError(try Roster(data: data!), "Invalid XML passes") { (error) in XCTAssertEqual(error as? ProfileError, ProfileError.invalidRoster, "Error thrown not expected type") } } func testEntry() { do { let path = Bundle(for: type(of: self)).url(forResource: "rosterValidLong", withExtension: "xml") let data = try Data(contentsOf: path!) let roster = try Roster(data: data) XCTAssertNil(roster.entry("no-such-locomotive"), "Roster contains expected nil entry") XCTAssertNotNil(roster.entry("RHW_MEC_605"), "Roster does not contain expected entry") } catch { XCTFail("Test could not be set up correctly") } } func testUpdateRoster() { do { var path = Bundle(for: type(of: self)).url(forResource: "rosterValidLong", withExtension: "xml") var data = try Data(contentsOf: path!) let roster = try Roster(data: data) XCTAssertNil(roster.entry("no-such-locomotive"), "Roster contains expected nil entry") XCTAssertNotNil(roster.entry("ADW_B&O_6031"), "Roster does not contain expected entry") XCTAssertNotNil(roster.entry("RHW_MEC_605"), "Roster does not contain expected entry") path = Bundle(for: type(of: self)).url(forResource: "rosterValidShort", withExtension: "xml") data = try Data(contentsOf: path!) try roster.updateRoster(data) XCTAssertNil(roster.entry("no-such-locomotive"), "Roster contains expected nil entry") XCTAssertNil(roster.entry("ADW_B&O_6031"), "Roster contains expected nil entry") XCTAssertNotNil(roster.entry("RHW_MEC_605"), "Roster does not contain expected entry") XCTAssertNotNil(roster.entry("added-locomotive"), "Roster does not contain expected entry") } catch { XCTFail("Test could not be set up correctly") } } }
mit
f9803e12c36cd3d76ece6d7a49acfcc4
42.326531
112
0.624823
4.404564
false
true
false
false
khizkhiz/swift
test/DebugInfo/shadowcopy-linetable.swift
2
799
// RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s func markUsed<T>(t: T) {} func foo(x: inout Int64) { // Make sure the shadow copy is being made in the prologue or (at // line 0), but the code to load the value from the inout storage is // not. // CHECK: %[[X:.*]] = alloca %Vs5Int64*, align {{(4|8)}} // CHECK: store %Vs5Int64* %0, %Vs5Int64** %[[X]], align {{(4|8)}} // CHECK-SAME: !dbg ![[LOC0:.*]] // CHECK-NEXT: call void @llvm.dbg.declare // CHECK-NEXT: getelementptr inbounds %Vs5Int64, %Vs5Int64* %0, i32 0, i32 0, // CHECK-SAME: !dbg ![[LOC1:.*]] // CHECK: ![[LOC0]] = !DILocation(line: 0, // CHECK: ![[LOC1]] = !DILocation(line: [[@LINE+1]], x = x + 2 } func main() { var x : Int64 = 1 foo(&x) markUsed("break here to see \(x)") } main()
apache-2.0
d8ed76315bf09ab0d3146ce45d5edf84
29.730769
79
0.57572
2.823322
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/RSTBSupport/Classes/RSEnhancedDateTimePickerStepGenerator.swift
1
2084
// // RSEnhancedDateTimePickerStepGenerator.swift // ResearchSuiteExtensions // // Created by James Kizer on 3/27/19. // import UIKit import Gloss import ResearchSuiteTaskBuilder import ResearchKit open class RSEnhancedDateTimePickerStepGenerator: RSTBBaseStepGenerator { public init(){} let _supportedTypes = [ "enhancedDateTimePicker" ] public var supportedTypes: [String]! { return self._supportedTypes } open func generateSteps(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper, identifierPrefix: String) -> [ORKStep]? { guard let stepDescriptor = RSEnhancedDateTimePickerStepDescriptor(json: jsonObject) else { return nil } let identifier = "\(identifierPrefix).\(stepDescriptor.identifier)" let step = RSEnhancedDateTimePickerStep( identifier: identifier, defaultDate: stepDescriptor.defaultDate, minimumDate: stepDescriptor.minimumDate, maximumDate: stepDescriptor.maximumDate, minuteInterval: stepDescriptor.minuteInterval ) step.title = helper.localizationHelper.localizedString(stepDescriptor.title) step.text = helper.localizationHelper.localizedString(stepDescriptor.text) if let formattedTitle = stepDescriptor.formattedTitle { step.attributedTitle = self.generateAttributedString(descriptor: formattedTitle, helper: helper) } if let formattedText = stepDescriptor.formattedText { step.attributedText = self.generateAttributedString(descriptor: formattedText, helper: helper) } if let buttonText = stepDescriptor.buttonText { step.buttonText = buttonText } step.isOptional = stepDescriptor.optional return [step] } public func processStepResult(type: String, jsonObject: JsonObject, result: ORKStepResult, helper: RSTBTaskBuilderHelper) -> JSON? { return nil } }
apache-2.0
12ab05c5098cf0ec9896c5929d05a989
31.061538
136
0.666027
5.572193
false
false
false
false
shotaroikeda/flashcard-ios
flashcard-ios/AppDelegate.swift
1
3210
// // AppDelegate.swift // flashcard-ios // // Created by Shotaro Ikeda on 2/26/16. // Copyright © 2016 Shotaro Ikeda. All rights reserved. // import UIKit import Firebase var ref = Firebase(url: "https://spartahack2016.firebaseio.com") @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. UIApplication.sharedApplication().setStatusBarStyle(.LightContent, animated: true) let notificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(notificationSettings) UIApplication.sharedApplication().cancelAllLocalNotifications() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. let localNotification = UILocalNotification() localNotification.fireDate = NSDate().dateByAddingTimeInterval(5) // Warn 20 seconds later localNotification.alertBody = "It's time to review!" localNotification.alertAction = "Open" localNotification.category = "closedAndReadyToReviewCategory" localNotification.soundName = UILocalNotificationDefaultSoundName UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } 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. UIApplication.sharedApplication().cancelAllLocalNotifications() } 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
79e2ac28a529ec084ee753ee01806ecc
47.621212
285
0.751324
5.920664
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/MessageAnimator.swift
2
4483
import UIKit import WordPressShared /// NoticeAnimator is a helper class to animate error messages. /// /// The notices show at the top of the target view, and are meant to appear to /// be attached to a navigation bar. The expected usage is to display offline /// status or requests taking longer than usual. /// /// To use an NoticeAnimator, you need to keep a reference to it, and call two /// methods: /// /// - `layout()` from your `UIView.layoutSubviews()` or /// `UIViewController.viewDidLayoutSubviews()`. Failure to do this won't render /// the animation correctly. /// /// - `animateMessage(_)` when you want to change the message displayed. Pass /// nil if you want to hide the error view. /// class MessageAnimator: Animator { // MARK: - Private Constants fileprivate struct Defaults { static let animationDuration = 0.3 static let padding = UIOffset(horizontal: 15, vertical: 20) static let labelFont = WPStyleGuide.regularTextFont() } // MARK: - Private properties fileprivate var previousHeight: CGFloat = 0 fileprivate var message: String? { get { return noticeLabel.label.text } set { noticeLabel.label.text = newValue } } // MARK: - Private Immutable Properties fileprivate let targetView: UIView fileprivate let noticeLabel: PaddedLabel = { let label = PaddedLabel() label.backgroundColor = .primary(.shade40) label.clipsToBounds = true label.padding.horizontal = Defaults.padding.horizontal label.label.textColor = UIColor.white label.label.font = Defaults.labelFont label.label.numberOfLines = 0 return label }() // MARK: - Private Computed Properties fileprivate var shouldDisplayMessage: Bool { return message != nil } fileprivate var targetTableView: UITableView? { return targetView as? UITableView } // MARK: - Initializers @objc init(target: UIView) { targetView = target super.init() } // MARK: - Public Methods @objc func layout() { var targetFrame = noticeLabel.frame targetFrame.size.width = targetView.bounds.width targetFrame.size.height = heightForMessage(message) noticeLabel.frame = targetFrame } @objc func animateMessage(_ message: String?) { let shouldAnimate = self.message != message self.message = message if shouldAnimate { animateWithDuration(Defaults.animationDuration, preamble: preamble, animations: animations, cleanup: cleanup) } } // MARK: - Animation Methods fileprivate func preamble() { UIView.performWithoutAnimation { [weak self] in self?.targetView.layoutIfNeeded() } if shouldDisplayMessage == true && noticeLabel.superview == nil { targetView.addSubview(noticeLabel) noticeLabel.frame.size.height = CGSize.zero.height noticeLabel.label.alpha = 0 } } fileprivate func animations() { let height = heightForMessage(message) if shouldDisplayMessage { // Position + Size + Alpha noticeLabel.frame.origin.y = -height noticeLabel.frame.size.height = height noticeLabel.label.alpha = 1 // Table Insets + Offset targetTableView?.contentInset.top += height - previousHeight if targetTableView?.contentOffset.y == 0 { targetTableView?.contentOffset.y = -height + previousHeight } } else { // Size + Alpha noticeLabel.frame.size.height = CGSize.zero.height noticeLabel.label.alpha = 0 // Table Insets targetTableView?.contentInset.top -= previousHeight } previousHeight = height } fileprivate func cleanup() { if shouldDisplayMessage == false { noticeLabel.removeFromSuperview() previousHeight = CGSize.zero.height } } // MARK: - Helpers fileprivate func heightForMessage(_ message: String?) -> CGFloat { guard let message = message else { return CGSize.zero.height } let size = message.suggestedSize(with: Defaults.labelFont, width: targetView.frame.width) return round(size.height + Defaults.padding.vertical) } }
gpl-2.0
10702e6f9ed05031af459626abb65996
28.688742
121
0.626589
5.042745
false
false
false
false
StanDimitroff/cogs-ios-client-sdk
CogsSDK/Classes/String+Utils.swift
2
1568
// // String+Utils.swift // CogsSDK // /** * Copyright (C) 2017 Aviata Inc. All Rights Reserved. * This code is licensed under the Apache License 2.0 * * This license can be found in the LICENSE.txt at or near the root of the * project or repository. It can also be found here: * http://www.apache.org/licenses/LICENSE-2.0 * * You should have received a copy of the Apache License 2.0 license with this * code or source file. If not, please contact [email protected] */ import Foundation extension String { func split(_ len: Int) -> [String] { var array = [String]() var currentIndex = 0 let length = self.characters.count while currentIndex < length { let startIndex = self.characters.index(self.startIndex, offsetBy: currentIndex) let endIndex = self.characters.index(startIndex, offsetBy: len, limitedBy: self.endIndex) let substr = self.substring(with: startIndex..<endIndex!) array.append(substr) currentIndex += len } return array } func hexToByteArray() -> [UInt8] { return self.split(2).map() { UInt8(strtoul($0, nil, 16)) } } func matches(regex: String) -> Bool { do { let regex = try NSRegularExpression(pattern: regex) let nsString = self as NSString let _ = regex.matches(in: self, range: NSRange(location: 0, length: nsString.length)) return true } catch let error { assertionFailure("Invalid regex: \(error.localizedDescription)") return false } } }
apache-2.0
5c3ef1e45e4b2c24e879fb5d3829d174
26.508772
97
0.641582
4.030848
false
false
false
false
HuangJinyong/iOSDEV
使用UIScrollView创建可滚动的内容/使用UIScrollView创建可滚动的内容/ViewController.swift
1
1288
// // ViewController.swift // 使用UIScrollView创建可滚动的内容 // // Created by Jinyong on 2016/10/16. // Copyright © 2016年 Jinyong. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { let image = UIImage(named: "img") var imageView: UIImageView! var scrollView: UIScrollView! override func viewDidLoad() { super.viewDidLoad() imageView = UIImageView(image: image) scrollView = UIScrollView(frame: view.bounds) scrollView.delegate = self scrollView.addSubview(imageView) scrollView.contentSize = imageView.bounds.size view.addSubview(scrollView) } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 当用户滚动或拖动时触发 scrollView.alpha = 0.5 } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // 当滚动结束时触发 scrollView.alpha = 1 } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { // 当完成拖拽时触发 scrollView.alpha = 1 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
83ece57f18e567ef9b06a1f55715ebf8
23.22
96
0.64327
4.983539
false
false
false
false
jackwilsdon/GTFSKit
GTFSKit/Route.swift
1
1943
// // Route.swift // GTFSKit // import Foundation public struct Route: CSVParsable { public let id: String // route_id (Required) public let agencyId: String? // agency_id (Optional) public let shortName: String // route_short_name (Required) public let longName: String // route_long_name (Required) public let desc: String? // route_desc (Optional) public let type: RouteType // route_type (Required) public let url: String? // route_url (Optional) public let color: String? // route_color (Optional) public let textColor: String? // route_text_color (Optional) public init(id: String, agencyId: String?, shortName: String, longName: String, desc: String?, type: RouteType, url: String?, color: String?, textColor: String?) { self.id = id self.agencyId = agencyId self.shortName = shortName self.longName = longName self.desc = desc self.type = type self.url = url self.color = color self.textColor = textColor } public static func parse(data: CSVData) -> Route? { if !data.containsColumns("route_id", "route_short_name", "route_long_name", "route_type") { return nil } let id = data["route_id"]! let agencyId = data["agency_id"] let shortName = data["route_short_name"]! let longName = data["route_long_name"]! let desc = data["route_desc"] guard let type = data.get("route_type", parser: RouteType.fromString) else { return nil } let url = data["route_url"] let color = data["route_color"] let textColor = data["route_text_color"] return Route(id: id, agencyId: agencyId, shortName: shortName, longName: longName, desc: desc, type: type, url: url, color: color, textColor: textColor) } }
gpl-3.0
e22a37faf5723c70aa263da346f936c4
35.660377
167
0.592898
3.989733
false
false
false
false
Rochester-Ting/DouyuTVDemo
RRDouyuTV/RRDouyuTV/Classes/Home(首页)/GameView.swift
1
1996
// // GameView.swift // RRDouyuTV // // Created by 丁瑞瑞 on 16/10/16. // Copyright © 2016年 Rochester. All rights reserved. // import UIKit fileprivate let kgameCellId = "kgameCellId" fileprivate let kItemSize = 70 fileprivate let kMargin = 10 class GameView: UIView { @IBOutlet weak var collectionView: UICollectionView! var gameArrs : [RGameModel]?{ didSet { collectionView.reloadData() } } override func awakeFromNib() { super.awakeFromNib() collectionView.register(UINib(nibName: "GameViewCell", bundle: nil), forCellWithReuseIdentifier: kgameCellId) collectionView.contentInset = UIEdgeInsetsMake(0, CGFloat(kMargin), 0, CGFloat(kMargin)) collectionView.showsHorizontalScrollIndicator = false // collectionView.backgroundColor = UIColor.red } class func gameView()->GameView{ return Bundle.main.loadNibNamed("GameView", owner: nil, options: nil)?.first as! GameView } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: kItemSize, height: kItemSize) layout.minimumLineSpacing = CGFloat(kMargin) layout.minimumInteritemSpacing = CGFloat(kMargin) layout.scrollDirection = .horizontal } } extension GameView : UICollectionViewDelegate{ } extension GameView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameArrs?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kgameCellId, for: indexPath) as! GameViewCell cell.gameModel = gameArrs![indexPath.item] cell.line.isHidden = true return cell } }
mit
26aaf6c57019589bc2cb83e11925b3f6
34.482143
121
0.705586
5.081841
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleContactCell.swift
1
9859
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import AddressBookUI import MessageUI public class AABubbleContactCell: AABubbleCell, ABNewPersonViewControllerDelegate, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate { private let avatar = AAAvatarView() private let name = UILabel() private let contact = UILabel() private var bindedRecords = [String]() private let tapView = UIView() public init(frame: CGRect) { super.init(frame: frame, isFullSize: false) name.font = UIFont.mediumSystemFontOfSize(17) contact.font = UIFont.systemFontOfSize(15) tapView.backgroundColor = UIColor.clearColor() contentView.addSubview(avatar) contentView.addSubview(name) contentView.addSubview(contact) contentView.addSubview(tapView) contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) tapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleContactCell.contactDidTap))) tapView.userInteractionEnabled = true } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func contactDidTap() { if let m = bindedMessage { if let c = m.content as? ACContactContent { let menuBuilder = AAMenuBuilder() let phones = c.getPhones() for i in 0..<phones.size() { let p = phones.getWithInt(i) as! String menuBuilder.add(p, closure: { () -> () in if let url = NSURL(string: "tel:\(p)") { if !UIApplication.sharedApplication().openURL(url) { self.controller.alertUser("ErrorUnableToCall") } } else { self.controller.alertUser("ErrorUnableToCall") } }) } let emails = c.getEmails() for i in 0..<emails.size() { let e = emails.getWithInt(i) as! String menuBuilder.add(e, closure: { () -> () in let emailController = MFMailComposeViewController() emailController.delegate = self emailController.setToRecipients([e]) self.controller.presentViewController(emailController, animated: true, completion: nil) }) } menuBuilder.add(AALocalized("ProfileAddToContacts"), closure: { () -> () in let add = ABNewPersonViewController() add.newPersonViewDelegate = self let person: ABRecordRef = ABPersonCreate().takeRetainedValue() let name = c.getName().trim() let nameParts = name.componentsSeparatedByString(" ") ABRecordSetValue(person, kABPersonFirstNameProperty, nameParts[0], nil) if (nameParts.count >= 2) { let lastName = name.substringFromIndex(nameParts[0].endIndex).trim() ABRecordSetValue(person, kABPersonLastNameProperty, lastName, nil) } if (phones.size() > 0) { let phonesValues: ABMultiValueRef = ABMultiValueCreateMutable(UInt32(kABMultiStringPropertyType)).takeRetainedValue() for i in 0..<phones.size() { let p = phones.getWithInt(i) as! String ABMultiValueAddValueAndLabel(phonesValues, p.replace(" ", dest: ""), kABPersonPhoneMainLabel, nil) } ABRecordSetValue(person, kABPersonPhoneProperty, phonesValues, nil) } if (emails.size() > 0) { let phonesValues: ABMultiValueRef = ABMultiValueCreateMutable(UInt32(kABMultiStringPropertyType)).takeRetainedValue() for i in 0..<emails.size() { let p = emails.getWithInt(i) as! String ABMultiValueAddValueAndLabel(phonesValues, p.replace(" ", dest: ""), kABPersonPhoneMainLabel, nil) } ABRecordSetValue(person, kABPersonEmailProperty, phonesValues, nil) } add.displayedPerson = person self.controller.presentViewController(AANavigationController(rootViewController: add), animated: true, completion: nil) }) controller.showActionSheet(menuBuilder.items, cancelButton: "AlertCancel", destructButton: nil, sourceView: tapView, sourceRect: tapView.bounds, tapClosure: menuBuilder.tapClosure) } } } public func newPersonViewController(newPersonView: ABNewPersonViewController, didCompleteWithNewPerson person: ABRecord?) { newPersonView.dismissViewControllerAnimated(true, completion: nil) } public func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } public override func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) { let contactLayout = cellLayout as! AAContactCellLayout // Always update bubble insets if (isOut) { bindBubbleType(.TextOut, isCompact: false) bubbleInsets = UIEdgeInsets( top: AABubbleCell.bubbleTop, left: 0 + (AADevice.isiPad ? 16 : 0), bottom: AABubbleCell.bubbleBottom, right: 4 + (AADevice.isiPad ? 16 : 0)) contentInsets = UIEdgeInsets( top: AABubbleCell.bubbleContentTop, left: 6, bottom: AABubbleCell.bubbleContentBottom, right: 10) name.textColor = ActorSDK.sharedActor().style.chatTextOutColor } else { bindBubbleType(.TextIn, isCompact: false) bubbleInsets = UIEdgeInsets( top: AABubbleCell.bubbleTop, left: 4 + (AADevice.isiPad ? 16 : 0), bottom: AABubbleCell.bubbleBottom, right: 0 + (AADevice.isiPad ? 16 : 0)) contentInsets = UIEdgeInsets( top: (isGroup ? 18 : 0) + AABubbleCell.bubbleContentTop, left: 13, bottom: AABubbleCell.bubbleContentBottom, right: 10) name.textColor = ActorSDK.sharedActor().style.chatTextInColor } name.text = contactLayout.name var s = "" for i in contactLayout.records { if (s != ""){ s += "\n" } s += i } contact.text = s contact.numberOfLines = contactLayout.records.count bindedRecords = contactLayout.records avatar.bind(contactLayout.name, id: 0, avatar: nil) } public override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { // Convenience let insets = fullContentInsets let contentWidth = self.contentView.frame.width let height = max(44, bindedRecords.count * 18 + 22) layoutBubble(200, contentHeight: CGFloat(height)) if (isOut) { avatar.frame = CGRectMake(contentWidth - insets.right - 200, insets.top, 44, 44) tapView.frame = CGRectMake(contentWidth - insets.left - 200, insets.top, 200, CGFloat(height)) } else { avatar.frame = CGRectMake(insets.left, insets.top, 44, 44) tapView.frame = CGRectMake(insets.left, insets.top, 200, CGFloat(height)) } name.frame = CGRectMake(avatar.right + 6, insets.top, 200 - 58, 22) contact.frame = CGRectMake(avatar.right + 6, insets.top + 22, 200 - 58, 200) contact.sizeToFit() } } public class AAContactCellLayout: AACellLayout { let name: String let records: [String] init(name: String, records: [String], date: Int64, layouter: AABubbleLayouter) { self.name = name self.records = records let height = max(44, records.count * 18 + 22) + 12 super.init(height: CGFloat(height), date: date, key: "location", layouter: layouter) } } public class AABubbleContactCellLayouter: AABubbleLayouter { public func isSuitable(message: ACMessage) -> Bool { if (!ActorSDK.sharedActor().enableExperimentalFeatures) { return false } if (message.content is ACContactContent) { return true } return false } public func cellClass() -> AnyClass { return AABubbleContactCell.self } public func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout { let content = message.content as! ACContactContent var records = [String]() for i in 0..<content.getPhones().size() { records.append(content.getPhones().getWithInt(i) as! String) } for i in 0..<content.getEmails().size() { records.append(content.getEmails().getWithInt(i) as! String) } return AAContactCellLayout(name: content.getName(), records: records, date: Int64(message.date), layouter: self) } }
agpl-3.0
04682b6d2928513c85ead0f9f758cb9e
42.245614
196
0.569632
5.238576
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGeometry/Geometry/Vector.swift
1
6791
// // Vector.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // @frozen public struct Vector: Hashable { public var x: Double public var y: Double public var z: Double @inlinable @inline(__always) public init() { self.x = 0 self.y = 0 self.z = 0 } @inlinable @inline(__always) public init(x: Int, y: Int, z: Int) { self.x = Double(x) self.y = Double(y) self.z = Double(z) } @inlinable @inline(__always) public init(x: Double, y: Double, z: Double) { self.x = x self.y = y self.z = z } @inlinable @inline(__always) public init<T: BinaryInteger>(x: T, y: T, z: T) { self.x = Double(x) self.y = Double(y) self.z = Double(z) } @inlinable @inline(__always) public init<T: BinaryFloatingPoint>(x: T, y: T, z: T) { self.x = Double(x) self.y = Double(y) self.z = Double(z) } } extension Vector { @inlinable @inline(__always) public var magnitude: Double { get { return hypot(hypot(x, y), z) } set { let m = self.magnitude let scale = m == 0 ? 0 : newValue / m self *= scale } } } extension Vector: CustomStringConvertible { @inlinable @inline(__always) public var description: String { return "Vector(x: \(x), y: \(y), z: \(z))" } } extension Vector: Codable { @inlinable @inline(__always) public init(from decoder: Decoder) throws { var container = try decoder.unkeyedContainer() self.x = try container.decode(Double.self) self.y = try container.decode(Double.self) self.z = try container.decode(Double.self) } @inlinable @inline(__always) public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(x) try container.encode(y) try container.encode(z) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension Vector: Sendable { } extension Vector { @inlinable @inline(__always) public func offset(dx: Double, dy: Double, dz: Double) -> Vector { return Vector(x: self.x + dx, y: self.y + dy, z: self.z + dz) } } extension Vector: Tensor { public typealias Indices = Range<Int> public typealias Scalar = Double @inlinable @inline(__always) public static var numberOfComponents: Int { return 3 } @inlinable @inline(__always) public subscript(position: Int) -> Double { get { return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] } } set { withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue } } } @inlinable @inline(__always) public func map(_ transform: (Double) -> Double) -> Vector { return Vector(x: transform(x), y: transform(y), z: transform(z)) } @inlinable @inline(__always) public func combined(_ other: Vector, _ transform: (Double, Double) -> Double) -> Vector { return Vector(x: transform(self.x, other.x), y: transform(self.y, other.y), z: transform(self.z, other.z)) } @inlinable @inline(__always) public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result { var accumulator = initialResult updateAccumulatingResult(&accumulator, x) updateAccumulatingResult(&accumulator, y) updateAccumulatingResult(&accumulator, z) return accumulator } } @inlinable @inline(__always) public func dot(_ lhs: Vector, _ rhs: Vector) -> Double { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z } @inlinable @inline(__always) public func cross(_ lhs: Vector, _ rhs: Vector) -> Vector { return Vector(x: lhs.y * rhs.z - lhs.z * rhs.y, y: lhs.z * rhs.x - lhs.x * rhs.z, z: lhs.x * rhs.y - lhs.y * rhs.x) } @inlinable @inline(__always) public prefix func +(val: Vector) -> Vector { return val } @inlinable @inline(__always) public prefix func -(val: Vector) -> Vector { return Vector(x: -val.x, y: -val.y, z: -val.z) } @inlinable @inline(__always) public func +(lhs: Vector, rhs: Vector) -> Vector { return Vector(x: lhs.x + rhs.x, y: lhs.y + rhs.y, z: lhs.z + rhs.z) } @inlinable @inline(__always) public func -(lhs: Vector, rhs: Vector) -> Vector { return Vector(x: lhs.x - rhs.x, y: lhs.y - rhs.y, z: lhs.z - rhs.z) } @inlinable @inline(__always) public func *(lhs: Double, rhs: Vector) -> Vector { return Vector(x: lhs * rhs.x, y: lhs * rhs.y, z: lhs * rhs.z) } @inlinable @inline(__always) public func *(lhs: Vector, rhs: Double) -> Vector { return Vector(x: lhs.x * rhs, y: lhs.y * rhs, z: lhs.z * rhs) } @inlinable @inline(__always) public func /(lhs: Vector, rhs: Double) -> Vector { return Vector(x: lhs.x / rhs, y: lhs.y / rhs, z: lhs.z / rhs) } @inlinable @inline(__always) public func *= (lhs: inout Vector, rhs: Double) { lhs.x *= rhs lhs.y *= rhs lhs.z *= rhs } @inlinable @inline(__always) public func /= (lhs: inout Vector, rhs: Double) { lhs.x /= rhs lhs.y /= rhs lhs.z /= rhs } @inlinable @inline(__always) public func += (lhs: inout Vector, rhs: Vector) { lhs.x += rhs.x lhs.y += rhs.y lhs.z += rhs.z } @inlinable @inline(__always) public func -= (lhs: inout Vector, rhs: Vector) { lhs.x -= rhs.x lhs.y -= rhs.y lhs.z -= rhs.z }
mit
ca24e50833b4d1e3a864a5a02b27a6c4
26.055777
130
0.60536
3.546214
false
false
false
false
jemartti/OnTheMap
OnTheMap/UdacityClient.swift
1
8841
// // UdacityClient.swift // OnTheMap // // Created by Jacob Marttinen on 3/5/17. // Copyright © 2017 Jacob Marttinen. All rights reserved. // import Foundation // MARK: - UdacityClient: NSObject class UdacityClient : NSObject { // MARK: Properties // shared session var session = URLSession.shared // authentication state var sessionID: String? = nil var userKey: String? = nil var user: UdacityUser? = nil // MARK: Initializers override init() { super.init() session = { let configuration = URLSessionConfiguration.default configuration.timeoutIntervalForRequest = 5 configuration.timeoutIntervalForResource = 5 return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil) }() } // MARK: GET func taskForGETMethod(_ method: String, completionHandlerForGET: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask { /* Build the URL, Configure the request */ let request = NSMutableURLRequest(url: udacityURLWithPathExtension(method)) /* Make the request */ let task = session.dataTask(with: request as URLRequest) { (data, response, error) in func sendError(_ error: String) { let userInfo = [NSLocalizedDescriptionKey : error] completionHandlerForGET(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo)) } /* GUARD: Was there an error? */ guard (error == nil) else { sendError("The request failed (likely due to a network issue). Check your settings and try again.") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sendError("The request failed due to a server error. Try again later.") return } if statusCode < 200 || statusCode > 299 { if statusCode == 403 { sendError("Invalid credentials.") } else { sendError("The request failed due to a server error (\(statusCode)). Try again later.") } return } /* GUARD: Was there any data returned? */ guard let data = data else { sendError("The request failed due to a server error. Try again later.") return } /* Parse the data and use the data (happens in completion handler) */ let range = Range(uncheckedBounds: (5, data.count)) let newData = data.subdata(in: range) ClientHelpers.convertDataWithCompletionHandler(newData, completionHandlerForConvertData: completionHandlerForGET) } /* Start the request */ task.resume() return task } // MARK: POST func taskForPOSTMethod(_ method: String, jsonBody: String, completionHandlerForPOST: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask { /* Build the URL, Configure the request */ let request = NSMutableURLRequest(url: udacityURLWithPathExtension(method)) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Accept") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = jsonBody.data(using: String.Encoding.utf8) /* Make the request */ let task = session.dataTask(with: request as URLRequest) { (data, response, error) in func sendError(_ error: String) { let userInfo = [NSLocalizedDescriptionKey : error] completionHandlerForPOST(nil, NSError(domain: "taskForPOSTMethod", code: 1, userInfo: userInfo)) } /* GUARD: Was there an error? */ guard (error == nil) else { sendError("The request failed (likely due to a network issue). Check your settings and try again.") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sendError("The request failed due to a server error. Try again later.") return } if statusCode < 200 || statusCode > 299 { if statusCode == 403 { sendError("Invalid credentials.") } else { sendError("The request failed due to a server error (\(statusCode)). Try again later.") } return } /* GUARD: Was there any data returned? */ guard let data = data else { sendError("The request failed due to a server error. Try again later.") return } /* Parse the data and use the data (happens in completion handler) */ let range = Range(uncheckedBounds: (5, data.count)) let newData = data.subdata(in: range) ClientHelpers.convertDataWithCompletionHandler(newData, completionHandlerForConvertData: completionHandlerForPOST) } /* Start the request */ task.resume() return task } // MARK: DELETE func taskForDELETEMethod(_ method: String, xsrfCookie: HTTPCookie?, completionHandlerForDELETE: @escaping (_ result: AnyObject?, _ error: NSError?) -> Void) -> URLSessionDataTask { /* Build the URL, Configure the request */ let request = NSMutableURLRequest(url: udacityURLWithPathExtension(method)) request.httpMethod = "DELETE" if let xsrfCookie = xsrfCookie { request.setValue(xsrfCookie.value, forHTTPHeaderField: "X-XSRF-TOKEN") } /* Make the request */ let task = session.dataTask(with: request as URLRequest) { (data, response, error) in func sendError(_ error: String) { let userInfo = [NSLocalizedDescriptionKey : error] completionHandlerForDELETE(nil, NSError(domain: "taskForDELETEMethod", code: 1, userInfo: userInfo)) } /* GUARD: Was there an error? */ guard (error == nil) else { sendError("The request failed (likely due to a network issue). Check your settings and try again.") return } /* GUARD: Did we get a successful 2XX response? */ guard let statusCode = (response as? HTTPURLResponse)?.statusCode else { sendError("The request failed due to a server error. Try again later.") return } if statusCode < 200 || statusCode > 299 { if statusCode == 403 { sendError("Invalid credentials.") } else { sendError("The request failed due to a server error (\(statusCode)). Try again later.") } return } /* GUARD: Was there any data returned? */ guard let data = data else { sendError("The request failed due to a server error. Try again later.") return } /* Parse the data and use the data (happens in completion handler) */ let range = Range(uncheckedBounds: (5, data.count)) let newData = data.subdata(in: range) ClientHelpers.convertDataWithCompletionHandler(newData, completionHandlerForConvertData: completionHandlerForDELETE) } /* Start the request */ task.resume() return task } // MARK: Helpers // create a URL from parameters private func udacityURLWithPathExtension(_ pathExtension: String? = nil) -> URL { var components = URLComponents() components.scheme = UdacityClient.Constants.ApiScheme components.host = UdacityClient.Constants.ApiHost components.path = UdacityClient.Constants.ApiPath + (pathExtension ?? "") return components.url! } // MARK: Shared Instance class func sharedInstance() -> UdacityClient { struct Singleton { static var sharedInstance = UdacityClient() } return Singleton.sharedInstance } }
mit
5aa797ad9b5470009800077bdb88d0de
37.60262
184
0.561312
5.594937
false
false
false
false
xedin/swift
stdlib/public/core/StringStorage.swift
2
24482
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims // Having @objc stuff in an extension creates an ObjC category, which we don't // want. #if _runtime(_ObjC) internal protocol _AbstractStringStorage : _NSCopying { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } var UTF16Length: Int { get } } internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */ internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */ @_effects(readonly) private func _isNSString(_ str:AnyObject) -> UInt8 { return _swift_stdlib_isNSString(str) } #else internal protocol _AbstractStringStorage { var asString: String { get } var count: Int { get } var isASCII: Bool { get } var start: UnsafePointer<UInt8> { get } } #endif extension _AbstractStringStorage { // ObjC interfaces. #if _runtime(_ObjC) @inline(__always) @_effects(releasenone) internal func _getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange ) { _precondition(aRange.location >= 0 && aRange.length >= 0, "Range out of bounds") _precondition(aRange.location + aRange.length <= Int(count), "Range out of bounds") let range = Range( uncheckedBounds: (aRange.location, aRange.location+aRange.length)) let str = asString str._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(start: buffer, count: range.count), range: range) } @inline(__always) @_effects(releasenone) internal func _getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): guard maxLength >= count + 1 else { return 0 } outputPtr.initialize(from: start, count: count) outputPtr[count] = 0 return 1 default: return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding) } } @inline(__always) @_effects(readonly) internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): return start default: return _cocoaCStringUsingEncodingTrampoline(self, encoding) } } @_effects(readonly) internal func _nativeIsEqual<T:_AbstractStringStorage>( _ nativeOther: T ) -> Int8 { if count != nativeOther.count { return 0 } return (start == nativeOther.start || (memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0 } @inline(__always) @_effects(readonly) internal func _isEqual(_ other: AnyObject?) -> Int8 { guard let other = other else { return 0 } if self === other { return 1 } // Handle the case where both strings were bridged from Swift. // We can't use String.== because it doesn't match NSString semantics. let knownOther = _KnownCocoaString(other) switch knownOther { case .storage: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __StringStorage.self)) case .shared: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __SharedStringStorage.self)) #if !(arch(i386) || arch(arm)) case .tagged: fallthrough #endif case .cocoa: // We're allowed to crash, but for compatibility reasons NSCFString allows // non-strings here. if _isNSString(other) != 1 { return 0 } // At this point we've proven that it is an NSString of some sort, but not // one of ours. defer { _fixLifetime(other) } let otherUTF16Length = _stdlib_binary_CFStringGetLength(other) // CFString will only give us ASCII bytes here, but that's fine. // We already handled non-ASCII UTF8 strings earlier since they're Swift. if let otherStart = _cocoaUTF8Pointer(other) { //We know that otherUTF16Length is also its byte count at this point if count != otherUTF16Length { return 0 } return (start == otherStart || (memcmp(start, otherStart, count) == 0)) ? 1 : 0 } if UTF16Length != otherUTF16Length { return 0 } /* The abstract implementation of -isEqualToString: falls back to -compare: immediately, so when we run out of fast options to try, do the same. We can likely be more clever here if need be */ return _cocoaStringCompare(self, other) == 0 ? 1 : 0 } } #endif //_runtime(_ObjC) } private typealias CountAndFlags = _StringObject.CountAndFlags // // TODO(String docs): Documentation about the runtime layout of these instances, // which is a little complex. The second trailing allocation holds an // Optional<_StringBreadcrumbs>. // // NOTE: older runtimes called this class _StringStorage. The two // must coexist without conflicting ObjC class names, so it was // renamed. The old name must not be used in the new runtime. final internal class __StringStorage : __SwiftNativeNSString, _AbstractStringStorage { #if arch(i386) || arch(arm) // The total allocated storage capacity. Note that this includes the required // nul-terminator. internal var _realCapacity: Int internal var _count: Int internal var _flags: UInt16 internal var _reserved: UInt16 @inline(__always) internal var count: Int { return _count } @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else // The capacity of our allocation. Note that this includes the nul-terminator, // which is not available for overriding. internal var _realCapacityAndFlags: UInt64 internal var _countAndFlags: _StringObject.CountAndFlags @inline(__always) internal var count: Int { return _countAndFlags.count } // The total allocated storage capacity. Note that this includes the required // nul-terminator. @inline(__always) internal var _realCapacity: Int { return Int(truncatingIfNeeded: _realCapacityAndFlags & CountAndFlags.countMask) } #endif @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var UTF16Length: Int { @_effects(readonly) @inline(__always) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) private init(_doNotCallMe: ()) { _internalInvariantFailure("Use the create method") } deinit { _breadcrumbsAddress.deinitialize(count: 1) } } // Determine the actual number of code unit capacity to request from malloc. We // round up the nearest multiple of 8 that isn't a mulitple of 16, to fully // utilize malloc's small buckets while accounting for the trailing // _StringBreadCrumbs. // // NOTE: We may still under-utilize the spare bytes from the actual allocation // for Strings ~1KB or larger, though at this point we're well into our growth // curve. private func determineCodeUnitCapacity(_ desiredCapacity: Int) -> Int { #if arch(i386) || arch(arm) // FIXME: Adapt to actual 32-bit allocator. For now, let's arrange things so // that the instance size will be a multiple of 4. let bias = Int(bitPattern: _StringObject.nativeBias) let minimum = bias + desiredCapacity + 1 let size = (minimum + 3) & ~3 _internalInvariant(size % 4 == 0) let capacity = size - bias _internalInvariant(capacity > desiredCapacity) return capacity #else // Bigger than _SmallString, and we need 1 extra for nul-terminator. let minCap = 1 + Swift.max(desiredCapacity, _SmallString.capacity) _internalInvariant(minCap < 0x1_0000_0000_0000, "max 48-bit length") // Round up to the nearest multiple of 8 that isn't also a multiple of 16. let capacity = ((minCap + 7) & -16) + 8 _internalInvariant( capacity > desiredCapacity && capacity % 8 == 0 && capacity % 16 != 0) return capacity #endif } // Creation extension __StringStorage { @_effects(releasenone) private static func create( realCodeUnitCapacity: Int, countAndFlags: CountAndFlags ) -> __StringStorage { let storage = Builtin.allocWithTailElems_2( __StringStorage.self, realCodeUnitCapacity._builtinWordValue, UInt8.self, 1._builtinWordValue, Optional<_StringBreadcrumbs>.self) #if arch(i386) || arch(arm) storage._realCapacity = realCodeUnitCapacity storage._count = countAndFlags.count storage._flags = countAndFlags.flags #else storage._realCapacityAndFlags = UInt64(truncatingIfNeeded: realCodeUnitCapacity) storage._countAndFlags = countAndFlags #endif storage._breadcrumbsAddress.initialize(to: nil) storage.terminator.pointee = 0 // nul-terminated // NOTE: We can't _invariantCheck() now, because code units have not been // initialized. But, _StringGuts's initializer will. return storage } @_effects(releasenone) private static func create( capacity: Int, countAndFlags: CountAndFlags ) -> __StringStorage { _internalInvariant(capacity >= countAndFlags.count) let realCapacity = determineCodeUnitCapacity(capacity) _internalInvariant(realCapacity > capacity) return __StringStorage.create( realCodeUnitCapacity: realCapacity, countAndFlags: countAndFlags) } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, capacity: Int, isASCII: Bool ) -> __StringStorage { let countAndFlags = CountAndFlags( mortalCount: bufPtr.count, isASCII: isASCII) _internalInvariant(capacity >= bufPtr.count) let storage = __StringStorage.create( capacity: capacity, countAndFlags: countAndFlags) let addr = bufPtr.baseAddress._unsafelyUnwrappedUnchecked storage.mutableStart.initialize(from: addr, count: bufPtr.count) storage._invariantCheck() return storage } @_effects(releasenone) internal static func create( initializingFrom bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool ) -> __StringStorage { return __StringStorage.create( initializingFrom: bufPtr, capacity: bufPtr.count, isASCII: isASCII) } } // Usage extension __StringStorage { @inline(__always) private var mutableStart: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(Builtin.projectTailElems(self, UInt8.self)) } @inline(__always) private var mutableEnd: UnsafeMutablePointer<UInt8> { return mutableStart + count } @inline(__always) internal var start: UnsafePointer<UInt8> { return UnsafePointer(mutableStart) } @inline(__always) private final var end: UnsafePointer<UInt8> { return UnsafePointer(mutableEnd) } // Point to the nul-terminator. @inline(__always) private final var terminator: UnsafeMutablePointer<UInt8> { return mutableEnd } @inline(__always) private var codeUnits: UnsafeBufferPointer<UInt8> { return UnsafeBufferPointer(start: start, count: count) } // @opaque internal var _breadcrumbsAddress: UnsafeMutablePointer<_StringBreadcrumbs?> { let raw = Builtin.getTailAddr_Word( start._rawValue, _realCapacity._builtinWordValue, UInt8.self, Optional<_StringBreadcrumbs>.self) return UnsafeMutablePointer(raw) } // The total capacity available for code units. Note that this excludes the // required nul-terminator. internal var capacity: Int { return _realCapacity &- 1 } // The unused capacity available for appending. Note that this excludes the // required nul-terminator. // // NOTE: Callers who wish to mutate this storage should enfore nul-termination @inline(__always) private var unusedStorage: UnsafeMutableBufferPointer<UInt8> { return UnsafeMutableBufferPointer( start: mutableEnd, count: unusedCapacity) } // The capacity available for appending. Note that this excludes the required // nul-terminator. internal var unusedCapacity: Int { return _realCapacity &- count &- 1 } #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { let rawSelf = UnsafeRawPointer(Builtin.bridgeToRawPointer(self)) let rawStart = UnsafeRawPointer(start) _internalInvariant(unusedCapacity >= 0) _internalInvariant(count <= capacity) _internalInvariant(rawSelf + Int(_StringObject.nativeBias) == rawStart) _internalInvariant(self._realCapacity > self.count, "no room for nul-terminator") _internalInvariant(self.terminator.pointee == 0, "not nul terminated") let str = asString _internalInvariant(str._guts._object.isPreferredRepresentation) _countAndFlags._invariantCheck() if isASCII { _internalInvariant(_allASCII(self.codeUnits)) } if let crumbs = _breadcrumbsAddress.pointee { crumbs._invariantCheck(for: self.asString) } _internalInvariant(_countAndFlags.isNativelyStored) _internalInvariant(_countAndFlags.isTailAllocated) } #endif // INTERNAL_CHECKS_ENABLED } // Appending extension __StringStorage { // Perform common post-RRC adjustments and invariant enforcement. @_effects(releasenone) private func _postRRCAdjust(newCount: Int, newIsASCII: Bool) { let countAndFlags = CountAndFlags( mortalCount: newCount, isASCII: newIsASCII) #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif self.terminator.pointee = 0 // TODO(String performance): Consider updating breadcrumbs when feasible. self._breadcrumbsAddress.pointee = nil _invariantCheck() } // Perform common post-append adjustments and invariant enforcement. @_effects(releasenone) private func _postAppendAdjust( appendedCount: Int, appendedIsASCII isASCII: Bool ) { let oldTerminator = self.terminator _postRRCAdjust( newCount: self.count + appendedCount, newIsASCII: self.isASCII && isASCII) _internalInvariant(oldTerminator + appendedCount == self.terminator) } @_effects(releasenone) internal func appendInPlace( _ other: UnsafeBufferPointer<UInt8>, isASCII: Bool ) { _internalInvariant(self.capacity >= other.count) let srcAddr = other.baseAddress._unsafelyUnwrappedUnchecked let srcCount = other.count self.mutableEnd.initialize(from: srcAddr, count: srcCount) _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } @_effects(releasenone) internal func appendInPlace<Iter: IteratorProtocol>( _ other: inout Iter, isASCII: Bool ) where Iter.Element == UInt8 { var srcCount = 0 while let cu = other.next() { _internalInvariant(self.unusedCapacity >= 1) unusedStorage[srcCount] = cu srcCount += 1 } _postAppendAdjust(appendedCount: srcCount, appendedIsASCII: isASCII) } internal func clear() { _postRRCAdjust(newCount: 0, newIsASCII: true) } } // Removing extension __StringStorage { @_effects(releasenone) internal func remove(from lower: Int, to upper: Int) { _internalInvariant(lower <= upper) let lowerPtr = mutableStart + lower let upperPtr = mutableStart + upper let tailCount = mutableEnd - upperPtr lowerPtr.moveInitialize(from: upperPtr, count: tailCount) _postRRCAdjust( newCount: self.count &- (upper &- lower), newIsASCII: self.isASCII) } // Reposition a tail of this storage from src to dst. Returns the length of // the tail. @_effects(releasenone) internal func _slideTail( src: UnsafeMutablePointer<UInt8>, dst: UnsafeMutablePointer<UInt8> ) -> Int { _internalInvariant(dst >= mutableStart && src <= mutableEnd) let tailCount = mutableEnd - src dst.moveInitialize(from: src, count: tailCount) return tailCount } @_effects(releasenone) internal func replace( from lower: Int, to upper: Int, with replacement: UnsafeBufferPointer<UInt8> ) { _internalInvariant(lower <= upper) let replCount = replacement.count _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. lowerPtr.moveInitialize( from: UnsafeMutablePointer( mutating: replacement.baseAddress._unsafelyUnwrappedUnchecked), count: replCount) let isASCII = self.isASCII && _allASCII(replacement) _postRRCAdjust(newCount: lower + replCount + tailCount, newIsASCII: isASCII) } @_effects(releasenone) internal func replace<C: Collection>( from lower: Int, to upper: Int, with replacement: C, replacementCount replCount: Int ) where C.Element == UInt8 { _internalInvariant(lower <= upper) _internalInvariant(replCount - (upper - lower) <= unusedCapacity) // Position the tail. let lowerPtr = mutableStart + lower let tailCount = _slideTail( src: mutableStart + upper, dst: lowerPtr + replCount) // Copy in the contents. var isASCII = self.isASCII var srcCount = 0 for cu in replacement { if cu >= 0x80 { isASCII = false } lowerPtr[srcCount] = cu srcCount += 1 } _internalInvariant(srcCount == replCount) _postRRCAdjust( newCount: lower + replCount + tailCount, newIsASCII: isASCII) } } // For shared storage and bridging literals // NOTE: older runtimes called this class _SharedStringStorage. The two // must coexist without conflicting ObjC class names, so it was // renamed. The old name must not be used in the new runtime. final internal class __SharedStringStorage : __SwiftNativeNSString, _AbstractStringStorage { internal var _owner: AnyObject? internal var start: UnsafePointer<UInt8> #if arch(i386) || arch(arm) internal var _count: Int internal var _flags: UInt16 @inline(__always) internal var _countAndFlags: _StringObject.CountAndFlags { return CountAndFlags(count: _count, flags: _flags) } #else internal var _countAndFlags: _StringObject.CountAndFlags #endif internal var _breadcrumbs: _StringBreadcrumbs? = nil internal var count: Int { return _countAndFlags.count } internal init( immortal ptr: UnsafePointer<UInt8>, countAndFlags: _StringObject.CountAndFlags ) { self._owner = nil self.start = ptr #if arch(i386) || arch(arm) self._count = countAndFlags.count self._flags = countAndFlags.flags #else self._countAndFlags = countAndFlags #endif super.init() self._invariantCheck() } @inline(__always) final internal var isASCII: Bool { return _countAndFlags.isASCII } final internal var asString: String { @_effects(readonly) @inline(__always) get { return String(_StringGuts(self)) } } #if _runtime(_ObjC) @objc(length) final internal var UTF16Length: Int { @_effects(readonly) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc(isEqualToString:) @_effects(readonly) final internal func isEqual(to other:AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } #endif // _runtime(_ObjC) } extension __SharedStringStorage { #if !INTERNAL_CHECKS_ENABLED @inline(__always) internal func _invariantCheck() {} #else internal func _invariantCheck() { if let crumbs = _breadcrumbs { crumbs._invariantCheck(for: self.asString) } _countAndFlags._invariantCheck() _internalInvariant(!_countAndFlags.isNativelyStored) _internalInvariant(!_countAndFlags.isTailAllocated) let str = asString _internalInvariant(!str._guts._object.isPreferredRepresentation) } #endif // INTERNAL_CHECKS_ENABLED }
apache-2.0
5a99c4bfd45ffee73b8a57112f7417d1
28.892552
85
0.689772
4.267387
false
false
false
false
apple/swift-syntax
Sources/_SwiftSyntaxMacros/MacroSystem.swift
1
4241
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 SwiftDiagnostics import SwiftSyntax /// Describes the kinds of errors that can occur within a macro system. public enum MacroSystemError: Error { /// Indicates that a macro with the given name has already been defined. case alreadyDefined(new: Macro.Type, existing: Macro.Type) /// Indicates that an unknown macro was encountered during expansion. case unknownMacro(name: String, node: Syntax) /// Indicates that a macro evaluated as an expression by the given node /// is not an expression macro. case requiresExpressionMacro(macro: Macro.Type, node: Syntax) /// Indicates that a macro evaluated as a code item by the given node /// is not suitable for code items. case requiresCodeItemMacro(macro: Macro.Type, node: Syntax) /// Indicates that a macro produced diagnostics during evaluation. The /// diagnostics might not specifically include errors, but will be reported /// nonetheless. case evaluationDiagnostics(node: Syntax, diagnostics: [Diagnostic]) } /// A system of known macros that can be expanded syntactically public struct MacroSystem { var macros: [String : Macro.Type] = [:] /// Create an empty macro system. public init() { } /// Add a macro to the system. /// /// Throws an error if there is already a macro with this name. public mutating func add(_ macro: Macro.Type) throws { if let knownMacro = macros[macro.name] { throw MacroSystemError.alreadyDefined(new: macro, existing: knownMacro) } macros[macro.name] = macro } /// Look for a macro with the given name. public func lookup(_ macroName: String) -> Macro.Type? { return macros[macroName] } } /// Syntax rewriter that evaluates any macros encountered along the way. class MacroApplication : SyntaxRewriter { let macroSystem: MacroSystem let context: MacroEvaluationContext let errorHandler: (MacroSystemError) -> Void init( macroSystem: MacroSystem, context: MacroEvaluationContext, errorHandler: @escaping (MacroSystemError) -> Void ) { self.macroSystem = macroSystem self.context = context self.errorHandler = errorHandler } override func visitAny(_ node: Syntax) -> Syntax? { guard node.evaluatedMacroName != nil else { return nil } return node.evaluateMacro( with: macroSystem, context: context, errorHandler: errorHandler ) } override func visit(_ node: CodeBlockItemListSyntax) -> CodeBlockItemListSyntax { var newItems: [CodeBlockItemSyntax] = [] for item in node { // Recurse on the child node. let newItem = visit(item.item) // Flatten if we get code block item list syntax back. if let itemList = newItem.as(CodeBlockItemListSyntax.self) { newItems.append(contentsOf: itemList) } else { newItems.append(item.withItem(newItem)) } } return CodeBlockItemListSyntax(newItems) } } extension MacroSystem { /// Expand all macros encountered within the given syntax tree. /// /// - Parameter node: The syntax node in which macros will be evaluated. /// - Parameter context: The context in which macros are evaluated. /// - Parameter errorHandler: Errors encountered during traversal will /// be passed to the error handler. /// - Returns: the syntax tree with all macros evaluated. public func evaluateMacros<Node: SyntaxProtocol>( node: Node, in context: MacroEvaluationContext, errorHandler: (MacroSystemError) -> Void ) -> Syntax { return withoutActuallyEscaping(errorHandler) { errorHandler in let applier = MacroApplication( macroSystem: self, context: context, errorHandler: errorHandler ) return applier.visit(Syntax(node)) } } }
apache-2.0
ca018138215e5e138f10658fa751e183
32.65873
83
0.684744
4.5948
false
false
false
false
ITzTravelInTime/TINU
EFI Partition Mounter/EFI Partition Mounter/EFIPartitionMounterModel.swift
1
4337
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) 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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import AppKit import Command #if (!macOnlyMode && TINU) || (!TINU && isTool) public final class EFIPartitionMounterModel{ static let shared = EFIPartitionMounterModel() /* private struct VirtualDisk: Equatable{ }*/ //new efi partition mounter system draft public func getEFIPartitionsAndSubprtitionsNew() -> [EFIPartitionToolTypes.EFIPartitionStandard]? { var result: [BSDID: EFIPartitionToolTypes.EFIPartitionStandard]! = nil guard let diskutilData = Diskutil.List() else { print("No diskutil data!") return nil } print("Looking for drives with EFI partitions") for disk in diskutilData.allDisksAndPartitions where disk.APFSVolumes == nil{ print(" Scanning disk \(disk.DeviceIdentifier)") if !disk.hasEFIPartition() { print(" Disk doesn't have an EFI partition") continue } print(" Disk has EFI partition") guard let name = disk.DeviceIdentifier.driveName() else { continue } print(" Disk is named: \(name)") var res = EFIPartitionToolTypes.EFIPartitionStandard() res.displayName = name guard let removable: Bool = disk.DeviceIdentifier.isRemovable() else { continue } print(" Disk is " + (removable ? "removable" : "unremovable")) res.isRemovable = removable for partition in disk.Partitions ?? []{ print(" Scanning disk's partition: \(partition.DeviceIdentifier)") if partition.content == .eFI { print(" Partition is an EFI partition, getting info for disk and continuing") res.isMounted = partition.isMounted() res.bsdName = partition.DeviceIdentifier res.configType = res.isMounted ? EFIPartitionToolTypes.ConfigLocations.init(partition.mountPoint!) : nil continue } var part = EFIPartitionToolTypes.PartitionStandard() if !partition.isVolume(){ continue } part.drivePartDisplayName = partition.VolumeName! print(" Partition display name is: \(part.drivePartDisplayName)") if !partition.isMounted(){ continue } print(" Partition is mounted, getting the correct icon") part.drivePartIcon = IconsManager.shared.getCorrectDiskIcon(partition.DeviceIdentifier)//NSWorkspace.shared.icon(forFile: partition.MountPoint!) print(" Got partition icon") res.completeDrivePartitions.append(part) } if result == nil{ result = [:] } result[disk.DeviceIdentifier] = res } if result == nil{ return nil } for disk in diskutilData.allDisksAndPartitions where disk.APFSVolumes != nil{ guard let store = disk.APFSPhysicalStores?.first?.DeviceIdentifier.driveID else { continue } if result[store] == nil{ continue } for apfsVolume in disk.APFSVolumes ?? [] where !(apfsVolume.OSInternal ?? false){ var part = EFIPartitionToolTypes.PartitionStandard() if !apfsVolume.isVolume(){ continue } part.drivePartDisplayName = apfsVolume.VolumeName! if !apfsVolume.isMounted(){ continue } if apfsVolume.mountPoint?.starts(with: "/System") ?? false { continue } part.drivePartIcon = IconsManager.shared.getCorrectDiskIcon(apfsVolume.DeviceIdentifier) result[store]?.completeDrivePartitions.append(part) } } if result == nil{ return nil } var ret: [EFIPartitionToolTypes.EFIPartitionStandard] = [] for r in result{ ret.append(r.value) } return ret.sorted(by: { $0.bsdName.driveNumber ?? 0 < $1.bsdName.driveNumber ?? 0 }) } } #endif
gpl-2.0
4170840eb9b13fa8ed01a2ccfb5ff676
28.107383
148
0.700254
3.967978
false
false
false
false
Telerik-Verified-Plugins/Geofencing
src/ios/GeofencePlugin.swift
2
18596
// // GeofencePlugin.swift // ionic-geofence // // Created by tomasz on 07/10/14. // // import Foundation import AudioToolbox import WebKit let TAG = "GeofencePlugin" let iOS8 = floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) let iOS7 = floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_7_1) func log(message: String){ NSLog("%@ - %@", TAG, message) } func log(messages: [String]) { for message in messages { log(message); } } @available(iOS 8.0, *) @objc(HWPGeofencePlugin) class GeofencePlugin : CDVPlugin { lazy var geoNotificationManager = GeoNotificationManager() let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT override func pluginInitialize () { NSNotificationCenter.defaultCenter().addObserver( self, selector: "didReceiveLocalNotification:", name: "CDVLocalNotification", object: nil ) NSNotificationCenter.defaultCenter().addObserver( self, selector: "didReceiveTransition:", name: "handleTransition", object: nil ) } func initialize(command: CDVInvokedUrlCommand) { log("Plugin initialization") //let faker = GeofenceFaker(manager: geoNotificationManager) //faker.start() if iOS8 { promptForNotificationPermission() } geoNotificationManager = GeoNotificationManager() geoNotificationManager.registerPermissions() let (ok, warnings, errors) = geoNotificationManager.checkRequirements() log(warnings) log(errors) let result: CDVPluginResult if ok { result = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: warnings.joinWithSeparator("\n")) } else { result = CDVPluginResult( status: CDVCommandStatus_ILLEGAL_ACCESS_EXCEPTION, messageAsString: (errors + warnings).joinWithSeparator("\n") ) } commandDelegate!.sendPluginResult(result, callbackId: command.callbackId) } func deviceReady(command: CDVInvokedUrlCommand) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } func ping(command: CDVInvokedUrlCommand) { log("Ping") let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } func promptForNotificationPermission() { UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings( forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: nil ) ) } func addOrUpdate(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { // do some task for geo in command.arguments { self.geoNotificationManager.addOrUpdateGeoNotification(JSON(geo)) } dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func getWatched(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { let watched = self.geoNotificationManager.getWatchedGeoNotifications()! let watchedJsonString = watched.description dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: watchedJsonString) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func remove(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { for id in command.arguments { self.geoNotificationManager.removeGeoNotification(id as! String) } dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func removeAll(command: CDVInvokedUrlCommand) { dispatch_async(dispatch_get_global_queue(priority, 0)) { self.geoNotificationManager.removeAllGeoNotifications() dispatch_async(dispatch_get_main_queue()) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK) self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) } } } func didReceiveTransition (notification: NSNotification) { log("didReceiveTransition") if let geoNotificationString = notification.object as? String { let js = "setTimeout('geofence.onTransitionReceived([" + geoNotificationString + "])',0)" evaluateJs(js) } } func didReceiveLocalNotification (notification: NSNotification) { log("didReceiveLocalNotification") if UIApplication.sharedApplication().applicationState != UIApplicationState.Active { var data = "undefined" if let uiNotification = notification.object as? UILocalNotification { if let notificationData = uiNotification.userInfo?["geofence.notification.data"] as? String { data = notificationData } let js = "setTimeout('geofence.onNotificationClicked(" + data + ")',0)" evaluateJs(js) } } } func evaluateJs (script: String) { if let webView = webView { if let uiWebView = webView as? UIWebView { uiWebView.stringByEvaluatingJavaScriptFromString(script) } else if let wkWebView = webView as? WKWebView { wkWebView.evaluateJavaScript(script, completionHandler: nil) } } else { log("webView is nil") } } } // class for faking crossing geofences @available(iOS 8.0, *) class GeofenceFaker { let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT let geoNotificationManager: GeoNotificationManager init(manager: GeoNotificationManager) { geoNotificationManager = manager } func start() { dispatch_async(dispatch_get_global_queue(priority, 0)) { while (true) { log("FAKER") let notify = arc4random_uniform(4) if notify == 0 { log("FAKER notify chosen, need to pick up some region") var geos = self.geoNotificationManager.getWatchedGeoNotifications()! if geos.count > 0 { //WTF Swift?? let index = arc4random_uniform(UInt32(geos.count)) let geo = geos[Int(index)] let id = geo["id"].stringValue dispatch_async(dispatch_get_main_queue()) { if let region = self.geoNotificationManager.getMonitoredRegion(id) { log("FAKER Trigger didEnterRegion") self.geoNotificationManager.locationManager( self.geoNotificationManager.locationManager, didEnterRegion: region ) } } } } NSThread.sleepForTimeInterval(3) } } } func stop() { } } @available(iOS 8.0, *) class GeoNotificationManager : NSObject, CLLocationManagerDelegate { let locationManager = CLLocationManager() let store = GeoNotificationStore() override init() { log("GeoNotificationManager init") super.init() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest } func registerPermissions() { if iOS8 { locationManager.requestAlwaysAuthorization() } } func addOrUpdateGeoNotification(geoNotification: JSON) { log("GeoNotificationManager addOrUpdate") let (_, warnings, errors) = checkRequirements() log(warnings) log(errors) let location = CLLocationCoordinate2DMake( geoNotification["latitude"].doubleValue, geoNotification["longitude"].doubleValue ) log("AddOrUpdate geo: \(geoNotification)") let radius = geoNotification["radius"].doubleValue as CLLocationDistance let id = geoNotification["id"].stringValue let region = CLCircularRegion(center: location, radius: radius, identifier: id) var transitionType = 0 if let i = geoNotification["transitionType"].int { transitionType = i } region.notifyOnEntry = 0 != transitionType & 1 region.notifyOnExit = 0 != transitionType & 2 //store store.addOrUpdate(geoNotification) locationManager.startMonitoringForRegion(region) } func checkRequirements() -> (Bool, [String], [String]) { var errors = [String]() var warnings = [String]() if (!CLLocationManager.isMonitoringAvailableForClass(CLRegion)) { errors.append("Geofencing not available") } if (!CLLocationManager.locationServicesEnabled()) { errors.append("Error: Locationservices not enabled") } let authStatus = CLLocationManager.authorizationStatus() if (authStatus != CLAuthorizationStatus.AuthorizedAlways) { errors.append("Warning: Location always permissions not granted") } if (iOS8) { if let notificationSettings = UIApplication.sharedApplication().currentUserNotificationSettings() { if notificationSettings.types == .None { errors.append("Error: notification permission missing") } else { if !notificationSettings.types.contains(.Sound) { warnings.append("Warning: notification settings - sound permission missing") } if !notificationSettings.types.contains(.Alert) { warnings.append("Warning: notification settings - alert permission missing") } if !notificationSettings.types.contains(.Badge) { warnings.append("Warning: notification settings - badge permission missing") } } } else { errors.append("Error: notification permission missing") } } let ok = (errors.count == 0) return (ok, warnings, errors) } func getWatchedGeoNotifications() -> [JSON]? { return store.getAll() } func getMonitoredRegion(id: String) -> CLRegion? { for object in locationManager.monitoredRegions { let region = object if (region.identifier == id) { return region } } return nil } func removeGeoNotification(id: String) { store.remove(id) let region = getMonitoredRegion(id) if (region != nil) { log("Stoping monitoring region \(id)") locationManager.stopMonitoringForRegion(region!) } } func removeAllGeoNotifications() { store.clear() for object in locationManager.monitoredRegions { let region = object log("Stoping monitoring region \(region.identifier)") locationManager.stopMonitoringForRegion(region) } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { log("update location") } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { log("fail with error: \(error)") } func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) { log("deferred fail error: \(error)") } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { log("Entering region \(region.identifier)") handleTransition(region, transitionType: 1) } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { log("Exiting region \(region.identifier)") handleTransition(region, transitionType: 2) } func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) { let lat = (region as! CLCircularRegion).center.latitude let lng = (region as! CLCircularRegion).center.longitude let radius = (region as! CLCircularRegion).radius log("Starting monitoring for region \(region) lat \(lat) lng \(lng) of radius \(radius)") } func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) { log("State for region " + region.identifier) } func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) { log("Monitoring region " + region!.identifier + " failed " + error.description) } func handleTransition(region: CLRegion!, transitionType: Int) { if var geoNotification = store.findById(region.identifier) { geoNotification["transitionType"].int = transitionType if geoNotification["notification"].isExists() { notifyAbout(geoNotification) } NSNotificationCenter.defaultCenter().postNotificationName("handleTransition", object: geoNotification.rawString(NSUTF8StringEncoding, options: [])) } } func notifyAbout(geo: JSON) { log("Creating notification") let notification = UILocalNotification() notification.timeZone = NSTimeZone.defaultTimeZone() let dateTime = NSDate() notification.fireDate = dateTime notification.soundName = UILocalNotificationDefaultSoundName notification.alertBody = geo["notification"]["text"].stringValue if let json = geo["notification"]["data"] as JSON? { notification.userInfo = ["geofence.notification.data": json.rawString(NSUTF8StringEncoding, options: [])!] } UIApplication.sharedApplication().scheduleLocalNotification(notification) if let vibrate = geo["notification"]["vibrate"].array { if (!vibrate.isEmpty && vibrate[0].intValue > 0) { AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } } } class GeoNotificationStore { init() { createDBStructure() } func createDBStructure() { let (tables, err) = SD.existingTables() if (err != nil) { log("Cannot fetch sqlite tables: \(err)") return } if (tables.filter { $0 == "GeoNotifications" }.count == 0) { if let err = SD.executeChange("CREATE TABLE GeoNotifications (ID TEXT PRIMARY KEY, Data TEXT)") { //there was an error during this function, handle it here log("Error while creating GeoNotifications table: \(err)") } else { //no error, the table was created successfully log("GeoNotifications table was created successfully") } } } func addOrUpdate(geoNotification: JSON) { if (findById(geoNotification["id"].stringValue) != nil) { update(geoNotification) } else { add(geoNotification) } } func add(geoNotification: JSON) { let id = geoNotification["id"].stringValue let err = SD.executeChange("INSERT INTO GeoNotifications (Id, Data) VALUES(?, ?)", withArgs: [id, geoNotification.description]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func update(geoNotification: JSON) { let id = geoNotification["id"].stringValue let err = SD.executeChange("UPDATE GeoNotifications SET Data = ? WHERE Id = ?", withArgs: [geoNotification.description, id]) if err != nil { log("Error while adding \(id) GeoNotification: \(err)") } } func findById(id: String) -> JSON? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { //there was an error during the query, handle it here log("Error while fetching \(id) GeoNotification table: \(err)") return nil } else { if (resultSet.count > 0) { let jsonString = resultSet[0]["Data"]!.asString()! return JSON(data: jsonString.dataUsingEncoding(NSUTF8StringEncoding)!) } else { return nil } } } func getAll() -> [JSON]? { let (resultSet, err) = SD.executeQuery("SELECT * FROM GeoNotifications") if err != nil { //there was an error during the query, handle it here log("Error while fetching from GeoNotifications table: \(err)") return nil } else { var results = [JSON]() for row in resultSet { if let data = row["Data"]?.asString() { results.append(JSON(data: data.dataUsingEncoding(NSUTF8StringEncoding)!)) } } return results } } func remove(id: String) { let err = SD.executeChange("DELETE FROM GeoNotifications WHERE Id = ?", withArgs: [id]) if err != nil { log("Error while removing \(id) GeoNotification: \(err)") } } func clear() { let err = SD.executeChange("DELETE FROM GeoNotifications") if err != nil { log("Error while deleting all from GeoNotifications: \(err)") } } }
apache-2.0
5810fe45ca6ffc564d3ca3c1f314ed9b
34.286528
159
0.605668
5.334481
false
false
false
false
ShiWeiCN/AlgorithmsSwift
Algorithms/Algorithms/LinkedList/List.swift
1
355
// // List.swift // Algorithms // // Created by shiwei on 22/03/2017. // Copyright © 2017 shiwei. All rights reserved. // import Foundation class Node<T: Equatable>: Equatable { var element: T? var next: Node<T>? } func ==<T: Equatable>(lhs: Node<T>, rhs: Node<T>) -> Bool { return lhs.element == rhs.element && lhs.next == rhs.next }
mit
87b4fc0e45c483375b22b966ea4d430b
18.666667
61
0.624294
3.051724
false
false
false
false
zirinisp/SlackKit
SlackKit/Sources/Team.swift
1
2115
// // Team.swift // // Copyright © 2016 Peter Zignego. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public struct Team { public let id: String? internal(set) public var name: String? internal(set) public var domain: String? internal(set) public var emailDomain: String? internal(set) public var messageEditWindowMinutes: Int? internal(set) public var overStorageLimit: Bool? internal(set) public var prefs: [String: Any]? internal(set) public var plan: String? internal(set) public var icon: TeamIcon? internal init(team: [String: Any]?) { id = team?["id"] as? String name = team?["name"] as? String domain = team?["domain"] as? String emailDomain = team?["email_domain"] as? String messageEditWindowMinutes = team?["msg_edit_window_mins"] as? Int overStorageLimit = team?["over_storage_limit"] as? Bool prefs = team?["prefs"] as? [String: Any] plan = team?["plan"] as? String icon = TeamIcon(icon: team?["icon"] as? [String: Any]) } }
mit
1b2c0182c881f8274b50323bd9c9b3ab
43.978723
80
0.701514
4.262097
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Multi-tap Delay.xcplaygroundpage/Contents.swift
1
1308
//: ## Multi-tap Delay //: A multi-tap delay is a delay line where multiple 'taps' or outputs are //: taken from a delay buffer at different points, and the taps are then //: summed with the original. Multi-tap delays are great for creating //: rhythmic delay patterns, but they can also be used to create sound //: fields of such density that they start to take on some of the qualities //: we'd more usually associate with reverb. - Geoff Smith, Sound on Sound import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) var player = try AKAudioPlayer(file: file) player.looping = true //: In AudioKit, you can create a multitap easily through creating a function //: that mixes together several delays and gains. func multitapDelay(input: AKNode, times: [Double], gains: [Double]) -> AKMixer { let mix = AKMixer(input) zip(times, gains).forEach { (time, gain) -> () in let delay = AKDelay(input, time: time, feedback: 0.0, dryWetMix: 1) mix.connect(AKBooster(delay, gain: gain)) } return mix } AudioKit.output = multitapDelay(player, times: [0.1, 0.2, 0.4], gains: [0.5, 2.0, 0.5]) AudioKit.start() player.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
mit
de5e1c548650a25831807249701975f9
39.90625
87
0.708716
3.904478
false
false
false
false
TotalDigital/People-iOS
People at Total/UICollectionViewLeftAlignedLayout.swift
1
4419
// // UICollectionViewLeftAlignedLayout.swift // SwiftDemo // // Created by Florian Letellier on 31/01/2017. // Copyright © 2017 Florian Letellier. All rights reserved. import UIKit extension UICollectionViewLayoutAttributes { func leftAlignFrameWithSectionInset(_ sectionInset:UIEdgeInsets){ var frame = self.frame frame.origin.x = sectionInset.left self.frame = frame } } class UICollectionViewLeftAlignedLayout: UICollectionViewFlowLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { var attributesCopy: [UICollectionViewLayoutAttributes] = [] if let attributes = super.layoutAttributesForElements(in: rect) { attributes.forEach({ attributesCopy.append($0.copy() as! UICollectionViewLayoutAttributes) }) } for attributes in attributesCopy { if attributes.representedElementKind == nil { let indexpath = attributes.indexPath if let attr = layoutAttributesForItem(at: indexpath) { attributes.frame = attr.frame } } } return attributesCopy } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let currentItemAttributes = super.layoutAttributesForItem(at: indexPath as IndexPath)?.copy() as? UICollectionViewLayoutAttributes { let sectionInset = self.evaluatedSectionInsetForItem(at: indexPath.section) let isFirstItemInSection = indexPath.item == 0 let layoutWidth = self.collectionView!.frame.width - sectionInset.left - sectionInset.right if (isFirstItemInSection) { currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset) return currentItemAttributes } let previousIndexPath = IndexPath.init(row: indexPath.item - 1, section: indexPath.section) let previousFrame = layoutAttributesForItem(at: previousIndexPath)?.frame ?? CGRect.zero let previousFrameRightPoint = previousFrame.origin.x + previousFrame.width let currentFrame = currentItemAttributes.frame let strecthedCurrentFrame = CGRect.init(x: sectionInset.left, y: currentFrame.origin.y, width: layoutWidth, height: currentFrame.size.height) // if the current frame, once left aligned to the left and stretched to the full collection view // widht intersects the previous frame then they are on the same line let isFirstItemInRow = !previousFrame.intersects(strecthedCurrentFrame) if (isFirstItemInRow) { // make sure the first item on a line is left aligned currentItemAttributes.leftAlignFrameWithSectionInset(sectionInset) return currentItemAttributes } var frame = currentItemAttributes.frame frame.origin.x = previousFrameRightPoint + evaluatedMinimumInteritemSpacing(at: indexPath.section) currentItemAttributes.frame = frame return currentItemAttributes } return nil } func evaluatedMinimumInteritemSpacing(at sectionIndex:Int) -> CGFloat { if let delegate = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout { let inteitemSpacing = delegate.collectionView?(self.collectionView!, layout: self, minimumInteritemSpacingForSectionAt: sectionIndex) if let inteitemSpacing = inteitemSpacing { return inteitemSpacing } } return self.minimumInteritemSpacing } func evaluatedSectionInsetForItem(at index: Int) ->UIEdgeInsets { if let delegate = self.collectionView?.delegate as? UICollectionViewDelegateFlowLayout { let insetForSection = delegate.collectionView?(self.collectionView!, layout: self, insetForSectionAt: index) if let insetForSectionAt = insetForSection { return insetForSectionAt } } return self.sectionInset } }
apache-2.0
82e1f16e6ba2ce22eba2a37611e7dd88
45.020833
145
0.640561
6.248939
false
false
false
false
JetBrains/kotlin-native
backend.native/tests/objcexport/deallocRetain.swift
1
2110
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ import Kt // Note: these tests rely on GC assertions: without the fix and the assertions it won't actually crash. // GC should fire an assertion if it obtains a reference to Kotlin object that is being (or has been) deallocated. private func test1() throws { // Attempt to make the state predictable: DeallocRetainKt.garbageCollect() DeallocRetain.deallocated = false try assertFalse(DeallocRetain.deallocated) try autoreleasepool { let obj = DeallocRetain() try obj.checkWeak() } // Runs DeallocRetain.deinit: DeallocRetainKt.garbageCollect() try assertTrue(DeallocRetain.deallocated) // Might crash due to double-dispose if the dealloc applied addRef/releaseRef to reclaimed Kotlin object: DeallocRetainKt.garbageCollect() } private class DeallocRetain : DeallocRetainBase { static var deallocated = false static var retainObject: DeallocRetain? = nil static weak var weakObject: DeallocRetain? = nil #if NO_GENERICS static var kotlinWeakRef: KotlinWeakReference? = nil #else static var kotlinWeakRef: KotlinWeakReference<AnyObject>? = nil #endif override init() { super.init() DeallocRetain.weakObject = self DeallocRetain.kotlinWeakRef = DeallocRetainKt.createWeakReference(value: self) } func checkWeak() throws { try assertSame(actual: DeallocRetain.weakObject, expected: self) try assertSame(actual: DeallocRetain.kotlinWeakRef!.value as AnyObject, expected: self) } deinit { DeallocRetain.retainObject = self DeallocRetain.retainObject = nil try! assertNil(DeallocRetain.weakObject) try! assertNil(DeallocRetain.kotlinWeakRef!.value) try! assertFalse(DeallocRetain.deallocated) DeallocRetain.deallocated = true } } class DeallocRetainTests : SimpleTestProvider { override init() { super.init() test("Test1", test1) } }
apache-2.0
cc4aeb897a2bb44007016e3eb690cdac
28.71831
114
0.709953
4.350515
false
true
false
false
tanggod/GoogleSignIn
GoogleLogin/SecondViewController.swift
2
5069
// // SecondViewController.swift // LoginDemo // // Created by Zhihui Tang on 08/10/15. // Copyright © 2015 Zhihui Tang. All rights reserved. // import UIKit class SecondViewController: UIViewController, UIAlertViewDelegate { private let backgroundImage = UIImageView(frame: MainBounds) override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. var imageName: String? switch AppWidth { case 375: imageName = NSBundle.mainBundle().pathForResource("[email protected]", ofType: nil) case 414: imageName = NSBundle.mainBundle().pathForResource("[email protected]", ofType: nil) case 568: imageName = NSBundle.mainBundle().pathForResource("[email protected]", ofType: nil) default: imageName = NSBundle.mainBundle().pathForResource("[email protected]", ofType: nil) } // backgroundImage.image = UIImage(contentsOfFile: imageName!) // view.addSubview(backgroundImage) let label = UILabel(frame:CGRect(origin: CGPointMake(10.0, 100.0), size: CGSizeMake(150,50))) label.text = "This is a Label" self.view.addSubview(label) let btn = UIButton(frame:CGRect(origin: CGPointMake(10.0, 110.0), size: CGSizeMake(150,50))) btn.setTitle("button", forState: UIControlState.Normal) btn.backgroundColor = UIColor.redColor() btn.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(btn) let startBtn: NoHighlightButton = NoHighlightButton() // let startBtn: UIButton = UIButton() startBtn.setBackgroundImage(UIImage(named: "into_home"), forState: .Normal) startBtn.setTitle("开始小日子", forState: UIControlState.Normal) startBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) startBtn.frame = CGRect(x: (AppWidth - 210) * 0.5, y: AppHeight - 120, width: 210, height: 45) startBtn.addTarget(self, action: "showMainTabbar", forControlEvents: .TouchUpInside) view.addSubview(startBtn) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ @IBAction func close(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func showMessage(sender: AnyObject) { let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.Alert) let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in } alert.addAction(alertAction) presentViewController(alert, animated: true) { () -> Void in } } func buttonClick(sender: UIButton!){ print("button clicked") let alert = UIAlertView() //直接这样创建有bug //var alert = UIAlertView(title: “alert”, message: “this is an alert”, delegate: self, cancelButtonTitle: “cancel”) alert.title = "alert" alert.delegate = self alert.addButtonWithTitle("cancel") alert.message = "this is an alert" alert.show() let vc = self.childViewControllers.last vc?.view.removeFromSuperview() vc?.removeFromParentViewController() } func showMainTabbar() { print("do something: showMainTabbar") dismissViewControllerAnimated(true, completion: nil) } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { print("buttonIndex:\(buttonIndex)") } @IBAction func gotoNextViewController(sender: AnyObject) { let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil); let vc = mainStoryboard.instantiateViewControllerWithIdentifier("ThirdViewController") self.showVC(vc) } private func showVC(vc: UIViewController) { let screenWidth = self.view.frame.size.width let screenHeight = self.view.frame.size.height vc.willMoveToParentViewController(self) addChildViewController(vc) vc.view.frame = CGRectMake(200, 0, screenWidth, screenHeight) view.addSubview(vc.view) vc.didMoveToParentViewController(self) } } class NoHighlightButton: UIButton { /// 重写setFrame方法 override var highlighted: Bool { didSet{ super.highlighted = false } } }
apache-2.0
dc6853772f816055f145705936c37f64
35.405797
123
0.655255
4.807656
false
false
false
false
brightdigit/swiftver
Sources/SwiftVer/RFC3339DateFormatter.swift
1
570
import Foundation private let _rfc3339DateFormatter = { () -> DateFormatter in let formatter = DateFormatter() formatter.setupRFC3339DateFormatter() return formatter }() public extension DateFormatter { internal func setupRFC3339DateFormatter() { locale = Locale(identifier: "en_US_POSIX") dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssXXX" timeZone = TimeZone(secondsFromGMT: 0) } /** RFC3339 DateFormatter for reading dates from autorevision. */ static var rfc3339DateFormatter: DateFormatter { return _rfc3339DateFormatter } }
mit
9a48d365b01436aced886a26a853db11
23.782609
61
0.717544
4.384615
false
false
false
false
chinesemanbobo/PPDemo
Pods/Down/Source/Renderers/DownASTRenderable.swift
2
2550
// // DownASTRenderable.swift // Down // // Created by Rob Phillips on 5/31/16. // Copyright © 2016-2019 Down. All rights reserved. // import Foundation import libcmark public protocol DownASTRenderable: DownRenderable { func toAST(_ options: DownOptions) throws -> UnsafeMutablePointer<cmark_node> } extension DownASTRenderable { /// Generates an abstract syntax tree from the `markdownString` property /// /// - Parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - Returns: An abstract syntax tree representation of the Markdown input /// - Throws: `MarkdownToASTError` if conversion fails public func toAST(_ options: DownOptions = .default) throws -> UnsafeMutablePointer<cmark_node> { return try DownASTRenderer.stringToAST(markdownString, options: options) } /// Parses the `markdownString` property into an abstract syntax tree and returns the root `Document` node. /// /// - Parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - Returns: The root Document node for the abstract syntax tree representation of the Markdown input /// - Throws: `MarkdownToASTError` if conversion fails public func toDocument(_ options: DownOptions = .default) throws -> Document { let tree = try toAST(options) guard tree.type == CMARK_NODE_DOCUMENT else { throw DownErrors.astRenderingError } return Document(cmarkNode: tree) } } public struct DownASTRenderer { /// Generates an abstract syntax tree from the given CommonMark Markdown string /// /// **Important:** It is the caller's responsibility to call `cmark_node_free(ast)` on the returned value /// /// - Parameters: /// - string: A string containing CommonMark Markdown /// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default` /// - Returns: An abstract syntax tree representation of the Markdown input /// - Throws: `MarkdownToASTError` if conversion fails public static func stringToAST(_ string: String, options: DownOptions = .default) throws -> UnsafeMutablePointer<cmark_node> { var tree: UnsafeMutablePointer<cmark_node>? string.withCString { let stringLength = Int(strlen($0)) tree = cmark_parse_document($0, stringLength, options.rawValue) } guard let ast = tree else { throw DownErrors.markdownToASTError } return ast } }
mit
013a13e6dc1768f8f65d76fba78dbcbc
38.828125
130
0.684974
4.47193
false
false
false
false
Eonil/SignalGraph.Swift
Code/Protocols/StateStorages.swift
1
3373
// // StateStorage.swift // SG5 // // Created by Hoon H. on 2015/07/01. // Copyright © 2015 Eonil. All rights reserved. // public protocol Viewable { typealias Snapshot var snapshot: Snapshot { get } } public protocol Editable: Viewable { var snapshot: Snapshot { get set } } public protocol ChannelType: StationType, Viewable { } public protocol StorageType: ChannelType, Editable { } public protocol WatchableChannelType: ChannelType, EmissiveStationType { } public protocol WatchableStorageType: StorageType, EmissiveStationType { } public protocol TransactionType { typealias Mutation } public protocol TransactionApplicable { typealias Transaction : TransactionType mutating func apply(transaction: Transaction) } public protocol TransactionalStorageType: StorageType, TransactionApplicable { } public protocol StateChannelType: ChannelType, EmissiveStationType { typealias State = Snapshot typealias OutgoingSignal : TimingSignalType } public protocol StateStorageType: StateChannelType, TransactionalStorageType { } public protocol ValueChannelType: StateChannelType { var state: State { get } } public protocol ValueStorageType: ValueChannelType, StateStorageType { var state: State { get set } } public protocol CollectionChannelType: StateChannelType { typealias Transaction : CollectionTransactionType } public protocol CollectionStorageType: StateStorageType { } public protocol SetChannelType: CollectionChannelType { typealias Element : Hashable typealias Snapshot = Set<Element> typealias Transaction = CollectionTransaction<Element,()> typealias OutgoingSignal = TimingSignal<Snapshot,Transaction> } public protocol SetStorageType: SetChannelType, CollectionStorageType { } public protocol ArrayChannelType: CollectionChannelType { typealias Element typealias Snapshot = [Element] // typealias Transaction = CollectionTransaction<Int,Element> typealias Transaction = CollectionTransaction<Range<Int>,[Element]> typealias OutgoingSignal = TimingSignal<Snapshot,Transaction> } public protocol ArrayStorageType: ArrayChannelType, CollectionStorageType { } public protocol DictionaryChannelType: CollectionChannelType { typealias Key : Hashable typealias Value typealias Snapshot = [Key:Value] typealias Transaction = CollectionTransaction<Key,Value> typealias OutgoingSignal = TimingSignal<Snapshot,Transaction> } public protocol DictionaryStorageType: DictionaryChannelType, CollectionStorageType { } public protocol Countable { var count: Int { get } } public protocol ViewableSet: Viewable, Countable, SequenceType { } public protocol EditableSet: ViewableSet, Editable, Countable { typealias Element : Hashable mutating func insert(member: Element) mutating func remove(member: Element) -> Element? mutating func removeAll() } public protocol ViewableArray: Viewable, Countable { typealias Element subscript(index: Int) -> Element { get } } public protocol EditableArray: ViewableArray, Editable { typealias Element subscript(index: Int) -> Element { get set } } public protocol ViewableDictionary: Viewable, Countable { typealias Key : Hashable typealias Value subscript(key: Key) -> Value? { get } } public protocol EditableDictionary: ViewableDictionary, Editable { // Compiler fail. Ah... // subscript(key: Key) -> Value? { get set } }
mit
6c69d04b3fbed1d8f47a4158ddd67fe7
18.952663
85
0.782622
4.028674
false
false
false
false
sweetkk/SWMusic
SWMusic/Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UIControl.swift
8
2966
import ReactiveSwift import UIKit import enum Result.NoError extension Reactive where Base: UIControl { /// The current associated action of `self`, with its registered event mask /// and its disposable. internal var associatedAction: Atomic<(action: CocoaAction<Base>, controlEvents: UIControlEvents, disposable: Disposable)?> { return associatedValue { _ in Atomic(nil) } } /// Set the associated action of `self` to `action`, and register it for the /// control events specified by `controlEvents`. /// /// - parameters: /// - action: The action to be associated. /// - controlEvents: The control event mask. /// - disposable: An outside disposable that will be bound to the scope of /// the given `action`. internal func setAction(_ action: CocoaAction<Base>?, for controlEvents: UIControlEvents, disposable: Disposable? = nil) { associatedAction.modify { associatedAction in associatedAction?.disposable.dispose() if let action = action { base.addTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) let compositeDisposable = CompositeDisposable() compositeDisposable += isEnabled <~ action.isEnabled compositeDisposable += { [weak base = self.base] in base?.removeTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) } compositeDisposable += disposable associatedAction = (action, controlEvents, ScopedDisposable(compositeDisposable)) } else { associatedAction = nil } } } /// Create a signal which sends a `value` event for each of the specified /// control events. /// /// - parameters: /// - controlEvents: The control event mask. /// /// - returns: /// A signal that sends the control each time the control event occurs. public func controlEvents(_ controlEvents: UIControlEvents) -> Signal<Base, NoError> { return Signal { observer in let receiver = CocoaTarget(observer) { $0 as! Base } base.addTarget(receiver, action: #selector(receiver.sendNext), for: controlEvents) let disposable = lifetime.ended.observeCompleted(observer.sendCompleted) return ActionDisposable { [weak base = self.base] in disposable?.dispose() base?.removeTarget(receiver, action: #selector(receiver.sendNext), for: controlEvents) } } } @available(*, unavailable, renamed: "controlEvents(_:)") public func trigger(for controlEvents: UIControlEvents) -> Signal<(), NoError> { fatalError() } /// Sets whether the control is enabled. public var isEnabled: BindingTarget<Bool> { return makeBindingTarget { $0.isEnabled = $1 } } /// Sets whether the control is selected. public var isSelected: BindingTarget<Bool> { return makeBindingTarget { $0.isSelected = $1 } } /// Sets whether the control is highlighted. public var isHighlighted: BindingTarget<Bool> { return makeBindingTarget { $0.isHighlighted = $1 } } }
mit
b7ea25a7d2521e7866c63600f93f7d6a
33.091954
126
0.697235
4.298551
false
false
false
false
eofster/Telephone
UseCases/RecordCountingPurchaseCheckUseCase.swift
1
1810
// // RecordCountingPurchaseCheckUseCase.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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. // @objc public protocol RecordCountingPurchaseCheckUseCaseOutput { func didCheckPurchase() func didFailCheckingPurchase(recordCount count: Int) } public final class RecordCountingPurchaseCheckUseCase { private lazy var origin: UseCase = { return self.factory.make(output: WeakPurchaseCheckUseCaseOutput(origin: self)) }() private var count = 0 private let factory: PurchaseCheckUseCaseFactory private let output: RecordCountingPurchaseCheckUseCaseOutput public init(factory: PurchaseCheckUseCaseFactory, output: RecordCountingPurchaseCheckUseCaseOutput) { self.factory = factory self.output = output } } extension RecordCountingPurchaseCheckUseCase: CallHistoryRecordGetAllUseCaseOutput { public func update(records: [CallHistoryRecord]) { count = records.count origin.execute() } } extension RecordCountingPurchaseCheckUseCase: PurchaseCheckUseCaseOutput { public func didCheckPurchase(expiration: Date) { output.didCheckPurchase() } public func didFailCheckingPurchase() { output.didFailCheckingPurchase(recordCount: count) } }
gpl-3.0
af2f7298ebf236a18de9d97902ce6404
32.481481
105
0.748894
4.683938
false
false
false
false
SeriousChoice/SCSwift
SCSwift/Utils/SCCollectionCell.swift
1
3790
// // SCCollectionCell.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import Foundation public protocol SCCollectionCellDelegate : AnyObject { func scCollectionCellDidPress(cell: UICollectionViewCell) } open class SCCollectionCell : UICollectionViewCell, UIGestureRecognizerDelegate { // MARK: - Constants & Variables public weak var scDelegate: SCCollectionCellDelegate? private var animationDuration: TimeInterval = 0.0 public var pressGesture: UILongPressGestureRecognizer? // MARK: - Cell Methods override open func awakeFromNib() { super.awakeFromNib() } override open func layoutSubviews() { super.layoutSubviews() layer.shadowPath = UIBezierPath(roundedRect: contentView.bounds, cornerRadius: contentView.layer.cornerRadius).cgPath } // MARK: - Gestures Methods override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if pressGesture != nil { UIView.animate(withDuration: animationDuration, animations: { self.transform = CGAffineTransform(scaleX: 0.95, y: 0.95) }) } } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) if pressGesture != nil { if let touch = touches.first { let location = touch.location(in: self) UIView.animate(withDuration: animationDuration, animations: { self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) if (location.x > 0 && location.x < frame.size.width) && (location.y > 0 && location.y < frame.size.height) { scDelegate?.scCollectionCellDidPress(cell: self) } } } } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) if pressGesture != nil { UIView.animate(withDuration: animationDuration, animations: { self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } } override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return true } @available(iOS 9.0, *) open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive press: UIPress) -> Bool { return true } // MARK: - Custom Methods public func applyPressAnimation(duration: TimeInterval) { animationDuration = duration pressGesture = UILongPressGestureRecognizer(target: self, action: nil) pressGesture?.cancelsTouchesInView = false pressGesture?.minimumPressDuration = 0 pressGesture?.delegate = self self.addGestureRecognizer(pressGesture!) } public func applyCornerRadius(value: CGFloat) { contentView.setBorders(borderWidth: UIScreen.separatorHeight, borderColor: .clear, cornerRadius: value) contentView.layer.masksToBounds = true } public func applyShadow(color: UIColor, offset: CGSize, radius: CGFloat, opacity: Float) { layer.shadowColor = color.cgColor layer.shadowOffset = offset layer.shadowRadius = radius layer.shadowOpacity = opacity layer.masksToBounds = false layer.shadowPath = UIBezierPath(roundedRect: contentView.bounds, cornerRadius: contentView.layer.cornerRadius).cgPath } }
mit
74d392149efa5fa2792f4443084f9cbd
33.135135
125
0.637371
5.269819
false
false
false
false
Scior/Spica
Spica/PreferencesViewController.swift
1
3327
// // PreferencesViewController.swift // Spica // // Created by Scior on 2017/08/19. // Copyright © 2017年 Scior. All rights reserved. // import UIKit class PreferencesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: 定数 private let ShowPreferencesDetailSegueIdentifier = "Show Preferences Detail" // MARK: - プロパティ @IBOutlet weak var tableView: UITableView! var preferences = Preferences() let tableMenuTitles = ["flickr", "foo"] var hierarchisedItems : [[Preferences.ItemValue<String>]] = [] // MARK: - メソッド override func viewDidLoad() { super.viewDidLoad() hierarchisedItems = [ [Preferences.convertItemToString(from: preferences.items.fetchingPhotoCount), Preferences.convertItemToString(from: preferences.items.hoge)], [preferences.items.foo] ] // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return tableMenuTitles.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return hierarchisedItems[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.value1, reuseIdentifier: "PreferencesCell") let preferencesItem = getPreferncesItem(for: indexPath) cell.textLabel?.text = preferencesItem.description cell.detailTextLabel?.text = preferencesItem.selected cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return tableMenuTitles[section] } // アイテム選択時の処理 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { performSegue(withIdentifier: ShowPreferencesDetailSegueIdentifier, sender: indexPath) } private func getPreferncesItem(for indexPath: IndexPath) -> Preferences.ItemValue<String> { let item = hierarchisedItems[indexPath.section][indexPath.row] let converted = Preferences.ItemValue<String>( index: item.index, values: item.values.map { String($0) }, description: item.description ) return converted } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == ShowPreferencesDetailSegueIdentifier { guard let viewContoroller = segue.destination as? PreferencesDetailViewController else { fatalError() } guard let index = sender as? IndexPath else { fatalError() } viewContoroller.navigationItem.title = tableView.cellForRow(at: index)?.textLabel?.text // viewContoroller.tableMenuTitles = } } }
mit
b7a5132499bcded9270e5f4eef1a2ed7
32.151515
106
0.654479
5.259615
false
false
false
false
Kievkao/YoutubeClassicPlayer
ClassicalPlayer/Networking/Services/ComposersService.swift
1
1300
// // ComposersService.swift // ClassicalPlayer // // Created by Andrii Kravchenko on 22.12.17. // import UIKit import Alamofire protocol ComposersServiceProtocol { func loadComposers(completion: @escaping (([Composer]?, Error?) -> Void)) } final class ComposersService: ComposersServiceProtocol { private let router: APIRouterProtocol init(router: APIRouterProtocol) { self.router = router } func loadComposers(completion: @escaping (([Composer]?, Error?) -> Void)) { guard let request = router.request(method: .get, params: [:]) else { return } Alamofire.request(request).responseJSON { response in let error = response.error guard error == nil else { completion(nil, error) return } guard let json = response.result.value as? [String: AnyObject] else { completion(nil, ParsingError.jsonCast) return } guard let results = json["results"] as? [[String: AnyObject]] else { completion(nil, ParsingError.responseStructure) return } completion(results.map { Composer(json: $0) }, nil) } } }
mit
1e19c0d9a94389619e1ea6c681facecd
27.888889
85
0.568462
4.779412
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/05135-swift-sourcemanager-getmessage.swift
11
407
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing [Void{ Void{ let start = [Void{ protocol e : b { func b<e>(e : d " let f = [[Void{ protocol c : b { e>: Any).C("\((object1: (f: S class B<U : b { e let start = [Void{ let f = [Void{ case c, { (e : d { let start = [[Void{ class case c, 0.
mit
a717253af511dae2671f36d71f6ca834
17.5
87
0.638821
2.826389
false
true
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Services/ConcreteAnnouncementsService.swift
1
2990
import Foundation class ConcreteAnnouncementsRepository: AnnouncementsRepository { // MARK: Properties private let dataStore: DataStore private let imageRepository: ImageRepository private var subscription: Any? private var readAnnouncementIdentifiers = [AnnouncementIdentifier]() var models = [AnnouncementImpl]() { didSet { announcementsObservers.forEach(provideLatestData) } } private var announcementsObservers = [AnnouncementsRepositoryObserver]() // MARK: Initialization init(eventBus: EventBus, dataStore: DataStore, imageRepository: ImageRepository) { self.dataStore = dataStore self.imageRepository = imageRepository let updateCachedAnnouncements = DataStoreChangedConsumer("ConcreteAnnouncementsRepository") { [weak self] in self?.reloadAnnouncementsFromStore() } subscription = eventBus.subscribe(consumer: updateCachedAnnouncements) reloadAnnouncementsFromStore() readAnnouncementIdentifiers = dataStore.fetchReadAnnouncementIdentifiers().defaultingTo(.empty) } // MARK: Functions func add(_ observer: AnnouncementsRepositoryObserver) { provideLatestData(to: observer) announcementsObservers.append(observer) } func fetchAnnouncement(identifier: AnnouncementIdentifier) -> Announcement? { models.first(where: { $0.identifier == identifier }) } func markRead(announcement: AnnouncementImpl) { readAnnouncementIdentifiers.append(announcement.identifier) announcementsObservers.forEach({ (observer) in observer.announcementsServiceDidUpdateReadAnnouncements(readAnnouncementIdentifiers) }) dataStore.performTransaction { (transaction) in transaction.saveReadAnnouncements(self.readAnnouncementIdentifiers) } } // MARK: Private private func reloadAnnouncementsFromStore() { guard let announcements = dataStore.fetchAnnouncements() else { return } models = announcements.sorted(by: isLastEditTimeAscending).map(makeAnnouncement) } private func makeAnnouncement(from characteristics: AnnouncementCharacteristics) -> AnnouncementImpl { AnnouncementImpl( repository: self, dataStore: dataStore, imageRepository: imageRepository, characteristics: characteristics ) } private func isLastEditTimeAscending( _ first: AnnouncementCharacteristics, _ second: AnnouncementCharacteristics ) -> Bool { return first.lastChangedDateTime.compare(second.lastChangedDateTime) == .orderedDescending } private func provideLatestData(to observer: AnnouncementsRepositoryObserver) { observer.announcementsServiceDidChangeAnnouncements(models) observer.announcementsServiceDidUpdateReadAnnouncements(readAnnouncementIdentifiers) } }
mit
a316908d2c184d55afe7bd1857e05331
33.767442
116
0.711371
5.897436
false
false
false
false
tndatacommons/Compass-iOS
Compass/src/Model/SharedData.swift
1
5912
// // SharedData.swift // Compass // // Created by Ismael Alonso on 4/18/16. // Copyright © 2016 Tennessee Data Commons. All rights reserved. // import Locksmith //Contains all the data that needs to be universally accessible or editable. class SharedData{ /*-----------------------------------* * Category attributes and functions * *-----------------------------------*/ //Internal map, contains the map of categories indexed by ID. private static var internalCategoryMap: [Int: CategoryContent] = [Int: CategoryContent](); //List handler. static var publicCategories: [CategoryContent]{ //Returns an unordered, unfiltered list of categories. get{ var categories = [CategoryContent](); for (_, category) in internalCategoryMap{ categories.append(category); } return categories; } //Generates the internal map from the list of categories this is set to. set (categories){ internalCategoryMap.removeAll(); for category in categories{ internalCategoryMap[category.getId()] = category; } } }; //Splits an ordered list of categories into groups private static func splitInGroups(categories: [CategoryContent]) -> [[CategoryContent]]{ //Stick the categories into individual lists grouped by group. var categoryLists = [[CategoryContent]](); var categoryList = [CategoryContent](); //Set the current group as the first one, we don't want to be appending first // thing because arrays are value types, not reference types. var currentGroup = categories[0].getGroup(); for category in categories{ if (currentGroup != category.getGroup()){ categoryLists.append(categoryList); categoryList = [CategoryContent](); currentGroup = category.getGroup(); } categoryList.append(category); } categoryLists.append(categoryList); return categoryLists; } //Returns a list of non-default categories, starting with all the featured ones. static var nonDefaultCategoryLists: [[CategoryContent]]{ get{ //Stick all the featured categories not selected by default in an array. var categories = [CategoryContent](); for (_, category) in internalCategoryMap{ if (!category.isSelectedByDefault()){ categories.append(category); } } //Sort them by group and title. categories.sortInPlace({ if ($0.getGroup() < $1.getGroup()){ if ($0.getGroup() == -1){ return false; } return true; } if ($0.getGroup() > $1.getGroup()){ if ($1.getGroup() == -1){ return true; } return false; } return $0.getTitle() < $1.getTitle(); }); return splitInGroups(categories); } } static var filteredCategoryLists: [[CategoryContent]]{ get{ //Stick all the featured categories not selected by default in an array. var featured = [CategoryContent](); for (_, category) in internalCategoryMap{ if (category.isFeatured() && !category.isSelectedByDefault()){ featured.append(category); } } //Sort them by group and title. featured.sortInPlace({ if ($0.getGroup() < $1.getGroup()){ return true; } if ($0.getGroup() > $1.getGroup()){ return false; } return $0.getTitle() < $1.getTitle(); }); print("Featured: \(featured.count)"); return splitInGroups(featured); } } //Gets a single category given its ID in O(1) or nil if the id isn't mapped static func getCategory(categoryId: Int) -> CategoryContent?{ return internalCategoryMap[categoryId]; } /*-------------------------------* * User attributes and functions * *-------------------------------*/ //Internal instance of the user object. private static var internalUser: User?; //Creates a User instance containing a token. private static func readUserWithToken() -> User{ return User(token: Locksmith.loadDataForUserAccount("CompassAccount")!["token"] as! String); } //Manages access to the User instance. static var user: User{ //Returns the user instance if it exists, otherwise, it creates one with the token. get{ return internalUser ?? readUserWithToken(); } //Sets a user instance. set (user){ internalUser = user; } } //Tells whether user data exists and, therefore, a user is logged in. static func isUserLoggedIn() -> Bool{ return Locksmith.loadDataForUserAccount("CompassAccount") != nil; } /*------------------------------------* * Feed data attributes and functions * *------------------------------------*/ //Internal instance for FeedData private static var internalFeedData: FeedData = FeedData(); static var feedData: FeedData{ get{ return self.internalFeedData; } set (feedData){ self.internalFeedData = feedData; FeedTypes.setDataSource(feedData ?? FeedData()); } }; }
mit
be3d8bb4f4d49f10fd5f7acf79eb37ca
33.16763
100
0.527153
5.398174
false
false
false
false
manavgabhawala/swift
test/IRGen/sil_generic_witness_methods.swift
1
4676
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s // REQUIRES: CPU=x86_64 // FIXME: These should be SIL tests, but we can't parse generic types in SIL // yet. protocol P { func concrete_method() static func concrete_static_method() func generic_method<Z>(_ x: Z) } struct S {} // CHECK-LABEL: define hidden swiftcc void @_T027sil_generic_witness_methods05call_D0{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.P) func call_methods<T: P, U>(_ x: T, y: S, z: U) { // CHECK: [[STATIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 1 // CHECK: [[STATIC_METHOD_PTR:%.*]] = load i8*, i8** [[STATIC_METHOD_ADDR]], align 8 // CHECK: [[STATIC_METHOD:%.*]] = bitcast i8* [[STATIC_METHOD_PTR]] to void (%swift.type*, %swift.type*, i8**)* // CHECK: call swiftcc void [[STATIC_METHOD]](%swift.type* swiftself %T, %swift.type* %T, i8** %T.P) T.concrete_static_method() // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** %T.P, align 8 // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* %T, i8** %T.P) x.concrete_method() // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_T027sil_generic_witness_methods1SVMf, {{.*}} %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(y) // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* %U, %swift.opaque* noalias nocapture swiftself {{.*}}, %swift.type* %T, i8** %T.P) x.generic_method(z) } // CHECK-LABEL: define hidden swiftcc void @_T027sil_generic_witness_methods017call_existential_D0{{[_0-9a-zA-Z]*}}F(%T27sil_generic_witness_methods1PP* noalias nocapture dereferenceable({{.*}})) func call_existential_methods(_ x: P, y: S) { // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%0]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[WTABLE]], align 8 // CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.concrete_method() // CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X]], i32 0, i32 1 // CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8 // CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %T27sil_generic_witness_methods1PP, %T27sil_generic_witness_methods1PP* [[X:%.*]], i32 0, i32 2 // CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8 // CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 2 // CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8 // CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)* // CHECK: call swiftcc void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_T027sil_generic_witness_methods1SVMf, {{.*}} %swift.opaque* noalias nocapture swiftself {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]]) x.generic_method(y) }
apache-2.0
7898ecf079d56defe1eb06f2637ec6e0
76.933333
252
0.639435
3.240471
false
false
false
false
sviatoslav/EndpointProcedure
Examples/Using DefaultConfigurationProvider and HTTPRequestDataBuidlerProvider.playground/Sources/Any.swift
2
3677
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import Dispatch struct ValueBox<Value> { typealias Getter = () -> Value typealias Setter = (Value) -> Void private let setter: Setter private let getter: Getter var value: Value { get { return getter() } set { setter(newValue) } } init(getter: @escaping Getter, setter: @escaping Setter) { self.getter = getter self.setter = setter } } enum ProcedureOutputBoxCreator { static func outputBox<P: OutputProcedure>(for procedure: P) -> ValueBox<Pending<ProcedureResult<P.Output>>> { let getter = { return procedure.output } let setter = { procedure.output = $0 } let valueBox = ValueBox(getter: getter, setter: setter) return valueBox } } enum ProcedureInputBoxCreator { static func inputBox<P: InputProcedure>(for procedure: P) -> ValueBox<Pending<P.Input>> { let getter = { return procedure.input } let setter = { procedure.input = $0 } let valueBox = ValueBox(getter: getter, setter: setter) return valueBox } } public class AnyInputProcedure<Input>: GroupProcedure, InputProcedure { private var inputBox: ValueBox<Pending<Input>> public var input: Pending<Input> { get { return self.inputBox.value } set { self.inputBox.value = newValue } } public init<Base: Procedure>(dispatchQueue: DispatchQueue? = nil, _ base: Base) where Base: InputProcedure, Input == Base.Input { self.inputBox = ProcedureInputBoxCreator.inputBox(for: base) super.init(dispatchQueue: dispatchQueue, operations: [base]) self.log.enabled = false } } public class AnyOutputProcedure<Output>: GroupProcedure, OutputProcedure { private var outputBox: ValueBox<Pending<ProcedureResult<Output>>> public var output: Pending<ProcedureResult<Output>> { get { return self.outputBox.value } set { self.outputBox.value = newValue } } public init<Base: Procedure>(dispatchQueue: DispatchQueue? = nil, _ base: Base) where Base: OutputProcedure, Output == Base.Output { self.outputBox = ProcedureOutputBoxCreator.outputBox(for: base) super.init(dispatchQueue: dispatchQueue, operations: [base]) self.log.enabled = false } } public class AnyProcedure<Input, Output>: GroupProcedure, InputProcedure, OutputProcedure { private var inputBox: ValueBox<Pending<Input>> public var input: Pending<Input> { get { return self.inputBox.value } set { self.inputBox.value = newValue } } private var outputBox: ValueBox<Pending<ProcedureResult<Output>>> public var output: Pending<ProcedureResult<Output>> { get { return self.outputBox.value } set { self.outputBox.value = newValue } } public init<Base: Procedure>(dispatchQueue: DispatchQueue? = nil, _ base: Base) where Base: InputProcedure & OutputProcedure, Output == Base.Output, Input == Base.Input { self.inputBox = ProcedureInputBoxCreator.inputBox(for: base) self.outputBox = ProcedureOutputBoxCreator.outputBox(for: base) super.init(dispatchQueue: dispatchQueue, operations: [base]) log.enabled = false } }
mit
5e459410795e345a348a061dccf44be6
30.689655
118
0.600653
4.577833
false
false
false
false