repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
onevcat/CotEditor | CotEditor/Sources/KeySortable.swift | 2 | 3198 | //
// KeySortable.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2022-04-14.
//
// ---------------------------------------------------------------------------
//
// © 2022 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol KeySortable {
func compare(with other: Self, key: String) -> ComparisonResult
}
extension MutableCollection where Self: RandomAccessCollection, Element: KeySortable {
/// Sort the receiver using NSSortDescriptor.
///
/// - Parameter descriptors: The description how to sort.
mutating func sort(using descriptors: [NSSortDescriptor]) {
guard !descriptors.isEmpty, self.compareCount(with: 1) == .greater else { return }
self.sort {
for descriptor in descriptors {
guard let identifier = descriptor.key else { continue }
switch $0.compare(with: $1, key: identifier) {
case .orderedAscending: return descriptor.ascending
case .orderedDescending: return !descriptor.ascending
case .orderedSame: continue
}
}
return false
}
}
}
extension Sequence where Element: KeySortable {
/// Return the sorted elements of the receiver by sorting using NSSortDescriptor.
///
/// - Parameter descriptors: The description how to sort.
/// - Returns: The sorted result.
func sorted(using descriptors: [NSSortDescriptor]) -> [Element] {
guard !descriptors.isEmpty, self.compareCount(with: 1) == .greater else { return Array(self) }
return self.sorted {
for descriptor in descriptors {
guard let identifier = descriptor.key else { continue }
switch $0.compare(with: $1, key: identifier) {
case .orderedAscending: return descriptor.ascending
case .orderedDescending: return !descriptor.ascending
case .orderedSame: continue
}
}
return false
}
}
}
extension Comparable {
/// Compare the receiver with the given value.
///
/// - Parameter other: The value to compare with.
/// - Returns: The result of comparison.
func compare(_ other: Self) -> ComparisonResult {
if self > other {
return .orderedAscending
} else if self < other {
return .orderedDescending
} else {
return .orderedSame
}
}
}
| apache-2.0 | c181613fd186a6989751d17040d5fe33 | 28.878505 | 102 | 0.579293 | 5.090764 | false | false | false | false |
edragoev1/pdfjet | Sources/Example_44/main.swift | 1 | 2951 | import Foundation
import PDFjet
/**
* Example_44.swift
*
*/
public class Example_44 {
public init() throws {
let rotate = ClockWise._0_degrees
let stream = OutputStream(toFileAtPath: "Example_44.pdf", append: false)
let pdf = PDF(stream!)
let f1 = Font(pdf, CoreFont.HELVETICA)
f1.setSize(12.0)
// Chinese (Simplified) font
let f2 = Font(pdf, "STHeitiSC-Light")
f2.setSize(12.0)
let page = Page(pdf, Letter.PORTRAIT)
let column = TextColumn(rotate)
column.setLocation(70.0, 70.0)
column.setWidth(500.0)
column.setSpaceBetweenLines(5.0)
column.setSpaceBetweenParagraphs(10.0)
let p1 = Paragraph()
p1.add(TextLine(f1,
"The Swiss Confederation was founded in 1291 as a defensive alliance among three cantons. In succeeding years, other localities joined the original three. The Swiss Confederation secured its independence from the Holy Roman Empire in 1499. Switzerland's sovereignty and neutrality have long been honored by the major European powers, and the country was not involved in either of the two World Wars. The political and economic integration of Europe over the past half century, as well as Switzerland's role in many UN and international organizations, has strengthened Switzerland's ties with its neighbors. However, the country did not officially become a UN member until 2002."))
column.addParagraph(p1)
let chinese = "用于附属装置选择器应用程序的分析方法和计算基于与物料、附属装置和机器有关的不同参数和变量。 此类参数和变量的准确性会影响附属装置选择 应用程序结果的准确性。 虽然沃尔沃建筑设备公司、其子公司和附属公司(统称“沃尔沃建筑设备”)已尽力确保附属装置选择应用程序的准确性,但沃尔沃建筑设备无法保证结果准确无误。 因此,沃尔沃建筑设备并未对附属装置选择应用程序结果的准确性作出保证或声明(无论明示或暗示)。 沃尔沃建筑设备特此声明不对有关附属装置选择应用程序报告,此处获得的结果,或用于附属装置选择应用程序的设备的适宜性的所有明示或暗示保证,包括但不限于用于特定目的的适销性或合适性的任何保证承担任何责任。 在任何情况下,沃尔沃建筑设备均不对为实体或由实体创建的结果(或任何其它实体)以及由此造成的任何间接、意外、必然或特殊损害,包括但不限于损失收益或利润承担任何责任。"
column.addChineseParagraph(f2, chinese)
column.drawOn(page)
pdf.complete()
}
} // End of Example_44.swift
let time0 = Int64(Date().timeIntervalSince1970 * 1000)
_ = try Example_44()
let time1 = Int64(Date().timeIntervalSince1970 * 1000)
print("Example_44 => \(time1 - time0)")
| mit | def2139bd54d6b6ade86d25fd2289872 | 42.156863 | 680 | 0.726488 | 2.800254 | false | false | false | false |
ibm-cloud-security/appid-clientsdk-swift | Source/IBMCloudAppID/internal/OAuthManager.swift | 1 | 1378 | /* * Copyright 2016, 2017 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class OAuthManager {
private(set) var appId:AppID
private(set) var preferenceManager:PreferenceManager
internal var registrationManager:RegistrationManager?
internal var authorizationManager:AuthorizationManager?
internal var tokenManager:TokenManager?
init(appId:AppID) {
self.appId = appId
self.preferenceManager = PreferenceManager()
self.registrationManager = RegistrationManager(oauthManager: self)
self.authorizationManager = AuthorizationManager(oAuthManager: self)
self.tokenManager = TokenManager(oAuthManager: self)
}
internal func setPreferredLocale(_ locale: Locale) {
self.authorizationManager?.preferredLocale = locale
}
}
| apache-2.0 | a75bd71476403afc92f9c01a2f666c43 | 37.277778 | 79 | 0.724964 | 4.801394 | false | false | false | false |
iOSDevLog/iOSDevLog | Instagram/Pods/LeanCloud/Sources/Storage/ObjectProfiler.swift | 1 | 23496 | //
// ObjectProfiler.swift
// LeanCloud
//
// Created by Tang Tianyong on 2/23/16.
// Copyright © 2016 LeanCloud. All rights reserved.
//
import Foundation
class ObjectProfiler {
/// Registered object class table indexed by class name.
static var objectClassTable: [String: LCObject.Type] = [:]
/**
Property list table indexed by synthesized class identifier number.
- note: Any properties declared by superclass are not included in each property list.
*/
static var propertyListTable: [UInt: [objc_property_t]] = [:]
/**
Register an object class.
- parameter aClass: The object class to be registered.
*/
static func registerClass(_ aClass: LCObject.Type) {
synthesizeProperty(aClass)
cache(objectClass: aClass)
}
/**
Synthesize all non-computed properties for object class.
- parameter aClass: The object class need to be synthesized.
*/
static func synthesizeProperty(_ aClass: LCObject.Type) {
let properties = synthesizableProperties(aClass)
properties.forEach { synthesizeProperty($0, aClass) }
cache(properties: properties, aClass)
}
/**
Cache an object class.
- parameter aClass: The class to be cached.
*/
static func cache(objectClass: LCObject.Type) {
objectClassTable[objectClass.objectClassName()] = objectClass
}
/**
Cache a property list.
- parameter properties: The property list to be cached.
- parameter aClass: The class of property list.
*/
static func cache(properties: [objc_property_t], _ aClass: AnyClass) {
propertyListTable[UInt(bitPattern: ObjectIdentifier(aClass))] = properties
}
/**
Register object classes.
This method will scan the loaded classes list at runtime to find out object classes.
- note: When subclass and superclass have the same class name,
subclass will be registered for the class name.
*/
static func registerClasses() {
var classes = [LCObject.self]
let subclasses = Runtime.subclasses(LCObject.self) as! [LCObject.Type]
classes.append(contentsOf: subclasses)
/* Sort classes to make sure subclass will be registered after superclass. */
classes = Runtime.toposort(classes: classes) as! [LCObject.Type]
classes.forEach { registerClass($0) }
}
/**
Find all synthesizable properties of object class.
A synthesizable property must satisfy following conditions:
* It is a non-computed property.
* It is a LeanCloud data type property.
- note: Any synthesizable properties declared by superclass are not included.
- parameter aClass: The object class.
- returns: An array of synthesizable properties.
*/
static func synthesizableProperties(_ aClass: LCObject.Type) -> [objc_property_t] {
return Runtime.nonComputedProperties(aClass).filter { hasLCValue($0) }
}
/**
Check whether a property has LeanCloud data type.
- parameter property: Target property.
- returns: true if property type has LeanCloud data type, false otherwise.
*/
static func hasLCValue(_ property: objc_property_t) -> Bool {
return getLCValue(property) != nil
}
/**
Get concrete LCValue subclass of property.
- parameter property: The property to be inspected.
- returns: Concrete LCValue subclass, or nil if property type is not LCValue.
*/
static func getLCValue(_ property: objc_property_t) -> LCValue.Type? {
guard let typeEncoding: String = Runtime.typeEncoding(property) else {
return nil
}
guard typeEncoding.hasPrefix("@\"") else {
return nil
}
let startIndex: String.Index = typeEncoding.index(typeEncoding.startIndex, offsetBy: 2)
let endIndex: String.Index = typeEncoding.index(typeEncoding.endIndex, offsetBy: -1)
let name: Substring = typeEncoding[startIndex..<endIndex]
if let subclass = objc_getClass(String(name)) as? AnyClass {
if let type = subclass as? LCValue.Type {
return type
}
}
return nil
}
/**
Get concrete LCValue subclass of an object property.
- parameter object: Target object.
- parameter propertyName: The name of property to be inspected.
- returns: Concrete LCValue subclass, or nil if property type is not LCValue.
*/
static func getLCValue(_ object: LCObject, _ propertyName: String) -> LCValue.Type? {
let property = class_getProperty(object_getClass(object), propertyName)
if property != nil {
return getLCValue(property!)
} else {
return nil
}
}
/**
Check if object has a property of type LCValue for given name.
- parameter object: Target object.
- parameter propertyName: The name of property to be inspected.
- returns: true if object has a property of type LCValue for given name, false otherwise.
*/
static func hasLCValue(_ object: LCObject, _ propertyName: String) -> Bool {
return getLCValue(object, propertyName) != nil
}
/**
Synthesize a single property for class.
- parameter property: Property which to be synthesized.
- parameter aClass: Class of property.
*/
static func synthesizeProperty(_ property: objc_property_t, _ aClass: AnyClass) {
let getterName = Runtime.propertyName(property)
let setterName = "set\(getterName.firstUppercaseString):"
class_replaceMethod(aClass, Selector(getterName), unsafeBitCast(self.propertyGetter, to: IMP.self), "@@:")
class_replaceMethod(aClass, Selector(setterName), unsafeBitCast(self.propertySetter, to: IMP.self), "v@:@")
}
/**
Iterate all object properties of type LCValue.
- parameter object: The object to be inspected.
- parameter body: The body for each iteration.
*/
static func iterateProperties(_ object: LCObject, body: (String, objc_property_t) -> Void) {
var visitedKeys: Set<String> = []
var aClass: AnyClass? = object_getClass(object)
repeat {
guard aClass != nil else { return }
let properties = propertyListTable[UInt(bitPattern: ObjectIdentifier(aClass!))]
properties?.forEach { property in
let key = Runtime.propertyName(property)
if !visitedKeys.contains(key) {
visitedKeys.insert(key)
body(key, property)
}
}
aClass = class_getSuperclass(aClass)
} while aClass != LCObject.self
}
/**
Get deepest descendant newborn orphan objects of an object recursively.
- parameter object: The root object.
- parameter parent: The parent object for each iteration.
- parameter visited: The visited objects.
- parameter output: A set of deepest descendant newborn orphan objects.
- returns: true if object has newborn orphan object, false otherwise.
*/
static func deepestNewbornOrphans(_ object: LCValue, parent: LCValue?, output: inout Set<LCObject>) -> Bool {
var hasNewbornOrphan = false
switch object {
case let object as LCObject:
object.forEachChild { child in
if deepestNewbornOrphans(child, parent: object, output: &output) {
hasNewbornOrphan = true
}
}
/* Check if object is a newborn orphan.
If parent is not an LCObject, we think that it is an orphan. */
if !object.hasObjectId && !(parent is LCObject) {
if !hasNewbornOrphan {
output.insert(object)
}
hasNewbornOrphan = true
}
default:
(object as! LCValueExtension).forEachChild { child in
if deepestNewbornOrphans(child, parent: object, output: &output) {
hasNewbornOrphan = true
}
}
}
return hasNewbornOrphan
}
/**
Get deepest descendant newborn orphan objects.
- parameter object: The root object.
- returns: A set of deepest descendant newborn orphan objects.
*/
static func deepestNewbornOrphans(_ object: LCObject) -> Set<LCObject> {
var output: Set<LCObject> = []
_ = deepestNewbornOrphans(object, parent: nil, output: &output)
output.remove(object)
return output
}
/**
Create toposort for a set of objects.
- parameter objects: A set of objects need to be sorted.
- returns: An array of objects ordered by toposort.
*/
static func toposort(_ objects: Set<LCObject>) -> [LCObject] {
var result: [LCObject] = []
var visitStatusTable: [UInt: Int] = [:]
toposortStart(objects, &result, &visitStatusTable)
return result
}
fileprivate static func toposortStart(_ objects: Set<LCObject>, _ result: inout [LCObject], _ visitStatusTable: inout [UInt: Int]) {
objects.forEach { try! toposortVisit($0, objects, &result, &visitStatusTable) }
}
fileprivate static func toposortVisit(_ value: LCValue, _ objects: Set<LCObject>, _ result: inout [LCObject], _ visitStatusTable: inout [UInt: Int]) throws {
guard let object = value as? LCObject else {
(value as! LCValueExtension).forEachChild { child in
try! toposortVisit(child, objects, &result, &visitStatusTable)
}
return
}
let key = UInt(bitPattern: ObjectIdentifier(object))
switch visitStatusTable[key] ?? 0 {
case 0: /* Unvisited */
visitStatusTable[key] = 1
object.forEachChild { child in
try! toposortVisit(child, objects, &result, &visitStatusTable)
}
visitStatusTable[key] = 2
if objects.contains(object) {
result.append(object)
}
case 1: /* Visiting */
throw LCError(code: .inconsistency, reason: "Circular reference.", userInfo: nil)
default: /* Visited */
break
}
}
/**
Get all objects of an object family.
This method presumes that there is no circle in object graph.
- parameter object: The ancestor object.
- returns: A set of objects in family.
*/
static func family(_ object: LCObject) -> Set<LCObject> {
var result: Set<LCObject> = []
familyVisit(object, result: &result)
return result
}
fileprivate static func familyVisit(_ value: LCValue, result: inout Set<LCObject>) {
(value as! LCValueExtension).forEachChild { child in
familyVisit(child, result: &result)
}
if let object = value as? LCObject {
result.insert(object)
}
}
/**
Validate circular reference in object graph.
This method will check object and its all descendant objects.
- parameter object: The object to validate.
*/
static func validateCircularReference(_ object: LCObject) {
var visitStatusTable: [UInt: Int] = [:]
try! validateCircularReference(object, visitStatusTable: &visitStatusTable)
}
/**
Validate circular reference in object graph iteratively.
- parameter object: The object to validate.
- parameter visitStatusTable: The object visit status table.
*/
fileprivate static func validateCircularReference(_ object: LCValue, visitStatusTable: inout [UInt: Int]) throws {
let key = UInt(bitPattern: ObjectIdentifier(object))
switch visitStatusTable[key] ?? 0 {
case 0: /* Unvisited */
visitStatusTable[key] = 1
(object as! LCValueExtension).forEachChild { (child) in
try! validateCircularReference(child, visitStatusTable: &visitStatusTable)
}
visitStatusTable[key] = 2
case 1: /* Visiting */
throw LCError(code: .inconsistency, reason: "Circular reference.", userInfo: nil)
default: /* Visited */
break
}
}
/**
Check whether value is a boolean.
- parameter jsonValue: The value to check.
- returns: true if value is a boolean, false otherwise.
*/
fileprivate static func isBoolean(_ jsonValue: AnyObject) -> Bool {
switch String(describing: type(of: jsonValue)) {
case "__NSCFBoolean", "Bool": return true
default: return false
}
}
/**
Get object class by name.
- parameter className: The name of object class.
- returns: The class.
*/
static func objectClass(_ className: String) -> LCObject.Type? {
return ObjectProfiler.objectClassTable[className]
}
/**
Create LCObject object for class name.
- parameter className: The class name of LCObject type.
- returns: An LCObject object for class name.
*/
static func object(className: String) -> LCObject {
if let objectClass = objectClass(className) {
return objectClass.init()
} else {
return LCObject(className: className)
}
}
/**
Convert a dictionary to an object with specified class name.
- parameter dictionary: The source dictionary to be converted.
- parameter className: The object class name.
- returns: An LCObject object.
*/
static func object(dictionary: [String: AnyObject], className: String) -> LCObject {
let result = object(className: className)
let keyValues = dictionary.mapValue { try! object(jsonValue: $0) }
keyValues.forEach { (key, value) in
result.update(key, value)
}
return result
}
/**
Convert a dictionary to an object of specified data type.
- parameter dictionary: The source dictionary to be converted.
- parameter dataType: The data type.
- returns: An LCValue object, or nil if object can not be decoded.
*/
static func object(dictionary: [String: AnyObject], dataType: RESTClient.DataType) -> LCValue? {
switch dataType {
case .object, .pointer:
let className = dictionary["className"] as! String
return object(dictionary: dictionary, className: className)
case .relation:
return LCRelation(dictionary: dictionary)
case .geoPoint:
return LCGeoPoint(dictionary: dictionary)
case .bytes:
return LCData(dictionary: dictionary)
case .date:
return LCDate(dictionary: dictionary)
}
}
/**
Convert a dictionary to an LCValue object.
- parameter dictionary: The source dictionary to be converted.
- returns: An LCValue object.
*/
fileprivate static func object(dictionary: [String: AnyObject]) -> LCValue {
var result: LCValue!
if let type = dictionary["__type"] as? String {
if let dataType = RESTClient.DataType(rawValue: type) {
result = object(dictionary: dictionary, dataType: dataType)
}
}
if result == nil {
result = LCDictionary(dictionary.mapValue { try! object(jsonValue: $0) })
}
return result
}
/**
Convert JSON value to LCValue object.
- parameter jsonValue: The JSON value.
- returns: An LCValue object of the corresponding JSON value.
*/
static func object(jsonValue: AnyObject) throws -> LCValue {
switch jsonValue {
/* Note: a bool is also a number, we must match it first. */
case let bool where isBoolean(bool):
return LCBool(bool as! Bool)
case let number as NSNumber:
return LCNumber(number.doubleValue)
case let string as String:
return LCString(string)
case let array as [AnyObject]:
return LCArray(array.map { try! object(jsonValue: $0) })
case let dictionary as [String: AnyObject]:
return object(dictionary: dictionary)
case let data as Data:
return LCData(data)
case let date as Date:
return LCDate(date)
case is NSNull:
return LCNull()
case let object as LCValue:
return object
default:
break
}
throw LCError(code: .invalidType, reason: "Unrecognized object.")
}
/**
Convert an AnyObject object to JSON value.
- parameter object: The object to be converted.
- returns: The JSON value of object.
*/
static func lconValue(_ object: AnyObject) -> AnyObject {
switch object {
case let array as [AnyObject]:
return array.map { lconValue($0) } as AnyObject
case let dictionary as [String: AnyObject]:
return dictionary.mapValue { lconValue($0) } as AnyObject
case let object as LCValue:
return (object as! LCValueExtension).lconValue!
case let query as LCQuery:
return query.lconValue as AnyObject
default:
return object
}
}
/**
Find an error in JSON value.
- parameter jsonValue: The JSON value from which to find the error.
- returns: An error object, or nil if error not found.
*/
static func error(jsonValue: AnyObject?) -> LCError? {
var result: LCError?
switch jsonValue {
case let array as [AnyObject]:
for element in array {
if let error = self.error(jsonValue: element) {
result = error
break
}
}
case let dictionary as [String: AnyObject]:
let code = dictionary["code"] as? Int
let error = dictionary["error"] as? String
if code != nil || error != nil {
result = LCError(dictionary: dictionary)
} else {
for (_, value) in dictionary {
if let error = self.error(jsonValue: value) {
result = error
break
}
}
}
default:
break
}
return result
}
/**
Update object with a dictionary.
- parameter object: The object to be updated.
- parameter dictionary: A dictionary of key-value pairs.
*/
static func updateObject(_ object: LCObject, _ dictionary: [String: AnyObject]) {
dictionary.forEach { (key, value) in
object.update(key, try! self.object(jsonValue: value))
}
}
/**
Get property name from a setter selector.
- parameter selector: The setter selector.
- returns: A property name correspond to the setter selector.
*/
static func propertyName(_ setter: Selector) -> String {
var propertyName = NSStringFromSelector(setter)
let startIndex: String.Index = propertyName.index(propertyName.startIndex, offsetBy: 3)
let endIndex: String.Index = propertyName.index(propertyName.endIndex, offsetBy: -1)
propertyName = String(propertyName[startIndex..<endIndex])
return propertyName
}
/**
Get property value for given name from an object.
- parameter object: The object that owns the property.
- parameter propertyName: The property name.
- returns: The property value, or nil if such a property not found.
*/
static func propertyValue(_ object: LCObject, _ propertyName: String) -> LCValue? {
guard hasLCValue(object, propertyName) else {
return nil
}
return Runtime.instanceVariableValue(object, propertyName) as? LCValue
}
static func getJSONString(_ object: LCValue) -> String {
return getJSONString(object, depth: 0)
}
static func getJSONString(_ object: LCValue, depth: Int, indent: Int = 4) -> String {
switch object {
case is LCNull:
return "null"
case let number as LCNumber:
return "\(number.value)"
case let bool as LCBool:
return "\(bool.value)"
case let string as LCString:
let value = string.value
if depth > 0 {
return "\"\(value.doubleQuoteEscapedString)\""
} else {
return value
}
case let array as LCArray:
let value = array.value
if value.isEmpty {
return "[]"
} else {
let lastIndent = " " * (indent * depth)
let bodyIndent = " " * (indent * (depth + 1))
let body = value
.map { element in getJSONString(element, depth: depth + 1) }
.joined(separator: ",\n" + bodyIndent)
return "[\n\(bodyIndent)\(body)\n\(lastIndent)]"
}
case let dictionary as LCDictionary:
let value = dictionary.value
if value.isEmpty {
return "{}"
} else {
let lastIndent = " " * (indent * depth)
let bodyIndent = " " * (indent * (depth + 1))
let body = value
.map { (key, value) in (key, getJSONString(value, depth: depth + 1)) }
.sorted { (left, right) in left.0 < right.0 }
.map { (key, value) in "\"\(key.doubleQuoteEscapedString)\" : \(value)" }
.joined(separator: ",\n" + bodyIndent)
return "{\n\(bodyIndent)\(body)\n\(lastIndent)}"
}
case let object as LCObject:
let dictionary = object.dictionary.copy() as! LCDictionary
dictionary["__type"] = LCString("Object")
dictionary["className"] = LCString(object.actualClassName)
return getJSONString(dictionary, depth: depth)
case _ where object is LCRelation ||
object is LCGeoPoint ||
object is LCData ||
object is LCDate ||
object is LCACL:
let jsonValue = object.jsonValue
let dictionary = LCDictionary(unsafeObject: jsonValue as! [String : AnyObject])
return getJSONString(dictionary, depth: depth)
default:
return object.description
}
}
/**
Getter implementation of LeanCloud data type property.
*/
static let propertyGetter: @convention(c) (LCObject, Selector) -> AnyObject? = {
(object: LCObject, cmd: Selector) -> AnyObject? in
let key = NSStringFromSelector(cmd)
return object.get(key)
}
/**
Setter implementation of LeanCloud data type property.
*/
static let propertySetter: @convention(c) (LCObject, Selector, AnyObject?) -> Void = {
(object: LCObject, cmd: Selector, value: AnyObject?) -> Void in
let key = ObjectProfiler.propertyName(cmd)
let value = value as? LCValue
if ObjectProfiler.getLCValue(object, key) == nil {
object.set(key.firstLowercaseString, value: value)
} else {
object.set(key, value: value)
}
}
}
| mit | 47f17df94547a4fbcdcbb873a2d0c238 | 31.67733 | 161 | 0.597744 | 4.815536 | false | false | false | false |
wwu-pi/md2-framework | de.wwu.md2.framework/res/resources/ios/lib/model/type/MD2Boolean.swift | 1 | 2566 | //
// MD2Boolean.swift
// md2-ios-library
//
// Created by Christoph Rieger on 21.07.15.
// Copyright (c) 2015 Christoph Rieger. All rights reserved.
//
/// MD2 data type for boolean values.
class MD2Boolean: MD2DataType {
/// Computed property that returns the specific platformValue type to the generic property defined in the protocol.
var value: Any? {
get {
return platformValue
}
}
/// Contained platform type.
var platformValue: Bool?
/// Empty initializer.
init() {
// Nothing to initialize
}
/**
Required initializer to deserialize values from a string representation.
:param: value The string representation.
*/
required init(_ value: MD2String) {
if value.isSet() && value.equals(MD2String("true")) {
platformValue = true
} else if value.isSet() && value.equals(MD2String("false")) {
platformValue = false
}
}
/**
Initializer to create an MD2 data type from a native boolean value.
:param: value The boolean representation.
*/
init(_ value : Bool) {
platformValue = value
}
/**
Initialitzer to create an MD2 data type from another MD2Boolean value.
:param: md2Boolean The MD2 data type to copy.
*/
init(_ md2Boolean: MD2Boolean) {
platformValue = md2Boolean.platformValue
}
/**
Compare two objects based on their content (not just comparing references).
:param: value The object to compare with.
:returns: Whether the values are equal or not.
*/
func isSet() -> Bool {
return platformValue != nil
}
/**
Clone an object.
:returns: A copy of the object.
*/
func clone() -> MD2Type {
return MD2Boolean(self)
}
/**
Get a string representation of the object.
:returns: The string representation
*/
func toString() -> String {
if platformValue == nil {
return ""
}
return platformValue == true ? "true" : "false"
}
/**
Compare two objects based on their content (not just comparing references).
:param: value The object to compare with.
:returns: Whether the values are equal or not.
*/
func equals(value : MD2Type) -> Bool {
return (value is MD2Boolean)
&& platformValue == (value as! MD2Boolean).platformValue
}
} | apache-2.0 | 09476f0a4995f0b483dc4f484d078fa5 | 23.92233 | 119 | 0.574045 | 4.565836 | false | false | false | false |
uias/Pageboy | Sources/Shared/PageboyStatusView.swift | 1 | 5198 | //
// PageboyStatusView.swift
// Examples
//
// Created by Merrick Sapsford on 10/10/2020.
// Copyright © 2020 UI At Six. All rights reserved.
//
import UIKit
import Pageboy
class PageboyStatusView: UIView {
// MARK: Properties
private let divider = UIView()
private let countLabel = UILabel()
private let positionLabel = UILabel()
private let pageLabel = UILabel()
override var tintColor: UIColor! {
didSet {
updateForTintColor()
}
}
// MARK: Init
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
private func commonInit() {
let stackView = UIStackView()
stackView.axis = .vertical
addSubview(divider)
addSubview(stackView)
divider.translatesAutoresizingMaskIntoConstraints = false
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
divider.leadingAnchor.constraint(equalTo: leadingAnchor),
divider.topAnchor.constraint(equalTo: topAnchor),
divider.widthAnchor.constraint(equalToConstant: 1.0),
bottomAnchor.constraint(equalTo: divider.bottomAnchor),
stackView.leadingAnchor.constraint(equalTo: divider.trailingAnchor, constant: 8.0),
stackView.topAnchor.constraint(equalTo: topAnchor),
trailingAnchor.constraint(equalTo: stackView.trailingAnchor),
bottomAnchor.constraint(equalTo: stackView.bottomAnchor)
])
stackView.addArrangedSubview(countLabel)
stackView.addArrangedSubview(positionLabel)
stackView.addArrangedSubview(pageLabel)
updateCount(nil)
updatePosition(nil)
updatePage(nil)
tintColor = UIColor.white.withAlphaComponent(0.75)
switch traitCollection.userInterfaceIdiom {
case .tv:
countLabel.font = .systemFont(ofSize: 18)
positionLabel.font = .systemFont(ofSize: 18)
pageLabel.font = .systemFont(ofSize: 18)
default:
countLabel.font = .systemFont(ofSize: 14)
positionLabel.font = .systemFont(ofSize: 14)
pageLabel.font = .systemFont(ofSize: 14)
}
updateForTintColor()
}
// MARK: Styling
private func updateForTintColor() {
divider.backgroundColor = tintColor
countLabel.textColor = tintColor
positionLabel.textColor = tintColor
pageLabel.textColor = tintColor
}
// MARK: Data
private func updateCount(_ count: Int?) {
countLabel.text = "Page Count: \(count ?? 0)"
}
private func updatePosition(_ position: CGFloat?) {
positionLabel.text = "Current Position: \(String(format: "%.3f", position ?? 0.0))"
}
private func updatePage(_ page: Int?) {
pageLabel.text = "Current Page: \(page ?? 0)"
}
}
extension PageboyStatusView: PageboyViewControllerDelegate {
func pageboyViewController(_ pageboyViewController: PageboyViewController, didScrollTo position: CGPoint, direction: PageboyViewController.NavigationDirection, animated: Bool) {
switch pageboyViewController.navigationOrientation {
case .horizontal:
updatePosition(position.x)
case .vertical:
updatePosition(position.y)
@unknown default:
break
}
}
func pageboyViewController(_ pageboyViewController: PageboyViewController, willScrollToPageAt index: PageboyViewController.PageIndex, direction: PageboyViewController.NavigationDirection, animated: Bool) {
}
func pageboyViewController(_ pageboyViewController: PageboyViewController, didScrollToPageAt index: PageboyViewController.PageIndex, direction: PageboyViewController.NavigationDirection, animated: Bool) {
updatePage(index)
}
func pageboyViewController(_ pageboyViewController: PageboyViewController, didCancelScrollToPageAt index: PageboyViewController.PageIndex, returnToPageAt previousIndex: PageboyViewController.PageIndex) {
}
func pageboyViewController(_ pageboyViewController: PageboyViewController, didReloadWith currentViewController: UIViewController, currentPageIndex: PageboyViewController.PageIndex) {
updateCount(pageboyViewController.pageCount)
}
}
extension PageboyStatusView {
class func add(to viewController: PageboyViewController) {
let statusView = PageboyStatusView()
viewController.delegate = statusView
viewController.view.addSubview(statusView)
statusView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
statusView.leadingAnchor.constraint(equalTo: viewController.view.leadingAnchor, constant: 16.0),
viewController.view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: statusView.bottomAnchor, constant: 8.0)
])
}
}
| mit | 1c375a097f7b823478dc7f84b1618be8 | 33.190789 | 209 | 0.666538 | 5.787305 | false | false | false | false |
maicki/plank | Sources/Core/SchemaLoader.swift | 1 | 1815 | //
// SchemaLoader.swift
// Plank
//
// Created by Andrew Chun on 6/17/16.
// Copyright © 2016 Rahul Malik. All rights reserved.
//
import Foundation
protocol SchemaLoader {
func loadSchema(_ schemaUrl: URL) -> Schema
}
class FileSchemaLoader: SchemaLoader {
static let sharedInstance = FileSchemaLoader()
static let sharedPropertyLoader = Schema.propertyFunctionForType(loader: FileSchemaLoader.sharedInstance)
var refs: [URL: Schema]
init() {
self.refs = [URL: Schema]()
}
func loadSchema(_ schemaUrl: URL) -> Schema {
if let cachedValue = refs[schemaUrl] {
return cachedValue
}
// Load from local file
guard let data = try? Data(contentsOf: URL(fileURLWithPath: schemaUrl.path)) else {
fatalError("Error loading or parsing schema at URL: \(schemaUrl)")
}
guard let jsonResult = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) else {
fatalError("Invalid JSON. Unable to parse json at URL: \(schemaUrl)")
}
guard let jsonDict = jsonResult as? JSONObject else {
fatalError("Invalid Schema. Expected dictionary as the root object type for schema at URL: \(schemaUrl)")
}
let id = jsonDict["id"] as? String ?? ""
guard id.hasSuffix(schemaUrl.lastPathComponent) == true else {
fatalError("Invalid Schema: The value for the `id` (\(id) must end with the filename \(schemaUrl.lastPathComponent).")
}
guard let schema = FileSchemaLoader.sharedPropertyLoader(jsonDict, schemaUrl) else {
fatalError("Invalid Schema. Unable to parse schema at URL: \(schemaUrl)")
}
refs[schemaUrl] = schema
return schema
}
}
| apache-2.0 | df6d9e18b1672093ca59cfb545c88ffb | 32.592593 | 144 | 0.651047 | 4.557789 | false | false | false | false |
yukoyang/YYAutoBanner | demo/YYAutoBanner/ViewController.swift | 1 | 1375 | //
// ViewController.swift
// YYAutoBanner
//
// Created by ZANADU on 15/11/20.
// Copyright © 2015年 yangying. All rights reserved.
//
import UIKit
class ViewController: UIViewController,BannerViewTapDelegate {
var bannerV = BannerView()
var urls = [NSURL]()
override func viewDidLoad() {
super.viewDidLoad()
let url1 = NSURL(string: "http://img5q.duitang.com/uploads/item/201501/27/20150127163843_BQyf3.jpeg")
let url2 = NSURL(string: "http://img5.duitang.com/uploads/item/201501/27/20150127164025_BzEm8.jpeg")
let url3 = NSURL(string: "http://bizhi.33lc.com/uploadfile/2015/0130/20150130023019720.jpg")
let url4 = NSURL(string: "http://bizhi.33lc.com/uploadfile/2015/0130/20150130023017376.jpg")
urls = [url1!,url2!,url3!,url4!]
bannerV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
self.view.addSubview(bannerV)
bannerV.pageTintColor = UIColor.lightGrayColor()
bannerV.currentPageTintColor = UIColor(red: 0.93, green: 0.31, blue: 0.49, alpha: 1)
bannerV.defaultSettings()
bannerV.delegate = self
bannerV.setbannerObjects(urls)
}
//BannerViewTapDelegate
func BannerViewTapWithIndex(index: Int) {
print("click \(index) image")
}
}
| mit | 2934ccac0fa139b39f2216418113be23 | 30.181818 | 109 | 0.649417 | 3.438596 | false | false | false | false |
dangdangfeng/BOOKS | Swift 4/GuidedTour.playground/Pages/Simple Values.xcplaygroundpage/Contents.swift | 1 | 4141 | //: # A Swift Tour
//:
//: Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. In Swift, this can be done in a single line:
//:
print("Hello, world!")
//: If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a `main()` function. You also don’t need to write semicolons at the end of every statement.
//:
//: This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
//:
//: ## Simple Values
//:
//: Use `let` to make a constant and `var` to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
//:
var myVariable = 42
myVariable = 50
let myConstant = 42
//: A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that `myVariable` is an integer because its initial value is an integer.
//:
//: If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
//:
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
//: - Experiment:
//: Create a constant with an explicit type of `Float` and a value of `4`.
//:
//: Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.
//:
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
//: - Experiment:
//: Try removing the conversion to `String` from the last line. What error do you get?
//:
//: There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (`\`) before the parentheses. For example:
//:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
//: - Experiment:
//: Use `\()` to include a floating-point calculation in a string and to include someone’s name in a greeting.
//:
//: Use three double quotes (`"""`) for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quote. For example:
//:
let quotation = """
Even though there's whitespace to the left,
the actual lines aren't indented.
Except for this line.
Double quotes (") can appear without being escaped.
I still have \(apples + oranges) pieces of fruit.
"""
//: Create arrays and dictionaries using brackets (`[]`), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.
//:
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
//: To create an empty array or dictionary, use the initializer syntax.
//:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
//: If type information can be inferred, you can write an empty array as `[]` and an empty dictionary as `[:]`—for example, when you set a new value for a variable or pass an argument to a function.
//:
shoppingList = []
occupations = [:]
//: See [License](License) for this sample's licensing information.
//:
//: [Next](@next)
| mit | daa47299b59ec26f60372a9f8ef72edf | 47.364706 | 417 | 0.723668 | 4.135815 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/Date+Extensions.swift | 1 | 870 | import Foundation
extension Date {
/// Determine if `self` is before the specified `date`.
/// - Parameters:
/// - date: The date to compare with
/// - inclusive: Whether to include `self` in comparison range (i.e. <=)
/// - Returns: A boolean indicating if `self` is before specified `date`.
public func isBefore(_ date: Date, inclusive: Bool = false) -> Bool {
return inclusive ? self <= date : self < date
}
/// Determine if `self` is after the specified `date`.
/// - Parameters:
/// - date: The date to compare with
/// - inclusive: Whether to include `self` in comparison range (i.e. >=)
/// - Returns: A boolean indicating if `self` is after specified `date`.
public func isAfter(_ date: Date, inclusive: Bool = false) -> Bool {
return inclusive ? self >= date : self > date
}
}
| mit | 633501f1dc4a618dd8fcfa7cfcade922 | 36.826087 | 78 | 0.609195 | 4.084507 | false | false | false | false |
Rhapsody/Observable-Swift | Observable-Swift/OwningEventReference.swift | 1 | 1673 | //
// OwningEventReference.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 28/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
/// A subclass of event reference allowing it to own other object[s].
/// Additionally, the reference makes added events own itself.
/// This retain cycle allows owned objects to live as long as valid subscriptions exist.
open class OwningEventReference<T>: EventReference<T> {
internal var owned: AnyObject? = nil
open override func add(_ subscription: SubscriptionType) -> SubscriptionType {
let subscr = super.add(subscription)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
open override func add(_ handler : @escaping (T) -> ()) -> EventSubscription<T> {
let subscr = super.add(handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
open override func remove(_ subscription : SubscriptionType) {
subscription.removeOwnedObject(self)
return event.remove(subscription)
}
open override func removeAll() {
for subscription in event._subscriptions {
subscription.removeOwnedObject(self)
}
event.removeAll()
}
open override func add(owner : AnyObject, _ handler : @escaping HandlerType) -> SubscriptionType {
let subscr = event.add(owner: owner, handler)
if owned != nil {
subscr.addOwnedObject(self)
}
return subscr
}
public override init(event: Event<T>) {
super.init(event: event)
}
}
| mit | 8450be0578ab86f52ebe52a6dbb5a824 | 28.767857 | 102 | 0.626875 | 4.57967 | false | false | false | false |
omaralbeik/SwifterSwift | Sources/Extensions/UIKit/UIAlertControllerExtensions.swift | 1 | 4537 | //
// UIAlertControllerExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/23/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
#if canImport(AudioToolbox)
import AudioToolbox
#endif
// MARK: - Methodss
public extension UIAlertController {
/// SwifterSwift: Present alert view controller in the current view controller.
///
/// - Parameters:
/// - animated: set true to animate presentation of alert controller (default is true).
/// - vibrate: set true to vibrate the device while presenting the alert (default is false).
/// - completion: an optional completion handler to be called after presenting alert controller (default is nil).
public func show(animated: Bool = true, vibrate: Bool = false, completion: (() -> Void)? = nil) {
UIApplication.shared.keyWindow?.rootViewController?.present(self, animated: animated, completion: completion)
if vibrate {
#if canImport(AudioToolbox)
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate)
#endif
}
}
/// SwifterSwift: Add an action to Alert
///
/// - Parameters:
/// - title: action title
/// - style: action style (default is UIAlertActionStyle.default)
/// - isEnabled: isEnabled status for action (default is true)
/// - handler: optional action handler to be called when button is tapped (default is nil)
/// - Returns: action created by this method
@discardableResult public func addAction(title: String, style: UIAlertAction.Style = .default, isEnabled: Bool = true, handler: ((UIAlertAction) -> Void)? = nil) -> UIAlertAction {
let action = UIAlertAction(title: title, style: style, handler: handler)
action.isEnabled = isEnabled
addAction(action)
return action
}
/// SwifterSwift: Add a text field to Alert
///
/// - Parameters:
/// - text: text field text (default is nil)
/// - placeholder: text field placeholder text (default is nil)
/// - editingChangedTarget: an optional target for text field's editingChanged
/// - editingChangedSelector: an optional selector for text field's editingChanged
public func addTextField(text: String? = nil, placeholder: String? = nil, editingChangedTarget: Any?, editingChangedSelector: Selector?) {
addTextField { textField in
textField.text = text
textField.placeholder = placeholder
if let target = editingChangedTarget, let selector = editingChangedSelector {
textField.addTarget(target, action: selector, for: .editingChanged)
}
}
}
}
// MARK: - Initializers
public extension UIAlertController {
/// SwifterSwift: Create new alert view controller with default OK action.
///
/// - Parameters:
/// - title: alert controller's title.
/// - message: alert controller's message (default is nil).
/// - defaultActionButtonTitle: default action button title (default is "OK")
/// - tintColor: alert controller's tint color (default is nil)
public convenience init(title: String, message: String? = nil, defaultActionButtonTitle: String = "OK", tintColor: UIColor? = nil) {
self.init(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil)
addAction(defaultAction)
if let color = tintColor {
view.tintColor = color
}
}
/// SwifterSwift: Create new error alert view controller from Error with default OK action.
///
/// - Parameters:
/// - title: alert controller's title (default is "Error").
/// - error: error to set alert controller's message to it's localizedDescription.
/// - defaultActionButtonTitle: default action button title (default is "OK")
/// - tintColor: alert controller's tint color (default is nil)
public convenience init(title: String = "Error", error: Error, defaultActionButtonTitle: String = "OK", preferredStyle: UIAlertController.Style = .alert, tintColor: UIColor? = nil) {
self.init(title: title, message: error.localizedDescription, preferredStyle: preferredStyle)
let defaultAction = UIAlertAction(title: defaultActionButtonTitle, style: .default, handler: nil)
addAction(defaultAction)
if let color = tintColor {
view.tintColor = color
}
}
}
#endif
| mit | e02987a2725641378a8acecf529b76a7 | 42.615385 | 186 | 0.667989 | 4.805085 | false | false | false | false |
peferron/algo | EPI/Arrays/Compute a random subset/swift/main.swift | 1 | 927 | // swiftlint:disable variable_name
func swap(_ array: inout [Int], _ i: Int, _ j: Int) {
(array[i], array[j]) = (array[j], array[i])
}
// O(n) time and space, since we build an array of size n.
public func randomSubsetArray(n: Int, k: Int) -> [Int] {
var array = (0..<n).map { $0 }
for i in 0..<k {
let r = i + Int(arc4random_uniform(UInt32(n - i)))
swap(&array, i, r)
}
return [Int](array.prefix(k))
}
// Works exactly like randomSubsetArray, but with a dictionary to record value swaps instead of an
// array. Reduces complexity to O(k) time and space.
public func randomSubsetDictionary(n: Int, k: Int) -> [Int] {
var values = [Int: Int]()
for i in 0..<k {
let r = i + Int(arc4random_uniform(UInt32(n - i)))
let vi = values[i] ?? i
let vr = values[r] ?? r
values[i] = vr
values[r] = vi
}
return (0..<k).map { values[$0]! }
}
| mit | 3524d4a31d03c432fffa9b860e7322e1 | 27.090909 | 98 | 0.566343 | 3.00974 | false | false | false | false |
jigneshsheth/Datastructures | DataStructure/DataStructureTests/Array/TwoSumTest.swift | 1 | 1547 | //
// TwoSumTest.swift
// DataStructureTests
//
// Created by Jigs Sheth on 11/2/21.
// Copyright © 2021 jigneshsheth.com. All rights reserved.
//
import XCTest
@testable import DataStructure
class TwoSumTest: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testTwoSum_Efficient() throws {
var nums = [2,7,11,15]
var target = 9
var result = [0,1]
XCTAssertEqual(TwoSum().twoSum_Efficient(nums, target), result)
nums = [3,2,4]
target = 6
result = [1,2]
XCTAssertEqual(TwoSum().twoSum_Efficient(nums, target), result)
nums = [3,3]
target = 6
result = [0,1]
XCTAssertEqual(TwoSum().twoSum_Efficient(nums, target), result)
}
func testTwoSum() throws {
var nums = [2,7,11,15]
var target = 9
var result = [0,1]
XCTAssertEqual(TwoSum().twoSum(nums, target), result)
nums = [3,2,4]
target = 6
result = [1,2]
XCTAssertEqual(TwoSum().twoSum(nums, target), result)
nums = [3,3]
target = 6
result = [0,1]
XCTAssertEqual(TwoSum().twoSum(nums, target), result)
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit | e5272a2aa72ca223741f3fc69235188e | 22.074627 | 111 | 0.643596 | 3.390351 | false | true | false | false |
normand1/TDDWeatherApp | TDDWeatherApp/ViewController.swift | 1 | 5884 | //
// ViewController.swift
// TDDWeatherApp
//
// Created by David Norman on 6/25/15.
// Copyright (c) 2015 David Norman. All rights reserved.
//
import UIKit
enum MeasurementUnit : Int {
case celsius
case fahrenheit
case kelvin
}
class ViewController: UIViewController {
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var zipTextField: UITextField!
@IBOutlet weak var suggestionLabel: UILabel!
var currentMeasurementUnit : MeasurementUnit
var fifteenMinTimer : Timer
var shouldUpdate : Bool
required init?(coder aDecoder: NSCoder) {
currentMeasurementUnit = MeasurementUnit.fahrenheit
fifteenMinTimer = Timer()
shouldUpdate = true
super.init(coder: aDecoder)
}
//MARK: View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let fifteenMinsInSecs = (60 * 15) as TimeInterval
self.fifteenMinTimer = Timer(timeInterval: fifteenMinsInSecs, target: self, selector: #selector(ViewController.setShouldUpdateToTrue), userInfo: nil, repeats: true)
RunLoop.current.add(self.fifteenMinTimer, forMode: RunLoopMode.commonModes)
self.customizeUI()
}
func customizeUI() {
self.zipTextField.backgroundColor = UIColor.clear
}
override func viewDidAppear(_ animated: Bool) {
UIView.animate(withDuration: 2, animations: { () -> Void in
self.view.backgroundColor = UIColor(red: 0.863, green: 0.925, blue: 0.992, alpha: 1.00)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setShouldUpdateToTrue() {
shouldUpdate = true
}
func updateWeatherFromNetwork() {
shouldUpdate = false
OpenWeatherAPIHandler.fetchWeatherForZip(self.zipTextField.text, callback: {
(tempResult, weatherDescription) -> Void in
//set UI Temp element with tempResult
self.updateUIWithLatestTemp(tempResult, weatherDescription: weatherDescription)
})
}
func updateWeatherFromCache() {
if let tempResult = CacheAccess.tempFromCache(self.zipTextField.text!) {
if let weatherDescription = CacheAccess.weatherDescriptionFromCache(self.zipTextField.text!) {
self.updateUIWithLatestTemp(tempResult, weatherDescription: weatherDescription)
}
} else {
self.updateWeatherFromNetwork()
}
// Data for zip code had not yet been fetched so update from the network instead
}
func updateUIWithLatestTemp(_ tempResult : Double?, weatherDescription : String) {
DispatchQueue.main.async(execute: { () -> Void in
if let tempResultExists = tempResult {
if let updatedTempResult = TemperatureConverter.correctTempForCurrentMeasurementUnit(tempResultExists, measurementUnit: self.currentMeasurementUnit) {
let tempUnitSymbol = ViewControllerUtility.symbolForMeasurementUnit(self.currentMeasurementUnit)
let tempResultString = updatedTempResult.format(".01")
self.tempLabel.text = "\(tempResultString)\(tempUnitSymbol!)"
self.suggestionLabel.text = "\(ViewControllerUtility.weatherDescriptionAndTempConsiderationsCombined(tempResultExists, apiWeatherDescription: weatherDescription))"
self.updateBackgroundColorForTemp(tempResultExists)
} else {
self.showErrorAlert()
}
} else {
self.showErrorAlert()
}
})
}
func updateBackgroundColorForTemp(_ tempInKelvin : Double) {
UIView.animate(withDuration: 2, animations: { () -> Void in
switch tempInKelvin {
case 0...288:
self.view.backgroundColor = UIColor(red: 0.667, green: 0.831, blue: 0.976, alpha: 1.00)
case 289...297:
self.view.backgroundColor = UIColor(red: 0.671, green: 0.980, blue: 0.886, alpha: 1.00)
case 298...302:
self.view.backgroundColor = UIColor(red: 0.973, green: 0.824, blue: 0.663, alpha: 1.00)
case 303...500:
self.view.backgroundColor = UIColor(red: 1.000, green: 0.588, blue: 0.408, alpha: 1.00)
default:
self.view.backgroundColor = UIColor(red: 0.863, green: 0.925, blue: 0.992, alpha: 1.00)
}
})
}
//MARK: Actions
@IBAction func FindWeatherTap(_ sender: UIButton) {
if ViewControllerUtility.checkIfIsZip(self.zipTextField.text!) {
if CacheAccess.zipIsCached(self.zipTextField.text!) {
self.handleZipIsAlreadyCached()
} else {
self.updateWeatherFromNetwork()
}
self.view.endEditing(true)
} else {
self.showErrorAlert()
}
}
func handleZipIsAlreadyCached() {
if self.shouldUpdate {
self.shouldUpdate = false
self.updateWeatherFromNetwork()
} else {
self.updateWeatherFromCache()
}
}
func showErrorAlert() {
let alert = UIAlertView(title: "Error", message: "Please enter a correct zipcode", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
@IBAction func tapChangeMeasurementUnit(_ sender: UIButton) {
//cycle to next measurement unit [C, F, K] enum
let nextMeasurementUnit = (self.currentMeasurementUnit.rawValue + 1) % 3
self.currentMeasurementUnit = MeasurementUnit(rawValue: nextMeasurementUnit)!
self.FindWeatherTap(sender)
}
}
| mit | 20b68176399b6ae0ee76184113a5017b | 35.320988 | 183 | 0.620836 | 4.772101 | false | false | false | false |
alessiobrozzi/firefox-ios | Account/FxAState.swift | 5 | 12884 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import FxA
import Shared
import SwiftyJSON
// The version of the state schema we persist.
let StateSchemaVersion = 1
// We want an enum because the set of states is closed. However, each state has state-specific
// behaviour, and the state's behaviour accumulates, so each state is a class. Switch on the
// label to get exhaustive cases.
public enum FxAStateLabel: String {
case engagedBeforeVerified = "engagedBeforeVerified"
case engagedAfterVerified = "engagedAfterVerified"
case cohabitingBeforeKeyPair = "cohabitingBeforeKeyPair"
case cohabitingAfterKeyPair = "cohabitingAfterKeyPair"
case married = "married"
case separated = "separated"
case doghouse = "doghouse"
// See http://stackoverflow.com/a/24137319
static let allValues: [FxAStateLabel] = [
engagedBeforeVerified,
engagedAfterVerified,
cohabitingBeforeKeyPair,
cohabitingAfterKeyPair,
married,
separated,
doghouse,
]
}
public enum FxAActionNeeded {
case none
case needsVerification
case needsPassword
case needsUpgrade
}
func state(fromJSON json: JSON) -> FxAState? {
if json.error != nil {
return nil
}
if let version = json["version"].int {
if version == StateSchemaVersion {
return stateV1(fromJSON:json)
}
}
return nil
}
func stateV1(fromJSON json: JSON) -> FxAState? {
if let labelString = json["label"].string {
if let label = FxAStateLabel(rawValue: labelString) {
switch label {
case .engagedBeforeVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData,
let knownUnverifiedAt = json["knownUnverifiedAt"].int64,
let lastNotifiedUserAt = json["lastNotifiedUserAt"].int64 {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: UInt64(knownUnverifiedAt), lastNotifiedUserAt: UInt64(lastNotifiedUserAt),
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .engagedAfterVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .cohabitingBeforeKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData {
return CohabitingBeforeKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB)
}
case .cohabitingAfterKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData,
let keyPairJSON = json["keyPair"].dictionaryObject as? [String: AnyObject],
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64 {
return CohabitingAfterKeyPairState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt))
}
case .married:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kA = json["kA"].string?.hexDecodedData,
let kB = json["kB"].string?.hexDecodedData,
let keyPairJSON = json["keyPair"].dictionaryObject as? [String: AnyObject],
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64,
let certificate = json["certificate"].string,
let certificateExpiresAt = json["certificateExpiresAt"].int64 {
return MarriedState(sessionToken: sessionToken, kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt),
certificate: certificate, certificateExpiresAt: UInt64(certificateExpiresAt))
}
case .separated:
return SeparatedState()
case .doghouse:
return DoghouseState()
}
}
}
return nil
}
// Not an externally facing state!
open class FxAState: JSONLiteralConvertible {
open var label: FxAStateLabel { return FxAStateLabel.separated } // This is bogus, but we have to do something!
open var actionNeeded: FxAActionNeeded {
// Kind of nice to have this in one place.
switch label {
case .engagedBeforeVerified: return .needsVerification
case .engagedAfterVerified: return .none
case .cohabitingBeforeKeyPair: return .none
case .cohabitingAfterKeyPair: return .none
case .married: return .none
case .separated: return .needsPassword
case .doghouse: return .needsUpgrade
}
}
open func asJSON() -> JSON {
return JSON([
"version": StateSchemaVersion,
"label": self.label.rawValue,
] as NSDictionary)
}
}
open class SeparatedState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.separated }
override public init() {
super.init()
}
}
// Not an externally facing state!
open class TokenState: FxAState {
let sessionToken: Data
init(sessionToken: Data) {
self.sessionToken = sessionToken
super.init()
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
// Not an externally facing state!
open class ReadyForKeys: TokenState {
let keyFetchToken: Data
let unwrapkB: Data
init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.keyFetchToken = keyFetchToken
self.unwrapkB = unwrapkB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["keyFetchToken"] = JSON(keyFetchToken.hexEncodedString as NSString)
d["unwrapkB"] = JSON(unwrapkB.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
open class EngagedBeforeVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedBeforeVerified }
// Timestamp, in milliseconds after the epoch, when we first knew the account was unverified.
// Use this to avoid nagging the user to verify her account immediately after connecting.
let knownUnverifiedAt: Timestamp
let lastNotifiedUserAt: Timestamp
public init(knownUnverifiedAt: Timestamp, lastNotifiedUserAt: Timestamp, sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.knownUnverifiedAt = knownUnverifiedAt
self.lastNotifiedUserAt = lastNotifiedUserAt
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["knownUnverifiedAt"] = JSON(NSNumber(value: knownUnverifiedAt))
d["lastNotifiedUserAt"] = JSON(NSNumber(value: lastNotifiedUserAt))
return JSON(d as NSDictionary)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedBeforeVerifiedState {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: knownUnverifiedAt, lastNotifiedUserAt: lastNotifiedUserAt,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
open class EngagedAfterVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedAfterVerified }
override public init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedAfterVerifiedState {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
// Not an externally facing state!
open class TokenAndKeys: TokenState {
open let kA: Data
open let kB: Data
init(sessionToken: Data, kA: Data, kB: Data) {
self.kA = kA
self.kB = kB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["kA"] = JSON(kA.hexEncodedString as NSString)
d["kB"] = JSON(kB.hexEncodedString as NSString)
return JSON(d as NSDictionary)
}
}
open class CohabitingBeforeKeyPairState: TokenAndKeys {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingBeforeKeyPair }
}
// Not an externally facing state!
open class TokenKeysAndKeyPair: TokenAndKeys {
let keyPair: KeyPair
// Timestamp, in milliseconds after the epoch, when keyPair expires. After this time, generate a new keyPair.
let keyPairExpiresAt: Timestamp
init(sessionToken: Data, kA: Data, kB: Data, keyPair: KeyPair, keyPairExpiresAt: Timestamp) {
self.keyPair = keyPair
self.keyPairExpiresAt = keyPairExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["keyPair"] = JSON(keyPair.jsonRepresentation() as NSDictionary)
d["keyPairExpiresAt"] = JSON(NSNumber(value: keyPairExpiresAt))
return JSON(d as NSDictionary)
}
func isKeyPairExpired(_ now: Timestamp) -> Bool {
return keyPairExpiresAt < now
}
}
open class CohabitingAfterKeyPairState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingAfterKeyPair }
}
open class MarriedState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.married }
let certificate: String
let certificateExpiresAt: Timestamp
init(sessionToken: Data, kA: Data, kB: Data, keyPair: KeyPair, keyPairExpiresAt: Timestamp, certificate: String, certificateExpiresAt: Timestamp) {
self.certificate = certificate
self.certificateExpiresAt = certificateExpiresAt
super.init(sessionToken: sessionToken, kA: kA, kB: kB, keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["certificate"] = JSON(certificate as NSString)
d["certificateExpiresAt"] = JSON(NSNumber(value: certificateExpiresAt))
return JSON(d as NSDictionary)
}
func isCertificateExpired(_ now: Timestamp) -> Bool {
return certificateExpiresAt < now
}
func withoutKeyPair() -> CohabitingBeforeKeyPairState {
let newState = CohabitingBeforeKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB)
return newState
}
func withoutCertificate() -> CohabitingAfterKeyPairState {
let newState = CohabitingAfterKeyPairState(sessionToken: sessionToken,
kA: kA, kB: kB,
keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
return newState
}
open func generateAssertionForAudience(_ audience: String, now: Timestamp) -> String {
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience,
issuer: "127.0.0.1",
issuedAt: now,
duration: OneHourInMilliseconds)
return assertion!
}
}
open class DoghouseState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.doghouse }
override public init() {
super.init()
}
}
| mpl-2.0 | ef2b8ab55c0e93841c4a6a5359d911a8 | 37.118343 | 151 | 0.654533 | 5.352721 | false | false | false | false |
RemarkableIO/Publinks | Publinks/Publink.swift | 1 | 3775 | //
// Publink.swift
//
// Created by Giles Van Gruisen on 11/12/14.
// Copyright (c) 2014 Giles Van Gruisen. All rights reserved.
//
infix operator >>> { associativity left }
public func >>><T>(publink: Publink<T>, subscriptionBlock: T -> ()) {
publink.subscribe(subscriptionBlock)
}
/** Performs subscription blocks with a value upon calling `publish(value: T)` with value of the type set upon initialization. */
public class Publink<ParameterType> {
/** A block that accepts a value as an argument */
typealias SubscriptionBlock = (ParameterType) -> ()
/** Subscription blocks to be called with optional value on `publish(value: T)` */
private var subscriptionBlocks: [SubscriptionBlock] {
didSet {
updateAllSubscriptionBlocks()
}
}
/** Named subscription blocks to be called with optional value on `publish(value: T)` */
private var namedSubscriptionBlocks = [String: SubscriptionBlock]()
/** A collection of all subscription blocks */
private var allSubscriptionBlocks = [SubscriptionBlock]()
/** The last value passed to `publish(value: T)`, to be passed to a block upon subscription if `callsLast` is set to true */
private var lastValue: ParameterType?
/** If set to true, blocks will be called with lastValue immediately upon subscription. Default value is true */
public var callsLast = true
/** The number of times publish has been called */
private var publishCount = 0
/** Initializes a Publink */
public init() {
subscriptionBlocks = []
}
/** Called by subscriber, passing a SubscriptionBlock to be called with an optional value when publish(value: T?) is called */
public func subscribe(newSubscriptionBlock: SubscriptionBlock) {
// Add subscription block
subscriptionBlocks.append(newSubscriptionBlock)
// Try to call with last value
callLast(newSubscriptionBlock)
}
/** Called by subscriber, passing a SubscriptionBlock to be called with an optional value when publish(value: T?) is called */
public func subscribeNamed(name: String, newSubscriptionBlock: SubscriptionBlock) {
// Add subscription block
namedSubscriptionBlocks[name] = newSubscriptionBlock
// Try to call with last value
callLast(newSubscriptionBlock)
// Update all blocks
updateAllSubscriptionBlocks()
}
/** Call to unsubscribe a particular subscription block */
public func unsubscribe(name: String) {
namedSubscriptionBlocks[name] = nil
updateAllSubscriptionBlocks()
}
/** Called by publisher with optional value. Calls every block in subscriptionBlocks */
public func publish(value: ParameterType) {
// Increment publishCount
publishCount += 1
// Set the last value to be passed into new subscription blocks if callsLast is true
lastValue = value
// Enumerate subscription blocks and pass optional value to each
for subscriptionBlock in allSubscriptionBlocks {
subscriptionBlock(value)
}
}
private func updateAllSubscriptionBlocks() {
// Update all blocks to subscription blocks
allSubscriptionBlocks = subscriptionBlocks
// Add each named block
for (name, block) in namedSubscriptionBlocks {
allSubscriptionBlocks += [block]
}
}
/** Checks callsLast and, if true, passes lastValue into into subscriptionBlock */
private func callLast(subscriptionBlock: SubscriptionBlock) {
// Call new subscription block with lastValue is callsLast is set to true
if callsLast && publishCount > 0 {
subscriptionBlock(lastValue!)
}
}
}
| mit | 3560c36718e197f9867454d3ab942bae | 31.826087 | 130 | 0.678146 | 4.98679 | false | false | false | false |
qinhaichuan/Microblog | microblog/Pods/SnapKit/Source/ConstraintViewController+Extensions.swift | 2 | 2282 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
public extension ConstraintViewController {
@available(iOS, deprecated=0.30.0, message="Please use newer snp.* syntax.")
public var topLayoutGuideTop: ConstraintItem {
return self.snp.topLayoutGuideTop
}
@available(iOS, deprecated=0.30.0, message="Please use newer snp.* syntax.")
public var topLayoutGuideBottom: ConstraintItem {
return self.snp.topLayoutGuideBottom
}
@available(iOS, deprecated=0.30.0, message="Please use newer snp.* syntax.")
public var bottomLayoutGuideTop: ConstraintItem {
return self.snp.bottomLayoutGuideTop
}
@available(iOS, deprecated=0.30.0, message="Please use newer snp.* syntax.")
public var bottomLayoutGuideBottom: ConstraintItem {
return self.snp.bottomLayoutGuideBottom
}
public var snp: ConstraintViewControllerDSL {
return ConstraintViewControllerDSL(viewController: self)
}
}
#endif
| mit | 86ea57c288d2d1acb9f81d4132ffbec7 | 39.75 | 84 | 0.688869 | 4.705155 | false | false | false | false |
gigascorp/fiscal-cidadao | ios/FiscalCidadao/Convenio.swift | 1 | 1902 | /*
Copyright (c) 2009-2014, Apple Inc. All rights reserved.
Copyright (C) 2016 Andrea Mendonça, Emílio Weba, Guilherme Ribeiro, Márcio Oliveira, Thiago Nunes, Wallas Henrique
This file is part of Fiscal Cidadão.
Fiscal Cidadão 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.
Fiscal Cidadão 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 Fiscal Cidadão. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class Convenio: NSObject
{
var id : Int
var startDate : String?
var endDate : String?
var location : (Double, Double)
var desc : String
var responsible : String
var proponent : String
var responsiblePhone : String?
var status : String?
var value : Float
init(id : Int, startDate : String?, endDate : String?, location : (Double, Double), desc : String, proponent : String, responsible : String, responsiblePhone : String?, status : String?, value : Float)
{
self.id = id
self.startDate = startDate
self.endDate = endDate
self.location = location
self.desc = desc
self.proponent = proponent
self.responsible = responsible
self.responsiblePhone = responsiblePhone
self.status = status
self.value = value
}
override var description : String
{
return "Convenio {id: \(id)" + ", description \(desc), proponente : \(responsible) location(\(location))}"
}
}
| gpl-3.0 | ccae4cebea9042a616a2ac864ce574b8 | 31.672414 | 205 | 0.682322 | 4.268018 | false | false | false | false |
gregomni/swift | stdlib/public/core/Join.swift | 10 | 5786 | //===--- Join.swift - Protocol and Algorithm for concatenation ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence that presents the elements of a base sequence of sequences
/// concatenated using a given separator.
@frozen // lazy-performance
public struct JoinedSequence<Base: Sequence> where Base.Element: Sequence {
public typealias Element = Base.Element.Element
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal var _separator: ContiguousArray<Element>
/// Creates an iterator that presents the elements of the sequences
/// traversed by `base`, concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // lazy-performance
public init<Separator: Sequence>(base: Base, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separator = ContiguousArray(separator)
}
}
extension JoinedSequence {
/// An iterator that presents the elements of the sequences traversed
/// by a base iterator, concatenated using a given separator.
@frozen // lazy-performance
public struct Iterator {
@frozen // lazy-performance
@usableFromInline // lazy-performance
internal enum _JoinIteratorState {
case start
case generatingElements
case generatingSeparator
case end
}
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal var _inner: Base.Element.Iterator?
@usableFromInline // lazy-performance
internal var _separatorData: ContiguousArray<Element>
@usableFromInline // lazy-performance
internal var _separator: ContiguousArray<Element>.Iterator?
@usableFromInline // lazy-performance
internal var _state: _JoinIteratorState = .start
/// Creates an iterator that presents the elements of `base` sequences
/// concatenated using `separator`.
///
/// - Complexity: O(`separator.count`).
@inlinable // lazy-performance
public init<Separator: Sequence>(base: Base.Iterator, separator: Separator)
where Separator.Element == Element {
self._base = base
self._separatorData = ContiguousArray(separator)
}
}
}
extension JoinedSequence.Iterator: IteratorProtocol {
public typealias Element = Base.Element.Element
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // lazy-performance
public mutating func next() -> Element? {
while true {
switch _state {
case .start:
if let nextSubSequence = _base.next() {
_inner = nextSubSequence.makeIterator()
_state = .generatingElements
} else {
_state = .end
return nil
}
case .generatingElements:
let result = _inner!.next()
if _fastPath(result != nil) {
return result
}
_inner = _base.next()?.makeIterator()
if _inner == nil {
_state = .end
return nil
}
if !_separatorData.isEmpty {
_separator = _separatorData.makeIterator()
_state = .generatingSeparator
}
case .generatingSeparator:
let result = _separator!.next()
if _fastPath(result != nil) {
return result
}
_state = .generatingElements
case .end:
return nil
}
}
}
}
extension JoinedSequence: Sequence {
/// Return an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(base: _base.makeIterator(), separator: _separator)
}
@inlinable // lazy-performance
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
var result = ContiguousArray<Element>()
let separatorSize = _separator.count
if separatorSize == 0 {
for x in _base {
result.append(contentsOf: x)
}
return result
}
var iter = _base.makeIterator()
if let first = iter.next() {
result.append(contentsOf: first)
while let next = iter.next() {
result.append(contentsOf: _separator)
result.append(contentsOf: next)
}
}
return result
}
}
extension Sequence where Element: Sequence {
/// Returns the concatenated elements of this sequence of sequences,
/// inserting the given separator between each element.
///
/// This example shows how an array of `[Int]` instances can be joined, using
/// another `[Int]` instance as the separator:
///
/// let nestedNumbers = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
/// let joined = nestedNumbers.joined(separator: [-1, -2])
/// print(Array(joined))
/// // Prints "[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]"
///
/// - Parameter separator: A sequence to insert between each of this
/// sequence's elements.
/// - Returns: The joined sequence of elements.
@inlinable // lazy-performance
public __consuming func joined<Separator: Sequence>(
separator: Separator
) -> JoinedSequence<Self>
where Separator.Element == Element.Element {
return JoinedSequence(base: self, separator: separator)
}
}
| apache-2.0 | 64bce39765988ddb6313bcc54a63dda8 | 31.144444 | 80 | 0.645005 | 4.610359 | false | false | false | false |
bastienFalcou/FindMyContacts | ContactSyncing/Helpers/Classes/ContactFetcher.swift | 1 | 2658 | //
// PhoneContactsFetcher.swift
// FindMyContacts
//
// Created by Bastien Falcou on 1/6/17.
// Copyright © 2017 Bastien Falcou. All rights reserved.
//
import Foundation
import RealmSwift
import EthanolContacts
import ReactiveSwift
import Contacts
final class ContactFetcher: NSObject {
static var shared = ContactFetcher()
private let phoneContactFetcher = PhoneContactFetcher()
var syncContactsAction: Action<Void, [PhoneContact], NSError>!
let isContactsPermissionGranted = MutableProperty(false)
override init() {
super.init()
self.syncContactsAction = Action(self.syncLocalAddressBook)
}
func requestContactsPermission() {
self.phoneContactFetcher.authorize(success: {
self.updateAuthorizationStatusIfNeeded()
}) { _ in
self.updateAuthorizationStatusIfNeeded()
}
}
// PRAGMA: - private
fileprivate func syncLocalAddressBook() -> SignalProducer<[PhoneContact], NSError> {
return SignalProducer { sink, disposable in
self.phoneContactFetcher.fetchContacts(for: [.GivenName, .FamilyName, .Phone], success: { contacts in
RealmManager.shared.performInBackground { backgroundRealm in
var contactEntities = Set<PhoneContact>()
backgroundRealm.beginWrite()
for contact in contacts where contact.phone != nil && !contact.phone!.isEmpty {
let contactEntity = PhoneContact.uniqueObject(for: contact.identifier, in: backgroundRealm)
contactEntity.phoneNumber = contact.phone!.first!
contactEntity.username = contact.familyName.isEmpty ? "\(contact.givenName)" : "\(contact.givenName) \(contact.familyName)"
contactEntities.insert(contactEntity)
}
do {
backgroundRealm.add(contactEntities)
try backgroundRealm.commitWrite()
try PhoneContact.substractObsoleteLocalContacts(with: Array(contactEntities), realm: backgroundRealm)
DispatchQueue.main.async {
RealmManager.shared.realm.refresh()
sink.send(value: Array(RealmManager.shared.realm.objects(PhoneContact.self)))
sink.sendCompleted()
}
} catch {
print("Contacts: failed to save synced contacts: \(error)")
sink.send(error: error as NSError)
}
}
}) { error in
let error = error != nil ? error! as NSError : NSError(domain: "bastienFalcou.FindMyContacts.ContactFetcher.", code: 0, userInfo: nil)
print("Contacts: failed to save synced contacts: \(error.localizedDescription)")
sink.send(error: error)
}
}
}
func updateAuthorizationStatusIfNeeded() {
let authorizationStatus = CNContactStore.authorizationStatus(for: .contacts)
self.isContactsPermissionGranted.value = authorizationStatus == .authorized
}
}
| mit | be454c81d87b6bef1f16ebdc74a891e2 | 32.632911 | 138 | 0.735792 | 4.050305 | false | false | false | false |
thomas0326/DTSwiftDemo | DTSwiftDemo/ClosureObj.swift | 1 | 4110 | //
// ClosureObj.swift
// first_swift_demo
//
// Created by liuyuting on 16/12/1.
// Copyright © 2016年 pf. All rights reserved.
//
import UIKit
class ClosureObj: NSObject {
// 直接赋值属性,看看和闭包有何区别,看不出来吗,那就往下看吧
var str : String = "jack"
// 闭包可以这么定义
var str0 : String = {
return "jack"
}()
// 可以省略 = 和 ()
var str1 : String{
return "jack"
}
// 可以包含get方法
var str2 : String {
get{
return "jack"
}
}
// 当然也可以包含 set 方法
var str3 : String {
get{
return "jack"
}
set{
print("jack")
}
}
// 那willSet 和 willGet 也可以咯
var str4 : String = "Bob" {
willSet{
print("Bob")
}
didSet{
print("Bob")
}
}
// 闭包定义
// {
//
// (arguments) - > returnType in
// code
// }(arguments)
// 可以在闭包中定义参数,返回值。闭包后用括号执行,并在括号中可以传参, 例如
var s = {
(arg1:String,arg2:String) -> String in
return arg1 + arg2
}("Job1","Bob2")
// 基于上面最全的定义方式,我们可以省略参数类型:
var s2 = {
arg1,arg2 -> String in
return arg1 + arg2
}("Job1","Bob2")
// swift 的类型推到,根据后面括号的传参能自动判断参数的类型
// 那么我们是不是也可以省略 返回值类型,但是在声明时要确定
// eg:
var s3 : String = {
arg1,arg2 in
return arg1 + arg2
}("Job1","Bob2")
// 是不是很爽,其实还可以更爽
var s4 : String = {
return $0 + $1
}("Job1","Bob2")
// 这样写return 是不是感觉没有作用,那就这样好了
var s5 : String = {
$0 + $1
}("Job1","Bob2")
// 如果闭包没有参数呢,那还不简单
var s6 : String = {
return "Job"
}()
// 什么,你说括号也没用,那干脆点好了
// tip: 没有() 也不需要 = 了
var s7 : String {
return "JOB"
}
// 回头再看看上面声明的str 变量,是不是耳目一新了
func test() {
let arr = [20,35]
let a = arr.map { (number) -> String in
var output = ""
while number > 0 {
output = String(number % 10) + output
// number /= 10
}
return output
}
}
func increment(amount : Int) -> (() -> Int){
var total = 0
func incrementAmount() -> Int {
total += amount
return total
}
return incrementAmount
}
// 逃逸闭包
// @escaping
//
// 传递给函数的闭包如果不是在函数内调用,而是在函数内用外部变量保存当前的闭包,在合适的时间再进行调用,这是就需要在闭包参数前加入 @escaping 关键字,不然编译器会报错。
//
// 比较好理解的就是经常用到的网络请求,请求完成才执行完成的闭包。
//
// 官方的例子如下:
var escapClosures : [() -> String] = []
func escap(escapClosure: @escaping () -> String){
escapClosures.append(escapClosure)
}
// @autoclosure 自动闭包
// 如果不用autoClosure
var customers = ["ALex","EWa","job","jack"]
func serve(customer customerCloser : () -> String){
print("Now serving is \(customerCloser())")
}
func test2 () {
serve(customer: {customers.remove(at: 0)})
}
// 使用autoClosure
func serve2(customer customerClosure: @autoclosure () -> String){
print("Now serving is \(customerClosure())")
}
func test3 (){
serve2(customer: customers.remove(at: 0))
}
}
| mit | 7b28fefe226b9838e8280f3d186331f6 | 18.921687 | 93 | 0.474448 | 3.333669 | false | false | false | false |
mpimenov/omim | iphone/Maps/Classes/CarPlay/Templates Data/RouteInfo.swift | 7 | 1397 | @objc(MWMRouteInfo)
class RouteInfo: NSObject {
let timeToTarget: TimeInterval
let targetDistance: String
let targetUnits: UnitLength
let distanceToTurn: String
let streetName: String
let turnUnits: UnitLength
let turnImageName: String?
let nextTurnImageName: String?
let speed: Int
let roundExitNumber: Int
@objc init(timeToTarget: TimeInterval,
targetDistance: String,
targetUnits: String,
distanceToTurn: String,
streetName: String,
turnUnits: String,
turnImageName: String?,
nextTurnImageName: String?,
speed: Int,
roundExitNumber: Int) {
self.timeToTarget = timeToTarget
self.targetDistance = targetDistance
self.targetUnits = RouteInfo.unitLength(for: targetUnits)
self.distanceToTurn = distanceToTurn
self.streetName = streetName;
self.turnUnits = RouteInfo.unitLength(for: turnUnits)
self.turnImageName = turnImageName
self.nextTurnImageName = nextTurnImageName
self.speed = speed
self.roundExitNumber = roundExitNumber
}
class func unitLength(for targetUnits: String) -> UnitLength {
switch targetUnits {
case "mi":
return .miles
case "ft":
return .feet
case "km":
return .kilometers
case "m":
return .meters
default:
return .meters
}
}
}
| apache-2.0 | 6eddcd08e586ebdc0e8d732d98c42acf | 26.94 | 64 | 0.662133 | 4.463259 | false | false | false | false |
breadwallet/breadwallet | BreadWallet/BRAPIClient.swift | 2 | 39902 | //
// BRAPIClient.swift
// BreadWallet
//
// Created by Samuel Sutch on 11/4/15.
// Copyright (c) 2016 breadwallet 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 Foundation
let BRAPIClientErrorDomain = "BRApiClientErrorDomain"
// these flags map to api feature flag name values
// eg "buy-bitcoin-with-cash" is a persistent name in the /me/features list
@objc public enum BRFeatureFlags: Int, CustomStringConvertible {
case buyBitcoin
case earlyAccess
public var description: String {
switch self {
case .buyBitcoin: return "buy-bitcoin";
case .earlyAccess: return "early-access";
}
}
}
public typealias URLSessionTaskHandler = (Data?, HTTPURLResponse?, NSError?) -> Void
public typealias URLSessionChallengeHandler = (URLSession.AuthChallengeDisposition, URLCredential?) -> Void
// an object which implements BRAPIAdaptor can execute API Requests on the current wallet's behalf
public protocol BRAPIAdaptor {
// execute an API request against the current wallet
func dataTaskWithRequest(
_ request: URLRequest, authenticated: Bool, retryCount: Int,
handler: @escaping URLSessionTaskHandler
) -> URLSessionDataTask
}
extension String {
static var urlQuoteCharacterSet: CharacterSet {
let cset = (NSMutableCharacterSet.urlQueryAllowed as NSCharacterSet).mutableCopy() as! NSMutableCharacterSet
cset.removeCharacters(in: "?=&")
return cset as CharacterSet
}
var urlEscapedString: String {
return self.addingPercentEncoding(
withAllowedCharacters: String.urlQuoteCharacterSet)!
}
}
func getHeaderValue(_ k: String, d: [String: String]?) -> String? {
guard let d = d else {
return nil
}
if let v = d[k] { // short path: attempt to get the header directly
return v
}
let lkKey = k.lowercased() // long path: compare lowercase keys
for (lk, lv) in d {
if lk.lowercased() == lkKey {
return lv
}
}
return nil
}
func getAuthKey() -> BRKey? {
if let manager = BRWalletManager.sharedInstance(), let authKey = manager.authPrivateKey {
return BRKey(privateKey: authKey)
}
return nil
}
func getDeviceId() -> String {
let ud = UserDefaults.standard
if let s = ud.string(forKey: "BR_DEVICE_ID") {
return s
}
let s = CFUUIDCreateString(nil, CFUUIDCreate(nil)) as String
ud.setValue(s, forKey: "BR_DEVICE_ID")
print("new device id \(s)")
return s
}
func isBreadChallenge(_ r: HTTPURLResponse) -> Bool {
if let headers = r.allHeaderFields as? [String: String],
let challenge = getHeaderValue("www-authenticate", d: headers) {
if challenge.lowercased().hasPrefix("bread") {
return true
}
}
return false
}
func buildURLResourceString(_ url: URL?) -> String {
var urlStr = ""
if let url = url {
urlStr = "\(url.path)"
if let query = url.query {
if query.lengthOfBytes(using: String.Encoding.utf8) > 0 {
urlStr = "\(urlStr)?\(query)"
}
}
}
return urlStr
}
func buildRequestSigningString(_ r: URLRequest) -> String {
var parts = [
r.httpMethod ?? "",
"",
getHeaderValue("content-type", d: r.allHTTPHeaderFields) ?? "",
getHeaderValue("date", d: r.allHTTPHeaderFields) ?? "",
buildURLResourceString(r.url)
]
if let meth = r.httpMethod {
switch meth {
case "POST", "PUT", "PATCH":
if let d = r.httpBody , d.count > 0 {
let sha = (d as NSData).sha256()
parts[1] = (NSData(uInt256: sha) as NSData).base58String()
}
default: break
}
}
return parts.joined(separator: "\n")
}
@objc open class BRAPIClient: NSObject, URLSessionDelegate, URLSessionTaskDelegate, BRAPIAdaptor {
// BRAPIClient is intended to be used as a singleton so this is the instance you should use
static let sharedClient = BRAPIClient()
// whether or not to emit log messages from this instance of the client
var logEnabled = true
// proto is the transport protocol to use for talking to the API (either http or https)
var proto = "https"
// host is the server(s) on which the API is hosted
#if Debug || Testflight
var host = "stage.breadwallet.com"
#else
var host = "api.breadwallet.com"
#endif
// isFetchingAuth is set to true when a request is currently trying to renew authentication (the token)
// it is useful because fetching auth is not idempotent and not reentrant, so at most one auth attempt
// can take place at any one time
fileprivate var isFetchingAuth = false
// used when requests are waiting for authentication to be fetched
fileprivate var authFetchGroup: DispatchGroup = DispatchGroup()
// storage for the session constructor below
fileprivate var _session: Foundation.URLSession? = nil
// the NSURLSession on which all NSURLSessionTasks are executed
fileprivate var session: Foundation.URLSession {
if _session == nil {
let config = URLSessionConfiguration.default
_session = Foundation.URLSession(configuration: config, delegate: self, delegateQueue: queue)
}
return _session!
}
// the queue on which the NSURLSession operates
fileprivate var queue = OperationQueue()
// convenience getter for the API endpoint
var baseUrl: String {
return "\(proto)://\(host)"
}
// prints whatever you give it if logEnabled is true
func log(_ s: String) {
if !logEnabled {
return
}
print("[BRAPIClient] \(s)")
}
var deviceId: String {
return getDeviceId()
}
// MARK: Networking functions
// Constructs a full NSURL for a given path and url parameters
func url(_ path: String, args: Dictionary<String, String>? = nil) -> URL {
func joinPath(_ k: String...) -> URL {
return URL(string: ([baseUrl] + k).joined(separator: ""))!
}
if let args = args {
return joinPath(path + "?" + args.map({
"\($0.0.urlEscapedString)=\($0.1.urlEscapedString)"
}).joined(separator: "&"))
} else {
return joinPath(path)
}
}
func signRequest(_ request: URLRequest) -> URLRequest {
var mutableRequest = request
let dateHeader = getHeaderValue("date", d: mutableRequest.allHTTPHeaderFields)
if dateHeader == nil {
// add Date header if necessary
mutableRequest.setValue(Date().RFC1123String(), forHTTPHeaderField: "Date")
}
if let manager = BRWalletManager.sharedInstance(),
let tokenData = manager.userAccount,
let token = tokenData["token"],
let authKey = getAuthKey(),
let signingData = buildRequestSigningString(mutableRequest).data(using: String.Encoding.utf8),
let sig = authKey.compactSign((signingData as NSData).sha256_2()) {
let hval = "bread \(token):\((sig as NSData).base58String())"
mutableRequest.setValue(hval, forHTTPHeaderField: "Authorization")
}
return mutableRequest as URLRequest
}
func decorateRequest(_ request: URLRequest) -> URLRequest {
var actualRequest = request
let testnet = BRWalletManager.sharedInstance()?.isTestnet
#if Testflight
let testflight = true
#else
let testflight = false
#endif
actualRequest.setValue("\((testnet ?? false) ? 1 : 0)", forHTTPHeaderField: "X-Bitcoin-Testnet")
actualRequest.setValue("\(testflight ? 1 : 0)", forHTTPHeaderField: "X-Testflight")
return actualRequest
}
open func dataTaskWithRequest(_ request: URLRequest, authenticated: Bool = false,
retryCount: Int = 0, handler: @escaping URLSessionTaskHandler) -> URLSessionDataTask {
let start = Date()
var logLine = ""
if let meth = request.httpMethod, let u = request.url {
logLine = "\(meth) \(u) auth=\(authenticated) retry=\(retryCount)"
}
let origRequest = (request as NSURLRequest).mutableCopy() as! URLRequest
var actualRequest = decorateRequest(request)
if authenticated {
actualRequest = signRequest(actualRequest)
}
return session.dataTask(with: actualRequest, completionHandler: { (data, resp, err) -> Void in
DispatchQueue.main.async {
let end = Date()
let dur = Int(end.timeIntervalSince(start) * 1000)
if let httpResp = resp as? HTTPURLResponse {
var errStr = ""
if httpResp.statusCode >= 400 {
if let data = data, let s = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
errStr = s as String
}
}
self.log("\(logLine) -> status=\(httpResp.statusCode) duration=\(dur)ms errStr=\(errStr)")
if authenticated && isBreadChallenge(httpResp) {
self.log("\(logLine) got authentication challenge from API - will attempt to get token")
self.getToken { err in
if err != nil && retryCount < 1 { // retry once
self.log("\(logLine) error retrieving token: \(String(describing: err)) - will retry")
DispatchQueue.main.asyncAfter(deadline: DispatchTime(uptimeNanoseconds: 1)) {
self.dataTaskWithRequest(
origRequest, authenticated: authenticated,
retryCount: retryCount + 1, handler: handler
).resume()
}
} else if err != nil && retryCount > 0 { // fail if we already retried
self.log("\(logLine) error retrieving token: \(String(describing: err)) - will no longer retry")
handler(nil, nil, err)
} else if retryCount < 1 { // no error, so attempt the request again
self.log("\(logLine) retrieved token, so retrying the original request")
self.dataTaskWithRequest(
origRequest, authenticated: authenticated,
retryCount: retryCount + 1, handler: handler).resume()
} else {
self.log("\(logLine) retried token multiple times, will not retry again")
handler(data, httpResp, err)
}
}
} else {
handler(data, httpResp, err as NSError?)
}
} else {
self.log("\(logLine) encountered connection error \(String(describing: err))")
handler(data, nil, err as NSError?)
}
}
})
}
// retrieve a token and save it in the keychain data for this account
func getToken(_ handler: @escaping (NSError?) -> Void) {
if isFetchingAuth {
log("already fetching auth, waiting...")
authFetchGroup.notify(queue: DispatchQueue.main) {
handler(nil)
}
return
}
guard let authKey = getAuthKey(), let authPubKey = authKey.publicKey else {
return handler(NSError(domain: BRAPIClientErrorDomain, code: 500, userInfo: [
NSLocalizedDescriptionKey: NSLocalizedString("Wallet not ready", comment: "")]))
}
isFetchingAuth = true
log("auth: entering group")
authFetchGroup.enter()
var req = URLRequest(url: url("/token"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
let reqJson = [
"pubKey": (authPubKey as NSData).base58String(),
"deviceID": getDeviceId()
]
do {
let dat = try JSONSerialization.data(withJSONObject: reqJson, options: [])
req.httpBody = dat
} catch let e {
log("JSON Serialization error \(e)")
isFetchingAuth = false
authFetchGroup.leave()
return handler(NSError(domain: BRAPIClientErrorDomain, code: 500, userInfo: [
NSLocalizedDescriptionKey: NSLocalizedString("JSON Serialization Error", comment: "")]))
}
session.dataTask(with: req, completionHandler: { (data, resp, err) in
DispatchQueue.main.async {
if let httpResp = resp as? HTTPURLResponse {
// unsuccessful response from the server
if httpResp.statusCode != 200 {
if let data = data, let s = String(data: data, encoding: String.Encoding.utf8) {
self.log("Token error: \(s)")
}
self.isFetchingAuth = false
self.authFetchGroup.leave()
return handler(NSError(domain: BRAPIClientErrorDomain, code: httpResp.statusCode, userInfo: [
NSLocalizedDescriptionKey: NSLocalizedString("Unable to retrieve API token", comment: "")]))
}
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.log("POST /token json response: \(json)")
if let topObj = json as? NSDictionary,
let tok = topObj["token"] as? NSString,
let uid = topObj["userID"] as? NSString,
let walletManager = BRWalletManager.sharedInstance() {
// success! store it in the keychain
let kcData = ["token": tok, "userID": uid]
walletManager.userAccount = kcData
}
} catch let e {
self.log("JSON Deserialization error \(e)")
}
}
self.isFetchingAuth = false
self.authFetchGroup.leave()
handler(err as NSError?)
}
}) .resume()
}
// MARK: URLSession Delegate
public func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if (challenge.protectionSpace.host == host && challenge.protectionSpace.serverTrust != nil) {
log("URLSession challenge accepted!")
completionHandler(.useCredential,
URLCredential(trust: challenge.protectionSpace.serverTrust!))
} else {
log("URLSession challenge rejected")
completionHandler(.rejectProtectionSpace, nil)
}
}
}
// disable following redirect
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
var actualRequest = request
if let currentReq = task.currentRequest, var curHost = currentReq.url?.host, let curScheme = currentReq.url?.scheme {
if let curPort = currentReq.url?.port, curPort != 443 && curPort != 80 {
curHost = "\(curHost):\(curPort)"
}
if curHost == host && curScheme == proto {
// follow the redirect if we're interacting with our API
actualRequest = decorateRequest(request)
log("redirecting \(String(describing: currentReq.url)) to \(String(describing: request.url))")
if let curAuth = currentReq.allHTTPHeaderFields?["Authorization"], curAuth.hasPrefix("bread") {
// add authentication because the previous request was authenticated
log("adding authentication to redirected request")
actualRequest = signRequest(actualRequest)
}
return completionHandler(actualRequest)
}
}
completionHandler(nil)
}
// MARK: API Functions
// Fetches the /v1/fee-per-kb endpoint
open func feePerKb(_ handler: @escaping (_ feePerKb: uint_fast64_t, _ error: String?) -> Void) {
let req = URLRequest(url: url("/fee-per-kb"))
let task = self.dataTaskWithRequest(req) { (data, response, err) -> Void in
var feePerKb: uint_fast64_t = 0
var errStr: String? = nil
if err == nil {
do {
let parsedObject: Any? = try JSONSerialization.jsonObject(
with: data!, options: JSONSerialization.ReadingOptions.allowFragments)
if let top = parsedObject as? NSDictionary, let n = top["fee_per_kb"] as? NSNumber {
feePerKb = n.uint64Value
}
} catch (let e) {
self.log("fee-per-kb: error parsing json \(e)")
}
if feePerKb == 0 {
errStr = "invalid json"
}
} else {
self.log("fee-per-kb network error: \(String(describing: err))")
errStr = "bad network connection"
}
handler(feePerKb, errStr)
}
task.resume()
}
// MARK: push notifications
open func savePushNotificationToken(_ token: Data, pushNotificationType: String = "d") {
var req = URLRequest(url: url("/me/push-devices"))
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
let reqJson = [
"token": token.hexString,
"service": "apns",
"data": ["e": pushNotificationType]
] as [String : Any]
do {
let dat = try JSONSerialization.data(withJSONObject: reqJson, options: .prettyPrinted)
req.httpBody = dat
} catch (let e) {
log("JSON Serialization error \(e)")
return //handler(NSError(domain: BRAPIClientErrorDomain, code: 500, userInfo: [
//NSLocalizedDescriptionKey: NSLocalizedString("JSON Serialization Error", comment: "")]))
}
dataTaskWithRequest(req as URLRequest, authenticated: true, retryCount: 0) { (dat, resp, er) in
let dat2 = NSString(data: (dat != nil ? dat! : Data()), encoding: String.Encoding.utf8.rawValue)
self.log("token resp: \(String(describing: resp)) data: \(String(describing: dat2))")
}.resume()
}
// MARK: feature flags API
open func defaultsKeyForFeatureFlag(_ name: String) -> String {
return "ff:\(name)"
}
open func updateFeatureFlags(onComplete: @escaping () -> Void) {
let req = URLRequest(url: url("/me/features"))
dataTaskWithRequest(req, authenticated: true) { (data, resp, err) in
if let resp = resp, let data = data {
let jsonString = String(data: data, encoding: .utf8)
self.log("got features data = \(String(describing: jsonString))")
if resp.statusCode == 200 {
let defaults = UserDefaults.standard
do {
let j = try JSONSerialization.jsonObject(with: data, options: [])
let features = j as! [[String: AnyObject]]
for feat in features {
if let fn = feat["name"], let fname = fn as? String,
let fe = feat["enabled"], let fenabled = fe as? Bool {
self.log("feature \(fname) enabled: \(fenabled)")
defaults.set(fenabled, forKey: self.defaultsKeyForFeatureFlag(fname))
} else {
self.log("malformed feature: \(feat)")
}
}
} catch let e {
self.log("error loading features json: \(e)")
}
}
} else {
self.log("error fetching features: \(String(describing: err))")
}
onComplete()
}.resume()
}
open func featureEnabled(_ flag: BRFeatureFlags) -> Bool {
#if Testflight || Debug
return true
#else
let defaults = UserDefaults.standard
return defaults.bool(forKey: defaultsKeyForFeatureFlag(flag.description))
#endif
}
// MARK: key value access
fileprivate class KVStoreAdaptor: BRRemoteKVStoreAdaptor {
let client: BRAPIClient
init(client: BRAPIClient) {
self.client = client
}
func ver(key: String, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) {
var req = URLRequest(url: client.url("/kv/1/\(key)"))
req.httpMethod = "HEAD"
client.dataTaskWithRequest(req, authenticated: true, retryCount: 0) { (dat, resp, err) in
if let err = err {
self.client.log("[KV] HEAD key=\(key) err=\(err)")
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
guard let resp = resp, let v = self._extractVersion(resp), let d = self._extractDate(resp) else {
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
completionFunc(v, d, self._extractErr(resp))
}.resume()
}
func put(_ key: String, value: [UInt8], version: UInt64,
completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) {
var req = URLRequest(url: client.url("/kv/1/\(key)"))
req.httpMethod = "PUT"
req.addValue("\(version)", forHTTPHeaderField: "If-None-Match")
req.addValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
req.addValue("\(value.count)", forHTTPHeaderField: "Content-Length")
var val = value
req.httpBody = Data(bytes: &val, count: value.count)
client.dataTaskWithRequest(req, authenticated: true, retryCount: 0) { (dat, resp, err) in
if let err = err {
self.client.log("[KV] PUT key=\(key) err=\(err)")
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
guard let resp = resp, let v = self._extractVersion(resp), let d = self._extractDate(resp) else {
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
completionFunc(v, d, self._extractErr(resp))
}.resume()
}
func del(_ key: String, version: UInt64,
completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> ()) {
var req = URLRequest(url: client.url("/kv/1/\(key)"))
req.httpMethod = "DELETE"
req.addValue("\(version)", forHTTPHeaderField: "If-None-Match")
client.dataTaskWithRequest(req, authenticated: true, retryCount: 0) { (dat, resp, err) in
if let err = err {
self.client.log("[KV] DELETE key=\(key) err=\(err)")
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
guard let resp = resp, let v = self._extractVersion(resp), let d = self._extractDate(resp) else {
return completionFunc(0, Date(timeIntervalSince1970: 0), .unknown)
}
completionFunc(v, d, self._extractErr(resp))
}.resume()
}
func get(_ key: String, version: UInt64,
completionFunc: @escaping (UInt64, Date, [UInt8], BRRemoteKVStoreError?) -> ()) {
var req = URLRequest(url: client.url("/kv/1/\(key)"))
req.httpMethod = "GET"
req.addValue("\(version)", forHTTPHeaderField: "If-None-Match")
client.dataTaskWithRequest(req as URLRequest, authenticated: true, retryCount: 0) { (dat, resp, err) in
if let err = err {
self.client.log("[KV] GET key=\(key) err=\(err)")
return completionFunc(0, Date(timeIntervalSince1970: 0), [], .unknown)
}
guard let resp = resp, let v = self._extractVersion(resp),
let d = self._extractDate(resp), let dat = dat else {
return completionFunc(0, Date(timeIntervalSince1970: 0), [], .unknown)
}
let ud = (dat as NSData).bytes.bindMemory(to: UInt8.self, capacity: dat.count)
let dp = UnsafeBufferPointer<UInt8>(start: ud, count: dat.count)
completionFunc(v, d, Array(dp), self._extractErr(resp))
}.resume()
}
func keys(_ completionFunc:
@escaping ([(String, UInt64, Date, BRRemoteKVStoreError?)], BRRemoteKVStoreError?) -> ()) {
var req = URLRequest(url: client.url("/kv/_all_keys"))
req.httpMethod = "GET"
client.dataTaskWithRequest(req as URLRequest, authenticated: true, retryCount: 0) { (dat, resp, err) in
if let err = err {
self.client.log("[KV] KEYS err=\(err)")
return completionFunc([], .unknown)
}
guard let resp = resp, let dat = dat , resp.statusCode == 200 else {
return completionFunc([], .unknown)
}
// data is encoded as:
// LE32(num) + (num * (LEU8(keyLeng) + (keyLen * LEU32(char)) + LEU64(ver) + LEU64(msTs) + LEU8(del)))
var i = UInt(MemoryLayout<UInt32>.size)
let c = (dat as NSData).uInt32(atOffset: 0)
var items = [(String, UInt64, Date, BRRemoteKVStoreError?)]()
for _ in 0..<c {
let keyLen = UInt((dat as NSData).uInt32(atOffset: i))
i += UInt(MemoryLayout<UInt32>.size)
let range: Range<Int> = Int(i)..<Int(i + keyLen)
guard let key = NSString(data: dat.subdata(in: range),
encoding: String.Encoding.utf8.rawValue) as String? else {
self.client.log("Well crap. Failed to decode a string.")
return completionFunc([], .unknown)
}
i += keyLen
let ver = (dat as NSData).uInt64(atOffset: i)
i += UInt(MemoryLayout<UInt64>.size)
let date = Date.withMsTimestamp((dat as NSData).uInt64(atOffset: i))
i += UInt(MemoryLayout<UInt64>.size)
let deleted = (dat as NSData).uInt8(atOffset: i) > 0
i += UInt(MemoryLayout<UInt8>.size)
items.append((key, ver, date, deleted ? .tombstone : nil))
self.client.log("keys: \(key) \(ver) \(date) \(deleted)")
}
completionFunc(items, nil)
}.resume()
}
func _extractDate(_ r: HTTPURLResponse) -> Date? {
if let remDate = r.allHeaderFields["Last-Modified"] as? String, let dateDate = Date.fromRFC1123(remDate) {
return dateDate
}
return nil
}
func _extractVersion(_ r: HTTPURLResponse) -> UInt64? {
if let remVer = r.allHeaderFields["Etag"] as? String, let verInt = UInt64(remVer) {
return verInt
}
return nil
}
func _extractErr(_ r: HTTPURLResponse) -> BRRemoteKVStoreError? {
switch r.statusCode {
case 404:
return .notFound
case 409:
return .conflict
case 410:
return .tombstone
case 200...399:
return nil
default:
return .unknown
}
}
}
fileprivate var _kvStore: BRReplicatedKVStore? = nil
open var kv: BRReplicatedKVStore? {
get {
if let k = _kvStore {
return k
}
if let key = getAuthKey() {
_kvStore = try? BRReplicatedKVStore(encryptionKey: key, remoteAdaptor: KVStoreAdaptor(client: self))
return _kvStore
}
return nil
}
}
// MARK: Assets API
open class func bundleURL(_ bundleName: String) -> URL {
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let bundleDirUrl = docsUrl.appendingPathComponent("bundles", isDirectory: true)
let bundleUrl = bundleDirUrl.appendingPathComponent("\(bundleName)-extracted", isDirectory: true)
return bundleUrl
}
open func updateBundle(_ bundleName: String, handler: @escaping (_ error: String?) -> Void) {
// 1. check if we already have a bundle given the name
// 2. if we already have it:
// 2a. get the sha256 of the on-disk bundle
// 2b. request the versions of the bundle from server
// 2c. request the diff between what we have and the newest one, if ours is not already the newest
// 2d. apply the diff and extract to the bundle folder
// 3. otherwise:
// 3a. download and extract the bundle
// set up the environment
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let bundleDirUrl = docsUrl.appendingPathComponent("bundles", isDirectory: true)
let bundleUrl = bundleDirUrl.appendingPathComponent("\(bundleName).tar")
let bundleDirPath = bundleDirUrl.path
let bundlePath = bundleUrl.path
let bundleExtractedUrl = bundleDirUrl.appendingPathComponent("\(bundleName)-extracted")
let bundleExtractedPath = bundleExtractedUrl.path
print("[BRAPIClient] bundleUrl \(bundlePath)")
// determines if the bundle exists, but also creates the bundles/extracted directory if it doesn't exist
func exists() throws -> Bool {
var attrs = try? fm.attributesOfItem(atPath: bundleDirPath)
if attrs == nil {
try fm.createDirectory(atPath: bundleDirPath, withIntermediateDirectories: true, attributes: nil)
attrs = try fm.attributesOfItem(atPath: bundleDirPath)
}
var attrsExt = try? fm.attributesOfFileSystem(forPath: bundleExtractedPath)
if attrsExt == nil {
try fm.createDirectory(atPath: bundleExtractedPath, withIntermediateDirectories: true, attributes: nil)
attrsExt = try fm.attributesOfItem(atPath: bundleExtractedPath)
}
return fm.fileExists(atPath: bundlePath)
}
// extracts the bundle
func extract() throws {
try BRTar.createFilesAndDirectoriesAtPath(bundleExtractedPath, withTarPath: bundlePath)
}
guard var bundleExists = try? exists() else {
return handler(NSLocalizedString("error determining if bundle exists", comment: "")) }
// attempt to use the tar file that was bundled with the binary
if !bundleExists {
if let bundledBundleUrl = Bundle.main.url(forResource: bundleName, withExtension: "tar") {
do {
try fm.copyItem(at: bundledBundleUrl, to: bundleUrl)
bundleExists = true
log("used bundled bundle for \(bundleName)")
} catch let e {
log("unable to copy bundled bundle `\(bundleName)` \(bundledBundleUrl) -> \(bundleUrl): \(e)")
}
}
}
if bundleExists {
// bundle exists, download and apply the diff, then remove diff file
log("bundle \(bundleName) exists, fetching diff for most recent version")
guard let curBundleContents = try? Data(contentsOf: URL(fileURLWithPath: bundlePath)) else {
return handler(NSLocalizedString("error reading current bundle", comment: "")) }
let curBundleSha = (NSData(uInt256: (curBundleContents as NSData).sha256()) as Data).hexString
dataTaskWithRequest(URLRequest(url: url("/assets/bundles/\(bundleName)/versions")))
{ (data, resp, err) -> Void in
if let data = data,
let parsed = try? JSONSerialization.jsonObject(with: data, options: .allowFragments),
let top = parsed as? NSDictionary,
let versions = top["versions"] as? [String]
, err == nil {
if versions.index(of: curBundleSha) == (versions.count - 1) {
// have the most recent version
self.log("already at most recent version of bundle \(bundleName)")
do {
try extract()
return handler(nil)
} catch let e {
return handler(NSLocalizedString("error extracting bundle: " + "\(e)", comment: ""))
}
} else { // don't have the most recent version, download diff
self.log("Fetching most recent version of bundle \(bundleName)")
let req = URLRequest(url:
self.url("/assets/bundles/\(bundleName)/diff/\(curBundleSha)"))
self.dataTaskWithRequest(req, handler: { (diffDat, diffResp, diffErr) -> Void in
if let diffDat = diffDat , diffErr == nil {
let diffPath = bundleDirUrl.appendingPathComponent("\(bundleName).diff").path
let oldBundlePath = bundleDirUrl.appendingPathComponent("\(bundleName).old").path
do {
if fm.fileExists(atPath: diffPath) {
try fm.removeItem(atPath: diffPath)
}
if fm.fileExists(atPath: oldBundlePath) {
try fm.removeItem(atPath: oldBundlePath)
}
try diffDat.write(to: URL(fileURLWithPath: diffPath), options: .atomic)
try fm.moveItem(atPath: bundlePath, toPath: oldBundlePath)
_ = try BRBSPatch.patch(
oldBundlePath, newFilePath: bundlePath, patchFilePath: diffPath)
try fm.removeItem(atPath: diffPath)
try fm.removeItem(atPath: oldBundlePath)
try extract()
return handler(nil)
} catch let e {
// something failed, clean up whatever we can, next attempt
// will download fresh
_ = try? fm.removeItem(atPath: diffPath)
_ = try? fm.removeItem(atPath: oldBundlePath)
_ = try? fm.removeItem(atPath: bundlePath)
return handler(
NSLocalizedString("error downloading diff: " + "\(e)", comment: ""))
}
}
}).resume()
}
}
else {
return handler(NSLocalizedString("error determining versions", comment: ""))
}
}.resume()
} else {
// bundle doesn't exist. download a fresh copy
log("bundle \(bundleName) doesn't exist, downloading new copy")
let req = URLRequest(url: url("/assets/bundles/\(bundleName)/download"))
dataTaskWithRequest(req) { (data, response, err) -> Void in
if err != nil || response?.statusCode != 200 {
return handler(NSLocalizedString("error fetching bundle: ", comment: "") + "\(String(describing: err))")
}
if let data = data {
do {
try data.write(to: URL(fileURLWithPath: bundlePath), options: .atomic)
try extract()
return handler(nil)
} catch let e {
return handler(NSLocalizedString("error writing bundle file: ", comment: "") + "\(e)")
}
}
}.resume()
}
}
}
| mit | 7e5509e0ae1e8a885442ab6614e5a97b | 46.054245 | 215 | 0.539447 | 5.142673 | false | false | false | false |
aleph7/PlotKit | PlotKit/Model/TickMark.swift | 1 | 813 | // Copyright © 2015 Venture Media Labs. All rights reserved.
//
// This file is part of PlotKit. The full PlotKit copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
import Foundation
public struct TickMark {
public var value: Double
public var label: String
public var lineWidth = CGFloat(1.0)
public var lineLength = CGFloat(5.0)
public init(_ value: Double) {
self.value = value
label = String(format: "%.5g", arguments: [value])
}
public init(_ value: Int) {
self.value = Double(value)
label = "\(value)"
}
public init(_ value: Double, label: String) {
self.value = value
self.label = label
}
}
| mit | cb08c32d9fdb707a108a233d8bb92d5b | 27 | 77 | 0.649015 | 4.164103 | false | false | false | false |
amco/couchbase-lite-ios | Swift/PredicateQuery.swift | 1 | 6995 | //
// PredicateQuery.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// A compiled database query, similar to a N1QL or SQL query.
public class PredicateQuery {
/// Creates a database query from the component pieces of a SELECT statement, all of
/// which are optional except FROM.
///
/// - Parameters:
/// - db: The database.
/// - wherePredicate: The where predicate.
/// - groupBy: The groupby expressions.
/// - having: THe having predicate.
/// - returning: The returning values.
/// - distinct: The distinct flag.
/// - orderBy: The order by as an array of the SortDescriptor objects.
public init(from db: Database,
where wherePredicate: Predicate? = nil,
groupBy: [PredicateExpression]? = nil,
having: Predicate? = nil,
returning: [PredicateExpression]? = nil,
distinct: Bool = false,
orderBy: [SortDescriptor]? = nil)
{
database = db
_impl = db._impl.createQueryWhere(wherePredicate)
_impl.distinct = distinct
_impl.orderBy = orderBy
_impl.groupBy = groupBy
_impl.having = having
_impl.returning = returning
}
/// The database being queried.
public let database: Database
/// The number of result rows to skip; corresponds to the OFFSET property of a SQL or N1QL query.
/// This can be useful for "paging" through a large query, but skipping many rows is slow.
/// Defaults to 0.
public var offset: UInt = 0
/// The maximum number of rows to return; corresponds to the LIMIT property of a SQL or N1QL query.
/// Defaults to unlimited.
public var limit: UInt = UInt.max
/// Values to substitute for placeholder parameters defined in the query. Defaults to nil.
/// The dictionary's keys are parameter names, and values are the values to use.
/// All parameters must be given values before running the query, or it will fail.
public var parameters: [String : Any] = [:]
/// Checks whether the query is valid without running it.
///
/// - Throws: An error if the query is not valid.
public func check() throws {
try _impl.check()
}
/// Returns a string describing the implementation of the compiled query.
/// This is intended to be read by a developer for purposes of optimizing the query, especially
/// to add database indexes. It's not machine-readable and its format may change.
///
/// As currently implemented, the result is two or more lines separated by newline characters:
/// * The first line is the SQLite SELECT statement.
/// * The subsequent lines are the output of SQLite's "EXPLAIN QUERY PLAN" command applied to that
/// statement; for help interpreting this, see https://www.sqlite.org/eqp.html . The most
/// important thing to know is that if you see "SCAN TABLE", it means that SQLite is doing a
/// slow linear scan of the documents instead of using an index.
///
/// - Returns: The compilied query description.
/// - Throws: An error if the query is not valid.
public func explain() throws -> String {
return try _impl.explain()
}
/// Runs the query, using the current settings (skip, limit, parameters), returning an enumerator
/// that returns result rows one at a time.
/// You can run the query any number of times, and you can even have multiple enumerators active at
/// once.
/// The results come from a snapshot of the database taken at the moment -run: is called, so they
/// will not reflect any changes made to the database afterwards.
///
/// - Returns: The QueryIterator object.
/// - Throws: An error on a failure.
public func run() throws -> QueryIterator {
_impl.offset = offset
_impl.limit = limit
_impl.parameters = parameters
return try QueryIterator(database: database, enumerator: _impl.run())
}
/// A convenience method equivalent to -run: except that its enumerator returns Documents
/// directly, not QueryRows.
///
/// - Returns: The DocumentIterator.
/// - Throws: An error on a failure.
public func allDocuments() throws -> DocumentIterator {
return try DocumentIterator(database: database, enumerator: _impl.allDocuments())
}
private let _impl: CBLPredicateQuery
}
/// Either NSPredicates or Strings can be used for a Query's "where" and "having" clauses.
public protocol Predicate { }
extension NSPredicate : Predicate { }
extension String : Predicate { }
/// Either NSExpressions or Strings can be used for a Query's "groupBy" and "returning" clauses.
public protocol PredicateExpression { }
extension NSExpression : PredicateExpression { }
extension String : PredicateExpression { }
/// NSExpressions, NSSortDescriptors, or Strings can be used for a Query's "orderBy" clause.
public protocol SortDescriptor { }
extension NSExpression : SortDescriptor { }
extension NSSortDescriptor : SortDescriptor { }
extension String : SortDescriptor { }
/// An iterator of Documents in a Database,
/// returned by Database.allDocuments or Query.allDocuments.
public struct DocumentIterator : Sequence, IteratorProtocol {
public typealias Element = MutableDocument
public mutating func next() -> MutableDocument? {
if let doc = _enumerator.nextObject() as? CBLMutableDocument {
return MutableDocument(doc)
} else {
return nil
}
}
init(database: Database, enumerator: NSEnumerator) {
_database = database
_enumerator = enumerator
}
let _database: Database
let _enumerator: NSEnumerator
}
/// The iterator that returns successive rows from a Query.
public struct QueryIterator : Sequence, IteratorProtocol {
public typealias Element = QueryRow
public mutating func next() -> QueryRow? {
let obj = enumerator.nextObject()
if let row = obj as? CBLQueryRow {
return FullTextQueryRow(impl: row, database: database)
} else if let row = obj as? CBLFullTextQueryRow {
return QueryRow(impl: row, database: database)
} else {
return nil
}
}
let database: Database
let enumerator: NSEnumerator
}
| apache-2.0 | 5888f12d576576cd38975ff8e5ef7aac | 34.507614 | 103 | 0.66619 | 4.626323 | false | false | false | false |
mikehuffaker/udacity-ios-meme-me-2.0 | MemeMe-2_0/MemeTextDelegate.swift | 1 | 866 | //
// MemeTxtDelegate.swift
// MemeMe-2_0
//
// Created by Mike Huffaker on 1/30/17.
// Copyright © 2016 Mike Huffaker. All rights reserved.
//
import Foundation
import UIKit
class MemeTxtDelegate : NSObject, UITextFieldDelegate
{
func textFieldDidBeginEditing(_ textField: UITextField)
{
print( "MemeTxtFieldDelegate::textFieldDidBeginEditing()" )
// Only if the text field has is initial value, then null
// out when the user starts editing
if textField.text == "TOP" || textField.text == "BOTTOM"
{
textField.text = ""
}
return
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool
{
print( "MemeTxtFieldDelegate::textFieldShouldReturn()")
textField.resignFirstResponder()
return true;
}
}
| mit | 2092ccaf987a94bdc24c14929780671e | 23.027778 | 67 | 0.611561 | 4.752747 | false | false | false | false |
nbkey/DouYuTV | DouYu/DouYu/Classes/Home/View/CollectionItemCell.swift | 1 | 1060 | //
// CollectionItemCell.swift
// DouYu
//
// Created by 吉冠坤 on 2017/7/29.
// Copyright © 2017年 吉冠坤. All rights reserved.
//
import UIKit
class CollectionItemCell: UICollectionViewCell {
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var titileLabel: UILabel!
var index :Int? {
didSet {
guard let index = index else {return}
// Initialization code
iconImageView.image = UIImage(named: iconImageNames[index])
//homeNewItem_Activity homeNewItem_allLive homeNewItem_msg homeNewItem_rankingList
titileLabel.text = titleNames[index]
}
}
private lazy var iconImageNames :[String] = {
let iconImageNames = ["homeNewItem_rankingList", "homeNewItem_msg", "homeNewItem_Activity", "homeNewItem_allLive"]
return iconImageNames
}()
var titleNames :[String] = {
return ["排行榜", "消息", "活动", "全部直播"]
}()
override func awakeFromNib() {
super.awakeFromNib()
}
}
| mit | 0ab3194fe911d1cd95b9826202c46d01 | 28.228571 | 122 | 0.630499 | 4.027559 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Scene/TextRenderer.swift | 1 | 14601 | //
// TextRenderer.swift
// CesiumKit
//
// Created by Ryan Walklin on 26/02/2016.
// Copyright © 2016 Test Toast. All rights reserved.
//
import Foundation
import simd
private struct TextUniformStruct: UniformStruct {
var modelMatrix: float4x4 = Matrix4.identity.floatRepresentation
var viewProjectionMatrix: float4x4 = Matrix4.identity.floatRepresentation
var foregroundColor: float4 = Color().floatRepresentation
}
class TextUniformMap: NativeUniformMap {
//FIXME: color etc here
var modelMatrix: Matrix4 {
get {
return Matrix4(simd: double4x4([
simd_double(_uniformStruct.modelMatrix[0]),
simd_double(_uniformStruct.modelMatrix[1]),
simd_double(_uniformStruct.modelMatrix[2]),
simd_double(_uniformStruct.modelMatrix[3])
]))
}
set {
_uniformStruct.modelMatrix = newValue.floatRepresentation
}
}
var viewProjectionMatrix: Matrix4 {
get {
return Matrix4(simd: double4x4([
simd_double(_uniformStruct.viewProjectionMatrix[0]),
simd_double(_uniformStruct.viewProjectionMatrix[1]),
simd_double(_uniformStruct.viewProjectionMatrix[2]),
simd_double(_uniformStruct.viewProjectionMatrix[3])
]))
}
set {
_uniformStruct.viewProjectionMatrix = newValue.floatRepresentation
}
}
var foregroundColor: Color {
get {
return Color(simd: simd_double(_uniformStruct.foregroundColor))
}
set {
_uniformStruct.foregroundColor = newValue.floatRepresentation
}
}
var uniformBufferProvider: UniformBufferProvider! = nil
fileprivate var _fontAtlasTexture: Texture! = nil
fileprivate var _uniformStruct = TextUniformStruct()
// compiled shader doesn't need to generate struct at runtime
let uniformDescriptors: [UniformDescriptor] = []
lazy var uniformUpdateBlock: UniformUpdateBlock = { buffer in
buffer.write(from: &self._uniformStruct, length: MemoryLayout<TextUniformStruct>.size)
return [self._fontAtlasTexture!]
}
}
/**
* Generates a DrawCommand and VerteArray for the required glyphs of the provided String using
* a FontAtlas. Based on Objective-C code from [Moore (2015)](http://metalbyexample.com/rendering-text-in-metal-with-signed-distance-fields/).
*/
open class TextRenderer: Primitive {
open var color: Color
open var string: String {
didSet {
_updateMesh = true
}
}
open var viewportRect: Cartesian4 {
didSet {
_updateMetrics = true
}
}
open var pointSize: Int {
didSet {
_updateMesh = true
}
}
fileprivate var _updateMesh: Bool = true
fileprivate var _updateMetrics: Bool = false
open fileprivate (set) var meshSize: Cartesian2 = Cartesian2()
fileprivate let _command = DrawCommand()
fileprivate var _fontAtlas: FontAtlas! = nil
let fontName: String
//private var _rs: RenderState! = nil
fileprivate let _offscreenTarget: Bool
fileprivate let _blendingState: BlendingState
fileprivate let _attributes = [
// attribute vec4 position;
VertexAttributes(
buffer: nil,
bufferIndex: VertexDescriptorFirstBufferOffset,
index: 0,
format: .float4,
offset: 0,
size: 16,
normalize: false),
// attribute vec2 textureCoordinates;
VertexAttributes(
buffer: nil,
bufferIndex: VertexDescriptorFirstBufferOffset,
index: 1,
format: .float2,
offset: 16,
size: 8,
normalize: false)
]
public init (string: String, fontName: String, color: Color, pointSize: Int, viewportRect: Cartesian4, offscreenTarget: Bool = false) {
self.string = string
self.fontName = fontName
self.color = color
self.pointSize = pointSize
self.viewportRect = viewportRect
_offscreenTarget = offscreenTarget
_blendingState = BlendingState(
enabled: true,
equationRgb: .add,
equationAlpha: .add,
functionSourceRgb: .sourceAlpha,
functionSourceAlpha: .sourceAlpha,
functionDestinationRgb: .oneMinusSourceAlpha,
functionDestinationAlpha: .oneMinusSourceAlpha,
color: nil
)
_command.pass = .overlayText
_command.uniformMap = TextUniformMap()
super.init()
let meshCGSize = computeSize()
meshSize = Cartesian2(x: Double(meshCGSize.width), y: Double(meshCGSize.height))
_command.owner = self
}
override func update (_ frameState: inout FrameState) {
guard let context = frameState.context else {
return
}
if _fontAtlas == nil {
_fontAtlas = FontAtlas.fromCache(context, fontName: fontName, pointSize: pointSize)
}
guard let map = _command.uniformMap as? TextUniformMap else {
return
}
if !show || !_fontAtlas.ready || string == "" {
return
}
map._fontAtlasTexture = _fontAtlas.texture
if _command.pipeline == nil {
_command.pipeline = RenderPipeline.withCompiledShader(
context,
shaderSourceName: "TextRenderer",
compiledMetalVertexName: "text_vertex_shade",
compiledMetalFragmentName: "text_fragment_shade",
uniformStructSize: MemoryLayout<TextUniformStruct>.stride,
vertexDescriptor: VertexDescriptor(attributes: _attributes),
depthStencil: _offscreenTarget ? false : context.depthTexture,
blendingState: _blendingState
)
map.uniformBufferProvider = _command.pipeline!.shaderProgram.createUniformBufferProvider(context.device, deallocationBlock: nil)
}
if _command.renderState == nil || _updateMesh {
_updateMetrics = true
let meshCGSize = computeSize()
meshSize = Cartesian2(x: Double(meshCGSize.width), y: Double(meshCGSize.height))
let meshRect = CGRect(x: 0, y: 0, width: meshCGSize.width, height: meshCGSize.height)
_command.vertexArray = buildMesh(context, string: string, inRect: meshRect, withFontAtlas: _fontAtlas, atSize: Int(Double(pointSize)))
_updateMesh = false
}
if _updateMetrics {
map.viewProjectionMatrix = Matrix4.computeOrthographicOffCenter(left: 0, right: viewportRect.width, bottom: 0, top: viewportRect.height)
_command.renderState = RenderState(
device: context.device,
viewport: viewportRect
)
_updateMetrics = false
}
map.foregroundColor = color
frameState.commandList.append(_command)
}
open func computeSize (constrainingTo width: Double? = nil) -> CGSize {
let constrainedWidth = width ?? viewportRect.width
let attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0)
CFAttributedStringReplaceString(attrString, CFRangeMake(0, 0), string as CFString!)
let font = CTFontCreateWithName(fontName as CFString, CGFloat(pointSize), nil)
let stringRange = CFRangeMake(0, CFAttributedStringGetLength(attrString))
CFAttributedStringSetAttribute(attrString, stringRange, kCTFontAttributeName, font)
let framesetter = CTFramesetterCreateWithAttributedString(attrString!)
var fitRange = CFRangeMake(0, 0)
let textSize = CTFramesetterSuggestFrameSizeWithConstraints(framesetter, CFRangeMake(0, 0), nil, CGSize(width: CGFloat(constrainedWidth), height: CGFloat.greatestFiniteMagnitude), &fitRange)
assert(stringRange == fitRange, "Core Text layout failed")
return textSize
}
fileprivate func buildMesh (_ context: Context, string: String, inRect rect: CGRect, withFontAtlas fontAtlas: FontAtlas, atSize size: Int) -> VertexArray?
{
let attrString = NSMutableAttributedString(string: string)
let stringRange = CFRangeMake(0, attrString.length)
let font = CTFontCreateCopyWithAttributes(fontAtlas.parentFont, CGFloat(size), nil, nil)
CFAttributedStringSetAttribute(attrString, stringRange, kCTFontAttributeName, font)
let rectPath = CGPath(rect: rect, transform: nil)
let framesetter = CTFramesetterCreateWithAttributedString(attrString)
let frame = CTFramesetterCreateFrame(framesetter, stringRange, rectPath, nil)
let frameGlyphCount: CFIndex = ((CTFrameGetLines(frame) as NSArray) as! [CTLine]).reduce(0, { $0 + CTLineGetGlyphCount($1) })
let vertexCount = frameGlyphCount * 4
var vertices = [Float]()
var indices = [Int]()
let glyphEnumeratorBlock = { (glyph: CGGlyph, glyphIndex: Int, glyphBounds: CGRect) -> Bool in
guard let glyphInfo = fontAtlas.glyphDescriptors[Int(glyph)] else {
logPrint(.debug, "Font atlas has no entry corresponding to glyph \(glyph): Skipping...")
return false
}
let minX = Float(glyphBounds.minX)
let maxX = Float(glyphBounds.maxX)
let minY = Float(glyphBounds.minY)
let maxY = Float(glyphBounds.maxY)
let minS = Float(glyphInfo.topLeft.x)
let maxS = Float(glyphInfo.bottomRight.x)
let minT = Float(glyphInfo.bottomRight.y)
let maxT = Float(glyphInfo.topLeft.y)
vertices.append(contentsOf: [minX, maxY, 0, 1, minS, maxT])
vertices.append(contentsOf: [minX, minY, 0, 1, minS, minT])
vertices.append(contentsOf: [maxX, minY, 0, 1, maxS, minT])
vertices.append(contentsOf: [maxX, maxY, 0, 1, maxS, maxT])
indices.append(glyphIndex * 4)
indices.append(glyphIndex * 4 + 1)
indices.append(glyphIndex * 4 + 2)
indices.append(glyphIndex * 4 + 2)
indices.append(glyphIndex * 4 + 3)
indices.append(glyphIndex * 4)
return true
}
enumerateGlyphsInFrame(frame, usingBlock: glyphEnumeratorBlock)
guard let vertexBuffer = Buffer(device: context.device, array: &vertices, componentDatatype: .float32, sizeInBytes: vertices.sizeInBytes) else {
logPrint(.critical, "Cannot create Buffer")
return nil
}
vertexBuffer.metalBuffer.label = "Text Mesh Vertices"
let indexBuffer: Buffer
if indices.count < Math.SixtyFourKilobytes {
let indicesShort = indices.map { UInt16($0) }
guard let shortBuffer = Buffer(
device: context.device,
array: indicesShort,
componentDatatype: ComponentDatatype.unsignedShort,
sizeInBytes: indicesShort.sizeInBytes) else {
logPrint(.critical, "Cannot create Buffer")
return nil
}
indexBuffer = shortBuffer
} else {
let indicesInt = indices.map({ UInt32($0) })
guard let longBuffer = Buffer(
device: context.device,
array: indicesInt,
componentDatatype: ComponentDatatype.unsignedInt,
sizeInBytes: indicesInt.sizeInBytes) else {
logPrint(.critical, "Cannot create Buffer")
return nil
}
indexBuffer = longBuffer
}
indexBuffer.metalBuffer.label = "Text Mesh Indices"
var attributes = _attributes
attributes[0].buffer = vertexBuffer
return VertexArray(attributes: attributes, vertexCount: vertexCount, indexBuffer: indexBuffer, indexCount: indices.count)
}
fileprivate func enumerateGlyphsInFrame (_ frame: CTFrame, usingBlock addGlyph: (_ glyph: CGGlyph, _ glyphIndex: Int, _ glyphBounds: CGRect) -> Bool) {
let entire = CFRangeMake(0, 0)
let framePath = CTFrameGetPath(frame)
let frameBoundingRect = framePath.boundingBoxOfPath
let lines = (CTFrameGetLines(frame) as NSArray) as! [CTLine]
var lineOriginBuffer = [CGPoint](repeating: CGPoint(), count: lines.count)
CTFrameGetLineOrigins(frame, entire, &lineOriginBuffer)
var glyphIndexInFrame: CFIndex = 0
for (lineIndex, line) in lines.enumerated() {
let lineOrigin = lineOriginBuffer[lineIndex]
let runs = (CTLineGetGlyphRuns(line) as NSArray) as! [CTRun]
for run in runs {
let glyphCount = CTRunGetGlyphCount(run)
var glyphBuffer = [CGGlyph](repeating: 0, count: glyphCount)
CTRunGetGlyphs(run, entire, &glyphBuffer);
var positionBuffer = [CGPoint](repeating: CGPoint(), count: glyphCount)
CTRunGetPositions(run, entire, &positionBuffer);
for glyphIndex in 0..<glyphCount {
let glyph = glyphBuffer[glyphIndex]
let glyphOrigin = positionBuffer[glyphIndex]
var glyphRect = CTRunGetImageBounds(run, nil, CFRangeMake(glyphIndex, 1))
let boundsTransX = frameBoundingRect.origin.x + lineOrigin.x
let boundsTransY = frameBoundingRect.origin.y + lineOrigin.y + glyphOrigin.y
let pathTransform = CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: boundsTransX, ty: boundsTransY)
glyphRect = glyphRect.applying(pathTransform)
let added = addGlyph(glyph, glyphIndexInFrame, glyphRect)
if added {
glyphIndexInFrame += 1
}
}
}
}
}
}
| apache-2.0 | 03becde9c833e3b2bebe96e4a9c2b9c4 | 37.120104 | 198 | 0.596164 | 4.981235 | false | false | false | false |
rudkx/swift | test/attr/attr_inlinable_available_maccatalyst.swift | 1 | 21650 | // This is the same test as attr_inlinable_available, but specifically using a
// macCatalyst target which has its own version floor separate from iOS. The two
// tests could be merged in the future if there were a CI bot running tests with
// OS=maccatalyst and there were a lit.py substitution for the -target argument
// that substituted to a macCatalyst SDK version compatible with the
// configuration of this test.
// REQUIRES: maccatalyst_support
// Primary execution of this test. Uses the default minimum inlining version,
// which is the version when Swift was introduced.
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version min
// Check that `-library-level api` implies `-target-min-inlining-version min`
// RUN: %target-typecheck-verify-swift -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -library-level api
// Check that these rules are only applied when requested and that at least some
// diagnostics are not present without it.
// RUN: not %target-typecheck-verify-swift -swift-version 5 -target %target-cpu-apple-ios14.4-macabi 2>&1 | %FileCheck --check-prefix NON_MIN %s
// Check that -target-min-inlining-version overrides -library-level, allowing
// library owners to disable this behavior for API libraries if needed.
// RUN: not %target-typecheck-verify-swift -swift-version 5 -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version target -library-level api 2>&1 | %FileCheck --check-prefix NON_MIN %s
// Check that we respect -target-min-inlining-version by cranking it up high
// enough to suppress any possible errors.
// RUN: %target-swift-frontend -typecheck -disable-objc-attr-requires-foundation-module %s -swift-version 5 -enable-library-evolution -target %target-cpu-apple-ios14.4-macabi -target-min-inlining-version 42.0
// NON_MIN: error: expected error not produced
// NON_MIN: {'BetweenTargets' is only available in}
/// Declaration with no availability annotation. Should be inferred as minimum
/// inlining target.
public struct NoAvailable {
@usableFromInline internal init() {}
}
@available(macCatalyst 12, *)
public struct BeforeInliningTarget {
@usableFromInline internal init() {}
}
@available(macCatalyst 13.1, *)
public struct AtInliningTarget {
@usableFromInline internal init() {}
}
@available(macCatalyst 14, *)
public struct BetweenTargets {
@usableFromInline internal init() {}
}
@available(macCatalyst 14.4, *)
public struct AtDeploymentTarget {
@usableFromInline internal init() {}
}
@available(macCatalyst 15, *)
public struct AfterDeploymentTarget {
@usableFromInline internal init() {}
}
//
// Uses in resilient functions are based on the minimum deployment target
// (i.e. the -target).
//
public func deployedUseNoAvailable( // expected-note 5 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 12, *)
public func deployedUseBeforeInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 13.1, *)
public func deployedUseAtInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 14, *)
public func deployedUseBetweenTargets(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 14.4, *)
public func deployedUseAtDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 15, *)
public func deployedUseAfterDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
//
// Uses in inlinable functions are based on the minimum inlining target
//
@inlinable public func inlinedUseNoAvailable( // expected-note 8 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14, *) {
_ = BetweenTargets()
}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 12, *)
@inlinable public func inlinedUseBeforeInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14, *) {
_ = BetweenTargets()
}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 13.1, *)
@inlinable public func inlinedUseAtInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14, *) {
_ = BetweenTargets()
}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 14, *)
@inlinable public func inlinedUseBetweenTargets(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 14.4, *)
@inlinable public func inlinedUseAtDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
@available(macCatalyst 15, *)
@inlinable public func inlinedUseAfterDeploymentTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets,
_: AtDeploymentTarget,
_: AfterDeploymentTarget
) {
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget()
}
//
// Edge cases.
//
// Internal functions should use the minimum deployment target.
internal func fn() {
_ = AtDeploymentTarget()
}
// @_alwaysEmitIntoClient acts like @inlinable.
@_alwaysEmitIntoClient public func aEICUseNoAvailable( // expected-note 8 {{add @available attribute}}
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14, *) {
_ = BetweenTargets()
}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
// @_backDeploy acts like @inlinable.
@available(macCatalyst 13.1, *)
@_backDeploy(before: macCatalyst 999.0)
public func backDeployedToInliningTarget(
_: NoAvailable,
_: BeforeInliningTarget,
_: AtInliningTarget,
_: BetweenTargets, // expected-error {{'BetweenTargets' is only available in}}
_: AtDeploymentTarget, // expected-error {{'AtDeploymentTarget' is only available in}}
_: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
) {
defer {
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets() // expected-error {{'BetweenTargets' is only available in}} expected-note {{add 'if #available'}}
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 14, *) {
_ = BetweenTargets()
}
if #available(macCatalyst 14.4, *) {
_ = AtDeploymentTarget()
}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
}
// Default arguments act like @inlinable.
public func defaultArgsUseNoAvailable( // expected-note 3 {{add @available attribute}}
_: Any = NoAvailable.self,
_: Any = BeforeInliningTarget.self,
_: Any = AtInliningTarget.self,
_: Any = BetweenTargets.self, // expected-error {{'BetweenTargets' is only available in}}
_: Any = AtDeploymentTarget.self, // expected-error {{'AtDeploymentTarget' is only available in}}
_: Any = AfterDeploymentTarget.self // expected-error {{'AfterDeploymentTarget' is only available in}}
) {}
public struct PublicStruct { // expected-note 6 {{add @available attribute}}
// Public declarations act like @inlinable.
public var aPublic: NoAvailable
public var bPublic: BeforeInliningTarget
public var cPublic: AtInliningTarget
public var dPublic: BetweenTargets // expected-error {{'BetweenTargets' is only available in}}
public var ePublic: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}}
public var fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
// Internal declarations act like non-inlinable.
var aInternal: NoAvailable
var bInternal: BeforeInliningTarget
var cInternal: AtInliningTarget
var dInternal: BetweenTargets
var eInternal: AtDeploymentTarget
var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
@available(macCatalyst 14, *)
public internal(set) var internalSetter: Void {
@inlinable get {
// Public inlinable getter acts like @inlinable
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget() // expected-error {{'AtDeploymentTarget' is only available in}}
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
set {
// Private setter acts like non-inlinable
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
}
}
@frozen public struct FrozenPublicStruct { // expected-note 6 {{add @available attribute}}
// Public declarations act like @inlinable.
public var aPublic: NoAvailable
public var bPublic: BeforeInliningTarget
public var cPublic: AtInliningTarget
public var dPublic: BetweenTargets // expected-error {{'BetweenTargets' is only available in}}
public var ePublic: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}}
public var fPublic: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
// Internal declarations act like @inlinable in a frozen struct.
var aInternal: NoAvailable
var bInternal: BeforeInliningTarget
var cInternal: AtInliningTarget
var dInternal: BetweenTargets // expected-error {{'BetweenTargets' is only available in}}
var eInternal: AtDeploymentTarget // expected-error {{'AtDeploymentTarget' is only available in}}
var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
}
internal struct InternalStruct { // expected-note {{add @available attribute}}
// Internal declarations act like non-inlinable.
var aInternal: NoAvailable
var bInternal: BeforeInliningTarget
var cInternal: AtInliningTarget
var dInternal: BetweenTargets
var eInternal: AtDeploymentTarget
var fInternal: AfterDeploymentTarget // expected-error {{'AfterDeploymentTarget' is only available in}}
}
// Top-level code, if somehow present in a resilient module, is treated like
// a non-inlinable function.
defer {
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
}
_ = NoAvailable()
_ = BeforeInliningTarget()
_ = AtInliningTarget()
_ = BetweenTargets()
_ = AtDeploymentTarget()
_ = AfterDeploymentTarget() // expected-error {{'AfterDeploymentTarget' is only available in}} expected-note {{add 'if #available'}}
if #available(macCatalyst 15, *) {
_ = AfterDeploymentTarget()
}
| apache-2.0 | ab6d39c4aed34933bae0519e79231168 | 37.250883 | 208 | 0.711224 | 4.284583 | false | false | false | false |
onthebeachh/restriccion-vehicular | Restriccion Vehicular/RestriccionController.swift | 1 | 1284 | //
// RestriccionController.swift
// Restriccion Vehicular
//
// Created by RWBook Retina on 6/25/15.
// Copyright (c) 2015 RABO IT. All rights reserved.
//
import UIKit
import Parse
class RestriccionController: UIViewController {
@IBOutlet var labelConSello: UILabel!
@IBOutlet var labelSinSello: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
var restriccion = LibraryAPI.sharedInstance.getRestriccionActual()
NSNotificationCenter.defaultCenter().addObserver(self, selector:"reloadLabels:", name: "actualizarRestriccionNotification", object: nil)
}
}
func reloadLabels(notification: NSNotification) {
let userInfo = notification.userInfo as! [String: AnyObject]
var restriccion = userInfo["restriccion"] as! Restriccion?
dispatch_async(dispatch_get_main_queue()){
self.labelSinSello.text = restriccion!.restriccionSinSello
self.labelConSello.text = restriccion!.restriccionConSello
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| cc0-1.0 | 9c8073624620d237549acc6210e9017a | 29.571429 | 148 | 0.673676 | 4.128617 | false | false | false | false |
moysklad/ios-remap-sdk | Sources/MoyskladiOSRemapSDK/Mapping/Serialization/MSStore+Serialize.swift | 1 | 1107 | //
// MSStore+Serialize.swift
// MoyskladiOSRemapSDK
//
// Created by Антон Ефименко on 21.09.2018.
// Copyright © 2018 Andrey Parshakov. All rights reserved.
//
import Foundation
extension MSStore {
public func dictionary(metaOnly: Bool = true) -> Dictionary<String, Any> {
var dict = [String: Any]()
if meta.href.count > 0 {
dict["meta"] = meta.dictionary()
}
guard !metaOnly else { return dict }
dict.merge(info.dictionary())
dict["owner"] = serialize(entity: owner, metaOnly: metaOnly)
dict["shared"] = shared
dict["group"] = serialize(entity: group, metaOnly: metaOnly)
dict["code"] = code
dict["externalCode"] = externalCode ?? ""
dict["archived"] = archived
dict["address"] = address ?? ""
dict["pathName"] = pathName ?? ""
dict["parent"] = serialize(entity: parent, metaOnly: true)
dict["attributes"] = attributes?.compactMap { $0.value()?.dictionary(metaOnly: false) }
return dict
}
}
| mit | a894cd7eb7875092dd7eaac37c055e87 | 29.361111 | 95 | 0.574565 | 3.974545 | false | false | false | false |
ilyathewhite/Euler | EulerSketch/EulerSketch/Commands/Sketch+Combined.playground/Pages/Tangents2.xcplaygroundpage/Contents.swift | 1 | 1608 | //: Playground - noun: a place where people can play
import Cocoa
import PlaygroundSupport
import EulerSketchOSX
let sketch = Sketch()
sketch.addPoint("O", hint: (300, 250))
sketch.addCircle("c", withCenter: "O", hintRadius: 150)
sketch.addPoint("A", hint: (300, 500))
sketch.addTangent("AT1", toCircle: "c", selector: leftPoint)
sketch.addTangent("AT2", toCircle: "c", selector: rightPoint)
sketch.addSegment("T1T2")
sketch.addPoint("P", onCircle: "c", hint: (350, 500))
sketch.addIntersection("Q", ofRay: "AP", andCircle: "c") { [unowned sketch] points in
let P = try! sketch.getPoint("P")
return points.first { !same($0, P) }
}
sketch.addMidPoint("M", ofSegment: "PQ")
sketch.addSegment("MT1")
sketch.addSegment("MT2")
sketch.addSegment("AQ")
// result
sketch.addAngleMark(count: 1, fromRay: "MT2", toRay: "MP")
sketch.addAngleMark(count: 1, fromRay: "MP", toRay: "MT1")
sketch.assert("angle T2MP == angle PMT1") { [unowned sketch] in
let MT2 = try sketch.getRay("MT2")
let MP = try sketch.getRay("MP")
let MT1 = try sketch.getRay("MT1")
return same(HSAngle(ray1: MT2, ray2: MP).angle, HSAngle(ray1: MP, ray2: MT1).angle)
}
// hint
// sketch.addCircle("c1", throughPoints: "M", "T1", "T2", style: .extra)
sketch.eval()
// sketch adjustments
sketch.hide(figureNamed: "ray_MT1")
sketch.hide(figureNamed: "ray_MT2")
sketch.point("M", setNameLocation: .bottomLeft)
sketch.point("T1", setNameLocation: .topLeft)
sketch.point("T2", setNameLocation: .topRight)
sketch.point("Q", setNameLocation: .bottomRight)
// live view
PlaygroundPage.current.liveView = sketch.quickView()
| mit | f516f15d00b50f37ff914c43b7e4b56e | 26.254237 | 86 | 0.698383 | 2.96679 | false | false | false | false |
idrisyildiz7/IOS-ToDoList | ToDoList/SimpleTodoList/SimpleTodoList/ListTableTableViewController.swift | 1 | 6375 | //
// ListTableTableViewController.swift
// SimpleTodoList
//
// Created by İDRİS YILDIZ on 06/01/15.
// Copyright (c) 2015 İDRİS YILDIZ. All rights reserved.
//
import UIKit
import EventKit // for import events in system calendar
class ListTableTableViewController: UITableViewController {
//segue variables
var items: [ViewController.ToDoItems] = []
var selectedItemIndex:Int? //Which title
var selectedRowIndex:Int? //Which item
//UI variables
@IBOutlet weak var addButton: UIBarButtonItem!
@IBOutlet weak var homeButton: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
title = items[selectedItemIndex!].name
self.tableView.backgroundColor = items[selectedItemIndex!].Color
//Adding buttons to navigation item
self.navigationItem.rightBarButtonItem = addButton
self.navigationItem.leftBarButtonItem = homeButton
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "addAndConfigureSegue" {
let sg = segue.destinationViewController as! AddItemViewController
sg.backgroundColor = self.tableView.backgroundColor
sg.titleString = "Add"
sg.items = items
sg.selectedItemIndex = selectedItemIndex
}
else if segue.identifier == "HomeSegue" {
let sg = segue.destinationViewController as! ViewController
sg.ItemsTitles = items
}
else if segue.identifier == "editSegue" {
let sg = segue.destinationViewController as! AddItemViewController
sg.backgroundColor = self.tableView.backgroundColor
sg.titleString = "Edit"
sg.items = items
sg.selectedItemIndex = selectedItemIndex
if let indexPath = self.tableView.indexPathForSelectedRow {
sg.selectedRow = indexPath.row
}
else {
sg.selectedRow = selectedRowIndex!
}
}
}
//Table view data source overrides
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items[selectedItemIndex!].Items.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//Configures the cell
var cell = tableView.dequeueReusableCellWithIdentifier("todoList") as UITableViewCell
cell.textLabel?.text = items[selectedItemIndex!].Items[indexPath.row].description
cell.textLabel?.font = UIFont(name: "Helvetica", size: 16.0)
cell.backgroundColor = items[selectedItemIndex!].Color
if items[selectedItemIndex!].Items[indexPath.row].isDone
{
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
cell.textLabel?.font = UIFont(name: "Helvetica-Oblique", size: 16.0)
}
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
//Edit rows actions
let editAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Edit" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//edit action
self.selectedRowIndex = indexPath.row
self.performSegueWithIdentifier("editSegue", sender: self)
})
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
//delete action
let date:NSDate = self.items[self.selectedItemIndex!].Items[indexPath.row].dateAndTime
let note:String = self.items[self.selectedItemIndex!].Items[indexPath.row].description
let title:String = self.items[self.selectedItemIndex!].name
//Delete event from calendar
self.deleteFromCalender(date, title: title, note: note)
self.items[self.selectedItemIndex!].Items.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
})
return [deleteAction,editAction]
}
func deleteFromCalender(date:NSDate,title:String,note:String) {
//Delete event from calendar
var eventStore : EKEventStore = EKEventStore()
var startDate = date.dateByAddingTimeInterval(-60*60*24)
var endDate = date.dateByAddingTimeInterval(60*60*24*3)
var predicate2 = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil)
var eV = eventStore.eventsMatchingPredicate(predicate2) as [EKEvent]!
if eV != nil {
for i in eV {
if (i.notes == note && i.title == title) {
eventStore.removeEvent(i, span: EKSpanThisEvent, error: nil)
}
}
}}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if !self.items[selectedItemIndex!].Items[indexPath.row].isDone {
self.items[selectedItemIndex!].Items[indexPath.row].isDone = true
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.font = UIFont(name: "Helvetica-Oblique", size: 16.0)
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.Checkmark
}
else {
self.items[selectedItemIndex!].Items[indexPath.row].isDone = false
tableView.cellForRowAtIndexPath(indexPath)?.textLabel?.font = UIFont(name: "Helvetica", size: 16.0)
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = UITableViewCellAccessoryType.None
}
}
}
| mit | 7cbb690129ab7e600d1844ce7da1e701 | 41.192053 | 182 | 0.657981 | 5.417517 | false | false | false | false |
coniferprod/ThereAndBack-iOS | App2/App2/ViewController.swift | 1 | 1194 | import UIKit
class ViewController: UIViewController {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var identifierLabel: UILabel!
@IBOutlet weak var verifiedLabel: UILabel!
let mainAppScheme = "app1"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
identifierLabel.text = "identifier = \(appDelegate.identifier)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backToMainApp(_ sender: Any) {
guard let mainAppURL = URL(string: "\(mainAppScheme)://barfoo") else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(mainAppURL, options: [:], completionHandler: nil)
}
else {
UIApplication.shared.openURL(mainAppURL)
}
}
}
| mit | a88b9290aa7c39a70b6210cf713ebc0a | 27.428571 | 87 | 0.623116 | 5.102564 | false | false | false | false |
cxd/recognisetextobject | recogniseobject/TextSegment.swift | 1 | 1585 | //
// TextSegment.swift
// recogniseobject
//
import Foundation
import UIKit
class TextSegment {
var rect:CGRect?
var scaledRect:CGRect?
var displayRect:CGRect?
var charMapping:String?
var isMapped:Bool = false
/**
a corresponding CIImage from the source that represents
this particular segment.
**/
var image:CIImage?
init() {
}
convenience init(inRect:CGRect, inScaledRect:CGRect) {
self.init()
rect = inRect
scaledRect = inScaledRect
}
convenience init(inRect:CGRect, inScaledRect:CGRect, inText:String) {
self.init()
rect = inRect
scaledRect = inScaledRect
charMapping = inText
isMapped = true
}
/**
when results are finalised the mapping for the text is provided.
**/
func mapText(inText:String) {
charMapping = inText
isMapped = true
}
/**
determine if a point is contained within the display rectangle
**/
func displayContains(point:CGPoint) -> Bool {
if let rect = self.displayRect {
let flag = rect.contains(point)
var text=""
if let t = self.charMapping {
text=t
}
print("Debug: Rect (\(rect.origin.x), \(rect.origin.y), \(rect.size.width + rect.origin.x), \(rect.size.height + rect.origin.y)) contains \(flag) point:(\(point.x), \(point.y)) Text:\(text))")
return flag
}
return false
}
}
| apache-2.0 | eddb8f5d9368f9b4cca9017fcff80a8f | 21.323944 | 204 | 0.556467 | 4.354396 | false | false | false | false |
curiousurick/BluetoothBackupSensor-iOS | CSS427Bluefruit_Connect/BLE Test/ColorPickerViewController.swift | 4 | 9840 | //
// ColorPickerViewController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 1/23/15.
// Copyright (c) 2015 Adafruit Industries. All rights reserved.
//
import UIKit
protocol ColorPickerViewControllerDelegate: HelpViewControllerDelegate {
func sendColor(red:UInt8, green:UInt8, blue:UInt8)
}
class ColorPickerViewController: UIViewController, UITextFieldDelegate, ISColorWheelDelegate {
var delegate:ColorPickerViewControllerDelegate!
@IBOutlet var helpViewController:HelpViewController!
@IBOutlet var infoButton:UIButton!
private var infoBarButton:UIBarButtonItem?
var helpPopoverController:UIPopoverController?
// @IBOutlet var redSlider:UISlider!
// @IBOutlet var greenSlider:UISlider!
// @IBOutlet var blueSlider:UISlider!
// @IBOutlet var redField:UITextField!
// @IBOutlet var greenField:UITextField!
// @IBOutlet var blueField:UITextField!
// @IBOutlet var swatchView:UIView!
@IBOutlet var valueLable:UILabel!
@IBOutlet var sendButton:UIButton!
@IBOutlet var wheelView:UIView!
@IBOutlet var wellView:UIView!
@IBOutlet var wheelHorzConstraint:NSLayoutConstraint!
@IBOutlet var wellVertConstraint:NSLayoutConstraint! //34 for 3.5"
@IBOutlet var wellHeightConstraint:NSLayoutConstraint! //64 for 3.5"
@IBOutlet var sendVertConstraint:NSLayoutConstraint! //46 for 3.5"
@IBOutlet var brightnessSlider: UISlider!
@IBOutlet var sliderGradientView: GradientView!
var colorWheel:ISColorWheel!
convenience init(aDelegate:ColorPickerViewControllerDelegate){
//Separate NIBs for iPhone & iPad
var nibName:NSString
if IS_IPHONE {
nibName = "ColorPickerViewController_iPhone"
}
else{ //IPAD
nibName = "ColorPickerViewController_iPad"
}
self.init(nibName: nibName as String, bundle: NSBundle.mainBundle())
self.delegate = aDelegate
self.title = "Color Picker"
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Color Picker"
//setup help view
self.helpViewController.title = "Color Picker Help"
self.helpViewController.delegate = delegate
//add info bar button
let archivedData = NSKeyedArchiver.archivedDataWithRootObject(infoButton)
let buttonCopy = NSKeyedUnarchiver.unarchiveObjectWithData(archivedData) as! UIButton
buttonCopy.addTarget(self, action: Selector("showInfo:"), forControlEvents: UIControlEvents.TouchUpInside)
infoBarButton = UIBarButtonItem(customView: buttonCopy)
self.navigationItem.rightBarButtonItem = infoBarButton
sendButton.layer.cornerRadius = 4.0
sendButton.layer.borderColor = sendButton.currentTitleColor.CGColor
sendButton.layer.borderWidth = 1.0;
wellView.backgroundColor = UIColor.whiteColor()
wellView.layer.borderColor = UIColor.blackColor().CGColor
wellView.layer.borderWidth = 1.0
wheelView.backgroundColor = UIColor.clearColor()
//customize brightness slider
let sliderTrackImage = UIImage(named: "clearPixel.png")
brightnessSlider.setMinimumTrackImage(sliderTrackImage, forState: UIControlState.Normal)
brightnessSlider.setMaximumTrackImage(sliderTrackImage, forState: UIControlState.Normal)
sliderGradientView.endColor = wellView.backgroundColor!
//adjust layout for 3.5" displays
if (IS_IPHONE_4) {
wellVertConstraint.constant = 34
wellHeightConstraint.constant = 64
sendVertConstraint.constant = 46
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
//Add color wheel
if wheelView.subviews.count == 0 {
// let size = wheelView.bounds.size
// let wheelSize = CGSizeMake(size.width * 0.9, size.width * 0.9)
// let rect = CGRectMake(size.width / 2 - wheelSize.width / 2,
//// 0.0,
// size.height * 0.1,
// wheelSize.width,
// wheelSize.height)
let rect = CGRectMake(
0.0,
0.0,
wheelView.bounds.size.width,
wheelView.bounds.size.height)
colorWheel = ISColorWheel(frame: rect)
colorWheel.delegate = self
colorWheel.continuous = true
wheelView.addSubview(colorWheel)
}
}
// @IBAction func sliderValueChanged(sender:UISlider) {
//
// var textField:UITextField
//
// switch sender.tag {
// case 0: //red
// textField = redField
// case 1: //green
// textField = greenField
// case 2: //blue
// textField = blueField
// default:
// printLog(self, "\(__FUNCTION__)", "slider returned invalid tag")
// return
// }
//
// //Dismiss any text field
//
// //Update textfield
// textField.text = "\(Int(sender.value))"
//
// //Update value label
// updateValueLabel()
//
// }
func updateValueLabel() {
//RGB method
// valueLable.text = "R:\(redField.text) G:\(greenField.text) B:\(blueField.text)"
//
// //Update color swatch
// let color = UIColor(red: CGFloat(redSlider.value / 255.0), green: CGFloat(greenSlider.value / 255.0), blue: CGFloat(blueSlider.value / 255.0), alpha: 1.0)
// swatchView.backgroundColor = color
}
// func textFieldDidEndEditing(textField: UITextField) {
//
// var slider:UISlider
//
// switch textField.tag {
// case 0: //red
// slider = redSlider
// case 1: //green
// slider = greenSlider
// case 2: //blue
// slider = blueSlider
// default:
// printLog(self, "\(__FUNCTION__)", "textField returned with invalid tag")
// return
// }
//
// //Update slider
// var intVal = textField.text.toInt()?
// if (intVal != nil) {
// slider.value = Float(intVal!)
// }
// else {
// printLog(self, "\(__FUNCTION__)", "textField returned non-integer value")
// return
// }
//
// //Update value label
// updateValueLabel()
//
// }
@IBAction func showInfo(sender:AnyObject) {
// Show help info view on iPhone via flip transition, called via "i" button in navbar
if (IS_IPHONE) {
presentViewController(helpViewController, animated: true, completion: nil)
}
//iPad
else if (IS_IPAD) {
//show popover if it isn't shown
helpPopoverController?.dismissPopoverAnimated(true)
helpPopoverController = UIPopoverController(contentViewController: helpViewController)
helpPopoverController?.backgroundColor = UIColor.darkGrayColor()
let rightBBI:UIBarButtonItem! = self.navigationController?.navigationBar.items?.last!.rightBarButtonItem
let aFrame:CGRect = rightBBI!.customView!.frame
helpPopoverController?.presentPopoverFromRect(aFrame,
inView: rightBBI.customView!.superview!,
permittedArrowDirections: UIPopoverArrowDirection.Any,
animated: true)
}
}
@IBAction func brightnessSliderChanged(sender: UISlider) {
colorWheelDidChangeColor(colorWheel)
}
@IBAction func sendColor() {
//Send color bytes thru UART
var r:CGFloat = 0.0
var g:CGFloat = 0.0
var b:CGFloat = 0.0
wellView.backgroundColor!.getRed(&r, green: &g, blue: &b, alpha: nil)
delegate.sendColor((UInt8(255.0 * Float(r))), green: (UInt8(255.0 * Float(g))), blue: (UInt8(255.0 * Float(b))))
}
func colorWheelDidChangeColor(colorWheel:ISColorWheel) {
let colorWheelColor = colorWheel.currentColor()
// sliderTintView.backgroundColor = colorWheelColor
sliderGradientView.endColor = colorWheelColor!
let brightness = CGFloat(brightnessSlider.value)
var red:CGFloat = 0.0
var green:CGFloat = 0.0
var blue:CGFloat = 0.0
colorWheelColor.getRed(&red, green: &green, blue: &blue, alpha: nil)
red *= brightness; green *= brightness; blue *= brightness
let color = UIColor(red: red, green: green, blue: blue, alpha: 1.0)
wellView.backgroundColor = color
// var r:CGFloat = 0.0
// var g:CGFloat = 0.0
// var b:CGFloat = 0.0
//// var a:UnsafeMutablePointer<CGFloat>
// color.getRed(&r, green: &g, blue: &b, alpha: nil)
valueLable.text = "R:\(Int(255.0 * Float(red))) G:\(Int(255.0 * Float(green))) B:\(Int(255.0 * Float(blue)))"
}
}
| mit | bf8a4c85a82b39a54e897e1124308564 | 31.475248 | 166 | 0.580285 | 4.8 | false | false | false | false |
Henryforce/KRActivityIndicatorView | KRActivityIndicatorView/KRActivityIndicatorAnimationSemiCircleSpin.swift | 2 | 2321 | //
// KRActivityIndicatorAnimationSemiCircleSpin.swift
// KRActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Originally written to work in iOS by Vinh Nguyen in 2016
// Adapted to OSX by Henry Serrano in 2017
// 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 Cocoa
class KRActivityIndicatorAnimationSemiCircleSpin: KRActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) {
let duration: CFTimeInterval = 0.6
// Animation
let animation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
animation.keyTimes = [0, 0.5, 1]
animation.values = [0, Float.pi, 2 * Float.pi]
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = KRActivityIndicatorShape.circleSemi.layerWith(size: size, color: color)
let frame = CGRect(
x: (layer.bounds.width - size.width) / 2,
y: (layer.bounds.height - size.height) / 2,
width: size.width,
height: size.height
)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 5daf88b1b3ea4b5a88c25eb4a32c8e23 | 39.017241 | 92 | 0.698406 | 4.651303 | false | false | false | false |
sugar2010/SwiftOptimizer | swix/twoD/matrix2d.swift | 2 | 4708 | //
// matrix2d.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
struct matrix2d {
let n: Int
var rows: Int
var columns: Int
var count: Int
var shape: (Int, Int)
var flat:matrix
init(columns: Int, rows: Int) {
self.n = rows * columns
self.rows = rows
self.columns = columns
self.shape = (rows, columns)
self.count = n
self.flat = zeros(rows * columns)
}
subscript(i: String) -> matrix {
get {
assert(i == "diag", "Currently the only support x[string] is x[\"diag\"]")
var x = diag(self)
return x
}
set {
assert(i == "diag")
diag_set_objc(!self, !newValue, self.shape.0.cint, self.shape.1.cint)
}
}
func indexIsValidForRow(r: Int, c: Int) -> Bool {
return r >= 0 && r < rows && c>=0 && c < columns
}
subscript(i: Int, j: Int) -> Double {
get {
assert(indexIsValidForRow(i, c:j), "Index out of range")
return flat[i*columns + j]
}
set {
assert(indexIsValidForRow(i, c:j), "Index out of range")
flat[i*columns + j] = newValue
}
}
subscript(r: Range<Int>, c: Range<Int>) -> matrix2d {
get {
var rr = toArray(r)
var cc = toArray(c)
var (j, i) = meshgrid(rr, cc)
var idx = (j.flat*columns.double + i.flat)
var z = flat[idx]
var zz = reshape(z, (rr.n, cc.n))
return zz
}
set {
var rr = toArray(r)
var cc = toArray(c)
var (j, i) = meshgrid(rr, cc)
var idx = j.flat*columns.double + i.flat
flat[idx] = newValue.flat
}
}
subscript(r: matrix, c: matrix) -> matrix2d {
get {
var (j, i) = meshgrid(r, c)
var idx = (j.flat*columns.double + i.flat)
var z = flat[idx]
var zz = reshape(z, (r.n, c.n))
return zz
}
set {
var (j, i) = meshgrid(r, c)
var idx = j.flat*columns.double + i.flat
flat[idx] = newValue.flat
}
}
subscript(r: matrix) -> matrix {
get {return self.flat[r]}
set {flat.grid = newValue.grid}
}
subscript(i: Range<Int>, k: Int) -> matrix {
get {
var idx = toArray(i)
var x:matrix = self.flat[idx * self.columns.double + k.double]
return x
}
set {
var idx = toArray(i)
self.flat[idx * self.columns.double + k.double] = newValue[idx]
}
}
subscript(i: Int, k: Range<Int>) -> matrix {
get {
var idx = toArray(k)
var x:matrix = self.flat[i.double * self.columns.double + idx]
return x
}
set {
var idx = toArray(k)
self.flat[i.double * self.columns.double + idx] = newValue[idx]
}
}
}
func println(x: matrix2d, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
print(prefix)
var suffix = ", "
var pre:String
var post:String
var printedSpacer = false
for i in 0..<x.shape.0{
// pre and post nice -- internal variables
if i==0 {pre = ""}
else {pre = " "}
if i==x.shape.0-1{post=""}
else {post = "],\n"}
if printWholeMatrix || x.shape.0 < 16 || i<4-1 || i>x.shape.0-4{
print(x[i, 0..<x.shape.1], prefix:pre, postfix:post, format: format, printWholeMatrix:printWholeMatrix)
}
else if printedSpacer==false{
printedSpacer=true
println(" ...,")
}
}
print(postfix)
print(newline)
}
func print(x: matrix2d, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printWholeMatrix:printWholeMatrix)
}
func zeros_like(x: matrix2d) -> matrix2d{
var y:matrix2d = zeros((x.shape.0, x.shape.1))
return y
}
func transpose (x: matrix2d) -> matrix2d{
let n = x.shape.0
let m = x.shape.1
var y = zeros((m, n))
var xP = matrixToPointer(x.flat)
var yP = matrixToPointer(y.flat)
transpose_objc(xP, yP, m.cint, n.cint);
return y
}
func argwhere(idx: matrix2d) -> matrix{
return argwhere(idx.flat)
}
func copy(x: matrix2d, y: matrix2d){
copy(x.flat, y.flat)
}
| mit | ea56e5182668cde6c72d4347ce680c32 | 26.057471 | 145 | 0.515081 | 3.461765 | false | false | false | false |
webim/webim-client-sdk-ios | WebimClientLibrary/Backend/Items/DepartmentItem.swift | 1 | 3665 | //
// DepartmentItem.swift
// Cosmos
//
// Created by Nikita Lazarev-Zubov on 11.12.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
/**
Encapsulates internal representation of single department.
- author:
Nikita Lazarev-Zubov
- copyright:
2017 Webim
*/
final class DepartmentItem {
// MARK: - Constants
// Raw values equal to field names received in responses from server.
private enum JSONField: String {
case key = "key"
case localizedNames = "localeToName"
case name = "name"
case onlineStatus = "online"
case order = "order"
case logo = "logo"
}
enum InternalDepartmentOnlineStatus: String {
case busyOffline = "busy_offline"
case busyOnline = "busy_online"
case offline = "offline"
case online = "online"
case unknown
}
// MARK: - Properties
private let key: String
private let name: String
private let onlineStatus: InternalDepartmentOnlineStatus
private let order: Int
private var localizedNames: [String: String]?
private var logo: String?
// MARK: - Initialization
init?(jsonDictionary: [String: Any?]) {
guard let key = jsonDictionary[JSONField.key.rawValue] as? String,
let name = jsonDictionary[JSONField.name.rawValue] as? String,
let onlineStatusString = jsonDictionary[JSONField.onlineStatus.rawValue] as? String,
let order = jsonDictionary[JSONField.order.rawValue] as? Int else {
return nil
}
self.key = key
self.name = name
self.onlineStatus = InternalDepartmentOnlineStatus(rawValue: onlineStatusString) ?? .unknown
self.order = order
if let logoURLString = jsonDictionary[JSONField.logo.rawValue] as? String {
self.logo = logoURLString
}
if let localizedNames = jsonDictionary[JSONField.localizedNames.rawValue] as? [String: String] {
self.localizedNames = localizedNames
}
}
// MARK: - Methods
func getKey() -> String {
return key
}
func getName() -> String {
return name
}
func getOnlineStatus() -> InternalDepartmentOnlineStatus {
return onlineStatus
}
func getOrder() -> Int {
return order
}
func getLocalizedNames() -> [String: String]? {
return localizedNames
}
func getLogoURLString() -> String? {
return logo
}
}
| mit | 660dd0e817af6465286fe642d0ef2acd | 30.86087 | 104 | 0.654203 | 4.585732 | false | false | false | false |
thierrybucco/Eureka | Source/Rows/DatePickerRow.swift | 5 | 4877 | // DateRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class DatePickerCell: Cell<Date>, CellType {
@IBOutlet weak public var datePicker: UIDatePicker!
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
let datePicker = UIDatePicker()
self.datePicker = datePicker
self.datePicker.translatesAutoresizingMaskIntoConstraints = false
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.contentView.addSubview(self.datePicker)
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": self.datePicker]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[picker]-0-|", options: [], metrics: nil, views: ["picker": self.datePicker]))
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
selectionStyle = .none
accessoryType = .none
editingAccessoryType = .none
datePicker.datePickerMode = datePickerMode()
datePicker.addTarget(self, action: #selector(DatePickerCell.datePickerValueChanged(_:)), for: .valueChanged)
}
deinit {
datePicker?.removeTarget(self, action: nil, for: .allEvents)
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
datePicker.isUserInteractionEnabled = !row.isDisabled
detailTextLabel?.text = nil
textLabel?.text = nil
datePicker.setDate(row.value ?? Date(), animated: row is CountDownPickerRow)
datePicker.minimumDate = (row as? DatePickerRowProtocol)?.minimumDate
datePicker.maximumDate = (row as? DatePickerRowProtocol)?.maximumDate
if let minuteIntervalValue = (row as? DatePickerRowProtocol)?.minuteInterval {
datePicker.minuteInterval = minuteIntervalValue
}
}
func datePickerValueChanged(_ sender: UIDatePicker) {
row?.value = sender.date
}
private func datePickerMode() -> UIDatePickerMode {
switch row {
case is DatePickerRow:
return .date
case is TimePickerRow:
return .time
case is DateTimePickerRow:
return .dateAndTime
case is CountDownPickerRow:
return .countDownTimer
default:
return .date
}
}
}
open class _DatePickerRow: Row<DatePickerCell>, DatePickerRowProtocol {
open var minimumDate: Date?
open var maximumDate: Date?
open var minuteInterval: Int?
required public init(tag: String?) {
super.init(tag: tag)
displayValueFor = nil
}
}
/// A row with an Date as value where the user can select a date directly.
public final class DatePickerRow: _DatePickerRow, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with an Date as value where the user can select a time directly.
public final class TimePickerRow: _DatePickerRow, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with an Date as value where the user can select date and time directly.
public final class DateTimePickerRow: _DatePickerRow, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
/// A row with an Date as value where the user can select hour and minute as a countdown timer.
public final class CountDownPickerRow: _DatePickerRow, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
| mit | 5803701aaf74c1d00180b51677802fbf | 35.669173 | 174 | 0.690383 | 4.758049 | false | false | false | false |
Alchemistxxd/AXStylishNavigationBar | CarPro/CollectionViewDataProvider.swift | 1 | 2651 | //
// RenditionCollectionDataProvider.swift
// Final Car Pro
//
// Created by Xudong Xu on 1/11/21.
//
import Cocoa
class CollectionViewDataProvider<ViewItem: NSCollectionViewItem, DataItem>: NSObject, NSCollectionViewDelegate, NSCollectionViewDataSource, NSTableViewDataSource {
var userInfo: [String: Any] = [:]
var itemForRepresentedObjectAtIndexPath: ((_ collectionView: NSCollectionView, _ indexPath: IndexPath, _ viewItem: ViewItem, _ dataItem: DataItem) -> Void)?
var didSelectItemsAtIndexPaths: ((_ collectionView: NSCollectionView, _ indexPaths: Set<IndexPath>, _ dataItems: [DataItem]) -> Void)?
var pasteboardWriterForItemAtIndexPath: ((_ collectionView: NSCollectionView, _ indexPath: IndexPath, _ dataItem: DataItem) throws -> NSPasteboardWriting)?
init(_ identifier: NSUserInterfaceItemIdentifier, _ collectionView: NSCollectionView) {
self.identifier = identifier
self.collectionView = collectionView
}
private(set) var identifier: NSUserInterfaceItemIdentifier
private(set) var collectionView: NSCollectionView! {
didSet {
collectionView.setDraggingSourceOperationMask(.every, forLocal: false)
collectionView.delegate = self
collectionView.dataSource = self
}
}
var dataSource: [DataItem] = [] {
didSet {
DispatchQueue.main.async {
self.collectionView?.reloadData()
}
}
}
func numberOfSections(in collectionView: NSCollectionView) -> Int {
1
}
func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
dataSource.count
}
func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
let viewItem = collectionView.makeItem(withIdentifier: identifier, for: indexPath) as! ViewItem
let dataItem = dataSource[indexPath.item]
itemForRepresentedObjectAtIndexPath?(collectionView, indexPath, viewItem, dataItem)
return viewItem
}
func collectionView(_ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set<IndexPath>) {
didSelectItemsAtIndexPaths?(collectionView, indexPaths, indexPaths.map { dataSource[$0.item] })
}
func collectionView(_ collectionView: NSCollectionView, pasteboardWriterForItemAt indexPath: IndexPath) -> NSPasteboardWriting? {
let dataItem = dataSource[indexPath.item]
return try? pasteboardWriterForItemAtIndexPath?(collectionView, indexPath, dataItem)
}
}
| mit | 938122e70efc837ce3bc29d9d6990e5d | 40.421875 | 163 | 0.705394 | 5.688841 | false | false | false | false |
tuannme/Up | Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotate.swift | 2 | 2806 | //
// NVActivityIndicatorBallClipRotate.swift
// NVActivityIndicatorViewDemo
//
// The MIT License (MIT)
// Copyright (c) 2016 Vinh Nguyen
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
class NVActivityIndicatorAnimationBallClipRotate: NVActivityIndicatorAnimationDelegate {
func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let duration: CFTimeInterval = 0.75
// Scale animation
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.values = [1, 0.6, 1]
// Rotate animation
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotateAnimation.keyTimes = scaleAnimation.keyTimes
rotateAnimation.values = [0, M_PI, 2 * M_PI]
// Animation
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.duration = duration
animation.repeatCount = HUGE
animation.isRemovedOnCompletion = false
// Draw circle
let circle = NVActivityIndicatorShape.ringThirdFour.layerWith(size: CGSize(width: size.width, height: size.height), color: color)
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2,
y: (layer.bounds.size.height - size.height) / 2,
width: size.width,
height: size.height)
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
| mit | 0d6e00667a805a4d9395b0ca6816751e | 40.880597 | 137 | 0.683535 | 4.992883 | false | false | false | false |
mattruston/idb | GamingDBScraper/GamingDBScraper/Images.swift | 1 | 4934 | //
// GameImages.swift
// GamingDBScraper
//
// Created by Matthew Ruston on 10/26/17.
// Copyright © 2017 MattRuston. All rights reserved.
//
import Foundation
fileprivate var fileJson: [[String: Any]] = []
fileprivate let basePath = "https://images.igdb.com/igdb/image/upload/"
// MARK: - Games
func downloadGameImages() {
readInFileData("igdb_games.json")
for id in getGameIds() {
downloadImage(id)
}
}
fileprivate func getGameIds() -> [String] {
var ids: [String] = []
print("Parsing games")
for game in fileJson {
if let imageData = game["cover"] as? [String: Any] {
if let path = imageData["cloudinary_id"] as? String {
ids.append(path)
}
}
}
return ids
}
// MARK: - Platform
func downloadPlatformImages() {
readInFileData("igdb_platforms.json")
for id in getPlatformIds() {
downloadImage(id)
}
}
fileprivate func getPlatformIds() -> [String] {
var ids: [String] = []
print("Parsing platforms")
for platform in fileJson {
if let imageData = platform["logo"] as? [String: Any] {
if let path = imageData["cloudinary_id"] as? String {
ids.append(path)
}
}
}
return ids
}
// MARK: - Company
func downloadCompanyImages() {
readInFileData("igdb_companies.json")
for id in getCompanyIds() {
downloadImage(id)
}
}
fileprivate func getCompanyIds() -> [String] {
var ids: [String] = []
print("Parsing companies")
for company in fileJson {
if let imageData = company["logo"] as? [String: Any] {
if let path = imageData["cloudinary_id"] as? String {
ids.append(path)
}
}
}
return ids
}
// MARK: - Company
func downloadCharacterImages() {
readInFileData("igdb_characters.json")
for id in getCharacterIds() {
downloadImage(id)
}
}
fileprivate func getCharacterIds() -> [String] {
var ids: [String] = []
print("Parsing characters")
for character in fileJson {
if let imageData = character["mug_shot"] as? [String: Any] {
if let path = imageData["cloudinary_id"] as? String {
ids.append(path)
}
}
}
return ids
}
// MARK: - Helpers
fileprivate func downloadImage(_ id: String) {
let types: [String] = [".jpg", ".png"]
var done = false
for type in types.reversed() {
guard let url: URL = URL(string: "\(basePath)\(id)\(type)") else {
continue
}
var semaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: url) { (data, response, error) in
defer { semaphore.signal() }
if let _ = error {
print("ERROR: Failed to get: \(id)\(type)")
return
}
guard let data = data, data.count > 0 else {
print("ERROR: No data for image: \(id)\(type)")
return
}
if saveImage(data: data, id: id, type: type) {
print("saved: \(id)")
done = true
}
}.resume()
semaphore.wait()
if done {
return
}
}
}
fileprivate func saveImage(data: Data, id: String, type: String) -> Bool {
if let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let imagePath = documentDirectoryUrl.appendingPathComponent("images/\(id)\(type)")
do {
try data.write(to: imagePath)
} catch {
return false
}
return true
}
return false
}
fileprivate func readInFileData(_ file: String) {
if let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileUrl = documentDirectoryUrl.appendingPathComponent(file)
do {
let data = try Data(contentsOf: fileUrl)
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
fileJson = json
} else {
//For some reason something isnt the right type of dictionary, so we want to filter that out
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [Any] {
print("Json had: \(json.count)")
if let filtered = json.filter({ (item) -> Bool in
return item is [String: Any]
}) as? [[String: Any]] {
print("filtered had: \(filtered.count)")
fileJson = filtered
}
}
}
} catch {
print(error)
}
}
}
| mit | b11f092a3054054aec64a92a2a84edd9 | 25.521505 | 112 | 0.533144 | 4.312063 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeedEntryAuthor.swift | 2 | 2889 | //
// AtomFeedEntryAuthor.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// The "atom:author" element is a Person construct that indicates the
/// author of the entry or feed.
///
/// If an atom:entry element does not contain atom:author elements, then
/// the atom:author elements of the contained atom:source element are
/// considered to apply. In an Atom Feed Document, the atom:author
/// elements of the containing atom:feed element are considered to apply
/// to the entry if there are no atom:author elements in the locations
/// described above.
public class AtomFeedEntryAuthor {
/// The "atom:name" element's content conveys a human-readable name for
/// the person. The content of atom:name is Language-Sensitive. Person
/// constructs MUST contain exactly one "atom:name" element.
public var name: String?
/// The "atom:email" element's content conveys an e-mail address
/// associated with the person. Person constructs MAY contain an
/// atom:email element, but MUST NOT contain more than one. Its content
/// MUST conform to the "addr-spec" production in [RFC2822].
public var email: String?
/// The "atom:uri" element's content conveys an IRI associated with the
/// person. Person constructs MAY contain an atom:uri element, but MUST
/// NOT contain more than one. The content of atom:uri in a Person
/// construct MUST be an IRI reference [RFC3987].
public var uri: String?
}
// MARK: - Equatable
extension AtomFeedEntryAuthor: Equatable {
public static func ==(lhs: AtomFeedEntryAuthor, rhs: AtomFeedEntryAuthor) -> Bool {
return
lhs.name == rhs.name &&
lhs.email == rhs.email &&
lhs.uri == rhs.uri
}
}
| mit | 46c46907444d41efba426ce63b65f5bc | 41.485294 | 87 | 0.709588 | 4.364048 | false | false | false | false |
DanijelHuis/HDAugmentedReality | Example/HDAugmentedRealityDemo/TestAnnotationView.swift | 1 | 6411 | //
// TestAnnotationView.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 30/04/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
import HDAugmentedReality
import CoreLocation
open class TestAnnotationView: ARAnnotationView, UIGestureRecognizerDelegate
{
open var backgroundImageView: UIImageView?
open var gradientImageView: UIImageView?
open var iconImageView: UIImageView?
open var titleLabel: UILabel?
open var arFrame: CGRect = CGRect.zero // Just for test stacking
override open weak var annotation: ARAnnotation? { didSet { self.bindAnnotation() } }
override open func initialize()
{
super.initialize()
self.loadUi()
}
override open func didMoveToSuperview()
{
super.didMoveToSuperview()
if self.superview != nil { self.startRotating() }
else { self.stopRotating() }
}
/// We are creating all UI programatically because XIBs are heavyweight.
func loadUi()
{
let image = UIImage(named: "annotationViewBackground")?.resizableImage(withCapInsets: UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 30), resizingMode: .stretch)
let gradientImage = UIImage(named: "annotationViewGradient")?.withRenderingMode(.alwaysTemplate)
// Gradient
let gradientImageView = UIImageView()
gradientImageView.contentMode = .scaleAspectFit
gradientImageView.image = gradientImage
self.addSubview(gradientImageView)
self.gradientImageView = gradientImageView
// Background
let backgroundImageView = UIImageView()
backgroundImageView.image = image
self.addSubview(backgroundImageView)
self.backgroundImageView = backgroundImageView
// Icon
let iconImageView = UIImageView()
iconImageView.contentMode = .scaleAspectFit
self.addSubview(iconImageView)
self.iconImageView = iconImageView
// Title label
self.titleLabel?.removeFromSuperview()
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 10)
label.numberOfLines = 0
label.backgroundColor = UIColor.clear
label.textColor = UIColor.white
self.addSubview(label)
self.titleLabel = label
// Gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(TestAnnotationView.tapGesture))
self.addGestureRecognizer(tapGesture)
// Other
self.backgroundColor = UIColor.clear
if self.annotation != nil { self.bindUi() }
}
func bindAnnotation()
{
guard let annotation = self.annotation as? TestAnnotation else { return }
let type = annotation.type
let icon = type.icon
let tintColor = type.tintColor
self.gradientImageView?.tintColor = tintColor
self.iconImageView?.tintColor = tintColor
self.iconImageView?.image = icon
}
func layoutUi()
{
let height = self.frame.size.height
self.backgroundImageView?.frame = self.bounds
self.iconImageView?.frame.size = CGSize(width: 20, height: 20)
self.iconImageView?.center = CGPoint(x: height/2, y: height/2)
self.gradientImageView?.frame.size = CGSize(width: 40, height: 40)
self.gradientImageView?.center = CGPoint(x: height/2, y: height/2)
self.gradientImageView?.layer.cornerRadius = (self.gradientImageView?.frame.size.width ?? 0) / 2
self.gradientImageView?.layer.masksToBounds = true
self.titleLabel?.frame = CGRect(x: 58, y: 0, width: self.frame.size.width - 20, height: self.frame.size.height);
}
// This method is called whenever distance/azimuth is set
override open func bindUi()
{
let annotationTitle = (self.annotation as? TestAnnotation)?.type.title ?? self.annotation?.title ?? ""
var distance: String = ""
if let annotation = self.annotation { distance = annotation.distanceFromUser > 1000 ? String(format: "%.1fkm", annotation.distanceFromUser / 1000) : String(format:"%.0fm", annotation.distanceFromUser) }
self.titleLabel?.text = "\(annotationTitle)\n\(distance)"
/*
if let annotation = self.annotation, let title = annotation.title
{
let distance = annotation.distanceFromUser > 1000 ? String(format: "%.1fkm", annotation.distanceFromUser / 1000) : String(format:"%.0fm", annotation.distanceFromUser)
let text = String(format: "%@\nAZ: %.0f°\nDST: %@", title, annotation.azimuth, distance)
self.titleLabel?.text = text
}*/
}
open override func layoutSubviews()
{
super.layoutSubviews()
self.layoutUi()
}
@objc open func tapGesture()
{
guard let annotation = self.annotation, let rootViewController = UIApplication.shared.delegate?.window??.rootViewController else { return }
let alertController = UIAlertController(title: annotation.title, message: "Tapped", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(action)
rootViewController.presentedViewController?.present(alertController, animated: true, completion: nil)
}
//==========================================================================================================================================================
// MARK: Annotations
//==========================================================================================================================================================
private func startRotating()
{
let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotateAnimation.fromValue = 0
rotateAnimation.toValue = CGFloat(Double.pi * 2)
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.duration = Double.random(in: 1..<3)
rotateAnimation.repeatCount=Float.infinity
self.gradientImageView?.layer.add(rotateAnimation, forKey: nil)
}
private func stopRotating()
{
self.gradientImageView?.layer.removeAllAnimations()
}
}
| mit | 160cd272c4983f140e66d83bb911158a | 38.085366 | 210 | 0.616381 | 5.315091 | false | false | false | false |
LYM-mg/MGOFO | MGOFO/MGOFO/Class/Tools/NetWorkTools.swift | 1 | 10917 | /**
NetWorkTools.swift
Created by i-Techsys.com on 16/11/24.
Swift 3.0封装 Alamofire
*/
import UIKit
import Alamofire
// MARK: - 请求方法类型枚举
enum MethodType: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
// MARK: - Swift 3.0封装 Alamofire
/// Swift 3.0封装 Alamofire
class NetWorkTools: NSObject {
/// 请求时间
var elapsedTime: TimeInterval?
/// 请求单例工具类对象
// static let share = NetWorkTools()
// class func share() -> NetWorkTools {
// struct single {
// static let singleDefault = NetWorkTools()
// }
// return single.singleDefault
// }
// MARK: 通用请求的Manager
static let defManager: SessionManager = {
var defHeaders = Alamofire.SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
let defConf = URLSessionConfiguration.default
defConf.timeoutIntervalForRequest = 5
defConf.httpAdditionalHeaders = defHeaders
let manager = Alamofire.SessionManager(configuration: defConf)
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
// credential = URLCredential(forTrust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
return manager
}()
// MARK: 后台请求的Manager
static let backgroundManager: SessionManager = {
let defHeaders = Alamofire.SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
let backgroundConf = URLSessionConfiguration.background(withIdentifier: "io.zhibo.api.backgroud")
backgroundConf.httpAdditionalHeaders = defHeaders
return Alamofire.SessionManager(configuration: backgroundConf)
}()
// MARK: 私有会话的Manager
static let ephemeralManager: SessionManager = {
let defHeaders = Alamofire.SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
let ephemeralConf = URLSessionConfiguration.ephemeral
ephemeralConf.timeoutIntervalForRequest = 5
ephemeralConf.httpAdditionalHeaders = defHeaders
return Alamofire.SessionManager(configuration: ephemeralConf)
}()
}
// MARK: - 通用请求方法
extension NetWorkTools {
/// 通用请求方法
/**
- parameter type: 请求方式
- parameter urlString: 请求网址
- parameter parameters: 请求参数
- parameter succeed: 请求成功回调
- parameter failure: 请求失败回调
- parameter error: 错误信息
*/
/// 备注:通用请求方法,增加失败回调,参考系统闭包
static func requestJSON(type: MethodType,urlString: String, parameters: [String : Any]? = nil ,succeed:@escaping ((_ result : Any?, _ error: Error?) -> Swift.Void), failure:@escaping ((_ error: Error?) -> Swift.Void)) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "text/html",
// "Content-Type": "application/x-www-form-urlencoded",
// "Content-Type": "charset=utf-8",
// "Content-Type": "application/json"
]
let start = CACurrentMediaTime()
// 2.发送网络数据请求
NetWorkTools.defManager.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default,headers: headers).responseJSON { (response) in
let end = CACurrentMediaTime()
let elapsedTime = end - start
print("请求时间 = \(elapsedTime)")
// print("response.timeline = \(response.timeline)")
// 请求失败
if response.result.isFailure {
print(response.result.error)
failure(response.result.error)
return
}
// 请求成功
if response.result.isSuccess {
// 3.获取结果
guard let result = response.result.value else {
failure(response.result.error)
return
}
// 4.将结果回调出去
succeed(result, nil)
}
}
}
/// 通用请求方法
/**
备注:通用请求方法,增加失败回调,参考系统闭包
- parameter type: 请求方式
- parameter urlString: 请求网址
- parameter parameters: 请求参数
- parameter succeed: 请求成功回调
- parameter failure: 请求失败回调
- parameter error: 错误信息
*/
static func requestData(type: MethodType,urlString: String, parameters: [String : Any]? = nil ,succeed:@escaping ((_ result : Any?, _ error: Error?) -> Swift.Void), failure: @escaping ((_ error: Error?) -> Swift.Void)) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
let headers: HTTPHeaders = [
"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
"Accept": "text/html",
"Content-Type": "charset=utf-8"
]
let start = CACurrentMediaTime()
// 2.发送网络数据请求
NetWorkTools.defManager.request(urlString, method: method, parameters: parameters,headers: headers).responseJSON { (response) in
let end = CACurrentMediaTime()
let elapsedTime = end - start
print("请求时间 = \(elapsedTime)")
// 请求失败
if response.result.isFailure {
print(response.result.error)
failure(response.result.error)
return
}
// 请求成功
if response.result.isSuccess {
// 3.获取结果
guard let result = response.result.value else {
succeed(nil, response.result.error)
return
}
// 4.将结果回调出去
succeed(result, nil)
}
}
}
}
// MARK: - 下载请求
extension NetWorkTools {
// 目标路径闭包展开
func downloadData(type: MethodType,urlString: String, parameters: [String : Any]? = nil ,succeed:@escaping ((_ result : Any?, _ error: Error?) -> Swift.Void), failure:@escaping ((_ error: Error?) -> Swift.Void)) {
//指定下载路径(文件名不变)
let destination: DownloadRequest.DownloadFileDestination = { _, response in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(response.suggestedFilename!)
//两个参数表示如果有同名文件则会覆盖,如果路径中文件夹不存在则会自动创建
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
//开始下载
NetWorkTools.backgroundManager.download(urlString, to: destination)
.downloadProgress { progress in
print("当前进度: \(progress.fractionCompleted)")
}
.response { (response) in
// if let imagePath = response.destinationURL?.path {
// let image = UIImage(contentsOfFile: imagePath)
// }
}
}
}
// MARK: - 上传
extension NetWorkTools {
func upload(fileURL: URL,urlStr: String,method: HTTPMethod,completed:@escaping (() -> Swift.Void)) {
NetWorkTools.backgroundManager.upload(fileURL, to: urlStr, method: method)
.uploadProgress { progress in // main queue by default
print("当前进度: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
completed()
}
}
}
// MARK: -
// MARK: - 判断网络类型
//(与官方风格一致,推荐使用)
enum NetworkStatuses {
case NetworkStatusNone // 没有网络
case NetworkStatus2G // 2G
case NetworkStatus3G // 3G
case NetworkStatus4G // 4G
case NetworkStatusWIFI // WIFI
}
extension NetWorkTools {
/// 获取网络状态
class func getNetworkStates() -> NetworkStatuses? {
guard let object1 = UIApplication.shared.value(forKey: "statusBar") as? NSObject else { return nil }
guard let object2 = object1.value(forKey: "foregroundView") as? UIView else { return nil }
let subviews = object2.subviews
var status = NetworkStatuses.NetworkStatusNone
for child in subviews {
if child.isKind(of: NSClassFromString("UIStatusBarDataNetworkItemView")!) {
// 获取到状态栏码
guard let networkType = child.value(forKey: "dataNetworkType") as? Int else { return nil }
switch (networkType) {
case 0: // 无网模式
status = NetworkStatuses.NetworkStatusNone;
case 1: // 2G模式
status = NetworkStatuses.NetworkStatus2G;
case 2: // 3G模式
status = NetworkStatuses.NetworkStatus3G;
case 3: // 4G模式
status = NetworkStatuses.NetworkStatus4G;
case 5: // WIFI模式
status = NetworkStatuses.NetworkStatusWIFI;
default:
break
}
}
}
// 返回网络类型
return status;
}
}
| mit | e8adda87a88a9a5df633cae9f2d4b061 | 35.555556 | 225 | 0.575645 | 4.891607 | false | false | false | false |
ragnar/VindsidenApp | VindsidenKit/AppConfig.swift | 1 | 5540 | //
// AppConfig.swift
// VindsidenApp
//
// Created by Ragnar Henriksen on 15/12/14.
// Copyright (c) 2014 Ragnar Henriksen. All rights reserved.
//
import Foundation
#if os(iOS)
import StoreKit
#endif
@objc(AppConfig)
open class AppConfig : NSObject {
fileprivate struct Defaults {
static let firstLaunchKey = "Defaults.firstLaunchKey"
fileprivate static let spotlightIndexed = "Defaults.spotlightIndexed"
fileprivate static let bootCount = "Defaults.bootCount"
}
public struct Global {
static let plotHistory = 6.0
}
public struct Bundle {
static var prefix = "org.juniks" // Could be done automatic by reading info.plist
static let appName = "VindsidenApp" // Could be done automatic by reading info.plist
static let todayName = "VindsidenToday"
static let watchName = "Watch"
#if os(iOS)
public static let frameworkBundleIdentifier = "\(prefix).VindsidenKit"
#else
public static let frameworkBundleIdentifier = "\(prefix).VindsidenWatchKit"
#endif
}
struct ApplicationGroups {
static let primary = "group.\(Bundle.prefix).\(Bundle.appName)"
}
public struct Extensions {
public static let widgetBundleIdentifier = "\(Bundle.prefix).\(Bundle.appName).\(Bundle.todayName)"
public static let watchBundleIdentifier = "\(Bundle.prefix).\(Bundle.appName).\(Bundle.watchName)"
}
public struct CoreData {
public static let datamodelName = "Vindsiden"
public static let sqliteName = "\(datamodelName).sqlite"
}
public struct Error {
public static let domain = "\(Bundle.prefix).\(Bundle.appName)"
}
@objc open class var sharedConfiguration: AppConfig {
struct Singleton {
static let sharedAppConfiguration = AppConfig()
}
return Singleton.sharedAppConfiguration
}
@objc open var applicationUserDefaults: UserDefaults {
return UserDefaults(suiteName: ApplicationGroups.primary)!
}
open lazy var frameworkBundle: Foundation.Bundle = {
return Foundation.Bundle(identifier: Bundle.frameworkBundleIdentifier)!
}()
open lazy var applicationDocumentsDirectory: URL? = {
let urlOrNil = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: ApplicationGroups.primary)
if let url = urlOrNil {
return url as URL
} else {
return nil
}
}()
open fileprivate(set) var isFirstLaunch: Bool {
get {
registerDefaults()
return applicationUserDefaults.bool(forKey: Defaults.firstLaunchKey)
}
set {
applicationUserDefaults.set(newValue, forKey: Defaults.firstLaunchKey)
}
}
open fileprivate(set) var isSpotlightIndexed: Int {
get {
return applicationUserDefaults.integer(forKey: Defaults.spotlightIndexed)
}
set {
applicationUserDefaults.set(newValue, forKey: Defaults.spotlightIndexed)
}
}
fileprivate func registerDefaults() {
#if os(watchOS)
let defaultOptions: [String: AnyObject] = [
Defaults.firstLaunchKey: true as AnyObject,
]
#elseif os(iOS)
let defaultOptions: [String: AnyObject] = [
Defaults.firstLaunchKey: true as AnyObject,
]
#elseif os(OSX)
let defaultOptions: [String: AnyObject] = [
Defaults.firstLaunchKey: true
]
#endif
applicationUserDefaults.register(defaults: defaultOptions)
}
open func runHandlerOnFirstLaunch(_ firstLaunchHandler: () -> Void) {
if isFirstLaunch {
isFirstLaunch = false
firstLaunchHandler()
}
}
open func shouldIndexForFirstTime( _ completionHandler: () -> Void) {
if isSpotlightIndexed < 2 {
isSpotlightIndexed = 2
completionHandler()
}
}
@objc open func relativeDate( _ dateOrNil: Date?) -> String {
var dateToUse: Date
if let date = dateOrNil {
dateToUse = (date as NSDate).earlierDate(Date())
} else {
dateToUse = Date()
}
return dateToUse.releativeString()
}
// MARK: - Review
open func presentReviewControllerIfCriteriaIsMet() {
defer {
applicationUserDefaults.synchronize()
}
let version = (Foundation.Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String)
guard let bootCount = applicationUserDefaults.dictionary(forKey: Defaults.bootCount) as? [String:Int] else {
applicationUserDefaults.set([version: 1], forKey: Defaults.bootCount)
return
}
guard let count = bootCount[version] else {
applicationUserDefaults.set([version: 1], forKey: Defaults.bootCount)
return
}
applicationUserDefaults.set([version: count + 1], forKey: Defaults.bootCount)
if count % 7 == 0 {
applicationUserDefaults.set([version: 1], forKey: Defaults.bootCount)
#if os(iOS)
if #available(iOS 10.3, *) {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(1), execute: {
SKStoreReviewController.requestReview()
})
}
#endif
}
}
}
| bsd-2-clause | 92a70bee901caf27e84f810359b5bf2a | 27.265306 | 121 | 0.61426 | 5.009042 | false | false | false | false |
loganisitt/AHPagingMenuViewController | Swift/AHPagingMenuViewController/AHPagingMenuViewController.swift | 1 | 29741 | //
// AHPagingMenuViewController.swift
// VERSION 1.0 - LICENSE MIT
//
// Menu Slider Page! Enjoy
// Swift Version
//
// Created by André Henrique Silva on 01/04/15.
// Bugs? Send -> [email protected] Thank you!
// Copyright (c) 2015 André Henrique Silva. All rights reserved. http://andrehenrique.me =D
//
import UIKit
import ObjectiveC
@objc protocol AHPagingMenuDelegate
{
/**
Change position number
:param: form position initial
:param: to position final
*/
optional func AHPagingMenuDidChangeMenuPosition(form: NSInteger, to: NSInteger);
/**
Change position obj
:param: form obj initial
:param: to obj final
*/
optional func AHPagingMenuDidChangeMenuFrom(form: AnyObject, to: AnyObject);
}
var AHPagingMenuViewControllerKey: UInt8 = 0
extension UIViewController {
func setAHPagingController(menuViewController: AHPagingMenuViewController)
{
self.willChangeValueForKey("AHPagingMenuViewController")
objc_setAssociatedObject(self, &AHPagingMenuViewControllerKey, menuViewController, objc_AssociationPolicy(OBJC_ASSOCIATION_ASSIGN))
self.didChangeValueForKey("AHPagingMenuViewController")
}
func pagingMenuViewController() -> AHPagingMenuViewController
{
var controller = objc_getAssociatedObject(self, &AHPagingMenuViewControllerKey) as! AHPagingMenuViewController;
return controller;
}
}
class AHPagingMenuViewController: UIViewController, UIScrollViewDelegate
{
//Privates
internal var bounce: Bool!
internal var fade: Bool!
internal var transformScale: Bool!
internal var showArrow: Bool!
internal var changeFont: Bool!
internal var changeColor: Bool!
internal var currentPage: NSInteger!
internal var selectedColor: UIColor!
internal var dissectedColor: UIColor!
internal var selectedFont: UIFont!
internal var dissectedFont: UIFont!
internal var scaleMax: CGFloat!
internal var scaleMin: CGFloat!
internal var viewControllers: NSMutableArray?
internal var iconsMenu: NSMutableArray?
internal var delegate: AHPagingMenuDelegate?
internal var NAV_SPACE_VALUE: CGFloat = 15.0
internal var NAV_HEIGHT: CGFloat = 45.0 + (UIApplication.sharedApplication().statusBarFrame.size.height)
internal var NAV_TITLE_SIZE: CGFloat = 30.0
//Publics
private var navView: UIView?
private var navLine: UIView?
private var viewConteiner: UIScrollView?
private var arrowRight: UIImageView?
private var arrowLeft: UIImageView?
// MARK: inits
required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder);
self.inicializeValues(NSArray.new(), iconsMenu: NSArray.new(), position: 0)
}
init(controllers:NSArray, icons: NSArray)
{
super.init(nibName: nil, bundle: nil);
self.inicializeValues(controllers, iconsMenu: icons , position: 0)
}
init( controllers:(NSArray), icons: (NSArray), position:(NSInteger))
{
super.init(nibName: nil, bundle: nil)
self.inicializeValues(controllers, iconsMenu: icons, position: position)
}
// MARK: Cycle Life
override func loadView()
{
super.loadView()
self.view.backgroundColor = UIColor.whiteColor();
var viewConteiner = UIScrollView.new()
viewConteiner.delegate = self
viewConteiner.pagingEnabled = true
viewConteiner.showsHorizontalScrollIndicator = false
viewConteiner.showsVerticalScrollIndicator = false
viewConteiner.contentSize = CGSizeMake(0,0)
self.view.addSubview(viewConteiner)
self.viewConteiner = viewConteiner
var navView = UIView.new()
navView.backgroundColor = UIColor.whiteColor()
navView.clipsToBounds = true
self.view.addSubview(navView)
self.navView = navView
var arrowRight = UIImageView(image: UIImage(named:"arrowRight"))
arrowRight.userInteractionEnabled = true
arrowRight.addGestureRecognizer(UITapGestureRecognizer(target:self, action:Selector("goNextView")))
arrowRight.image = arrowRight.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
self.navView?.addSubview(arrowRight)
self.arrowRight = arrowRight;
var arrowLeft = UIImageView(image: UIImage(named:"arrowLeft"))
arrowLeft.userInteractionEnabled = true
arrowLeft.addGestureRecognizer(UITapGestureRecognizer(target:self, action:Selector("goPrevieusView")))
arrowLeft.image = arrowLeft.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
self.navView?.addSubview(arrowLeft)
self.arrowLeft = arrowLeft
var navLine = UIView.new()
navLine.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
self.view.addSubview(navLine)
self.navLine = navLine
}
override func viewDidLoad()
{
super.viewDidLoad()
var count = 0
for controller in self.viewControllers!
{
self.includeControllerOnInterface(controller as! UIViewController, titleView: self.iconsMenu!.objectAtIndex(count) as! UIView, tag: count)
count++
}
self.viewConteiner?.setContentOffset(CGPointMake(CGFloat(self.currentPage!) * self.viewConteiner!.frame.size.width, self.viewConteiner!.contentOffset.y), animated: false)
}
override func viewDidAppear(animated: Bool)
{
super.viewDidAppear(animated)
self.resetNavBarConfig();
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
NAV_HEIGHT = 45.0 + UIApplication.sharedApplication().statusBarFrame.size.height
self.viewConteiner?.frame = CGRectMake(0, NAV_HEIGHT, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT)
self.viewConteiner?.contentOffset = CGPointMake(CGFloat(self.currentPage) * self.viewConteiner!.frame.size.width, self.viewConteiner!.contentOffset.y)
self.arrowLeft?.center = CGPointMake( NAV_SPACE_VALUE, self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0)
self.arrowRight?.center = CGPointMake( self.view.frame.size.width - NAV_SPACE_VALUE , self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0)
self.navView?.frame = CGRectMake( 0, 0, self.view.frame.size.width, NAV_HEIGHT)
self.navLine?.frame = CGRectMake( 0.0, self.navView!.frame.size.height, self.navView!.frame.size.width, 1.0)
var count = 0;
for controller in self.viewControllers! as NSArray as! [UIViewController]
{
controller.view.frame = CGRectMake(self.view.frame.size.width * CGFloat(count), 0, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT)
var titleView = self.iconsMenu?.objectAtIndex(count) as! UIView
var affine = titleView.transform
titleView.transform = CGAffineTransformMakeScale(1.0, 1.0)
if(titleView.isKindOfClass(UIImageView))
{
var icon = titleView as! UIImageView;
titleView.frame = CGRectMake( 50.0 * CGFloat(count), 0, ( icon.image != nil ? (NAV_TITLE_SIZE * icon.image!.size.width) / icon.image!.size.height : NAV_TITLE_SIZE ) , NAV_TITLE_SIZE)
}
else if(titleView.isKindOfClass(UILabel))
{
titleView.sizeToFit()
}
if(self.transformScale!)
{
titleView.transform = affine
}
var spacing = (self.view.frame.size.width/2.0) - self.NAV_SPACE_VALUE - titleView.frame.size.width/2.0 - CGFloat( self.showArrow! ? self.arrowLeft!.image!.size.width : 0.0)
titleView.center = CGPointMake(self.navView!.center.x + (spacing * CGFloat(count)) - (CGFloat(self.currentPage) * spacing) , self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height)/2.0)
count++
}
self.viewConteiner?.contentSize = CGSizeMake(self.view.frame.size.width * CGFloat(count), self.view.frame.size.height - NAV_HEIGHT)
}
override func shouldAutorotate() -> Bool
{
return true;
}
// MARK: Methods Public
internal func addNewController(controller:UIViewController, title: AnyObject)
{
self.viewControllers?.addObject(controller);
if title.isKindOfClass(NSString)
{
var label = UILabel.new()
label.text = title as? String;
self.iconsMenu?.addObject(label);
self.includeControllerOnInterface(controller, titleView: label, tag: self.iconsMenu!.count - 1)
}
else if title.isKindOfClass(UIImage)
{
var image = UIImageView(image: title as? UIImage)
image.image = image.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
image.contentMode = UIViewContentMode.ScaleAspectFill
self.iconsMenu!.addObject(image)
self.includeControllerOnInterface(controller, titleView: image, tag: self.iconsMenu!.count - 1)
}
else
{
NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. NSString or UIImage Please!", userInfo:nil).raise()
}
self.viewDidLayoutSubviews()
self.resetNavBarConfig();
}
internal func setPosition(position: NSInteger, animated:Bool)
{
self.currentPage = position
self.viewConteiner?.setContentOffset(CGPointMake( CGFloat(self.currentPage!) * self.viewConteiner!.frame.size.width, self.viewConteiner!.contentOffset.y), animated: animated)
}
internal func goNextView()
{
if self.currentPage! < self.viewControllers!.count
{
self.setPosition(self.currentPage! + 1, animated: true)
}
}
internal func goPrevieusView()
{
if self.currentPage > 0
{
self.setPosition(self.currentPage! - 1, animated: true)
}
}
internal func resetNavBarConfig()
{
var count = 0;
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if(titleView.isKindOfClass(UIImageView))
{
titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor
}
else
{
if( titleView.isKindOfClass(UILabel))
{
var titleText = titleView as! UILabel
titleText.textColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor
titleText.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont
}
}
var transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax)
titleView.transform = CGAffineTransformMakeScale(transform!, transform!)
count++
}
self.arrowLeft!.alpha = (self.showArrow! ? (self.currentPage == 0 ? 0.0 : 1.0) :0.0);
self.arrowRight!.alpha = (self.showArrow! ? (self.currentPage == self.viewControllers!.count - 1 ? 0.0 : 1.0) :0.0);
self.arrowRight!.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor)
self.arrowLeft!.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor)
}
// MARK: Methods Private
private func inicializeValues(viewControllers: NSArray!, iconsMenu: NSArray!, position: NSInteger!)
{
var elementsController = NSMutableArray.new();
for controller in viewControllers
{
if controller.isKindOfClass(UIViewController)
{
var controller_element = controller as! UIViewController
controller_element.setAHPagingController(self)
elementsController.addObject(controller)
}
else
{
NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. Controller Please", userInfo:nil).raise()
}
}
var iconsController = NSMutableArray.new();
for icon in iconsMenu
{
if icon.isKindOfClass(NSString)
{
var label = UILabel.new()
label.text = icon as? String
iconsController.addObject(label)
}
else if(icon.isKindOfClass(UIImage))
{
var imageView = UIImageView(image: icon as? UIImage)
imageView.image = imageView.image!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
imageView.contentMode = UIViewContentMode.ScaleAspectFill
iconsController.addObject(imageView)
}
else
{
NSException(name:"ClassRequeredNotFoundException", reason:"Not Allowed Class. NSString or UIImage Please!", userInfo:nil).raise()
}
}
if(iconsController.count != elementsController.count)
{
NSException(name:"TitleAndControllersException", reason:"Title and controllers not match", userInfo:nil).raise()
}
self.bounce = true
self.fade = true
self.showArrow = true
self.transformScale = false
self.changeFont = true
self.changeColor = true
self.selectedColor = UIColor.blackColor()
self.dissectedColor = UIColor(red: 0.0 , green: 122.0/255.0, blue: 1.0, alpha: 1.0)
self.selectedFont = UIFont(name: "HelveticaNeue-Medium", size: 16)!
self.dissectedFont = UIFont(name: "HelveticaNeue", size: 16)!
self.currentPage = position
self.viewControllers = elementsController
self.iconsMenu = iconsController
self.scaleMax = 1.0
self.scaleMin = 0.9
}
private func includeControllerOnInterface(controller: UIViewController, titleView:UIView, tag:(NSInteger))
{
controller.view.clipsToBounds = true;
controller.view.frame = CGRectMake(self.viewConteiner!.contentSize.width, 0.0, self.view.frame.size.width, self.view.frame.size.height - NAV_HEIGHT)
self.viewConteiner?.contentSize = CGSizeMake(self.view.frame.size.width + self.viewConteiner!.contentSize.width, self.view.frame.size.height - NAV_HEIGHT)
self.addChildViewController(controller)
controller.didMoveToParentViewController(self)
self.viewConteiner?.addSubview(controller.view)
var tap = UITapGestureRecognizer(target:self, action:Selector("tapOnButton:"))
titleView.addGestureRecognizer(tap)
titleView.userInteractionEnabled = true;
titleView.tag = tag
self.navView?.addSubview(titleView);
}
func tapOnButton(sender: UITapGestureRecognizer)
{
if sender.view!.tag != self.currentPage
{
var frame = self.viewConteiner!.frame
frame.origin.y = 0;
frame.origin.x = frame.size.width * CGFloat(sender.view!.tag)
self.viewConteiner?.scrollRectToVisible(frame, animated:true)
}
}
private func changeColorFrom(fromColor: (UIColor), toColor: UIColor, porcent:(CGFloat)) ->UIColor
{
var redStart: CGFloat = 0
var greenStart : CGFloat = 0
var blueStart: CGFloat = 0
var alphaStart : CGFloat = 0
fromColor.getRed(&redStart, green: &greenStart, blue: &blueStart, alpha: &alphaStart)
var redFinish: CGFloat = 0
var greenFinish: CGFloat = 0
var blueFinish: CGFloat = 0
var alphaFinish: CGFloat = 0
toColor.getRed(&redFinish, green: &greenFinish, blue: &blueFinish, alpha: &alphaFinish)
return UIColor(red: (redStart - ((redStart-redFinish) * porcent)) , green: (greenStart - ((greenStart-greenFinish) * porcent)) , blue: (blueStart - ((blueStart-blueFinish) * porcent)) , alpha: (alphaStart - ((alphaStart-alphaFinish) * porcent)));
}
// MARK: Setters
internal func setBounce(bounce: Bool)
{
self.viewConteiner?.bounces = bounce;
self.bounce = bounce;
}
internal func setFade(fade: Bool)
{
self.fade = fade;
}
internal func setTransformScale(transformScale: Bool)
{
self.transformScale = transformScale
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
var transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax);
titleView.transform = CGAffineTransformMakeScale(transform, transform)
count++
}
}
}
internal func setShowArrow(showArrow: Bool)
{
self.showArrow = showArrow;
if (self.isViewLoaded() && self.view.window != nil)
{
UIView .animateWithDuration(0.3, animations: { () -> Void in
self.arrowLeft?.alpha = (self.showArrow! ? (self.currentPage == 0 ? 0.0 : 1.0) : 0.0)
self.arrowRight?.alpha = (self.showArrow! ? (self.currentPage == self.viewControllers!.count - 1 ? 0.0 : 1.0) :0.0)
self.viewDidLayoutSubviews()
})
}
}
internal func setChangeFont(changeFont:Bool)
{
self.changeFont = changeFont
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont
titleView.sizeToFit()
}
count++
}
}
}
internal func setChangeColor(changeColor: Bool)
{
self.changeColor = changeColor;
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UIImageView)
{
titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor
}
else if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor)
}
count++
}
self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
}
}
internal func setSelectColor(selectedColor: UIColor)
{
self.selectedColor = selectedColor
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UIImageView)
{
titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor
}
else if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor)
}
count++
}
self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
}
}
internal func setDissectColor(dissectedColor: UIColor)
{
self.dissectedColor = dissectedColor
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UIImageView)
{
titleView.tintColor = self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor
}
else if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.textColor = (self.changeColor! ? (count == self.currentPage ? self.selectedColor: self.dissectedColor) : self.selectedColor)
}
count++
}
self.arrowLeft?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
self.arrowRight?.tintColor = (self.changeColor! ? self.dissectedColor : self.selectedColor);
}
}
internal func setSelectFont(selectedFont: UIFont)
{
self.selectedFont = selectedFont
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont
titleView.sizeToFit()
}
count++
}
}
}
internal func setDissectFont(dissectedFont: UIFont)
{
self.dissectedFont = selectedFont
if (self.isViewLoaded() && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
if titleView.isKindOfClass(UILabel)
{
var title = titleView as! UILabel
title.font = self.changeFont! ? ( count == self.currentPage ? self.selectedFont : self.dissectedFont ) : self.selectedFont
titleView.sizeToFit()
}
count++
}
}
}
internal func setContentBackgroundColor(backgroundColor: UIColor)
{
self.viewConteiner?.backgroundColor = backgroundColor
}
internal func setNavBackgroundColor(backgroundColor: UIColor)
{
self.navView?.backgroundColor = backgroundColor
}
internal func setNavLineBackgroundColor(backgroundColor: UIColor)
{
self.navLine?.backgroundColor = backgroundColor
}
internal func setScaleMax(scaleMax: CGFloat, scaleMin:CGFloat)
{
if scaleMax < scaleMin || scaleMin < 0.0 || scaleMax < 0.0
{
return;
}
self.scaleMax = scaleMax;
self.scaleMin = scaleMin;
if (self.isViewLoaded() && self.transformScale == true && self.view.window != nil)
{
var count = 0
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
var transform = (self.transformScale! ? ( count == self.currentPage ? self.scaleMax: self.scaleMin): self.scaleMax);
titleView.transform = CGAffineTransformMakeScale(transform,transform)
if titleView.isKindOfClass(UILabel)
{
titleView.sizeToFit()
}
count++
}
}
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView)
{
if scrollView == self.viewConteiner
{
var xPosition = scrollView.contentOffset.x;
var fractionalPage = Float(xPosition / scrollView.frame.size.width);
var currentPage = Int(round(fractionalPage));
if fractionalPage == Float(currentPage) && currentPage != self.currentPage
{
self.delegate?.AHPagingMenuDidChangeMenuPosition?(self.currentPage, to: currentPage)
self.delegate?.AHPagingMenuDidChangeMenuFrom?(self.viewControllers!.objectAtIndex(self.currentPage), to: self.viewControllers!.objectAtIndex(currentPage))
self.currentPage = currentPage;
}
var porcent = fabs(fractionalPage - Float(currentPage))/0.5;
if self.showArrow!
{
if currentPage <= 0
{
self.arrowLeft?.alpha = 0;
self.arrowRight?.alpha = 1.0 - CGFloat(porcent);
}
else if currentPage >= self.iconsMenu!.count - 1
{
self.arrowLeft?.alpha = 1.0 - CGFloat(porcent);
self.arrowRight?.alpha = 0.0;
}
else
{
self.arrowLeft?.alpha = 1.0 - CGFloat(porcent);
self.arrowRight?.alpha = 1.0 - CGFloat(porcent);
}
}
else
{
self.arrowLeft?.alpha = 0;
self.arrowRight?.alpha = 0;
}
var count = 0;
for titleView in self.iconsMenu! as NSArray as! [UIView]
{
titleView.alpha = CGFloat (( self.fade! ? (count <= (currentPage + 1) && count >= (currentPage - 1) ? 1.3 - porcent : 0.0 ) : (count <= self.currentPage + 1 || count >= self.currentPage - 1 ? 1.0: 0.0)))
var spacing = (self.view.frame.size.width/2.0) - self.NAV_SPACE_VALUE - titleView.frame.size.width/2 - (self.showArrow! ? self.arrowLeft!.image!.size.width : 0.0)
titleView.center = CGPointMake(self.navView!.center.x + (spacing * CGFloat(count)) - (CGFloat(fractionalPage) * spacing), self.navView!.center.y + (UIApplication.sharedApplication().statusBarFrame.size.height/2.0))
var distance_center = CGFloat(fabs(titleView.center.x - self.navView!.center.x))
if titleView.isKindOfClass(UIImageView)
{
if( distance_center < spacing)
{
if self.changeColor!
{
titleView.tintColor = self.changeColorFrom(self.selectedColor, toColor: self.dissectedColor, porcent: distance_center/spacing)
}
}
}
else if titleView.isKindOfClass(UILabel)
{
var titleText = titleView as! UILabel;
if( distance_center < spacing)
{
if self.changeColor!
{
titleText.textColor = self.changeColorFrom(self.selectedColor, toColor: self.dissectedColor, porcent: distance_center/spacing)
}
if self.changeFont!
{
titleText.font = (distance_center < spacing/2.0 ? self.selectedFont : self.dissectedFont)
titleText.sizeToFit()
}
}
}
if (self.transformScale! && count <= (currentPage + 1) && count >= (currentPage - 1))
{
var transform = CGFloat(self.scaleMax! + ((self.scaleMax! - self.scaleMin!) * (-distance_center/spacing)))
titleView.transform = CGAffineTransformMakeScale(transform, transform);
}
count++;
}
}
}
}
| mit | 8149ea3c9f63563a332eaceddaa770b7 | 38.233509 | 254 | 0.573388 | 4.889674 | false | false | false | false |
Yalantis/PixPic | PixPic/External/Reachability.swift | 1 | 12613 | /*
Copyright (c) 2014, Ashley Mills
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Reachability.swift version 2.2beta2
import SystemConfiguration
import Foundation
public enum ReachabilityError: ErrorType {
case FailedToCreateWithAddress(sockaddr_in)
case FailedToCreateWithHostname(String)
case UnableToSetCallback
case UnableToSetDispatchQueue
}
public let reachabilityChangedNotification = "reachabilityChangedNotification"
func callback(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) {
let reachability = Unmanaged<Reachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
dispatch_async(dispatch_get_main_queue()) {
reachability.reachabilityChanged(flags)
}
}
public class Reachability: NSObject {
public typealias NetworkReachable = (Reachability) -> Void
public typealias NetworkUnreachable = (Reachability) -> Void
public enum NetworkStatus: CustomStringConvertible {
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
public var description: String {
switch self {
case .ReachableViaWWAN:
return "Cellular"
case .ReachableViaWiFi:
return "WiFi"
case .NotReachable:
return "No Connection"
}
}
}
// MARK: - *** Public properties ***
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUnreachable?
public var reachableOnWWAN: Bool
public var notificationCenter = NSNotificationCenter.defaultCenter()
public var currentReachabilityStatus: NetworkStatus {
if isReachable() {
if isReachableViaWiFi() {
return .ReachableViaWiFi
}
if isRunningOnDevice {
return .ReachableViaWWAN
}
}
return .NotReachable
}
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
private var previousFlags: SCNetworkReachabilityFlags?
// MARK: - *** Initialisation methods ***
required public init(reachabilityRef: SCNetworkReachability) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init(hostname: String) throws {
let nodename = (hostname as NSString).UTF8String
guard let ref = SCNetworkReachabilityCreateWithName(nil, nodename) else { throw ReachabilityError.FailedToCreateWithHostname(hostname) }
self.init(reachabilityRef: ref)
}
public static func reachabilityForInternetConnection() throws -> Reachability {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let ref = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { throw ReachabilityError.FailedToCreateWithAddress(zeroAddress) }
return Reachability(reachabilityRef: ref)
}
public static func reachabilityForLocalWiFi() throws -> Reachability {
var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
let address: UInt32 = 0xA9FE0000
localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian)
guard let ref = withUnsafePointer(&localWifiAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else { throw ReachabilityError.FailedToCreateWithAddress(localWifiAddress) }
return Reachability(reachabilityRef: ref)
}
// MARK: - *** Notifier methods ***
public func startNotifier() throws {
guard !notifierRunning else { return }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(reachabilityRef!, callback, &context) {
stopNotifier()
throw ReachabilityError.UnableToSetCallback
}
if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) {
stopNotifier()
throw ReachabilityError.UnableToSetDispatchQueue
}
// Perform an intial check
dispatch_async(reachabilitySerialQueue) { () -> Void in
let flags = self.reachabilityFlags
self.reachabilityChanged(flags)
}
notifierRunning = true
}
public func stopNotifier() {
defer { notifierRunning = false }
guard let reachabilityRef = reachabilityRef else { return }
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil)
}
// MARK: - *** Connection test methods ***
public func isReachable() -> Bool {
let flags = reachabilityFlags
return isReachableWithFlags(flags)
}
public func isReachableViaWWAN() -> Bool {
let flags = reachabilityFlags
// Check we're not on the simulator, we're REACHABLE and check we're on WWAN
return isRunningOnDevice && isReachable(flags) && isOnWWAN(flags)
}
public func isReachableViaWiFi() -> Bool {
let flags = reachabilityFlags
// Check we're reachable
if !isReachable(flags) {
return false
}
// Must be on WiFi if reachable but not on an iOS device (i.e. simulator)
if !isRunningOnDevice {
return true
}
// Check we're NOT on WWAN
return !isOnWWAN(flags)
}
// MARK: - *** Private methods ***
private var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
private var notifierRunning = false
private var reachabilityRef: SCNetworkReachability?
private let reachabilitySerialQueue = dispatch_queue_create("uk.co.ashleymills.reachability", DISPATCH_QUEUE_SERIAL)
private func reachabilityChanged(flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
if isReachableWithFlags(flags) {
if let block = whenReachable {
block(self)
}
} else {
if let block = whenUnreachable {
block(self)
}
}
notificationCenter.postNotificationName(reachabilityChangedNotification, object:self)
previousFlags = flags
}
private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool {
if !isReachable(flags) {
return false
}
if isConnectionRequiredOrTransient(flags) {
return false
}
if isRunningOnDevice {
if isOnWWAN(flags) && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
private func isConnectionRequired() -> Bool {
return connectionRequired()
}
private func connectionRequired() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags)
}
// Dynamic, on demand connection?
private func isConnectionOnDemand() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags) && isConnectionOnTrafficOrDemand(flags)
}
// Is user intervention required?
private func isInterventionRequired() -> Bool {
let flags = reachabilityFlags
return isConnectionRequired(flags) && isInterventionRequired(flags)
}
private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool {
#if os(iOS)
return flags.contains(.IsWWAN)
#else
return false
#endif
}
private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.Reachable)
}
private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionRequired)
}
private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.InterventionRequired)
}
private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionOnTraffic)
}
private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionOnDemand)
}
func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return !flags.intersect([.ConnectionOnTraffic, .ConnectionOnDemand]).isEmpty
}
private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.TransientConnection)
}
private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.IsLocalAddress)
}
private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.IsDirect)
}
private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool {
let testcase: SCNetworkReachabilityFlags = [.ConnectionRequired, .TransientConnection]
return flags.intersect(testcase) == testcase
}
private var reachabilityFlags: SCNetworkReachabilityFlags {
guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() }
var flags = SCNetworkReachabilityFlags()
let gotFlags = withUnsafeMutablePointer(&flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
} else {
return SCNetworkReachabilityFlags()
}
}
override public var description: String {
var W: String
if isRunningOnDevice {
W = isOnWWAN(reachabilityFlags) ? "W" : "-"
} else {
W = "X"
}
let R = isReachable(reachabilityFlags) ? "R" : "-"
let c = isConnectionRequired(reachabilityFlags) ? "c" : "-"
let t = isTransientConnection(reachabilityFlags) ? "t" : "-"
let i = isInterventionRequired(reachabilityFlags) ? "i" : "-"
let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-"
let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-"
let l = isLocalAddress(reachabilityFlags) ? "l" : "-"
let d = isDirect(reachabilityFlags) ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
| mit | d99dc0c3dee3187c3365853faea8f9a8 | 33.367847 | 196 | 0.670261 | 5.503054 | false | false | false | false |
EZ-NET/CodePiece | CodePieceCore/Data/Code.swift | 1 | 3654 | //
// Code.swift
// CodePiece
//
// Created by Tomohiro Kumagai on 2020/05/22.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Foundation
/// プログラムコードを保持するデータ型です。
public struct Code {
/// プログラムコードを行単位で保持します。各行は開業で終わります。
public var newlineTerminatedLines: Array<String>
/// プログラムコードを行単位のシーケンスで受け取って初期化します。
/// - Parameter lines: プログラムコードです。各行は改行で終わります。
public init<S: Sequence>(newlineTerminatedLines lines: S) where S.Element : StringProtocol {
newlineTerminatedLines = lines.map(String.init(_:))
}
}
extension Code : LosslessStringConvertible {
/// ソースコード文字列から初期化します。
/// - Parameter code: ソースコードです。
public init(_ code: String) {
newlineTerminatedLines = code.split(separator: "\n", omittingEmptySubsequences: false).map { $0 + "\n" }
}
/// コードが空だった時に `true` を返します。
public var isEmpty: Bool {
return newlineTerminatedLines.allSatisfy {
$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
}
/// コードを文字列で表現します。
public var description: String {
guard !isEmpty else {
return ""
}
return normalizedIndentation(of: newlineTerminatedLines).joined()
}
}
private extension Code {
/// いちばん低いインデントレベルをインデントなしとみなして、インデントを正規化します。
/// - Parameter lines: 正規化する対象のコードです。
/// - Returns: 正規化されたコードを返します。
func normalizedIndentation<T:Sequence>(of lines: T) -> [String] where T.Element == String {
/// ソースコードの各行で、いちばん冒頭のスペースが少ない行の冒頭スペース数を取得します。
/// - Parameter lines: 対象のソースコードです。
/// - Returns: いちばん少なかった冒頭のスペース数です。
func minimumCountOfSpace(_ lines: [String]) -> Int {
let emptyPattern = try! NSRegularExpression(pattern: ##"^\s*\n$"##)
let indentPattern = try! NSRegularExpression(pattern: ##"^( *)"##)
let counts = lines.compactMap { line -> Int? in
let lineRange = NSRange(location: 0, length: line.count)
guard emptyPattern.firstMatch(in: line, range: lineRange) == nil else {
return nil
}
guard let match = indentPattern.firstMatch(in: line, range: NSRange(location: 0, length: line.count)) else {
return nil
}
return match.range.length
}
return counts.min() ?? 0
}
/// 不必要なインデントを削除します。
/// - Parameters:
/// - lines: 対象のソースコードです。
/// - indentCount: 削除するインデントのスペース数です。
/// - Returns: 不必要なインデントを削除したソースコードです。
func trimmedIndentation(from lines: [String], indentCount: Int) -> [String] {
guard indentCount > 0 else {
return lines
}
let pattern = "^\(String(repeating: " ", count: indentCount))"
return lines.map { line in
return line.replacingOccurrences(of: pattern, with: "", options: .regularExpression, range: line.startIndex ..< line.endIndex)
}
}
let lines = lines.replacingTabToSpace(spacesPerTab: 4)
let indentCount = minimumCountOfSpace(lines)
return trimmedIndentation(from: lines, indentCount: indentCount)
}
}
| gpl-3.0 | b5bfbf41613b836f2ad2849d4a2bc3a9 | 24.025862 | 130 | 0.675164 | 2.980493 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/WPStyleGuide+Reader.swift | 1 | 13019 | import Foundation
import WordPressShared
/**
A WPStyleGuide extension with styles and methods specific to the
Reader feature.
*/
extension WPStyleGuide
{
// MARK: Original Post/Site Attribution Styles.
public class func originalAttributionParagraphAttributes() -> [String: AnyObject] {
let fontSize = originalAttributionFontSize()
let font = WPFontManager.systemRegularFontOfSize(fontSize)
let lineHeight:CGFloat = Cards.defaultLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName : paragraphStyle,
NSFontAttributeName : font,
NSForegroundColorAttributeName: grey(),
]
}
public class func siteAttributionParagraphAttributes() -> [String: AnyObject] {
let attributes = NSMutableDictionary(dictionary: originalAttributionParagraphAttributes())
attributes.setValue(mediumBlue(), forKey: NSForegroundColorAttributeName)
return NSDictionary(dictionary: attributes) as! [String: AnyObject]
}
public class func originalAttributionFontSize() -> CGFloat {
return Cards.contentFontSize
}
// MARK: - Reader Card Styles
// MARK: - Custom Colors
public class func readerCardCellBorderColor() -> UIColor {
return UIColor(red: 215.0/255.0, green: 227.0/255.0, blue: 235.0/255.0, alpha: 1.0)
}
public class func readerCardCellHighlightedBorderColor() -> UIColor {
// #87a6bc
return UIColor(red: 135/255.0, green: 166/255.0, blue: 188/255.0, alpha: 1.0)
}
// MARK: - Card Attributed Text Attributes
public class func readerCrossPostTitleAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.crossPostTitleFontSize
let font = WPFontManager.merriweatherBoldFontOfSize(fontSize)
let lineHeight = Cards.crossPostLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font,
NSForegroundColorAttributeName: darkGrey()
]
}
public class func readerCrossPostBoldSubtitleAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.crossPostSubtitleFontSize
let font = WPFontManager.systemBoldFontOfSize(fontSize)
let lineHeight = Cards.crossPostLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font,
NSForegroundColorAttributeName: grey()
]
}
public class func readerCrossPostSubtitleAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.crossPostSubtitleFontSize
let font = WPFontManager.systemRegularFontOfSize(fontSize)
let lineHeight = Cards.crossPostLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font,
NSForegroundColorAttributeName: grey()
]
}
public class func readerCardTitleAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.titleFontSize
let font = WPFontManager.merriweatherBoldFontOfSize(fontSize)
let lineHeight = Cards.titleLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font
]
}
public class func readerCardSummaryAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.contentFontSize
let font = WPFontManager.merriweatherRegularFontOfSize(fontSize)
let lineHeight = Cards.defaultLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font
]
}
public class func readerCardWordCountAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.buttonFontSize
let font = WPFontManager.systemRegularFontOfSize(fontSize)
let lineHeight = Cards.defaultLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font,
NSForegroundColorAttributeName: greyDarken10()
]
}
public class func readerCardReadingTimeAttributes() -> [NSObject: AnyObject] {
let fontSize:CGFloat = Cards.subtextFontSize
let font = WPFontManager.systemRegularFontOfSize(fontSize)
let lineHeight = Cards.defaultLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font,
NSForegroundColorAttributeName: greyDarken10()
]
}
// MARK: - Detail styles
public class func readerDetailTitleAttributes() -> [NSObject: AnyObject] {
let fontSize = Detail.titleFontSize
let font = WPFontManager.merriweatherBoldFontOfSize(fontSize)
let lineHeight = Detail.titleLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font
]
}
// MARK: - Stream Header Attributed Text Attributes
public class func readerStreamHeaderDescriptionAttributes() -> [NSObject: AnyObject] {
let fontSize = Cards.contentFontSize
let font = WPFontManager.merriweatherRegularFontOfSize(fontSize)
let lineHeight = Cards.defaultLineHeight
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.minimumLineHeight = lineHeight
paragraphStyle.maximumLineHeight = lineHeight
paragraphStyle.alignment = .Center
return [
NSParagraphStyleAttributeName: paragraphStyle,
NSFontAttributeName: font
]
}
// MARK: - Apply Card Styles
public class func applyReaderCardSiteButtonStyle(button:UIButton) {
let fontSize = Cards.buttonFontSize
button.titleLabel!.font = WPFontManager.systemRegularFontOfSize(fontSize)
button.setTitleColor(mediumBlue(), forState: .Normal)
button.setTitleColor(lightBlue(), forState: .Highlighted)
button.setTitleColor(darkGrey(), forState: .Disabled)
}
public class func applyReaderCardBylineLabelStyle(label:UILabel) {
let fontSize:CGFloat = Cards.subtextFontSize
label.font = WPFontManager.systemRegularFontOfSize(fontSize)
label.textColor = greyDarken10()
}
public class func applyReaderCardTitleLabelStyle(label:UILabel) {
label.textColor = darkGrey()
}
public class func applyReaderCardSummaryLabelStyle(label:UILabel) {
label.textColor = darkGrey()
}
public class func applyReaderCardTagButtonStyle(button:UIButton) {
let fontSize = Cards.buttonFontSize
button.setTitleColor(mediumBlue(), forState: .Normal)
button.setTitleColor(lightBlue(), forState: .Highlighted)
button.titleLabel?.font = WPFontManager.systemRegularFontOfSize(fontSize)
}
public class func applyReaderCardActionButtonStyle(button:UIButton) {
let fontSize = Cards.buttonFontSize
button.setTitleColor(greyDarken10(), forState: .Normal)
button.setTitleColor(lightBlue(), forState: .Highlighted)
button.setTitleColor(jazzyOrange(), forState: .Selected)
button.setTitleColor(greyDarken10(), forState: .Disabled)
button.titleLabel?.font = WPFontManager.systemRegularFontOfSize(fontSize)
}
// MARK: - Apply Stream Header Styles
public class func applyReaderStreamHeaderTitleStyle(label:UILabel) {
let fontSize:CGFloat = 14.0
label.font = WPFontManager.systemRegularFontOfSize(fontSize)
label.textColor = darkGrey()
}
public class func applyReaderStreamHeaderDetailStyle(label:UILabel) {
let fontSize:CGFloat = Cards.subtextFontSize
label.font = WPFontManager.systemRegularFontOfSize(fontSize)
label.textColor = greyDarken10()
}
public class func applyReaderStreamHeaderFollowingStyle(button:UIButton) {
let fontSize = Cards.buttonFontSize
let title = NSLocalizedString("Following", comment: "Gerund. A button label indicating the user is currently subscribed to a topic or site in ther eader. Tapping unsubscribes the user.")
button.setTitle(title, forState: .Normal)
button.setTitle(title, forState: .Highlighted)
button.setTitleColor(validGreen(), forState: .Normal)
button.setTitleColor(lightBlue(), forState: .Highlighted)
button.titleLabel?.font = WPFontManager.systemRegularFontOfSize(fontSize)
button.setImage(UIImage(named: "icon-reader-following"), forState: .Normal)
button.setImage(UIImage(named: "icon-reader-follow-highlight"), forState: .Highlighted)
}
public class func applyReaderStreamHeaderNotFollowingStyle(button:UIButton) {
let fontSize = Cards.buttonFontSize
let title = NSLocalizedString("Follow", comment: "Verb. A button label. Tapping subscribes the user to a topic or site in the reader")
button.setTitle(title, forState: .Normal)
button.setTitle(title, forState: .Highlighted)
button.setTitleColor(greyLighten10(), forState: .Normal)
button.setTitleColor(lightBlue(), forState: .Highlighted)
button.titleLabel?.font = WPFontManager.systemRegularFontOfSize(fontSize)
button.setImage(UIImage(named: "icon-reader-follow"), forState: .Normal)
button.setImage(UIImage(named: "icon-reader-follow-highlight"), forState: .Highlighted)
}
public class func applyReaderSiteStreamDescriptionStyle(label:UILabel) {
let fontSize = Cards.contentFontSize
label.font = WPFontManager.merriweatherRegularFontOfSize(fontSize)
label.textColor = darkGrey()
}
public class func applyReaderSiteStreamCountStyle(label:UILabel) {
let fontSize:CGFloat = 12.0
label.font = WPFontManager.systemRegularFontOfSize(fontSize)
label.textColor = grey()
}
// MARK: - Gap Marker Styles
public class func applyGapMarkerButtonStyle(button:UIButton) {
let normalImage = UIImage(color: WPStyleGuide.greyDarken10(), havingSize: button.bounds.size)
let highlightedImage = UIImage(color: WPStyleGuide.lightBlue(), havingSize: button.bounds.size)
button.setBackgroundImage(normalImage, forState: .Normal)
button.setBackgroundImage(highlightedImage, forState: .Highlighted)
button.titleLabel?.font = WPFontManager.systemSemiBoldFontOfSize(Cards.loadMoreButtonFontSize)
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
}
// MARK: - Metrics
public struct Cards
{
public static let defaultLineHeight:CGFloat = UIDevice.isPad() ? 26.0 : 22.0
public static let titleFontSize:CGFloat = UIDevice.isPad() ? 24.0 : 18.0
public static let titleLineHeight:CGFloat = UIDevice.isPad() ? 32.0 : 24.0
public static let contentFontSize:CGFloat = UIDevice.isPad() ? 16.0 : 14.0
public static let buttonFontSize:CGFloat = 14.0
public static let subtextFontSize:CGFloat = 12.0
public static let loadMoreButtonFontSize:CGFloat = 15.0
public static let crossPostTitleFontSize:CGFloat = 16.0
public static let crossPostSubtitleFontSize:CGFloat = 13.0
public static let crossPostLineHeight:CGFloat = 20.0
}
public struct Detail
{
public static let titleFontSize:CGFloat = UIDevice.isPad() ? 32.0 : 18.0
public static let titleLineHeight:CGFloat = UIDevice.isPad() ? 40.0 : 24.0
public static let contentFontSize:CGFloat = UIDevice.isPad() ? 16.0 : 14.0
}
}
| gpl-2.0 | 041f59fcf72b8bae14144f19cfe167d0 | 37.979042 | 194 | 0.702204 | 5.511854 | false | false | false | false |
grafiti-io/SwiftCharts | SwiftCharts/Layers/ChartStackedBarsLayer.swift | 1 | 7758 | //
// ChartStackedBarsLayer.swift
// Examples
//
// Created by ischuetz on 15/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public typealias ChartStackedBarItemModel = (quantity: Double, bgColor: UIColor)
open class ChartStackedBarModel: ChartBarModel {
let items: [ChartStackedBarItemModel]
public init(constant: ChartAxisValue, start: ChartAxisValue, items: [ChartStackedBarItemModel]) {
self.items = items
let axisValue2Scalar = items.reduce(start.scalar) {sum, item in
sum + item.quantity
}
let axisValue2 = start.copy(axisValue2Scalar)
super.init(constant: constant, axisValue1: start, axisValue2: axisValue2)
}
lazy var totalQuantity: Double = {
return self.items.reduce(0) {total, item in
total + item.quantity
}
}()
}
class ChartStackedBarsViewGenerator<T: ChartStackedBarModel>: ChartBarsViewGenerator<T, ChartPointViewBarStacked> {
fileprivate typealias FrameBuilder = (_ barModel: ChartStackedBarModel, _ item: ChartStackedBarItemModel, _ currentTotalQuantity: Double) -> (frame: ChartPointViewBarStackedFrame, length: CGFloat)
fileprivate let stackedViewGenerator: ChartStackedBarsLayer<ChartPointViewBarStacked>.ChartBarViewGenerator?
init(horizontal: Bool, layer: ChartCoordsSpaceLayer, barWidth: CGFloat, viewGenerator: ChartStackedBarsLayer<ChartPointViewBarStacked>.ChartBarViewGenerator? = nil) {
self.stackedViewGenerator = viewGenerator
super.init(horizontal: horizontal, layer: layer, barWidth: barWidth, viewGenerator: nil)
}
override func generateView(_ barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor? = nil, settings: ChartBarViewSettings, model: ChartBarModel, index: Int, groupIndex: Int, chart: Chart? = nil) -> ChartPointViewBarStacked {
let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel)
let frameBuilder: FrameBuilder = {
switch self.horizontal {
case true:
return {barModel, item, currentTotalQuantity in
let p0 = self.layer.modelLocToScreenLoc(x: currentTotalQuantity)
let p1 = self.layer.modelLocToScreenLoc(x: currentTotalQuantity + item.quantity)
let length = p1 - p0
let barLeftScreenLoc = self.layer.modelLocToScreenLoc(x: length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar)
return (frame: ChartPointViewBarStackedFrame(rect:
CGRect(
x: p0 - barLeftScreenLoc,
y: 0,
width: length,
height: self.barWidth), color: item.bgColor), length: length)
}
case false:
return {barModel, item, currentTotalQuantity in
let p0 = self.layer.modelLocToScreenLoc(y: currentTotalQuantity)
let p1 = self.layer.modelLocToScreenLoc(y: currentTotalQuantity + item.quantity)
let length = p1 - p0
let barTopScreenLoc = self.layer.modelLocToScreenLoc(y: length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar)
return (frame: ChartPointViewBarStackedFrame(rect:
CGRect(
x: 0,
y: p0 - barTopScreenLoc,
width: self.barWidth,
height: length), color: item.bgColor), length: length)
}
}
}()
let stackFrames = barModel.items.reduce((currentTotalQuantity: barModel.axisValue1.scalar, currentTotalLength: CGFloat(0), frames: Array<ChartPointViewBarStackedFrame>())) {tuple, item in
let frameWithLength = frameBuilder(barModel, item, tuple.currentTotalQuantity)
return (currentTotalQuantity: tuple.currentTotalQuantity + item.quantity, currentTotalLength: tuple.currentTotalLength + frameWithLength.length, frames: tuple.frames + [frameWithLength.frame])
}
let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLoc)
return stackedViewGenerator?(viewPoints.p1, viewPoints.p2, barWidth, barModel.bgColor, stackFrames.frames, settings, barModel, index) ??
ChartPointViewBarStacked(p1: viewPoints.p1, p2: viewPoints.p2, width: barWidth, bgColor: barModel.bgColor, stackFrames: stackFrames.frames, settings: settings)
}
}
public struct ChartTappedBarStacked {
public let model: ChartStackedBarModel
public let barView: ChartPointViewBarStacked
public let stackedItemModel: ChartStackedBarItemModel
public let stackedItemView: UIView
public let stackedItemViewFrameRelativeToBarParent: CGRect
public let stackedItemIndex: Int
public let layer: ChartCoordsSpaceLayer
}
open class ChartStackedBarsLayer<T: ChartPointViewBarStacked>: ChartCoordsSpaceLayer {
public typealias ChartBarViewGenerator = (_ p1: CGPoint, _ p2: CGPoint, _ width: CGFloat, _ bgColor: UIColor?, _ stackFrames: [ChartPointViewBarStackedFrame], _ settings: ChartBarViewSettings, _ model: ChartBarModel, _ index: Int) -> T
fileprivate let barModels: [ChartStackedBarModel]
fileprivate let horizontal: Bool
fileprivate let barWidth: CGFloat
fileprivate let settings: ChartBarViewSettings
fileprivate var barViews: [UIView] = []
fileprivate let stackFrameSelectionViewUpdater: ChartViewSelector?
fileprivate var tapHandler: ((ChartTappedBarStacked) -> Void)?
public init(xAxis: ChartAxis, yAxis: ChartAxis, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat, settings: ChartBarViewSettings, stackFrameSelectionViewUpdater: ChartViewSelector? = nil, tapHandler: ((ChartTappedBarStacked) -> Void)? = nil) {
self.barModels = barModels
self.horizontal = horizontal
self.barWidth = barWidth
self.settings = settings
self.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater
self.tapHandler = tapHandler
super.init(xAxis: xAxis, yAxis: yAxis)
}
open override func chartInitialized(chart: Chart) {
super.chartInitialized(chart: chart)
let barsGenerator = ChartStackedBarsViewGenerator(horizontal: horizontal, layer: self, barWidth: barWidth)
for (index, barModel) in barModels.enumerated() {
let barView = barsGenerator.generateView(barModel, settings: isTransform ? settings.copy(animDuration: 0, animDelay: 0) : settings, model: barModel, index: index, groupIndex: 0, chart: chart)
barView.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater
barView.stackedTapHandler = {[weak self] tappedStackedBar in guard let weakSelf = self else {return}
let stackFrameIndex = tappedStackedBar.stackFrame.index
let itemModel = barModel.items[stackFrameIndex]
let tappedStacked = ChartTappedBarStacked(model: barModel, barView: barView, stackedItemModel: itemModel, stackedItemView: tappedStackedBar.stackFrame.view, stackedItemViewFrameRelativeToBarParent: tappedStackedBar.stackFrame.viewFrameRelativeToBarSuperview, stackedItemIndex: stackFrameIndex, layer: weakSelf)
weakSelf.tapHandler?(tappedStacked)
}
barViews.append(barView)
chart.addSubview(barView)
}
}
}
| apache-2.0 | b2d2442f78e318bb9d52d4e2d27dbab4 | 50.72 | 327 | 0.675303 | 5.428971 | false | false | false | false |
GeminiSolutions/Places | Sources/Place.swift | 1 | 2582 | //
// Place.swift
// Places
//
// Copyright © 2017 Gemini Solutions. All rights reserved.
//
import Foundation
import DataStore
open class Place: DSContentJSONDictionary<String,Any> {
public typealias PlaceIdType = Int
public typealias JSONObjectType = [String:Any]
public var id: PlaceIdType?
public var lastUpdate: Date?
public var name: String? {
get {
return content["name"] as? String
}
set {
set(newValue, for: "name")
}
}
public var tags: [String]? {
get {
return content["tags"] as? [String]
}
set {
set(newValue, for: "tags")
}
}
public var latitude: Double? {
get {
return content["latitude"] as? Double
}
set {
set(newValue, for: "latitude")
}
}
public var longitude: Double? {
get {
return content["longitude"] as? Double
}
set {
set(newValue, for: "longitude")
}
}
public var coordinate: PlaceCoordinate2D? {
get {
guard let latitude = self.latitude, let longitude = self.longitude else { return nil }
return PlaceCoordinate2D(latitude, longitude)
}
set {
self.latitude = newValue?.latitude
self.longitude = newValue?.longitude
}
}
override public required init() {
super.init()
}
public required init?(content: JSONObjectType) {
guard Place.validate(content) else { return nil }
super.init(json: content)
}
class public func placeIdFromString(_ string: String) -> PlaceIdType? {
return PlaceIdType(string)
}
class public func stringFromPlaceId(_ placeId: PlaceIdType) -> String {
return String(placeId)
}
class open func validate(_ json: JSONObjectType) -> Bool {
guard json.keys.contains("name") else { return false }
guard json.keys.contains("latitude") else { return false }
guard json.keys.contains("longitude") else { return false }
return true
}
class open var Fields: [[String:Any]] {
return [["name":"name", "label": "Name", "type":"String", "required":"true"],
["name":"tags", "label": "Tags", "type":"Array<String>", "required":"false"],
["name":"latitude", "label" :"Latitude", "type":"Double", "required":"true"],
["name":"longitude", "label": "Longitude", "type":"Double", "required":"true"]]
}
}
| mit | 32dae28e1f7fb132eb162716bd711fc5 | 26.168421 | 98 | 0.555986 | 4.45 | false | false | false | false |
gkaimakas/ReactiveBluetooth | ReactiveBluetooth/Classes/CBCentralManager/CBCentralManager+DelegateEvent.swift | 1 | 3685 | //
// CBCentralManager+DelegateEvent.swift
// FBSnapshotTestCase
//
// Created by George Kaimakas on 02/03/2018.
//
import CoreBluetooth
import Result
extension CBCentralManager {
internal enum DelegateEvent {
case didUpdateState(central: CBCentralManager)
case willRestoreState(central: CBCentralManager, dict: [String: Any])
case didDiscover(central: CBCentralManager, peripheral: CBPeripheral, advertismentData: Set<CBPeripheral.AdvertismentData>, RSSI: NSNumber)
case didConnect(central: CBCentralManager, peripheral: CBPeripheral, error: Error?)
case didDisconnect(central: CBCentralManager, peripheral: CBPeripheral, error: Error?)
func filter(central: CBCentralManager) -> Bool {
switch self {
case .didUpdateState(central: let _central):
return central == _central
case .willRestoreState(central: let _central, dict: _):
return central == _central
case .didDiscover(central: let _central, peripheral: _, advertismentData: _, RSSI: _):
return central == _central
case .didConnect(central: let _central, peripheral: _, error: _):
return central == _central
case .didDisconnect(central: let _central, peripheral: _, error: _):
return central == _central
}
}
func filter(peripheral: CBPeripheral) -> Bool {
return filter(peripheral: peripheral.identifier)
}
func filter(peripheral identifier: UUID) -> Bool {
switch self {
case .didUpdateState(central: _),
.willRestoreState(central: _, dict: _):
return false
case .didDiscover(central: _, peripheral: let _peripheral, advertismentData: _, RSSI: _):
return identifier.uuidString == _peripheral.identifier.uuidString
case .didConnect(central: _, peripheral: let _peripheral, error: _):
return identifier.uuidString == _peripheral.identifier.uuidString
case .didDisconnect(central: _, peripheral: let _peripheral, error: _):
return identifier.uuidString == _peripheral.identifier.uuidString
}
}
var didUpdateState: CBCentralManager? {
switch self {
case .didUpdateState(let central): return central
default: return nil
}
}
var willRestoreState: [String: Any]? {
switch self {
case .willRestoreState(_ , let dict): return dict
default: return nil
}
}
var didDiscoverPeripheral: (peripheral: CBPeripheral, advertismentData: Set<CBPeripheral.AdvertismentData>, RSSI: NSNumber)? {
switch self {
case .didDiscover(_ , let peripheral, let advertismentData, let RSSI):
return (peripheral: peripheral, advertismentData: advertismentData, RSSI: RSSI)
default:
return nil
}
}
var didConnect: (peripheral: CBPeripheral, error:Error?)? {
switch self {
case .didConnect(central: _, let peripheral, let error):
return (peripheral: peripheral, error: error)
default:
return nil
}
}
var didDisconnect: (peripheral: CBPeripheral, error:Error?)? {
switch self {
case .didDisconnect(central: _, let peripheral, let error):
return (peripheral: peripheral, error: error)
default:
return nil
}
}
}
}
| mit | 3c7f0a2164d49991fa0cfbeb1ae6748c | 38.623656 | 147 | 0.589417 | 5.427099 | false | true | false | false |
alexmx/Insider | Insider/Insider.swift | 1 | 9627 | //
// Insider.swift
// Insider
//
// Created by Alexandru Maimescu on 2/16/16.
// Copyright © 2016 Alex Maimescu. All rights reserved.
//
import Foundation
public typealias InsiderMessage = [NSObject: AnyObject]
/// The Insider delegate protocol.
@objc
public protocol InsiderDelegate: AnyObject {
/**
This method will be called on delegate for "send" command
- parameter insider: instance of Insider class
- parameter params: request params
*/
@objc(insider:didReceiveRemoteMessage:)
optional func insider(_ insider: Insider, didReceiveRemote message: InsiderMessage?)
/**
This method will be called on delegate for "sendAndWaitForResponse" command
- parameter insider: instance of Insider class
- parameter params: request params
- returns: return params
*/
@objc(insider:returnResponseMessageForRemoteMessage:)
optional func insider(_ insider: Insider, returnResponseMessageForRemote message: InsiderMessage?) -> InsiderMessage?
/**
This method will be called on delegate for "notification" command
- parameter insider: instance of Insider class
- parameter params: request params sent in notification
*/
@objc(insider:didSendNotificationWithMessage:)
optional func insider(_ insider: Insider, didSendNotificationWith message: InsiderMessage?)
/**
This method will be called on delegate for "systemInfo" command
- parameter insider: instance of Insider class
- parameter systemInfo: returned system information
*/
@objc(insider:didReturnSystemInfo:)
optional func insider(_ insider: Insider, didReturn systemInfo: InsiderMessage?)
/**
This method is caled when a new directory is created in sandbox
- parameter insider: instance of Insider class
- parameter path: path to the new created directory
*/
@objc(insider:didCreateDirectoryAtPath:)
optional func insider(_ insider: Insider, didCreateDirectoryAt path: String)
/**
This method is called when an item is removed from sandbox
- parameter insider: instance of Insider class
- parameter path: path of the removed item
*/
@objc(insider:didDeleteItemAtPath:)
optional func insider(_ insider: Insider, didDeleteItemAt path: String)
/**
This method is called when an item is downloaded from sandbox
- parameter insider: instance of Insider class
- parameter path: path to the downloaded item
*/
@objc(insider:didDownloadFileAtPath:)
optional func insider(_ insider: Insider, didDownloadFileAt path: String)
/**
This method is called when an item is moved in sandbox
- parameter insider: instance of Insider class
- parameter fromPath: initial path to the item
- parameter toPath: path to the item after it was moved
*/
@objc(insider:didMoveItemFromPath:toPath:)
optional func insider(_ insider: Insider, didMoveItem fromPath: String, to path: String)
/**
This method is called when an item is uploaded to sandbox
- parameter insider: instance of Insider class
- parameter path: path to the uploaded item
*/
@objc(insider:didUploadFileAtPath:)
optional func insider(_ insider: Insider, didUploadFileAt path: String)
}
/// The Insider API facade class.
@objcMembers
final public class Insider: NSObject {
private struct Endpoints {
static let sendMessage = "/send"
static let sendMessageAndWaitForResponse = "/sendAndWaitForResponse"
static let sendNotification = "/notification"
static let systemInfo = "/systemInfo"
static let documents = "/documents"
static let library = "/library"
static let tmp = "/tmp"
}
/// The shared instance.
public static let shared = Insider()
/// The Insider delegate.
public weak var delegate: InsiderDelegate?
/// The Insider notification key.
public static let insiderNotificationKey = "com.insider.insiderNotificationKey"
private lazy var deviceInfoService = DeviceInfoService()
private let localWebServer = LocalWebServer()
// MARK: - Public methods
/**
Start the local web server which will listen for commands.
By default server listens on port 8080.
*/
public func start() {
addHandlersForServer(localWebServer)
localWebServer.start()
}
/**
Start the local web server which will listen for commands, for given delegate.
By default server listens on port 8080.
- parameter delegate: Insider delegate reference
*/
public func start(withDelegate delegate: InsiderDelegate?) {
self.delegate = delegate
start()
}
/// Start the local web server which will listen for commands, for given delegate and port number.
///
/// - Parameters:
/// - delegate: The Insider delegate reference.
/// - port: the port on which local webserver will listen for commands.
public func start(withDelegate delegate: InsiderDelegate?, port: UInt) {
self.delegate = delegate
addHandlersForServer(localWebServer)
localWebServer.startWithPort(port)
}
/**
Stop the local web server.
*/
public func stop() {
localWebServer.stop()
}
// MARK: - Private methods
private func addHandlersForServer(_ server: LocalWebServer) {
server.delegate = self
// Add sandbox access handlers
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
server.addSandboxDirectory(documentsPath!, endpoint: Endpoints.documents)
let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first
server.addSandboxDirectory(libraryPath!, endpoint: Endpoints.library)
let tmpPath = NSTemporaryDirectory()
server.addSandboxDirectory(tmpPath, endpoint: Endpoints.tmp)
// Invoke method on delegate
server.addHandlerForMethod(.POST, path: Endpoints.sendMessage) { (requestParams) -> (LocalWebServerResponse) in
let didProcessParams = self.didReceiveRemoteMessage(requestParams)
return LocalWebServerResponse(statusCode: (didProcessParams) ? .success : .notFound)
}
// Invoke method on delegate and wait for return value
server.addHandlerForMethod(.POST, path: Endpoints.sendMessageAndWaitForResponse) { (requestParams) -> (LocalWebServerResponse) in
let response = self.returnResponseMessageForRemoteMesssage(requestParams)
if let response = response {
return LocalWebServerResponse(response: response)
} else {
return LocalWebServerResponse(statusCode: .notFound)
}
}
// Send a local notification
server.addHandlerForMethod(.POST, path: Endpoints.sendNotification) { (requestParams) -> (LocalWebServerResponse) in
self.sendLocalNotificationWithParams(requestParams)
return LocalWebServerResponse(statusCode: .success)
}
server.addHandlerForMethod(.GET, path: Endpoints.systemInfo) { _ in
return LocalWebServerResponse(response: self.getSystemInfo())
}
}
private func didReceiveRemoteMessage(_ message: InsiderMessage?) -> Bool {
guard let delegate = delegate else {
print("[Insider] Warning: Delegate not set.")
return false
}
delegate.insider?(self, didReceiveRemote: message)
return true
}
private func returnResponseMessageForRemoteMesssage(_ message: InsiderMessage?) -> InsiderMessage? {
guard let delegate = delegate else {
print("[Insider] Warning: Delegate not set.")
return nil
}
return delegate.insider?(self, returnResponseMessageForRemote: message)
}
private func sendLocalNotificationWithParams(_ params: InsiderMessage?) {
defer {
delegate?.insider?(self, didSendNotificationWith: params)
}
NotificationCenter.default.post(name: Notification.Name(rawValue: Insider.insiderNotificationKey), object: params)
}
private func getSystemInfo() -> InsiderMessage? {
let systemInfo = self.deviceInfoService.allSystemInfo
defer {
delegate?.insider?(self, didReturn: systemInfo)
}
return systemInfo
}
}
extension Insider: LocalWebServerDelegate {
func localWebServer(_ server: LocalWebServer, didCreateDirectoryAtPath path: String) {
delegate?.insider?(self, didCreateDirectoryAt: path)
}
func localWebServer(_ server: LocalWebServer, didDeleteItemAtPath path: String) {
delegate?.insider?(self, didDeleteItemAt: path)
}
func localWebServer(_ server: LocalWebServer, didDownloadFileAtPath path: String) {
delegate?.insider?(self, didDownloadFileAt: path)
}
func localWebServer(_ server: LocalWebServer, didMoveItemFromPath fromPath: String, toPath: String) {
delegate?.insider?(self, didMoveItem: fromPath, to: toPath)
}
func localWebServer(_ server: LocalWebServer, didUploadFileAtPath path: String) {
delegate?.insider?(self, didUploadFileAt: path)
}
}
| mit | f61f96c98f41b20504c5962deb5b12e4 | 34.520295 | 137 | 0.666944 | 4.992739 | false | false | false | false |
milseman/swift | stdlib/public/core/StringBridge.swift | 9 | 10949 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
#if _runtime(_ObjC)
// Swift's String bridges NSString via this protocol and these
// variables, allowing the core stdlib to remain decoupled from
// Foundation.
/// Effectively an untyped NSString that doesn't require foundation.
public typealias _CocoaString = AnyObject
public // @testable
func _stdlib_binary_CFStringCreateCopy(
_ source: _CocoaString
) -> _CocoaString {
let result = _swift_stdlib_CFStringCreateCopy(nil, source) as AnyObject
return result
}
public // @testable
func _stdlib_binary_CFStringGetLength(
_ source: _CocoaString
) -> Int {
return _swift_stdlib_CFStringGetLength(source)
}
public // @testable
func _stdlib_binary_CFStringGetCharactersPtr(
_ source: _CocoaString
) -> UnsafeMutablePointer<UTF16.CodeUnit>? {
return UnsafeMutablePointer(mutating: _swift_stdlib_CFStringGetCharactersPtr(source))
}
/// Bridges `source` to `Swift.String`, assuming that `source` has non-ASCII
/// characters (does not apply ASCII optimizations).
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
func _cocoaStringToSwiftString_NonASCII(
_ source: _CocoaString
) -> String {
let cfImmutableValue = _stdlib_binary_CFStringCreateCopy(source)
let length = _stdlib_binary_CFStringGetLength(cfImmutableValue)
let start = _stdlib_binary_CFStringGetCharactersPtr(cfImmutableValue)
return String(_StringCore(
baseAddress: start,
count: length,
elementShift: 1,
hasCocoaBuffer: true,
owner: unsafeBitCast(cfImmutableValue, to: Optional<AnyObject>.self)))
}
/// Loading Foundation initializes these function variables
/// with useful values
/// Produces a `_StringBuffer` from a given subrange of a source
/// `_CocoaString`, having the given minimum capacity.
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringToContiguous(
source: _CocoaString, range: Range<Int>, minimumCapacity: Int
) -> _StringBuffer {
_sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(source) == nil,
"Known contiguously stored strings should already be converted to Swift")
let startIndex = range.lowerBound
let count = range.upperBound - startIndex
let buffer = _StringBuffer(capacity: max(count, minimumCapacity),
initialSize: count, elementWidth: 2)
_swift_stdlib_CFStringGetCharacters(
source, _swift_shims_CFRange(location: startIndex, length: count),
buffer.start.assumingMemoryBound(to: _swift_shims_UniChar.self))
return buffer
}
/// Reads the entire contents of a _CocoaString into contiguous
/// storage of sufficient capacity.
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringReadAll(
_ source: _CocoaString, _ destination: UnsafeMutablePointer<UTF16.CodeUnit>
) {
_swift_stdlib_CFStringGetCharacters(
source, _swift_shims_CFRange(
location: 0, length: _swift_stdlib_CFStringGetLength(source)), destination)
}
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringSlice(
_ target: _StringCore, _ bounds: Range<Int>
) -> _StringCore {
_sanityCheck(target.hasCocoaBuffer)
let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped
_sanityCheck(
_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
let cfResult = _swift_stdlib_CFStringCreateWithSubstring(
nil, cfSelf, _swift_shims_CFRange(
location: bounds.lowerBound, length: bounds.count)) as AnyObject
return String(_cocoaString: cfResult)._core
}
@_versioned
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
internal func _cocoaStringSubscript(
_ target: _StringCore, _ position: Int
) -> UTF16.CodeUnit {
let cfSelf: _swift_shims_CFStringRef = target.cocoaBuffer.unsafelyUnwrapped
_sanityCheck(_swift_stdlib_CFStringGetCharactersPtr(cfSelf) == nil,
"Known contiguously stored strings should already be converted to Swift")
return _swift_stdlib_CFStringGetCharacterAtIndex(cfSelf, position)
}
//
// Conversion from NSString to Swift's native representation
//
internal var kCFStringEncodingASCII : _swift_shims_CFStringEncoding {
return 0x0600
}
extension String {
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
public // SPI(Foundation)
init(_cocoaString: AnyObject) {
if let wrapped = _cocoaString as? _NSContiguousString {
self._core = wrapped._core
return
}
// "copy" it into a value to be sure nobody will modify behind
// our backs. In practice, when value is already immutable, this
// just does a retain.
let cfImmutableValue
= _stdlib_binary_CFStringCreateCopy(_cocoaString) as AnyObject
let length = _swift_stdlib_CFStringGetLength(cfImmutableValue)
// Look first for null-terminated ASCII
// Note: the code in clownfish appears to guarantee
// nul-termination, but I'm waiting for an answer from Chris Kane
// about whether we can count on it for all time or not.
let nulTerminatedASCII = _swift_stdlib_CFStringGetCStringPtr(
cfImmutableValue, kCFStringEncodingASCII)
// start will hold the base pointer of contiguous storage, if it
// is found.
var start: UnsafeMutableRawPointer?
let isUTF16 = (nulTerminatedASCII == nil)
if isUTF16 {
let utf16Buf = _swift_stdlib_CFStringGetCharactersPtr(cfImmutableValue)
start = UnsafeMutableRawPointer(mutating: utf16Buf)
} else {
start = UnsafeMutableRawPointer(mutating: nulTerminatedASCII)
}
self._core = _StringCore(
baseAddress: start,
count: length,
elementShift: isUTF16 ? 1 : 0,
hasCocoaBuffer: true,
owner: cfImmutableValue)
}
}
// At runtime, this class is derived from `_SwiftNativeNSStringBase`,
// which is derived from `NSString`.
//
// The @_swift_native_objc_runtime_base attribute
// This allows us to subclass an Objective-C class and use the fast Swift
// memory allocator.
@objc @_swift_native_objc_runtime_base(_SwiftNativeNSStringBase)
public class _SwiftNativeNSString {}
@objc
public protocol _NSStringCore :
_NSCopying, _NSFastEnumeration {
// The following methods should be overridden when implementing an
// NSString subclass.
func length() -> Int
func characterAtIndex(_ index: Int) -> UInt16
// We also override the following methods for efficiency.
}
/// An `NSString` built around a slice of contiguous Swift `String` storage.
public final class _NSContiguousString : _SwiftNativeNSString {
public init(_ _core: _StringCore) {
_sanityCheck(
_core.hasContiguousStorage,
"_NSContiguousString requires contiguous storage")
self._core = _core
super.init()
}
@objc
init(coder aDecoder: AnyObject) {
_sanityCheckFailure("init(coder:) not implemented for _NSContiguousString")
}
@objc
func length() -> Int {
return _core.count
}
@objc
func characterAtIndex(_ index: Int) -> UInt16 {
return _core[index]
}
@objc @inline(__always) // Performance: To save on reference count operations.
func getCharacters(
_ buffer: UnsafeMutablePointer<UInt16>,
range aRange: _SwiftNSRange) {
_precondition(aRange.location + aRange.length <= Int(_core.count))
if _core.elementWidth == 2 {
UTF16._copy(
source: _core.startUTF16 + aRange.location,
destination: UnsafeMutablePointer<UInt16>(buffer),
count: aRange.length)
}
else {
UTF16._copy(
source: _core.startASCII + aRange.location,
destination: UnsafeMutablePointer<UInt16>(buffer),
count: aRange.length)
}
}
@objc
func _fastCharacterContents() -> UnsafeMutablePointer<UInt16>? {
return _core.elementWidth == 2 ? _core.startUTF16 : nil
}
//
// Implement sub-slicing without adding layers of wrapping
//
@objc func substringFromIndex(_ start: Int) -> _NSContiguousString {
return _NSContiguousString(_core[Int(start)..<Int(_core.count)])
}
@objc func substringToIndex(_ end: Int) -> _NSContiguousString {
return _NSContiguousString(_core[0..<Int(end)])
}
@objc func substringWithRange(_ aRange: _SwiftNSRange) -> _NSContiguousString {
return _NSContiguousString(
_core[Int(aRange.location)..<Int(aRange.location + aRange.length)])
}
@objc func copy() -> AnyObject {
// Since this string is immutable we can just return ourselves.
return self
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape the object referenced by the opaque pointer passed to it or
/// anything transitively reachable form this object. Doing so
/// will result in undefined behavior.
@_semantics("self_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointer<Result>(
_ body: (OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
defer {
_fixLifetime(self)
}
return try body(selfAsPointer)
}
/// The caller of this function guarantees that the closure 'body' does not
/// escape either object referenced by the opaque pointer pair passed to it or
/// transitively reachable objects. Doing so will result in undefined
/// behavior.
@_semantics("pair_no_escaping_closure")
func _unsafeWithNotEscapedSelfPointerPair<Result>(
_ rhs: _NSContiguousString,
_ body: (OpaquePointer, OpaquePointer) throws -> Result
) rethrows -> Result {
let selfAsPointer = unsafeBitCast(self, to: OpaquePointer.self)
let rhsAsPointer = unsafeBitCast(rhs, to: OpaquePointer.self)
defer {
_fixLifetime(self)
_fixLifetime(rhs)
}
return try body(selfAsPointer, rhsAsPointer)
}
public let _core: _StringCore
}
extension String {
/// Same as `_bridgeToObjectiveC()`, but located inside the core standard
/// library.
public func _stdlib_binary_bridgeToObjectiveCImpl() -> AnyObject {
if let ns = _core.cocoaBuffer,
_swift_stdlib_CFStringGetLength(ns) == _core.count {
return ns
}
_sanityCheck(_core.hasContiguousStorage)
return _NSContiguousString(_core)
}
@inline(never) @_semantics("stdlib_binary_only") // Hide the CF dependency
public func _bridgeToObjectiveCImpl() -> AnyObject {
return _stdlib_binary_bridgeToObjectiveCImpl()
}
}
#endif
| apache-2.0 | 8bdf4cb28abd99bc88478ed710f6f270 | 32.07855 | 87 | 0.707279 | 4.543154 | false | false | false | false |
heitortsergent/KeenClient-iOS | KeenSwiftClientExample/KeenSwiftClientExample/ThirdViewController.swift | 1 | 4316 | //
// ThirdViewController.swift
// KeenSwiftClientExample
//
// Created by Heitor Sergent on 6/30/15.
// Copyright (c) 2015 Keen.IO. All rights reserved.
//
import UIKit
@objc(ThirdViewController) class ThirdViewController: UIViewController {
@IBOutlet weak var resultTextView: UITextView!;
@IBAction func sendQueryButtonPressed(sender: AnyObject) {
let countQueryCompleted = { (responseData: NSData!, returningResponse: NSURLResponse!, error: NSError!) -> Void in
do {
let responseDictionary: NSDictionary? = try NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary;
NSLog("response: %@", responseDictionary!);
if error != nil {
self.resultTextView.text = "Error! 😞 \n\n error: \(error.localizedDescription)";
} else if let errorCode = responseDictionary!.objectForKey("error_code"),
errorMessage = responseDictionary!.objectForKey("message") as? String {
self.resultTextView.text = "Failure! 😞 \n\n error code: \(errorCode)\n\n message: \(errorMessage)";
} else {
let result: NSNumber = responseDictionary!.objectForKey("result") as! NSNumber;
NSLog("result: %@", result);
// Get result value when querying with group_by property
//var resultArray: NSArray = responseDictionary!.objectForKey("result") as! NSArray;
//var resultDictionary: NSDictionary = resultArray[0] as! NSDictionary;
//var resultValue: NSNumber = resultDictionary.objectForKey("result") as! NSNumber;
//NSLog("resultValue: %@", resultValue);
self.resultTextView.text = "Success! 😄 \n\n response: \(responseDictionary!.description)";
}
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
}
// Async querying
let countQuery: KIOQuery = KIOQuery(query:"count", andPropertiesDictionary:["event_collection": "tab_views", "timeframe": "this_7_days"]);
KeenClient.sharedClient().runAsyncQuery(countQuery, block: countQueryCompleted);
// Multi-analysis querying example
/*
var countUniqueQuery: KIOQuery = KIOQuery(query:"count_unique", andPropertiesDictionary:["event_collection": "collection", "target_property": "key", "timeframe": "this_7_days"]);
countQuery.queryName = "count_query";
countUniqueQuery.queryName = "count_unique_query";
KeenClient.sharedClient().runAsyncMultiAnalysisWithQueries([countQuery, countUniqueQuery], block: countQueryCompleted);
*/
// Funnel example
/*
var funnelQuery: KIOQuery = KIOQuery(query:"funnel", andPropertiesDictionary:["timeframe": "this_7_days", "steps": [["event_collection": "user_signed_up", @"actor_property": "user.id"], ["event_collection": "user_completed_profile", "actor_property": "user.id"]]]);
KeenClient.sharedClient().runAsyncQuery(funnelQuery, block: countQueryCompleted);
*/
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated);
let theEvent = ["view_name": "third view Swift", "action": "going to"];
do {
try KeenClient.sharedClient().addEvent(theEvent, toEventCollection: "tab_views")
} catch _ {
};
}
override func viewWillDisappear(animated : Bool) {
super.viewWillDisappear(animated);
let theEvent = ["view_name" : "third view Swift", "action" : "leaving from"];
do {
try KeenClient.sharedClient().addEvent(theEvent, toEventCollection: "tab_views")
} catch _ {
};
}
}
| mit | b5d274cd73993f7f853430dd79be0f52 | 42.94898 | 273 | 0.596935 | 5.055164 | false | false | false | false |
mohamede1945/quran-ios | Quran/GaplessAudioPlayerInteractor.swift | 2 | 2436 | //
// GaplessAudioPlayerInteractor.swift
// Quran
//
// Created by Mohamed Afifi on 5/14/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import Zip
class GaplessAudioPlayerInteractor: DefaultAudioPlayerInteractor {
weak var delegate: AudioPlayerInteractorDelegate?
let downloader: AudioFilesDownloader
let player: AudioPlayer
let lastAyahFinder: LastAyahFinder
var downloadCancelled: Bool = false
init(downloader: AudioFilesDownloader, lastAyahFinder: LastAyahFinder, player: AudioPlayer) {
self.downloader = downloader
self.lastAyahFinder = lastAyahFinder
self.player = player
self.player.delegate = self
}
func prePlayOperation(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber, completion: @escaping () -> Void) {
guard case .gapless(let databaseName) = qari.audioType else {
fatalError("Unsupported qari type gapped")
}
let baseFileName = qari.localFolder().appendingPathComponent(databaseName)
let dbFile = baseFileName.appendingPathExtension(Files.databaseLocalFileExtension)
let zipFile = baseFileName.appendingPathExtension(Files.databaseRemoteFileExtension)
guard !dbFile.isReachable else {
completion()
return
}
Queue.background.async {
do {
try Zip.unzipFile(zipFile, destination: qari.localFolder(), overwrite: true, password: nil, progress: nil)
} catch {
Crash.recordError(error, reason: "Cannot unzip file '\(zipFile)' to '\(qari.localFolder())'")
// delete the zip and try to re-download it again, next time.
try? FileManager.default.removeItem(at: zipFile)
}
Queue.main.async {
completion()
}
}
}
}
| gpl-3.0 | 61fecc55252ff2fac2644f13c2475297 | 33.8 | 122 | 0.673235 | 4.785855 | false | false | false | false |
material-components/material-components-ios-codelabs | MDC-104/Swift/Starter/Shrine/Shrine/ApplicationScheme.swift | 1 | 2742 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents
class ApplicationScheme: NSObject {
private static var singleton = ApplicationScheme()
static var shared: ApplicationScheme {
return singleton
}
override init() {
self.buttonScheme.colorScheme = self.colorScheme
self.buttonScheme.typographyScheme = self.typographyScheme
super.init()
}
public let buttonScheme = MDCButtonScheme()
public let colorScheme: MDCColorScheming = {
let scheme = MDCSemanticColorScheme(defaults: .material201804)
scheme.primaryColor =
UIColor(red: 252.0/255.0, green: 184.0/255.0, blue: 171.0/255.0, alpha: 1.0)
scheme.primaryColorVariant =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.onPrimaryColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.secondaryColor =
UIColor(red: 254.0/255.0, green: 234.0/255.0, blue: 230.0/255.0, alpha: 1.0)
scheme.onSecondaryColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.surfaceColor =
UIColor(red: 255.0/255.0, green: 251.0/255.0, blue: 250.0/255.0, alpha: 1.0)
scheme.onSurfaceColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.backgroundColor =
UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
scheme.onBackgroundColor =
UIColor(red: 68.0/255.0, green: 44.0/255.0, blue: 46.0/255.0, alpha: 1.0)
scheme.errorColor =
UIColor(red: 197.0/255.0, green: 3.0/255.0, blue: 43.0/255.0, alpha: 1.0)
return scheme
}()
public let typographyScheme: MDCTypographyScheming = {
let scheme = MDCTypographyScheme()
let fontName = "Rubik"
scheme.headline5 = UIFont(name: fontName, size: 24)!
scheme.headline6 = UIFont(name: fontName, size: 20)!
scheme.subtitle1 = UIFont(name: fontName, size: 16)!
scheme.button = UIFont(name: fontName, size: 14)!
return scheme
}()
public let shapeScheme: MDCShapeScheming = {
let scheme = MDCShapeScheme()
return scheme
}()
}
| apache-2.0 | a0a57dd8aeade3ffd6f17665d374124e | 35.078947 | 85 | 0.694384 | 3.381011 | false | false | false | false |
Sidetalker/TapMonkeys | TapMonkeys/TapMonkeys/GlobalUIClasses.swift | 1 | 13457 | //
// GlobalUIClasses.swift
// TapMonkeys
//
// Created by Kevin Sullivan on 5/13/15.
// Copyright (c) 2015 Kevin Sullivan. All rights reserved.
//
import UIKit
enum ObjectType {
case Monkey
case Writing
case Income
}
class ConstraintView: UIView {
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.backgroundColor = UIColor.clearColor()
}
}
class AutoUpdateLabel: UILabel {
var index = -1
var controller: TabBarController?
var type: ObjectType = .Monkey
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let timer = NSTimer.scheduledTimerWithTimeInterval(0.10, target: self, selector: Selector("refresh"), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
func refresh() {
if controller == nil { return }
let saveData = load(controller!)
if type == .Monkey {
let total = generalFormatter.stringFromNumber(saveData.monkeyTotals![index])!
self.text = "Total Letters: \(total)"
}
else if type == .Income {
let amount = currencyFormatter.stringFromNumber(saveData.incomeTotals![index])!
self.text = "Total: \(amount)"
}
}
}
protocol AnimatedLockDelegate {
func tappedLock(view: AnimatedLockView)
}
class AnimatedLockView: UIView {
@IBOutlet var nibView: UIView!
@IBOutlet weak var bgView: UIView!
@IBOutlet weak var lockImage: UIImageView!
@IBOutlet weak var requirementsText: UILabel!
@IBOutlet weak var staticText: UILabel!
@IBOutlet weak var pic: UIImageView!
var locked = true
var type: ObjectType = .Monkey
var index = -1
var animator: UIDynamicAnimator?
var delegate: AnimatedLockDelegate?
var transitionView: UIView?
var nightMode = false
var lockImages = [UIImage]()
var lockImagesNight = [UIImage]()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
func configure() {
NSBundle.mainBundle().loadNibNamed("AnimatedLockView", owner: self, options: nil)
nibView.frame = self.frame
self.addSubview(nibView)
transitionView = UIView(frame: self.frame)
transitionView!.backgroundColor = UIColor.whiteColor()
self.nibView.addSubview(transitionView!)
self.nibView.sendSubviewToBack(transitionView!)
self.nibView.bringSubviewToFront(lockImage)
for i in 1...12 {
let imageName = "animatedLock" + (NSString(format: "%02d", i) as String)
let imageNameNight = "animatedLockNight" + (NSString(format: "%02d", i) as String)
if let image = UIImage(named: imageName) {
lockImages.append(image)
}
if let imageNight = UIImage(named: imageNameNight) {
lockImagesNight.append(imageNight)
}
}
lockImage.animationImages = nightMode ? lockImagesNight : lockImages
lockImage.animationDuration = 0.35
lockImage.animationRepeatCount = 1
let singleTap = UITapGestureRecognizer(target: self, action: Selector("lockTap:"))
self.addGestureRecognizer(singleTap)
}
func customize(saveData: SaveData) {
nightMode = saveData.nightMode!
staticText.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
requirementsText.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
pic.alpha = nightMode ? 0.5 : 1.0
lockImage.image = nightMode ? lockImagesNight[0] : lockImages[0]
lockImage.animationImages = nightMode ? lockImagesNight : lockImages
bgView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor()
if self.superview != nil {
self.frame = self.superview!.frame
}
staticText.text = "Unlock With"
if type == .Monkey {
if index > 1 {
if !saveData.monkeyUnlocks![index - 1] && !saveData.monkeyUnlocks![index - 2] {
requirementsText.text = "?????"
pic.image = UIImage(named: "unknownUnlock")
return
}
}
let unlockIndex = Int(monkeys[index].unlockCost[0].0)
let quantity = Int(monkeys[index].unlockCost[0].1)
let plurarity = quantity > 1 ? "s" : ""
requirementsText.text = "\(quantity) \(incomes[unlockIndex].name)\(plurarity)"
if quantity == 0 {
staticText.text = "Unlock For"
requirementsText.text = "FREE"
}
pic.image = UIImage(named:monkeys[index].imageName)
}
else if type == .Writing {
if index > 1 {
if !saveData.writingUnlocked![index - 1] && !saveData.writingUnlocked![index - 2] {
requirementsText.text = "?????"
pic.image = UIImage(named: "unknownUnlock")
return
}
}
requirementsText.text = "\(writings[index].unlockCost) Letters"
if writings[index].unlockCost == 0 {
staticText.text = "Unlock For"
requirementsText.text = "FREE"
}
pic.image = UIImage(named:writings[index].imageName)
}
else if type == .Income {
if index > 1 {
if !saveData.incomeUnlocks![index - 1] && !saveData.incomeUnlocks![index - 2] {
requirementsText.text = "?????"
pic.image = UIImage(named: "unknownUnlock")
return
}
}
let unlockIndex = Int(incomes[index].unlockCost[0].0)
let quantity = Int(incomes[index].unlockCost[0].1)
let plurarity = quantity > 1 ? "s" : ""
requirementsText.text = "\(quantity) \(writings[unlockIndex].name)\(plurarity)"
if quantity == 0 {
staticText.text = "Unlock For"
requirementsText.text = "FREE"
}
pic.image = UIImage(named:incomes[index].imageName)
}
}
func lockTap(sender: UITapGestureRecognizer) {
delegate?.tappedLock(self)
}
func unlock() {
lockImage.image = nightMode ? UIImage(named: "animatedNightLock12") : UIImage(named: "animatedLock12")
lockImage.startAnimating()
let angularVelocityLock: CGFloat = 0.4
let linearVelocityLock = CGPoint(x: 25, y: -150)
// Set up the gravitronator
let gravity = UIGravityBehavior(items: [lockImage])
let velocity = UIDynamicItemBehavior(items: [lockImage])
gravity.gravityDirection = CGVectorMake(0, 0.4)
velocity.addAngularVelocity(angularVelocityLock, forItem: lockImage)
velocity.addLinearVelocity(linearVelocityLock, forItem: lockImage)
animator = UIDynamicAnimator(referenceView: self.nibView)
animator?.addBehavior(velocity)
animator?.addBehavior(gravity)
UIView.animateWithDuration(0.66, delay: 0.0, options: nil, animations: { () -> Void in
self.bgView.alpha = 0.0
self.transitionView!.alpha = 0.0
self.requirementsText.alpha = 0.0
self.staticText.alpha = 0.0
self.pic.alpha = 0.0
}, completion: { (Bool) -> Void in
})
UIView.animateWithDuration(0.51, delay: 0.39, options: nil, animations: { () -> Void in
self.lockImage.alpha = 0.0
}, completion: { (Bool) -> Void in
self.removeFromSuperview()
})
}
}
protocol DataHeaderDelegate {
func toggleLight(sender: DataHeader)
}
//@IBDesignable class DataHeader: UIView {
class DataHeader: UIView {
@IBOutlet var nibView: UIView!
@IBOutlet weak var lightbulbButton: UIButton!
@IBOutlet weak var lettersLabel: UILabel!
@IBOutlet weak var moneyLabel: UILabel!
@IBOutlet weak var wrapperView: UIView!
var letters: Float = 0
var money: Float = 0
var nightMode = false
var gonnaDisplayBulb = true
var delegate: DataHeaderDelegate?
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
@IBAction func tapLightbulb(sender: AnyObject) {
delegate?.toggleLight(self)
}
func configure() {
NSBundle.mainBundle().loadNibNamed("DataHeader", owner: self, options: nil)
self.addSubview(nibView)
nibView.frame = self.frame
lettersLabel.text = "0"
moneyLabel.text = "$0.00"
lettersLabel.alpha = 0.0
moneyLabel.alpha = 0.0
lightbulbButton.alpha = 0.0
lightbulbButton.setBackgroundImage(TapStyle.imageOfLightbulb(frame: CGRect(origin: CGPointZero, size: lightbulbButton.frame.size), colorLightbulb: nightMode ? UIColor.lightTextColor() : UIColor.blackColor()), forState: UIControlState.Normal)
align()
backgroundColor = UIColor.whiteColor()
wrapperView.backgroundColor = UIColor.clearColor()
lightbulbButton.backgroundColor = UIColor.clearColor()
}
func align() {
lettersLabel.sizeToFit()
moneyLabel.sizeToFit()
}
func getCenterLetters() -> CGPoint {
return getCenter(lettersLabel)
}
func getCenterMoney() -> CGPoint {
return getCenter(moneyLabel)
}
func getCenter(view: UIView) -> CGPoint {
var newX = view.frame.origin.x
var newY = view.frame.origin.y
newX += view.frame.width / 2
newY += view.frame.height / 2
return CGPoint(x: newX, y: newY)
}
func update(data: SaveData, animated: Bool = true) {
// Stupid hack for a stupid nib
if self.gonnaDisplayBulb && nibView.frame == self.bounds {
self.gonnaDisplayBulb = false
reveal(lightbulbButton, animated: false)
}
else {
nibView.frame = self.frame
}
// Night mode
if nightMode != data.nightMode! {
nightMode = !nightMode
nibView.backgroundColor = nightMode ? UIColor.blackColor() : UIColor.whiteColor()
lettersLabel?.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
moneyLabel?.textColor = nightMode ? UIColor.lightTextColor() : UIColor.blackColor()
lightbulbButton.setBackgroundImage(TapStyle.imageOfLightbulb(frame: CGRect(origin: CGPointZero, size: lightbulbButton.frame.size), colorLightbulb: nightMode ? UIColor.lightTextColor() : UIColor.blackColor()), forState: UIControlState.Normal)
}
if self.letters == 0 && data.letters! > 0 {
revealLetters(animated)
}
if self.money == 0 && data.money! > 0 {
revealMoney(animated)
}
self.letters = data.letters!
self.money = data.money!
let moneyText = currencyFormatter.stringFromNumber(data.money!)!
lettersLabel?.text = "\(generalFormatter.stringFromNumber(self.letters)!)"
moneyLabel?.text = "\(moneyText)"
if letters > 0 && animated { pulseLetters() }
if money > 0 && animated { pulseMoney() }
}
func revealLetters(animated: Bool) {
reveal(lettersLabel, animated: animated)
}
func revealMoney(animated: Bool) {
reveal(moneyLabel, animated: animated)
}
func reveal(view: UIView, animated: Bool = true) {
UIView.animateWithDuration(animated ? 0.4 : 0.1, animations: { () -> Void in
view.alpha = 1.0
})
}
func pulseLetters() {
pulse(lettersLabel)
}
func pulseMoney() {
pulse(moneyLabel)
}
func pulse(view: UIView) {
UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
view.transform = CGAffineTransformMakeScale(1.15, 1.15)
}, completion: { (Bool) -> Void in
UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
view.transform = CGAffineTransformIdentity
}, completion: nil)
})
}
override func translatesAutoresizingMaskIntoConstraints() -> Bool {
return false
}
} | mit | 52d60026b4ca15d490646117e9280176 | 31.744526 | 253 | 0.569964 | 4.782161 | false | false | false | false |
andrewredko/SingleCell | SingleCell-Demo/SingleCell-Demo/ViewController.swift | 1 | 9149 | //
// ViewController.swift
// SingleCell-Demo
//
// Created by Andrew Redko on 9/27/2016.
// Copyright © 2016 Andrew Redko. All rights reserved.
//
import UIKit
import SingleCell
class ViewController: UIViewController {
// MARK: - Private vars
private let datePicker = UIDatePicker()
private let dateFormatter = DateFormatter()
// MARK: - IBOutlets
@IBOutlet weak var singleCell: SingleCell!
@IBOutlet weak var valueSingleCell: ValueSingleCell!
@IBOutlet weak var switchSingleCell: SwitchSingleCell!
@IBOutlet weak var inputSingleCell: InputSingleCell!
@IBOutlet weak var actionResultLabel: UILabel!
@IBOutlet weak var showDetailViewCell: SwitchSingleCell!
@IBOutlet weak var showDisclosureCell: SwitchSingleCell!
@IBOutlet weak var showImageCell: SwitchSingleCell!
@IBOutlet weak var darkColorThemeCell: SwitchSingleCell!
// MARK: - Show Content IBActions
private var singleCellInitImage: UIImage!
private var valueSingleCellInitImage: UIImage!
private var switchSingleCellInitImage: UIImage!
private var inputSingleCellInitImage: UIImage!
@IBAction func showImageValueChanged(_ sender: SwitchSingleCell) {
if singleCellInitImage == nil {
preserveInitialImages()
}
if sender.isOn {
singleCell.image = singleCellInitImage
valueSingleCell.image = valueSingleCellInitImage
switchSingleCell.image = switchSingleCellInitImage
inputSingleCell.image = inputSingleCellInitImage
} else {
singleCell.image = nil
valueSingleCell.image = nil
switchSingleCell.image = nil
inputSingleCell.image = nil
}
}
fileprivate func preserveInitialImages() {
singleCellInitImage = singleCell.image
valueSingleCellInitImage = valueSingleCell.image
switchSingleCellInitImage = switchSingleCell.image
inputSingleCellInitImage = inputSingleCell.image
}
@IBAction func showDetailViewValueChanged(_ sender: SwitchSingleCell) {
if sender.isOn {
valueSingleCell.detailText = ValueSingleCell.Defaults.detailText
switchSingleCell.showSwitch = true
inputSingleCell.detailText = InputSingleCell.Defaults.detailText
} else {
valueSingleCell.detailText = nil
switchSingleCell.showSwitch = false
inputSingleCell.detailText = nil
}
}
@IBAction func showDisclosureValueChanged(_ sender: SwitchSingleCell) {
let show = sender.isOn
singleCell.showDisclosure = show
valueSingleCell.showDisclosure = show
switchSingleCell.showDisclosure = show
inputSingleCell.showDisclosure = show
}
// MARK: - Dark Theme IBAction
@IBAction func darkThemeChanged(_ sender: SwitchSingleCell) {
let isDark = sender.isOn
if isDark {
setDarkColorTheme()
} else {
setDefaultColorTheme()
}
}
private func setDefaultColorTheme() {
setDefaultColorTheme(onCell: singleCell)
setDefaultColorTheme(onCell: valueSingleCell)
setDefaultColorTheme(onCell: switchSingleCell)
setDefaultColorTheme(onCell: inputSingleCell)
setDefaultColorTheme(onCell: showImageCell)
setDefaultColorTheme(onCell: showDetailViewCell)
setDefaultColorTheme(onCell: showDisclosureCell)
setDefaultColorTheme(onCell: darkColorThemeCell)
self.view.backgroundColor = UIColor(red: 239 / 255.0, green: 239 / 255.0, blue: 244 / 255.0, alpha: 1.0)
setStatusBarStyle(isDarkTheme: false)
}
private func setDarkColorTheme() {
setDarkColorTheme(onCell: singleCell)
setDarkColorTheme(onCell: valueSingleCell)
setDarkColorTheme(onCell: switchSingleCell)
setDarkColorTheme(onCell: inputSingleCell)
setDarkColorTheme(onCell: showImageCell)
setDarkColorTheme(onCell: showDetailViewCell)
setDarkColorTheme(onCell: showDisclosureCell)
setDarkColorTheme(onCell: darkColorThemeCell)
self.view.backgroundColor = UIColor(white: 0.05, alpha: 1.0)
setStatusBarStyle(isDarkTheme: true)
}
private func setDefaultColorTheme(onCell cell: SingleCell) {
cell.bkgdNormalColor = nil
cell.bordersColor = nil
cell.textNormalColor = nil
cell.disclosureColor = nil
if let cell = cell as? ValueSingleCell {
cell.detailNormalColor = nil
} else if let cell = cell as? SwitchSingleCell {
cell.onTintColor = nil
}
if let cell = cell as? InputSingleCell {
cell.detailNormalColor = UIColor(red: 48 / 255.0, green: 131 / 255.0,
blue: 251 / 255.0, alpha: 1.0)
}
}
private func setDarkColorTheme(onCell cell: SingleCell) {
cell.bkgdNormalColor = UIColor(white: 0.10, alpha: 1.0)
cell.bordersColor = UIColor(white: 0.18, alpha: 1.0)
cell.textNormalColor = UIColor(white: 0.84, alpha: 1.0)
cell.disclosureColor = UIColor(red: 204 / 255.0, green: 204 / 255.0,
blue: 206 / 255.0, alpha: 1.0)
if let cell = cell as? ValueSingleCell {
cell.detailNormalColor = UIColor(white: 0.84, alpha: 1.0)
} else if let cell = cell as? SwitchSingleCell {
cell.onTintColor = UIColor(red: 57 / 255.0, green: 139 / 255.0,
blue: 247 / 255.0, alpha: 1.0)
}
}
private func setStatusBarStyle(isDarkTheme: Bool) {
UIApplication.shared.statusBarStyle = isDarkTheme ? .lightContent : .default
}
// MARK: - Setup
override func viewDidLoad() {
super.viewDidLoad()
setupDatePicker()
setupInputSingleCell()
assignActionsToTouchEvents()
}
private func setupDatePicker() {
dateFormatter.locale = Locale.current
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
datePicker.datePickerMode = .time
datePicker.addTarget(self, action: #selector(pickerDateChanged), for: .valueChanged)
}
func pickerDateChanged() {
inputSingleCell.detailText = stringFromDate(datePicker.date)
}
func stringFromDate(_ optDate : Date?) -> String {
guard let date = optDate else {
return ""
}
return dateFormatter.string(from: date)
}
private func setupInputSingleCell() {
inputSingleCell.setInputDelegate(self)
inputSingleCell.setInputView(datePicker)
// Add input accessory view with Done button on the right side
let toolBar = UIToolbar()
toolBar.barStyle = UIBarStyle.default
toolBar.isTranslucent = true
toolBar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneButton = UIBarButtonItem(title: "Done", style: .done, target: self, action: #selector(dismissDatePicker))
toolBar.setItems([flexBarButton, doneButton], animated: false)
inputSingleCell.setInputAccessoryView(toolBar)
}
func dismissDatePicker() {
if inputSingleCell.isFirstResponder {
inputSingleCell.detailText = stringFromDate(datePicker.date)
_ = inputSingleCell.resignFirstResponder()
}
}
private func assignActionsToTouchEvents() {
// Standard "addTarget" is used to subscribe to touch events
singleCell.addTarget(self, action: #selector(cellTouched), for: .touchUpInside)
switchSingleCell.addTarget(self, action: #selector(cellTouched), for: .touchUpInside)
valueSingleCell.addTarget(self, action: #selector(cellTouched), for: .touchUpInside)
inputSingleCell.addTarget(self, action: #selector(cellTouched), for: .touchUpInside)
}
@objc private func cellTouched(_ sender: SingleCell) {
self.actionResultLabel.alpha = 1.0
self.actionResultLabel.text = "\"\(sender.text!)\" tapped."
// Hide message after some delay
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: {
UIView.animate(withDuration: 0.2, animations: {
self.actionResultLabel.alpha = 0.0
})
})
}
}
// MARK: - UITextFieldDelegate
extension ViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
let activeButton = textField.superview as! UIControl
activeButton.isSelected = true
}
func textFieldDidEndEditing(_ textField: UITextField) {
let activeButton = textField.superview as! InputSingleCell
_ = activeButton.resignFirstResponder()
activeButton.isSelected = false
}
}
| mit | 5ca209e4aaa481c2dfb799069a64a14b | 34.320463 | 121 | 0.642654 | 4.85305 | false | false | false | false |
bustosalex/productpal | productpal/AddProductTab.swift | 1 | 3384 | //
// AddProductTab.swift
// productpal
//
// Created by Alexander Bustos on 5/5/16.
// Copyright © 2016 University of Wisconsin Parkisde. All rights reserved.
//
import UIKit
import CoreData
class AddProductTab: UITableViewController {
//These are the attributes for the core data model
@IBOutlet weak var itemName: UITextField!
@IBOutlet weak var productNumber: UITextField!
@IBOutlet weak var storeName: UITextField!
@IBOutlet weak var itemDescription: UITextField!
@IBOutlet weak var returnDate: UIDatePicker!
@IBOutlet weak var warrantyDate: UIDatePicker!
@IBOutlet weak var protectionDate: UIDatePicker!
let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
/**
When the user hits save or done it will first check to see if the text fields are filled properly other wise it will
throw an error message.
Then we begin to save the name, description, store, and all of the relevant dates into a core data object.
*/
@IBAction func saveProduct(sender: AnyObject) {
let entityDescription = NSEntityDescription.entityForName("Products", inManagedObjectContext: managedObjectContext)
let product = Products(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
let check = checkIfShitIsFilledOut()
if(check != true){
fieldsNotFilledErrorMessage()
}
else{
product.itemName = itemName.text!
product.store = storeName.text!
product.itemDescription = itemDescription.text!
product.returnDate = returnDate.date
product.warrantyDate = warrantyDate.date
product.protectionDate = protectionDate.date
do {
try managedObjectContext.save()
}
catch let error as NSError{
print(error.localizedFailureReason)
}
}
}
/**
This function checks if three text fields are filled
The name of the item, it's description and the store where it was bought
If any of these fields are empty then it will return false other wise it
will return true.
*/
func checkIfShitIsFilledOut()->Bool{
var isFilled = true
if ((itemName.text?.isEmpty) != false){
isFilled = false
}
else if((itemDescription.text?.isEmpty) != false){
isFilled = false
}
else if((storeName.text?.isEmpty) != false){
isFilled = false
}
return isFilled
}
/**
This is a simple method that pops up an error message if a required field isn't properly filled
*/
func fieldsNotFilledErrorMessage(){
let alert = UIAlertController(title: "Error", message: "You didn't fill everything in!!!", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default) { _ in })
self.presentViewController(alert, animated: true){}
}
func createReminder(){
}
}
| mit | 05da2e68d92fb446b439b2e2bd785a3a | 31.84466 | 123 | 0.626958 | 5.220679 | false | false | false | false |
Laieringc/solosk | TheSolo/AppDelegate.swift | 1 | 6284 | //
// AppDelegate.swift
// TheSolo
//
// Created by TheSolo on 15/9/4.
// Copyright (c) 2015年 TheSolo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
window!.rootViewController = containerViewController
window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.TheSolo.TheSolo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TheSolo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("TheSolo.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 65a7b400f2901829d525b95bacd7ee56 | 53.155172 | 290 | 0.713149 | 5.747484 | false | false | false | false |
TotalDigital/People-iOS | People at Total/Job.swift | 1 | 1739 | //
// Job.swift
// justOne
//
// Created by Florian Letellier on 29/01/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
class Job: NSObject, NSCoding {
var id: Int?
var title: String?
var start_date: String?
var end_date: String?
var objDescription: String?
var location: String?
override init() {
}
init(id: Int?, title: String?,start_date: String?,end_date: String?,objDescription: String?,location: String?) {
self.id = id
self.title = title
self.start_date = start_date
self.end_date = end_date
self.objDescription = objDescription
self.location = location
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeObject(forKey: "id") as? Int
let title = aDecoder.decodeObject(forKey: "title") as? String
let start_date = aDecoder.decodeObject(forKey: "start_date") as? String
let end_date = aDecoder.decodeObject(forKey: "end_date") as? String
let objDescription = aDecoder.decodeObject(forKey: "objDescription") as? String
let location = aDecoder.decodeObject(forKey: "location") as? String
self.init(id: id, title: title,start_date: start_date,end_date: end_date,objDescription: objDescription,location: location)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(title, forKey: "title")
aCoder.encode(start_date, forKey: "start_date")
aCoder.encode(end_date, forKey: "end_date")
aCoder.encode(objDescription, forKey: "objDescription")
aCoder.encode(location, forKey: "location")
}
}
| apache-2.0 | 2c43d1cc50ee13532e3487877e1d8205 | 31.185185 | 131 | 0.641542 | 3.923251 | false | false | false | false |
hejunbinlan/RealmResultsController | Example/RealmResultsController-iOSTests/RealmNotificationTests.swift | 1 | 1500 | //
// RealmNotificationTests.swift
// RealmResultsController
//
// Created by Pol Quintana on 6/8/15.
// Copyright © 2015 Redbooth.
//
import Foundation
import Quick
import Nimble
import RealmSwift
@testable import RealmResultsController
class RealmNotificationSpec: QuickSpec {
override func spec() {
var realm: Realm!
beforeSuite {
RealmTestHelper.loadRealm()
realm = try! Realm()
}
describe("loggerForRealm(realm:)") {
var createdLogger: RealmLogger!
context("Create a logger") {
beforeEach {
createdLogger = RealmNotification.loggerForRealm(realm)
}
it("Should have stored the logger in its shared instance") {
expect(RealmNotification.sharedInstance.loggers.count).to(equal(1))
expect(RealmNotification.sharedInstance.loggers.first!) === createdLogger
}
}
context("Retrieve a created logger") {
var retrievedLogger: RealmLogger!
beforeEach {
retrievedLogger = RealmNotification.loggerForRealm(realm)
}
it("Should have retrieve the logger stored in its shared instance") {
expect(RealmNotification.sharedInstance.loggers.count).to(equal(1))
expect(retrievedLogger) === createdLogger
}
}
}
}
} | mit | 8d70fc9d174134789141d66a5c235cf1 | 31.608696 | 93 | 0.574383 | 5.411552 | false | true | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps | TheMovieManager-v2/TheMovieManager/TMDBConvenience.swift | 1 | 15803 | //
// TMDBConvenience.swift
// TheMovieManager
//
// Created by Jarrod Parkes on 2/11/15.
// Copyright (c) 2015 Jarrod Parkes. All rights reserved.
//
import UIKit
import Foundation
// MARK: - TMDBClient (Convenient Resource Methods)
extension TMDBClient {
// MARK: Authentication (GET) Methods
/*
Steps for Authentication...
https://www.themoviedb.org/documentation/api/sessions
Step 1: Create a new request token
Step 2a: Ask the user for permission via the website
Step 3: Create a session ID
Bonus Step: Go ahead and get the user id 😄!
*/
func authenticateWithViewController(hostViewController: UIViewController, completionHandlerForAuth: (success: Bool, errorString: String?) -> Void) {
// chain completion handlers for each request so that they run one after the other
getRequestToken() { (success, requestToken, errorString) in
if success {
// success! we have the requestToken!
print(requestToken)
self.requestToken = requestToken
self.loginWithToken(requestToken, hostViewController: hostViewController) { (success, errorString) in
if success {
self.getSessionID(requestToken) { (success, sessionID, errorString) in
if success {
// success! we have the sessionID!
self.sessionID = sessionID
self.getUserID() { (success, userID, errorString) in
if success {
if let userID = userID {
// and the userID 😄!
self.userID = userID
}
}
completionHandlerForAuth(success: success, errorString: errorString)
}
} else {
completionHandlerForAuth(success: success, errorString: errorString)
}
}
} else {
completionHandlerForAuth(success: success, errorString: errorString)
}
}
} else {
completionHandlerForAuth(success: success, errorString: errorString)
}
}
}
private func getRequestToken(completionHandlerForToken: (success: Bool, requestToken: String?, errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [String:AnyObject]()
/* 2. Make the request */
taskForGETMethod(Methods.AuthenticationTokenNew, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForToken(success: false, requestToken: nil, errorString: "Login Failed (Request Token).")
} else {
if let requestToken = results[TMDBClient.JSONResponseKeys.RequestToken] as? String {
completionHandlerForToken(success: true, requestToken: requestToken, errorString: nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.RequestToken) in \(results)")
completionHandlerForToken(success: false, requestToken: nil, errorString: "Login Failed (Request Token).")
}
}
}
}
private func loginWithToken(requestToken: String?, hostViewController: UIViewController, completionHandlerForLogin: (success: Bool, errorString: String?) -> Void) {
let authorizationURL = NSURL(string: "\(TMDBClient.Constants.AuthorizationURL)\(requestToken!)")
let request = NSURLRequest(URL: authorizationURL!)
let webAuthViewController = hostViewController.storyboard!.instantiateViewControllerWithIdentifier("TMDBAuthViewController") as! TMDBAuthViewController
webAuthViewController.urlRequest = request
webAuthViewController.requestToken = requestToken
webAuthViewController.completionHandlerForView = completionHandlerForLogin
let webAuthNavigationController = UINavigationController()
webAuthNavigationController.pushViewController(webAuthViewController, animated: false)
performUIUpdatesOnMain {
hostViewController.presentViewController(webAuthNavigationController, animated: true, completion: nil)
}
}
private func getSessionID(requestToken: String?, completionHandlerForSession: (success: Bool, sessionID: String?, errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.RequestToken: requestToken!]
/* 2. Make the request */
taskForGETMethod(Methods.AuthenticationSessionNew, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForSession(success: false, sessionID: nil, errorString: "Login Failed (Session ID).")
} else {
if let sessionID = results[TMDBClient.JSONResponseKeys.SessionID] as? String {
completionHandlerForSession(success: true, sessionID: sessionID, errorString: nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.SessionID) in \(results)")
completionHandlerForSession(success: false, sessionID: nil, errorString: "Login Failed (Session ID).")
}
}
}
}
private func getUserID(completionHandlerForUserID: (success: Bool, userID: Int?, errorString: String?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID: TMDBClient.sharedInstance().sessionID!]
/* 2. Make the request */
taskForGETMethod(Methods.Account, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
print(error)
completionHandlerForUserID(success: false, userID: nil, errorString: "Login Failed (User ID).")
} else {
if let userID = results[TMDBClient.JSONResponseKeys.UserID] as? Int {
completionHandlerForUserID(success: true, userID: userID, errorString: nil)
} else {
print("Could not find \(TMDBClient.JSONResponseKeys.UserID) in \(results)")
completionHandlerForUserID(success: false, userID: nil, errorString: "Login Failed (User ID).")
}
}
}
}
// MARK: GET Convenience Methods
func getFavoriteMovies(completionHandlerForFavMovies: (result: [TMDBMovie]?, error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID: TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDFavoriteMovies
mutableMethod = subtituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
/* 2. Make the request */
taskForGETMethod(mutableMethod, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForFavMovies(result: nil, error: error)
} else {
if let results = results[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForFavMovies(result: movies, error: nil)
} else {
completionHandlerForFavMovies(result: nil, error: NSError(domain: "getFavoriteMovies parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getFavoriteMovies"]))
}
}
}
}
func getWatchlistMovies(completionHandlerForWatchlist: (result: [TMDBMovie]?, error: NSError?) -> Void) {
/* 1. Specify parameters, the API method, and the HTTP body (if POST) */
let parameters = [
TMDBClient.ParameterKeys.SessionID : sessionID!
]
var mutableMethod: String = Methods.AccountIDWatchlistMovies
mutableMethod = subtituteKeyInMethod(mutableMethod, key: URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
/* 2. Make the request */
taskForGETMethod(mutableMethod, parameters: parameters) { (result, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForWatchlist(result: nil, error: error)
} else {
if let results = result[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]]{
completionHandlerForWatchlist(result: TMDBMovie.moviesFromResults(results), error: nil)
} else {
completionHandlerForWatchlist(result: nil, error: NSError(domain: "getWatchListMovies parsing", code: 0, userInfo: [NSLocalizedDescriptionKey : "Could not parse getWatchlistMovies"]))
}
}
}
}
func getMoviesForSearchString(searchString: String, completionHandlerForMovies: (result: [TMDBMovie]?, error: NSError?) -> Void) -> NSURLSessionDataTask? {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.Query: searchString]
/* 2. Make the request */
let task = taskForGETMethod(Methods.SearchMovie, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForMovies(result: nil, error: error)
} else {
if let results = results[TMDBClient.JSONResponseKeys.MovieResults] as? [[String:AnyObject]] {
let movies = TMDBMovie.moviesFromResults(results)
completionHandlerForMovies(result: movies, error: nil)
} else {
completionHandlerForMovies(result: nil, error: NSError(domain: "getMoviesForSearchString parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getMoviesForSearchString"]))
}
}
}
return task
}
func getConfig(completionHandlerForConfig: (didSucceed: Bool, error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [String:AnyObject]()
/* 2. Make the request */
taskForGETMethod(Methods.Config, parameters: parameters) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForConfig(didSucceed: false, error: error)
} else if let newConfig = TMDBConfig(dictionary: results as! [String:AnyObject]) {
self.config = newConfig
completionHandlerForConfig(didSucceed: true, error: nil)
} else {
completionHandlerForConfig(didSucceed: false, error: NSError(domain: "getConfig parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse getConfig"]))
}
}
}
// MARK: POST Convenience Methods
func postToFavorites(movie: TMDBMovie, favorite: Bool, completionHandlerForFavorite: (result: Int?, error: NSError?) -> Void) {
/* 1. Specify parameters, method (if has {key}), and HTTP body (if POST) */
let parameters = [TMDBClient.ParameterKeys.SessionID : TMDBClient.sharedInstance().sessionID!]
var mutableMethod: String = Methods.AccountIDFavorite
mutableMethod = subtituteKeyInMethod(mutableMethod, key: TMDBClient.URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
let jsonBody = "{\"\(TMDBClient.JSONBodyKeys.MediaType)\": \"movie\",\"\(TMDBClient.JSONBodyKeys.MediaID)\": \"\(movie.id)\",\"\(TMDBClient.JSONBodyKeys.Favorite)\": \(favorite)}"
/* 2. Make the request */
taskForPOSTMethod(mutableMethod, parameters: parameters, jsonBody: jsonBody) { (results, error) in
/* 3. Send the desired value(s) to completion handler */
if let error = error {
completionHandlerForFavorite(result: nil, error: error)
} else {
if let results = results[TMDBClient.JSONResponseKeys.StatusCode] as? Int {
completionHandlerForFavorite(result: results, error: nil)
} else {
completionHandlerForFavorite(result: nil, error: NSError(domain: "postToFavoritesList parsing", code: 0, userInfo: [NSLocalizedDescriptionKey: "Could not parse postToFavoritesList"]))
}
}
}
}
func postToWatchlist(movie: TMDBMovie, watchlist: Bool, completionHandlerForWatchlist: (result: Int?, error: NSError?) -> Void) {
/* 1. Specify parameters, the API method, and the HTTP body (if POST) */
let parameters = [
ParameterKeys.SessionID : TMDBClient.sharedInstance().sessionID!
]
var mutableMethod: String = Methods.AccountIDWatchlist
mutableMethod = subtituteKeyInMethod(mutableMethod, key: URLKeys.UserID, value: String(TMDBClient.sharedInstance().userID!))!
let jsonBody = "{\"\(JSONBodyKeys.MediaType)\" : \"movie\",\"\(JSONBodyKeys.MediaID)\" : \(movie.id),\"\(JSONBodyKeys.Watchlist)\" : \(true)}"
/* 2. Make the request */
taskForPOSTMethod(mutableMethod, parameters: parameters, jsonBody: jsonBody) { (result, error) in
if let error = error {
completionHandlerForWatchlist(result: nil, error: error)
} else {
if let results = result[JSONResponseKeys.StatusCode] as? Int where results == 1 {
completionHandlerForWatchlist(result: results, error: nil)
} else {
completionHandlerForWatchlist(result: nil, error: NSError(domain: "postToWatchlist parsing", code: 0, userInfo: [NSLocalizedDescriptionKey : "Could not parse postToFavoritesList"]))
}
}
}
/* 3. Send the desired value(s) to completion handler */
}
} | mit | 64739aa146b09f594ae9e348d8625537 | 49.472843 | 211 | 0.584415 | 5.467982 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSDictionary.swift | 1 | 28275 | // 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
//
@_implementationOnly import CoreFoundation
#if !os(WASI)
import Dispatch
#endif
fileprivate func getDescription(of object: Any) -> String? {
switch object {
case let nsArray as NSArray:
return nsArray.description(withLocale: nil, indent: 1)
case let nsDecimalNumber as NSDecimalNumber:
return nsDecimalNumber.description(withLocale: nil)
case let nsDate as NSDate:
return nsDate.description(with: nil)
case let nsOrderedSet as NSOrderedSet:
return nsOrderedSet.description(withLocale: nil)
case let nsSet as NSSet:
return nsSet.description(withLocale: nil)
case let nsDictionary as NSDictionary:
return nsDictionary.description(withLocale: nil)
case let hashableObject as Dictionary<AnyHashable, Any>:
return hashableObject._nsObject.description(withLocale: nil, indent: 1)
default:
return nil
}
}
open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding, ExpressibleByDictionaryLiteral {
private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID())
internal var _storage: [NSObject: AnyObject]
open var count: Int {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func object(forKey aKey: Any) -> Any? {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
if let val = _storage[__SwiftValue.store(aKey)] {
return __SwiftValue.fetch(nonOptional: val)
}
return nil
}
open func value(forKey key: String) -> Any? {
if key.hasPrefix("@") {
NSUnsupported()
} else {
return object(forKey: key)
}
}
open func keyEnumerator() -> NSEnumerator {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.keys.map { __SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
#if !os(WASI)
@available(*, deprecated)
public convenience init?(contentsOfFile path: String) {
self.init(contentsOf: URL(fileURLWithPath: path))
}
@available(*, deprecated)
public convenience init?(contentsOf url: URL) {
do {
guard let plistDoc = try? Data(contentsOf: url) else { return nil }
let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any>
guard let plistDictionary = plistDict else { return nil }
self.init(dictionary: plistDictionary)
} catch {
return nil
}
}
#endif
public override convenience init() {
self.init(objects: [], forKeys: [], count: 0)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
_storage = [NSObject : AnyObject](minimumCapacity: cnt)
for idx in 0..<cnt {
let key = keys[idx].copy()
let value = objects[idx]
_storage[key as! NSObject] = value
}
}
public convenience init(object: Any, forKey key: NSCopying) {
self.init(objects: [object], forKeys: [key as! NSObject])
}
public convenience init(objects: [Any], forKeys keys: [NSObject]) {
let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count)
keyBuffer.initialize(from: keys, count: keys.count)
let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count)
valueBuffer.initialize(from: objects.map { __SwiftValue.store($0) }, count: objects.count)
self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count)
keyBuffer.deinitialize(count: keys.count)
valueBuffer.deinitialize(count: objects.count)
keyBuffer.deallocate()
valueBuffer.deallocate()
}
public convenience init(dictionary otherDictionary: [AnyHashable : Any]) {
self.init(dictionary: otherDictionary, copyItems: false)
}
public convenience init(dictionary otherDictionary: [AnyHashable: Any], copyItems flag: Bool) {
if flag {
self.init(objects: Array(otherDictionary.values.map { __SwiftValue($0).copy() as! NSObject }), forKeys: otherDictionary.keys.map { __SwiftValue.store($0).copy() as! NSObject})
} else {
self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { __SwiftValue.store($0) })
}
}
required public convenience init(dictionaryLiteral elements: (Any, Any)...) {
var keys = [NSObject]()
var values = [Any]()
for (key, value) in elements {
keys.append(__SwiftValue.store(key))
values.append(value)
}
self.init(objects: values, forKeys: keys)
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject }
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(objects: objects as! [NSObject], forKeys: keys)
} else {
var objects = [AnyObject]()
var keys = [NSObject]()
var count = 0
while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"),
let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
keys.append(key as! NSObject)
objects.append(object as! NSObject)
count += 1
}
self.init(objects: objects, forKeys: keys)
}
}
open func encode(with aCoder: NSCoder) {
if let keyedArchiver = aCoder as? NSKeyedArchiver {
keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys")
keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects")
} else {
guard aCoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed decoding is unsupported.")
}
var count = 0
var keyKey: String {
"NS.key.\(count)"
}
var objectKey: String {
"NS.object.\(count)"
}
for key in self.allKeys {
aCoder.encode(key as AnyObject, forKey: keyKey)
aCoder.encode(self[key] as AnyObject, forKey: objectKey)
count += 1
}
}
}
public static var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableDictionary.self {
let dictionary = NSDictionary()
dictionary._storage = self._storage
return dictionary
}
return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject}))
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
// always create and return an NSMutableDictionary
let mutableDictionary = NSMutableDictionary()
mutableDictionary._storage = self._storage
return mutableDictionary
}
return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { __SwiftValue.store($0) } )
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Dictionary<AnyHashable, Any>:
return isEqual(to: other)
case let other as NSDictionary:
return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other))
default:
return false
}
}
open override var hash: Int {
return self.count
}
open var allKeys: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.keys)
} else {
var keys = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
keys.append(key)
}
return keys
}
}
open var allValues: [Any] {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
return Array(_storage.values)
} else {
var values = [Any]()
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
values.append(object(forKey: key)!)
}
return values
}
}
/// Alternative pseudo funnel method for fastpath fetches from dictionaries
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
for (key, value) in _storage {
keys.append(__SwiftValue.fetch(nonOptional: key))
objects.append(__SwiftValue.fetch(nonOptional: value))
}
} else {
let enumerator = keyEnumerator()
while let key = enumerator.nextObject() {
let value = object(forKey: key)!
keys.append(key)
objects.append(value)
}
}
}
open subscript (key: Any) -> Any? {
return object(forKey: key)
}
open func allKeys(for anObject: Any) -> [Any] {
var matching = Array<Any>()
enumerateKeysAndObjects(options: []) { key, value, _ in
if let val = value as? AnyHashable,
let obj = anObject as? AnyHashable {
if val == obj {
matching.append(key)
}
}
}
return matching
}
/// A string that represents the contents of the dictionary, formatted as
/// a property list (read-only)
///
/// If each key in the dictionary is an NSString object, the entries are
/// listed in ascending order by key, otherwise the order in which the entries
/// are listed is undefined. This property is intended to produce readable
/// output for debugging purposes, not for serializing data. If you want to
/// store dictionary data for later retrieval, see
/// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i)
/// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i).
open override var description: String {
return description(withLocale: nil)
}
open var descriptionInStringsFileFormat: String {
var lines = [String]()
for key in self.allKeys {
let line = NSMutableString(capacity: 0)
line.append("\"")
if let descriptionByType = getDescription(of: key) {
line.append(descriptionByType)
} else {
line.append("\(key)")
}
line.append("\"")
line.append(" = ")
line.append("\"")
let value = self.object(forKey: key)!
if let descriptionByTypeValue = getDescription(of: value) {
line.append(descriptionByTypeValue)
} else {
line.append("\(value)")
}
line.append("\"")
line.append(";")
lines.append(line._bridgeToSwift())
}
return lines.joined(separator: "\n")
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
open func description(withLocale locale: Locale?) -> String {
return description(withLocale: locale, indent: 0)
}
/// Returns a string object that represents the contents of the dictionary,
/// formatted as a property list.
///
/// - parameter locale: An object that specifies options used for formatting
/// each of the dictionary’s keys and values; pass `nil` if you don’t
/// want them formatted.
///
/// - parameter level: Specifies a level of indentation, to make the output
/// more readable: the indentation is (4 spaces) * level.
///
/// - returns: A string object that represents the contents of the dictionary,
/// formatted as a property list.
open func description(withLocale locale: Locale?, indent level: Int) -> String {
if level > 100 { return "..." }
var lines = [String]()
let indentation = String(repeating: " ", count: level * 4)
lines.append(indentation + "{")
let nextLevelIndentation = String(repeating: " ", count: (level + 1) * 4)
for key in self.allKeys {
var line = nextLevelIndentation
switch key {
case let nsArray as NSArray:
line += nsArray.description(withLocale: locale, indent: level + 1)
case let nsDate as Date:
line += nsDate.description(with: locale)
case let nsDecimalNumber as NSDecimalNumber:
line += nsDecimalNumber.description(withLocale: locale)
case let nsDictionary as NSDictionary:
line += nsDictionary.description(withLocale: locale, indent: level + 1)
case let nsOderedSet as NSOrderedSet:
line += nsOderedSet.description(withLocale: locale, indent: level + 1)
case let nsSet as NSSet:
line += nsSet.description(withLocale: locale)
default:
line += "\(key)"
}
line += " = "
let object = self.object(forKey: key)!
switch object {
case let nsArray as NSArray:
line += nsArray.description(withLocale: locale, indent: level + 1)
case let nsDate as NSDate:
line += nsDate.description(with: locale)
case let nsDecimalNumber as NSDecimalNumber:
line += nsDecimalNumber.description(withLocale: locale)
case let nsDictionary as NSDictionary:
line += nsDictionary.description(withLocale: locale, indent: level + 1)
case let nsOrderedSet as NSOrderedSet:
line += nsOrderedSet.description(withLocale: locale, indent: level + 1)
case let nsSet as NSSet:
line += nsSet.description(withLocale: locale)
case let hashableObject as Dictionary<AnyHashable, Any>:
line += hashableObject._nsObject.description(withLocale: nil, indent: level + 1)
default:
line += "\(object)"
}
line += ";"
lines.append(line)
}
lines.append(indentation + "}")
return lines.joined(separator: "\n")
}
open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool {
if count != otherDictionary.count {
return false
}
for key in keyEnumerator() {
if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable,
let value = object(forKey: key)! as? AnyHashable {
if otherValue != value {
return false
}
} else {
let otherBridgeable = otherDictionary[key as! AnyHashable]
let bridgeable = object(forKey: key)!
let equal = __SwiftValue.store(optional: otherBridgeable)?.isEqual(__SwiftValue.store(bridgeable))
if equal != true {
return false
}
}
}
return true
}
public struct Iterator : IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
public mutating func next() -> (key: Any, value: Any)? {
if let key = keyGenerator.next() {
return (key, dictionary.object(forKey: key)!)
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
internal struct ObjectGenerator: IteratorProtocol {
let dictionary : NSDictionary
var keyGenerator : Array<Any>.Iterator
mutating func next() -> Any? {
if let key = keyGenerator.next() {
return dictionary.object(forKey: key)!
} else {
return nil
}
}
init(_ dict : NSDictionary) {
self.dictionary = dict
self.keyGenerator = dict.allKeys.makeIterator()
}
}
open func objectEnumerator() -> NSEnumerator {
return NSGeneratorEnumerator(ObjectGenerator(self))
}
open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] {
var objects = [Any]()
for key in keys {
if let object = object(forKey: key) {
objects.append(object)
} else {
objects.append(marker)
}
}
return objects
}
#if !os(WASI)
open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool {
return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile)
}
// the atomically flag is ignored if url of a type that cannot be written atomically.
open func write(to url: URL, atomically: Bool) -> Bool {
do {
let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: .xml, options: 0)
try pListData.write(to: url, options: atomically ? .atomic : [])
return true
} catch {
return false
}
}
#endif
open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateKeysAndObjects(options: [], using: block)
}
open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) {
let count = self.count
var keys = [Any]()
var objects = [Any]()
var sharedStop = ObjCBool(false)
let lock = NSLock()
getObjects(&objects, andKeys: &keys, count: count)
withoutActuallyEscaping(block) { (closure: @escaping (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) -> () in
let iteration: (Int) -> Void = { (idx) in
lock.lock()
var stop = sharedStop
lock.unlock()
if stop.boolValue { return }
closure(keys[idx], objects[idx], &stop)
if stop.boolValue {
lock.lock()
sharedStop = stop
lock.unlock()
return
}
}
#if !os(WASI)
if opts.contains(.concurrent) {
DispatchQueue.concurrentPerform(iterations: count, execute: iteration)
} else {
for idx in 0..<count {
iteration(idx)
}
}
#else
for idx in 0..<count {
iteration(idx)
}
#endif
}
}
open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
return keysSortedByValue(options: [], usingComparator: cmptr)
}
open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] {
let sorted = allKeys.sorted { lhs, rhs in
return cmptr(lhs, rhs) == .orderedSame
}
return sorted
}
open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return keysOfEntries(options: [], passingTest: predicate)
}
open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var matching = Set<AnyHashable>()
enumerateKeysAndObjects(options: opts) { key, value, stop in
if predicate(key, value, stop) {
matching.insert(key as! AnyHashable)
}
}
return matching
}
internal override var _cfTypeID: CFTypeID {
return CFDictionaryGetTypeID()
}
}
extension NSDictionary : _SwiftBridgeable {
internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) }
internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableDictionary {
internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) }
}
extension CFDictionary : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) }
internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject }
}
extension Dictionary : _NSBridgeable {
internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() }
internal var _cfObject: CFDictionary { return _nsObject._cfObject }
}
open class NSMutableDictionary : NSDictionary {
open func removeObject(forKey aKey: Any) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage.removeValue(forKey: __SwiftValue.store(aKey))
}
/// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys)
open func setObject(_ anObject: Any, forKey aKey: AnyHashable) {
guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else {
NSRequiresConcreteImplementation()
}
_storage[__SwiftValue.store(aKey)] = __SwiftValue.store(anObject)
}
public convenience required init() {
self.init(capacity: 0)
}
public convenience init(capacity numItems: Int) {
self.init(objects: [], forKeys: [], count: 0)
// It is safe to reset the storage here because we know is empty
_storage = [NSObject: AnyObject](minimumCapacity: numItems)
}
public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) {
super.init(objects: objects, forKeys: keys, count: cnt)
}
open func addEntries(from otherDictionary: [AnyHashable : Any]) {
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
open func removeAllObjects() {
if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self {
_storage.removeAll()
} else {
for key in allKeys {
removeObject(forKey: key)
}
}
}
open func removeObjects(forKeys keyArray: [Any]) {
for key in keyArray {
removeObject(forKey: key)
}
}
open func setDictionary(_ otherDictionary: [AnyHashable : Any]) {
removeAllObjects()
for (key, obj) in otherDictionary {
setObject(obj, forKey: key)
}
}
/// - Note: See setObject(_:,forKey:) for details on the differential here
public subscript (key: AnyHashable) -> Any? {
get {
return object(forKey: key)
}
set {
if let val = newValue {
setObject(val, forKey: key)
} else {
removeObject(forKey: key)
}
}
}
}
extension NSDictionary : Sequence {
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
// MARK - Shared Key Sets
// We implement this as a shim for now. It is legal to call these methods and the behavior of the resulting NSDictionary will match Darwin's; however, the performance characteristics will be unmodified for the returned dictionary vs. a NSMutableDictionary created without a shared key set.
// SR-XXXX.
extension NSDictionary {
static let sharedKeySetPlaceholder = NSObject()
/* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:.
The keys are copied from the array and must be copyable.
If the array parameter is nil or not an NSArray, an exception is thrown.
If the array of keys is empty, an empty key set is returned.
The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used).
As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant.
Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage.
*/
open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any {
return sharedKeySetPlaceholder
}
}
extension NSMutableDictionary {
/* Create a mutable dictionary which is optimized for dealing with a known set of keys.
Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal.
As with any dictionary, the keys must be copyable.
If keyset is nil, an exception is thrown.
If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown.
*/
public convenience init(sharedKeySet keyset: Any) {
precondition(keyset as? NSObject == NSDictionary.sharedKeySetPlaceholder)
self.init()
}
}
extension NSDictionary: CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self._storage as [NSObject: AnyObject])
}
}
extension NSDictionary: _StructTypeBridgeable {
public typealias _StructType = Dictionary<AnyHashable,Any>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | f293e1b87d8f5805d9fb8a7e586accdc | 36.891421 | 289 | 0.60116 | 4.896414 | false | false | false | false |
jbourjeli/SwiftLabelPhoto | Photos++/LocalPhotoRepository.swift | 1 | 3714 | //
// LocalPhotoRepository.swift
// Photos++
//
// Created by Joseph Bourjeli on 9/29/16.
// Copyright © 2016 WorkSmarterComputing. All rights reserved.
//
import UIKit
fileprivate let fileImagePrefix = "image-"
fileprivate let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
fileprivate let imagesDirectoryURL = PropertyManager.default.sharedDocumentURL.appendingPathComponent("images")
public class LocalPhotoRepository: PhotoRepository {
public enum RepositoryError: Error {
case NoWhereToSave
case InvalidAssetsPath
case InvalidImageData
}
public func saveImage(_ image: UIImage) throws -> String {
if let assetsPath = self.assetsPath() {
let fileURL = URL(fileURLWithPath: assetsPath).appendingPathComponent("\(fileImagePrefix)\(UUID.init().uuidString)")
self.doAsync {
do {
print("saveImage: save to \(fileURL)")
try UIImagePNGRepresentation(image)?.write(to: fileURL)
} catch let error {
print("Error: saveImage [\(error)]")
}
}
return fileURL.lastPathComponent
}
throw RepositoryError.NoWhereToSave
}
public func deleteImage(withFilename filename: String) throws {
if let assetsPath = self.assetsPath() {
let fileURL = URL(fileURLWithPath: assetsPath).appendingPathComponent(filename)
try FileManager.default.removeItem(at: fileURL)
}
}
public func loadImage(withFilename filename: String) throws -> UIImage {
guard let assetsPath = self.assetsPath() else {
throw RepositoryError.InvalidAssetsPath
}
let fileURL = URL(fileURLWithPath: assetsPath).appendingPathComponent(filename)
let data = try Data(contentsOf: fileURL)
if let image = UIImage(data: data) {
return image
}
throw RepositoryError.InvalidImageData
}
public static func migrateImagesToAppGroup() {
let fileManager = FileManager.default
if !fileManager.fileExists(atPath: imagesDirectoryURL.path) {
do {
try fileManager.createDirectory(atPath: imagesDirectoryURL.path, withIntermediateDirectories: false, attributes: nil)
} catch let error {
print("LocalPhotoRepositor: Error creating images directory [\(error)]")
}
}
if let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let documentURL = URL(fileURLWithPath: documentPath, isDirectory: true)
do {
try fileManager.contentsOfDirectory(atPath: documentPath).forEach { element in
if element.hasPrefix(fileImagePrefix) {
try fileManager.moveItem(at: documentURL.appendingPathComponent(element),
to: imagesDirectoryURL.appendingPathComponent(element))
}
}
} catch let error {
print("LocalPhotoRepositor: Error reading document directory [\(error)]")
}
}
}
// MARK: - Privates
fileprivate func assetsPath() -> String? {
return imagesDirectoryURL.path
}
fileprivate func doAsync(_ doBlock: @escaping () -> Void ) {
let backgroundQueue = DispatchQueue.global(qos: .background)
backgroundQueue.async() {
doBlock()
}
}
}
| mit | fa8a3430e40523c2dbefc0c4abe3ac6d | 35.401961 | 133 | 0.608672 | 5.686064 | false | false | false | false |
ashfurrow/eidolon | Kiosk/App/CardHandler.swift | 2 | 7001 | import UIKit
import RxSwift
import CardFlight
class CardHandler: NSObject, CFTTransactionDelegate {
private let _cardStatus = PublishSubject<String>()
private let _userMessages = PublishSubject<String>()
private var cardReader: CFTCardReaderInfo?
var transaction: CFTTransaction?
var cardStatus: Observable<String> {
return _cardStatus.asObservable()
}
var userMessages: Observable<String> {
// User messages are things like "Swipe card", "processing", or "Swipe card again". Due to a problem with the
// CardFlight SDK, the user is prompted to accept processing for card tokenization, which is provides a
// unfriendly user experience (prompting to accept a transaction that we're not actually placing). So we
// auto-accept these requests and filter out confirmation messages, which don't apply to tokenization flows,
// until this issue is fixed: https://github.com/CardFlight/cardflight-v4-ios/issues/4
return _userMessages
.asObservable()
.filter { message -> Bool in
!message.hasSuffix("?")
}
}
var cardFlightCredentials: CFTCredentials {
let credentials = CFTCredentials()
credentials.setup(apiKey: self.APIKey, accountToken: self.APIToken, completion: nil)
return credentials
}
var card: (cardInfo: CFTCardInfo, token: String)?
let APIKey: String
let APIToken: String
init(apiKey: String, accountToken: String){
APIKey = apiKey
APIToken = accountToken
super.init()
self.transaction = CFTTransaction(delegate: self)
}
deinit {
self.end()
}
func startSearching() {
_cardStatus.onNext("Starting search...")
let tokenizationParameters = CFTTokenizationParameters(customerId: nil, credentials: self.cardFlightCredentials)
self.transaction?.beginTokenizing(tokenizationParameters: tokenizationParameters)
}
func end() {
transaction?.select(processOption: CFTProcessOption.abort)
transaction = nil
}
func transaction(_ transaction: CFTTransaction, didUpdate state: CFTTransactionState, error: Error?) {
switch state {
case .completed:
_cardStatus.onNext("Transaction completed")
case .processing:
_cardStatus.onNext("Transaction processing")
case .deferred:
_cardStatus.onNext("Transaction deferred")
case .pendingCardInput:
_cardStatus.onNext("Pending card input")
transaction.select(cardReaderInfo: cardReader, cardReaderModel: cardReader?.cardReaderModel ?? .unknown)
case .pendingTransactionParameters:
_cardStatus.onNext("Pending transaction parameters")
case .unknown:
_cardStatus.onNext("Unknown transactionstate")
case .pendingProcessOption:
break
}
}
func transaction(_ transaction: CFTTransaction, didComplete historicalTransaction: CFTHistoricalTransaction) {
if let cardInfo = historicalTransaction.cardInfo, let token = historicalTransaction.cardToken {
self.card = (cardInfo: cardInfo, token: token)
_cardStatus.onNext("Got Card")
_cardStatus.onCompleted()
} else {
_cardStatus.onNext("Card Flight Error – could not retrieve card data.");
if let error = historicalTransaction.error {
_cardStatus.onNext("response Error \(error)");
logger.log("CardReader got a response it cannot handle")
}
startSearching()
}
}
func transaction(_ transaction: CFTTransaction, didReceive cardReaderEvent: CFTCardReaderEvent, cardReaderInfo: CFTCardReaderInfo?) {
_cardStatus.onNext(cardReaderEvent.statusMessage)
}
func transaction(_ transaction: CFTTransaction, didUpdate cardReaderArray: [CFTCardReaderInfo]) {
self.cardReader = cardReaderArray.first
_cardStatus.onNext("Received new card reader availability, number of readers: \(cardReaderArray.count)")
}
func transaction(_ transaction: CFTTransaction, didRequestProcessOption cardInfo: CFTCardInfo) {
logger.log("Received request for processing option, will process transaction.")
_cardStatus.onNext("Request for process option, automatically processing...")
// We auto-accept the process option on the user's behalf because the prompt doesn't make sense in a
// tokenization flow. See comments in `userMessages` property above.
transaction.select(processOption: .process)
}
func transaction(_ transaction: CFTTransaction, didRequestDisplay message: CFTMessage) {
let message = message.primary ?? message.secondary ?? ""
_userMessages.onNext(message)
logger.log("Received request to display message: \(message)")
_cardStatus.onNext("Received message for user: \(message)")
}
}
typealias UnhandledDelegateCallbacks = CardHandler
/// We don't expect any of these functions to be called, but they are required for the delegate protocol.
extension UnhandledDelegateCallbacks {
func transaction(_ transaction: CFTTransaction, didDefer transactionData: Data) {
logger.log("Transaction has been deferred.")
_cardStatus.onNext("Transaction deferred")
}
public func transaction(_ transaction: CFTTransaction, didRequest cvm: CFTCVM) {
if cvm == CFTCVM.signature {
logger.log("Transaction requested signature from user, which should not occur for tokenization.")
_cardStatus.onNext("Ignoring user signature request from CardFlight")
}
}
}
extension CFTCardReaderEvent {
var statusMessage: String {
switch self {
case .unknown:
return "Unknown card event"
case .disconnected:
return "Reader is disconnected"
case .connected:
return "Reader is connected"
case .connectionErrored:
return "Connection error occurred"
case .cardSwiped:
return "Card swiped"
case .cardSwipeErrored:
return "Card swipe error"
case .cardInserted:
return "Card inserted"
case .cardInsertErrored:
return "Card insertion error"
case .cardRemoved:
return "Card removed"
case .cardTapped:
return "Card tapped"
case .cardTapErrored:
return "Card tap error"
case .updateStarted:
return "Update started"
case .updateCompleted:
return "Updated completed"
case .audioRecordingPermissionNotGranted:
return "iOS audio permissions no granted"
case .fatalError:
return "Fatal error"
case .connecting:
return "Connecting"
case .batteryStatusUpdated:
return "Battery status updated"
}
}
}
| mit | 7a3f3b7849f03d70b9c07ffa6142dc50 | 37.668508 | 137 | 0.66038 | 4.884159 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/FiatAccountTransactions/PaymentMethod/PaymentMethodInteractor.swift | 1 | 6643 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import PlatformKit
import PlatformUIKit
import RIBs
import RxCocoa
import RxSwift
import ToolKit
enum PaymentMethodAction {
case items([PaymentMethodCellSectionModel])
}
enum PaymentMethodEffects {
case closeFlow
case navigate(method: PaymentMethod)
}
protocol PaymentMethodRouting: ViewableRouting {}
protocol PaymentMethodPresentable: Presentable {
func connect(action: Driver<PaymentMethodAction>) -> Driver<PaymentMethodEffects>
}
protocol PaymentMethodListener: AnyObject {
/// Close the payment method screen
func closePaymentMethodScreen()
/// Routes to the `Linked Banks` screen
func routeToLinkedBanks()
/// Routes to the `Add [FiatCurrency] Wire Transfer` screen
func routeToWireTransfer()
}
final class PaymentMethodInteractor: PresentableInteractor<PaymentMethodPresentable>, PaymentMethodInteractable {
weak var router: PaymentMethodRouting?
weak var listener: PaymentMethodListener?
// MARK: - Private Properties
private var paymentMethodTypes: Single<[PaymentMethodType]> {
fiatCurrencyService
.tradingCurrency
.asSingle()
.flatMap(weak: self) { (self, fiatCurrency) -> Single<[PaymentMethodType]> in
self.linkedBanksFactory.bankPaymentMethods(for: fiatCurrency)
}
}
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let fiatCurrencyService: FiatCurrencyServiceAPI
private let linkedBanksFactory: LinkedBanksFactoryAPI
private let loadingViewPresenter: LoadingViewPresenting
private let selectionRelay = PublishRelay<(method: PaymentMethod, methodType: PaymentMethodType)>()
init(
presenter: PaymentMethodPresentable,
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
linkedBanksFactory: LinkedBanksFactoryAPI = resolve(),
fiatCurrencyService: FiatCurrencyServiceAPI = resolve(),
loadingViewPresenter: LoadingViewPresenting = resolve()
) {
self.analyticsRecorder = analyticsRecorder
self.linkedBanksFactory = linkedBanksFactory
self.fiatCurrencyService = fiatCurrencyService
self.loadingViewPresenter = loadingViewPresenter
super.init(presenter: presenter)
}
override func didBecomeActive() {
super.didBecomeActive()
let methods = paymentMethodTypes
.handleLoaderForLifecycle(loader: loadingViewPresenter, style: .circle)
.map { [weak self] (methods: [PaymentMethodType]) -> [PaymentMethodCellViewModelItem] in
guard let self = self else { return [] }
return methods.compactMap { type in
self.generateCellType(by: type) ?? nil
}
}
.map { [PaymentMethodCellSectionModel(items: $0)] }
.map { PaymentMethodAction.items($0) }
.asDriver(onErrorDriveWith: .empty())
let selectedPaymentMethod = selectionRelay
.share(replay: 1, scope: .whileConnected)
selectedPaymentMethod
.map(\.method)
.map(PaymentMethodEffects.navigate(method:))
.asDriverCatchError()
.drive(onNext: handle(effect:))
.disposeOnDeactivate(interactor: self)
presenter.connect(action: methods)
.drive(onNext: handle(effect:))
.disposeOnDeactivate(interactor: self)
}
// MARK: - Private
private func handle(effect: PaymentMethodEffects) {
switch effect {
case .closeFlow:
listener?.closePaymentMethodScreen()
case .navigate(let method):
switch method.type {
case .bankAccount:
listener?.routeToWireTransfer()
case .bankTransfer:
listener?.routeToLinkedBanks()
case .card,
.funds,
.applePay:
unimplemented()
}
}
}
private func generateCellType(by paymentMethodType: PaymentMethodType) -> PaymentMethodCellViewModelItem? {
var cellType: PaymentMethodCellViewModelItem?
switch paymentMethodType {
case .suggested(let method):
let viewModel: ExplainedActionViewModel
switch method.type {
case .funds:
unimplemented()
case .card:
unimplemented()
case .applePay:
unimplemented()
case .bankTransfer:
viewModel = ExplainedActionViewModel(
thumbImage: "icon-bank",
// TODO: Localization
title: "Link a Bank",
descriptions: [
// TODO: Localization
.init(title: "Instantly Available", titleColor: .titleText, titleFontSize: 14),
// TODO: Localization
// swiftlint:disable line_length
.init(title: "Securely link a bank and send cash to your Blockchain.com Wallet at anytime.", titleColor: .descriptionText, titleFontSize: 12)
],
badgeTitle: "Most Popular",
uniqueAccessibilityIdentifier: ""
)
case .bankAccount:
viewModel = ExplainedActionViewModel(
thumbImage: "icon-deposit-cash",
// TODO: Localization
title: "Wire Transfer",
descriptions: [
// TODO: Localization
.init(title: "3-5 Business Days", titleColor: .titleText, titleFontSize: 14),
// TODO: Localization
// swiftlint:disable line_length
.init(title: "Send funds directly from your bank account to your Blockchain.com Wallet. Bank fees may apply.", titleColor: .descriptionText, titleFontSize: 12)
],
badgeTitle: nil,
uniqueAccessibilityIdentifier: ""
)
}
viewModel.tap
// TODO: Analytics
.map { _ in (method, paymentMethodType) }
.emit(to: selectionRelay)
.disposeOnDeactivate(interactor: self)
cellType = .suggestedPaymentMethod(viewModel)
case .card,
.account,
.linkedBank,
.applePay:
cellType = nil
}
return cellType
}
}
| lgpl-3.0 | f329aee777f1ae588879b9572e3f227a | 35.494505 | 183 | 0.600873 | 5.877876 | false | false | false | false |
cfilipov/MuscleBook | MuscleBook/ExerciseDetailViewController.swift | 1 | 5095 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
import Eureka
import Kingfisher
class ExerciseDetailViewController : FormViewController {
private let db = DB.sharedInstance
let colorGenerator = colorPalette.repeatGenerator
let formatter = NSDateFormatter()
var muscleColorImages: [Muscle: UIImage] = [:]
var musclesDictionary: [MuscleMovement.Classification: [Muscle]] = [:]
let exercise: Exercise
let anatomyRow = SideBySideAnatomyViewRow("anatomy")
let whiteCircle = UIImage.circle(12, color: UIColor.whiteColor())
private var performanceCount: Int {
return db.count(Exercise.self, exerciseID: exercise.exerciseID)
}
init(exercise: Exercise) {
self.exercise = exercise
super.init(style: .Grouped)
hidesBottomBarWhenPushed = true
let muscles = try! db.find(exerciseID: exercise.exerciseID)
musclesDictionary = muscles.dictionary()
let muscleColorCoding = Dictionary(
Set<Muscle>(musclesDictionary.values.flatMap{$0})
.map{($0,self.colorGenerator.next()!)}
)
var anatomyConfig = AnatomyViewConfig(fillColors: muscleColorCoding, orientation: nil)
let tmpAnatomyView = AnatomySplitView()
anatomyConfig = tmpAnatomyView.configure(anatomyConfig)
anatomyRow.value = anatomyConfig
muscleColorImages = anatomyConfig.fillColors.mapValues{UIImage.circle(12, color: $0)}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView?.contentInset = UIEdgeInsetsMake(-36, 0, 0, 0)
title = "Exercise"
form +++ Section()
<<< LabelRow() {
$0.title = "Name"
$0.value = exercise.name
}
<<< LabelRow() {
$0.title = "Equipment"
$0.value = exercise.equipment.name
}
<<< LabelRow() {
$0.title = "Force"
$0.value = exercise.force?.name
}
<<< LabelRow() {
$0.title = "Mechanics"
$0.value = exercise.mechanics?.name
}
<<< LabelRow() {
$0.title = "Type"
$0.value = exercise.exerciseType.name
}
<<< LabelRow() {
$0.title = "Exercise ID"
$0.value = String(exercise.exerciseID)
}
<<< anatomyRow
<<< PushViewControllerRow() {
$0.title = "Instructions"
$0.controller = { ExerciseInstructionsViewController(exercise: self.exercise) }
}
<<< PushViewControllerRow() {
$0.title = "Statistics"
$0.controller = { ExerciseStatisticsViewController(exercise: self.exercise.exerciseReference) }
$0.hidden = self.performanceCount == 0 ? true : false
}
if let s = musclesDictionary[.Target] where !s.isEmpty {
form +++ Section("Target Muscles") <<< s.map(rowForMuscle)
}
if let s = musclesDictionary[.Stabilizer] where !s.isEmpty {
form +++ Section("Stabilizers") <<< s.map(rowForMuscle)
}
if let s = musclesDictionary[.Synergist] where !s.isEmpty {
form +++ Section("Synergists") <<< s.map(rowForMuscle)
}
if let s = musclesDictionary[.DynamicStabilizer] where !s.isEmpty {
form +++ Section("Dynamic Stabilizers") <<< s.map(rowForMuscle)
}
if let gif = exercise.gif, url = NSURL(string: gif) {
let prefetcher = ImagePrefetcher(
urls: [url],
optionsInfo: nil,
progressBlock: nil,
completionHandler: nil
)
prefetcher.start()
}
}
private func rowForString(name: String) -> LabelRow {
let row = LabelRow()
row.title = name
row.cellSetup(cellSetupHandler)
return row
}
private func rowForMuscle(muscle: Muscle) -> LabelRow {
let row = LabelRow()
row.title = muscle.name
row.cellSetup(cellSetupHandler)
row.cellSetup { cell, row in
cell.imageView?.image = self.muscleColorImages[muscle] ?? self.whiteCircle
}
return row
}
private func cellSetupHandler(cell: LabelCell, row: LabelRow) {
cell.detailTextLabel?.hidden = true
}
}
| gpl-3.0 | a39291ccdc163525a5a1731c2e3c3f73 | 30.84375 | 107 | 0.608636 | 4.365895 | false | false | false | false |
rayho/CodePathTwitter | CodePathTwitter/ComposeController.swift | 1 | 4613 | //
// ComposeController.swift
// CodePathTwitter
//
// Created by Ray Ho on 9/28/14.
// Copyright (c) 2014 Prime Rib Software. All rights reserved.
//
import UIKit
class ComposeController: UIViewController, UITextViewDelegate {
let MAX_CHARS: Int = 140
var charsRemainingLabel: UILabel!
var textView: UITextView!
var inReplyToTweet: Tweet?
// Convenience method to launch this view controller, for composing a new tweet
class func launch(fromViewController: UIViewController) {
launch(fromViewController, inReplyToTweet: nil)
}
// Convenience method to launch this view controller, for replying to a tweet
class func launch(fromViewController: UIViewController, inReplyToTweet: Tweet?) {
var toViewController: ComposeController = ComposeController()
toViewController.inReplyToTweet = inReplyToTweet
var navController: UINavigationController = UINavigationController(rootViewController: toViewController)
fromViewController.presentViewController(navController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Construct navigation
self.navigationItem.title = inReplyToTweet != nil ? "Reply" : "Compose"
var cancelButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel:")
var submitButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "submit:")
self.navigationItem.leftBarButtonItem = cancelButton
self.navigationItem.rightBarButtonItem = submitButton
// Construct views
self.view.backgroundColor = UIColor.whiteColor()
charsRemainingLabel = UILabel()
charsRemainingLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
charsRemainingLabel.numberOfLines = 0
charsRemainingLabel.textAlignment = NSTextAlignment.Right
textView = UITextView()
textView.setTranslatesAutoresizingMaskIntoConstraints(false)
textView.font = UIFont.systemFontOfSize(17)
textView.delegate = self
if (inReplyToTweet != nil) {
var replyToText: String = "@\(inReplyToTweet!.user.screenName) "
for screenName in inReplyToTweet!.mentions {
replyToText += "@\(screenName) "
}
textView.text = replyToText
}
self.view.addSubview(charsRemainingLabel)
self.view.addSubview(textView)
self.view.layoutIfNeeded()
let viewDictionary: Dictionary = ["charsRemainingLabel": charsRemainingLabel, "textView": textView]
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textView]-[charsRemainingLabel(60)]-|", options: NSLayoutFormatOptions.allZeros, metrics: nil, views: viewDictionary))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.topLayoutGuide, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.bottomLayoutGuide, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: charsRemainingLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: textView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 0))
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
func cancel(sender: AnyObject) {
NSLog("Cancelling composer ...")
dismissViewControllerAnimated(true, completion: nil)
}
func submit(sender: AnyObject) {
NSLog("Submitting tweet ...")
var textTrimmed = textView.text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
if (textTrimmed.utf16Count > 0) {
TWTR.postTweet(textTrimmed, inReplyToStatusId: (inReplyToTweet != nil) ? inReplyToTweet!.id : nil)
dismissViewControllerAnimated(true, completion: nil)
} else {
NSLog("No text in tweet. Ignoring submit button press.")
}
}
func textViewDidChange(textView: UITextView) {
updateUI()
}
func updateUI() {
let numCharsRemaining: Int = MAX_CHARS - self.textView.text.utf16Count
charsRemainingLabel.text = "\(numCharsRemaining)"
}
}
| mit | bf83f69ff6bc505564b9f96defa668ca | 47.052083 | 233 | 0.715803 | 5.401639 | false | false | false | false |
antrix1989/PhotoSlider | Pod/Classes/ImageView.swift | 1 | 3160 | //
// ImageView.swift
//
// Created by nakajijapan on 3/29/15.
// Copyright (c) 2015 net.nakajijapan. All rights reserved.
//
import UIKit
class ImageView: UIView, UIScrollViewDelegate {
var imageView:UIImageView!
var scrollView:UIScrollView!
var progressView: PhotoSlider.ProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
func initialize() {
self.backgroundColor = UIColor.clearColor()
self.userInteractionEnabled = true
// for zoom
self.scrollView = UIScrollView(frame: self.bounds)
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.minimumZoomScale = 1.0
self.scrollView.maximumZoomScale = 3.0
self.scrollView.bounces = true
self.scrollView.delegate = self
// image
self.imageView = UIImageView(frame: self.bounds)
self.imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.imageView.userInteractionEnabled = true
self.addSubview(self.scrollView)
self.scrollView.addSubview(self.imageView)
// progress view
self.progressView = ProgressView(frame: CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0))
self.progressView.center = CGPoint(x: self.frame.size.width / 2.0, y: self.frame.size.height / 2.0)
self.progressView.hidden = true
self.addSubview(self.progressView)
let doubleTabGesture = UITapGestureRecognizer(target: self, action: "didDoubleTap:")
doubleTabGesture.numberOfTapsRequired = 2
self.addGestureRecognizer(doubleTabGesture)
self.imageView.autoresizingMask =
UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleLeftMargin |
UIViewAutoresizing.FlexibleRightMargin |
UIViewAutoresizing.FlexibleTopMargin |
UIViewAutoresizing.FlexibleHeight |
UIViewAutoresizing.FlexibleBottomMargin
}
func loadImage(imageURL: NSURL) {
self.progressView.hidden = false
self.imageView.sd_setImageWithURL(
imageURL,
placeholderImage: nil,
options: .CacheMemoryOnly,
progress: { (receivedSize, expectedSize) -> Void in
let progress = Float(receivedSize) / Float(expectedSize)
self.progressView.animateCurveToProgress(progress)
}) { (image, error, cacheType, ImageView) -> Void in
self.progressView.hidden = true
}
}
func didDoubleTap(sender: UIGestureRecognizer) {
if self.scrollView.zoomScale == 1.0 {
self.scrollView.setZoomScale(2.0, animated: true)
} else {
self.scrollView.setZoomScale(0.0, animated: true)
}
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
}
| mit | 338c0f4a9b3ed9a7bef0337f75645e8b | 32.263158 | 107 | 0.640823 | 5.096774 | false | false | false | false |
carabina/DDMathParser | MathParser/Expression.swift | 2 | 5048 | //
// Expression.swift
// DDMathParser
//
// Created by Dave DeLong on 8/17/15.
//
//
import Foundation
public struct ExpressionError: ErrorType {
public enum Kind {
case InvalidFormat
case MissingLeftOperand(Operator)
case MissingRightOperand(Operator)
}
public let kind: Kind
public let range: Range<String.Index>
}
public class Expression {
public enum Kind {
case Number(Double)
case Variable(String)
case Function(String, Array<Expression>)
public var isNumber: Bool {
guard case .Number(_) = self else { return false }
return true
}
public var isVariable: Bool {
guard case .Variable(_) = self else { return false }
return true
}
public var isFunction: Bool {
guard case .Function(_) = self else { return false }
return true
}
}
public let kind: Kind
public let range: Range<String.Index>
public init(string: String, operatorSet: OperatorSet = OperatorSet.defaultOperatorSet, options: TokenResolverOptions = TokenResolverOptions.defaultOptions, locale: NSLocale? = nil) throws {
let tokenizer = Tokenizer(string: string, operatorSet: operatorSet, locale: locale)
let resolver = TokenResolver(tokenizer: tokenizer, options: options)
let grouper = TokenGrouper(resolver: resolver)
let expressionizer = Expressionizer(grouper: grouper)
let e: Expression
do {
e = try expressionizer.expression()
} catch let error {
self.kind = .Variable("fake")
self.range = string.startIndex ..< string.endIndex
throw error
}
self.kind = e.kind
self.range = e.range
if case let .Function(_, args) = kind {
args.forEach { $0.parent = self }
}
}
internal weak var parent: Expression?
internal init(kind: Kind, range: Range<String.Index>) {
self.kind = kind
self.range = range
if case let .Function(_, args) = kind {
args.forEach { $0.parent = self }
}
}
public func simplify(substitutions: Substitutions = [:], evaluator: Evaluator) -> Expression {
switch kind {
case .Number(_): return Expression(kind: kind, range: range)
case .Variable(_):
if let resolved = try? evaluator.evaluate(self, substitutions: substitutions) {
return Expression(kind: .Number(resolved), range: range)
}
return Expression(kind: kind, range: range)
case let .Function(f, args):
let newArgs = args.map { $0.simplify(substitutions, evaluator: evaluator) }
let areAllArgsNumbers = newArgs.reduce(true) { $0 && $1.kind.isNumber }
guard areAllArgsNumbers else {
return Expression(kind: .Function(f, newArgs), range: range)
}
guard let value = try? evaluator.evaluate(self) else {
return Expression(kind: .Function(f, newArgs), range: range)
}
return Expression(kind: .Number(value), range: range)
}
}
}
extension Expression: CustomStringConvertible {
public var description: String {
switch kind {
case .Number(let d): return d.description
case .Variable(let v):
if v.containsString(" ") { return "\"\(v)\"" }
return "$\(v)"
case .Function(let f, let args):
let params = args.map { $0.description }
if let builtIn = BuiltInOperator(rawValue: f) {
let op = Operator(builtInOperator: builtIn)
guard let token = op.tokens.first else {
fatalError("Built-in operator doesn't have any tokens")
}
switch (op.arity, op.associativity) {
case (.Binary, _):
return "\(params[0]) \(token) \(params[1])"
case (.Unary, .Left):
return "\(params[0])\(token)"
case (.Unary, .Right):
return "\(token)\(params[0])"
}
} else {
let joined = params.joinWithSeparator(", ")
return "\(f)(\(joined))"
}
}
}
}
extension Expression: Equatable { }
public func ==(lhs: Expression, rhs: Expression) -> Bool {
switch (lhs.kind, rhs.kind) {
case (.Number(let l), .Number(let r)): return l == r
case (.Variable(let l), .Variable(let r)): return l == r
case (.Function(let lf, let lArg), .Function(let rf, let rArg)): return lf == rf && lArg == rArg
default: return false
}
}
| mit | 97637c71191975eda64e08de9b006cfe | 33.813793 | 193 | 0.530111 | 4.803045 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/RoundedCornerView.swift | 5 | 991 | import UIKit
class RoundedCornerView: UIView {
var corners: UIRectCorner = [] {
didSet {
update()
}
}
var radius: CGFloat = 0 {
didSet {
update()
}
}
private var currentSize = CGSize.zero
func update() {
currentSize = bounds.size
let radii = CGSize(width: radius, height: radius)
let bezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: radii)
let shapeLayer = CAShapeLayer()
shapeLayer.frame = bounds
shapeLayer.path = bezierPath.cgPath
layer.mask = shapeLayer
}
private func updateIfSizeChanged() {
if currentSize != bounds.size {
update()
}
}
override var bounds: CGRect {
didSet {
updateIfSizeChanged()
}
}
override var frame: CGRect {
didSet {
updateIfSizeChanged()
}
}
}
| mit | b9b05cdbd4317fc97dbf1922da11a32f | 21.022222 | 106 | 0.536831 | 5.161458 | false | false | false | false |
movabletype/smartphone-app | MT_iOS/MT_iOS/Classes/View/UploaderTableViewCell.swift | 1 | 1101 | //
// UploaderTableViewCell.swift
// MT_iOS
//
// Created by CHEEBOW on 2016/02/09.
// Copyright © 2016年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class UploaderTableViewCell: UITableViewCell {
@IBOutlet weak var thumbView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var checkMark: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
progress = 0.0
self.checkMark.alpha = 0.0
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
var progress: Float {
get {
return progressView.progress
}
set {
progressView.progress = newValue
}
}
var uploaded: Bool {
get {
return self.checkMark.alpha == 1.0
}
set {
self.checkMark.alpha = newValue ? 1.0 : 0.0
}
}
}
| mit | 5623366cfa171fc3914bb4c72f91fa8d | 22.361702 | 63 | 0.598361 | 4.556017 | false | false | false | false |
Fenrikur/ef-app_ios | Eurofurence/Extensions/UITableView+Extensions.swift | 1 | 2448 | import UIKit
extension UITableView {
func register<T>(_ cellType: T.Type) where T: UITableViewCell {
let cellName = String(describing: T.self)
let nib = UINib(nibName: cellName, bundle: .main)
register(nib, forCellReuseIdentifier: cellName)
}
func dequeue<T>(_ cellType: T.Type) -> T where T: UITableViewCell {
let identifier = String(describing: T.self)
guard let cell = dequeueReusableCell(withIdentifier: identifier) as? T else {
abortDueToUnregisteredOrMissingCell(cellType, identifier: identifier)
}
return cell
}
func dequeue<T>(_ cellType: T.Type, for indexPath: IndexPath) -> T where T: UITableViewCell {
let identifier = String(describing: T.self)
guard let cell = dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? T else {
abortDueToUnregisteredOrMissingCell(cellType, identifier: identifier)
}
return cell
}
func customCellForRow<T>(at indexPath: IndexPath) -> T where T: UITableViewCell {
let cell = cellForRow(at: indexPath)
guard let castedCell = cellForRow(at: indexPath) as? T else {
fatalError("Expected to dequeue cell of type \(T.self), got \(type(of: cell))")
}
return castedCell
}
func registerConventionBrandedHeader() {
let headerType = ConventionBrandedTableViewHeaderFooterView.self
register(headerType, forHeaderFooterViewReuseIdentifier: headerType.identifier)
}
func dequeueConventionBrandedHeader() -> ConventionBrandedTableViewHeaderFooterView {
let identifier = ConventionBrandedTableViewHeaderFooterView.identifier
guard let header = dequeueReusableHeaderFooterView(withIdentifier: identifier) as? ConventionBrandedTableViewHeaderFooterView else {
fatalError("\(ConventionBrandedTableViewHeaderFooterView.self) is not registered in this table view!")
}
return header
}
func adjustScrollIndicatorInsetsForSafeAreaCompensation() {
if #available(iOS 11.0, *) {
scrollIndicatorInsets.right = -safeAreaInsets.right
}
}
private func abortDueToUnregisteredOrMissingCell<T>(_ type: T.Type, identifier: String) -> Never {
fatalError("Cell registered with identifier \"\(identifier)\" not present, or not an instance of \(type)")
}
}
| mit | 17a8571a4bddd2cd56c162d1d5e0f356 | 38.483871 | 140 | 0.675654 | 4.995918 | false | false | false | false |
qianyu09/AppLove | App Love/UI/ViewControllers/AppListViewController.swift | 1 | 3906 | //
// AppListViewController.swift
// App Love
//
// Created by Woodie Dovich on 2016-03-31.
// Copyright © 2016 Snowpunch. All rights reserved.
//
// The main view. Can reorder or delete apps.
//
import UIKit
class AppListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var toolBar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
initTableView()
Theme.toolBar(toolBar)
displayAppList()
// BaseHttper()
}
func displayAppList() {
if (AppList.sharedInst.load() == false) {
loadDefaultApps()
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (SearchList.sharedInst.appModelDic.count > 0) {
addAppsSelectedFromSearchResults()
}
}
func addAppsSelectedFromSearchResults() {
let newApps = SearchList.sharedInst.getArray()
AppList.sharedInst.appModels.appendContentsOf(newApps)
SearchList.sharedInst.removeAll()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
AppList.sharedInst.save()
self.tableView.reloadData()
})
}
// apps to display initially, to check out how the app functions
func loadDefaultApps () {
let defaultAppIds = [Const.MusketSmoke, Const.AppLove]
for appId:Int in defaultAppIds {
AppInfo.get(String(appId)) { (model, succeeded, error) -> Void in
// add an app model
if let appModel = model {
AppList.sharedInst.addAppModel(appModel)
}
let finishedLoading = (defaultAppIds.count == AppList.sharedInst.appModels.count)
if (finishedLoading)
{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
AppList.sharedInst.save()
self.tableView.reloadData()
})
}
}
}
}
@IBAction func onQRCode(sender: AnyObject) {
performSegueWithIdentifier("QRCode", sender: nil)
}
@IBAction func onSearch(sender: AnyObject) {
performSegueWithIdentifier("AppSearch", sender: nil)
}
@IBAction func editMode(sender: UIBarButtonItem) {
if (self.tableView.editing) {
sender.title = "Edit"
self.tableView.setEditing(false, animated: true)
} else {
sender.title = "Done"
self.tableView.setEditing(true, animated: true)
}
}
@IBAction func onAbout(sender: AnyObject) {
let alertController:UIAlertController = UIAlertController(title: "About", message: "where did you want to go", preferredStyle: UIAlertControllerStyle.ActionSheet)
let action1:UIAlertAction = UIAlertAction(title: "AppList", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
self.performSegueWithIdentifier("AppList", sender: nil)
}
let action2:UIAlertAction = UIAlertAction(title: "about", style: UIAlertActionStyle.Default) { (action:UIAlertAction) in
if let storyboard = self.storyboard {
let aboutVC = storyboard.instantiateViewControllerWithIdentifier("about")
self.navigationController!.pushViewController(aboutVC, animated: true)
}
}
let action3:UIAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(action1)
alertController.addAction(action2)
alertController.addAction(action3)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
| mit | f5004684702237a0209e23e15ee06a89 | 32.956522 | 170 | 0.599488 | 4.936789 | false | false | false | false |
rsyncOSX/RsyncOSX | RsyncOSX/RemoteinfoEstimation.swift | 1 | 7400 | //
// RemoteInfoTaskWorkQueue.swift
// RsyncOSX
//
// Created by Thomas Evensen on 31.12.2017.
// Copyright © 2017 Thomas Evensen. All rights reserved.
//
// swiftlint:disable line_length
import Cocoa
import Foundation
protocol SetRemoteInfo: AnyObject {
func setremoteinfo(remoteinfotask: RemoteinfoEstimation?)
func getremoteinfo() -> RemoteinfoEstimation?
}
final class RemoteinfoEstimation: SetConfigurations, Presentoutput {
// (hiddenID, index)
typealias Row = (Int, Int)
var stackoftasktobeestimated: [Row]?
var records: [NSMutableDictionary]?
var updateviewprocesstermination: () -> Void
weak var startstopProgressIndicatorDelegate: StartStopProgressIndicator?
weak var getmultipleselectedindexesDelegate: GetMultipleSelectedIndexes?
var index: Int?
private var maxnumber: Int?
// estimated list, configs as NSDictionary
var estimatedlistandconfigs: Estimatedlistforsynchronization?
private func prepareandstartexecutetasks() {
stackoftasktobeestimated = [Row]()
if getmultipleselectedindexesDelegate?.multipleselection() == false {
for i in 0 ..< (configurations?.getConfigurations()?.count ?? 0) {
let task = configurations?.getConfigurations()?[i].task
if SharedReference.shared.synctasks.contains(task ?? "") {
stackoftasktobeestimated?.append((configurations?.getConfigurations()?[i].hiddenID ?? 0, i))
}
}
} else {
let indexes = getmultipleselectedindexesDelegate?.getindexes()
for i in 0 ..< (indexes?.count ?? 0) {
if let index = indexes?[i] {
let task = configurations?.getConfigurations()?[index].task
if SharedReference.shared.synctasks.contains(task ?? "") {
stackoftasktobeestimated?.append((configurations?.getConfigurations()?[index].hiddenID ?? 0, index))
}
}
}
}
maxnumber = stackoftasktobeestimated?.count
}
func selectalltaskswithnumbers(deselect: Bool) {
guard records != nil else { return }
for i in 0 ..< (records?.count ?? 0) {
let number = (records?[i].value(forKey: DictionaryStrings.transferredNumber.rawValue) as? String) ?? "0"
let delete = (records?[i].value(forKey: DictionaryStrings.deletefiles.rawValue) as? String) ?? "0"
if Int(number) ?? 0 > 0 || Int(delete) ?? 0 > 0 {
if deselect {
records?[i].setValue(0, forKey: DictionaryStrings.select.rawValue)
} else {
records?[i].setValue(1, forKey: DictionaryStrings.select.rawValue)
}
}
}
}
private func finalizeandpreparesynchronizelist() {
guard self.records != nil else { return }
var quickbackuplist = [Int]()
var records = [NSMutableDictionary]()
for i in 0 ..< (self.records?.count ?? 0) {
if self.records?[i].value(forKey: DictionaryStrings.select.rawValue) as? Int == 1 {
if let hiddenID = self.records?[i].value(forKey: DictionaryStrings.hiddenID.rawValue) as? Int,
let record = self.records?[i]
{
quickbackuplist.append(hiddenID)
records.append(record)
}
}
}
estimatedlistandconfigs = Estimatedlistforsynchronization(quickbackuplist: quickbackuplist, estimatedlist: records)
SharedReference.shared.estimatedlistforsynchronization = estimatedlistandconfigs
}
@MainActor
private func startestimation() async {
guard (stackoftasktobeestimated?.count ?? 0) > 0 else { return }
if let index = stackoftasktobeestimated?.remove(at: 0).1 {
self.index = index
startstopProgressIndicatorDelegate?.start()
let estimation = EstimateremoteInformationOnetask(index: index, local: false, processtermination: processtermination)
await estimation.startestimation()
}
}
init(viewcontroller: NSViewController, processtermination: @escaping () -> Void) {
updateviewprocesstermination = processtermination
startstopProgressIndicatorDelegate = viewcontroller as? StartStopProgressIndicator
getmultipleselectedindexesDelegate = SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain
prepareandstartexecutetasks()
records = [NSMutableDictionary]()
estimatedlistandconfigs = Estimatedlistforsynchronization()
Task {
await startestimation()
}
}
deinit {
self.stackoftasktobeestimated = nil
self.estimatedlistandconfigs = nil
// print("deinit RemoteinfoEstimation")
}
func abort() {
stackoftasktobeestimated = nil
estimatedlistandconfigs = nil
}
}
extension RemoteinfoEstimation: CountRemoteEstimatingNumberoftasks {
func maxCount() -> Int {
return maxnumber ?? 0
}
func inprogressCount() -> Int {
return stackoftasktobeestimated?.count ?? 0
}
}
extension RemoteinfoEstimation {
func processtermination(data: [String]?) {
presentoutputfromrsync(data: data)
if let index = index {
let record = RemoteinfonumbersOnetask(outputfromrsync: data).record()
record.setValue(configurations?.getConfigurations()?[index].localCatalog, forKey: DictionaryStrings.localCatalog.rawValue)
record.setValue(configurations?.getConfigurations()?[index].offsiteCatalog, forKey: DictionaryStrings.offsiteCatalog.rawValue)
record.setValue(configurations?.getConfigurations()?[index].hiddenID, forKey: DictionaryStrings.hiddenID.rawValue)
record.setValue(configurations?.getConfigurations()?[index].dayssincelastbackup, forKey: DictionaryStrings.daysID.rawValue)
if configurations?.getConfigurations()?[index].offsiteServer.isEmpty == true {
record.setValue(DictionaryStrings.localhost.rawValue, forKey: DictionaryStrings.offsiteServer.rawValue)
} else {
record.setValue(configurations?.getConfigurations()?[index].offsiteServer, forKey: DictionaryStrings.offsiteServer.rawValue)
}
record.setValue(configurations?.getConfigurations()?[index].task, forKey: DictionaryStrings.task.rawValue)
records?.append(record)
estimatedlistandconfigs?.estimatedlist?.append(record)
guard stackoftasktobeestimated?.count ?? 0 > 0 else {
selectalltaskswithnumbers(deselect: false)
startstopProgressIndicatorDelegate?.stop()
// Prepare tasks with changes for synchronization
finalizeandpreparesynchronizelist()
return
}
// Update View
updateviewprocesstermination()
if let nextindex = stackoftasktobeestimated?.remove(at: 0).1 {
self.index = nextindex
Task {
let estimation = EstimateremoteInformationOnetask(index: nextindex, local: false, processtermination: processtermination)
await estimation.startestimation()
}
}
}
}
}
| mit | 5e8e4ae76b5e92b0a117b4a7833a2410 | 43.305389 | 141 | 0.643465 | 4.709739 | false | true | false | false |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Home/Controller/GameViewController.swift | 1 | 4062 | //
// GameViewController.swift
// DouYu
//
// Created by 张萌 on 2018/1/19.
// Copyright © 2018年 JiaYin. All rights reserved.
//
import UIKit
private let kEdgeMargin : CGFloat = 10
private let kItemSizeW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemSizeH : CGFloat = kItemSizeW * 6 / 5
private let kHeaderH : CGFloat = 50
private let kCommonViewH : CGFloat = 90
private let kGameCellID : String = "kGameCellID"
private let kHeaderID : String = "kHeaderID"
class GameViewController: BaseViewController {
fileprivate lazy var gameVM : GameViewModel = GameViewModel()
// 懒加载控件
fileprivate lazy var collection : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemSizeW, height: kItemSizeH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.sectionInset = UIEdgeInsetsMake(0, kEdgeMargin, 0, kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderH)
let collection = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collection.dataSource = self
collection.backgroundColor = UIColor.white
collection.autoresizingMask = [.flexibleWidth, .flexibleHeight]
collection .register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collection.register( UINib(nibName: "HeaderCollectionReusableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderID)
return collection
}()
fileprivate lazy var topHeaderView : HeaderCollectionReusableView = {
let topHeaderView = HeaderCollectionReusableView.headerCollectionReusableView()
topHeaderView.frame = CGRect(x: 0, y: -(kHeaderH + kCommonViewH), width: kScreenW, height: kHeaderH)
topHeaderView.titleLabel.text = "常用"
topHeaderView.moreBtn.isHidden = true
return topHeaderView
}()
fileprivate lazy var commonView : RecommendGameView = {
let commonView = RecommendGameView.recommendGameView()
commonView.frame = CGRect(x: 0, y: -kCommonViewH, width: kScreenW, height: kCommonViewH)
return commonView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK: 设置UI
extension GameViewController {
override func setupUI() {
contentView = collection
view.addSubview(collection)
collection.addSubview(topHeaderView)
collection.addSubview(commonView)
collection.contentInset = UIEdgeInsetsMake(kHeaderH + kCommonViewH, 0, 0, 0)
super.setupUI()
}
}
/// MARK:- 加载网络数据
extension GameViewController {
fileprivate func loadData() {
gameVM.loadAllGameData {
self.collection.reloadData()
self.commonView.groups = Array(self.gameVM.games[0..<6])
self.finishLoadData()
}
}
}
extension GameViewController : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameVM.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionViewGameCell
cell.group = gameVM.games[indexPath.row]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collection.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "kHeaderID", for: indexPath) as! HeaderCollectionReusableView
headerView.titleLabel.text = "全部"
headerView.moreBtn.isHidden = true
return headerView
}
}
| mit | aace7d7b98f343f305a80bdf983ca3b6 | 39.616162 | 187 | 0.713255 | 5.201811 | false | false | false | false |
avito-tech/Marshroute | Example/NavigationDemo/Common/Services/TopViewControllerFindingService/TopViewControllerFindingServiceImpl.swift | 1 | 1990 | import Marshroute
final class TopViewControllerFindingServiceImpl: TopViewControllerFindingService {
// MARK: - Init
let rootTransitionsHandlerProvider: () -> ContainingTransitionsHandler?
let topViewControllerFinder: TopViewControllerFinder
init(topViewControllerFinder: TopViewControllerFinder,
rootTransitionsHandlerProvider: @escaping () -> ContainingTransitionsHandler?)
{
self.topViewControllerFinder = topViewControllerFinder
self.rootTransitionsHandlerProvider = rootTransitionsHandlerProvider
}
// MARK: - TopViewControllerFindingService
func topViewControllerAndItsContainerViewController()
-> (UIViewController, UIViewController)?
{
guard let topViewController = self.topViewController()
else { return nil }
let containerViewController = containerViewControllerForViewController(
topViewController
)
return (topViewController, containerViewController)
}
// MARK: - Private
private func topViewController()
-> UIViewController?
{
guard let rootTransitionsHandler = rootTransitionsHandlerProvider()
else { return nil }
let topViewController = topViewControllerFinder.findTopViewController(
containingTransitionsHandler: rootTransitionsHandler
)
return topViewController
}
private func containerViewControllerForViewController(_ viewController: UIViewController)
-> UIViewController
{
var containerViewController = viewController
if let navigationController = viewController.navigationController {
containerViewController = navigationController
}
if let splitViewController = viewController.splitViewController {
containerViewController = splitViewController
}
return containerViewController
}
}
| mit | 1a1f9fc6c6de6741fcfc120151a2cd6c | 33.310345 | 93 | 0.69196 | 7.624521 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/Sections/Me/Settings/ForumList/ForumNameModel.swift | 1 | 1322 | //
// ForumNameModel.swift
// HiPDA
//
// Created by leizh007 on 2017/1/24.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
import RxDataSources
/// 版块名称的模型
struct ForumNameModel {
/// 版块名称
let forumName: String
/// 版块的描述信息
let forumDescription: String?
/// 等级
///
/// - first: 一级
/// - secondary: 二级
/// - secondaryLast: 二级末尾
enum Level {
case first
case secondary
case secondaryLast
}
/// 所属级别
let level: Level
/// 是否被选中
var isChoosed: Bool
}
// MARK: - IdentifiableType
extension ForumNameModel: IdentifiableType {
typealias Identity = String
var identity: String {
return "\(self)"
}
}
// MARK: - Equatable
extension ForumNameModel: Equatable {
static func ==(lhs: ForumNameModel, rhs: ForumNameModel) -> Bool {
return lhs.forumName == rhs.forumName &&
lhs.level == rhs.level &&
lhs.isChoosed == rhs.isChoosed
}
}
// MARK: - CustomStringConvertible
extension ForumNameModel: CustomStringConvertible {
var description: String {
return "ForumNameModel(forumName: \(forumName), level: \(level), isChoosed: \(isChoosed))"
}
}
| mit | d0afb44001e05ca720082a526663caaa | 18.453125 | 98 | 0.607229 | 3.772727 | false | false | false | false |
brentdax/swift | test/Frontend/dependencies.swift | 4 | 5956 | // XFAIL: linux
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC %s
// RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file %S/../Inputs/empty\ file.swift | %FileCheck -check-prefix=CHECK-BASIC-YAML %s
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %S/../Inputs/empty\ file.swift
// RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t.swiftdeps
// CHECK-BASIC-LABEL: - :
// CHECK-BASIC: Inputs/empty\ file.swift
// CHECK-BASIC: Swift.swiftmodule
// CHECK-BASIC-NOT: :
// CHECK-BASIC-YAML-LABEL: depends-external:
// CHECK-BASIC-YAML-NOT: empty\ file.swift
// CHECK-BASIC-YAML: "{{.*}}/Swift.swiftmodule"
// CHECK-BASIC-YAML-NOT: {{:$}}
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck %S/../Inputs/empty\ file.swift 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s
// NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file)
// RUN: %target-swift-frontend -emit-dependencies-path - -emit-module %S/../Inputs/empty\ file.swift -o %t/empty\ file.swiftmodule -emit-module-doc-path %t/empty\ file.swiftdoc -emit-objc-header-path %t/empty\ file.h -emit-parseable-module-interface-path %t/empty\ file.swiftinterface | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftinterface :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-NOT: :
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -track-system-dependencies -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT-TRACK-SYSTEM %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s
// CHECK-IMPORT-LABEL: - :
// CHECK-IMPORT: dependencies.swift
// CHECK-IMPORT-DAG: Swift.swiftmodule
// CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-DAG: Inputs/dependencies/UserClangModule.h
// CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-DAG: Inputs/dependencies/module.modulemap
// CHECK-IMPORT-DAG: ObjectiveC.swift
// CHECK-IMPORT-DAG: Foundation.swift
// CHECK-IMPORT-DAG: CoreGraphics.swift
// CHECK-IMPORT-NOT: :
// CHECK-IMPORT-TRACK-SYSTEM-LABEL: - :
// CHECK-IMPORT-TRACK-SYSTEM: dependencies.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Swift.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: SwiftOnoneSupport.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreFoundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreGraphics.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Foundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: ObjectiveC.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/UserClangModule.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: swift/shims/module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreFoundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreGraphics.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/CoreGraphics.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/Foundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/NSObject.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/ObjectiveC.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/module.map
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr/include/objc/objc.h
// CHECK-IMPORT-TRACK-SYSTEM-NOT: :
// CHECK-IMPORT-YAML-LABEL: depends-external:
// CHECK-IMPORT-YAML-NOT: dependencies.swift
// CHECK-IMPORT-YAML-DAG: "{{.*}}/Swift.swiftmodule"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/$$$$$.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/UserClangModule.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/extra-header.h"
// CHECK-IMPORT-YAML-DAG: "{{.*}}Inputs/dependencies/module.modulemap"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/ObjectiveC.swift"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/Foundation.swift"
// CHECK-IMPORT-YAML-DAG: "{{.*}}/CoreGraphics.swift"
// CHECK-IMPORT-YAML-NOT: {{^-}}
// CHECK-IMPORT-YAML-NOT: {{:$}}
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path - -typecheck -primary-file %s | %FileCheck -check-prefix=CHECK-IMPORT-YAML %s
import Foundation
import UserClangModule
class Test: NSObject {}
_ = A()
_ = USER_VERSION
_ = EXTRA_VERSION
_ = MONEY
#if ERROR
_ = someRandomUndefinedName
#endif
| apache-2.0 | d7ceac42b90c942dac929a1f95fb03bf | 52.178571 | 337 | 0.743788 | 3.279736 | false | false | false | false |
eastsss/SwiftyUtilities | SwiftyUtilities/UIKit/Nib Loading/NibLoader.swift | 2 | 1878 | //
// NibLoader.swift
// SwiftyUtilities
//
// Created by Anatoliy Radchenko on 02/06/2017.
// Copyright © 2017 SwiftyUtilities. All rights reserved.
//
import UIKit
public class NibLoader {
public static func load<T: UIView>(
_ type: T.Type,
addAsSubviewTo view: UIView,
fileOwner: AnyObject? = nil,
useAutoLayout: Bool = true) -> UIView? {
var owner = fileOwner
if owner == nil {
owner = view
}
let nib = self.nib(forType: type)
guard let loadedView = self.view(fromNib: nib, nibFileOwner: owner) else {
return nil
}
view.addSubview(loadedView)
if useAutoLayout {
view.attachSubviewUsingConstraints(subview: loadedView)
} else {
loadedView.frame = view.bounds
loadedView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
return loadedView
}
public static func nib(forType type: Swift.AnyClass) -> UINib {
let nibName = self.nibName(forType: type)
let bundle = Bundle(for: type)
let nib = UINib(nibName: nibName, bundle: bundle)
return nib
}
}
// MARK: Supporting methods
private extension NibLoader {
static func nibName(forType type: Swift.AnyClass) -> String {
let fullTypeName = NSStringFromClass(type)
let nameComponents = fullTypeName.components(separatedBy: ".")
if let lastNameComponent = nameComponents.last {
return lastNameComponent
} else {
return fullTypeName
}
}
static func view(fromNib nib: UINib, nibFileOwner: AnyObject?) -> UIView? {
let instantiatedView = nib.instantiate(withOwner: nibFileOwner, options: nil).first as? UIView
return instantiatedView
}
}
| mit | 19b778274c8243a837955b4cef052c52 | 27.876923 | 102 | 0.601492 | 4.623153 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/CustomXibView.swift | 1 | 880 | //
// CustomXibView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 28.2.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// This is a utility class for views that contain views created within xib files
class CustomXibView: UIView
{
// ATTRIBUTES --------------
private var view: UIView!
// OTHER METHODS ----------
// This function should be called in the view initializers
func setupXib(nibName: String)
{
view = loadViewFromNib(nibName: nibName)
view.frame = bounds
view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
addSubview(view)
}
private func loadViewFromNib(nibName: String) -> UIView
{
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName, bundle: bundle)
return nib.instantiate(withOwner: self, options: nil)[0] as! UIView
}
}
| mit | c289db95a79f751d2b8fa17cfaa745fd | 22.756757 | 95 | 0.704209 | 3.772532 | false | false | false | false |
sarah-j-smith/Quest | Common/GradientView.swift | 1 | 693 | //
// GradientView.swift
// SwiftAdventure
//
// Created by Sarah Smith on 3/01/2015.
// Copyright (c) 2015 Sarah Smith. All rights reserved.
//
import Foundation
import Cocoa
@IBDesignable class GradientView : NSView
{
@IBInspectable var startColor : NSColor = NSColor.lightGrayColor() {
didSet {
needsDisplay = true
}
}
@IBInspectable var endColor : NSColor = NSColor.darkGrayColor() {
didSet {
needsDisplay = true
}
}
override func drawRect(dirtyRect: NSRect) {
let gradient = NSGradient(startingColor: startColor, endingColor: endColor)
gradient.drawInRect(bounds, angle: 270.0)
}
} | mit | 417481ec0de734b13207c4968661fe1c | 22.931034 | 83 | 0.637807 | 4.442308 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/implement-stack-using-queues.swift | 1 | 944 | /**
* https://leetcode.com/problems/implement-stack-using-queues/
*
*
*/
// Date: Wed May 4 22:40:38 PDT 2022
class MyStack {
private var q1: [Int]
private var q2: [Int]
private var last: Int
init() {
q1 = []
q2 = []
last = 0
}
func push(_ x: Int) {
q1.append(x)
last = x
}
func pop() -> Int {
var sz = q1.count
while sz > 1 {
sz -= 1
last = q1.removeFirst()
q2.append(last)
}
let ret = q1.removeLast()
q1 = q2
q2 = []
return ret
}
func top() -> Int {
return last
}
func empty() -> Bool {
return q1.isEmpty
}
}
/**
* Your MyStack object will be instantiated and called as such:
* let obj = MyStack()
* obj.push(x)
* let ret_2: Int = obj.pop()
* let ret_3: Int = obj.top()
* let ret_4: Bool = obj.empty()
*/ | mit | cd8fbafadc844f5793aee47ef2de319c | 16.830189 | 63 | 0.461864 | 3.300699 | false | false | false | false |
jadevance/fuzz-therapy-iOS | Fuzz Therapy/LoggedInViewController.swift | 1 | 3470 | import UIKit
import Google
@objc(LoggedInViewController)
class LoggedInViewController: UIViewController, GIDSignInUIDelegate {
@IBOutlet weak var signInButton: GIDSignInButton!
@IBOutlet weak var signOutButton: UIButton!
@IBOutlet weak var disconnectButton: UIButton!
@IBOutlet weak var statusText: UILabel!
@IBOutlet weak var createProfileButton: UIButton!
@IBOutlet weak var editProfileButton: UIButton!
@IBOutlet weak var searchButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(LoggedInViewController.receiveToggleAuthUINotification(_:)),
name: "ToggleAuthUINotification",
object: nil)
toggleAuthUI()
statusText.text = ""
signInButton.hidden = true
signOutButton.hidden = true
editProfileButton.hidden = true
createProfileButton.hidden = true
searchButton.hidden = true
}
func toggleAuthUI() {
getCurrentUserData(){ myUser in
if (GIDSignIn.sharedInstance().hasAuthInKeychain() && CurrentUser.sharedInstance.user?.name != "placeholder"){
// Signed in, no Fuzz Therapy account
self.signInButton.hidden = true
self.signOutButton.hidden = false
self.disconnectButton.hidden = true
self.editProfileButton.hidden = true
self.createProfileButton.hidden = false
self.searchButton.hidden = true
} else if (GIDSignIn.sharedInstance().hasAuthInKeychain() && CurrentUser.sharedInstance.user?.name == "placeholder") {
// Signed in, has a Fuzz Therapy account
self.signInButton.hidden = true
self.signOutButton.hidden = false
self.disconnectButton.hidden = true
self.editProfileButton.hidden = false
self.createProfileButton.hidden = true
self.searchButton.hidden = false
} else {
// Not signed in
self.createProfileButton.hidden = true
self.editProfileButton.hidden = true
self.searchButton.hidden = true
self.signInButton.hidden = false
self.signOutButton.hidden = true
self.disconnectButton.hidden = true
self.statusText.text = "Sign in with Google"
}
}
}
@IBAction func didTapSignOut(sender: AnyObject) {
GIDSignIn.sharedInstance().signOut()
toggleAuthUI()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self,
name: "ToggleAuthUINotification",
object: nil)
}
@IBAction func unwindToMenu(segue: UIStoryboardSegue) {}
// part of the Google oauth bridging from Objective C
@objc func receiveToggleAuthUINotification(notification: NSNotification) {
if (notification.name == "ToggleAuthUINotification") {
self.toggleAuthUI()
if notification.userInfo != nil {
let userInfo:Dictionary<String,String!> = notification.userInfo as! Dictionary<String,String!>
self.statusText.text = userInfo["statusText"]
}
}
}
}
| apache-2.0 | 7a0e84a68d3be0eb7ca55d176f506e59 | 36.311828 | 130 | 0.624784 | 5.578778 | false | false | false | false |
adriankrupa/swift3D | Source/Matrix.swift | 1 | 5710 | //
// Matrix.swift
// swift3D
//
// Created by Adrian Krupa on 15.11.2015.
// Copyright © 2015 Adrian Krupa. All rights reserved.
//
import Foundation
import simd
public extension float2x2 {
/// Return the determinant of a squared matrix.
public var determinant : Float {
get {
return self[0,0]*self[1,1]-self[0,1]*self[1,0]
}
}
}
public extension float3x3 {
/// Return the determinant of a squared matrix.
public var determinant : Float {
get {
let t1 = self[0,0] * (self[1,1] * self[2,2] - self[2,1] * self[1,2])
let t2 = -self[1,0] * (self[0,1] * self[2,2] - self[2,1] * self[0,2])
let t3 = self[2,0] * (self[0,1] * self[1,2] - self[1,1] * self[0,2])
return t1 + t2 + t3
}
}
public init(_ m: float4x4) {
self.init([float3(m[0]), float3(m[1]), float3(m[2])])
}
}
public extension float4x4 {
/// Return the determinant of a squared matrix.
public var determinant : Float {
get {
let SubFactor00 = self[2,2] * self[3,3] - self[3,2] * self[2,3];
let SubFactor01 = self[2,1] * self[3,3] - self[3,1] * self[2,3];
let SubFactor02 = self[2,1] * self[3,2] - self[3,1] * self[2,2];
let SubFactor03 = self[2,0] * self[3,3] - self[3,0] * self[2,3];
let SubFactor04 = self[2,0] * self[3,2] - self[3,0] * self[2,2];
let SubFactor05 = self[2,0] * self[3,1] - self[3,0] * self[2,1];
let DetCof = float4(
+(self[1,1] * SubFactor00 - self[1,2] * SubFactor01 + self[1,3] * SubFactor02),
-(self[1,0] * SubFactor00 - self[1,2] * SubFactor03 + self[1,3] * SubFactor04),
+(self[1,0] * SubFactor01 - self[1,1] * SubFactor03 + self[1,3] * SubFactor05),
-(self[1,0] * SubFactor02 - self[1,1] * SubFactor04 + self[1,2] * SubFactor05));
return
self[0,0] * DetCof[0] + self[0,1] * DetCof[1] +
self[0,2] * DetCof[2] + self[0,3] * DetCof[3];
}
}
public init(_ m: float3x3) {
self.init([float4(m[0]), float4(m[1]), float4(m[2]), float4(0, 0, 0, 1)])
}
}
public extension double2x2 {
/// Return the determinant of a squared matrix.
public var determinant : Double {
get {
return self[0,0]*self[1,1]-self[0,1]*self[1,0]
}
}
}
public extension double3x3 {
/// Return the determinant of a squared matrix.
public var determinant : Double {
get {
let t1 = self[0,0] * (self[1,1] * self[2,2] - self[2,1] * self[1,2])
let t2 = -self[1,0] * (self[0,1] * self[2,2] - self[2,1] * self[0,2])
let t3 = self[2,0] * (self[0,1] * self[1,2] - self[1,1] * self[0,2])
return t1 + t2 + t3
}
}
public init(_ m: double4x4) {
self.init([double3(m[0]), double3(m[1]), double3(m[2])])
}
}
public extension double4x4 {
/// Return the determinant of a squared matrix.
public var determinant : Double {
get {
let SubFactor00 = self[2,2] * self[3,3] - self[3,2] * self[2,3];
let SubFactor01 = self[2,1] * self[3,3] - self[3,1] * self[2,3];
let SubFactor02 = self[2,1] * self[3,2] - self[3,1] * self[2,2];
let SubFactor03 = self[2,0] * self[3,3] - self[3,0] * self[2,3];
let SubFactor04 = self[2,0] * self[3,2] - self[3,0] * self[2,2];
let SubFactor05 = self[2,0] * self[3,1] - self[3,0] * self[2,1];
let DetCof = double4(
+(self[1,1] * SubFactor00 - self[1,2] * SubFactor01 + self[1,3] * SubFactor02),
-(self[1,0] * SubFactor00 - self[1,2] * SubFactor03 + self[1,3] * SubFactor04),
+(self[1,0] * SubFactor01 - self[1,1] * SubFactor03 + self[1,3] * SubFactor05),
-(self[1,0] * SubFactor02 - self[1,1] * SubFactor04 + self[1,2] * SubFactor05));
return
self[0,0] * DetCof[0] + self[0,1] * DetCof[1] +
self[0,2] * DetCof[2] + self[0,3] * DetCof[3];
}
}
public init(_ m: double3x3) {
self.init([double4(m[0]), double4(m[1]), double4(m[2]), double4(0, 0, 0, 1)])
}
}
public func ==(a: float4x4, b: float4x4) -> Bool {
for i in 0..<4 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: float4x4, b: float4x4) -> Bool {
return !(a==b)
}
public func ==(a: float3x3, b: float3x3) -> Bool {
for i in 0..<3 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: float3x3, b: float3x3) -> Bool {
return !(a==b)
}
public func ==(a: float2x2, b: float2x2) -> Bool {
for i in 0..<2 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: float2x2, b: float2x2) -> Bool {
return !(a==b)
}
public func ==(a: double4x4, b: double4x4) -> Bool {
for i in 0..<4 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: double4x4, b: double4x4) -> Bool {
return !(a==b)
}
public func ==(a: double3x3, b: double3x3) -> Bool {
for i in 0..<3 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: double3x3, b: double3x3) -> Bool {
return !(a==b)
}
public func ==(a: double2x2, b: double2x2) -> Bool {
for i in 0..<2 {
if(a[i] != b[i]) {
return false
}
}
return true
}
public func !=(a: double2x2, b: double2x2) -> Bool {
return !(a==b)
} | mit | ffbe2491df3d575e09a62a79259f2455 | 28.43299 | 96 | 0.496584 | 2.746032 | false | false | false | false |
swaaws/shift | ios app/schichtplan/schichtplan/AppDelegate.swift | 1 | 12327 | //
// AppDelegate.swift
// schichtplan
//
// Created by Sebastian Heitzer on 23.09.16.
// Copyright © 2016 Sebastian Heitzer. All rights reserved.
//
import UIKit
import CoreData
import EventKit
func addCalendar(){
var key = ""
let defaults = UserDefaults.standard
if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") {
key = id
}
if key == "" {
let eventStore = EKEventStore();
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
print("Erstelle Kalender")
// Use Event Store to create a new calendar instance
// Configure its title
let newCalendar = EKCalendar(for: .event, eventStore: eventStore)
// Probably want to prevent someone from saving a calendar
// if they don't type in a name...
newCalendar.title = "Schichtplan"
// Access list of available sources from the Event Store
let sourcesInEventStore = eventStore.sources
// Filter the available sources and select the "Local" source to assign to the new calendar's
// source property
newCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
// Save the calendar using the Event Store instance
do {
try eventStore.saveCalendar(newCalendar, commit: true)
UserDefaults.standard.set(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
} catch {
print("error")
}
}
}
)
} else {
print("Calendar already exist")
}
}
var event = [NSManagedObject]()
func addEvent(){
var key = ""
let defaults = UserDefaults.standard
if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") {
key = id
}
if key == "" {
print("Can't add Events because Calendar not exits")
} else {
let eventStore = EKEventStore();
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
var key = ""
let defaults = UserDefaults.standard
if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") {
key = id
}
//TODO: handle if the user has deleted the calendar
let newCalendar = eventStore.calendar(withIdentifier: key)
func new_event(title: String, begin: NSDate, end: NSDate ) {
let event1 = EKEvent(eventStore: eventStore)
event1.title = title
event1.startDate = begin as Date
event1.endDate = end as Date
event1.notes = "description"
event1.calendar = newCalendar!
do {
try eventStore.save(event1, span: .thisEvent)
} catch {
print("?")
return
}
}
for index in 0...(event.count - 1) {
let derevent = event[index]
let shift = derevent.value(forKey: "shift") as? String
let dateString = derevent.value(forKey: "date") as? String // change to your date format
// let nextdate = dateString?.toDateTime()
// nextdate.Day += 1
//
let enddate = dateString?.toDateTime()
let cal = NSCalendar(identifier: .gregorian)
let newDate: NSDate = cal!.date(bySettingHour: 2, minute: 0, second: 0, of: enddate as! Date)! as NSDate
new_event(title: shift!, begin: (dateString?.toDateTime())!,end: newDate as NSDate)
}
print("create event")
}
}
)
}
}
func delCalendar(){
var key = ""
let defaults = UserDefaults.standard
if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") {
key = id
}
if key == "" {
print("nothing to do")
} else {
let eventStore = EKEventStore();
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
var key = ""
let defaults = UserDefaults.standard
if let id = defaults.string(forKey: "EventTrackerPrimaryCalendar") {
key = id
}
//TODO: handle if the user has deleted the calendar
print("Delete Kalender")
let newCalendar = eventStore.calendar(withIdentifier: key)
let defauults = UserDefaults.standard
defauults.set("", forKey: "EventTrackerPrimaryCalendar")
let sourcesInEventStore = eventStore.sources
// Filter the available sources and select the "Local" source to assign to the new calendar's
// source property
newCalendar?.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
// Save the calendar using the Event Store instance
do {
try eventStore.removeCalendar(newCalendar!, commit: true)
} catch {
print("error")
}
}
}
)
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult), didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UIApplication.shared.setMinimumBackgroundFetchInterval(
UIApplicationBackgroundFetchIntervalMinimum)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Config")
request.predicate = NSPredicate(format: "kind = %@", "token")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count == 1 {
}
}catch{
print("error")
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
let defaults = UserDefaults.standard
func applicationDidEnterBackground(_ application: UIApplication) {
print("im in Background")
if defaults.string(forKey: "EventTrackerPrimaryCalendar") != "" {
// delCalendar()
// sleep(4)
// addCalendar()
// sleep(4)
// addEvent()
} else {
print("nothing to do")
}
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "schichtplan")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | b3616ca8c17f1945b82226f64270c2f3 | 38.254777 | 285 | 0.546163 | 5.995136 | false | false | false | false |
ducn/Slux | Example/Tests/EventEmitterTests.swift | 1 | 1602 | //
// EventEmitterTests.swift
// Slux
//
// Created by Duc Ngo on 1/31/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
import Slux
class EventEmitterTests: QuickSpec {
let createEvent = "Create"
let updateEvent = "Update"
let deleteEvent = "Delete"
override func spec() {
describe("emitt") { () -> Void in
let emitter = EventEmitter()
var l = [EventListener]()
var callback = 0
beforeEach({ () -> Void in
let l1 = emitter.on(self.createEvent, callback: {
callback = 1
})
let l2 = emitter.on(self.updateEvent, callback: {
callback = 2
})
let l3 = emitter.on(self.deleteEvent, callback: {
callback = 3
})
l.append(l1)
l.append(l2)
l.append(l3)
})
it("Should able to emit events"){
emitter.emit(self.createEvent)
expect(callback) == 1
emitter.emit(self.updateEvent)
expect(callback) == 2
emitter.emit(self.deleteEvent)
expect(callback) == 3
}
it("Should not emit to unregistered event"){
callback = 0
emitter.removeListener(self.createEvent, listener: l[0])
emitter.emit(self.createEvent)
expect(callback) == 0
}
}
}
} | mit | 73cc2664f62299e500d4554d1a7da2b9 | 27.105263 | 72 | 0.481574 | 4.722714 | false | false | false | false |
Constructor-io/constructorio-client-swift | AutocompleteClient/FW/Logic/Request/CIOTrackBrowseResultsLoadedData.swift | 1 | 1558 | //
// CIOTrackBrowseResultsLoadedData.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
/**
Struct encapsulating the parameters that must/can be set set in order to track browse results loaded
*/
struct CIOTrackBrowseResultsLoadedData: CIORequestData {
let filterName: String
let filterValue: String
let resultCount: Int
let resultID: String?
let url: String
func url(with baseURL: String) -> String {
return String(format: Constants.TrackBrowseResultsLoaded.format, baseURL)
}
init(filterName: String, filterValue: String, resultCount: Int, resultID: String? = nil, url: String = "Not Available") {
self.filterName = filterName
self.filterValue = filterValue
self.resultCount = resultCount
self.resultID = resultID
self.url = url
}
func decorateRequest(requestBuilder: RequestBuilder) {}
func httpMethod() -> String {
return "POST"
}
func httpBody(baseParams: [String: Any]) -> Data? {
var dict = [
"filter_name": self.filterName,
"filter_value": self.filterValue,
"result_count": Int(self.resultCount),
"url": self.url
] as [String: Any]
if self.resultID != nil {
dict["resultID"] = self.resultID
}
dict["beacon"] = true
dict.merge(baseParams) { current, _ in current }
return try? JSONSerialization.data(withJSONObject: dict)
}
}
| mit | 58835c023e1c91d1de3c86349e7a24bc | 26.803571 | 125 | 0.637123 | 4.242507 | false | false | false | false |
mohsinalimat/DKCamera | DKCamera/DKCamera.swift | 1 | 18887 | //
// DKCamera.swift
// DKCameraDemo
//
// Created by ZhangAo on 15/8/30.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
import AVFoundation
import CoreMotion
public class DKCamera: UIViewController {
public var didCancelled: (() -> Void)?
public var didFinishCapturingImage: ((image: UIImage) -> Void)?
public var cameraOverlayView: UIView?
public var flashModel:AVCaptureFlashMode! {
didSet {
self.updateFlashButton()
self.updateFlashMode()
self.updateFlashModelToUserDefautls(self.flashModel)
}
}
public class func isAvailable() -> Bool {
return UIImagePickerController.isSourceTypeAvailable(.Camera)
}
private let captureSession = AVCaptureSession()
private var previewLayer: AVCaptureVideoPreviewLayer?
private var currentDevice: AVCaptureDevice?
private var captureDeviceFront: AVCaptureDevice?
private var captureDeviceBack: AVCaptureDevice?
private var currentOrientation = UIApplication.sharedApplication().statusBarOrientation
private let motionManager = CMMotionManager()
private lazy var flashButton: UIButton = {
let flashButton = UIButton()
flashButton.addTarget(self, action: "switchFlashMode", forControlEvents: .TouchUpInside)
return flashButton
}()
private var cameraSwitchButton: UIButton!
override public func viewDidLoad() {
super.viewDidLoad()
self.setupDevices()
self.setupUI()
self.beginSession()
self.setupMotionManager()
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if !self.captureSession.running {
self.captureSession.startRunning()
}
if !self.motionManager.accelerometerActive {
self.motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler: { (accelerometerData, error) -> Void in
if error == nil {
self.outputAccelertionData(accelerometerData.acceleration)
} else {
println("error while update accelerometer: \(error!.localizedDescription)")
}
})
}
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
self.captureSession.stopRunning()
self.motionManager.stopAccelerometerUpdates()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupDevices() {
let devices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice]
for device in devices {
if device.position == .Back {
self.captureDeviceBack = device
}
if device.position == .Front {
self.captureDeviceFront = device
}
}
self.currentDevice = self.captureDeviceBack ?? self.captureDeviceFront
}
private func setupUI() {
self.view.backgroundColor = UIColor.blackColor()
if let cameraOverlayView = self.cameraOverlayView {
self.view.addSubview(cameraOverlayView)
}
let bottomView = UIView()
let bottomViewHeight: CGFloat = 70
bottomView.bounds.size = CGSize(width: self.view.bounds.width, height: bottomViewHeight)
bottomView.frame.origin = CGPoint(x: 0, y: self.view.bounds.height - bottomViewHeight)
bottomView.autoresizingMask = .FlexibleWidth | .FlexibleTopMargin
bottomView.backgroundColor = UIColor(white: 0, alpha: 0.4)
self.view.addSubview(bottomView)
// switch button
let cameraSwitchButton: UIButton = {
let cameraSwitchButton = UIButton()
cameraSwitchButton.addTarget(self, action: "switchCamera", forControlEvents: .TouchUpInside)
cameraSwitchButton.setImage(DKCameraResource.cameraSwitchImage(), forState: .Normal)
cameraSwitchButton.sizeToFit()
return cameraSwitchButton
}()
cameraSwitchButton.frame.origin = CGPoint(x: bottomView.bounds.width - cameraSwitchButton.bounds.width - 15,
y: (bottomView.bounds.height - cameraSwitchButton.bounds.height) / 2)
cameraSwitchButton.autoresizingMask = .FlexibleLeftMargin | .FlexibleTopMargin | .FlexibleBottomMargin
bottomView.addSubview(cameraSwitchButton)
self.cameraSwitchButton = cameraSwitchButton
// capture button
let captureButton: UIButton = {
class CaptureButton: UIButton {
private override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
self.backgroundColor = UIColor.whiteColor()
return true
}
private override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
self.backgroundColor = UIColor.whiteColor()
return true
}
private override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) {
self.backgroundColor = nil
}
private override func cancelTrackingWithEvent(event: UIEvent?) {
self.backgroundColor = nil
}
}
let captureButton = CaptureButton()
captureButton.addTarget(self, action: "takePicture", forControlEvents: .TouchUpInside)
captureButton.bounds.size = CGSizeApplyAffineTransform(CGSize(width: bottomViewHeight,
height: bottomViewHeight), CGAffineTransformMakeScale(0.9, 0.9))
captureButton.layer.cornerRadius = captureButton.bounds.height / 2
captureButton.layer.borderColor = UIColor.whiteColor().CGColor
captureButton.layer.borderWidth = 2
captureButton.layer.masksToBounds = true
return captureButton
}()
captureButton.center = CGPoint(x: bottomView.bounds.width / 2, y: bottomView.bounds.height / 2)
captureButton.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin
bottomView.addSubview(captureButton)
// cancel button
let cancelButton: UIButton = {
let cancelButton = UIButton()
cancelButton.addTarget(self, action: "dismiss", forControlEvents: .TouchUpInside)
cancelButton.setImage(DKCameraResource.cameraCancelImage(), forState: .Normal)
cancelButton.sizeToFit()
return cancelButton
}()
cancelButton.frame.origin = CGPoint(x: self.view.bounds.width - cancelButton.bounds.width - 15, y: 25)
cancelButton.autoresizingMask = .FlexibleBottomMargin | .FlexibleLeftMargin
self.view.addSubview(cancelButton)
let flashButton: UIButton = {
let flashButton = UIButton()
flashButton.addTarget(self, action: "switchFlashMode", forControlEvents: .TouchUpInside)
return flashButton
}()
self.flashButton.frame.origin = CGPoint(x: 5, y: 15)
self.view.addSubview(self.flashButton)
}
// MARK: - Callbacks
internal func dismiss() {
if let didCancelled = self.didCancelled {
didCancelled()
}
}
internal func takePicture() {
if let stillImageOutput = self.captureSession.outputs.first as? AVCaptureStillImageOutput {
dispatch_async(dispatch_get_global_queue(0, 0), { () -> Void in
let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo)
connection.videoOrientation = self.currentOrientationToAVCaptureVideoOrientation()
stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection, completionHandler: { (imageDataSampleBuffer, error: NSError?) -> Void in
if error == nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let metaData: NSDictionary = CMCopyDictionaryOfAttachments(nil,
imageDataSampleBuffer,
CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)).takeUnretainedValue()
if let didFinishCapturingImage = self.didFinishCapturingImage,
image = UIImage(data: imageData) {
didFinishCapturingImage(image: image)
}
} else {
println("error while capturing still image: \(error!.localizedDescription)")
}
})
})
}
}
// MARK: - Handles Focus
override public func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let anyTouch = touches.first as! UITouch
let touchPoint = anyTouch.locationInView(self.view)
self.focusAtTouchPoint(touchPoint)
}
// MARK: - Handles Switch Camera
internal func switchCamera() {
self.currentDevice = self.currentDevice == self.captureDeviceBack ?
self.captureDeviceFront : self.captureDeviceBack
self.setupCurrentDevice();
}
// MARK: - Handles Flash
internal func switchFlashMode() {
switch self.flashModel! {
case .Auto:
self.flashModel = .Off
case .On:
self.flashModel = .Auto
case .Off:
self.flashModel = .On
}
}
private func flashModelFromUserDefaults() -> AVCaptureFlashMode {
let rawValue = NSUserDefaults.standardUserDefaults().integerForKey("DKCamera.flashModel")
return AVCaptureFlashMode(rawValue: rawValue)!
}
private func updateFlashModelToUserDefautls(flashModel: AVCaptureFlashMode) {
NSUserDefaults.standardUserDefaults().setInteger(flashModel.rawValue, forKey: "DKCamera.flashModel")
}
private func updateFlashButton() {
struct FlashImage {
static let images = [
AVCaptureFlashMode.Auto : DKCameraResource.cameraFlashAutoImage(),
AVCaptureFlashMode.On : DKCameraResource.cameraFlashOnImage(),
AVCaptureFlashMode.Off : DKCameraResource.cameraFlashOffImage()
]
}
var flashImage: UIImage = FlashImage.images[self.flashModel]!
self.flashButton.setImage(flashImage, forState: .Normal)
self.flashButton.sizeToFit()
}
// MARK: - Capture Session
private func beginSession() {
self.captureSession.sessionPreset = AVCaptureSessionPresetHigh
self.setupCurrentDevice()
let stillImageOutput = AVCaptureStillImageOutput()
if self.captureSession.canAddOutput(stillImageOutput) {
self.captureSession.addOutput(stillImageOutput)
}
self.previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
self.view.layer.insertSublayer(self.previewLayer, atIndex: 0)
self.previewLayer?.frame = self.view.layer.frame
}
private func setupCurrentDevice() {
if let currentDevice = self.currentDevice {
if currentDevice.flashAvailable {
self.flashButton.hidden = false
self.flashModel = self.flashModelFromUserDefaults()
} else {
self.flashButton.hidden = true
}
for oldInput in self.captureSession.inputs as! [AVCaptureInput] {
self.captureSession.removeInput(oldInput)
}
let frontInput = AVCaptureDeviceInput(device: self.currentDevice, error: nil)
if self.captureSession.canAddInput(frontInput) {
self.captureSession.addInput(frontInput)
}
if currentDevice.lockForConfiguration(nil) {
if currentDevice.isFocusModeSupported(.ContinuousAutoFocus) {
currentDevice.focusMode = .ContinuousAutoFocus
}
if currentDevice.isExposureModeSupported(.ContinuousAutoExposure) {
currentDevice.exposureMode = .ContinuousAutoExposure
}
currentDevice.unlockForConfiguration()
}
}
}
private func updateFlashMode() {
if let currentDevice = self.currentDevice
where currentDevice.flashAvailable && currentDevice.lockForConfiguration(nil) {
currentDevice.flashMode = self.flashModel
currentDevice.unlockForConfiguration()
}
}
private func focusAtTouchPoint(touchPoint: CGPoint) {
func showFocusViewAtPoint(touchPoint: CGPoint) {
struct FocusView {
static let focusView: UIView = {
let focusView = UIView()
let diameter: CGFloat = 100
focusView.bounds.size = CGSize(width: diameter, height: diameter)
focusView.layer.borderWidth = 2
focusView.layer.cornerRadius = diameter / 2
focusView.layer.borderColor = UIColor.whiteColor().CGColor
return focusView
}()
}
FocusView.focusView.transform = CGAffineTransformIdentity
FocusView.focusView.center = touchPoint
self.view.addSubview(FocusView.focusView)
UIView.animateWithDuration(0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.1,
options: .CurveEaseInOut, animations: { () -> Void in
FocusView.focusView.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.6, 0.6)
}) { (Bool) -> Void in
FocusView.focusView.removeFromSuperview()
}
}
if self.currentDevice == nil || self.currentDevice?.flashAvailable == false {
return
}
let focusPoint = self.previewLayer!.captureDevicePointOfInterestForPoint(touchPoint)
showFocusViewAtPoint(touchPoint)
if let currentDevice = self.currentDevice
where currentDevice.lockForConfiguration(nil) {
currentDevice.focusPointOfInterest = focusPoint
currentDevice.exposurePointOfInterest = focusPoint
currentDevice.focusMode = .ContinuousAutoFocus
if currentDevice.isExposureModeSupported(.ContinuousAutoExposure) {
currentDevice.exposureMode = .ContinuousAutoExposure
}
currentDevice.unlockForConfiguration()
}
}
// MARK: - Handles Orientation
private func setupMotionManager() {
self.motionManager.accelerometerUpdateInterval = 0.2
self.motionManager.gyroUpdateInterval = 0.2
}
private func outputAccelertionData(acceleration: CMAcceleration) {
var currentOrientation: UIInterfaceOrientation?
if acceleration.x >= 0.75 {
currentOrientation = .LandscapeLeft
} else if acceleration.x <= -0.75 {
currentOrientation = .LandscapeRight
} else if acceleration.y <= -0.75 {
currentOrientation = .Portrait
} else if acceleration.y >= 0.75 {
currentOrientation = .PortraitUpsideDown
} else {
return
}
if self.currentOrientation != currentOrientation! {
self.currentOrientation = currentOrientation!
self.updateUIForCurrentOrientation()
}
}
private func currentOrientationToAVCaptureVideoOrientation() -> AVCaptureVideoOrientation {
switch self.currentOrientation {
case .Portrait:
return .Portrait
case .PortraitUpsideDown:
return .PortraitUpsideDown
case .LandscapeLeft:
return .LandscapeLeft
case .LandscapeRight:
return .LandscapeRight
default:
return .Portrait
}
}
private func updateUIForCurrentOrientation() {
var degree = 0.0
switch self.currentOrientation {
case .Portrait:
degree = 0
case .PortraitUpsideDown:
degree = 180
case .LandscapeLeft:
degree = 270
case .LandscapeRight:
degree = 90
default:
degree = 0.0
}
// degrees to radians
let rotateAffineTransform = CGAffineTransformRotate(CGAffineTransformIdentity, CGFloat(degree / 180.0 * M_PI))
UIView.animateWithDuration(0.2) { () -> Void in
self.flashButton.transform = rotateAffineTransform
self.cameraSwitchButton.transform = rotateAffineTransform
}
}
}
// MARK: - Rersources
private extension NSBundle {
class func cameraBundle() -> NSBundle {
let assetPath = NSBundle(forClass: DKCameraResource.self).resourcePath!
return NSBundle(path: assetPath.stringByAppendingPathComponent("DKCameraResource.bundle"))!
}
}
private class DKCameraResource {
private class func imageForResource(name: String) -> UIImage {
let bundle = NSBundle.cameraBundle()
let imagePath = bundle.pathForResource(name, ofType: "png", inDirectory: "Images")
let image = UIImage(contentsOfFile: imagePath!)
return image!
}
class func cameraCancelImage() -> UIImage {
return imageForResource("camera_cancel")
}
class func cameraFlashOnImage() -> UIImage {
return imageForResource("camera_flash_on")
}
class func cameraFlashAutoImage() -> UIImage {
return imageForResource("camera_flash_auto")
}
class func cameraFlashOffImage() -> UIImage {
return imageForResource("camera_flash_off")
}
class func cameraSwitchImage() -> UIImage {
return imageForResource("camera_switch")
}
}
| mit | 331b77359e0d84b891fd35392325dfa2 | 35.669903 | 163 | 0.605348 | 5.999047 | false | false | false | false |
alexcomu/swift3-tutorial | 11-Coredata/11-Coredata/AppDelegate.swift | 1 | 4757 | //
// AppDelegate.swift
// 11-Coredata
//
// Created by Alex Comunian on 17/01/17.
// Copyright © 2017 Alex Comunian. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "_1_Coredata")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
// declare a shared access to the AppDelegate
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
| mit | 212cb6e45aec4a99cbd1ce9530808755 | 46.089109 | 285 | 0.689235 | 5.778858 | false | false | false | false |
Snail93/iOSDemos | SnailSwiftDemos/Pods/JTAppleCalendar/Sources/CalendarStructs.swift | 2 | 17422 | //
// CalendarStructs.swift
//
// Copyright (c) 2016-2017 JTAppleCalendar (https://github.com/patchthecode/JTAppleCalendar)
//
// 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.
//
/// Describes which month the cell belongs to
/// - ThisMonth: Cell belongs to the current month
/// - PreviousMonthWithinBoundary: Cell belongs to the previous month.
/// Previous month is included in the date boundary you have set in your
/// delegate - PreviousMonthOutsideBoundary: Cell belongs to the previous
/// month. Previous month is not included in the date boundary you have set
/// in your delegate - FollowingMonthWithinBoundary: Cell belongs to the
/// following month. Following month is included in the date boundary you have
/// set in your delegate - FollowingMonthOutsideBoundary: Cell belongs to the
/// following month. Following month is not included in the date boundary you
/// have set in your delegate You can use these cell states to configure how
/// you want your date cells to look. Eg. you can have the colors belonging
/// to the month be in color black, while the colors of previous months be in
/// color gray.
public struct CellState {
/// returns true if a cell is selected
public let isSelected: Bool
/// returns the date as a string
public let text: String
/// returns the a description of which month owns the date
public let dateBelongsTo: DateOwner
/// returns the date
public let date: Date
/// returns the day
public let day: DaysOfWeek
/// returns the row in which the date cell appears visually
public let row: () -> Int
/// returns the column in which the date cell appears visually
public let column: () -> Int
/// returns the section the date cell belongs to
public let dateSection: () -> (range: (start: Date, end: Date), month: Int, rowCount: Int)
/// returns the position of a selection in the event you wish to do range selection
public let selectedPosition: () -> SelectionRangePosition
/// returns the cell.
/// Useful if you wish to display something at the cell's frame/position
public var cell: () -> JTAppleCell?
/// Shows if a cell's selection/deselection was done either programatically or by the user
/// This variable is guranteed to be non-nil inside of a didSelect/didDeselect function
public var selectionType: SelectionType? = nil
}
/// Defines the parameters which configures the calendar.
public struct ConfigurationParameters {
/// The start date boundary of your calendar
var startDate: Date
/// The end-date boundary of your calendar
var endDate: Date
/// Number of rows you want to calendar to display per date section
var numberOfRows: Int
/// Your calendar() Instance
var calendar: Calendar
/// Describes the types of in-date cells to be generated.
var generateInDates: InDateCellGeneration
/// Describes the types of out-date cells to be generated.
var generateOutDates: OutDateCellGeneration
/// Sets the first day of week
var firstDayOfWeek: DaysOfWeek
/// Determine if dates of a month should stay in its section
/// or if it can flow into another months section. This value is ignored
/// if your calendar has registered headers
var hasStrictBoundaries: Bool
/// init-function
public init(startDate: Date,
endDate: Date,
numberOfRows: Int? = nil,
calendar: Calendar? = nil,
generateInDates: InDateCellGeneration? = nil,
generateOutDates: OutDateCellGeneration? = nil,
firstDayOfWeek: DaysOfWeek? = nil,
hasStrictBoundaries: Bool? = nil) {
self.startDate = startDate
self.endDate = endDate
self.numberOfRows = 6
if let validNumberOfRows = numberOfRows {
switch validNumberOfRows {
case 1, 2, 3:
self.numberOfRows = validNumberOfRows
default:
break
}
}
if let nonNilHasStrictBoundaries = hasStrictBoundaries {
self.hasStrictBoundaries = nonNilHasStrictBoundaries
} else {
self.hasStrictBoundaries = self.numberOfRows > 1 ? true : false
}
self.calendar = calendar ?? Calendar.current
self.generateInDates = generateInDates ?? .forAllMonths
self.generateOutDates = generateOutDates ?? .tillEndOfGrid
self.firstDayOfWeek = firstDayOfWeek ?? .sunday
}
}
public struct MonthSize {
var defaultSize: CGFloat
var months: [CGFloat:[MonthsOfYear]]?
var dates: [CGFloat: [Date]]?
public init(defaultSize: CGFloat, months: [CGFloat:[MonthsOfYear]]? = nil, dates: [CGFloat: [Date]]? = nil) {
self.defaultSize = defaultSize
self.months = months
self.dates = dates
}
}
struct CalendarData {
var months: [Month]
var totalSections: Int
var sectionToMonthMap: [Int: Int]
var totalDays: Int
}
/// Defines a month structure.
public struct Month {
/// Start index day for the month.
/// The start is total number of days of previous months
let startDayIndex: Int
/// Start cell index for the month.
/// The start is total number of cells of previous months
let startCellIndex: Int
/// The total number of items in this array are the total number
/// of sections. The actual number is the number of items in each section
let sections: [Int]
/// Number of inDates for this month
public let inDates: Int
/// Number of outDates for this month
public let outDates: Int
/// Maps a section to the index in the total number of sections
let sectionIndexMaps: [Int: Int]
/// Number of rows for the month
public let rows: Int
/// Name of the month
public let name: MonthsOfYear
// Return the total number of days for the represented month
public let numberOfDaysInMonth: Int
// Return the total number of day cells
// to generate for the represented month
var numberOfDaysInMonthGrid: Int {
return numberOfDaysInMonth + inDates + outDates
}
var startSection: Int {
return sectionIndexMaps.keys.min()!
}
// Return the section in which a day is contained
func indexPath(forDay number: Int) -> IndexPath? {
let sectionInfo = sectionFor(day: number)
let externalSection = sectionInfo.externalSection
let internalSection = sectionInfo.internalSection
let dateOfStartIndex = sections[0..<internalSection].reduce(0, +) - inDates + 1
let itemIndex = number - dateOfStartIndex
return IndexPath(item: itemIndex, section: externalSection)
}
private func sectionFor(day: Int) -> (externalSection: Int, internalSection: Int) {
var variableNumber = day
let possibleSection = sections.index {
let retval = variableNumber + inDates <= $0
variableNumber -= $0
return retval
}!
return (sectionIndexMaps.key(for: possibleSection)!, possibleSection)
}
// Return the number of rows for a section in the month
func numberOfRows(for section: Int, developerSetRows: Int) -> Int {
var retval: Int
guard let theSection = sectionIndexMaps[section] else {
return 0
}
let fullRows = rows / developerSetRows
let partial = sections.count - fullRows
if theSection + 1 <= fullRows {
retval = developerSetRows
} else if fullRows == 0 && partial > 0 {
retval = rows
} else {
retval = 1
}
return retval
}
// Returns the maximum number of a rows for a completely full section
func maxNumberOfRowsForFull(developerSetRows: Int) -> Int {
var retval: Int
let fullRows = rows / developerSetRows
if fullRows < 1 {
retval = rows
} else {
retval = developerSetRows
}
return retval
}
func boundaryIndicesFor(section: Int) -> (startIndex: Int, endIndex: Int)? {
// Check internal sections to see
if !(0..<sections.count ~= section) {
return nil
}
let startIndex = section == 0 ? inDates : 0
var endIndex = sections[section] - 1
if section + 1 == sections.count {
endIndex -= inDates + 1
}
return (startIndex: startIndex, endIndex: endIndex)
}
}
struct JTAppleDateConfigGenerator {
func setupMonthInfoDataForStartAndEndDate(_ parameters: ConfigurationParameters)
-> (months: [Month], monthMap: [Int: Int], totalSections: Int, totalDays: Int) {
let differenceComponents = parameters.calendar.dateComponents([.month], from: parameters.startDate, to: parameters.endDate)
let numberOfMonths = differenceComponents.month! + 1
// if we are for example on the same month
// and the difference is 0 we still need 1 to display it
var monthArray: [Month] = []
var monthIndexMap: [Int: Int] = [:]
var section = 0
var startIndexForMonth = 0
var startCellIndexForMonth = 0
var totalDays = 0
let numberOfRowsPerSectionThatUserWants = parameters.numberOfRows
// Section represents # of months. section is used as an offset
// to determine which month to calculate
// Track the month name index
var monthNameIndex = parameters.calendar.component(.month, from: parameters.startDate) - 1
let allMonthsOfYear: [MonthsOfYear] = [.jan, .feb, .mar, .apr, .may, .jun, .jul, .aug, .sep, .oct, .nov, .dec]
for monthIndex in 0 ..< numberOfMonths {
if let currentMonthDate = parameters.calendar.date(byAdding: .month, value: monthIndex, to: parameters.startDate) {
var numberOfDaysInMonthVariable = parameters.calendar.range(of: .day, in: .month, for: currentMonthDate)!.count
let numberOfDaysInMonthFixed = numberOfDaysInMonthVariable
var numberOfRowsToGenerateForCurrentMonth = 0
var numberOfPreDatesForThisMonth = 0
let predatesGeneration = parameters.generateInDates
if predatesGeneration != .off {
numberOfPreDatesForThisMonth = numberOfInDatesForMonth(currentMonthDate, firstDayOfWeek: parameters.firstDayOfWeek, calendar: parameters.calendar)
numberOfDaysInMonthVariable += numberOfPreDatesForThisMonth
if predatesGeneration == .forFirstMonthOnly && monthIndex != 0 {
numberOfDaysInMonthVariable -= numberOfPreDatesForThisMonth
numberOfPreDatesForThisMonth = 0
}
}
if parameters.generateOutDates == .tillEndOfGrid {
numberOfRowsToGenerateForCurrentMonth = maxNumberOfRowsPerMonth
} else {
let actualNumberOfRowsForThisMonth = Int(ceil(Float(numberOfDaysInMonthVariable) / Float(maxNumberOfDaysInWeek)))
numberOfRowsToGenerateForCurrentMonth = actualNumberOfRowsForThisMonth
}
var numberOfPostDatesForThisMonth = 0
let postGeneration = parameters.generateOutDates
switch postGeneration {
case .tillEndOfGrid, .tillEndOfRow:
numberOfPostDatesForThisMonth =
maxNumberOfDaysInWeek * numberOfRowsToGenerateForCurrentMonth - (numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth)
numberOfDaysInMonthVariable += numberOfPostDatesForThisMonth
default:
break
}
var sectionsForTheMonth: [Int] = []
var sectionIndexMaps: [Int: Int] = [:]
for index in 0..<6 {
// Max number of sections in the month
if numberOfDaysInMonthVariable < 1 {
break
}
monthIndexMap[section] = monthIndex
sectionIndexMaps[section] = index
var numberOfDaysInCurrentSection = numberOfRowsPerSectionThatUserWants * maxNumberOfDaysInWeek
if numberOfDaysInCurrentSection > numberOfDaysInMonthVariable {
numberOfDaysInCurrentSection = numberOfDaysInMonthVariable
// assert(false)
}
totalDays += numberOfDaysInCurrentSection
sectionsForTheMonth.append(numberOfDaysInCurrentSection)
numberOfDaysInMonthVariable -= numberOfDaysInCurrentSection
section += 1
}
monthArray.append(Month(
startDayIndex: startIndexForMonth,
startCellIndex: startCellIndexForMonth,
sections: sectionsForTheMonth,
inDates: numberOfPreDatesForThisMonth,
outDates: numberOfPostDatesForThisMonth,
sectionIndexMaps: sectionIndexMaps,
rows: numberOfRowsToGenerateForCurrentMonth,
name: allMonthsOfYear[monthNameIndex],
numberOfDaysInMonth: numberOfDaysInMonthFixed
))
startIndexForMonth += numberOfDaysInMonthFixed
startCellIndexForMonth += numberOfDaysInMonthFixed + numberOfPreDatesForThisMonth + numberOfPostDatesForThisMonth
// Increment month name
monthNameIndex += 1
if monthNameIndex > 11 { monthNameIndex = 0 }
}
}
return (monthArray, monthIndexMap, section, totalDays)
}
private func numberOfInDatesForMonth(_ date: Date, firstDayOfWeek: DaysOfWeek, calendar: Calendar) -> Int {
let firstDayCalValue: Int
switch firstDayOfWeek {
case .monday: firstDayCalValue = 6
case .tuesday: firstDayCalValue = 5
case .wednesday: firstDayCalValue = 4
case .thursday: firstDayCalValue = 10
case .friday: firstDayCalValue = 9
case .saturday: firstDayCalValue = 8
default: firstDayCalValue = 7
}
var firstWeekdayOfMonthIndex = calendar.component(.weekday, from: date)
firstWeekdayOfMonthIndex -= 1
// firstWeekdayOfMonthIndex should be 0-Indexed
// push it modularly so that we take it back one day so that the
// first day is Monday instead of Sunday which is the default
return (firstWeekdayOfMonthIndex + firstDayCalValue) % maxNumberOfDaysInWeek
}
}
/// Contains the information for visible dates of the calendar.
public struct DateSegmentInfo {
/// Visible pre-dates
public let indates: [(date: Date, indexPath: IndexPath)]
/// Visible month-dates
public let monthDates: [(date: Date, indexPath: IndexPath)]
/// Visible post-dates
public let outdates: [(date: Date, indexPath: IndexPath)]
}
struct SelectedCellData {
let indexPath: IndexPath
let date: Date
var counterIndexPath: IndexPath?
let cellState: CellState
enum DateOwnerCategory {
case inDate, outDate, monthDate
}
var dateBelongsTo: DateOwnerCategory {
switch cellState.dateBelongsTo {
case .thisMonth: return .monthDate
case .previousMonthOutsideBoundary, .previousMonthWithinBoundary: return .inDate
case .followingMonthWithinBoundary, .followingMonthOutsideBoundary: return .outDate
}
}
init(indexPath: IndexPath, counterIndexPath: IndexPath? = nil, date: Date, cellState: CellState) {
self.indexPath = indexPath
self.date = date
self.cellState = cellState
self.counterIndexPath = counterIndexPath
}
}
| apache-2.0 | f0c89e738954189687e3efa301036dfa | 42.773869 | 170 | 0.633222 | 5.220857 | false | false | false | false |
couchbase/couchbase-lite-ios | Swift/Tests/QueryTest.swift | 1 | 82232 | //
// QueryTest.swift
// CouchbaseLite
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import CouchbaseLiteSwift
class QueryTest: CBLTestCase {
let kDOCID = SelectResult.expression(Meta.id)
let kSEQUENCE = SelectResult.expression(Meta.sequence)
let kTestDate = "2017-01-01T00:00:00.000Z"
let kTestBlob = "i'm blob"
@discardableResult func createDoc(numbered i: (Int), of number: (Int)) throws -> Document {
let doc = createDocument("doc\(i)")
doc.setValue(i, forKey: "number1")
doc.setValue(number - i, forKey: "number2")
try saveDocument(doc)
return doc
}
@discardableResult func loadNumbers(_ num: Int) throws -> [[String: Any]] {
var numbers:[[String: Any]] = []
try db.inBatch {
for i in 1...num {
let doc = try createDoc(numbered: i, of: num)
numbers.append(doc.toDictionary())
}
}
return numbers
}
func runTestWithNumbers(_ numbers: [[String: Any]], cases: [[Any]]) throws {
for c in cases {
let pred = NSPredicate(format: c[1] as! String)
var result = numbers.filter { pred.evaluate(with: $0) };
let total = result.count
let w = c[0] as! ExpressionProtocol
let q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(w)
let rows = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
let props = doc.toDictionary()
let number1 = props["number1"] as! Int
if let index = result.firstIndex(where: {($0["number1"] as! Int) == number1}) {
result.remove(at: index)
}
})
XCTAssertEqual(result.count, 0);
XCTAssertEqual(Int(rows), total);
}
}
func testQuerySelectItemsMax() throws {
let doc = MutableDocument(id: "docID").setString("value", forKey: "key")
try! self.db.saveDocument(doc)
/**
Add one more query item, e.g., '`32`' before `key`, will fail to return the
- `r.string(forKey:)`
- `r.value(forKey:)`
- `r.toJSON()` // empty
*/
let query =
"""
select
`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`10`,`11`,`12`,
`13`,`14`,`15`,`16`,`17`,`18`,`19`,`20`,`21`,`22`,`23`,`24`,
`25`,`26`,`27`,`28`,`29`,`30`,`31`,`32`,
`1`,`2`,`3`,`4`,`5`,`6`,`7`,`8`,`9`,`10`,`11`,`12`,
`13`,`14`,`15`,`16`,`17`,`18`,`19`,`20`,`21`,`22`,`23`,`24`,
`25`,`26`,`27`,`28`,`29`,`30`,`31`, `key` from _ limit 1
"""
let q = try self.db.createQuery(query)
let rs: ResultSet = try q.execute()
guard let r = rs.allResults().first else {
XCTFail("No result!")
return
}
XCTAssertEqual(r.toJSON(), "{\"key\":\"value\"}")
XCTAssertEqual(r.string(forKey: "key"), "value")
XCTAssertEqual(r.string(at: 63), "value")
XCTAssertEqual(r.value(at: 63) as! String, "value")
XCTAssertEqual(r.value(forKey: "key") as! String, "value")
}
func testNoWhereQuery() throws {
try loadJSONResource(name: "names_100")
let q = QueryBuilder.select(kDOCID).from(DataSource.database(db))
let numRows = try verifyQuery(q) { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
let expectedID = String(format: "doc-%03llu", n);
XCTAssertEqual(doc.id, expectedID);
XCTAssertEqual(doc.sequence, n);
XCTAssertEqual(doc.id, expectedID);
XCTAssertEqual(doc.sequence, n);
}
XCTAssertEqual(numRows, 100);
}
func testWhereComparison() throws {
let n1 = Expression.property("number1")
let cases = [
[n1.lessThan(Expression.int(3)), "number1 < 3"],
[n1.lessThanOrEqualTo(Expression.int(3)), "number1 <= 3"],
[n1.greaterThan(Expression.int(6)), "number1 > 6"],
[n1.greaterThanOrEqualTo(Expression.int(6)), "number1 >= 6"],
[n1.equalTo(Expression.int(7)), "number1 == 7"],
[n1.notEqualTo(Expression.int(7)), "number1 != 7"],
]
let numbers = try loadNumbers(10)
try runTestWithNumbers(numbers, cases: cases)
}
func testWhereArithmetic() throws {
let n1 = Expression.property("number1")
let n2 = Expression.property("number2")
let cases = [
[n1.multiply(Expression.int(2)).greaterThan(Expression.int(8)), "(number1 * 2) > 8"],
[n1.divide(Expression.int(2)).greaterThan(Expression.int(3)), "(number1 / 2) > 3"],
[n1.modulo(Expression.int(2)).equalTo(Expression.int(0)), "modulus:by:(number1, 2) == 0"],
[n1.add(Expression.int(5)).greaterThan(Expression.int(10)), "(number1 + 5) > 10"],
[n1.subtract(Expression.int(5)).greaterThan(Expression.int(0)), "(number1 - 5) > 0"],
[n1.multiply(n2).greaterThan(Expression.int(10)), "(number1 * number2) > 10"],
[n2.divide(n1).greaterThan(Expression.int(3)), "(number2 / number1) > 3"],
[n2.modulo(n1).equalTo(Expression.int(0)), "modulus:by:(number2, number1) == 0"],
[n1.add(n2).equalTo(Expression.int(10)), "(number1 + number2) == 10"],
[n1.subtract(n2).greaterThan(Expression.int(0)), "(number1 - number2) > 0"]
]
let numbers = try loadNumbers(10)
try runTestWithNumbers(numbers, cases: cases)
}
func testWhereAndOr() throws {
let n1 = Expression.property("number1")
let n2 = Expression.property("number2")
let cases = [
[n1.greaterThan(Expression.int(3)).and(n2.greaterThan(Expression.int(3))), "number1 > 3 AND number2 > 3"],
[n1.lessThan(Expression.int(3)).or(n2.lessThan(Expression.int(3))), "number1 < 3 OR number2 < 3"]
]
let numbers = try loadNumbers(10)
try runTestWithNumbers(numbers, cases: cases)
}
func testWhereNullOrMissing() throws {
let doc1 = createDocument("doc1")
doc1.setValue("Scott", forKey: "name")
doc1.setValue(nil, forKey: "address")
try saveDocument(doc1)
let doc2 = createDocument("doc2")
doc2.setValue("Tiger", forKey: "name")
doc2.setValue("123 1st ave", forKey: "address")
doc2.setValue(20, forKey: "age")
try saveDocument(doc2)
let name = Expression.property("name")
let address = Expression.property("address")
let age = Expression.property("age")
let work = Expression.property("work")
let tests: [[Any]] = [
[name.isNullOrMissing(), []],
[name.isNotValued(), []],
[name.notNullOrMissing(), [doc1, doc2]],
[name.isValued(), [doc1, doc2]],
[address.isNullOrMissing(), [doc1]],
[address.isNotValued(), [doc1]],
[address.notNullOrMissing(), [doc2]],
[address.isValued(), [doc2]],
[age.isNullOrMissing(), [doc1]],
[age.isNotValued(), [doc1]],
[age.notNullOrMissing(), [doc2]],
[age.isValued(), [doc2]],
[work.isNullOrMissing(), [doc1, doc2]],
[work.isNotValued(), [doc1, doc2]],
[work.notNullOrMissing(), []],
[work.isValued(), []]
]
for test in tests {
let exp = test[0] as! ExpressionProtocol
let expectedDocs = test[1] as! [Document]
let q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(exp)
let numRows = try verifyQuery(q, block: { (n, r) in
if (Int(n) <= expectedDocs.count) {
let docID = r.string(at: 0)!
XCTAssertEqual(docID, expectedDocs[Int(n)-1].id)
}
})
XCTAssertEqual(Int(numRows), expectedDocs.count);
}
}
func testWhereIs() throws {
let doc1 = MutableDocument()
doc1.setValue("string", forKey: "string")
try saveDocument(doc1)
var q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(
Expression.property("string").is(Expression.string("string")))
var numRows = try verifyQuery(q) { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
XCTAssertEqual(doc.id, doc1.id);
XCTAssertEqual(doc.string(forKey: "string")!, "string");
}
XCTAssertEqual(numRows, 1);
q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(
Expression.property("string").isNot(Expression.string("string1")))
numRows = try verifyQuery(q) { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
XCTAssertEqual(doc.id, doc1.id);
XCTAssertEqual(doc.string(forKey: "string")!, "string");
}
XCTAssertEqual(numRows, 1);
}
func testWhereBetween() throws {
let n1 = Expression.property("number1")
let cases = [
[n1.between(Expression.int(3), and: Expression.int(7)), "number1 BETWEEN {3, 7}"]
]
let numbers = try loadNumbers(10)
try runTestWithNumbers(numbers, cases: cases)
}
func testWhereLike() throws {
try loadJSONResource(name: "names_100")
let w = Expression.property("name.first").like(Expression.string("%Mar%"))
let q = QueryBuilder
.select(kDOCID)
.from(DataSource.database(db))
.where(w)
.orderBy(Ordering.property("name.first").ascending())
var firstNames: [String] = []
let numRows = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
let v: String? = doc.dictionary(forKey: "name")?.string(forKey: "first")
if let firstName = v {
firstNames.append(firstName)
}
})
XCTAssertEqual(numRows, 5);
XCTAssertEqual(firstNames.count, 5);
}
func testWhereIn() throws {
try loadJSONResource(name: "names_100")
let expected = ["Marcy", "Margaretta", "Margrett", "Marlen", "Maryjo"]
let names = expected.map() { Expression.string($0) }
let w = Expression.property("name.first").in(names)
let o = Ordering.property("name.first")
let q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(w).orderBy(o)
let numRows = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
let firstName = expected[Int(n)-1]
XCTAssertEqual(doc.dictionary(forKey: "name")!.string(forKey: "first")!, firstName)
})
XCTAssertEqual(Int(numRows), expected.count);
}
func testWhereRegex() throws {
// https://github.com/couchbase/couchbase-lite-ios/issues/1668
try loadJSONResource(name: "names_100")
let w = Expression.property("name.first").regex(Expression.string("^Mar.*"))
let q = QueryBuilder
.select(kDOCID)
.from(DataSource.database(db))
.where(w)
.orderBy(Ordering.property("name.first").ascending())
var firstNames: [String] = []
let numRows = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
let v: String? = doc.dictionary(forKey: "name")?.string(forKey: "first")
if let firstName = v {
firstNames.append(firstName)
}
})
XCTAssertEqual(numRows, 5);
XCTAssertEqual(firstNames.count, 5);
}
// https://issues.couchbase.com/browse/CBL-2036
func testFTSQueryOnDBNameWithHyphen() throws {
try Database.delete(withName: "cbl-test")
let db2 = try Database(name: "cbl-test")
let doc = MutableDocument()
doc.setValue("Dummie woman", forKey: "sentence")
try db2.saveDocument(doc)
let doc2 = MutableDocument()
doc2.setValue("Dummie man", forKey: "sentence")
try db2.saveDocument(doc2)
let fts_s = FullTextIndexItem.property("sentence")
let index = IndexBuilder.fullTextIndex(items: fts_s)
.language(nil)
.ignoreAccents(false)
try db2.createIndex(index, withName: "sentence")
let q = QueryBuilder.select([SelectResult.expression(Meta.id)])
.from(DataSource.database(db2))
.where(FullTextFunction.match(indexName: "sentence", query: "'woman'"))
let numRows = try verifyQuery(q) { (n, r) in }
XCTAssertEqual(numRows, 1)
}
func testFTSMatch() throws {
let doc = MutableDocument()
doc.setValue("Dummie woman", forKey: "sentence")
try db.saveDocument(doc)
let doc2 = MutableDocument()
doc2.setValue("Dummie man", forKey: "sentence")
try db.saveDocument(doc2)
let fts_s = FullTextIndexItem.property("sentence")
let index = IndexBuilder.fullTextIndex(items: fts_s)
.language(nil)
.ignoreAccents(false)
try db.createIndex(index, withName: "sentence")
// JSON Query
var q = QueryBuilder.select([SelectResult.expression(Meta.id)])
.from(DataSource.database(db))
.where(FullTextFunction.match(indexName: "sentence", query: "'woman'"))
var numRows = try verifyQuery(q) { (n, r) in }
XCTAssertEqual(numRows, 1)
q = QueryBuilder.select([SelectResult.expression(Meta.id)])
.from(DataSource.database(db))
.where(FullTextFunction.match(indexName: "sentence", query: "\"woman\""))
numRows = try verifyQuery(q) { (n, r) in }
XCTAssertEqual(numRows, 1)
// N1QL Query
var q2 = try db.createQuery("SELECT _id FROM `\(db.name)` WHERE MATCH(sentence, 'woman')")
numRows = try verifyQuery(q2) { (n, r) in }
XCTAssertEqual(numRows, 1)
q2 = try db.createQuery("SELECT _id FROM `\(db.name)` WHERE MATCH(sentence, \"woman\")")
numRows = try verifyQuery(q2) { (n, r) in }
XCTAssertEqual(numRows, 1)
}
func testWhereMatch() throws {
try loadJSONResource(name: "sentences")
let fts_s = FullTextIndexItem.property("sentence")
let index = IndexBuilder.fullTextIndex(items: fts_s)
.language(nil)
.ignoreAccents(false)
try db.createIndex(index, withName: "sentence")
// deprecated API
try checkMatchedQuery([kDOCID, SelectResult.property("sentence")],
ds: DataSource.database(db))
var s = Expression.property("sentence").from("db")
try checkMatchedQuery([kDOCID, SelectResult.expression(s)],
ds: DataSource.database(db).as("db"))
// new API
try checkFullTextMatchQuery([kDOCID, SelectResult.property("sentence")],
ds: DataSource.database(db))
s = Expression.property("sentence").from("db")
try checkFullTextMatchQuery([kDOCID, SelectResult.expression(s)],
ds: DataSource.database(db).as("db"))
}
// 'FullTextExpression' is deprecated: Use FullTextFunction(match:query:) instead.
func checkMatchedQuery(_ select: [SelectResultProtocol],
ds: DataSourceProtocol) throws {
let sentence = FullTextExpression.index("sentence")
let w = sentence.match("'Dummie woman'")
let o = Ordering.expression(FullTextFunction.rank("sentence")).descending()
let q = QueryBuilder.select(select)
.from(ds)
.where(w)
.orderBy(o)
let numRows = try verifyQuery(q) { (n, r) in }
XCTAssertEqual(numRows, 2)
}
func checkFullTextMatchQuery(_ select: [SelectResultProtocol],
ds: DataSourceProtocol) throws {
let w = FullTextFunction.match(indexName: "sentence", query: "'Dummie woman'")
let o = Ordering.expression(FullTextFunction.rank("sentence")).descending()
let q = QueryBuilder.select(select)
.from(ds)
.where(w)
.orderBy(o)
let numRows = try verifyQuery(q) { (n, r) in }
XCTAssertEqual(numRows, 2)
}
func testOrderBy() throws {
try loadJSONResource(name: "names_100")
for ascending in [true, false] {
var o: OrderingProtocol;
if (ascending) {
o = Ordering.expression(Expression.property("name.first")).ascending()
} else {
o = Ordering.expression(Expression.property("name.first")).descending()
}
let q = QueryBuilder.select(kDOCID).from(DataSource.database(db)).orderBy(o)
var firstNames: [String] = []
let numRows = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
if let firstName = doc.dictionary(forKey: "name")?.string(forKey: "first") {
firstNames.append(firstName)
}
})
XCTAssertEqual(numRows, 100)
XCTAssertEqual(Int(numRows), firstNames.count)
let sorted = firstNames.sorted(by: { s1, s2 in return ascending ? s1 < s2 : s1 > s2 })
XCTAssertEqual(firstNames, sorted);
}
}
func testSelectDistinct() throws {
let doc1 = MutableDocument()
doc1.setValue(20, forKey: "number")
try saveDocument(doc1)
let doc2 = MutableDocument()
doc2.setValue(20, forKey: "number")
try saveDocument(doc2)
let NUMBER = Expression.property("number")
let q = QueryBuilder.selectDistinct(SelectResult.expression(NUMBER)).from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.int(at: 0), 20)
})
XCTAssertEqual(numRow, 1)
}
func testJoin() throws {
try loadNumbers(100)
let doc = createDocument("joinme")
doc.setValue(42, forKey: "theone")
try saveDocument(doc)
let DOCID = SelectResult.expression(Meta.id.from("main"))
let q = QueryBuilder
.select(DOCID)
.from(DataSource.database(db).as("main"))
.join(
Join.join(DataSource.database(db).as("secondary"))
.on(Expression.property("number1").from("main")
.equalTo(Expression.property("theone").from("secondary"))))
let numRow = try verifyQuery(q, block: { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
XCTAssertEqual(doc.int(forKey: "number1"), 42)
})
XCTAssertEqual(numRow, 1)
}
func testLeftJoin() throws {
try loadNumbers(100)
let doc = createDocument("joinme")
doc.setValue(42, forKey: "theone")
try saveDocument(doc)
let NUMBER1 = Expression.property("number2").from("main")
let NUMBER2 = Expression.property("theone").from("secondary")
let join = Join.leftJoin(DataSource.database(db).as("secondary"))
.on(Expression.property("number1").from("main")
.equalTo(Expression.property("theone").from("secondary")))
let q = QueryBuilder
.select(SelectResult.expression(NUMBER1),SelectResult.expression(NUMBER2))
.from(DataSource.database(db).as("main"))
.join(join)
let numRow = try verifyQuery(q, block: { (n, r) in
if (n == 41) {
XCTAssertEqual(r.int(at: 0) , 59)
XCTAssertNil(r.value(at: 1));
}
if (n == 42) {
XCTAssertEqual(r.int(at: 0) , 58)
XCTAssertEqual(r.int(at: 1) , 42)
}
})
XCTAssertEqual(numRow, 101)
}
func testCrossJoin() throws {
try loadNumbers(10)
let NUMBER1 = Expression.property("number1").from("main")
let NUMBER2 = Expression.property("number2").from("secondary")
let join = Join.crossJoin(DataSource.database(db).as("secondary"))
let q = QueryBuilder
.select(SelectResult.expression(NUMBER1),SelectResult.expression(NUMBER2))
.from(DataSource.database(db).as("main"))
.join(join).orderBy(Ordering.expression(NUMBER2))
let numRow = try verifyQuery(q, block: { (n, r) in
let num1 = r.int(at: 0)
let num2 = r.int(at: 1)
XCTAssertEqual ((num1 - 1)%10,Int((n - 1) % 10) )
XCTAssertEqual (num2 ,Int((n - 1)/10) )
})
XCTAssertEqual(numRow, 100)
}
func testJoinByDocID() throws {
try loadNumbers(100)
let doc = MutableDocument(id: "joinme")
doc.setInt(42, forKey: "theone")
doc.setString("doc1", forKey: "numberID")
try db.saveDocument(doc)
let mainDS = DataSource.database(db).as("main")
let secondaryDS = DataSource.database(db).as("secondary")
let mainPropExpr = Meta.id.from("main")
let secondaryExpr = Expression.property("numberID").from("secondary")
let joinExpr = mainPropExpr.equalTo(secondaryExpr)
let join = Join.innerJoin(secondaryDS).on(joinExpr)
let mainDocID = SelectResult.expression(mainPropExpr).as("mainDocID")
let secondaryDocID = SelectResult.expression(Meta.id.from("secondary")).as("secondaryDocID")
let secondaryTheOne = SelectResult.expression(Expression.property("theone").from("secondary"))
let q = QueryBuilder
.select(mainDocID, secondaryDocID, secondaryTheOne)
.from(mainDS)
.join(join)
let numRows = try verifyQuery(q) { (n, row) in
XCTAssertEqual(n, 1)
guard
let docID = row.string(forKey: "mainDocID"),
let doc = db.document(withID: docID)
else {
assertionFailure()
return
}
XCTAssertEqual(doc.int(forKey: "number1"), 1)
XCTAssertEqual(doc.int(forKey: "number2"), 99)
XCTAssertEqual(row.string(forKey: "secondaryDocID"), "joinme")
XCTAssertEqual(row.int(forKey: "theone"), 42)
}
XCTAssertEqual(numRows, 1)
}
func testGroupBy() throws {
var expectedStates = ["AL", "CA", "CO", "FL", "IA"]
var expectedCounts = [1, 6, 1, 1, 3]
var expectedMaxZips = ["35243", "94153", "81223", "33612", "50801"]
try loadJSONResource(name: "names_100")
let STATE = Expression.property("contact.address.state");
let COUNT = Function.count(Expression.int(1))
let MAXZIP = Function.max(Expression.property("contact.address.zip"))
let GENDER = Expression.property("gender")
let S_STATE = SelectResult.expression(STATE)
let S_COUNT = SelectResult.expression(COUNT)
let S_MAXZIP = SelectResult.expression(MAXZIP)
var q = QueryBuilder
.select(S_STATE, S_COUNT, S_MAXZIP)
.from(DataSource.database(db))
.where(GENDER.equalTo(Expression.string("female")))
.groupBy(STATE)
.orderBy(Ordering.expression(STATE))
var numRow = try verifyQuery(q, block: { (n, r) in
let state = r.string(at: 0)!
let count = r.int(at: 1)
let maxzip = r.string(at: 2)!
let i: Int = Int(n-1)
if i < expectedStates.count {
XCTAssertEqual(state, expectedStates[i])
XCTAssertEqual(count, expectedCounts[i])
XCTAssertEqual(maxzip, expectedMaxZips[i])
}
})
XCTAssertEqual(numRow, 31)
// With Having
expectedStates = ["CA", "IA", "IN"]
expectedCounts = [6, 3, 2]
expectedMaxZips = ["94153", "50801", "47952"]
q = QueryBuilder
.select(S_STATE, S_COUNT, S_MAXZIP)
.from(DataSource.database(db))
.where(GENDER.equalTo(Expression.string("female")))
.groupBy(STATE)
.having(COUNT.greaterThan(Expression.int(1)))
.orderBy(Ordering.expression(STATE))
numRow = try verifyQuery(q, block: { (n, r) in
let state = r.string(at: 0)!
let count = r.int(at: 1)
let maxzip = r.string(at: 2)!
let i: Int = Int(n-1)
if i < expectedStates.count {
XCTAssertEqual(state, expectedStates[i])
XCTAssertEqual(count, expectedCounts[i])
XCTAssertEqual(maxzip, expectedMaxZips[i])
}
})
XCTAssertEqual(numRow, 15)
}
func testParameters() throws {
try loadNumbers(10)
let NUMBER1 = Expression.property("number1")
let PARAM_N1 = Expression.parameter("num1")
let PARAM_N2 = Expression.parameter("num2")
let q = QueryBuilder
.select([SelectResult.expression(NUMBER1),
SelectResult.expression(Expression.parameter("string")),
SelectResult.expression(Expression.parameter("maxInt")),
SelectResult.expression(Expression.parameter("minInt")),
SelectResult.expression(Expression.parameter("maxInt64")),
SelectResult.expression(Expression.parameter("minInt64")),
SelectResult.expression(Expression.parameter("maxFloat")),
SelectResult.expression(Expression.parameter("minFloat")),
SelectResult.expression(Expression.parameter("maxDouble")),
SelectResult.expression(Expression.parameter("minDouble")),
SelectResult.expression(Expression.parameter("bool")),
SelectResult.expression(Expression.parameter("date")),
SelectResult.expression(Expression.parameter("blob")),
SelectResult.expression(Expression.parameter("array")),
SelectResult.expression(Expression.parameter("dict"))])
.from(DataSource.database(db))
.where(NUMBER1.between(PARAM_N1, and: PARAM_N2))
.orderBy(Ordering.expression(NUMBER1))
let blob = Blob(contentType: "text/plain", data: kTestBlob.data(using: .utf8)!)
let subarray = MutableArrayObject(data: ["a", "b"])
let dict = MutableDictionaryObject(data: ["a": "aa", "b": "bb"])
q.parameters = Parameters()
.setValue(2, forName: "num1")
.setValue(5, forName: "num2")
.setString("someString", forName: "string")
.setInt(Int.max, forName: "maxInt")
.setInt(Int.min, forName: "minInt")
.setInt64(Int64.max, forName: "maxInt64")
.setInt64(Int64.min, forName: "minInt64")
.setFloat(Float.greatestFiniteMagnitude, forName: "maxFloat")
.setFloat(Float.leastNormalMagnitude, forName: "minFloat")
.setDouble(Double.greatestFiniteMagnitude, forName: "maxDouble")
.setDouble(Double.leastNormalMagnitude, forName: "minDouble")
.setBoolean(true, forName: "bool")
.setDate(dateFromJson(kTestDate), forName: "date")
.setBlob(blob, forName: "blob")
.setArray(subarray, forName: "array")
.setDictionary(dict, forName: "dict")
XCTAssertEqual(q.parameters!.value(forName: "string") as? String, "someString")
XCTAssertEqual(q.parameters!.value(forName: "maxInt") as! Int, Int.max)
XCTAssertEqual(q.parameters!.value(forName: "minInt") as! Int, Int.min)
XCTAssertEqual(q.parameters!.value(forName: "maxInt64") as! Int64, Int64.max)
XCTAssertEqual(q.parameters!.value(forName: "minInt64") as! Int64, Int64.min)
XCTAssertEqual(q.parameters!.value(forName: "maxFloat") as! Float, Float.greatestFiniteMagnitude)
XCTAssertEqual(q.parameters!.value(forName: "minFloat") as! Float, Float.leastNormalMagnitude)
XCTAssertEqual(q.parameters!.value(forName: "maxDouble") as! Double, Double.greatestFiniteMagnitude)
XCTAssertEqual(q.parameters!.value(forName: "minDouble") as! Double, Double.leastNormalMagnitude)
XCTAssertEqual(q.parameters!.value(forName: "bool") as! Bool, true)
XCTAssert((q.parameters!.value(forName: "date") as! Date).timeIntervalSince(dateFromJson(kTestDate)) < 1)
XCTAssertEqual((q.parameters!.value(forName: "blob") as! Blob).content, blob.content)
XCTAssertEqual(q.parameters!.value(forName: "array") as! MutableArrayObject, subarray)
XCTAssertEqual(q.parameters!.value(forName: "dict") as! MutableDictionaryObject, dict)
let expectedNumbers = [2, 3, 4, 5]
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.int(at: 0), expectedNumbers[Int(n-1)])
XCTAssertEqual(r.string(at: 1) , "someString")
XCTAssertEqual(r.int(at: 2), Int.max)
XCTAssertEqual(r.int(at: 3), Int.min)
XCTAssertEqual(r.int64(at: 4), Int64.max)
XCTAssertEqual(r.int64(at: 5), Int64.min)
XCTAssertEqual(r.float(at: 6), Float.greatestFiniteMagnitude)
XCTAssertEqual(r.float(at: 7), Float.leastNormalMagnitude)
XCTAssertEqual(r.double(at: 8), Double.greatestFiniteMagnitude)
XCTAssertEqual(r.double(at: 9), Double.leastNormalMagnitude)
XCTAssertEqual(r.boolean(at: 10), true)
XCTAssert(r.date(at: 11)!.timeIntervalSince(dateFromJson(kTestDate)) < 1)
XCTAssertEqual(r.blob(at: 12)!.content, blob.content)
XCTAssertEqual(r.array(at: 13), subarray)
XCTAssertEqual(r.dictionary(at: 14), dict)
})
XCTAssertEqual(numRow, 4)
}
func testMeta() throws {
try loadNumbers(5)
let DOC_ID = Meta.id
let REV_ID = Meta.revisionID
let DOC_SEQ = Meta.sequence
let NUMBER1 = Expression.property("number1")
let S_DOC_ID = SelectResult.expression(DOC_ID)
let S_REV_ID = SelectResult.expression(REV_ID)
let S_DOC_SEQ = SelectResult.expression(DOC_SEQ)
let S_NUMBER1 = SelectResult.expression(NUMBER1)
let q = QueryBuilder
.select(S_DOC_ID, S_REV_ID, S_DOC_SEQ, S_NUMBER1)
.from(DataSource.database(db))
.orderBy(Ordering.expression(DOC_SEQ))
let expectedDocIDs = ["doc1", "doc2", "doc3", "doc4", "doc5"]
let expectedSeqs = [1, 2, 3, 4, 5]
let expectedNumbers = [1, 2, 3, 4, 5]
let numRow = try verifyQuery(q, block: { (n, r) in
let id1 = r.string(at: 0)!
let id2 = r.string(forKey: "id")
let revID1 = r.string(at: 1)!
let revID2 = r.string(forKey: "revisionID")
let sequence1 = r.int(at: 2)
let sequence2 = r.int(forKey: "sequence")
let number = r.int(at: 3)
XCTAssertEqual(id1, id2)
XCTAssertEqual(id1, expectedDocIDs[Int(n-1)])
XCTAssertEqual(revID1, revID2)
XCTAssertEqual(revID1, db.document(withID: id1)!.revisionID)
XCTAssertEqual(sequence1, sequence2)
XCTAssertEqual(sequence1, expectedSeqs[Int(n-1)])
XCTAssertEqual(number, expectedNumbers[Int(n-1)])
})
XCTAssertEqual(numRow, 5)
}
func testLimit() throws {
try loadNumbers(10)
let NUMBER1 = Expression.property("number1")
var q = QueryBuilder
.select(SelectResult.expression(NUMBER1))
.from(DataSource.database(db))
.orderBy(Ordering.expression(NUMBER1))
.limit(Expression.int(5))
var expectedNumbers = [1, 2, 3, 4, 5]
var numRow = try verifyQuery(q, block: { (n, row) in
let number = row.value(at: 0) as! Int
XCTAssertEqual(number, expectedNumbers[Int(n-1)])
})
XCTAssertEqual(numRow, 5)
q = QueryBuilder
.select(SelectResult.expression(NUMBER1))
.from(DataSource.database(db))
.orderBy(Ordering.expression(NUMBER1))
.limit(Expression.parameter("LIMIT_NUM"))
q.parameters = Parameters().setValue(3, forName: "LIMIT_NUM")
expectedNumbers = [1, 2, 3]
numRow = try verifyQuery(q, block: { (n, r) in
let number = r.int(at: 0)
XCTAssertEqual(number, expectedNumbers[Int(n-1)])
})
XCTAssertEqual(numRow, 3)
}
func testLimitOffset() throws {
try loadNumbers(10)
let NUMBER1 = Expression.property("number1")
var q = QueryBuilder
.select(SelectResult.expression(NUMBER1))
.from(DataSource.database(db))
.orderBy(Ordering.expression(NUMBER1))
.limit(Expression.int(5), offset: Expression.int(3))
var expectedNumbers = [4, 5, 6, 7, 8]
var numRow = try verifyQuery(q, block: { (n, row) in
let number = row.value(at: 0) as! Int
XCTAssertEqual(number, expectedNumbers[Int(n-1)])
})
XCTAssertEqual(numRow, 5)
q = QueryBuilder
.select(SelectResult.expression(NUMBER1))
.from(DataSource.database(db))
.orderBy(Ordering.expression(NUMBER1))
.limit(Expression.parameter("LIMIT_NUM"), offset: Expression.parameter("OFFSET_NUM"))
q.parameters = Parameters()
.setValue(3, forName: "LIMIT_NUM")
.setValue(5, forName: "OFFSET_NUM")
expectedNumbers = [6, 7, 8]
numRow = try verifyQuery(q, block: { (n, r) in
let number = r.int(at: 0)
XCTAssertEqual(number, expectedNumbers[Int(n-1)])
})
XCTAssertEqual(numRow, 3)
}
func testQueryResult() throws {
try loadJSONResource(name: "names_100")
let FNAME = Expression.property("name.first")
let LNAME = Expression.property("name.last")
let GENDER = Expression.property("gender")
let CITY = Expression.property("contact.address.city")
let S_FNAME = SelectResult.expression(FNAME).as("firstname")
let S_LNAME = SelectResult.expression(LNAME).as("lastname")
let S_GENDER = SelectResult.expression(GENDER)
let S_CITY = SelectResult.expression(CITY)
let q = QueryBuilder
.select(S_FNAME, S_LNAME, S_GENDER, S_CITY)
.from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 4)
XCTAssertEqual(r.value(forKey: "firstname") as! String, r.value(at: 0) as! String)
XCTAssertEqual(r.value(forKey: "lastname") as! String, r.value(at: 1) as! String)
XCTAssertEqual(r.value(forKey: "gender") as! String, r.value(at: 2) as! String)
XCTAssertEqual(r.value(forKey: "city") as! String, r.value(at: 3) as! String)
})
XCTAssertEqual(numRow, 100)
}
func testQueryProjectingKeys() throws {
try loadNumbers(100)
let AVG = SelectResult.expression(Function.avg(Expression.property("number1")))
let CNT = SelectResult.expression(Function.count(Expression.property("number1")))
let MIN = SelectResult.expression(Function.min(Expression.property("number1")))
let MAX = SelectResult.expression(Function.max(Expression.property("number1")))
let SUM = SelectResult.expression(Function.sum(Expression.property("number1")))
let q = QueryBuilder
.select(AVG, CNT, MIN.as("min"), MAX, SUM.as("sum"))
.from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 5)
XCTAssertEqual(r.double(forKey: "$1"), r.double(at: 0))
XCTAssertEqual(r.int(forKey: "$2"), r.int(at: 1))
XCTAssertEqual(r.int(forKey: "min"), r.int(at: 2))
XCTAssertEqual(r.int(forKey: "$3"), r.int(at: 3))
XCTAssertEqual(r.int(forKey: "sum"), r.int(at: 4))
})
XCTAssertEqual(numRow, 1)
}
func testAggregateFunctions() throws {
try loadNumbers(100)
let AVG = SelectResult.expression(Function.avg(Expression.property("number1")))
let CNT = SelectResult.expression(Function.count(Expression.property("number1")))
let MIN = SelectResult.expression(Function.min(Expression.property("number1")))
let MAX = SelectResult.expression(Function.max(Expression.property("number1")))
let SUM = SelectResult.expression(Function.sum(Expression.property("number1")))
let q = QueryBuilder
.select(AVG, CNT, MIN, MAX, SUM)
.from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.double(at: 0), 50.5)
XCTAssertEqual(r.int(at: 1), 100)
XCTAssertEqual(r.int(at: 2), 1)
XCTAssertEqual(r.int(at: 3), 100)
XCTAssertEqual(r.int(at: 4), 5050)
})
XCTAssertEqual(numRow, 1)
}
func testArrayFunctions() throws {
let doc = MutableDocument(id: "doc1")
let array = MutableArrayObject()
array.addValue("650-123-0001")
array.addValue("650-123-0002")
doc.setValue(array, forKey: "array")
try self.db.saveDocument(doc)
let ARRAY_LENGTH = ArrayFunction.length(Expression.property("array"))
var q = QueryBuilder
.select(SelectResult.expression(ARRAY_LENGTH))
.from(DataSource.database(db))
var numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.int(at: 0), 2)
})
XCTAssertEqual(numRow, 1)
let ARRAY_CONTAINS1 = ArrayFunction.contains(Expression.property("array"), value: Expression.string("650-123-0001"))
let ARRAY_CONTAINS2 = ArrayFunction.contains(Expression.property("array"), value: Expression.string("650-123-0003"))
q = QueryBuilder
.select(SelectResult.expression(ARRAY_CONTAINS1), SelectResult.expression(ARRAY_CONTAINS2))
.from(DataSource.database(db))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.boolean(at: 0), true)
XCTAssertEqual(r.boolean(at: 1), false)
})
XCTAssertEqual(numRow, 1)
}
func testMathFunctions() throws {
let num = 0.6
let doc = MutableDocument(id: "doc1")
doc.setValue(num, forKey: "number")
try db.saveDocument(doc)
let expectedValues = [0.6,
acos(num),
asin(num),
atan(num),
atan2(90.0, num),
ceil(num),
cos(num),
num * 180.0 / Double.pi,
exp(num),
floor(num),
log(num),
log10(num),
pow(num, 2),
num * Double.pi / 180.0,
round(num),
round(num * 10.0) / 10.0,
1, sin(num),
sqrt(num),
tan(num),
trunc(num),
trunc(num * 10.0) / 10.0,
M_E,
Double.pi]
let p = Expression.property("number")
let functions = [Function.abs(p),
Function.acos(p),
Function.asin(p),
Function.atan(p),
Function.atan2(y: Expression.int(90), x: p),
Function.ceil(p),
Function.cos(p),
Function.degrees(p),
Function.exp(p),
Function.floor(p),
Function.ln(p),
Function.log(p),
Function.power(base: p, exponent: Expression.int(2)),
Function.radians(p),
Function.round(p),
Function.round(p, digits: Expression.int(1)),
Function.sign(p),
Function.sin(p),
Function.sqrt(p),
Function.tan(p),
Function.trunc(p),
Function.trunc(p, digits: Expression.int(1)),
Function.e(),
Function.pi()]
var index = 0
for f in functions {
let q = QueryBuilder
.select(SelectResult.expression(f))
.from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
let expected = expectedValues[index]
XCTAssertEqual(r.double(at: 0), expected, "Failure with \(f)")
})
XCTAssertEqual(numRow, 1)
index = index + 1
}
}
func testDivisionFunctionPrecision() throws {
let doc = MutableDocument()
.setDouble(5.0, forKey: "key1")
.setDouble(15.0, forKey: "key2")
.setDouble(5.5, forKey: "key3")
.setDouble(16.5, forKey: "key4")
try saveDocument(doc)
let withoutPrecision = Expression.property("key1").divide(Expression.property("key2"))
let withPrecision = Expression.property("key3").divide(Expression.property("key4"))
let q = QueryBuilder
.select(SelectResult.expression(withoutPrecision).as("withoutPrecision"),
SelectResult.expression(withPrecision).as("withPrecision"))
.from(DataSource.database(db))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssert(0.33333 - r.double(forKey: "withoutPrecision") < 0.0000)
XCTAssert(0.33333 - r.double(forKey: "withPrecision") < 0.0000)
})
XCTAssertEqual(numRow, 1)
}
func testStringFunctions() throws {
let str = " See you 18r "
let doc = MutableDocument(id: "doc1")
doc.setValue(str, forKey: "greeting")
try db.saveDocument(doc)
let p = Expression.property("greeting")
// Contains:
let CONTAINS1 = Function.contains(p, substring: Expression.string("8"))
let CONTAINS2 = Function.contains(p, substring: Expression.string("9"))
var q = QueryBuilder
.select(SelectResult.expression(CONTAINS1), SelectResult.expression(CONTAINS2))
.from(DataSource.database(db))
var numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.boolean(at: 0), true)
XCTAssertEqual(r.boolean(at: 1), false)
})
XCTAssertEqual(numRow, 1)
// Length:
let LENGTH = Function.length(p)
q = QueryBuilder
.select(SelectResult.expression(LENGTH))
.from(DataSource.database(db))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.int(at: 0), str.count)
})
XCTAssertEqual(numRow, 1)
// Lower, Ltrim, Rtrim, Trim, Upper
let LOWER = Function.lower(p)
let LTRIM = Function.ltrim(p)
let RTRIM = Function.rtrim(p)
let TRIM = Function.trim(p)
let UPPER = Function.upper(p)
q = QueryBuilder
.select(SelectResult.expression(LOWER),
SelectResult.expression(LTRIM),
SelectResult.expression(RTRIM),
SelectResult.expression(TRIM),
SelectResult.expression(UPPER))
.from(DataSource.database(db))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0), str.lowercased())
XCTAssertEqual(r.string(at: 1), "See you 18r ")
XCTAssertEqual(r.string(at: 2), " See you 18r")
XCTAssertEqual(r.string(at: 3), "See you 18r")
XCTAssertEqual(r.string(at: 4), str.uppercased())
})
XCTAssertEqual(numRow, 1)
}
func testQuantifiedOperators() throws {
try loadJSONResource(name: "names_100")
let DOC_ID = Meta.id
let S_DOC_ID = SelectResult.expression(DOC_ID)
let LIKES = Expression.property("likes")
let LIKE = ArrayExpression.variable("LIKE")
// ANY:
var q = QueryBuilder
.select(S_DOC_ID)
.from(DataSource.database(db))
.where(ArrayExpression.any(LIKE).in(LIKES).satisfies(LIKE.equalTo(Expression.string("climbing"))))
let expected = ["doc-017", "doc-021", "doc-023", "doc-045", "doc-060"]
var numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0), expected[Int(n)-1])
})
XCTAssertEqual(numRow, UInt64(expected.count))
// EVERY:
q = QueryBuilder
.select(S_DOC_ID)
.from(DataSource.database(db))
.where(ArrayExpression.every(LIKE).in(LIKES).satisfies(LIKE.equalTo(Expression.string("taxes"))))
numRow = try verifyQuery(q, block: { (n, r) in
if n == 1 {
XCTAssertEqual(r.string(at: 0), "doc-007")
}
})
XCTAssertEqual(numRow, 42)
// ANY AND EVERY:
q = QueryBuilder
.select(S_DOC_ID)
.from(DataSource.database(db))
.where(ArrayExpression.anyAndEvery(LIKE).in(LIKES).satisfies(LIKE.equalTo(Expression.string("taxes"))))
numRow = try verifyQuery(q, block: { (n, r) in })
XCTAssertEqual(numRow, 0)
}
func testSelectAll() throws {
try loadNumbers(100)
let NUMBER1 = Expression.property("number1")
let S_STAR = SelectResult.all()
let S_NUMBER1 = SelectResult.expression(NUMBER1)
let TESTDB_NUMBER1 = Expression.property("number1").from("testdb")
let S_TESTDB_STAR = SelectResult.all().from("testdb")
let S_TESTDB_NUMBER1 = SelectResult.expression(TESTDB_NUMBER1)
// SELECT *
var q = QueryBuilder
.select(S_STAR)
.from(DataSource.database(db))
var numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 1)
let a1 = r.dictionary(at: 0)!
let a2 = r.dictionary(forKey: db.name)!
XCTAssertEqual(a1.int(forKey: "number1"), Int(n))
XCTAssertEqual(a1.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(a2.int(forKey: "number1"), Int(n))
XCTAssertEqual(a2.int(forKey: "number2"), Int(100 - n))
})
XCTAssertEqual(numRow, 100)
// SELECT testdb.*
q = QueryBuilder
.select(S_TESTDB_STAR)
.from(DataSource.database(db).as("testdb"))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 1)
let a1 = r.dictionary(at: 0)!
let a2 = r.dictionary(forKey: "testdb")!
XCTAssertEqual(a1.int(forKey: "number1"), Int(n))
XCTAssertEqual(a1.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(a2.int(forKey: "number1"), Int(n))
XCTAssertEqual(a2.int(forKey: "number2"), Int(100 - n))
})
XCTAssertEqual(numRow, 100)
// SELECT *, number1
q = QueryBuilder
.select(S_STAR, S_NUMBER1)
.from(DataSource.database(db))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 2)
let a1 = r.dictionary(at: 0)!
let a2 = r.dictionary(forKey: db.name)!
XCTAssertEqual(a1.int(forKey: "number1"), Int(n))
XCTAssertEqual(a1.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(a2.int(forKey: "number1"), Int(n))
XCTAssertEqual(a2.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(r.int(at: 1), Int(n))
XCTAssertEqual(r.int(forKey: "number1"), Int(n))
})
XCTAssertEqual(numRow, 100)
// SELECT testdb.*, testdb.number1
q = QueryBuilder
.select(S_TESTDB_STAR, S_TESTDB_NUMBER1)
.from(DataSource.database(db).as("testdb"))
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.count, 2)
let a1 = r.dictionary(at: 0)!
let a2 = r.dictionary(forKey: "testdb")!
XCTAssertEqual(a1.int(forKey: "number1"), Int(n))
XCTAssertEqual(a1.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(a2.int(forKey: "number1"), Int(n))
XCTAssertEqual(a2.int(forKey: "number2"), Int(100 - n))
XCTAssertEqual(r.int(at: 1), Int(n))
XCTAssertEqual(r.int(forKey: "number1"), Int(n))
})
XCTAssertEqual(numRow, 100)
}
func testSelectAllWithDatabaseAliasWithMultipleSources() throws {
try loadNumbers(100)
let doc = createDocument()
doc.setValue(42, forKey: "theOne")
try saveDocument(doc)
let q = QueryBuilder
.selectDistinct([SelectResult.all().from("main"),
SelectResult.all().from("secondary")])
.from(DataSource.database(db).as("main"))
.join(
Join.join(DataSource.database(db).as("secondary"))
.on(Expression.property("number1").from("main")
.equalTo(Expression.property("theOne").from("secondary"))))
let numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.dictionary(at: 0), r.dictionary(forKey: "main"));
XCTAssertEqual(r.dictionary(at: 1), r.dictionary(forKey: "secondary"));
})
XCTAssertEqual(numRow, 1)
}
func testUnicodeCollationWithLocale() throws {
let letters = ["B", "A", "Z", "Å"]
for letter in letters {
let doc = createDocument()
doc.setValue(letter, forKey: "string")
try saveDocument(doc)
}
let STRING = Expression.property("string")
let S_STRING = SelectResult.expression(STRING)
// Without locale:
let NO_LOCALE = Collation.unicode()
var q = QueryBuilder
.select(S_STRING)
.from(DataSource.database(db))
.orderBy(Ordering.expression(STRING.collate(NO_LOCALE)))
var expected = ["A", "Å", "B", "Z"]
var numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0), expected[Int(n)-1])
})
XCTAssertEqual(numRow, UInt64(expected.count))
// With locale
let WITH_LOCALE = Collation.unicode().locale("se")
q = QueryBuilder
.select(S_STRING)
.from(DataSource.database(db))
.orderBy(Ordering.expression(STRING.collate(WITH_LOCALE)))
expected = ["A", "B", "Z", "Å"]
numRow = try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0), expected[Int(n)-1])
})
XCTAssertEqual(numRow, UInt64(expected.count))
}
func testCompareWithUnicodeCollation() throws {
let bothSensitive = Collation.unicode()
let accentSensitive = Collation.unicode().ignoreCase(true)
let caseSensitive = Collation.unicode().ignoreAccents(true)
let noSensitive = Collation.unicode().ignoreCase(true).ignoreCase(true)
let testCases = [
// Edge cases: empty and 1-char strings:
("", "", true, bothSensitive),
("", "a", false, bothSensitive),
("a", "a", true, bothSensitive),
// Case sensitive: lowercase come first by unicode rules:
("a", "A", false, bothSensitive),
("abc", "abc", true, bothSensitive),
("Aaa", "abc", false, bothSensitive),
("abc", "abC", false, bothSensitive),
("AB", "abc", false, bothSensitive),
// Case insenstive:
("ABCDEF", "ZYXWVU", false, accentSensitive),
("ABCDEF", "Z", false, accentSensitive),
("a", "A", true, accentSensitive),
("abc", "ABC", true, accentSensitive),
("ABA", "abc", false, accentSensitive),
("commonprefix1", "commonprefix2", false, accentSensitive),
("commonPrefix1", "commonprefix2", false, accentSensitive),
("abcdef", "abcdefghijklm", false, accentSensitive),
("abcdeF", "abcdefghijklm", false, accentSensitive),
// Now bring in non-ASCII characters:
("a", "á", false, accentSensitive),
("", "á", false, accentSensitive),
("á", "á", true, accentSensitive),
("•a", "•A", true, accentSensitive),
("test a", "test á", false, accentSensitive),
("test á", "test b", false, accentSensitive),
("test á", "test Á", true, accentSensitive),
("test á1", "test Á2", false, accentSensitive),
// Case sensitive, diacritic sensitive:
("ABCDEF", "ZYXWVU", false, bothSensitive),
("ABCDEF", "Z", false, bothSensitive),
("a", "A", false, bothSensitive),
("abc", "ABC", false, bothSensitive),
("•a", "•A", false, bothSensitive),
("test a", "test á", false, bothSensitive),
("Ähnlichkeit", "apple", false, bothSensitive), // Because 'h'-vs-'p' beats 'Ä'-vs-'a'
("ax", "Äz", false, bothSensitive),
("test a", "test Á", false, bothSensitive),
("test Á", "test e", false, bothSensitive),
("test á", "test Á", false, bothSensitive),
("test á", "test b", false, bothSensitive),
("test u", "test Ü", false, bothSensitive),
// Case sensitive, diacritic insensitive
("abc", "ABC", false, caseSensitive),
("test á", "test a", true, caseSensitive),
("test á", "test A", false, caseSensitive),
("test á", "test b", false, caseSensitive),
("test á", "test Á", false, caseSensitive),
// Case and diacritic insensitive
("test á", "test Á", true, noSensitive)
]
for data in testCases {
let doc = createDocument()
doc.setValue(data.0, forKey: "value")
try saveDocument(doc)
let VALUE = Expression.property("value")
let comparison = data.2 ?
VALUE.collate(data.3).equalTo(Expression.string(data.1)) :
VALUE.collate(data.3).lessThan(Expression.string(data.1))
let q = QueryBuilder.select().from(DataSource.database(db)).where(comparison)
let numRow = try verifyQuery(q, block: { (n, r) in })
XCTAssertEqual(numRow, 1)
try db.deleteDocument(doc)
}
}
func testResultSetEnumeration() throws {
try loadNumbers(5)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.orderBy(Ordering.property("number1"))
// Enumeration
var i = 0
var rs = try q.execute()
while let r = rs.next() {
XCTAssertEqual(r.string(at: 0), "doc\(i+1)")
i+=1
}
XCTAssertEqual(i, 5)
XCTAssertNil(rs.next())
XCTAssert(rs.allResults().isEmpty)
// Fast enumeration:
i = 0
rs = try q.execute()
for r in rs {
XCTAssertEqual(r.string(at: 0), "doc\(i+1)")
i+=1
}
XCTAssertEqual(i, 5)
XCTAssertNil(rs.next())
XCTAssert(rs.allResults().isEmpty)
}
func testGetAllResults() throws {
try loadNumbers(5)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.orderBy(Ordering.property("number1"))
// Get all results:
var i = 0
var rs = try q.execute()
var results = rs.allResults()
for r in results {
XCTAssertEqual(r.string(at: 0), "doc\(i+1)")
i+=1
}
XCTAssertEqual(results.count, 5)
XCTAssertNil(rs.next())
XCTAssert(rs.allResults().isEmpty)
// Partial enumerating then get all results:
i = 0
rs = try q.execute()
XCTAssertNotNil(rs.next())
XCTAssertNotNil(rs.next())
results = rs.allResults()
for r in results {
XCTAssertEqual(r.string(at: 0), "doc\(i+3)")
i+=1
}
XCTAssertEqual(results.count, 3)
XCTAssertNil(rs.next())
XCTAssert(rs.allResults().isEmpty)
}
func testMissingValue() throws {
let doc1 = createDocument("doc1")
doc1.setValue("Scott", forKey: "name")
doc1.setValue(nil, forKey: "address")
try saveDocument(doc1)
let q = QueryBuilder
.select(SelectResult.property("name"),
SelectResult.property("address"),
SelectResult.property("age"))
.from(DataSource.database(db))
let rs = try q.execute()
let r = rs.next()!
// Array:
XCTAssertEqual(r.count, 3)
XCTAssertEqual(r.string(at: 0), "Scott")
XCTAssertNil(r.value(at: 1))
XCTAssertNil(r.value(at: 2))
let array = r.toArray()
XCTAssertEqual(array.count, 3)
XCTAssertEqual(array[0] as! String, "Scott")
XCTAssertEqual(array[1] as! NSNull, NSNull())
XCTAssertEqual(array[2] as! NSNull, NSNull())
// Dictionary:
XCTAssertEqual(r.string(forKey: "name"), "Scott")
XCTAssertNil(r.value(forKey: "address"))
XCTAssertTrue(r.contains(key: "address"))
XCTAssertNil(r.value(forKey: "age"))
XCTAssertFalse(r.contains(key: "age"))
let dict = r.toDictionary()
XCTAssertEqual(dict.count, 2)
XCTAssertEqual(dict["name"] as! String, "Scott")
XCTAssertEqual(dict["address"] as! NSNull, NSNull())
}
func testJSONRepresentation() throws {
let doc1 = MutableDocument()
doc1.setValue("string", forKey: "string")
try saveDocument(doc1)
let q1 = QueryBuilder.select(kDOCID).from(DataSource.database(db)).where(
Expression.property("string").is(Expression.string("string")))
let json = q1.JSONRepresentation
let q = Query(database: db, JSONRepresentation: json)
let numRows = try verifyQuery(q) { (n, r) in
let doc = db.document(withID: r.string(at: 0)!)!
XCTAssertEqual(doc.id, doc1.id);
XCTAssertEqual(doc.string(forKey: "string")!, "string");
}
XCTAssertEqual(numRows, 1);
}
// MARK: META - isDeleted
func testMetaIsDeletedEmpty() throws {
try loadNumbers(5)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.isDeleted)
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 0)
}
func testIsDeletedWithSingleDocumentDeletion() throws {
// create doc
let doc = MutableDocument().setString("somevalue", forKey: "somekey")
try db.saveDocument(doc)
// check valid input
let selectAllDBQuery = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
var selectAllResultSet = try selectAllDBQuery.execute()
XCTAssertEqual(selectAllResultSet.allResults().count, 1)
let selectDeletedOnlyQuery = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.isDeleted)
var selectDeletedOnlyResultSet = try selectDeletedOnlyQuery.execute()
XCTAssertEqual(selectDeletedOnlyResultSet.allResults().count, 0)
// delete action
try db.deleteDocument(doc)
// vertify result
selectAllResultSet = try selectAllDBQuery.execute()
XCTAssertEqual(selectAllResultSet.allResults().count, 0)
selectDeletedOnlyResultSet = try selectDeletedOnlyQuery.execute()
XCTAssertEqual(selectDeletedOnlyResultSet.allResults().count, 1)
}
func testIsDeletedWithMultipleDocumentsDeletion() throws {
let documentsCount = 10
var docs = [MutableDocument]()
try db.inBatch {
for _ in 0..<documentsCount {
// create doc
let doc = MutableDocument().setString("somevalue", forKey: "somekey")
docs.append(doc)
try db.saveDocument(doc)
}
}
// check valid input
let selectAllDBQuery = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
var selectAllResultSet = try selectAllDBQuery.execute()
XCTAssertEqual(selectAllResultSet.allResults().count, documentsCount)
let selectDeletedOnlyQuery = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.isDeleted)
var selectDeletedOnlyResultSet = try selectDeletedOnlyQuery.execute()
XCTAssertEqual(selectDeletedOnlyResultSet.allResults().count, 0)
// delete action
try db.inBatch {
for doc in docs {
try db.deleteDocument(doc)
}
}
// vertify result
selectAllResultSet = try selectAllDBQuery.execute()
XCTAssertEqual(selectAllResultSet.allResults().count, 0)
selectDeletedOnlyResultSet = try selectDeletedOnlyQuery.execute()
XCTAssertEqual(selectDeletedOnlyResultSet.allResults().count, documentsCount)
}
// MARK: META - expired
func testMetaExpirationWithNoDocumentWithExpiration() throws {
try loadNumbers(5)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.expiration.greaterThan(Expression.int(0)))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 0)
}
func testMetaExpirationWithValidLessThan() throws {
let doc = MutableDocument()
try db.saveDocument(doc)
let expiry = Date(timeIntervalSinceNow: 120)
try db.setDocumentExpiration(withID: doc.id, expiration: expiry)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.expiration
.lessThan(Expression.double(expiry.addingTimeInterval(1).timeIntervalSince1970 * 1000)))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 1)
}
func testMetaExpirationWithInvalidLessThan() throws {
let doc = MutableDocument()
try db.saveDocument(doc)
let expiry = Date(timeIntervalSinceNow: 120)
try db.setDocumentExpiration(withID: doc.id, expiration: expiry)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.expiration
.lessThan(Expression.double(expiry.addingTimeInterval(-1).timeIntervalSince1970 * 1000)))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 0)
}
func testMetaExpirationWithValidGreaterThan() throws {
let doc = MutableDocument()
try db.saveDocument(doc)
let expiry = Date(timeIntervalSinceNow: 120)
try db.setDocumentExpiration(withID: doc.id, expiration: expiry)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.expiration
.greaterThan(Expression
.double(expiry.addingTimeInterval(-1).timeIntervalSince1970 * 1000)))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 1)
}
func testMetaExpirationWithInvalidGreaterThan() throws {
let doc = MutableDocument()
try db.saveDocument(doc)
let expiry = Date(timeIntervalSinceNow: 120)
try db.setDocumentExpiration(withID: doc.id, expiration: expiry)
let q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.expiration
.greaterThan(Expression
.double(expiry.addingTimeInterval(1).timeIntervalSince1970 * 1000)))
let rs = try q.execute()
XCTAssertEqual(rs.allResults().count, 0)
}
// MARK: META - revisionID
func testMetaRevisionID() throws {
// Create doc:
let doc = MutableDocument()
try db.saveDocument(doc)
var q = QueryBuilder
.select(SelectResult.expression(Meta.revisionID))
.from(DataSource.database(db))
.where(Meta.id.equalTo(Expression.string(doc.id)))
try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0)!, doc.revisionID!)
})
// Update doc:
doc.setValue("bar", forKey: "foo")
try db.saveDocument(doc)
try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0)!, doc.revisionID!)
})
// Use meta.revisionID in WHERE clause
q = QueryBuilder
.select(SelectResult.expression(Meta.id))
.from(DataSource.database(db))
.where(Meta.revisionID.equalTo(Expression.string(doc.revisionID!)))
try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0)!, doc.id)
})
// Delete doc:
try db.deleteDocument(doc)
q = QueryBuilder
.select(SelectResult.expression(Meta.revisionID))
.from(DataSource.database(db))
.where(Meta.isDeleted.equalTo(Expression.boolean(true)))
try verifyQuery(q, block: { (n, r) in
XCTAssertEqual(r.string(at: 0)!, doc.revisionID!)
})
}
// MARK: toJSON
func testQueryJSON() throws {
let json = try getRickAndMortyJSON()
let mDoc = try MutableDocument(id: "doc", json: json)
try self.db.saveDocument(mDoc)
let q = QueryBuilder.select([kDOCID,
SelectResult.property("name"),
SelectResult.property("isAlive"),
SelectResult.property("species"),
SelectResult.property("picture"),
SelectResult.property("gender"),
SelectResult.property("registered"),
SelectResult.property("latitude"),
SelectResult.property("longitude"),
SelectResult.property("aka"),
SelectResult.property("family"),
SelectResult.property("origin")])
.from(DataSource.database(self.db))
let rs = try q.execute()
let r = rs.allResults().first!
let jsonObj = r.toJSON().toJSONObj() as! [String: Any]
XCTAssertEqual(jsonObj["id"] as! String, "doc")
XCTAssertEqual(jsonObj["name"] as! String, "Rick Sanchez")
XCTAssertEqual(jsonObj["isAlive"] as! Bool, true)
XCTAssertEqual(jsonObj["longitude"] as! Double, -21.152958)
XCTAssertEqual((jsonObj["aka"] as! Array<Any>)[0] as! String, "Rick C-137")
XCTAssertEqual((jsonObj["aka"] as! Array<Any>)[3] as! String, "Rick the Alien")
XCTAssertEqual((jsonObj["family"] as! Array<[String:Any]>)[0]["name"] as! String, "Morty Smith")
XCTAssertEqual((jsonObj["family"] as! Array<[String:Any]>)[3]["name"] as! String, "Summer Smith")
}
// MARK: N1QL
func testN1QLQuerySanity() throws {
let doc1 = MutableDocument()
doc1.setValue("Jerry", forKey: "firstName")
doc1.setValue("Ice Cream", forKey: "lastName")
try self.db.saveDocument(doc1)
let doc2 = MutableDocument()
doc2.setValue("Ben", forKey: "firstName")
doc2.setValue("Ice Cream", forKey: "lastName")
try self.db.saveDocument(doc2)
let q = try self.db.createQuery("SELECT firstName, lastName FROM \(self.db.name)")
let results = try q.execute().allResults()
XCTAssertEqual(results[0].string(forKey: "firstName"), "Jerry")
XCTAssertEqual(results[0].string(forKey: "lastName"), "Ice Cream")
XCTAssertEqual(results[1].string(forKey: "firstName"), "Ben")
XCTAssertEqual(results[1].string(forKey: "lastName"), "Ice Cream")
}
func testInvalidN1QL() throws {
expectError(domain: CBLError.domain, code: CBLError.invalidQuery) {
_ = try self.db.createQuery("SELECT firstName, lastName")
}
}
func testN1QLQueryOffsetWithoutLimit() throws {
let doc1 = MutableDocument()
doc1.setValue("Jerry", forKey: "firstName")
doc1.setValue("Ice Cream", forKey: "lastName")
try self.db.saveDocument(doc1)
let doc2 = MutableDocument()
doc2.setValue("Ben", forKey: "firstName")
doc2.setValue("Ice Cream", forKey: "lastName")
try self.db.saveDocument(doc2)
let q = try self.db.createQuery("SELECT firstName, lastName FROM \(self.db.name) offset 1")
let results = try q.execute().allResults()
XCTAssertEqual(results.count, 1)
}
// MARK: -- LiveQuery
func testJSONLiveQuery() throws {
let q = QueryBuilder
.select()
.from(DataSource.database(db))
.where(Expression.property("number1").lessThan(Expression.int(10)))
.orderBy(Ordering.property("number1"))
try testLiveQuery(query: q)
}
func testN1QLLiveQuery() throws {
let q = try db.createQuery("SELECT * FROM testdb WHERE number1 < 10")
try testLiveQuery(query: q)
}
func testLiveQuery(query: Query) throws {
try loadNumbers(100)
var count = 0;
let x1 = expectation(description: "1st change")
let x2 = expectation(description: "2nd change")
let token = query.addChangeListener { (change) in
count = count + 1
XCTAssertNotNil(change.query)
XCTAssertNil(change.error)
let rows = Array(change.results!)
if count == 1 {
XCTAssertEqual(rows.count, 9)
x1.fulfill()
} else {
XCTAssertEqual(rows.count, 10)
x2.fulfill()
}
}
wait(for: [x1], timeout: 2.0)
try! self.createDoc(numbered: -1, of: 100)
wait(for: [x2], timeout: 2.0)
query.removeChangeListener(withToken: token)
}
func testLiveQueryNoUpdate() throws {
var count = 0;
let q = QueryBuilder
.select()
.from(DataSource.database(db))
let x1 = expectation(description: "1st change")
let token = q.addChangeListener { (change) in
count = count + 1
XCTAssertNotNil(change.query)
XCTAssertNil(change.error)
let rows = Array(change.results!)
XCTAssertEqual(rows.count, 0)
x1.fulfill()
}
wait(for: [x1], timeout: 5.0)
XCTAssertEqual(count, 1)
q.removeChangeListener(withToken: token)
}
// When adding a second listener after the first listener is notified, the second listener
// should get the change (current result).
func testLiveQuerySecondListenerReturnsResultsImmediately() throws {
try createDoc(numbered: 7, of: 10)
let query = QueryBuilder
.select(SelectResult.property("number1"))
.from(DataSource.database(db))
.where(Expression.property("number1").lessThan(Expression.int(10)))
.orderBy(Ordering.property("number1"))
// first listener
let x1 = expectation(description: "1st change")
var count = 0;
let token = query.addChangeListener { (change) in
count = count + 1
let rows = Array(change.results!)
if count == 1 {
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0].int(at: 0), 7)
x1.fulfill()
}
}
wait(for: [x1], timeout: 5.0)
XCTAssertEqual(count, 1)
// adding a second listener should be returning the last results!
let x2 = expectation(description: "1st change from 2nd listener")
var count2 = 0
let token2 = query.addChangeListener { (change) in
count2 = count2 + 1
let rows = Array(change.results!)
if count2 == 1 {
XCTAssertEqual(rows.count, 1)
XCTAssertEqual(rows[0].int(at: 0), 7)
x2.fulfill()
}
}
wait(for: [x2], timeout: 2.0)
query.removeChangeListener(withToken: token)
query.removeChangeListener(withToken: token2)
XCTAssertEqual(count, 1)
XCTAssertEqual(count2, 1)
}
func testLiveQueryReturnsEmptyResultSet() throws {
try loadNumbers(100)
let query = QueryBuilder
.select(SelectResult.property("number1"))
.from(DataSource.database(db))
.where(Expression.property("number1").lessThan(Expression.int(10)))
.orderBy(Ordering.property("number1"))
let x1 = expectation(description: "wait-for-live-query-changes")
var count = 0;
let token = query.addChangeListener { (change) in
count = count + 1
let rows = Array(change.results!)
if count == 1 {
// initial notification about already existing result set!
XCTAssertEqual(rows.count, 9)
XCTAssertEqual(rows[0].int(at: 0), 1)
} else {
// deleted the doc should return empty result set!
XCTAssertEqual(rows.count, 8)
x1.fulfill()
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
try! self.db.purgeDocument(withID: "doc1")
}
wait(for: [x1], timeout: 10.0)
query.removeChangeListener(withToken: token)
XCTAssertEqual(count, 2)
}
/// When having more than one listeners, each listener should have independent result sets.
/// This means that both listeners should be able to iterate separately through the result
/// correct when getting the same change notified.
func testLiveQueryMultipleListenersReturnIndependentResultSet() throws {
try loadNumbers(100)
let query = QueryBuilder
.select(SelectResult.property("number1"))
.from(DataSource.database(db))
.where(Expression.property("number1").lessThan(Expression.int(10)))
.orderBy(Ordering.property("number1"))
let x1 = expectation(description: "1st change")
let x2 = expectation(description: "2nd change")
var count1 = 0;
let token1 = query.addChangeListener { (change) in
count1 = count1 + 1
guard let results = change.results else {
XCTFail("Results are empty")
return
}
if count1 == 1 {
var num = 0
for result in results {
num = num + 1
XCTAssert(result.int(at: 0) < 10)
}
XCTAssertEqual(num, 9)
x1.fulfill()
} else if count1 == 2 {
var num = 0
for result in results {
num = num + 1
XCTAssert(result.int(at: 0) < 10)
}
XCTAssertEqual(num, 10)
x2.fulfill()
}
}
let y1 = expectation(description: "1st change - 2nd listener")
let y2 = expectation(description: "2nd change - 2nd listener")
var count2 = 0;
let token2 = query.addChangeListener { (change) in
count2 = count2 + 1
guard let results = change.results else {
XCTFail("Results are empty")
return
}
if count2 == 1 {
var num = 0
for result in results {
num = num + 1
XCTAssert(result.int(at: 0) < 10)
}
XCTAssertEqual(num, 9)
y1.fulfill()
} else if count2 == 2 {
var num = 0
for result in results {
num = num + 1
XCTAssert(result.int(at: 0) < 10)
}
XCTAssertEqual(num, 10)
y2.fulfill()
}
}
wait(for: [x1, y1], timeout: 5.0)
try! self.createDoc(numbered: -1, of: 100)
wait(for: [x2, y2], timeout: 5.0)
query.removeChangeListener(withToken: token1)
query.removeChangeListener(withToken: token2)
XCTAssertEqual(count1, 2)
XCTAssertEqual(count2, 2)
}
func testLiveQueryUpdateQueryParam() throws {
try loadNumbers(100)
let x1 = expectation(description: "1st change")
let x2 = expectation(description: "1st change")
let query = QueryBuilder
.select(SelectResult.property("number1"))
.from(DataSource.database(db))
.where(Expression.property("number1").lessThan(Expression.parameter("param")))
.orderBy(Ordering.property("number1"))
// set the param
query.parameters = Parameters().setInt(10, forName: "param")
var count = 0;
let token = query.addChangeListener { (change) in
count = count + 1
let rows = Array(change.results!)
if count == 1 {
XCTAssertEqual(rows.count, 9)
x1.fulfill()
} else {
XCTAssertEqual(rows.count, 4)
x2.fulfill()
}
}
wait(for: [x1], timeout: 5.0)
query.parameters = Parameters().setInt(5, forName: "param")
wait(for: [x2], timeout: 5.0)
query.removeChangeListener(withToken: token)
XCTAssertEqual(count, 2)
}
}
| apache-2.0 | 479500c53645e172121b204ac458c70d | 39.075085 | 124 | 0.550308 | 4.303125 | false | true | false | false |
qinting513/SwiftNote | PullToRefreshKit-master 自定义刷新控件/Source/Classes/ElasticRefreshControl.swift | 2 | 5430 | //
// ElasticRefreshControl.swift
// SWTest
//
// Created by huangwenchen on 16/7/29.
// Copyright © 2016年 Leo. All rights reserved.
//
import Foundation
import UIKit
@IBDesignable
open class ElasticRefreshControl: UIView {
//目标,height 80, 高度 40
open let spinner:UIActivityIndicatorView = UIActivityIndicatorView()
var radius:CGFloat{
get{
return totalHeight / 4 - margin
}
}
open var progress:CGFloat = 0.0{
didSet{
setNeedsDisplay()
}
}
open var margin:CGFloat = 4.0{
didSet{
setNeedsDisplay()
}
}
var arrowRadius:CGFloat{
get{
return radius * 0.5 - 0.2 * radius * adjustedProgress
}
}
var adjustedProgress:CGFloat{
get{
return min(max(progress,0.0),1.0)
}
}
let totalHeight:CGFloat = 80
open var arrowColor = UIColor.white{
didSet{
setNeedsDisplay()
}
}
open var elasticTintColor = UIColor.init(white: 0.5, alpha: 0.6){
didSet{
setNeedsDisplay()
}
}
var animating = false{
didSet{
if animating{
spinner.startAnimating()
setNeedsDisplay()
}else{
spinner.stopAnimating()
setNeedsDisplay()
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
func commonInit(){
self.isOpaque = false
addSubview(spinner)
sizeToFit()
spinner.hidesWhenStopped = true
spinner.activityIndicatorViewStyle = .gray
}
open override func layoutSubviews() {
super.layoutSubviews()
spinner.center = CGPoint(x: self.bounds.width / 2.0, y: 0.75 * totalHeight)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func sinCGFloat(_ angle:CGFloat)->CGFloat{
let result = sinf(Float(angle))
return CGFloat(result)
}
func cosCGFloat(_ angle:CGFloat)->CGFloat{
let result = cosf(Float(angle))
return CGFloat(result)
}
open override func draw(_ rect: CGRect) {
//如果在Animating,则什么都不做
if animating {
super.draw(rect)
return
}
let context = UIGraphicsGetCurrentContext()
let centerX = rect.width/2.0
let lineWidth = 2.5 - 1.0 * adjustedProgress
//上面圆的信息
let upCenter = CGPoint(x: centerX, y: (0.75 - 0.5 * adjustedProgress) * totalHeight)
let upRadius = radius - radius * 0.3 * adjustedProgress
//下面圆的信息
let downRadius:CGFloat = radius - radius * 0.75 * adjustedProgress
let downCenter = CGPoint(x: centerX, y: totalHeight - downRadius - margin)
//偏移的角度
let offSetAngle:CGFloat = CGFloat(M_PI_2 / 12.0)
//计算上面圆的左/右的交点坐标
let upP1 = CGPoint(x: upCenter.x - upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
let upP2 = CGPoint(x: upCenter.x + upRadius * cosCGFloat(offSetAngle), y: upCenter.y + upRadius * sinCGFloat(offSetAngle))
//计算下面的圆左/右叫点坐标
let downP1 = CGPoint(x: downCenter.x - downRadius * cosCGFloat(offSetAngle), y: downCenter.y - downRadius * sinCGFloat(offSetAngle))
//计算Control Point
let controPonintLeft = CGPoint(x: downCenter.x - downRadius, y: (downCenter.y + upCenter.y)/2)
let controPonintRight = CGPoint(x: downCenter.x + downRadius, y: (downCenter.y + upCenter.y)/2)
//实际绘制
context?.setFillColor(elasticTintColor.cgColor)
context?.addArc(center: upCenter, radius: upRadius, startAngle: CGFloat(-M_PI)-offSetAngle, endAngle: offSetAngle, clockwise: false)
context?.move(to: CGPoint(x: upP1.x, y: upP1.y))
context?.addQuadCurve(to: downP1, control: controPonintLeft)
context?.addArc(center: downCenter, radius: downRadius, startAngle: CGFloat(-M_PI)-offSetAngle, endAngle: offSetAngle, clockwise: true)
context?.addQuadCurve(to: upP2, control: controPonintRight)
context?.fillPath()
//绘制箭头
context?.setStrokeColor(arrowColor.cgColor)
context?.setLineWidth(lineWidth)
context?.addArc(center: upCenter, radius: arrowRadius, startAngle: 0, endAngle: CGFloat(M_PI * 1.5), clockwise: false)
context?.strokePath()
context?.setFillColor(arrowColor.cgColor)
context?.setLineWidth(0.0)
context?.move(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius + lineWidth * 1.5))
context?.addLine(to: CGPoint(x: upCenter.x + lineWidth * 0.865 * 3, y: upCenter.y - arrowRadius))
context?.addLine(to: CGPoint(x: upCenter.x, y: upCenter.y - arrowRadius - lineWidth * 1.5))
context?.fillPath()
}
override open func sizeToFit() {
var width = frame.size.width
if width < 30.0{
width = 30.0
}
self.frame = CGRect(x: frame.origin.x, y: frame.origin.y,width: width, height: totalHeight)
}
}
| apache-2.0 | 9cb3946f156b0b5b51a4fc18b8c7dc6d | 33.822368 | 143 | 0.59966 | 4.227636 | false | false | false | false |
cxpyear/ZSZQApp | spdbapp/spdbapp/Classes/Manage/DownLoadManager.swift | 1 | 20670 | //
// DownLoadFiles.swift
// spdbapp
//
// Created by GBTouchG3 on 15/5/19.
// Copyright (c) 2015年 shgbit. All rights reserved.
//
import UIKit
import Alamofire
//class DownloadFile: NSObject {
// var filename: String = ""
// var filebar: Float = 0
//}
//var downloadlist:[DownloadFile] = []
//var downloadFileList = [FileDownloadInfo]()
class DownloadFile: NSObject {
var filebar: Float = 0
var fileid: String = ""
var fileResumeData: NSData = NSData()
var isdownloading = Bool()
}
var downloadlist:[DownloadFile] = []
var isDownloading = Bool()
class DownLoadManager: NSObject {
// var session = NSURLSession()
// var docDirectoryURL = NSURL()
override init(){
super.init()
downloadJSON()
downloadFile()
// var urls = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
// self.docDirectoryURL = urls.first as! NSURL
// var sessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("com.DownloadDemo")
// //("com.DownloadDemo")
// //[NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.DownloadDemo"];
// sessionConfiguration.HTTPMaximumConnectionsPerHost = 5;
//
// self.session = NSURLSession(configuration: sessionConfiguration, delegate: self, delegateQueue: nil)
//[NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
// initDownloadFileList()
}
func downloadJSON(){
Alamofire.request(.GET, server.meetingServiceUrl).responseJSON(options: NSJSONReadingOptions.MutableContainers, completionHandler: { (request , response , data , error ) -> Void in
if error != nil{
println("get json error = \(error)")
return
}else{
// println("json data = \(jsonFilePath)")
if let dataValue: AnyObject = data{
if let writeData = NSJSONSerialization.dataWithJSONObject(dataValue, options: NSJSONWritingOptions.allZeros, error: nil){
var isSameJsonData = isSameJsonFileExist(writeData, jsonFilePath)
if isSameJsonData == true{
return
}else{
var manager = NSFileManager.defaultManager()
if !manager.fileExistsAtPath(jsonFilePath){
manager.createFileAtPath(jsonFilePath, contents: nil , attributes: nil )
}
dataWriteToFile(writeData, jsonFilePath)
}
}
}
}
})
}
func downloadFile(){
var sources = current.sources
var meetingid = current.id
for var i = 0 ; i < sources.count ; i++ {
var source = GBSource(keyValues: sources[i])
var fileid = source.id
var filename = source.name
var downloadCurrentFile = DownloadFile()
downloadCurrentFile.fileid = fileid
var isfind:Bool = false
if downloadlist.count==0{
downloadlist.append(downloadCurrentFile)
}
else {
for var i = 0; i < downloadlist.count ; ++i {
if fileid == downloadlist[i].fileid {
isfind = true
downloadCurrentFile = downloadlist[i]
break
}
}
if !isfind {
downloadCurrentFile.filebar = 0
downloadlist.append(downloadCurrentFile)
}
}
//判断当前沙盒中是否存在对应的pdf文件,若存在,则直接返回,否则下载该文件。
var b = isSameFileExist(fileid)
if b == true{
println("\(filename)已存在")
downloadCurrentFile.filebar = 1
continue
}
var filepath = server.downloadFileUrl + "gbtouch/meetings/\(meetingid)/\(fileid).pdf"
var getPDFURL = NSURL(string: filepath)
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
var res: Alamofire.Request?
if downloadlist[i].fileResumeData.length > 0 && downloadlist[i].isdownloading == false{
res = Alamofire.download(resumeData: downloadlist[i].fileResumeData, destination)
println("resuming=======================")
}else{
res = Alamofire.download(.GET, getPDFURL!, destination)
println("downloading=======================")
}
res!.progress(closure: { (_ , totalBytesRead, totalBytesExpectedToRead) -> Void in
var processbar: Float = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
for var i = 0 ; i < downloadlist.count ; i++ {
if downloadlist[i].fileid == downloadCurrentFile.fileid{
if processbar > downloadCurrentFile.filebar{
downloadCurrentFile.filebar = processbar
downloadCurrentFile.isdownloading = true
// println("i = \(i) bar = \(processbar)")
if processbar == 1{
println("\(filename)下载完成")
}
}
}
}
}).response({ (_ , _ , _ , error ) -> Void in
for var i = 0 ; i < downloadlist.count ; i++ {
if downloadlist[i].fileid == downloadCurrentFile.fileid{
if error != nil{
if let errInfo = error!.userInfo{
if let resumeInfo: AnyObject = errInfo[NSURLSessionDownloadTaskResumeData]{
if let resumeD = resumeInfo as? NSData{
downloadCurrentFile.fileResumeData = resumeD
downloadCurrentFile.isdownloading = false
}
}
}
isDownloading = false
}else{
isDownloading = true
}
}
}
})
}
}
// func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
// var appdelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// self.session.getTasksWithCompletionHandler { (dataTask , uploadTask , downloadTask) -> Void in
// if downloadTask.count == 0{
// if appdelegate.backgroundTransferCompletionHandler != nil{
// var completionHandler: (() -> Void)? = appdelegate.backgroundTransferCompletionHandler
// appdelegate.backgroundTransferCompletionHandler = nil
//
// }
// }
// }
// }
//
// func initDownloadFileList(){
// var meetingid = current.id
// for var i = 0 ; i < current.sources.count ; i++ {
// var s = GBSource(keyValues: current.sources[i])
// var sid = s.id
//
// var isFileExist = isSamePDFFile(sid)
// if isFileExist == true{
// continue
// }
//
// var fileSource = server.downloadFileUrl + "gbtouch/meetings/\(meetingid)/\(sid).pdf"
// var fdi = FileDownloadInfo(titie: s.name, source: fileSource)
//
// if downloadFileList.count > 0{
// for var k = 0 ; k < downloadFileList.count ; k++ {
// if downloadFileList[k].fileid == sid{
// break
// }else{
// downloadFileList.append(fdi)
// }
// }
// }else{
// downloadFileList.append(fdi)
// }
//
// DownloadFile(fdi)
// }
// }
//
//
// func DownloadFile(fdi: FileDownloadInfo){
// if (fdi.isDownloading == false) {
// if (fdi.taskIdentifier == -1) {
// fdi.downloadTask = self.session.downloadTaskWithURL(NSURL(string: fdi.downloadSource)!)
// }else{
// fdi.downloadTask = self.session.downloadTaskWithResumeData(fdi.taskResumeData)
// }
//
// fdi.isDownloading = true;
// fdi.taskIdentifier = fdi.downloadTask.taskIdentifier;
// fdi.downloadTask.resume()
// }
// }
//
//
// func getFileDownloadInfoIndexWithTaskIdentifier(taskIdentifier: Int) -> Int{
// var index = 0
// for var i = 0 ; i < downloadFileList.count ; i++ {
// if downloadFileList[i].taskIdentifier == taskIdentifier{
// index = i;
// break;
// }
// }
// return index
// }
//
//
//
// func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
// if totalBytesExpectedToWrite == NSURLSessionTransferSizeUnknown{
// NSLog("Unknown transfer size");
// }else{
// NSLog("taskIdentifier = %lu", downloadTask.taskIdentifier)
// var index = self.getFileDownloadInfoIndexWithTaskIdentifier(downloadTask.taskIdentifier)
// var fdi = downloadFileList[index]
//
// fdi.downloadProgress = Float(totalBytesWritten) / Float(totalBytesExpectedToWrite)
// }
// }
//
//
// func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
// var error = NSErrorPointer()
// var fileManager = NSFileManager.defaultManager()
// if let destinationFilename = downloadTask.originalRequest.URL?.lastPathComponent{
// var destinationURL = self.docDirectoryURL.URLByAppendingPathComponent(destinationFilename)
//
// if let path = destinationURL.path{
// if fileManager.fileExistsAtPath(path){
// fileManager.removeItemAtURL(destinationURL, error: nil)
// }
//
// var success = fileManager.copyItemAtURL(location, toURL: destinationURL, error: error)
// var index = getFileDownloadInfoIndexWithTaskIdentifier(downloadTask.taskIdentifier)
// var fdi = downloadFileList[index]
// fdi.isDownloading = false
// fdi.downloadComplete = true
// fdi.taskIdentifier = -1
//
// }else{
// NSLog("unable to copy items ,Error = %@", error)
// }
//
// }
//
// }
}
// dynamic var downloadCurrentFile = DownloadFile()
//判断当前文件夹是否存在jsondata数据,如果不存在,则继续进入下面的步骤
//如果存在该数据,则判断当前json与本地jsonlocal是否一致,如果一致,则打印 json数据信息已经存在,return
// class func isSameJSONData(jsondata: NSData) -> Bool {
//
// var localJSONPath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
// var filemanager = NSFileManager.defaultManager()
//
// if filemanager.fileExistsAtPath(localJSONPath){
// let jsonLocal = filemanager.contentsAtPath(localJSONPath)
//
// if jsonLocal == jsondata {
// //println("json数据信息已经存在")
// return true
// }
// return false
// }
// return false
// }
// class func isStart(bool: Bool){
// if bool == true{
//// downLoadAllFile()
// downLoadJSON()
// }
// }
//-> (currentSeq: Int, totalCount: Int) -> (name: String, downSize: Int, allSize: Int)
// class func downLoadAllFile(){
// Alamofire.request(.GET, server.meetingServiceUrl).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, data, err) -> Void in
// if(err != nil){
// NSLog("download allsourcefile error ==== %@", err!)
// return
// }
//
// let json = JSON(data!)
// var meetingid = json["id"].stringValue
//
//
//
// if let agendasInfo = json["agenda"].array
// {
// //获取所有的议程信息
// for var i = 0 ;i < agendasInfo.count ; i++ {
// var agendas = agendasInfo[i]
//
// if let fileSourceInfo = agendas["source"].array{
// for var j = 0 ; j < fileSourceInfo.count ; j++ {
//
//// var downloadCurrent = DownloadFile()
//
// var fileid = fileSourceInfo[j].stringValue
// var filename = String()
//
// //根据source的id去寻找对应的name
// if let sources = json["source"].array{
// for var k = 0 ; k < sources.count ; k++ {
// if fileid == sources[k]["id"].stringValue{
// filename = sources[k]["name"].stringValue
// }
// }
// }
// var isfind:Bool = false
// var downloadCurrentFile = DownloadFile()
// downloadCurrentFile.filename = filename
// downloadCurrentFile.filebar = 0
// if downloadlist.count==0{
// downloadlist.append(downloadCurrentFile)
// }else {
// for var i = 0; i < downloadlist.count ; ++i {
// if filename == downloadlist[i].filename {
// isfind = true
// }
// }
// if !isfind {
// downloadlist.append(downloadCurrentFile)
// }
// }
//// println("count========\(downloadlist.count)")
// //http://192.168.16.141:10086/gbtouch/meetings/73c000fa-2f5b-44ef-9dff-addba27d8e18/6d1f55b9-9773-4932-a3c1-8fcc88b8ead1.pdf
//
// var filepath = server.downloadFileUrl + "gbtouch/meetings/\(meetingid)/\(fileid).pdf"
// var getPDFURL = NSURL(string: filepath)
//
// let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
// (temporaryURL, response) in
// if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.AllDomainsMask)[0] as? NSURL{
// var filenameURL = directoryURL.URLByAppendingPathComponent("\(filename)")
// return filenameURL
// }
// return temporaryURL
// }
//
//// println("file name = \(filename)")
// //判断../Documents是否存在当前filename为名的文件,如果存在,则返回;如不存在,则下载文件
// var b = self.isSamePDFFile(filename)
// if b == false{
// Alamofire.download(.GET, getPDFURL!, headers: nil, destination: destination).progress {
// (_, totalBytesRead, totalBytesExpectedToRead) in
// dispatch_async(dispatch_get_main_queue()) {
//
// downloadCurrentFile.filename = filename
// var processbar: Float = Float(totalBytesRead)/Float(totalBytesExpectedToRead)
// downloadCurrentFile.filebar = processbar
//// println("filename = \(downloadCurrentFile.filename) filebar = \(downloadCurrentFile.filebar)")
// for var i = 0; i < downloadlist.count ; ++i {
// if filename == downloadlist[i].filename {
// if processbar > downloadlist[i].filebar {
// downloadlist[i].filebar = processbar
// }
// }
// }
//// println("正在下载\(filename),文件下载进度为\(processbar)")
// if totalBytesRead == totalBytesExpectedToRead {
// println("\(filename) 下载成功")
// }
// }
// }
// }else if b == true{
// println("\(filename)文件已存在")
// }
// }
// }
// }
// }
// }
// }
// class func isFileDownload(name: String) -> Bool{
// var filepath = NSHomeDirectory().stringByAppendingPathComponent("Documents/\(name)")
// var manager = NSFileManager.defaultManager()
// if manager.fileExistsAtPath(filepath){
// return true
// }else{
// return false
// }
// }
//下载json数据到本地并保存
// class func downLoadJSON(){
//
// Alamofire.request(.GET, server.meetingServiceUrl).responseJSON(options: NSJSONReadingOptions.MutableContainers) { (_, _, data, err) -> Void in
// var jsonFilePath = NSHomeDirectory().stringByAppendingPathComponent("Documents/jsondata.txt")
//
// //println("\(jsonFilePath)")
//
// if(err != nil){
// println("下载当前json出错,error ===== \(err)")
// return
// }
// var jsondata = NSJSONSerialization.dataWithJSONObject(data!, options: NSJSONWritingOptions.allZeros, error: nil)
//
// //如果当前json和服务器上的json数据不一样,则保存。保存成功提示:当前json保存成功,否则提示:当前json保存失败。
// var bool = self.isSameJSONData(jsondata!)
// if !bool{
// var b = jsondata?.writeToFile(jsonFilePath, atomically: true)
// if (b! == true) {
// NSLog("当前json保存成功")
// }
// else{
// NSLog("当前json保存失败")
// }
//
// }
//
// var manager = NSFileManager.defaultManager()
// if !manager.fileExistsAtPath(jsonFilePath){
// var b = manager.createFileAtPath(jsonFilePath, contents: nil, attributes: nil)
// if b{
// println("创建json成功")
// }
// }
// }
// }
//}
//} | bsd-3-clause | 14f699d4d12eece3a1d66248b6a7a8c4 | 40.167689 | 204 | 0.476155 | 5.136514 | false | false | false | false |
insidegui/WWDC | WWDC/SessionCellView.swift | 1 | 9546 | //
// SessionCellView.swift
// WWDC
//
// Created by Guilherme Rambo on 13/05/18.
// Copyright © 2018 Guilherme Rambo. All rights reserved.
//
import Cocoa
import RxSwift
import RxCocoa
final class SessionCellView: NSView {
private var disposeBag = DisposeBag()
var viewModel: SessionViewModel? {
didSet {
guard viewModel !== oldValue else { return }
thumbnailImageView.image = #imageLiteral(resourceName: "noimage")
bindUI()
}
}
private weak var imageDownloadOperation: Operation?
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
buildUI()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
imageDownloadOperation?.cancel()
downloadedImageView.isHidden = true
favoritedImageView.isHidden = true
}
private func bindUI() {
disposeBag = DisposeBag()
guard let viewModel = viewModel else { return }
viewModel.rxTitle.distinctUntilChanged().asDriver(onErrorJustReturn: "").drive(titleLabel.rx.text).disposed(by: disposeBag)
viewModel.rxSubtitle.distinctUntilChanged().asDriver(onErrorJustReturn: "").drive(subtitleLabel.rx.text).disposed(by: disposeBag)
viewModel.rxContext.distinctUntilChanged().asDriver(onErrorJustReturn: "").drive(contextLabel.rx.text).disposed(by: disposeBag)
viewModel.rxIsFavorite.distinctUntilChanged().map({ !$0 }).bind(to: favoritedImageView.rx.isHidden).disposed(by: disposeBag)
viewModel.rxIsDownloaded.distinctUntilChanged().map({ !$0 }).bind(to: downloadedImageView.rx.isHidden).disposed(by: disposeBag)
let isSnowFlake = Observable.zip(viewModel.rxIsCurrentlyLive, viewModel.rxIsLab)
isSnowFlake.map({ !$0.0 && !$0.1 }).bind(to: snowFlakeView.rx.isHidden).disposed(by: disposeBag)
isSnowFlake.map({ $0.0 || $0.1 }).bind(to: thumbnailImageView.rx.isHidden).disposed(by: disposeBag)
isSnowFlake.subscribe(onNext: { [weak self] (isLive: Bool, isLab: Bool) -> Void in
if isLive {
self?.snowFlakeView.image = #imageLiteral(resourceName: "live-indicator")
} else if isLab {
self?.snowFlakeView.image = #imageLiteral(resourceName: "lab-indicator")
}
}).disposed(by: disposeBag)
viewModel.rxImageUrl.distinctUntilChanged({ $0 != $1 }).subscribe(onNext: { [weak self] imageUrl in
guard let imageUrl = imageUrl else { return }
self?.imageDownloadOperation?.cancel()
self?.imageDownloadOperation = ImageDownloadCenter.shared.downloadImage(from: imageUrl, thumbnailHeight: Constants.thumbnailHeight, thumbnailOnly: true) { [weak self] url, result in
guard url == imageUrl, result.thumbnail != nil else { return }
self?.thumbnailImageView.image = result.thumbnail
}
}).disposed(by: disposeBag)
viewModel.rxColor.distinctUntilChanged({ $0 == $1 }).subscribe(onNext: { [weak self] color in
self?.contextColorView.color = color
}).disposed(by: disposeBag)
viewModel.rxDarkColor.distinctUntilChanged({ $0 == $1 }).subscribe(onNext: { [weak self] color in
self?.snowFlakeView.backgroundColor = color
}).disposed(by: disposeBag)
viewModel.rxProgresses.subscribe(onNext: { [weak self] progresses in
if let progress = progresses.first {
self?.contextColorView.hasValidProgress = true
self?.contextColorView.progress = progress.relativePosition
} else {
self?.contextColorView.hasValidProgress = false
self?.contextColorView.progress = 0
}
}).disposed(by: disposeBag)
viewModel.rxSessionType.distinctUntilChanged().subscribe(onNext: { [weak self] type in
guard ![.lab, .session, .labByAppointment].contains(type) else { return }
switch type {
case .getTogether:
self?.thumbnailImageView.image = #imageLiteral(resourceName: "get-together")
default:
self?.thumbnailImageView.image = #imageLiteral(resourceName: "special")
}
}).disposed(by: disposeBag)
}
private lazy var titleLabel: NSTextField = {
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 14, weight: .medium)
l.textColor = .primaryText
l.cell?.backgroundStyle = .dark
l.lineBreakMode = .byTruncatingTail
return l
}()
private lazy var subtitleLabel: NSTextField = {
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 12)
l.textColor = .secondaryText
l.cell?.backgroundStyle = .dark
l.lineBreakMode = .byTruncatingTail
return l
}()
private lazy var contextLabel: NSTextField = {
let l = NSTextField(labelWithString: "")
l.font = .systemFont(ofSize: 12)
l.textColor = .tertiaryText
l.cell?.backgroundStyle = .dark
l.lineBreakMode = .byTruncatingTail
return l
}()
private lazy var thumbnailImageView: WWDCImageView = {
let v = WWDCImageView()
v.heightAnchor.constraint(equalToConstant: 48).isActive = true
v.widthAnchor.constraint(equalToConstant: 85).isActive = true
v.backgroundColor = .black
return v
}()
private lazy var snowFlakeView: WWDCImageView = {
let v = WWDCImageView()
v.heightAnchor.constraint(equalToConstant: 48).isActive = true
v.widthAnchor.constraint(equalToConstant: 85).isActive = true
v.isHidden = true
v.image = #imageLiteral(resourceName: "lab-indicator")
return v
}()
private lazy var contextColorView: TrackColorView = {
let v = TrackColorView()
v.widthAnchor.constraint(equalToConstant: 4).isActive = true
return v
}()
private lazy var textStackView: NSStackView = {
let v = NSStackView(views: [self.titleLabel, self.subtitleLabel, self.contextLabel])
v.orientation = .vertical
v.alignment = .leading
v.distribution = .equalSpacing
v.spacing = 0
return v
}()
private lazy var favoritedImageView: WWDCImageView = {
let v = WWDCImageView()
v.heightAnchor.constraint(equalToConstant: 14).isActive = true
v.drawsBackground = false
v.image = #imageLiteral(resourceName: "star-small")
return v
}()
private lazy var downloadedImageView: WWDCImageView = {
let v = WWDCImageView()
v.heightAnchor.constraint(equalToConstant: 11).isActive = true
v.drawsBackground = false
v.image = #imageLiteral(resourceName: "download-small")
return v
}()
private lazy var iconsStackView: NSStackView = {
let v = NSStackView(views: [])
v.distribution = .gravityAreas
v.orientation = .vertical
v.spacing = 4
v.addView(self.favoritedImageView, in: .top)
v.addView(self.downloadedImageView, in: .bottom)
v.translatesAutoresizingMaskIntoConstraints = false
v.widthAnchor.constraint(equalToConstant: 12).isActive = true
return v
}()
private func buildUI() {
wantsLayer = true
contextColorView.translatesAutoresizingMaskIntoConstraints = false
thumbnailImageView.translatesAutoresizingMaskIntoConstraints = false
snowFlakeView.translatesAutoresizingMaskIntoConstraints = false
textStackView.translatesAutoresizingMaskIntoConstraints = false
iconsStackView.translatesAutoresizingMaskIntoConstraints = false
addSubview(contextColorView)
addSubview(thumbnailImageView)
addSubview(snowFlakeView)
addSubview(textStackView)
addSubview(iconsStackView)
contextColorView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10).isActive = true
contextColorView.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
contextColorView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true
thumbnailImageView.centerYAnchor.constraint(equalTo: contextColorView.centerYAnchor).isActive = true
thumbnailImageView.leadingAnchor.constraint(equalTo: contextColorView.trailingAnchor, constant: 8).isActive = true
snowFlakeView.centerYAnchor.constraint(equalTo: thumbnailImageView.centerYAnchor).isActive = true
snowFlakeView.centerXAnchor.constraint(equalTo: thumbnailImageView.centerXAnchor).isActive = true
textStackView.centerYAnchor.constraint(equalTo: thumbnailImageView.centerYAnchor, constant: -1).isActive = true
textStackView.leadingAnchor.constraint(equalTo: thumbnailImageView.trailingAnchor, constant: 8).isActive = true
textStackView.trailingAnchor.constraint(equalTo: iconsStackView.leadingAnchor, constant: -2).isActive = true
iconsStackView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4).isActive = true
iconsStackView.topAnchor.constraint(equalTo: textStackView.topAnchor).isActive = true
iconsStackView.bottomAnchor.constraint(equalTo: textStackView.bottomAnchor).isActive = true
downloadedImageView.isHidden = true
favoritedImageView.isHidden = true
}
}
| bsd-2-clause | 22b3688e8ab616c552f01e31352a18b5 | 36.431373 | 193 | 0.669251 | 4.989545 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.