repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
butterproject/butter-ios | Butter/API/Providers/TVAPI.swift | 1 | 8166 | //
// TVAPI.swift
// Butter
//
// Created by DjinnGA on 24/07/2015.
// Copyright (c) 2015 Butter Project. All rights reserved.
//
import Foundation
import SwiftyJSON
class TVAPI {
static let sharedInstance = TVAPI()
let APIManager: ButterAPIManager = ButterAPIManager.sharedInstance
static let genres = [
"All",
"Action",
"Adventure",
"Animation",
"Children",
"Comedy",
"Crime",
"Documentary",
"Drama",
"Family",
"Fantasy",
"Game Show",
"Home and Garden",
"Horror",
"Mini Series",
"Mystery",
"News",
"Reality",
"Romance",
"Science Fiction",
"Soap",
"Special Interest",
"Sport",
"Suspense",
"Talk Show",
"Thriller",
"Western"
]
func load(page: Int, onCompletion: (newItems : Bool) -> Void) {
//Build the query
let urlParams = [
"sort" : "seeds",
"limit" : "\(APIManager.amountToLoad)",
"genre" : APIManager.genres[0],
"order" : "-1",
"keywords" : APIManager.searchString,
]
//Request the data from the API
RestApiManager.sharedInstance.getJSONFromURL("\(APIManager.TVShowsAPIEndpoint)\(page)", parameters: urlParams) { json in
let shows = json
for (_, show) in shows {
if !self.APIManager.isSearching {
if let _ = self.APIManager.cachedTVShows[show["imdb_id"].string!] { //Check it hasn't already been loaded
continue
}
}
if let iteID = show["tvdb_id"].string {
self.createShowFromJson(iteID, show)
}
}
onCompletion(newItems: shows.count > 0)
}
}
func getShow(id: String, onCompletion: (loadedFromCache : Bool) -> Void) {
let URL = NSURL(string: "http://eztvapi.re/show/\(id)")
let mutableURLRequest = NSMutableURLRequest(URL: URL!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 as NSTimeInterval!)
mutableURLRequest.HTTPMethod = "GET"
if let _ = self.APIManager.cachedTVShows[id] {
onCompletion(loadedFromCache: true)
} else {
RestApiManager.sharedInstance.getJSONFromURL(mutableURLRequest) { json in
self.createShowFromJson(json["tvdb_id"].string!, json)
onCompletion(loadedFromCache: false)
}
}
}
func createShowFromJson(tvdb_id : String, _ json : JSON) -> ButterItem {
let ite: ButterItem = ButterItem(id: Int(tvdb_id)!, torrents: JSON(""))
ite.setProperty("title", val: json["title"].string!)
ite.setProperty("imdb", val: json["imdb_id"].string!)
ite.setProperty("year", val: json["year"].string!)
ite.setProperty("seasons", val: json["num_seasons"].int!)
if (self.APIManager.isSearching) {
self.APIManager.searchResults[json["imdb_id"].string!] = ite
} else {
self.APIManager.cachedTVShows[json["imdb_id"].string!] = ite
}
ite.setProperty("coverURL", val: json["images","poster"].string!.stringByReplacingOccurrencesOfString("original", withString: "thumb", options: .LiteralSearch, range: nil))
RestApiManager.sharedInstance.loadImage(ite.getProperty("coverURL") as! String, onCompletion: { image in
ite.setProperty("cover", val: image)
})
ite.setProperty("fanartURL", val: json["images","fanart"].string!)
return ite
}
func requestShowInfo(imdb: String, onCompletion: () -> Void) {
let imdbURL = "http://eztvapi.re/show/\(imdb)"
let url = NSURL(string:imdbURL)
print(url)
let mutableURLRequest = NSMutableURLRequest(URL: url!)
mutableURLRequest.HTTPMethod = "GET"
let ite: ButterItem?
if (self.APIManager.isSearching) {
ite = ButterAPIManager.sharedInstance.searchResults[imdb]!
} else {
ite = ButterAPIManager.sharedInstance.cachedTVShows[imdb]!
}
// Download fanart
if ite!.hasProperty("fanartURL") {
RestApiManager.sharedInstance.loadImage(ite!.getProperty("fanartURL") as! String, onCompletion: { image in
ite!.setProperty("fanart", val: image)
onCompletion()
})
}
// Load show info
RestApiManager.sharedInstance.getJSONFromURL(mutableURLRequest) { json in
if let episodes: JSON? = json["episodes"] {
var showSeasons : [Int:[ButterItem]] = [Int:[ButterItem]]()
for (_, episode) in episodes! {
var episodeTorrents: [ButterTorrent] = [ButterTorrent]()
for (name, torr) in episode["torrents"] {
if (name == "0") {
} else {
let quTor: ButterTorrent = ButterTorrent(url: torr["url"].string!, seeds: torr["seeds"].int!, peers: torr["peers"].int!, quality: name, size: "", hash: "")
episodeTorrents.append(quTor)
}
}
let ep = ButterItem(id: episode["tvdb_id"].int!, torrents: episodeTorrents)
ep.setProperty("season", val: episode["season"].int!)
ep.setProperty("episode", val: episode["episode"].int!)
if let desc = episode["overview"].string {
ep.setProperty("description", val: desc)
} else {
let desc = "Synopsis Not Available"
ep.setProperty("description", val: desc)
}
if let title = episode["title"].string {
ep.setProperty("title", val: title)
} else {
let episode = episode["episode"].int!
ep.setProperty("title", val: "Episode \(episode)")
// TODO: Uncomment when Xcode 7.1 is released: http://stackoverflow.com/questions/24024754/escape-dictionary-key-double-quotes-when-doing-println-dictionary-item-in-swift
//ep.setProperty("title", val: "Episode \(episode["episode"].int!)")
}
ep.setProperty("first_aired", val: episode["first_aired"].int!)
if let _ = showSeasons[episode["season"].int!] {
var seasonEpisodes = showSeasons[episode["season"].int!]
seasonEpisodes!.append(ep)
showSeasons[episode["season"].int!] = seasonEpisodes
} else {
showSeasons[episode["season"].int!] = [ep]
}
}
ite!.setProperty("seasons", val: showSeasons)
}
if let rating = json["rating","percentage"].int {
let ratingFloat = Float(rating)
ite!.setProperty("rating", val: (ratingFloat/100)*5)
}
if json["network"].string != nil {
ite!.setProperty("network", val: json["network"].string!)
}
if json["air_day"].string != nil {
ite!.setProperty("air_day", val: json["air_day"].string!)
}
if json["air_time"].string != nil {
ite!.setProperty("air_time", val: json["air_time"].string!)
}
if let runtime = json["runtime"].string {
ite!.setProperty("runtime", val: Int(runtime)!)
}
if json["status"].string != nil {
ite!.setProperty("status", val: json["status"].string!)
}
if json["synopsis"].string != nil {
ite!.setProperty("description", val: json["synopsis"].string!)
}
var genres: String = ""
for (index, subJson) in json["genres"] {
if (index != "0") {
genres += ", \(subJson.string!)"
} else {
genres += subJson.string!
}
}
ite!.setProperty("genres", val: genres)
onCompletion()
}
}
} | gpl-3.0 | 1ca3d55b5d7cfb758a39c64da31431f7 | 34.977974 | 183 | 0.538697 | 4.329799 | false | false | false | false |
tokyovigilante/CesiumKit | CesiumKit/Core/Plane.swift | 1 | 4280 | //
// Plane.swift
// CesiumKit
//
// Created by Ryan Walklin on 4/10/2015.
// Copyright © 2015 Test Toast. All rights reserved.
//
import Foundation
/**
* A plane in Hessian Normal Form defined by
* <pre>
* ax + by + cz + d = 0
* </pre>
* where (a, b, c) is the plane's <code>normal</code>, d is the signed
* <code>distance</code> to the plane, and (x, y, z) is any point on
* the plane.
*
* @alias Plane
* @constructor
*
* @param {Cartesian3} normal The plane's normal (normalized).
* @param {Number} distance The shortest distance from the origin to the plane. The sign of
* <code>distance</code> determines which side of the plane the origin
* is on. If <code>distance</code> is positive, the origin is in the half-space
* in the direction of the normal; if negative, the origin is in the half-space
* opposite to the normal; if zero, the plane passes through the origin.
*
* @example
* // The plane x=0
* var plane = new Cesium.Plane(Cesium.Cartesian3.UNIT_X, 0.0);
*/
struct Plane {
/**
* The plane's normal.
*
* @type {Cartesian3}
*/
let normal: Cartesian3
/**
* The shortest distance from the origin to the plane. The sign of
* <code>distance</code> determines which side of the plane the origin
* is on. If <code>distance</code> is positive, the origin is in the half-space
* in the direction of the normal; if negative, the origin is in the half-space
* opposite to the normal; if zero, the plane passes through the origin.
*
* @type {Number}
*/
let distance: Double
init(normal: Cartesian3, distance: Double) {
self.normal = normal
self.distance = distance
}
/**
* Creates a plane from a normal and a point on the plane.
*
* @param {Cartesian3} point The point on the plane.
* @param {Cartesian3} normal The plane's normal (normalized).
* @param {Plane} [result] The object onto which to store the result.
* @returns {Plane} A new plane instance or the modified result parameter.
*
* @example
* var point = Cesium.Cartesian3.fromDegrees(-72.0, 40.0);
* var normal = ellipsoid.geodeticSurfaceNormal(point);
* var tangentPlane = Cesium.Plane.fromPointNormal(point, normal);
*/
init (fromPoint point: Cartesian3, normal: Cartesian3) {
let distance = -normal.dot(point)
self = Plane(normal: normal, distance: distance)
}
/**
* Creates a plane from the general equation
*
* @param {Cartesian4} coefficients The plane's normal (normalized).
* @param {Plane} [result] The object onto which to store the result.
* @returns {Plane} A new plane instance or the modified result parameter.
*/
init (fromCartesian4 coefficients: Cartesian4) {
normal = Cartesian3(cartesian4: coefficients)
distance = coefficients.w
}
/**
* Computes the signed shortest distance of a point to a plane.
* The sign of the distance determines which side of the plane the point
* is on. If the distance is positive, the point is in the half-space
* in the direction of the normal; if negative, the point is in the half-space
* opposite to the normal; if zero, the plane passes through the point.
*
* @param {Plane} plane The plane.
* @param {Cartesian3} point The point.
* @returns {Number} The signed shortest distance of the point to the plane.
*/
func getPointDistance (_ point: Cartesian3) -> Double {
return normal.dot(point) + distance
}
/*
/**
* A constant initialized to the XY plane passing through the origin, with normal in positive Z.
*
* @type {Plane}
* @constant
*/
Plane.ORIGIN_XY_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Z, 0.0));
/**
* A constant initialized to the YZ plane passing through the origin, with normal in positive X.
*
* @type {Plane}
* @constant
*/
Plane.ORIGIN_YZ_PLANE = freezeObject(new Plane(Cartesian3.UNIT_X, 0.0));
/**
* A constant initialized to the ZX plane passing through the origin, with normal in positive Y.
*
* @type {Plane}
* @constant
*/
Plane.ORIGIN_ZX_PLANE = freezeObject(new Plane(Cartesian3.UNIT_Y, 0.0));*/
}
| apache-2.0 | 37239e82df8deafcbbed486dcb922df4 | 31.664122 | 99 | 0.648516 | 3.80694 | false | false | false | false |
rudkx/swift | test/decl/protocol/req/associated_type_inference_fixed_type.swift | 1 | 20438 | // RUN: %target-typecheck-verify-swift
protocol P1 where A == Never {
associatedtype A
}
struct S1: P1 {}
protocol P2a {
associatedtype A
}
protocol P2b: P2a where A == Never {}
protocol P2c: P2b {}
struct S2a: P2b {}
struct S2b: P2c {}
// Fixed type witnesses can reference dependent members.
protocol P3a {
associatedtype A
associatedtype B
}
protocol P3b: P3a where A == [B] {}
struct S3: P3b {
typealias B = Never
}
protocol P4a where A == [B] {
associatedtype A
associatedtype B
}
protocol P4b {}
extension P4b {
typealias B = Self
}
struct S4: P4a, P4b {}
// Self is a valid fixed type witness.
protocol P5a {
associatedtype A
}
protocol P5b: P5a where A == Self {}
struct S5<X>: P5b {} // OK, A := S5<X>
protocol P6 where A == Never { // expected-error {{same-type constraint type 'Never' does not conform to required protocol 'P6'}}
// expected-error@+2 {{same-type constraint type 'Never' does not conform to required protocol 'P6'}}
// expected-note@+1 {{protocol requires nested type 'A}}
associatedtype A: P6
}
struct S6: P6 {} // expected-error {{type 'S6' does not conform to protocol 'P6'}}
protocol P7a where A == Never {
associatedtype A
}
// expected-error@+2 {{'Self.A' cannot be equal to both 'Bool' and 'Never'}}
// expected-note@+1 {{same-type constraint 'Self.A' == 'Never' implied here}}
protocol P7b: P7a where A == Bool {}
struct S7: P7b {}
protocol P8a where A == Never {
associatedtype A
}
protocol P8b where A == Bool {
associatedtype A
}
do {
struct Conformer: P8a, P8b {}
// expected-error@-1 {{'P8b' requires the types 'Conformer.A' (aka 'Never') and 'Bool' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer]}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P8b'}}
}
protocol P9a where A == Never {
associatedtype A
}
protocol P9b: P9a {
associatedtype A
}
struct S9a: P9b {}
// expected-error@+3 {{type 'S9b' does not conform to protocol 'P9a'}}
// expected-error@+2 {{'P9a' requires the types 'S9b.A' (aka 'Bool') and 'Never' be equivalent}}
// expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S9b]}}
struct S9b: P9b {
typealias A = Bool
}
struct S9c: P9b { // OK, S9c.A does not contradict Self.A == Never.
typealias Sugar = Never
typealias A = Sugar
}
protocol P10a where A == Never {
associatedtype A
}
protocol P10b {}
extension P10b {
typealias A = Bool
}
// FIXME: 'P10 extension.A' should not be considered a viable type witness;
// instead, the compiler should infer A := Never and synthesize S10.A.
// expected-error@+3 {{type 'S10' does not conform to protocol 'P10a'}}
// expected-error@+2 {{'P10a' requires the types 'S10.A' (aka 'Bool') and 'Never' be equivalent}}
// expected-note@+1 {{requirement specified as 'Self.A' == 'Never' [with Self = S10]}}
struct S10: P10b, P10a {}
protocol P11a {
associatedtype A
}
protocol P11b: P11a where A == Never {}
protocol Q11 {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
}
do {
struct Conformer: Q11, P11b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P11b'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P11a'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'Q11'}}
}
protocol P12 where A == B {
associatedtype A
associatedtype B
func foo(arg: A)
}
struct S12: P12 {
func foo(arg: Never) {}
}
protocol P13a {
associatedtype A
func foo(arg: A)
}
protocol P13b {
associatedtype B
}
protocol P13c: P13a, P13b where A == B {}
struct S13: P13c {
func foo(arg: Never) {}
}
protocol P14 {
associatedtype A = Array<Self>
}
do {
struct Outer<Element> {
struct Conformer: P14 {}
}
}
protocol P15a {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = Never // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P15b: P15a where A == B {}
do {
struct Conformer: P15b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P15a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P15b'}}
}
protocol P16a where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = Never // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P16b: P16a {}
do {
struct Conformer: P16b {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P16a'}}
}
protocol P17a where A == Never {
associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P17b {
associatedtype A = B // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol P17c where A == Never {
associatedtype A
associatedtype B = A
}
protocol P17d {
associatedtype A = B
associatedtype B = Int
}
do {
struct Conformer1: P17a {} // expected-error {{type 'Conformer1' does not conform to protocol 'P17a'}}
struct Conformer2<A>: P17b {} // expected-error {{type 'Conformer2<A>' does not conform to protocol 'P17b'}}
struct Conformer3: P17c {}
struct Conformer4<A>: P17d {}
}
protocol P18 {
associatedtype A = B
associatedtype B = C
associatedtype C = (D) -> D
associatedtype D
}
do {
struct Conformer<D>: P18 {}
}
protocol P19 where Self == A {
associatedtype A
associatedtype B = (A, A)
}
do {
struct Conformer: P19 {}
}
protocol P20 where A == B.Element, B == B.SubSequence, C.Element == B.Element {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: Collection
associatedtype C: Collection = Array<Character> // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer: P20 { // expected-error {{type 'Conformer' does not conform to protocol 'P20'}}
typealias B = Substring
}
}
protocol P21 where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = C // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer<C>: P21 {} // expected-error {{type 'Conformer<C>' does not conform to protocol 'P21'}}
}
protocol P22 where A == B, C == D {
associatedtype A
associatedtype B
associatedtype C = B
associatedtype D
}
do {
struct Conformer<A>: P22 {}
}
protocol P23 {
associatedtype A: P23 = B.A // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P23 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P23 {} // expected-error {{type 'Conformer' does not conform to protocol 'P23'}}
struct ConformerGeneric<T>: P23 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P23'}}
}
protocol P24 where A == B.A {
associatedtype A: P24 // expected-note 2 {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P24 = A.B // expected-note 2 {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P24 {} // expected-error {{type 'Conformer' does not conform to protocol 'P24'}}
struct ConformerGeneric<T>: P24 {} // expected-error {{type 'ConformerGeneric<T>' does not conform to protocol 'P24'}}
}
protocol P25a_1 where A == Int, B == C.Element {
associatedtype A
associatedtype B
associatedtype C: Sequence
}
protocol P25a_2 where A == C.Element, B == Int {
associatedtype A
associatedtype B
associatedtype C: Sequence
}
protocol P25b where A == B {
associatedtype A
associatedtype B
}
protocol P25c_1: P25a_1, P25b {}
protocol P25c_2: P25a_2, P25b {}
do {
struct Conformer1<C: Sequence>: P25c_1 where C.Element == Int {}
struct Conformer2<C: Sequence>: P25c_2 where C.Element == Int {}
}
protocol P26 where C == B, F == G {
associatedtype A = Int // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B = A // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
associatedtype D // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
associatedtype E = D // expected-note {{protocol requires nested type 'E'; do you want to add it?}}
associatedtype F // expected-note {{protocol requires nested type 'F'; do you want to add it?}}
associatedtype G = [B] // expected-note {{protocol requires nested type 'G'; do you want to add it?}}
}
do {
struct Conformer<D>: P26 {} // expected-error {{type 'Conformer<D>' does not conform to protocol 'P26'}}
}
protocol P27a where A == Int {
associatedtype A
}
protocol P27b where A == B.Element {
associatedtype A
associatedtype B: Sequence
}
protocol P27c_1: P27a, P27b {}
protocol P27c_2: P27b, P27a {}
do {
struct Conformer1<B: Sequence>: P27c_1 where B.Element == Int {}
struct Conformer2<B: Sequence>: P27c_2 where B.Element == Int {}
}
protocol P28a where A == Int {
associatedtype A
}
protocol P28b where A == Bool {
associatedtype A
}
protocol P28c where A == Never {
associatedtype A
}
protocol Q28a: P28a, P28b {}
// expected-error@-1 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}}
// expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}}
protocol Q28b: P28a, P28b, P28c {}
// expected-error@-1 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}}
// expected-error@-2 {{'Self.A' cannot be equal to both 'Never' and 'Int'}}
// expected-note@-3 {{same-type constraint 'Self.A' == 'Int' implied here}}
// expected-note@-4 {{same-type constraint 'Self.A' == 'Int' implied here}}
do {
struct Conformer1: Q28a {}
// expected-error@-1 {{'P28b' requires the types 'Conformer1.A' (aka 'Int') and 'Bool' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer1]}}
// expected-error@-3 {{type 'Conformer1' does not conform to protocol 'P28b'}}
struct Conformer2: Q28b {}
// expected-error@-1 {{'P28c' requires the types 'Conformer2.A' (aka 'Int') and 'Never' be equivalent}}
// expected-error@-2 {{'P28b' requires the types 'Conformer2.A' (aka 'Int') and 'Bool' be equivalent}}
// expected-note@-3 {{requirement specified as 'Self.A' == 'Never' [with Self = Conformer2]}}
// expected-note@-4 {{requirement specified as 'Self.A' == 'Bool' [with Self = Conformer2]}}
// expected-error@-5 {{type 'Conformer2' does not conform to protocol 'P28b'}}
// expected-error@-6 {{type 'Conformer2' does not conform to protocol 'P28c'}}
}
protocol P29a where A == Int {
associatedtype A
associatedtype B
}
protocol P29b where B == Never {
associatedtype B
}
protocol P29c where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q29a: P29a, P29b, P29c {}
// expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}}
// expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}}
protocol Q29b: P29c, P29a, P29b {}
// expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}}
// expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}}
do {
struct Conformer1: Q29a {}
// expected-error@-1 {{'P29b' requires the types 'Conformer1.B' (aka 'Int') and 'Never' be equivalent}}
// expected-note@-2 {{requirement specified as 'Self.B' == 'Never' [with Self = Conformer1]}}
// expected-error@-3 {{type 'Conformer1' does not conform to protocol 'P29b'}}
struct Conformer2: Q29b {}
// expected-error@-1 {{type 'Conformer2' does not conform to protocol 'P29a'}}
// expected-error@-2 {{type 'Conformer2' does not conform to protocol 'P29b'}}
// expected-error@-3 {{type 'Conformer2' does not conform to protocol 'P29c'}}
}
protocol P30a where A == Int {
associatedtype A
}
protocol P30b where A == Never {
associatedtype A
}
protocol P30c where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q30: P30c, P30a, P30b {}
// expected-error@-1 {{'Self.A' cannot be equal to both 'Never' and 'Int'}}
// expected-note@-2 {{same-type constraint 'Self.A' == 'Int' implied here}}
do {
struct Conformer: Q30 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P30a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P30b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P30c'}}
}
protocol P31a where B == Int {
associatedtype B
}
protocol P31b where B == Never {
associatedtype B
}
protocol P31c where B == A {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q31: P31c, P31a, P31b {}
// expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}}
// expected-note@-2 {{same-type constraint 'Self.B' == 'Int' implied here}}
do {
struct Conformer: Q31 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P31a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P31b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P31c'}}
}
protocol P32a where A == Int {
associatedtype A
}
protocol P32b where A == Bool {
associatedtype A
}
protocol P32c where B == Void {
associatedtype B
}
protocol P32d where B == Never {
associatedtype B
}
protocol P32e where A == B {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
protocol Q32: P32e, P32a, P32b, P32c, P32d {}
// expected-error@-1 {{'Self.B' cannot be equal to both 'Never' and 'Int'}}
// expected-error@-2 {{'Self.B' cannot be equal to both '()' and 'Int'}}
// expected-error@-3 {{'Self.A' cannot be equal to both 'Bool' and 'Int'}}
// expected-note@-4 3 {{same-type constraint 'Self.A' == 'Int' implied here}}
do {
struct Conformer: Q32 {}
// expected-error@-1 {{type 'Conformer' does not conform to protocol 'P32a'}}
// expected-error@-2 {{type 'Conformer' does not conform to protocol 'P32b'}}
// expected-error@-3 {{type 'Conformer' does not conform to protocol 'P32c'}}
// expected-error@-4 {{type 'Conformer' does not conform to protocol 'P32d'}}
// expected-error@-5 {{type 'Conformer' does not conform to protocol 'P32e'}}
}
protocol P33a where A == Int {
associatedtype A
}
protocol P33b where A == Int {
associatedtype A
}
protocol Q33: P33a, P33b {}
do {
struct Conformer: Q33 {}
}
protocol P34a {
associatedtype A = Void
}
protocol P34b {
associatedtype A = Never
}
protocol Q34a: P34a, P34b {}
protocol Q34b: P34b, P34a {}
protocol Q34c: P34a, P34b {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
}
do {
struct Conformer1: Q34a {}
struct Conformer2: Q34b {}
struct Conformer3: Q34c {} // expected-error {{type 'Conformer3' does not conform to protocol 'Q34c'}}
}
protocol P35 {
associatedtype A
associatedtype B = Array<C>
associatedtype C = Array<D>
associatedtype D = Array<A>
}
do {
struct Conformer: P35 {
typealias A = Never
}
struct ConformerGeneric<A>: P35 {}
}
struct G36<S: P36> {}
protocol P36 {
// FIXME: Don't create and expose malformed types like 'G36<Never>' -- check
// non-dependent type witnesses first.
// expected-note@+1 {{default type 'G36<Never>' for associated type 'A' (from protocol 'P36') does not conform to 'P36'}}
associatedtype A: P36 = G36<B>
associatedtype B: P36 = Never
}
do {
struct Conformer: P36 {} // expected-error {{type 'Conformer' does not conform to protocol 'P36'}}
}
protocol P37a {
associatedtype A
}
protocol P37b {
associatedtype B : P37a
associatedtype C where C == B.A // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer1<C>: P37b {
struct Inner: P37a { typealias A = C }
typealias B = Inner
}
struct Conformer2<T>: P37b { // expected-error {{type 'Conformer2<T>' does not conform to protocol 'P37b'}}
struct Inner: P37a { typealias A = T }
typealias B = Inner
}
}
protocol P38a {
associatedtype A
}
protocol P38b {
associatedtype B
}
protocol P38c: P38a, P38b where A == B {}
do {
struct Conformer<T>: P38c {
typealias A = Self
}
}
protocol P39 {
associatedtype A: P39
associatedtype B = A.C
associatedtype C = Never
}
do {
struct Conformer: P39 {
typealias A = Self
}
}
protocol P40a {
associatedtype A
associatedtype B = (A, A)
}
protocol P40b: P40a {
override associatedtype A = Int
}
protocol P40c: P40b {
override associatedtype A
override associatedtype B
}
do {
struct Conformer: P40c {}
}
protocol P41 {
associatedtype A where A == B.A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P41 = Self // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
}
do {
struct Conformer: P41 {} // expected-error{{type 'Conformer' does not conform to protocol 'P41'}}
}
protocol P42a {
associatedtype B: P42b
}
protocol P42b: P42a {
associatedtype A = B.A
}
do {
struct Conformer<B: P42b>: P42b {}
}
protocol P43a {
associatedtype A: P43a
associatedtype B
}
protocol P43b: P43a {
associatedtype C where C == A.B // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer<B: P43a>: P43b { // expected-error {{type 'Conformer<B>' does not conform to protocol 'P43b'}}
typealias A = Conformer<B.A>
}
}
protocol P44 {
associatedtype A: P44
associatedtype B // expected-note 2{{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == A.B // expected-note 3{{protocol requires nested type 'C'; do you want to add it?}}
}
do {
struct Conformer1<T: P44>: P44 { // expected-error {{type 'Conformer1<T>' does not conform to protocol 'P44'}}
typealias B = T.A
typealias A = Conformer1<T.A>
}
struct Conformer2<B: P44>: P44 { // expected-error {{type 'Conformer2<B>' does not conform to protocol 'P44'}}
typealias A = Conformer2<B.A>
}
struct Conformer3<B>: P44 { // expected-error {{type 'Conformer3<B>' does not conform to protocol 'P44'}}
typealias A = Conformer3<Int>
}
}
protocol P45 {
associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}}
associatedtype B: P45 = Conformer45<D> // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == B.A // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
associatedtype D = Never // expected-note {{protocol requires nested type 'D'; do you want to add it?}}
}
struct Conformer45<A>: P45 {} // expected-error {{type 'Conformer45<A>' does not conform to protocol 'P45'}}
protocol P46 {
associatedtype A: P46
associatedtype B // expected-note {{protocol requires nested type 'B'; do you want to add it?}}
associatedtype C where C == A.B // expected-note {{protocol requires nested type 'C'; do you want to add it?}}
func method(_: B)
}
do {
struct Conformer<T: P46>: P46 { // expected-error {{type 'Conformer<T>' does not conform to protocol 'P46'}}
typealias A = Conformer<T.A>
func method(_: T) {}
}
}
protocol P47 {
associatedtype A
}
do {
struct Outer<A> {
struct Inner: P47 {}
}
}
protocol P48a { associatedtype A = Int }
protocol P48b { associatedtype B }
protocol P48c: P48a, P48b where A == B {}
do {
struct Conformer: P48c {}
}
| apache-2.0 | eae526f3c43f72919906f233c010ba30 | 30.834891 | 129 | 0.677023 | 3.369827 | false | false | false | false |
jjude/swift-exercises | 009-count-upper-lower-letters.swift | 1 | 1176 | /* Write a program to count upper and lower case letters in a given string.
Logic:
- Swift doesn't have any string functions to identify upper or lower case characters
- So write extensions to identify upper and lower case characters
- Use regular expressions & rangeOfString to identify upper and lower case characters
Test Cases:
- Hello World should return 2 & 8
- Hello 123 World $# should also return 2 & 8
Author:
- Joseph Jude (jjude.com / @jjude)
Git Repo:
- http://github.com/jjude/swift-exercises
Blog Post:
- http://tech.jjude.com/swift-challenge-009
*/
import Foundation
extension Character {
func isUpper() -> Bool {
if String(self).rangeOfString("[A-Z]", options: .RegularExpressionSearch) != nil {
return true
}
return false
}
}
extension Character {
func isLower() -> Bool {
if String(self).rangeOfString("[a-z]", options: .RegularExpressionSearch) != nil {
return true
}
return false
}
}
let inputString = "Hello @World #$@123"
var (upper,lower) = (0,0)
for c in inputString.characters {
if c.isUpper() {
upper += 1
}
if c.isLower() {
lower += 1
}
}
print(upper, lower) | mit | aceb43a1bcfd606a5a47cd2b59259dfe | 20.017857 | 86 | 0.671769 | 3.721519 | false | false | false | false |
lyft/SwiftLint | Source/SwiftLintFramework/Rules/RuleConfigurations/SeverityLevelsConfiguration.swift | 1 | 1698 | import Foundation
public struct SeverityLevelsConfiguration: RuleConfiguration, Equatable {
public var consoleDescription: String {
let errorString: String
if let errorValue = error {
errorString = ", error: \(errorValue)"
} else {
errorString = ""
}
return "warning: \(warning)" + errorString
}
public var shortConsoleDescription: String {
if let errorValue = error {
return "w/e: \(warning)/\(errorValue)"
}
return "w: \(warning)"
}
var warning: Int
var error: Int?
var params: [RuleParameter<Int>] {
if let error = error {
return [RuleParameter(severity: .error, value: error),
RuleParameter(severity: .warning, value: warning)]
}
return [RuleParameter(severity: .warning, value: warning)]
}
public mutating func apply(configuration: Any) throws {
if let configurationArray = [Int].array(of: configuration), !configurationArray.isEmpty {
warning = configurationArray[0]
error = (configurationArray.count > 1) ? configurationArray[1] : nil
} else if let configDict = configuration as? [String: Int?],
!configDict.isEmpty, Set(configDict.keys).isSubset(of: ["warning", "error"]) {
warning = (configDict["warning"] as? Int) ?? warning
error = configDict["error"] as? Int
} else {
throw ConfigurationError.unknownConfiguration
}
}
}
public func == (lhs: SeverityLevelsConfiguration, rhs: SeverityLevelsConfiguration) -> Bool {
return lhs.warning == rhs.warning && lhs.error == rhs.error
}
| mit | c5584272ca78a04bb13830f67100f523 | 34.375 | 97 | 0.607185 | 4.783099 | false | true | false | false |
emilstahl/swift | test/Constraints/function.swift | 10 | 2191 | // RUN: %target-parse-verify-swift
func f0(x: Float) -> Float {}
func f1(x: Float) -> Float {}
func f2(@autoclosure x: () -> Float) {}
var f : Float
f0(f0(f))
f0(1)
f1(f1(f))
f2(f)
f2(1.0)
func call_lvalue(@autoclosure rhs: ()->Bool) -> Bool {
return rhs()
}
// Function returns
func weirdCast<T, U>(x: T) -> U {}
func ff() -> (Int) -> (Float) { return weirdCast }
// Block <-> function conversions
var funct: String -> String = { $0 }
var block: @convention(block) String -> String = funct
funct = block
block = funct
// Application of implicitly unwrapped optional functions
var optFunc: (String -> String)! = { $0 }
var s: String = optFunc("hi")
// <rdar://problem/17652759> Default arguments cause crash with tuple permutation
func testArgumentShuffle(first: Int = 7, third: Int = 9) {
}
testArgumentShuffle(third: 1, 2)
func rejectsAssertStringLiteral() {
assert("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
precondition("foo") // expected-error {{cannot convert value of type 'String' to expected argument type 'Bool'}}
}
// <rdar://problem/22243469> QoI: Poor error message with throws, default arguments, & overloads
func process(line: UInt = __LINE__, _ fn: () -> Void) {}
func process(line: UInt = __LINE__) -> Int { return 0 }
func dangerous() throws {}
func test() {
process { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> Void'}}
try dangerous()
test()
}
}
// <rdar://problem/19962010> QoI: argument label mismatches produce not-great diagnostic
class A {
func a(text:String) {
}
func a(text:String, something:Int?=nil) {
}
}
A().a(text:"sometext") // expected-error {{argument labels '(text:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'a' exist with these partially matching parameter lists: (String), (String, something: Int?)}}
// <rdar://problem/22451001> QoI: incorrect diagnostic when argument to print has the wrong type
func r22451001() -> AnyObject {}
print(r22451001(5)) // expected-error {{argument passed to call that takes no arguments}}
| apache-2.0 | a82bcfacddc7b8df125d1334860e635c | 27.454545 | 152 | 0.671383 | 3.477778 | false | true | false | false |
marko628/Playground | Answers.playgroundbook/Contents/Sources/PlaygroundInternal/MessageCell.swift | 1 | 3272 | // MessageCell.swift
import UIKit
class MessageCell: UITableViewCell {
let sourceIndicator = CAShapeLayer()
let messageLabel = UILabel()
static let defaultLayoutMargins: UIEdgeInsets = {
let verticalPadding = ceil(UIFont.preferredFont(forTextStyle: UIFontTextStyle.body).lineHeight / 2.0)
return UIEdgeInsets(top: verticalPadding, left: 55.0, bottom: verticalPadding, right: 20)
}()
var selectionRect: CGRect {
var rect = messageLabel.frame
rect.size.width = min(messageLabel.intrinsicContentSize.width, rect.size.width)
return rect
}
var messageText: String {
get {
return messageLabel.text ?? ""
}
set (text) {
messageLabel.text = text
}
}
class var reuseIdentifier: String {
return "MessageCell"
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = nil
selectionStyle = .none
layoutMargins = MessageCell.defaultLayoutMargins
sourceIndicator.fillColor = UIColor(white: 0.0, alpha: 0.2).cgColor
layer.addSublayer(sourceIndicator)
messageLabel.numberOfLines = 0
messageLabel.lineBreakMode = .byWordWrapping
messageLabel.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.body)
messageLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(messageLabel)
NSLayoutConstraint.activate([
messageLabel.leadingAnchor.constraint(equalTo: layoutMarginsGuide.leadingAnchor),
messageLabel.trailingAnchor.constraint(lessThanOrEqualTo: layoutMarginsGuide.trailingAnchor),
messageLabel.topAnchor.constraint(equalTo: layoutMarginsGuide.topAnchor),
messageLabel.bottomAnchor.constraint(equalTo: layoutMarginsGuide.bottomAnchor)
])
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Layout
override func layoutSubviews() {
sourceIndicator.frame = CGRect(x: layoutMargins.left - 20,
y: layoutMargins.top,
width: 5,
height: bounds.height - layoutMargins.top - layoutMargins.bottom)
sourceIndicator.path = UIBezierPath(roundedRect: sourceIndicator.bounds, cornerRadius: sourceIndicator.bounds.width / 2.0).cgPath
messageLabel.preferredMaxLayoutWidth = bounds.width - layoutMargins.left - layoutMargins.right
super.layoutSubviews()
}
// MARK: Accessibility
override var accessibilityLabel: String? {
set {
assertionFailure("Should not try to set the accessibility properties of an MessageCell.")
}
get {
let outputFormat = NSLocalizedString("com.apple.playgroundbook.template.Answers.output-cell-accessibility-format", value: "Output, %@", comment: "Accessibility text format for the output cell")
return String(format: outputFormat, messageText)
}
}
}
| mit | da761d31fee3e9c9917cd8fea6faffe8 | 37.046512 | 205 | 0.646088 | 5.770723 | false | false | false | false |
phillfarrugia/currency-converter | Currency Converter/CurrencySelectorView.swift | 1 | 5753 | //
// HorizontalLabelSelectorView.swift
// Currency Converter
//
// Created by Phill Farrugia on 5/06/2016.
// Copyright © 2016 Phill Farrugia. All rights reserved.
//
import UIKit
protocol CurrencySelectorViewDelegate {
func numberOfItems() -> Int
func textForItemAtIndex(index: Int) -> String?
func selectorDidSelectItemAtIndex(index: Int)
}
class CurrencySelectorView: UIView, UIScrollViewDelegate {
static private let kNumberOfItemsOffscreen: Int = 1
static private let kCurrencyLabelWidth: CGFloat = 120
static private let kCurrencyLabelMargin: CGFloat = 10
@IBOutlet weak private var shadowView: UIView!
@IBOutlet weak private var scrollView: UIScrollView!
var delegate: CurrencySelectorViewDelegate?
private var currencyLabels: [CurrencyLabel]?
private var selectedLabel: CurrencyLabel? {
didSet {
if let selectedLabel = selectedLabel, let index = currencyLabels?.indexOf(selectedLabel) {
if (selectedLabel != oldValue) {
delegate?.selectorDidSelectItemAtIndex(index)
}
}
}
}
var initialSelectionIndex: Int = 0
override func awakeFromNib() {
super.awakeFromNib()
clipsToBounds = false
scrollView.delegate = self
shadowView.addInnerShadowWithRadius(3.0, andColor: UIColor(white: 0, alpha:0.15), inDirection: [.Top, .Bottom])
}
func reloadData() {
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
guard let delegate = delegate else { return }
guard let scrollView = scrollView else { return }
let numberOfItems = delegate.numberOfItems()
let itemIndexes = 0..<numberOfItems
// Remove existing Currency Labels
if let currencyLabels = self.currencyLabels {
for currencyLabel in currencyLabels {
currencyLabel.removeFromSuperview()
}
}
// Calculate Scroll View Content Width & Content Inset
let labelsWidth = (CGFloat(numberOfItems) * CurrencySelectorView.kCurrencyLabelWidth) + (CGFloat(numberOfItems) * CurrencySelectorView.kCurrencyLabelMargin)
scrollView.contentSize.width = labelsWidth
scrollView.contentInset = UIEdgeInsetsMake(0, self.center.x - CurrencySelectorView.kCurrencyLabelWidth/2, 0, self.center.x - CurrencySelectorView.kCurrencyLabelWidth/2)
// Map new items into Currency Labels
self.currencyLabels = itemIndexes.map {
if let currencyText = delegate.textForItemAtIndex($0) {
return currencyLabelForIndex($0, text: currencyText)
}
return nil
}.flatMap { $0 }
// Add new Currency Labels as subviews
if let currencyLabels = self.currencyLabels {
for currencyLabel in currencyLabels {
scrollView.addSubview(currencyLabel)
}
}
// Check if Intitial Index is inside array bounds
if (numberOfItems > 0) {
if (initialSelectionIndex >= 0 && initialSelectionIndex < numberOfItems) {
scrollToItemAtIndex(initialSelectionIndex, animated: false)
} else {
scrollToItemAtIndex(0, animated: false)
}
}
}
private func currencyLabelForIndex(index: Int, text: String) -> CurrencyLabel {
let xOffset = ((CGFloat(index) * CurrencySelectorView.kCurrencyLabelWidth) + (CGFloat(index) * CurrencySelectorView.kCurrencyLabelMargin))
let frame = CGRectMake(xOffset, 0, CurrencySelectorView.kCurrencyLabelWidth, self.bounds.height)
let label = CurrencyLabel(frame: frame)
label.text = text
return label
}
private func scrollToItemAtIndex(index: Int, animated: Bool) {
guard let scrollView = scrollView else { return }
guard let currencyLabels = currencyLabels else { return }
// Deselect Current Selection
if let selectedLabel = selectedLabel {
selectedLabel.setSelected(false)
}
// New Selection Label at Index
let newSelection = currencyLabels[index]
newSelection.setSelected(true)
self.selectedLabel = newSelection
// Scroll to Currency Label center x
let xOffset = newSelection.center.x - self.center.x
let scrollViewContentOffset = CGPoint(x: xOffset, y: 0)
scrollView.setContentOffset(scrollViewContentOffset, animated: animated)
}
// MARK: UIScrollViewDelegate
func scrollViewDidScroll(scrollView: UIScrollView) {
guard let currencyLabels = currencyLabels else { return }
guard let selectedLabel = selectedLabel else { return }
let labelWidth = CurrencySelectorView.kCurrencyLabelWidth + CurrencySelectorView.kCurrencyLabelMargin
let targetItemIndex = Int(floor((scrollView.contentOffset.x + self.center.x) / labelWidth))
if (targetItemIndex >= 0 && targetItemIndex < currencyLabels.count) {
let targetItem = currencyLabels[targetItemIndex]
selectedLabel.setSelected(false)
targetItem.setSelected(true)
self.selectedLabel = targetItem
}
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
guard let currencyLabels = currencyLabels else { return }
guard let selectedLabel = selectedLabel else { return }
guard let selectedIndex = currencyLabels.indexOf(selectedLabel) else { return }
scrollToItemAtIndex(selectedIndex, animated: true)
}
}
| mit | 375b445392c47fc6fef3c2fdee65664e | 37.604027 | 176 | 0.651947 | 5.375701 | false | false | false | false |
SusanDoggie/DoggieGP | Sources/OpenCL/clFunction.swift | 1 | 4584 | //
// clFunction.swift
//
// The MIT License
// Copyright (c) 2015 - 2018 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import OpenCL
extension OpenCL {
public final class Library : LibraryProtocol {
let program: cl_program
fileprivate init(program: cl_program) {
self.program = program
}
deinit {
clReleaseProgram(program)
}
}
public final class Function : FunctionProtocol {
let library: Library
let kernel: cl_kernel
fileprivate init(library: Library, name: String) {
self.library = library
var error: cl_int = 0
self.kernel = name.withCString { clCreateKernel(library.program, $0, &error) }
guard error == CL_SUCCESS else { fatalError("clCreateKernel failed: \(error)") }
}
public func maxTotalThreadsPerThreadgroup(with device: Device) -> Int {
var size: size_t = 0
clGetKernelWorkGroupInfo(kernel, device.device, numericCast(CL_KERNEL_WORK_GROUP_SIZE), MemoryLayout.stride(ofValue: size), &size, nil)
return Int(size)
}
public func preferredThreadgroupSizeMultiple(with device: Device) -> Int {
var size: size_t = 0
clGetKernelWorkGroupInfo(kernel, device.device, numericCast(CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE), MemoryLayout.stride(ofValue: size), &size, nil)
return Int(size)
}
deinit {
clReleaseKernel(kernel)
}
}
public func library(source: String) -> Library {
return library(source: CollectionOfOne(source))
}
public func library<C: Collection>(source: C) -> Library where C.Iterator.Element == String {
var error: cl_int = 0
let _source = source.map { $0.cString(using: .utf8) }
var _buf = _source.map { $0?.withUnsafeBufferPointer { $0.baseAddress } }
let _program = clCreateProgramWithSource(context, numericCast(source.count), &_buf, nil, &error)
guard error == CL_SUCCESS else { fatalError("clCreateProgramWithSource failed: \(error)") }
guard let program = _program else { fatalError("clCreateProgramWithSource failed: \(error)") }
return Library(program: program)
}
}
extension OpenCL {
public struct BuildError: Error {
public let error: Int32
public let message: String
}
}
extension OpenCL.Library {
public func build(_ device: OpenCL.Device) throws {
var deviceId: cl_device_id? = device.device
let error = clBuildProgram(program, 1, &deviceId, nil, nil, nil)
if error != CL_SUCCESS {
var length: Int = 0
clGetProgramBuildInfo(program, device.device, cl_program_build_info(CL_PROGRAM_BUILD_LOG), 0, nil, &length)
var value = [CChar](repeating: 0, count: length)
clGetProgramBuildInfo(program, device.device, cl_program_build_info(CL_PROGRAM_BUILD_LOG), length, &value, nil)
throw OpenCL.BuildError(error: error, message: String(cString: &value))
}
}
}
extension OpenCL.Library {
public func function(name: String) -> OpenCL.Function {
return OpenCL.Function(library: self, name: name)
}
}
| mit | a2c0026e339639fc7d40e4d5acb4cf68 | 34.261538 | 166 | 0.625218 | 4.450485 | false | false | false | false |
ufogxl/MySQLTest | Sources/getCurrentInfo.swift | 1 | 5201 | //
// getCurrentInfo.swift
// GoodStudent
//
// Created by ufogxl on 2016/11/26.
//
// 获取当前状态信息,包括今日课表,一卡通和阳光长跑,如果在某个课程考试日期前14天内就包括该课程考试信息
import Foundation
import PerfectLib
import PerfectHTTP
import MySQL
import ObjectMapper
fileprivate let errorContent = ErrorContent()
fileprivate let container = ResponseContainer()
fileprivate let user_info = NSMutableDictionary()
func getCurrentInfo(_ request:HTTPRequest,response:HTTPResponse){
//读取网络请求的参数
//需要参数:username(对应学生表中的s_num)
let params = request.params()
phaseParams(params: params)
if !paramsValid(){
let errorStr = "参数错误"
errorContent.code = ErrCode.ARGUMENT_ERROR.hashValue
container.message = errorStr
container.data = errorContent
container.result = false
response.appendBody(string:container.toJSONString(prettyPrint: true)!)
response.completed()
return
}
if let currentInfo = makeCurrentInfo(){
container.data = currentInfo
container.result = true
container.message = "获取成功"
response.appendBody(string: container.toJSONString(prettyPrint: false)!)
response.completed()
}else{
errorContent.message = "系统错误,请稍后再试"
container.data = errorContent
container.result = false
container.message = "系统错误,请稍后再试!"
}
}
fileprivate func phaseParams(params:[(String,String)]){
for i in 0..<params.count{
user_info.setObject(params[i].1, forKey: NSString(string: params[i].0))
}
}
fileprivate func paramsValid() -> Bool{
let username = user_info["username"] as? String
if (username == nil) || (username! == ""){
return false
}
return true
}
fileprivate func makeCurrentInfo() -> CurrentInfo?{
let currentInfo = CurrentInfo()
currentInfo.date = time.presentedTime
var examInfo = [Exam]()
var courseInfo = [Course]()
var scoreInfo = [Score]()
let mysql = MySQL()
let connected = mysql.connect(host: db_host, user: db_user, password: db_password, db: database,port:db_port)
guard connected else {
print(mysql.errorMessage())
return nil
}
defer {
mysql.close()
}
if time.numberOfWeek > 14{
//获取考试信息
let statement = "SELECT c_name,exam_time,exam_place FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time>=\(getWhichExam()) order by exam_time limit 4"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else {
return nil
}
let results = mysql.storeResults()!
while let row = results.next(){
let exam = Exam()
exam.name = row[0]!
exam.time = getExamTime(Int(row[1]!)!)
exam.place = row[2]!
examInfo.append(exam)
}
if examInfo.count > 3{
examInfo.removeLast()
currentInfo.hasMoreExams = true
}
}
if time.numberOfWeek > 16{
//考试成绩
let statement = "SELECT c_name,score FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and exam_time<=\(getWhichExam() - 3) order by exam_time limit 4"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else{
return nil
}
let results = mysql.storeResults()!
while let row = results.next() {
let score = Score()
score.score = row[1]
score.name = row[0]
scoreInfo.append(score)
}
if scoreInfo.count > 3{
scoreInfo.removeLast()
currentInfo.hasMoreScore = true
}
}
//不在工作日或不在上课时间
if time.numberOfClass > 25 || time.numberOfWeek > 16{
currentInfo.courses = courseInfo
currentInfo.exams = examInfo
currentInfo.scores = scoreInfo
return currentInfo
}
let weekday = (time.numberOfClass - 1) / 5 + 1
//获取今日课表
let statement = "SELECT c_num,c_name,time,place,teacher FROM stujoincou WHERE s_num=\(Int(user_info["username"] as! String)!) and time between \((weekday-1) * 5 + 1) and \((weekday - 1) * 5 + 5) and time>=\(time.numberOfClass!) order by time"
let querySuccess = mysql.query(statement: statement)
guard querySuccess else {
return nil
}
let results = mysql.storeResults()!
while let row = results.next() {
let course = Course()
course.num = row[0]!
course.name = row[1]!
course.time = getClassTime(which: Int(row[2]!)!)
course.place = row[3]!
course.teacher = row[4]!
courseInfo.append(course)
}
currentInfo.courses = courseInfo
currentInfo.exams = examInfo
currentInfo.scores = scoreInfo
return currentInfo
}
| apache-2.0 | 013442b1c18f901fd56dac19ad06e872 | 28.111765 | 246 | 0.600323 | 4.073251 | false | false | false | false |
ShauryaS/Bookkeeper | Bookkeeping/LoginView.swift | 1 | 9337 | //
// LoginView.swift
// Bookkeeping
//
// Created by Shaurya Srivastava on 7/12/16.
// Copyright © 2016 CFO-online, Inc. All rights reserved.
//
import Foundation
import UIKit
import SwiftHTTP
class LogInView: UIViewController{
//variable for the textfield where the email/username is entered
@IBOutlet var emailUserTF: UITextField!
//variable for the textfield where the password is entered
@IBOutlet var passwordTF: UITextField!
//variable for the button which indactes whether credentials should be saved
@IBOutlet var rememberMeButton: UIButton!
//variable for error msg
var emsg = "error"
//called when the view is loaded
//Params: none
//sets the tap anywhere to get rid of keyboard function
//Return: none
override func viewDidLoad() {
super.viewDidLoad()
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LogInView.dismissKeyboard))
view.addGestureRecognizer(tap)
}
//Calls this function when the tap is recognized.
func dismissKeyboard() {
//Causes the view (or one of its embedded text fields) to resign the first responder status.
view.endEditing(true)
}
//params: boolean to determine if view should be animated
//func determines if savedData file exists
//reads file and gets info
//breaks up data read into separate variables (rememberMe, username, password, acctNum)
//depending on rememberMe boolean val, switches to the upload receipt view
//Return: none
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let filePath = getDocumentsDirectory().appending("/savedData.txt")
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
var savedContents = ""
do {
savedContents = try NSString(contentsOf: URL(fileURLWithPath: filePath), encoding: String.Encoding.utf8.rawValue) as String
let contents = savedContents.characters.split(separator: " ").map(String.init)
username = contents[0]
password = contents[1]
}
catch {
print("Error: "+"\(error)")
}
connectToBackEnd(username, password: password)
permitAuth()
}
}
//function that is called when view is going to appear
//Param: boolean variable to determine if view should be animated
//sets the navigation bar to be visible
//sets the tint of the notification bar to white (light content)
//sets the color of the notification bar to black
//Return: none
override func viewWillAppear(_ animated: Bool) {
self.navigationController?.isNavigationBarHidden = true
UIApplication.shared.isStatusBarHidden = false
UIApplication.shared.statusBarStyle = .lightContent
let statusBar: UIView = UIApplication.shared.value(forKey: "statusBar") as! UIView
if statusBar.responds(to: #selector(setter: UIView.backgroundColor)) {
statusBar.backgroundColor = UIColor.black
}
}
//default view method
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//param: AnyObject that is recieved by button
//param not used but necessary as button always sends an AnyObject
//gets text from the username and password textfields and saves text to vars username and password
//checks if either username or password is nil
//if nil, alert box tells the user to enter credentials
//else, attempts to connect to backend and get json data and permits auth accordingly
//Return: none
@IBAction func signIn(_ sender: AnyObject) {
username = emailUserTF.text!
password = passwordTF.text!
if username != "" && password != ""{
connectToBackEnd(username, password: password)
permitAuth()
}
else{
let alert = UIAlertController(title: "Login Failed", message: "Enter Credentials.", preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
//params: none
//depending on val of auth, if successful, calls saveAuth method and switches view
//if auth unsuccessful, changes auth val back to default val and alerts user that credentials are incorrect
//Return: none
func permitAuth(){
if auth == 1{
saveAuth(username, password: password)
self.performSegue(withIdentifier: "LogToMainSegue", sender: nil)
}
else{
auth = 3
let tempmsg = emsg
emsg = ""
let alert = UIAlertController(title: "Login Failed", message: tempmsg, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}
//params: username and password - needed for the HTTP posting
//trys to post data to get json file
//gets json data as string - converts to data - converts to anyobject
//json gets parsed
//all errors caught
//Return: none
func connectToBackEnd(_ username:String, password:String){
do {
let opt = try HTTP.POST(url+"/upload?v=2&u="+username+"&p="+password)
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
let jsonString = String(data: response.data, encoding: String.Encoding.utf8)
let data: Data = (jsonString!.data(using: String.Encoding.utf8))!
do{
let anyObj: Any? = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions(rawValue: 0))
self.parseJson(anyObj! as AnyObject)
} catch {
print("Error: \(error)")
}
}
} catch let error {
print("got an error creating the request: \(error)")
}
while auth == 3 || emsg == "error" {}
}
//param: json data as AnyObject
//parses the data recieved when the username and password are posted
//gets auth status and acct number and all the types and purposes options
//sets the data array for types and sorts it lexographically
//Return: none
func parseJson(_ anyObj:AnyObject){
var user = User()
if anyObj is NSDictionary {
user.accts = anyObj["accts"] as? String
user.types = anyObj["types"] as? [String: AnyObject]
user.emsg = anyObj["errmsg"] as? String
user.ok = anyObj["OK"] as? AnyObject
auth = Int((user.ok?.description)!)!
if user.accts != nil{
acctNum = user.accts!
}
if user.types != nil{
dataAll = user.types!
for key in (user.types?.keys)!{
dataTypes.append(key)
}
dataTypes = dataTypes.sorted{
return $0 < $1
}
}
if user.emsg != nil{
emsg = user.emsg!
}
}
}
//param: AnyObject that is recieved by button
//param not used but necessary as button always sends an AnyObject
//higlights/unhighlights remember me button depending on val of rememberMe
//changes val of rememberMe accordingly
//used to determine whether credentials should be saved
//Return: none
@IBAction func remember(_ sender: AnyObject) {
if rememberMe == false{
rememberMeButton.isSelected = true
rememberMe = true
}
else{
rememberMeButton.isSelected = false
rememberMe = false
}
}
//params: username and password - to be saved in file
//credential data is saved as string in a file
//Return: none
func saveAuth(_ username: String, password: String){
if rememberMe {
let filePath = getDocumentsDirectory().appending("/savedData.txt")
let fileurl = URL(fileURLWithPath: filePath)
let savedString = username+" "+password
do{
try savedString.write(to: fileurl, atomically: false, encoding: String.Encoding.utf8)
}
catch{
print("Error: "+"\(error)")
}
}
}
//params: str - boolean in string format
//func returns bool val depending on whether string val is "true" or "false"
//Return: Boolean value
func stringBool(_ str: String) -> Bool{
switch(str){
case "true":
return true
case "false":
return false
default:
return false
}
}
}
| apache-2.0 | 71cc5e04096373379b96b95317bf6d58 | 37.738589 | 141 | 0.606041 | 4.900787 | false | false | false | false |
adrfer/swift | stdlib/public/core/String.swift | 1 | 31578 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
/// An arbitrary Unicode string value.
///
/// Unicode-Correct
/// ===============
///
/// Swift strings are designed to be Unicode-correct. In particular,
/// the APIs make it easy to write code that works correctly, and does
/// not surprise end-users, regardless of where you venture in the
/// Unicode character space. For example, the `==` operator checks
/// for [Unicode canonical
/// equivalence](http://www.unicode.org/glossary/#deterministic_comparison),
/// so two different representations of the same string will always
/// compare equal.
///
/// Locale-Insensitive
/// ==================
///
/// The fundamental operations on Swift strings are not sensitive to
/// locale settings. That's because, for example, the validity of a
/// `Dictionary<String, T>` in a running program depends on a given
/// string comparison having a single, stable result. Therefore,
/// Swift always uses the default,
/// un-[tailored](http://www.unicode.org/glossary/#tailorable) Unicode
/// algorithms for basic string operations.
///
/// Importing `Foundation` endows swift strings with the full power of
/// the `NSString` API, which allows you to choose more complex
/// locale-sensitive operations explicitly.
///
/// Value Semantics
/// ===============
///
/// Each string variable, `let` binding, or stored property has an
/// independent value, so mutations to the string are not observable
/// through its copies:
///
/// var a = "foo"
/// var b = a
/// b.appendContentsOf("bar")
/// print("a=\(a), b=\(b)") // a=foo, b=foobar
///
/// Strings use Copy-on-Write so that their data is only copied
/// lazily, upon mutation, when more than one string instance is using
/// the same buffer. Therefore, the first in any sequence of mutating
/// operations may cost `O(N)` time and space, where `N` is the length
/// of the string's (unspecified) underlying representation.
///
/// Views
/// =====
///
/// `String` is not itself a collection of anything. Instead, it has
/// properties that present the string's contents as meaningful
/// collections:
///
/// - `characters`: a collection of `Character` ([extended grapheme
/// cluster](http://www.unicode.org/glossary/#extended_grapheme_cluster))
/// elements, a unit of text that is meaningful to most humans.
///
/// - `unicodeScalars`: a collection of `UnicodeScalar` ([Unicode
/// scalar
/// values](http://www.unicode.org/glossary/#unicode_scalar_value))
/// the 21-bit codes that are the basic unit of Unicode. These
/// values are equivalent to UTF-32 code units.
///
/// - `utf16`: a collection of `UTF16.CodeUnit`, the 16-bit
/// elements of the string's UTF-16 encoding.
///
/// - `utf8`: a collection of `UTF8.CodeUnit`, the 8-bit
/// elements of the string's UTF-8 encoding.
///
/// Growth and Capacity
/// ===================
///
/// When a string's contiguous storage fills up, new storage must be
/// allocated and characters must be moved to the new storage.
/// `String` uses an exponential growth strategy that makes `append` a
/// constant time operation *when amortized over many invocations*.
///
/// Objective-C Bridge
/// ==================
///
/// `String` is bridged to Objective-C as `NSString`, and a `String`
/// that originated in Objective-C may store its characters in an
/// `NSString`. Since any arbitrary subclass of `NSString` can
/// become a `String`, there are no guarantees about representation or
/// efficiency in this case. Since `NSString` is immutable, it is
/// just as though the storage was shared by some copy: the first in
/// any sequence of mutating operations causes elements to be copied
/// into unique, contiguous storage which may cost `O(N)` time and
/// space, where `N` is the length of the string representation (or
/// more, if the underlying `NSString` has unusual performance
/// characteristics).
public struct String {
/// An empty `String`.
public init() {
_core = _StringCore()
}
public // @testable
init(_ _core: _StringCore) {
self._core = _core
}
public // @testable
var _core: _StringCore
}
extension String {
@warn_unused_result
public // @testable
static func _fromWellFormedCodeUnitSequence<
Encoding: UnicodeCodecType, Input: CollectionType
where Input.Generator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> String {
return String._fromCodeUnitSequence(encoding, input: input)!
}
@warn_unused_result
public // @testable
static func _fromCodeUnitSequence<
Encoding: UnicodeCodecType, Input: CollectionType
where Input.Generator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> String? {
let (stringBufferOptional, _) =
_StringBuffer.fromCodeUnits(encoding, input: input,
repairIllFormedSequences: false)
if let stringBuffer = stringBufferOptional {
return String(_storage: stringBuffer)
} else {
return nil
}
}
@warn_unused_result
public // @testable
static func _fromCodeUnitSequenceWithRepair<
Encoding: UnicodeCodecType, Input: CollectionType
where Input.Generator.Element == Encoding.CodeUnit
>(
encoding: Encoding.Type, input: Input
) -> (String, hadError: Bool) {
let (stringBuffer, hadError) =
_StringBuffer.fromCodeUnits(encoding, input: input,
repairIllFormedSequences: true)
return (String(_storage: stringBuffer!), hadError)
}
}
extension String : _BuiltinUnicodeScalarLiteralConvertible {
@effects(readonly)
public // @testable
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {
self = String._fromWellFormedCodeUnitSequence(
UTF32.self, input: CollectionOfOne(UInt32(value)))
}
}
extension String : UnicodeScalarLiteralConvertible {
/// Create an instance initialized to `value`.
public init(unicodeScalarLiteral value: String) {
self = value
}
}
extension String : _BuiltinExtendedGraphemeClusterLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
byteSize: Builtin.Word,
isASCII: Builtin.Int1) {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(byteSize)))
}
}
extension String : ExtendedGraphemeClusterLiteralConvertible {
/// Create an instance initialized to `value`.
public init(extendedGraphemeClusterLiteral value: String) {
self = value
}
}
extension String : _BuiltinUTF16StringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF16")
public init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
numberOfCodeUnits: Builtin.Word
) {
self = String(
_StringCore(
baseAddress: COpaquePointer(start),
count: Int(numberOfCodeUnits),
elementShift: 1,
hasCocoaBuffer: false,
owner: nil))
}
}
extension String : _BuiltinStringLiteralConvertible {
@effects(readonly)
@_semantics("string.makeUTF8")
public init(
_builtinStringLiteral start: Builtin.RawPointer,
byteSize: Builtin.Word,
isASCII: Builtin.Int1) {
if Bool(isASCII) {
self = String(
_StringCore(
baseAddress: COpaquePointer(start),
count: Int(byteSize),
elementShift: 0,
hasCocoaBuffer: false,
owner: nil))
}
else {
self = String._fromWellFormedCodeUnitSequence(
UTF8.self,
input: UnsafeBufferPointer(
start: UnsafeMutablePointer<UTF8.CodeUnit>(start),
count: Int(byteSize)))
}
}
}
extension String : StringLiteralConvertible {
/// Create an instance initialized to `value`.
public init(stringLiteral value: String) {
self = value
}
}
extension String : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
var result = "\""
for us in self.unicodeScalars {
result += us.escape(asASCII: false)
}
result += "\""
return result
}
}
extension String {
/// Return the number of code units occupied by this string
/// in the given encoding.
@warn_unused_result
func _encodedLength<
Encoding: UnicodeCodecType
>(encoding: Encoding.Type) -> Int {
var codeUnitCount = 0
let output: (Encoding.CodeUnit) -> Void = { _ in codeUnitCount += 1 }
self._encode(encoding, output: output)
return codeUnitCount
}
// FIXME: this function does not handle the case when a wrapped NSString
// contains unpaired surrogates. Fix this before exposing this function as a
// public API. But it is unclear if it is valid to have such an NSString in
// the first place. If it is not, we should not be crashing in an obscure
// way -- add a test for that.
// Related: <rdar://problem/17340917> Please document how NSString interacts
// with unpaired surrogates
func _encode<
Encoding: UnicodeCodecType
>(encoding: Encoding.Type, output: (Encoding.CodeUnit) -> Void)
{
return _core.encode(encoding, output: output)
}
}
#if _runtime(_ObjC)
/// Compare two strings using the Unicode collation algorithm in the
/// deterministic comparison mode. (The strings which are equivalent according
/// to their NFD form are considered equal. Strings which are equivalent
/// according to the plain Unicode collation algorithm are additionally ordered
/// based on their NFD.)
///
/// See Unicode Technical Standard #10.
///
/// The behavior is equivalent to `NSString.compare()` with default options.
///
/// - returns:
/// * an unspecified value less than zero if `lhs < rhs`,
/// * zero if `lhs == rhs`,
/// * an unspecified value greater than zero if `lhs > rhs`.
@_silgen_name("swift_stdlib_compareNSStringDeterministicUnicodeCollation")
public func _stdlib_compareNSStringDeterministicUnicodeCollation(
lhs: AnyObject, _ rhs: AnyObject
) -> Int32
#endif
extension String : Equatable {
}
@warn_unused_result
public func ==(lhs: String, rhs: String) -> Bool {
if lhs._core.isASCII && rhs._core.isASCII {
if lhs._core.count != rhs._core.count {
return false
}
return _swift_stdlib_memcmp(
lhs._core.startASCII, rhs._core.startASCII,
rhs._core.count) == 0
}
return lhs._compareString(rhs) == 0
}
extension String : Comparable {
}
extension String {
#if _runtime(_ObjC)
/// This is consistent with Foundation, but incorrect as defined by Unicode.
/// Unicode weights some ASCII punctuation in a different order than ASCII
/// value. Such as:
///
/// 0022 ; [*02FF.0020.0002] # QUOTATION MARK
/// 0023 ; [*038B.0020.0002] # NUMBER SIGN
/// 0025 ; [*038C.0020.0002] # PERCENT SIGN
/// 0026 ; [*0389.0020.0002] # AMPERSAND
/// 0027 ; [*02F8.0020.0002] # APOSTROPHE
///
/// - Precondition: Both `self` and `rhs` are ASCII strings.
@warn_unused_result
public // @testable
func _compareASCII(rhs: String) -> Int {
var compare = Int(_swift_stdlib_memcmp(
self._core.startASCII, rhs._core.startASCII,
min(self._core.count, rhs._core.count)))
if compare == 0 {
compare = self._core.count - rhs._core.count
}
// This efficiently normalizes the result to -1, 0, or 1 to match the
// behavior of NSString's compare function.
return (compare > 0 ? 1 : 0) - (compare < 0 ? 1 : 0)
}
#endif
/// Compares two strings with the Unicode Collation Algorithm.
@warn_unused_result
@inline(never)
@_semantics("stdlib_binary_only") // Hide the CF/ICU dependency
public // @testable
func _compareDeterministicUnicodeCollation(rhs: String) -> Int {
// Note: this operation should be consistent with equality comparison of
// Character.
#if _runtime(_ObjC)
return Int(_stdlib_compareNSStringDeterministicUnicodeCollation(
_bridgeToObjectiveCImpl(), rhs._bridgeToObjectiveCImpl()))
#else
switch (_core.isASCII, rhs._core.isASCII) {
case (true, false):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf8_utf16(
lhsPtr, Int32(_core.count), rhsPtr, Int32(rhs._core.count)))
case (false, true):
// Just invert it and recurse for this case.
return -rhs._compareDeterministicUnicodeCollation(self)
case (false, false):
let lhsPtr = UnsafePointer<UTF16.CodeUnit>(_core.startUTF16)
let rhsPtr = UnsafePointer<UTF16.CodeUnit>(rhs._core.startUTF16)
return Int(_swift_stdlib_unicode_compare_utf16_utf16(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
case (true, true):
let lhsPtr = UnsafePointer<Int8>(_core.startASCII)
let rhsPtr = UnsafePointer<Int8>(rhs._core.startASCII)
return Int(_swift_stdlib_unicode_compare_utf8_utf8(
lhsPtr, Int32(_core.count),
rhsPtr, Int32(rhs._core.count)))
}
#endif
}
@warn_unused_result
public // @testable
func _compareString(rhs: String) -> Int {
#if _runtime(_ObjC)
// We only want to perform this optimization on objc runtimes. Elsewhere,
// we will make it follow the unicode collation algorithm even for ASCII.
if (_core.isASCII && rhs._core.isASCII) {
return _compareASCII(rhs)
}
#endif
return _compareDeterministicUnicodeCollation(rhs)
}
}
@warn_unused_result
public func <(lhs: String, rhs: String) -> Bool {
return lhs._compareString(rhs) < 0
}
// Support for copy-on-write
extension String {
/// Append the elements of `other` to `self`.
public mutating func appendContentsOf(other: String) {
_core.append(other._core)
}
/// Append `x` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(x: UnicodeScalar) {
_core.append(x)
}
var _utf16Count: Int {
return _core.count
}
public // SPI(Foundation)
init(_storage: _StringBuffer) {
_core = _StringCore(_storage)
}
}
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringNFDHashValue")
func _stdlib_NSStringNFDHashValue(str: AnyObject) -> Int
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringASCIIHashValue")
func _stdlib_NSStringASCIIHashValue(str: AnyObject) -> Int
#endif
extension String : Hashable {
/// The hash value.
///
/// **Axiom:** `x == y` implies `x.hashValue == y.hashValue`.
///
/// - Note: The hash value is not guaranteed to be stable across
/// different invocations of the same program. Do not persist the
/// hash value across program runs.
public var hashValue: Int {
#if _runtime(_ObjC)
// Mix random bits into NSString's hash so that clients don't rely on
// Swift.String.hashValue and NSString.hash being the same.
#if arch(i386) || arch(arm)
let hashOffset = Int(bitPattern: 0x88dd_cc21)
#else
let hashOffset = Int(bitPattern: 0x429b_1266_88dd_cc21)
#endif
// FIXME(performance): constructing a temporary NSString is extremely
// wasteful and inefficient.
let cocoaString = unsafeBitCast(
self._bridgeToObjectiveCImpl(), _NSStringCoreType.self)
// If we have an ASCII string, we do not need to normalize.
if self._core.isASCII {
return hashOffset ^ _stdlib_NSStringASCIIHashValue(cocoaString)
} else {
return hashOffset ^ _stdlib_NSStringNFDHashValue(cocoaString)
}
#else
if self._core.isASCII {
return _swift_stdlib_unicode_hash_ascii(
UnsafeMutablePointer<Int8>(_core.startASCII),
Int32(_core.count))
} else {
return _swift_stdlib_unicode_hash(
UnsafeMutablePointer<UInt16>(_core.startUTF16),
Int32(_core.count))
}
#endif
}
}
@warn_unused_result
@effects(readonly)
@_semantics("string.concat")
public func + (lhs: String, rhs: String) -> String {
var lhs = lhs
if (lhs.isEmpty) {
return rhs
}
lhs._core.append(rhs._core)
return lhs
}
// String append
public func += (inout lhs: String, rhs: String) {
if lhs.isEmpty {
lhs = rhs
}
else {
lhs._core.append(rhs._core)
}
}
extension String {
/// Constructs a `String` in `resultStorage` containing the given UTF-8.
///
/// Low-level construction interface used by introspection
/// implementation in the runtime library.
@_silgen_name("swift_stringFromUTF8InRawMemory")
public // COMPILER_INTRINSIC
static func _fromUTF8InRawMemory(
resultStorage: UnsafeMutablePointer<String>,
start: UnsafeMutablePointer<UTF8.CodeUnit>, utf8Count: Int
) {
resultStorage.initialize(
String._fromWellFormedCodeUnitSequence(UTF8.self,
input: UnsafeBufferPointer(start: start, count: utf8Count)))
}
}
extension String {
public typealias Index = CharacterView.Index
/// The position of the first `Character` in `self.characters` if
/// `self` is non-empty; identical to `endIndex` otherwise.
public var startIndex: Index { return characters.startIndex }
/// The "past the end" position in `self.characters`.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Index { return characters.endIndex }
/// Access the `Character` at `position`.
///
/// - Requires: `position` is a valid position in `self.characters`
/// and `position != endIndex`.
public subscript(i: Index) -> Character { return characters[i] }
}
@warn_unused_result
public func == (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._base == rhs._base
}
@warn_unused_result
public func < (lhs: String.Index, rhs: String.Index) -> Bool {
return lhs._base < rhs._base
}
extension String {
/// Access the characters in the given `subRange`.
///
/// - Complexity: O(1) unless bridging from Objective-C requires an
/// O(N) conversion.
public subscript(subRange: Range<Index>) -> String {
return String(characters[subRange])
}
}
extension String {
public mutating func reserveCapacity(n: Int) {
withMutableCharacters {
(inout v: CharacterView) in v.reserveCapacity(n)
}
}
public mutating func append(c: Character) {
withMutableCharacters {
(inout v: CharacterView) in v.append(c)
}
}
public mutating func appendContentsOf<
S : SequenceType
where S.Generator.Element == Character
>(newElements: S) {
withMutableCharacters {
(inout v: CharacterView) in v.appendContentsOf(newElements)
}
}
/// Create an instance containing `characters`.
public init<
S : SequenceType
where S.Generator.Element == Character
>(_ characters: S) {
self._core = CharacterView(characters)._core
}
}
extension String {
@available(*, unavailable, message="call the 'joinWithSeparator()' method on the sequence of elements")
public func join<
S : SequenceType where S.Generator.Element == String
>(elements: S) -> String {
fatalError("unavailable function can't be called")
}
}
extension SequenceType where Generator.Element == String {
/// Interpose the `separator` between elements of `self`, then concatenate
/// the result. For example:
///
/// ["foo", "bar", "baz"].joinWithSeparator("-|-") // "foo-|-bar-|-baz"
@warn_unused_result
public func joinWithSeparator(separator: String) -> String {
var result = ""
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
let separatorSize = separator.utf16.count
let reservation = self._preprocessingPass {
(s: Self) -> Int in
var r = 0
for chunk in s {
// FIXME(performance): this code assumes UTF-16 in-memory representation.
// It should be switched to low-level APIs.
r += separatorSize + chunk.utf16.count
}
return r - separatorSize
}
if let n = reservation {
result.reserveCapacity(n)
}
if separatorSize != 0 {
var gen = generate()
if let first = gen.next() {
result.appendContentsOf(first)
while let next = gen.next() {
result.appendContentsOf(separator)
result.appendContentsOf(next)
}
}
}
else {
for x in self {
result.appendContentsOf(x)
}
}
return result
}
}
extension String {
/// Replace the given `subRange` of elements with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`subRange.count`) if `subRange.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceRange<
C: CollectionType where C.Generator.Element == Character
>(
subRange: Range<Index>, with newElements: C
) {
withMutableCharacters {
(inout v: CharacterView) in v.replaceRange(subRange, with: newElements)
}
}
/// Replace the given `subRange` of elements with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`subRange.count`) if `subRange.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceRange(
subRange: Range<Index>, with newElements: String
) {
replaceRange(subRange, with: newElements.characters)
}
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func insert(newElement: Character, atIndex i: Index) {
withMutableCharacters {
(inout v: CharacterView) in v.insert(newElement, atIndex: i)
}
}
/// Insert `newElements` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count + newElements.count`).
public mutating func insertContentsOf<
S : CollectionType where S.Generator.Element == Character
>(newElements: S, at i: Index) {
withMutableCharacters {
(inout v: CharacterView) in v.insertContentsOf(newElements, at: i)
}
}
/// Remove and return the element at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func removeAtIndex(i: Index) -> Character {
return withMutableCharacters {
(inout v: CharacterView) in v.removeAtIndex(i)
}
}
/// Remove the indicated `subRange` of characters.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
public mutating func removeRange(subRange: Range<Index>) {
withMutableCharacters {
(inout v: CharacterView) in v.removeRange(subRange)
}
}
/// Remove all characters.
///
/// Invalidates all indices with respect to `self`.
///
/// - parameter keepCapacity: If `true`, prevents the release of
/// allocated storage, which can be a useful optimization
/// when `self` is going to be grown again.
public mutating func removeAll(keepCapacity keepCapacity: Bool = false) {
withMutableCharacters {
(inout v: CharacterView) in v.removeAll(keepCapacity: keepCapacity)
}
}
}
#if _runtime(_ObjC)
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringLowercaseString")
func _stdlib_NSStringLowercaseString(str: AnyObject) -> _CocoaStringType
@warn_unused_result
@_silgen_name("swift_stdlib_NSStringUppercaseString")
func _stdlib_NSStringUppercaseString(str: AnyObject) -> _CocoaStringType
#else
@warn_unused_result
internal func _nativeUnicodeLowercaseString(str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToLower(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToLower(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
@warn_unused_result
internal func _nativeUnicodeUppercaseString(str: String) -> String {
var buffer = _StringBuffer(
capacity: str._core.count, initialSize: str._core.count, elementWidth: 2)
// Try to write it out to the same length.
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
let z = _swift_stdlib_unicode_strToUpper(
dest, Int32(str._core.count),
str._core.startUTF16, Int32(str._core.count))
let correctSize = Int(z)
// If more space is needed, do it again with the correct buffer size.
if correctSize != str._core.count {
buffer = _StringBuffer(
capacity: correctSize, initialSize: correctSize, elementWidth: 2)
let dest = UnsafeMutablePointer<UTF16.CodeUnit>(buffer.start)
_swift_stdlib_unicode_strToUpper(
dest, Int32(correctSize), str._core.startUTF16, Int32(str._core.count))
}
return String(_storage: buffer)
}
#endif
// Unicode algorithms
extension String {
// FIXME: implement case folding without relying on Foundation.
// <rdar://problem/17550602> [unicode] Implement case folding
/// A "table" for which ASCII characters need to be upper cased.
/// To determine which bit corresponds to which ASCII character, subtract 1
/// from the ASCII value of that character and divide by 2. The bit is set iff
/// that character is a lower case character.
internal var _asciiLowerCaseTable: UInt64 {
@inline(__always)
get {
return 0b0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000_0000
}
}
/// The same table for upper case characters.
internal var _asciiUpperCaseTable: UInt64 {
@inline(__always)
get {
return 0b0000_0000_0000_0000_0001_1111_1111_1111_0000_0000_0000_0000_0000_0000_0000_0000
}
}
public var lowercaseString: String {
if self._core.isASCII {
let length = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: length, initialSize: length, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<length {
// For each character in the string, we lookup if it should be shifted
// in our ascii table, then we return 0x20 if it should, 0x0 if not.
// This code is equivalent to:
// switch source[i] {
// case let x where (x >= 0x41 && x <= 0x5a):
// dest[i] = x &+ 0x20
// case let x:
// dest[i] = x
// }
let value = source[i]
let isUpper =
_asciiUpperCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isUpper & 0x1) << 5
// Since we are left with either 0x0 or 0x20, we can safely truncate to
// a UInt8 and add to our ASCII value (this will not overflow numbers in
// the ASCII range).
dest[i] = value &+ UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringLowercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeLowercaseString(self)
#endif
}
public var uppercaseString: String {
if self._core.isASCII {
let length = self._core.count
let source = self._core.startASCII
let buffer = _StringBuffer(
capacity: length, initialSize: length, elementWidth: 1)
let dest = UnsafeMutablePointer<UInt8>(buffer.start)
for i in 0..<length {
// See the comment above in lowercaseString.
let value = source[i]
let isLower =
_asciiLowerCaseTable >>
UInt64(((value &- 1) & 0b0111_1111) >> 1)
let add = (isLower & 0x1) << 5
dest[i] = value &- UInt8(truncatingBitPattern: add)
}
return String(_storage: buffer)
}
#if _runtime(_ObjC)
return _cocoaStringToSwiftString_NonASCII(
_stdlib_NSStringUppercaseString(self._bridgeToObjectiveCImpl()))
#else
return _nativeUnicodeUppercaseString(self)
#endif
}
}
// Index conversions
extension String.Index {
/// Construct the position in `characters` that corresponds exactly to
/// `unicodeScalarIndex`. If no such position exists, the result is `nil`.
///
/// - Requires: `unicodeScalarIndex` is an element of
/// `characters.unicodeScalars.indices`.
public init?(
_ unicodeScalarIndex: String.UnicodeScalarIndex,
within characters: String
) {
if !unicodeScalarIndex._isOnGraphemeClusterBoundary {
return nil
}
self.init(_base: unicodeScalarIndex)
}
/// Construct the position in `characters` that corresponds exactly to
/// `utf16Index`. If no such position exists, the result is `nil`.
///
/// - Requires: `utf16Index` is an element of
/// `characters.utf16.indices`.
public init?(
_ utf16Index: String.UTF16Index,
within characters: String
) {
if let me = utf16Index.samePositionIn(
characters.unicodeScalars
)?.samePositionIn(characters) {
self = me
}
else {
return nil
}
}
/// Construct the position in `characters` that corresponds exactly to
/// `utf8Index`. If no such position exists, the result is `nil`.
///
/// - Requires: `utf8Index` is an element of
/// `characters.utf8.indices`.
public init?(
_ utf8Index: String.UTF8Index,
within characters: String
) {
if let me = utf8Index.samePositionIn(
characters.unicodeScalars
)?.samePositionIn(characters) {
self = me
}
else {
return nil
}
}
/// Return the position in `utf8` that corresponds exactly
/// to `self`.
///
/// - Requires: `self` is an element of `String(utf8).indices`.
@warn_unused_result
public func samePositionIn(
utf8: String.UTF8View
) -> String.UTF8View.Index {
return String.UTF8View.Index(self, within: utf8)
}
/// Return the position in `utf16` that corresponds exactly
/// to `self`.
///
/// - Requires: `self` is an element of `String(utf16).indices`.
@warn_unused_result
public func samePositionIn(
utf16: String.UTF16View
) -> String.UTF16View.Index {
return String.UTF16View.Index(self, within: utf16)
}
/// Return the position in `unicodeScalars` that corresponds exactly
/// to `self`.
///
/// - Requires: `self` is an element of `String(unicodeScalars).indices`.
@warn_unused_result
public func samePositionIn(
unicodeScalars: String.UnicodeScalarView
) -> String.UnicodeScalarView.Index {
return String.UnicodeScalarView.Index(self, within: unicodeScalars)
}
}
| apache-2.0 | be5a41e806e44b4a488aa2e6343a0498 | 30.864783 | 105 | 0.669105 | 4.09572 | false | false | false | false |
Havi4/Moya | Moya/Endpoint.swift | 3 | 2983 | import Foundation
import Alamofire
/// Used for stubbing responses.
public enum EndpointSampleResponse {
case Success(Int, () -> NSData)
case Error(Int?, NSError?, (() -> NSData)?)
case Closure(() -> EndpointSampleResponse)
func evaluate() -> EndpointSampleResponse {
switch self {
case Success, Error: return self
case Closure(let closure):
return closure().evaluate()
}
}
}
/// Class for reifying a target of the T enum unto a concrete Endpoint
public class Endpoint<T> {
public let URL: String
public let method: Moya.Method
public let sampleResponse: EndpointSampleResponse
public let parameters: [String: AnyObject]
public let parameterEncoding: Moya.ParameterEncoding
public let httpHeaderFields: [String: AnyObject]
/// Main initializer for Endpoint.
public init(URL: String, sampleResponse: EndpointSampleResponse, method: Moya.Method = Moya.Method.GET, parameters: [String: AnyObject] = [String: AnyObject](), parameterEncoding: Moya.ParameterEncoding = .URL, httpHeaderFields: [String: AnyObject] = [String: AnyObject]()) {
self.URL = URL
self.sampleResponse = sampleResponse
self.method = method
self.parameters = parameters
self.parameterEncoding = parameterEncoding
self.httpHeaderFields = httpHeaderFields
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added parameters.
public func endpointByAddingParameters(parameters: [String: AnyObject]) -> Endpoint<T> {
var newParameters = self.parameters ?? [String: AnyObject]()
for (key, value) in parameters {
newParameters[key] = value
}
return Endpoint(URL: URL, sampleResponse: sampleResponse, method: method, parameters: newParameters, parameterEncoding: parameterEncoding, httpHeaderFields: httpHeaderFields)
}
/// Convenience method for creating a new Endpoint with the same properties as the receiver, but with added HTTP header fields.
public func endpointByAddingHTTPHeaderFields(httpHeaderFields: [String: AnyObject]) -> Endpoint<T> {
var newHTTPHeaderFields = self.httpHeaderFields ?? [String: AnyObject]()
for (key, value) in httpHeaderFields {
newHTTPHeaderFields[key] = value
}
return Endpoint(URL: URL, sampleResponse: sampleResponse, method: method, parameters: parameters, parameterEncoding: parameterEncoding, httpHeaderFields: newHTTPHeaderFields)
}
}
/// Extension for converting an Endpoint into an NSURLRequest.
extension Endpoint {
public var urlRequest: NSURLRequest {
var request: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL)!)
request.HTTPMethod = method.method().rawValue
request.allHTTPHeaderFields = httpHeaderFields
return parameterEncoding.parameterEncoding().encode(request, parameters: parameters).0
}
}
| mit | af150dc21a742621f07dbc32e11fde81 | 42.867647 | 279 | 0.710359 | 5.365108 | false | false | false | false |
dfsilva/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/CocoaNetworkRuntime.swift | 1 | 4157 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
class CocoaNetworkRuntime : ARManagedNetworkProvider {
override init() {
super.init(factory: CocoaTcpConnectionFactory())
}
}
class CocoaTcpConnectionFactory: NSObject, ARAsyncConnectionFactory {
func createConnection(withConnectionId connectionId: jint,
with endpoint: ARConnectionEndpoint!,
with connectionInterface: ARAsyncConnectionInterface!) -> ARAsyncConnection! {
return CocoaTcpConnection(connectionId: Int(connectionId), endpoint: endpoint, connection: connectionInterface)
}
}
class CocoaTcpConnection: ARAsyncConnection, GCDAsyncSocketDelegate {
static let queue = DispatchQueue(label: "im.actor.network", attributes: [])
let READ_HEADER = 1
let READ_BODY = 2
var TAG: String!
var gcdSocket:GCDAsyncSocket? = nil
var header: Data?
init(connectionId: Int, endpoint: ARConnectionEndpoint!, connection: ARAsyncConnectionInterface!) {
super.init(endpoint: endpoint, with: connection)
TAG = "🎍ConnectionTcp#\(connectionId)"
}
override func doConnect() {
let endpoint = getEndpoint()
gcdSocket = GCDAsyncSocket(delegate: self, delegateQueue: CocoaTcpConnection.queue)
gcdSocket?.isIPv4PreferredOverIPv6 = false
do {
try self.gcdSocket!.connect(toHost: (endpoint?.host!)!, onPort: UInt16((endpoint?.port)!), withTimeout: Double(ARManagedConnection_CONNECTION_TIMEOUT) / 1000.0)
} catch _ {
}
}
// Affer successful connection
func socket(_ sock: GCDAsyncSocket!, didConnectToHost host: String!, port: UInt16) {
if (self.getEndpoint().type == ARConnectionEndpoint.type_TCP_TLS()) {
// NSLog("\(TAG) Starring TLS Session...")
sock.startTLS(nil)
} else {
startConnection()
}
}
// After TLS successful
func socketDidSecure(_ sock: GCDAsyncSocket!) {
// NSLog("\(TAG) TLS Session started...")
startConnection()
}
func startConnection() {
gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER)
onConnected()
}
// On connection closed
func socketDidDisconnect(_ sock: GCDAsyncSocket!, withError err: Error?) {
// NSLog("\(TAG) Connection closed...")
onClosed()
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
if (tag == READ_HEADER) {
// NSLog("\(TAG) Header received")
self.header = data
data.readUInt32(0) // IGNORE: package id
let size = data.readUInt32(5)
gcdSocket?.readData(toLength: UInt(size + 4), withTimeout: -1, tag: READ_BODY)
} else if (tag == READ_BODY) {
NSLog("\(TAG) Body received")
var package = Data()
package.append(self.header!)
package.append(data)
package.readUInt32(0) // IGNORE: package id
self.header = nil
onReceived(package.toJavaBytes())
gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER)
} else {
fatalError("Unknown tag in read data")
}
}
override func doClose() {
NSLog("\(TAG) Will try to close connection...")
if (gcdSocket != nil) {
NSLog("\(TAG) Closing connection...")
gcdSocket?.disconnect()
gcdSocket = nil
}
}
override func doSend(_ data: IOSByteArray!) {
gcdSocket?.write(data.toNSData(), withTimeout: -1, tag: 0)
}
}
private extension Data {
func readUInt32() -> UInt32 {
var raw: UInt32 = 0;
(self as NSData).getBytes(&raw, length: 4)
return raw.bigEndian
}
func readUInt32(_ offset: Int) -> UInt32 {
var raw: UInt32 = 0;
(self as NSData).getBytes(&raw, range: NSMakeRange(offset, 4))
return raw.bigEndian
}
}
| agpl-3.0 | ea426eb22cdaf2744faecb0863837940 | 31.20155 | 172 | 0.590756 | 4.819026 | false | false | false | false |
oleander/bitbar | Tests/BitBarTests/Helper/MockParent.swift | 1 | 511 | @testable import BitBar
import SwiftyBeaver
import Foundation
extension MenuEvent {
var log: SwiftyBeaver.Type {
return SwiftyBeaver.self
}
}
class MockParent: Hashable, GUI {
let queue: DispatchQueue = MockParent.newQueue(label: "MockParent")
var hashValue: Int {
return Int(bitPattern: ObjectIdentifier(self))
}
var log: SwiftyBeaver.Type {
return SwiftyBeaver.self
}
static func == (lhs: MockParent, rhs: MockParent) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
| mit | a7271f0ef723d588529cdbe49f598dd3 | 19.44 | 69 | 0.712329 | 4.023622 | false | false | false | false |
Rim21/BenchBudEEApp | BenchBudEE/BenchBudEE/BenchBudEEUUIDs.swift | 1 | 648 | //
// BenchBudEEUUIDs.swift
// BenchBudEE
//
// Created by Rim21 on 1/01/2015.
// Copyright (c) 2015 Nathan Rima. All rights reserved.
//
import CoreBluetooth
let BBSERVICE_UUID = "713D0000-503E-4C75-BA94-3148F18D941E"
let BB_READ_CHARACTERISTIC_UUID = "713D0002-503E-4C75-BA94-3148F18D941E"
let BB_WRITE_CHARACTERISTIC_UUID = "713D0003-503E-4C75-BA94-3148F18D941E"
let NOTIFY_MTU = 20
let BB_ServiceUUID:[AnyObject] = [CBUUID(string: BBSERVICE_UUID), CBUUID(string: "2220")]
let BB_Read_UUID:[AnyObject] = [CBUUID(string: BB_READ_CHARACTERISTIC_UUID), CBUUID(string: "2221")]
let BB_Write_UUID = CBUUID(string: BB_WRITE_CHARACTERISTIC_UUID) | mit | 5ef29bec8df5e2a7a2566f7d1aceb069 | 35.055556 | 100 | 0.748457 | 2.644898 | false | false | false | false |
linhaosunny/smallGifts | 小礼品/小礼品/Classes/Module/Main/NavigationController.swift | 1 | 1822 | //
// NavigationController.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/4/15.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
class NavigationController: UINavigationController {
//MARK: 懒加载
lazy var backBtn: UIButton = UIButton(backTarget: self, action: #selector(NavigationController.backBtnAction))
//MARK: 系统方法
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupNavigationBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: 私有方法
private func setupNavigationBar() {
self.interactivePopGestureRecognizer!.delegate = nil;
let appearance = UINavigationBar.appearance()
appearance.isTranslucent = false
appearance.setBackgroundImage(UIImage.image(withColor: SystemNavgationBackgroundColor, withSize: CGSize(width: 1, height: 1)), for: UIBarMetrics.default)
var textAttrs: [String : AnyObject] = Dictionary()
textAttrs[NSForegroundColorAttributeName] = UIColor.white
textAttrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 16)
appearance.titleTextAttributes = textAttrs
}
func backBtnAction() {
self.popViewController(animated: true)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
if self.childViewControllers.count > 0 {
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
}
| mit | 73e47314a8e2f13112537abe8b545f35 | 30.767857 | 161 | 0.689151 | 5.358434 | false | false | false | false |
xwu/swift | stdlib/public/Concurrency/TaskLocal.swift | 2 | 9493 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@_implementationOnly import _SwiftConcurrencyShims
/// Property wrapper that defines a task-local value key.
///
/// A task-local value is a value that can be bound and read in the context of a
/// `Task`. It is implicitly carried with the task, and is accessible by any
/// child tasks the task creates (such as TaskGroup or `async let` created tasks).
///
/// ### Task-local declarations
///
/// Task locals must be declared as static properties (or global properties,
/// once property wrappers support these), like this:
///
/// enum TracingExample {
/// @TaskLocal
/// static let traceID: TraceID?
/// }
///
/// ### Default values
/// Task local values of optional types default to `nil`. It is possible to define
/// not-optional task-local values, and an explicit default value must then be
/// defined instead.
///
/// The default value is returned whenever the task-local is read
/// from a context which either: has no task available to read the value from
/// (e.g. a synchronous function, called without any asynchronous function in its call stack),
///
///
/// ### Reading task-local values
/// Reading task local values is simple and looks the same as-if reading a normal
/// static property:
///
/// guard let traceID = TracingExample.traceID else {
/// print("no trace id")
/// return
/// }
/// print(traceID)
///
/// It is possible to perform task-local value reads from either asynchronous
/// or synchronous functions. Within asynchronous functions, as a "current" task
/// is always guaranteed to exist, this will perform the lookup in the task local context.
///
/// A lookup made from the context of a synchronous function, that is not called
/// from an asynchronous function (!), will immediately return the task-local's
/// default value.
///
/// ### Binding task-local values
/// Task local values cannot be `set` directly and must instead be bound using
/// the scoped `$traceID.withValue() { ... }` operation. The value is only bound
/// for the duration of that scope, and is available to any child tasks which
/// are created within that scope.
///
/// Detached tasks do not inherit task-local values, however tasks created using
/// the `Task { ... }` initializer do inherit task-locals by copying them to the
/// new asynchronous task, even though it is an un-structured task.
///
/// ### Examples
///
/// @TaskLocal
/// static var traceID: TraceID?
///
/// print("traceID: \(traceID)") // traceID: nil
///
/// $traceID.withValue(1234) { // bind the value
/// print("traceID: \(traceID)") // traceID: 1234
/// call() // traceID: 1234
///
/// Task { // unstructured tasks do inherit task locals by copying
/// call() // traceID: 1234
/// }
///
/// Task.detached { // detached tasks do not inherit task-local values
/// call() // traceID: nil
/// }
/// }
///
/// func call() {
/// print("traceID: \(traceID)") // 1234
/// }
///
/// This type must be a `class` so it has a stable identity, that is used as key
/// value for lookups in the task local storage.
@propertyWrapper
@available(SwiftStdlib 5.5, *)
public final class TaskLocal<Value: Sendable>: Sendable, CustomStringConvertible {
let defaultValue: Value
public init(wrappedValue defaultValue: Value) {
self.defaultValue = defaultValue
}
var key: Builtin.RawPointer {
unsafeBitCast(self, to: Builtin.RawPointer.self)
}
/// Gets the value currently bound to this task-local from the current task.
///
/// If no current task is available in the context where this call is made,
/// or if the task-local has no value bound, this will return the `defaultValue`
/// of the task local.
public func get() -> Value {
guard let rawValue = _taskLocalValueGet(key: key) else {
return self.defaultValue
}
// Take the value; The type should be correct by construction
let storagePtr =
rawValue.bindMemory(to: Value.self, capacity: 1)
return UnsafeMutablePointer<Value>(mutating: storagePtr).pointee
}
/// Binds the task-local to the specific value for the duration of the asynchronous operation.
///
/// The value is available throughout the execution of the operation closure,
/// including any `get` operations performed by child-tasks created during the
/// execution of the operation closure.
///
/// If the same task-local is bound multiple times, be it in the same task, or
/// in specific child tasks, the more specific (i.e. "deeper") binding is
/// returned when the value is read.
///
/// If the value is a reference type, it will be retained for the duration of
/// the operation closure.
@discardableResult
public func withValue<R>(_ valueDuringOperation: Value, operation: () async throws -> R,
file: String = #file, line: UInt = #line) async rethrows -> R {
// check if we're not trying to bind a value from an illegal context; this may crash
_checkIllegalTaskLocalBindingWithinWithTaskGroup(file: file, line: line)
_taskLocalValuePush(key: key, value: valueDuringOperation)
defer { _taskLocalValuePop() }
return try await operation()
}
/// Binds the task-local to the specific value for the duration of the
/// synchronous operation.
///
/// The value is available throughout the execution of the operation closure,
/// including any `get` operations performed by child-tasks created during the
/// execution of the operation closure.
///
/// If the same task-local is bound multiple times, be it in the same task, or
/// in specific child tasks, the "more specific" binding is returned when the
/// value is read.
///
/// If the value is a reference type, it will be retained for the duration of
/// the operation closure.
@discardableResult
public func withValue<R>(_ valueDuringOperation: Value, operation: () throws -> R,
file: String = #file, line: UInt = #line) rethrows -> R {
// check if we're not trying to bind a value from an illegal context; this may crash
_checkIllegalTaskLocalBindingWithinWithTaskGroup(file: file, line: line)
_taskLocalValuePush(key: key, value: valueDuringOperation)
defer { _taskLocalValuePop() }
return try operation()
}
public var projectedValue: TaskLocal<Value> {
get {
self
}
@available(*, unavailable, message: "use '$myTaskLocal.withValue(_:do:)' instead")
set {
fatalError("Illegal attempt to set a \(Self.self) value, use `withValue(...) { ... }` instead.")
}
}
// This subscript is used to enforce that the property wrapper may only be used
// on static (or rather, "without enclosing instance") properties.
// This is done by marking the `_enclosingInstance` as `Never` which informs
// the type-checker that this property-wrapper never wants to have an enclosing
// instance (it is impossible to declare a property wrapper inside the `Never`
// type).
@available(*, unavailable, message: "property wrappers cannot be instance members")
public static subscript(
_enclosingInstance object: Never,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<Never, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<Never, TaskLocal<Value>>
) -> Value {
get {
fatalError("Will never be executed, since enclosing instance is Never")
}
}
public var wrappedValue: Value {
self.get()
}
public var description: String {
"\(Self.self)(defaultValue: \(self.defaultValue))"
}
}
// ==== ------------------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_localValuePush")
func _taskLocalValuePush<Value>(
key: Builtin.RawPointer/*: Key*/,
value: __owned Value
) // where Key: TaskLocal
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_localValuePop")
func _taskLocalValuePop()
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_localValueGet")
func _taskLocalValueGet(
key: Builtin.RawPointer/*Key*/
) -> UnsafeMutableRawPointer? // where Key: TaskLocal
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_localsCopyTo")
func _taskLocalsCopy(
to target: Builtin.NativeObject
)
// ==== Checks -----------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
@usableFromInline
func _checkIllegalTaskLocalBindingWithinWithTaskGroup(file: String, line: UInt) {
if _taskHasTaskGroupStatusRecord() {
file.withCString { _fileStart in
_reportIllegalTaskLocalBindingWithinWithTaskGroup(
_fileStart, file.count, true, line)
}
}
}
@available(SwiftStdlib 5.5, *)
@usableFromInline
@_silgen_name("swift_task_reportIllegalTaskLocalBindingWithinWithTaskGroup")
func _reportIllegalTaskLocalBindingWithinWithTaskGroup(
_ _filenameStart: UnsafePointer<Int8>,
_ _filenameLength: Int,
_ _filenameIsASCII: Bool,
_ _line: UInt)
| apache-2.0 | b4addfee432da049022c690d06516b57 | 35.937743 | 102 | 0.668809 | 4.338665 | false | false | false | false |
RunningCharles/Arithmetic | src/8QuickSort.swift | 1 | 714 | #!/usr/bin/swift
func swap(_ values: inout [Int], _ i: Int, _ j: Int) {
if i == j { return }
let tmp = values[i]
values[i] = values[j]
values[j] = tmp
}
func quickSort(_ values: inout [Int], _ left: Int, _ right: Int) {
if left >= right { return }
let pivot = values[right]
var index = left
for i in left ..< right {
if values[i] < pivot {
swap(&values, index, i)
index += 1
}
}
swap(&values, index, right)
quickSort(&values, left, index - 1)
quickSort(&values, index + 1, right)
}
var values = [3,7,8,5,2,1,9,5,4]
print("start:", values)
quickSort(&values, 0, values.count - 1)
print("end:", values)
| bsd-3-clause | 8cbfb7cda7cb5e2386d07fcfa7e1b1f5 | 20.636364 | 66 | 0.526611 | 3.131579 | false | false | false | false |
royratcliffe/Snippets | Sources/UITableViewFetchedResultsController.swift | 1 | 10611 | // Snippets UITableViewFetchedResultsController.swift
//
// Copyright © 2015, 2016, Roy Ratcliffe, Pioneering Software, United Kingdom
//
// 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, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO
// EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//------------------------------------------------------------------------------
import UIKit
import CoreData
/// The controller cannot use Swift generics. Subclasses will still be able to
/// inherit from a generic class but Interface Builder will not be able to find
/// the subclass by name when instantiating a storyboard. For this reason, the
/// class uses the basic `NSFetchRequestResult` protocol for the fetch result
/// type which in turn inherits from `NSObjectProtocol`, and hence just
/// represents some basic `NSObject`.
open class UITableViewFetchedResultsController: UITableViewController, NSFetchedResultsControllerDelegate {
/// Use `prepareForSegue` to propagate the managed-object context. The
/// controller needs one.
public weak var managedObjectContext: NSManagedObjectContext!
/// Performs a fetch request using the fetched results controller. Aborts on
/// error, unless a Core Data error. Erases the fetched results controller
/// cache on Core Data errors, before retrying the fetch. Deletes all caches
/// if no specific cache. Aborts on Core Data errors if the second retry also
/// fails.
open func performFetch() {
// Disable error propagation.
do {
try fetchedResultsController.performFetch()
} catch let error as NSError {
NSLog("%@", error.localizedDescription)
abort()
} catch let error as CocoaError {
if error.code == CocoaError.Code.coreData {
NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: fetchedResultsController.cacheName)
do {
try fetchedResultsController.performFetch()
} catch {
NSLog("%@", error.localizedDescription)
abort()
}
}
}
}
/// De-initialises the controller. Exercises some retain-cycle paranoia by
/// disconnecting this view controller from the fetched-results
/// controller. The delegate reference is unowned and unsafe, not
/// weak. Therefore the delegate reference does not automatically become `nil`
/// when the view controller de-allocates from memory. There may be occasions
/// when an in-flight managed-object change notification from the fetch
/// controller tries to send change messages to the view controller when the
/// controller no longer exists. Prevent that from happening by explicitly
/// disconnecting the two controllers.
deinit {
dataSource.fetchedResultsController?.delegate = nil
}
//----------------------------------------------------------------------------
// MARK: - UI Table View Fetched Results Data Source
/// Gives public access to the data-source object so that controller
/// sub-classes can access the data source and set up blocks for mapping rows
/// to cell identifiers and configuring table cells using managed objects.
public let dataSource = UITableViewFetchedResultsDataSource<NSFetchRequestResult>()
// Delegate to the embedded data source.
/// Initialises the data source's fetched results controller if not already
/// set up. Uses user-defined run-time attributes to derive the entity
/// description and sort descriptor, and optionally also the section name
/// key-path and cache name.
open var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> {
if dataSource.fetchedResultsController == nil {
dataSource.fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: managedObjectContext,
sectionNameKeyPath: sectionNameKeyPath,
cacheName: cacheName)
dataSource.fetchedResultsController.delegate = self
}
return dataSource.fetchedResultsController
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.tableView(tableView, numberOfRowsInSection: section)
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return dataSource.tableView(tableView, cellForRowAt: indexPath)
}
open override func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.numberOfSections(in: tableView)
}
open override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return dataSource.tableView(tableView, titleForHeaderInSection: section)
}
//----------------------------------------------------------------------------
// MARK: - User-Defined Run-Time Attributes
@IBInspectable public var entityName: String!
@IBInspectable public var sortDescriptorKey: String!
@IBInspectable public var sortDescriptorAscending: Bool?
@IBInspectable public var sectionNameKeyPath: String?
@IBInspectable public var cacheName: String?
open var entity: NSEntityDescription? {
return NSEntityDescription.entity(forEntityName: entityName, in: managedObjectContext)
}
/// Constructs a fetch request based on the controller's user-defined run-time
/// attributes: its entity name, sort descriptor key and ascending flag. An
/// instance of `NSFetchedResultsController` requires a fetch request *with*
/// sort descriptors. Otherwise you will get an exception to that effect.
/// - returns: Answers a pre-configured fetch request.
open var fetchRequest: NSFetchRequest<NSFetchRequestResult> {
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entity
request.sortDescriptors = sortDescriptors
return request
}
/// Sort descriptors used by the fetch request.
open var sortDescriptors: [NSSortDescriptor] {
return [NSSortDescriptor(key: sortDescriptorKey, ascending: sortDescriptorAscending ?? true)]
}
//----------------------------------------------------------------------------
// MARK: - UI View Controller
// Sets up the table view data source and performs the initial pre-fetch. This
// assumes that you have already set up the cell-identifier-for-row and
// configure-cell-for-object blocks, or will do so soon before the table view
// starts to load.
open override func viewDidLoad() {
super.viewDidLoad()
if tableView.dataSource == nil {
tableView.dataSource = dataSource
}
performFetch()
}
//----------------------------------------------------------------------------
// MARK: - UI Table View Delegate
// Table view controllers automatically include the table view delegate
// protocol. Implement part of that protocol for setting up dynamic table row
// heights. Dequeue a non-indexed re-usable cell. Important that the cell is
// not dequeued with an index path because the dequeuing will otherwise
// recurse. Configure the cell and send back the height of the compressed
// fitting size. This relies on an explicit preferred width and constraints
// properly set up. If there are no constraints, use the cell's frame height.
open override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let cellIdentifier = dataSource.cellIdentifier(forRow: indexPath)
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) else {
return super.tableView(tableView, heightForRowAt: indexPath)
}
let object = dataSource.object(at: indexPath)
dataSource.configureCellForObjectBlock(cell, object)
guard !cell.constraints.isEmpty else {
return cell.frame.height
}
return cell.systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}
//----------------------------------------------------------------------------
// MARK: - Fetched Results Controller Delegate
open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .move:
if indexPath != newIndexPath {
tableView.moveRow(at: indexPath!, to: newIndexPath!)
}
case .update:
// Nothing to delete, nothing to insert.
tableView.reloadRows(at: [indexPath!], with: .fade)
}
}
open func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange sectionInfo: NSFetchedResultsSectionInfo,
atSectionIndex sectionIndex: Int,
for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections([sectionIndex], with: .fade)
case .delete:
tableView.deleteSections([sectionIndex], with: .fade)
case .move:
break
case .update:
break
}
}
open func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
open func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| mit | 7bee8a891eb8f75b1207099a16cf197f | 44.114894 | 114 | 0.688361 | 5.690821 | false | false | false | false |
klaus01/Centipede | Centipede/UIKit/CE_UIViewController.swift | 1 | 5532 | //
// CE_UIViewController.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import UIKit
extension UIViewController {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: UIViewController_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UIViewController_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: UIViewController_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.transitioningDelegate {
if obj is UIViewController_Delegate {
return obj as! UIViewController_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.transitioningDelegate = nil
self.transitioningDelegate = delegate
}
internal func getDelegateInstance() -> UIViewController_Delegate {
return UIViewController_Delegate()
}
@discardableResult
public func ce_animationController_forDismissed(handle: @escaping (UIViewController) -> UIViewControllerAnimatedTransitioning?) -> Self {
ce._animationController_forDismissed = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_animationController_forPresented(handle: @escaping (UIViewController, UIViewController, UIViewController) -> UIViewControllerAnimatedTransitioning?) -> Self {
ce._animationController_forPresented = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_interactionControllerForPresentation_using(handle: @escaping (UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?) -> Self {
ce._interactionControllerForPresentation_using = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_interactionControllerForDismissal_using(handle: @escaping (UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?) -> Self {
ce._interactionControllerForDismissal_using = handle
rebindingDelegate()
return self
}
@discardableResult
public func ce_presentationController_forPresented(handle: @escaping (UIViewController, UIViewController?, UIViewController) -> UIPresentationController?) -> Self {
ce._presentationController_forPresented = handle
rebindingDelegate()
return self
}
}
internal class UIViewController_Delegate: NSObject, UIViewControllerTransitioningDelegate {
var _animationController_forDismissed: ((UIViewController) -> UIViewControllerAnimatedTransitioning?)?
var _animationController_forPresented: ((UIViewController, UIViewController, UIViewController) -> UIViewControllerAnimatedTransitioning?)?
var _interactionControllerForPresentation_using: ((UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?)?
var _interactionControllerForDismissal_using: ((UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?)?
var _presentationController_forPresented: ((UIViewController, UIViewController?, UIViewController) -> UIPresentationController?)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(animationController(forDismissed:)) : _animationController_forDismissed,
#selector(animationController(forPresented:presenting:source:)) : _animationController_forPresented,
#selector(interactionControllerForPresentation(using:)) : _interactionControllerForPresentation_using,
#selector(interactionControllerForDismissal(using:)) : _interactionControllerForDismissal_using,
#selector(presentationController(forPresented:presenting:source:)) : _presentationController_forPresented,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return _animationController_forDismissed!(dismissed)
}
@objc func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return _animationController_forPresented!(presented, presenting, source)
}
@objc func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return _interactionControllerForPresentation_using!(animator)
}
@objc func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return _interactionControllerForDismissal_using!(animator)
}
@objc func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return _presentationController_forPresented!(presented, presenting, source)
}
}
| mit | 44bffd27a7c4a1bc0cf1e80959458071 | 46.264957 | 177 | 0.731465 | 6.276958 | false | false | false | false |
rokuz/omim | iphone/Maps/UI/Welcome/DeeplinkInfoViewController.swift | 2 | 1523 | protocol DeeplinkInfoViewControllerDelegate: AnyObject {
func deeplinkInfoViewControllerDidFinish(_ viewController: DeeplinkInfoViewController, deeplink: URL?)
}
class DeeplinkInfoViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var alertTitle: UILabel!
@IBOutlet weak var alertText: UILabel!
@IBOutlet weak var nextPageButton: UIButton!
var deeplinkURL: URL?
var delegate: DeeplinkInfoViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
guard let dlUrl = deeplinkURL, let host = dlUrl.host else { return }
switch host {
case "guides_page":
alertTitle.text = L("onboarding_guide_direct_download_title")
alertText.text = L("onboarding_guide_direct_download_subtitle")
nextPageButton.setTitle(L("onboarding_guide_direct_download_button"), for: .normal)
case "catalogue":
alertTitle.text = L("onboarding_bydeeplink_guide_title")
alertText.text = L("onboarding_bydeeplink_guide_subtitle")
nextPageButton.setTitle(L("current_location_unknown_continue_button"), for: .normal)
default:
break
}
Statistics.logEvent(kStatOnboardingDlShow, withParameters: [kStatType : host])
}
@IBAction func onNextButton(_ sender: UIButton) {
delegate?.deeplinkInfoViewControllerDidFinish(self, deeplink: deeplinkURL)
guard let dlUrl = deeplinkURL, let host = dlUrl.host else { return }
Statistics.logEvent(kStatOnboardingDlAccept, withParameters: [kStatType : host])
}
}
| apache-2.0 | 733014d6d042e0a7c7a0c416b49e6b99 | 38.051282 | 104 | 0.744583 | 4.532738 | false | false | false | false |
alex-alex/S2Geometry | Sources/S1Interval.swift | 1 | 11131 | //
// S1Interval.swift
// S2Geometry
//
// Created by Alex Studnicka on 7/1/16.
// Copyright © 2016 Alex Studnicka. MIT License.
//
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/**
An S1Interval represents a closed interval on a unit circle (also known as a
1-dimensional sphere). It is capable of representing the empty interval
(containing no points), the full interval (containing all points), and
zero-length intervals (containing a single point).
Points are represented by the angle they make with the positive x-axis in
the range [-Pi, Pi]. An interval is represented by its lower and upper bounds
(both inclusive, since the interval is closed). The lower bound may be
greater than the upper bound, in which case the interval is "inverted" (i.e.
it passes through the point (-1, 0)).
Note that the point (-1, 0) has two valid representations, Pi and -Pi. The
normalized representation of this point internally is Pi, so that endpoints
of normal intervals are in the range (-Pi, Pi]. However, we take advantage of
the point -Pi to construct two special intervals: the Full() interval is
[-Pi, Pi], and the Empty() interval is [Pi, -Pi].
*/
public struct S1Interval: Equatable {
public let lo: Double
public let hi: Double
/**
Both endpoints must be in the range -Pi to Pi inclusive. The value -Pi is
converted internally to Pi except for the Full() and Empty() intervals.
*/
public init(lo: Double, hi: Double) {
self.init(lo: lo, hi: hi, checked: false)
}
/**
Internal constructor that assumes that both arguments are in the correct
range, i.e. normalization from -Pi to Pi is already done.
*/
private init(lo: Double, hi: Double, checked: Bool) {
var newLo = lo
var newHi = hi
if !checked {
if lo == -M_PI && hi != M_PI {
newLo = M_PI
}
if hi == -M_PI && lo != M_PI {
newHi = M_PI
}
}
self.lo = newLo
self.hi = newHi
}
public static let empty = S1Interval(lo: M_PI, hi: -M_PI, checked: true)
public static let full = S1Interval(lo: -M_PI, hi: M_PI, checked: true)
/// Convenience method to construct an interval containing a single point.
public init(point p: Double) {
var p = p
if p == -M_PI { p = M_PI }
self.init(lo: p, hi: p)
}
/**
Convenience method to construct the minimal interval containing the two
given points. This is equivalent to starting with an empty interval and
calling AddPoint() twice, but it is more efficient.
*/
public init(p1: Double, p2: Double) {
var p1 = p1, p2 = p2
if p1 == -M_PI { p1 = M_PI }
if p2 == -M_PI { p2 = M_PI }
if S1Interval.positiveDistance(p1, p2) <= M_PI {
self.init(lo: p1, hi: p2, checked: true)
} else {
self.init(lo: p2, hi: p1, checked: true)
}
}
/**
An interval is valid if neither bound exceeds Pi in absolute value, and the
value -Pi appears only in the empty and full intervals.
*/
public var isValid: Bool {
return (abs(lo) <= M_PI && abs(hi) <= M_PI && !(lo == -M_PI && hi != M_PI) && !(hi == -M_PI && lo != M_PI))
}
/// Return true if the interval contains all points on the unit circle.
public var isFull: Bool {
return hi - lo == 2 * M_PI
}
/// Return true if the interval is empty, i.e. it contains no points.
public var isEmpty: Bool {
return lo - hi == 2 * M_PI
}
/// Return true if lo() > hi(). (This is true for empty intervals.)
public var isInverted: Bool {
return lo > hi
}
/// Return the midpoint of the interval. For full and empty intervals, the result is arbitrary.
public var center: Double {
let center = 0.5 * (lo + hi)
if !isInverted { return center }
// Return the center in the range (-Pi, Pi].
return (center <= 0) ? (center + M_PI) : (center - M_PI)
}
/// Return the length of the interval. The length of an empty interval is negative.
public var length: Double {
var length = hi - lo
if length >= 0 { return length }
length += 2 * M_PI
// Empty intervals have a negative length.
return (length > 0) ? length : -1
}
/**
Return the complement of the interior of the interval. An interval and its
complement have the same boundary but do not share any interior values. The
complement operator is not a bijection, since the complement of a singleton
interval (containing a single value) is the same as the complement of an
empty interval.
*/
public var complement: S1Interval {
if lo == hi {
return S1Interval.full // Singleton.
} else {
return S1Interval(lo: hi, hi: lo, checked: true) // Handles empty and full.
}
}
/// Return true if the interval (which is closed) contains the point 'p'.
public func contains(point p: Double) -> Bool {
// Works for empty, full, and singleton intervals.
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if (p == -M_PI) { p = M_PI }
return fastContains(point: p)
}
/**
Return true if the interval (which is closed) contains the point 'p'. Skips
the normalization of 'p' from -Pi to Pi.
*/
public func fastContains(point p: Double) -> Bool {
if isInverted {
return (p >= lo || p <= hi) && !isEmpty
} else {
return p >= lo && p <= hi
}
}
/// Return true if the interval contains the given interval 'y'. Works for empty, full, and singleton intervals.
public func contains(interval y: S1Interval) -> Bool {
// It might be helpful to compare the structure of these tests to
// the simpler Contains(double) method above.
if isInverted {
if y.isInverted {
return y.lo >= lo && y.hi <= hi
}
return (y.lo >= lo || y.hi <= hi) && !isEmpty
} else {
if y.isInverted {
return isFull || y.isEmpty
}
return y.lo >= lo && y.hi <= hi
}
}
/**
Returns true if the interior of this interval contains the entire interval
'y'. Note that x.InteriorContains(x) is true only when x is the empty or
full interval, and x.InteriorContains(S1Interval(p,p)) is equivalent to
x.InteriorContains(p).
*/
public func interiorContains(interval y: S1Interval) -> Bool {
if isInverted {
if !y.isInverted {
return y.lo > lo || y.hi < hi
}
return (y.lo > lo && y.hi < hi) || y.isEmpty
} else {
if y.isInverted {
return isFull || y.isEmpty
}
return (y.lo > lo && y.hi < hi) || isFull
}
}
/// Return true if the interior of the interval contains the point 'p'.
public func interiorContains(point p: Double) -> Bool {
// Works for empty, full, and singleton intervals.
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if (p == -M_PI) { p = M_PI }
if isInverted {
return p > lo || p < hi
} else {
return (p > lo && p < hi) || isFull
}
}
/**
Return true if the two intervals contain any points in common. Note that
the point +/-Pi has two representations, so the intervals [-Pi,-3] and
[2,Pi] intersect, for example.
*/
public func intersects(with y: S1Interval) -> Bool {
if isEmpty || y.isEmpty {
return false
}
if isInverted {
// Every non-empty inverted interval contains Pi.
return y.isInverted || y.lo <= hi || y.hi >= lo
} else {
if y.isInverted {
return y.lo <= hi || y.hi >= lo
}
return y.lo <= hi && y.hi >= lo
}
}
/**
Return true if the interior of this interval contains any point of the
interval 'y' (including its boundary). Works for empty, full, and singleton
intervals.
*/
public func interiorIntersects(with y: S1Interval) -> Bool {
if isEmpty || y.isEmpty || lo == hi {
return false
}
if isInverted {
return y.isInverted || y.lo < hi || y.hi > lo
} else {
if y.isInverted {
return y.lo < hi || y.hi > lo
}
return (y.lo < hi && y.hi > lo) || isFull
}
}
/**
Expand the interval by the minimum amount necessary so that it contains the
given point "p" (an angle in the range [-Pi, Pi]).
*/
public func add(point p: Double) -> S1Interval {
// assert (Math.abs(p) <= S2.M_PI);
var p = p
if p == -M_PI {
p = M_PI
}
if fastContains(point: p) {
return self
}
if isEmpty {
return S1Interval(point: p)
} else {
// Compute distance from p to each endpoint.
let dlo = S1Interval.positiveDistance(p, lo)
let dhi = S1Interval.positiveDistance(hi, p)
if dlo < dhi {
return S1Interval(lo: p, hi: hi)
} else {
return S1Interval(lo: lo, hi: p)
}
// Adding a point can never turn a non-full interval into a full one.
}
}
/**
Return an interval that contains all points within a distance "radius" of
a point in this interval. Note that the expansion of an empty interval is
always empty. The radius must be non-negative.
*/
public func expanded(radius: Double) -> S1Interval {
// assert (radius >= 0)
guard !isEmpty else { return self }
// Check whether this interval will be full after expansion, allowing
// for a 1-bit rounding error when computing each endpoint.
if length + 2 * radius >= 2 * M_PI - 1e-15 {
return .full
}
// NOTE(dbeaumont): Should this remainder be 2 * M_PI or just M_PI ??
var lo = remainder(self.lo - radius, 2 * M_PI)
let hi = remainder(self.hi + radius, 2 * M_PI)
if lo == -M_PI {
lo = M_PI
}
return S1Interval(lo: lo, hi: hi)
}
/// Return the smallest interval that contains this interval and the given interval "y".
public func union(with y: S1Interval) -> S1Interval {
// The y.is_full() case is handled correctly in all cases by the code
// below, but can follow three separate code paths depending on whether
// this interval is inverted, is non-inverted but contains Pi, or neither.
if y.isEmpty {
return self
}
if fastContains(point: y.lo) {
if fastContains(point: y.hi) {
// Either this interval contains y, or the union of the two
// intervals is the Full() interval.
if contains(interval: y) {
return self // is_full() code path
}
return .full
}
return S1Interval(lo: lo, hi: y.hi, checked: true)
}
if (fastContains(point: y.hi)) {
return S1Interval(lo: y.lo, hi: hi, checked: true)
}
// This interval contains neither endpoint of y. This means that either y
// contains all of this interval, or the two intervals are disjoint.
if isEmpty || y.fastContains(point: lo) {
return y
}
// Check which pair of endpoints are closer together.
let dlo = S1Interval.positiveDistance(y.hi, lo)
let dhi = S1Interval.positiveDistance(hi, y.lo)
if dlo < dhi {
return S1Interval(lo: y.lo, hi: hi, checked: true)
} else {
return S1Interval(lo: lo, hi: y.hi, checked: true)
}
}
/**
Compute the distance from "a" to "b" in the range [0, 2*Pi). This is
equivalent to (drem(b - a - S2.M_PI, 2 * S2.M_PI) + S2.M_PI), except that
it is more numerically stable (it does not lose precision for very small
positive distances).
*/
public static func positiveDistance(_ a: Double, _ b: Double) -> Double {
let d = b - a
if d >= 0 { return d }
// We want to ensure that if b == Pi and a == (-Pi + eps),
// the return result is approximately 2*Pi and not zero.
return (b + M_PI) - (a - M_PI)
}
}
public func ==(lhs: S1Interval, rhs: S1Interval ) -> Bool {
return (lhs.lo == rhs.lo && lhs.hi == rhs.hi) || (lhs.isEmpty && rhs.isEmpty)
}
| mit | 4d4570a06674050f4cd62a854a2c6477 | 29 | 113 | 0.645642 | 3.131683 | false | false | false | false |
travelish/SwiftNats | Sources/Connection.swift | 1 | 10697 | //
// Connection.swift
// SwiftNats
//
// Created by kakilangit on 1/21/16.
// Copyright © 2016 Travelish. All rights reserved.
//
// http://nats.io/documentation/internals/nats-protocol/
import Foundation
open class Nats: NSObject, StreamDelegate {
open var queue = DispatchQueue.main
open weak var delegate: NatsDelegate?
let version = "3.0.0-alpha.1"
let lang = "swift"
let name = "SwiftNats"
let MaxFrameSize: Int = 32
fileprivate var server: Server?
fileprivate var subscriptions = [NatsSubscription]()
fileprivate var id: String?
fileprivate var outputStream: OutputStream?
fileprivate var inputStream: InputStream?
fileprivate var writeQueue = OperationQueue()
fileprivate var connected: Bool = false
fileprivate var counter: UInt32 = 0
fileprivate var url: URL!
fileprivate var verbose: Bool = true
fileprivate var pedantic: Bool = false
fileprivate var isRunLoop: Bool = false
open var connectionId: String? {
return id
}
open var isConnected: Bool {
return connected
}
/**
* ================
* Public Functions
* ================
*/
public init(url: String, verbose: Bool = true, pedantic: Bool = false) {
self.url = URL(string: url)!
self.verbose = verbose
self.pedantic = pedantic
writeQueue.maxConcurrentOperationCount = 1
}
open func option(_ url: String, verbose: Bool = true, pedantic: Bool = false) {
self.url = URL(string: url)!
self.verbose = verbose
self.pedantic = pedantic
}
/**
* connect() -> Void
* make connection
*
*/
open func connect() {
self.open()
guard let newReadStream = inputStream, let newWriteStream = outputStream else { return }
guard isConnected else { return }
for stream in [newReadStream, newWriteStream] {
stream.delegate = self
stream.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
}
// NSRunLoop
RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date.distantFuture as Date)
}
/**
* reconnect() -> Void
* make connection
*
*/
open func reconnect(_ url: String, verbose: Bool = true, pedantic: Bool = false) {
self.option(url, verbose: verbose, pedantic: pedantic)
guard !isConnected else {
didDisconnect(nil)
self.reconnect(url, verbose: verbose, pedantic: pedantic)
return
}
self.connect()
}
/**
* disconnect() -> Void
* close connection
*
*/
open func disconnect() {
didDisconnect(nil)
}
/**
* subscribe(subject: String, queueGroup: String = "") -> Void
* subscribe to subject
*
*/
open func subscribe(_ subject: String, queueGroup: String = "") -> Void {
guard subscriptions.filter({ $0.subject == subject }).count == 0 else { return }
let sub = NatsSubscription(id: String.randomize("SUB_", length: 10), subject: subject, queueGroup: queueGroup, count: 0)
subscriptions.append(sub)
sendText(sub.sub())
}
/**
* unsubscribe(subject: String) -> Void
* unsubscribe from subject
*
*/
open func unsubscribe(_ subject: String, max: UInt32 = 0) {
guard let sub = subscriptions.filter({ $0.subject == subject }).first else { return }
subscriptions = subscriptions.filter({ $0.id != sub.id })
sendText(sub.unsub(max))
}
/**
* publish(subject: String) -> Void
* publish to subject
*
*/
open func publish(_ subject: String, payload: String) {
let pub: () -> String = {
if let data = payload.data(using: String.Encoding.utf8) {
return "\(Proto.PUB.rawValue) \(subject) \(data.count)\r\n\(payload)\r\n"
}
return ""
}
sendText(pub())
}
/**
* reply(subject: String, replyto: String, payload: String) -> Void
* reply to id in subject
*
*/
open func reply(_ subject: String, replyto: String, payload: String) {
let response: () -> String = {
if let data = payload.data(using: String.Encoding.utf8) {
return "\(Proto.PUB.rawValue) \(subject) \(replyto) \(data.count)\r\n\(payload)\r\n"
}
return ""
}
sendText(response())
}
// NSStreamDelegate
open func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch aStream {
case inputStream!:
switch eventCode {
case [.hasBytesAvailable]:
if let string = inputStream?.readStream()?.toString() {
dispatchInputStream(string)
}
break
case [.errorOccurred]:
didDisconnect(inputStream?.streamError as NSError?)
break
case [.endEncountered]:
didDisconnect(inputStream?.streamError as NSError?)
break
default:
break
}
default:
break
}
}
/**
* =================
* Private Functions
* =================
*/
/*
* open() -> Void
* open stream connection
* set server
* blocking, read & write stream in loop
*
*/
fileprivate func open() {
guard !isConnected else { return }
guard let host = url.host, let port = url.port else { return }
var readStream: Unmanaged<CFReadStream>?
var writeStream: Unmanaged<CFWriteStream>?
CFStreamCreatePairWithSocketToHost(nil, host as CFString!, UInt32(port), &readStream, &writeStream) // -> send
inputStream = readStream!.takeRetainedValue()
outputStream = writeStream!.takeRetainedValue()
guard let inStream = inputStream, let outStream = outputStream else { return }
inStream.open()
outStream.open()
if let info = inStream.readStreamLoop() { // <- receive
if info.hasPrefix(Proto.INFO.rawValue) {
if let config = info.flattenedMessage().removePrefix(Proto.INFO.rawValue).convertToDictionary() {
self.server = Server(data: config)
self.authorize(outStream, inStream)
}
}
}
}
/**
* authorize(outStream: NSOutputStream, _ inStream: NSInputStream) -> Void
* blocking, read & write stream in loop
*
*/
fileprivate func authorize(_ outStream: OutputStream, _ inStream: InputStream) {
do {
guard let srv = self.server else {
throw NSError(domain: NSURLErrorDomain, code: 400, userInfo: [NSLocalizedDescriptionKey: "Invalid Server"])
}
if !srv.authRequired {
didConnect()
return
}
guard let user = self.url?.user, let password = self.url?.password else {
throw NSError(domain: NSURLErrorDomain, code: 400, userInfo: [NSLocalizedDescriptionKey: "User/Password Required"])
}
let config = [
"verbose": self.verbose,
"pedantic": self.pedantic,
"ssl_required": srv.sslRequired,
"name": self.name,
"lang": self.lang,
"version": self.version,
"user": user,
"pass": password
] as [String : Any]
let configData = try JSONSerialization.data(withJSONObject: config, options: [])
if let configString = configData.toString() {
if let data = "\(Proto.CONNECT.rawValue) \(configString)\r\n".data(using: String.Encoding.utf8) {
outStream.writeStreamLoop(data) // -> send
if let info = inStream.readStreamLoop() { // <- receive
if info.hasPrefix(Proto.ERR.rawValue) {
let err = info.removePrefix(Proto.ERR.rawValue)
didDisconnect(NSError(domain: NSURLErrorDomain, code: 400, userInfo: [NSLocalizedDescriptionKey: err]))
} else {
didConnect()
}
}
}
}
} catch let error as NSError {
didDisconnect(error)
}
}
/**
* didConnect() -> Void
* set self.connection state
* delegate didConnect
* non blocking
*
*/
fileprivate func didConnect() {
self.id = String.randomize("CONN_", length: 10)
self.connected = true
queue.async { [weak self] in
guard let s = self else { return }
s.delegate?.natsDidConnect(nats:s)
}
}
/**
* didDisconnect() -> Void
* set self.connection state
* delegate didDisconnect
* non blocking
*
*/
fileprivate func didDisconnect(_ err: NSError?) {
self.connected = false
queue.async { [weak self] in
guard let s = self else { return }
guard let newReadStream = s.inputStream, let newWriteStream = s.outputStream else { return }
for stream in [newReadStream, newWriteStream] {
stream.delegate = nil
stream.remove(from: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
stream.close()
}
s.delegate?.natsDidDisconnect(nats:s, error: err)
}
}
/**
* sendData(data: NSData) -> Void
* write data to output stream
*
*/
fileprivate func sendData(_ data: Data) {
guard isConnected else { return }
writeQueue.addOperation { [weak self] in
guard let s = self else { return }
guard let stream = s.outputStream else { return }
stream.writeStreamLoop(data)
}
}
/**
* sendText(text: String) -> Void
* write string to output stream
*
*/
fileprivate func sendText(_ text: String) {
if let data = text.data(using: String.Encoding.utf8) {
sendData(data)
}
}
/**
* dispatchInputStream(msg: String) -> Void
* routing received message from NSStreamDelegate
*
*/
fileprivate func dispatchInputStream(_ msg: String) {
if msg.hasPrefix(Proto.PING.rawValue) {
processPing()
} else if msg.hasPrefix(Proto.OK.rawValue) {
processOk(msg)
} else if msg.hasPrefix(Proto.ERR.rawValue) {
processErr(msg.removePrefix(Proto.ERR.rawValue))
} else if msg.hasPrefix(Proto.MSG.rawValue) {
processMessage(msg)
}
}
/**
* processMessage(msg: String) -> Void
* processMessage
*
*/
fileprivate func processMessage(_ msg: String) {
let components = msg.components(separatedBy: CharacterSet.newlines).filter { !$0.isEmpty }
guard components.count > 0 else { return }
let header = components[0]
.removePrefix(Proto.MSG.rawValue)
.components(separatedBy: CharacterSet.whitespaces)
.filter { !$0.isEmpty }
let subject = header[0]
// let sid = UInt32(header[1])
// var byte = UInt32(header[2])
var payload: String?
var reply: String?
if components.count == 2 {
payload = components[1]
}
if header.count > 3 {
reply = header[2]
// byte = UInt32(header[3])
}
var sub = subscriptions.filter({ $0.subject == subject }).first
guard sub != nil else { return }
sub!.counter()
subscriptions = subscriptions.filter({ $0.subject != sub!.subject })
subscriptions.append(sub!)
let message = NatsMessage(subject: sub!.subject, count: sub!.count, reply: reply, payload: payload)
queue.async { [weak self] in
guard let s = self else { return }
s.delegate?.natsDidReceiveMessage(nats:s, msg: message)
}
}
/**
* processOk(msg: String) -> Void
* +OK
*
*/
fileprivate func processOk(_ msg: String) {
print("processOk \(msg)")
}
/**
* processErr(msg: String) -> Void
* -ERR
*
*/
fileprivate func processErr(_ msg: String) {
print("processErr \(msg)")
}
/**
* processPing() -> Void
* PING keep-alive message
* PONG keep-alive response
*
*/
fileprivate func processPing() {
sendText(Proto.PONG.rawValue)
}
}
| mit | 504526da8962de6abe17c071829433ce | 23.364465 | 122 | 0.659405 | 3.554669 | false | false | false | false |
funnyordie/TimeAgoInWords | TimeAgoInWords.swift | 1 | 6653 | //
// TimeAgoInWords.swift
// Ello
//
// Created by Ryan Boyajian on 4/2/15.
// Copyright (c) 2015 Ello. All rights reserved.
//
import Foundation
public class TimeAgoInWords {
}
private let table = "TimeAgoInWords"
private let resourceBundle: NSBundle = {
let thisBundle = NSBundle(forClass: TimeAgoInWords.self)
let bundlePath = thisBundle.pathForResource("TimeAgoInWords", ofType: "bundle")
let bundle = NSBundle(path: bundlePath!)
return bundle!
}()
public struct TimeAgoInWordsStrings {
static var LessThan = NSLocalizedString("less-than", tableName: table, bundle: resourceBundle, comment: "Indicates a less-than number")
static var About = NSLocalizedString("approximate", tableName: table, bundle: resourceBundle, comment: "Indicates an approximate number")
static var Over = NSLocalizedString("exceeding", tableName: table, bundle: resourceBundle, comment: "Indicates an exceeding number")
static var Almost = NSLocalizedString("approaching", tableName: table, bundle: resourceBundle, comment: "Indicates an approaching number")
static var Seconds = NSLocalizedString("seconds", tableName: table, bundle: resourceBundle, comment: "More than one second in time")
static var Minute = NSLocalizedString("one-minute", tableName: table, bundle: resourceBundle, comment: "One minute in time")
static var Minutes = NSLocalizedString("minutes", tableName: table, bundle: resourceBundle, comment: "More than one minute in time")
static var Hour = NSLocalizedString("one-hour", tableName: table, bundle: resourceBundle, comment: "One hour in time")
static var Hours = NSLocalizedString("hours", tableName: table, bundle: resourceBundle, comment: "More than one hour in time")
static var Day = NSLocalizedString("one-day", tableName: table, bundle: resourceBundle, comment: "One day in time")
static var Days = NSLocalizedString("days", tableName: table, bundle: resourceBundle, comment: "More than one day in time")
static var Month = NSLocalizedString("month", tableName: table, bundle: resourceBundle, comment:"One month in time")
static var Months = NSLocalizedString("months", tableName: table, bundle: resourceBundle, comment: "More than one month in time")
static var Year = NSLocalizedString("year", tableNmae: table, bundle: resourceBundle, comment:"One year in time")
static var Years = NSLocalizedString("years", tableName: table, bundle: resourceBundle, comment: "More than one year in time")
static public func updateStrings(dict: [String: String]) {
for (key, value) in dict {
switch key.lowercaseString {
case "lessthan": LessThan = value
case "about": About = value
case "over": Over = value
case "almost": Almost = value
case "seconds": Seconds = value
case "minute": Minute = value
case "minutes": Minutes = value
case "hour": Hour = value
case "hours": Hours = value
case "day": Day = value
case "days": Days = value
case "month": Month = value
case "months": Months = value
case "year": Year = value
case "years": Years = value
default: print("TimeAgoInWordsStrings.updateStrings key \(key) is not supported.")
}
}
}
}
public extension NSDate {
func distanceOfTimeInWords(toDate:NSDate) -> String {
let MINUTES_IN_YEAR = 525_600.0
let MINUTES_IN_QUARTER_YEAR = 131_400.0
let MINUTES_IN_THREE_QUARTERS_YEAR = 394_200.0
let distanceInSeconds = round(abs(toDate.timeIntervalSinceDate(self)))
let distanceInMinutes = round(distanceInSeconds / 60.0)
let distanceInMonths = (Int(round(distanceInMinutes / 43_200.0)))
switch distanceInMinutes {
case 0...1:
switch distanceInSeconds {
case 0...4:
return TimeAgoInWordsStrings.LessThan + "5" + TimeAgoInWordsStrings.Seconds
case 5...9:
return TimeAgoInWordsStrings.LessThan + "10" + TimeAgoInWordsStrings.Seconds
case 10...19:
return TimeAgoInWordsStrings.LessThan + "20" + TimeAgoInWordsStrings.Seconds
case 20...39:
return "30" + TimeAgoInWordsStrings.Seconds
case 40...59:
return TimeAgoInWordsStrings.LessThan + "1" + TimeAgoInWordsStrings.Minute
default:
return "1" + TimeAgoInWordsStrings.Minute
}
case 2...45:
return "\(Int(round(distanceInMinutes)))" + TimeAgoInWordsStrings.Minutes
case 45...90:
return TimeAgoInWordsStrings.About + "1" + TimeAgoInWordsStrings.Hour
// 90 mins up to 24 hours
case 90...1_440:
return TimeAgoInWordsStrings.About + "\(Int(round(distanceInMinutes / 60.0)))" + TimeAgoInWordsStrings.Hours
// 24 hours up to 42 hours
case 1_440...2_520:
return "1" + TimeAgoInWordsStrings.Day
// 42 hours up to 30 days
case 2_520...43_200:
return "\(Int(round(distanceInMinutes / 1_440.0)))" + TimeAgoInWordsStrings.Days
// 30 days up to 60 days
case 43_200...86_400:
return TimeAgoInWordsStrings.About + "\(distanceInMonths)" + (distanceInMonths == 1 ? TimeAgoInWordsStrings.Month : TimeAgoInWordsStrings.Months)
// 60 days up to 365 days
case 86_400...525_600:
return "\(distanceInMonths)" + (distanceInMonths == 1 ? TimeAgoInWordsStrings.Month : TimeAgoInWordsStrings.Months)
// TODO: handle leap year like rails does
default:
let remainder = distanceInMinutes % MINUTES_IN_YEAR
let distanceInYears = Int(floor(distanceInMinutes / MINUTES_IN_YEAR))
if remainder < MINUTES_IN_QUARTER_YEAR {
return TimeAgoInWordsStrings.About + "\(distanceInYears)" + (distanceInYears == 1 ? TimeAgoInWordsStrings.Year : TimeAgoInWordsStrings.Years)
}
else if remainder < MINUTES_IN_THREE_QUARTERS_YEAR {
return TimeAgoInWordsStrings.Over + "\(distanceInYears)" + (distanceInYears == 1 ? TimeAgoInWordsStrings.Year : TimeAgoInWordsStrings.Years)
}
else {
return TimeAgoInWordsStrings.Almost + "\(distanceInYears + 1)" + (distanceInYears == 0 ? TimeAgoInWordsStrings.Year : TimeAgoInWordsStrings.Years)
}
}
}
func timeAgoInWords() -> String {
return self.distanceOfTimeInWords(NSDate())
}
}
| mit | fe7fbcb1f6ff348686081cc45fe885c2 | 50.976563 | 162 | 0.649932 | 4.314527 | false | false | false | false |
camdenfullmer/UnsplashSwift | Tests/MockedURLProtocol.swift | 1 | 2246 | // MockedURLProtocol.swift
//
// Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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
class MockedURLProtocol : NSURLProtocol {
static var responseData : NSData?
static var statusCode : Int?
override static func canInitWithRequest(request: NSURLRequest) -> Bool {
return request.URL?.scheme == "https" && request.URL?.host == "api.unsplash.com"
}
override func startLoading() {
let request = self.request
let client = self.client
let response = NSHTTPURLResponse(
URL: request.URL!,
statusCode: MockedURLProtocol.statusCode!,
HTTPVersion: "HTTP/1.1",
headerFields: nil)
client?.URLProtocol(self, didReceiveResponse: response!, cacheStoragePolicy:.NotAllowed)
if let data = MockedURLProtocol.responseData {
client?.URLProtocol(self, didLoadData: data)
}
client?.URLProtocolDidFinishLoading(self)
}
override func stopLoading() {
}
override static func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
} | mit | 5ed39475855e13403344a3a65c08b086 | 39.125 | 96 | 0.703473 | 4.90393 | false | false | false | false |
lorentey/Attabench | BenchmarkModel/Timestamp.swift | 2 | 842 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Darwin
import BigInt
public struct Timestamp {
let tick: UInt64
public init() {
self.tick = mach_absolute_time()
}
}
private let timeInfo: mach_timebase_info = {
var info = mach_timebase_info()
guard mach_timebase_info(&info) == KERN_SUCCESS else { fatalError("Can't get mach_timebase_info") }
guard info.denom > 0 else { fatalError("mach_timebase_info.denom == 0") }
return info
}()
public func -(left: Timestamp, right: Timestamp) -> Time {
let elapsed = BigInt(left.tick) - BigInt(right.tick)
return Time(picoseconds: elapsed * 1000 * BigInt(timeInfo.numer) / BigInt(timeInfo.denom))
}
| mit | 0fdcfd9ac292fe381d9031a830f6645e | 31.269231 | 103 | 0.693683 | 3.728889 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Logging/TurnTimer.swift | 1 | 1963 | //
// TurnTimer.swift
// HSTracker
//
// Created by Benjamin Michotte on 12/03/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
import CleanroomLogger
@objc final class TurnTimer: NSObject {
/** How long a turn can last in seconds */
private static let TurnLengthSec = 75
private(set) var seconds: Int = 75
private(set) var playerSeconds: Int = 0
private(set) var opponentSeconds: Int = 0
private var turnTime: Int = 75
private var timer: Timer?
weak var timerHud: TimerHud?
private var currentPlayer: PlayerType = .player
init(gui: TimerHud) {
self.timerHud = gui
}
func startTurn(for player: PlayerType, timeout: Int = -1) {
seconds = TurnTimer.TurnLengthSec
self.currentPlayer = player
timer?.invalidate()
self.timer = Timer(timeInterval: 1,
target: self,
selector: #selector(self.timerTick),
userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: RunLoopMode.defaultRunLoopMode)
if timeout < 0 {
seconds = 75
} else {
seconds = timeout
}
}
func start() {
playerSeconds = 0
opponentSeconds = 0
seconds = 75
timer?.invalidate()
}
func stop() {
timer?.invalidate()
}
func timerTick() {
if seconds > 0 {
seconds -= 1
}
if self.currentPlayer == .player {
self.playerSeconds += 1
} else {
self.opponentSeconds += 1
}
/*if game.isMulliganDone() {
if isPlayersTurn {
playerSeconds += 1
} else {
opponentSeconds += 1
}
}*/
DispatchQueue.main.async { [unowned(unsafe) self] in
self.timerHud?.tick(seconds: self.seconds,
playerSeconds: self.playerSeconds,
opponentSeconds: self.opponentSeconds)
}
}
}
| mit | e5516968b55a2bc3b50cebd8d70f0275 | 21.295455 | 67 | 0.577472 | 4.147992 | false | false | false | false |
wackosix/WSNetEaseNews | NetEaseNews/Classes/External/PhotoBrowser/Frameworks/CFSnapKit/Source/ConstraintDescription.swift | 1 | 19919 | //
// SnapKit
//
// Copyright (c) 2011-2015 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
#else
import AppKit
#endif
public protocol RelationTarget {
var constraintItem: ConstraintItem { get }
}
public protocol FloatConvertible: RelationTarget {
var floatValue: Float { get }
}
extension FloatConvertible {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
}
extension Float: FloatConvertible, RelationTarget {
public var floatValue: Float {
return self
}
}
extension Int: FloatConvertible, RelationTarget {
public var floatValue: Float {
return Float(self)
}
}
extension UInt: FloatConvertible, RelationTarget {
public var floatValue: Float {
return Float(self)
}
}
extension Double: FloatConvertible, RelationTarget {
public var floatValue: Float {
return Float(self)
}
}
extension CGFloat: FloatConvertible, RelationTarget {
public var floatValue: Float {
return Float(self)
}
}
@available(iOS 9.0, OSX 10.11, *)
extension NSLayoutAnchor: RelationTarget {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: self, attributes: ConstraintAttributes.None)
}
}
extension CGPoint: RelationTarget {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
}
extension CGSize: RelationTarget {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
}
extension EdgeInsets: RelationTarget {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
}
extension View: RelationTarget {
public var constraintItem: ConstraintItem {
return ConstraintItem(object: self, attributes: ConstraintAttributes.None)
}
}
extension ConstraintItem: RelationTarget {
public var constraintItem: ConstraintItem {
return self
}
}
/**
Used to expose the final API of a `ConstraintDescription` which allows getting a constraint from it
*/
public class ConstraintDescriptionFinalizable {
private let backing: ConstraintDescription
internal init(_ backing: ConstraintDescription) {
self.backing = backing
}
public var constraint: Constraint {
return backing.constraint
}
}
/**
Used to expose priority APIs
*/
public class ConstraintDescriptionPriortizable: ConstraintDescriptionFinalizable {
public func priority(priority: FloatConvertible) -> ConstraintDescriptionFinalizable {
return ConstraintDescriptionFinalizable(self.backing.priority(priority))
}
public func priorityRequired() -> ConstraintDescriptionFinalizable {
return ConstraintDescriptionFinalizable(self.backing.priorityRequired())
}
public func priorityHigh() -> ConstraintDescriptionFinalizable {
return ConstraintDescriptionFinalizable(self.backing.priorityHigh())
}
public func priorityMedium() -> ConstraintDescriptionFinalizable {
return ConstraintDescriptionFinalizable(self.backing.priorityMedium())
}
public func priorityLow() -> ConstraintDescriptionFinalizable {
return ConstraintDescriptionFinalizable(self.backing.priorityLow())
}
}
/**
Used to expose multiplier & constant APIs
*/
public class ConstraintDescriptionEditable: ConstraintDescriptionPriortizable {
public func multipliedBy(amount: FloatConvertible) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.multipliedBy(amount))
}
public func dividedBy(amount: FloatConvertible) -> ConstraintDescriptionEditable {
return self.multipliedBy(1 / amount.floatValue)
}
public func offset(amount: FloatConvertible) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.offset(amount))
}
public func offset(amount: CGPoint) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.offset(amount))
}
public func offset(amount: CGSize) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.offset(amount))
}
public func offset(amount: EdgeInsets) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.offset(amount))
}
public func inset(amount: FloatConvertible) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.inset(amount))
}
public func inset(amount: EdgeInsets) -> ConstraintDescriptionEditable {
return ConstraintDescriptionEditable(self.backing.inset(amount))
}
}
/**
Used to expose relation APIs
*/
public class ConstraintDescriptionRelatable {
private let backing: ConstraintDescription
init(_ backing: ConstraintDescription) {
self.backing = backing
}
public func equalTo(other: RelationTarget, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .Equal, location: location))
}
public func equalTo(other: LayoutSupport, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .Equal, location: location))
}
public func lessThanOrEqualTo(other: RelationTarget, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .LessThanOrEqualTo, location: location))
}
public func lessThanOrEqualTo(other: LayoutSupport, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .LessThanOrEqualTo, location: location))
}
public func greaterThanOrEqualTo(other: RelationTarget, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .GreaterThanOrEqualTo, location: location))
}
public func greaterThanOrEqualTo(other: LayoutSupport, file: String = #file, line: UInt = #line) -> ConstraintDescriptionEditable {
let location = SourceLocation(file: file, line: line)
return ConstraintDescriptionEditable(self.backing.constrainTo(other, relation: .GreaterThanOrEqualTo, location: location))
}
}
/**
Used to expose chaining APIs
*/
public class ConstraintDescriptionExtendable: ConstraintDescriptionRelatable {
public var left: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.left)
}
public var top: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.top)
}
public var bottom: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.bottom)
}
public var right: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.right)
}
public var leading: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.leading)
}
public var trailing: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.trailing)
}
public var width: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.width)
}
public var height: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.height)
}
public var centerX: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.centerX)
}
public var centerY: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.centerY)
}
public var baseline: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.baseline)
}
@available(iOS 8.0, *)
public var firstBaseline: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.firstBaseline)
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.leftMargin)
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.rightMargin)
}
@available(iOS 8.0, *)
public var topMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.topMargin)
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.bottomMargin)
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.leadingMargin)
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.trailingMargin)
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.centerXWithinMargins)
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintDescriptionExtendable {
return ConstraintDescriptionExtendable(self.backing.centerYWithinMargins)
}
}
/**
Used to internally manage building constraint
*/
internal class ConstraintDescription {
private var location: SourceLocation? = nil
private var left: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Left) }
private var top: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Top) }
private var right: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Right) }
private var bottom: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Bottom) }
private var leading: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Leading) }
private var trailing: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Trailing) }
private var width: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Width) }
private var height: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Height) }
private var centerX: ConstraintDescription { return self.addConstraint(ConstraintAttributes.CenterX) }
private var centerY: ConstraintDescription { return self.addConstraint(ConstraintAttributes.CenterY) }
private var baseline: ConstraintDescription { return self.addConstraint(ConstraintAttributes.Baseline) }
@available(iOS 8.0, *)
private var firstBaseline: ConstraintDescription { return self.addConstraint(ConstraintAttributes.FirstBaseline) }
@available(iOS 8.0, *)
private var leftMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.LeftMargin) }
@available(iOS 8.0, *)
private var rightMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.RightMargin) }
@available(iOS 8.0, *)
private var topMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.TopMargin) }
@available(iOS 8.0, *)
private var bottomMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.BottomMargin) }
@available(iOS 8.0, *)
private var leadingMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.LeadingMargin) }
@available(iOS 8.0, *)
private var trailingMargin: ConstraintDescription { return self.addConstraint(ConstraintAttributes.TrailingMargin) }
@available(iOS 8.0, *)
private var centerXWithinMargins: ConstraintDescription { return self.addConstraint(ConstraintAttributes.CenterXWithinMargins) }
@available(iOS 8.0, *)
private var centerYWithinMargins: ConstraintDescription { return self.addConstraint(ConstraintAttributes.CenterYWithinMargins) }
// MARK: initializer
init(fromItem: ConstraintItem) {
self.fromItem = fromItem
self.toItem = ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
// MARK: multiplier
private func multipliedBy(amount: FloatConvertible) -> ConstraintDescription {
self.multiplier = amount.floatValue
return self
}
private func dividedBy(amount: FloatConvertible) -> ConstraintDescription {
self.multiplier = 1.0 / amount.floatValue;
return self
}
// MARK: offset
private func offset(amount: FloatConvertible) -> ConstraintDescription {
self.constant = amount.floatValue
return self
}
private func offset(amount: CGPoint) -> ConstraintDescription {
self.constant = amount
return self
}
private func offset(amount: CGSize) -> ConstraintDescription {
self.constant = amount
return self
}
private func offset(amount: EdgeInsets) -> ConstraintDescription {
self.constant = amount
return self
}
// MARK: inset
private func inset(amount: FloatConvertible) -> ConstraintDescription {
let value = CGFloat(amount.floatValue)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
private func inset(amount: EdgeInsets) -> ConstraintDescription {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
return self
}
// MARK: priority
private func priority(priority: FloatConvertible) -> ConstraintDescription {
self.priority = priority.floatValue
return self
}
private func priorityRequired() -> ConstraintDescription {
return self.priority(1000.0)
}
private func priorityHigh() -> ConstraintDescription {
return self.priority(750.0)
}
private func priorityMedium() -> ConstraintDescription {
#if os(iOS) || os(tvOS)
return self.priority(500.0)
#else
return self.priority(501.0)
#endif
}
private func priorityLow() -> ConstraintDescription {
return self.priority(250.0)
}
// MARK: Constraint
internal var constraint: Constraint {
if self.concreteConstraint == nil {
if self.relation == nil {
fatalError("Attempting to create a constraint from a ConstraintDescription before it has been fully chained.")
}
self.concreteConstraint = ConcreteConstraint(
fromItem: self.fromItem,
toItem: self.toItem,
relation: self.relation!,
constant: self.constant,
multiplier: self.multiplier,
priority: self.priority,
location: self.location
)
}
return self.concreteConstraint!
}
// MARK: Private
private let fromItem: ConstraintItem
private var toItem: ConstraintItem {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var relation: ConstraintRelation? {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var constant: Any = Float(0.0) {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var multiplier: Float = 1.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var priority: Float = 1000.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
private var concreteConstraint: ConcreteConstraint? = nil
private func addConstraint(attributes: ConstraintAttributes) -> ConstraintDescription {
if self.relation == nil {
self.fromItem.attributes += attributes
}
return self
}
private func constrainTo(other: RelationTarget, relation: ConstraintRelation, location: SourceLocation) -> ConstraintDescription {
self.location = location
if let constant = other as? FloatConvertible {
self.constant = constant.floatValue
}
let item = other.constraintItem
if item.attributes != ConstraintAttributes.None {
let toLayoutAttributes = item.attributes.layoutAttributes
if toLayoutAttributes.count > 1 {
let fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
if toLayoutAttributes != fromLayoutAttributes {
NSException(name: "Invalid Constraint", reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
return self
}
item.attributes = ConstraintAttributes.None
}
}
self.toItem = item
self.relation = relation
return self
}
@available(iOS 7.0, *)
private func constrainTo(other: LayoutSupport, relation: ConstraintRelation, location: SourceLocation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation, location: location)
}
}
| mit | d8de988a02fa245c8ff18c9190cc9aac | 38.133595 | 147 | 0.707465 | 5.448304 | false | false | false | false |
johnno1962/eidolon | Kiosk/Auction Listings/ListingsViewModel.swift | 1 | 12884 | import Foundation
import RxSwift
typealias ShowDetailsClosure = (SaleArtwork) -> Void
typealias PresentModalClosure = (SaleArtwork) -> Void
protocol ListingsViewModelType {
var auctionID: String { get }
var syncInterval: NSTimeInterval { get }
var pageSize: Int { get }
var logSync: (NSDate) -> Void { get }
var numberOfSaleArtworks: Int { get }
var showSpinner: Observable<Bool>! { get }
var gridSelected: Observable<Bool>! { get }
var updatedContents: Observable<NSDate> { get }
var scheduleOnBackground: (observable: Observable<AnyObject>) -> Observable<AnyObject> { get }
var scheduleOnForeground: (observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> { get }
func saleArtworkViewModelAtIndexPath(indexPath: NSIndexPath) -> SaleArtworkViewModel
func showDetailsForSaleArtworkAtIndexPath(indexPath: NSIndexPath)
func presentModalForSaleArtworkAtIndexPath(indexPath: NSIndexPath)
func imageAspectRatioForSaleArtworkAtIndexPath(indexPath: NSIndexPath) -> CGFloat?
}
// Cheating here, should be in the instance but there's only ever one instance, so ¯\_(ツ)_/¯
private let backgroundScheduler = SerialDispatchQueueScheduler(globalConcurrentQueueQOS: .Default)
class ListingsViewModel: NSObject, ListingsViewModelType {
// These are private to the view model – should not be accessed directly
private var saleArtworks = Variable(Array<SaleArtwork>())
private var sortedSaleArtworks = Variable<Array<SaleArtwork>>([])
let auctionID: String
let pageSize: Int
let syncInterval: NSTimeInterval
let logSync: (NSDate) -> Void
var scheduleOnBackground: (observable: Observable<AnyObject>) -> Observable<AnyObject>
var scheduleOnForeground: (observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]>
var numberOfSaleArtworks: Int {
return sortedSaleArtworks.value.count
}
var showSpinner: Observable<Bool>!
var gridSelected: Observable<Bool>!
var updatedContents: Observable<NSDate> {
return sortedSaleArtworks
.asObservable()
.map { $0.count > 0 }
.ignore(false)
.map { _ in NSDate() }
}
let showDetails: ShowDetailsClosure
let presentModal: PresentModalClosure
let provider: Networking
init(provider: Networking,
selectedIndex: Observable<Int>,
showDetails: ShowDetailsClosure,
presentModal: PresentModalClosure,
pageSize: Int = 10,
syncInterval: NSTimeInterval = SyncInterval,
logSync:(NSDate) -> Void = ListingsViewModel.DefaultLogging,
scheduleOnBackground: (observable: Observable<AnyObject>) -> Observable<AnyObject> = ListingsViewModel.DefaultScheduler(onBackground: true),
scheduleOnForeground: (observable: Observable<[SaleArtwork]>) -> Observable<[SaleArtwork]> = ListingsViewModel.DefaultScheduler(onBackground: false),
auctionID: String = AppSetup.sharedState.auctionID) {
self.provider = provider
self.auctionID = auctionID
self.showDetails = showDetails
self.presentModal = presentModal
self.pageSize = pageSize
self.syncInterval = syncInterval
self.logSync = logSync
self.scheduleOnBackground = scheduleOnBackground
self.scheduleOnForeground = scheduleOnForeground
super.init()
setup(selectedIndex)
}
// MARK: Private Methods
private func setup(selectedIndex: Observable<Int>) {
recurringListingsRequest()
.takeUntil(rx_deallocated)
.bindTo(saleArtworks)
.addDisposableTo(rx_disposeBag)
showSpinner = sortedSaleArtworks.asObservable().map { sortedSaleArtworks in
return sortedSaleArtworks.count == 0
}
gridSelected = selectedIndex.map { ListingsViewModel.SwitchValues(rawValue: $0) == .Some(.Grid) }
let distinctSaleArtworks = saleArtworks
.asObservable()
.distinctUntilChanged { (lhs, rhs) -> Bool in
return lhs == rhs
}
.mapReplace(0) // To use in combineLatest, we must have an array of identically-typed observables.
[selectedIndex, distinctSaleArtworks]
.combineLatest { ints in
// We use distinctSaleArtworks to trigger an update, but ints[1] is unused.
return ints[0]
}
.startWith(0)
.map { selectedIndex in
return ListingsViewModel.SwitchValues(rawValue: selectedIndex)
}
.filterNil()
.map { [weak self] switchValue -> [SaleArtwork] in
guard let me = self else { return [] }
return switchValue.sortSaleArtworks(me.saleArtworks.value)
}
.bindTo(sortedSaleArtworks)
.addDisposableTo(rx_disposeBag)
}
private func listingsRequestForPage(page: Int) -> Observable<AnyObject> {
return provider.request(.AuctionListings(id: auctionID, page: page, pageSize: self.pageSize)).filterSuccessfulStatusCodes().mapJSON()
}
// Repeatedly calls itself with page+1 until the count of the returned array is < pageSize.
private func retrieveAllListingsRequest(page: Int) -> Observable<AnyObject> {
return Observable.create { [weak self] observer in
guard let me = self else { return NopDisposable.instance }
return me.listingsRequestForPage(page).subscribeNext { object in
guard let array = object as? Array<AnyObject> else { return }
guard let me = self else { return }
// This'll either be the next page request or .empty.
let nextPage: Observable<AnyObject>
// We must have more results to retrieve
if array.count >= me.pageSize {
nextPage = me.retrieveAllListingsRequest(page+1)
} else {
nextPage = .empty()
}
Observable.just(object)
.concat(nextPage)
.subscribe(observer)
}
}
}
// Fetches all pages of the auction
private func allListingsRequest() -> Observable<[SaleArtwork]> {
let backgroundJSONParsing = scheduleOnBackground(observable: retrieveAllListingsRequest(1)).reduce([AnyObject]())
{ (memo, object) in
guard let array = object as? Array<AnyObject> else { return memo }
return memo + array
}
.mapToObjectArray(SaleArtwork)
.logServerError("Sale artworks failed to retrieve+parse")
.catchErrorJustReturn([])
return scheduleOnForeground(observable: backgroundJSONParsing)
}
private func recurringListingsRequest() -> Observable<Array<SaleArtwork>> {
let recurring = Observable<Int>.interval(syncInterval, scheduler: MainScheduler.instance)
.map { _ in NSDate() }
.startWith(NSDate())
.takeUntil(rx_deallocating)
return recurring
.doOnNext(logSync)
.flatMap { [weak self] _ in
return self?.allListingsRequest() ?? .empty()
}
.map { [weak self] newSaleArtworks -> [SaleArtwork] in
guard let me = self else { return [] }
let currentSaleArtworks = me.saleArtworks.value
// So we want to do here is pretty simple – if the existing and new arrays are of the same length,
// then update the individual values in the current array and return the existing value.
// If the array's length has changed, then we pass through the new array
if newSaleArtworks.count == currentSaleArtworks.count {
if update(currentSaleArtworks, newSaleArtworks: newSaleArtworks) {
return currentSaleArtworks
}
}
return newSaleArtworks
}
}
// MARK: Private class methods
private class func DefaultLogging(date: NSDate) {
#if (arch(i386) || arch(x86_64)) && os(iOS)
logger.log("Syncing on \(date)")
#endif
}
private class func DefaultScheduler<T>(onBackground background: Bool)(observable: Observable<T>) -> Observable<T> {
if background {
return observable.observeOn(backgroundScheduler)
} else {
return observable.observeOn(MainScheduler.instance)
}
}
// MARK: Public methods
func saleArtworkViewModelAtIndexPath(indexPath: NSIndexPath) -> SaleArtworkViewModel {
return sortedSaleArtworks.value[indexPath.item].viewModel
}
func imageAspectRatioForSaleArtworkAtIndexPath(indexPath: NSIndexPath) -> CGFloat? {
return sortedSaleArtworks.value[indexPath.item].artwork.defaultImage?.aspectRatio
}
func showDetailsForSaleArtworkAtIndexPath(indexPath: NSIndexPath) {
showDetails(sortedSaleArtworks.value[indexPath.item])
}
func presentModalForSaleArtworkAtIndexPath(indexPath: NSIndexPath) {
presentModal(sortedSaleArtworks.value[indexPath.item])
}
// MARK: - Switch Values
enum SwitchValues: Int {
case Grid = 0
case LeastBids
case MostBids
case HighestCurrentBid
case LowestCurrentBid
case Alphabetical
var name: String {
switch self {
case .Grid:
return "Grid"
case .LeastBids:
return "Least Bids"
case .MostBids:
return "Most Bids"
case .HighestCurrentBid:
return "Highest Bid"
case .LowestCurrentBid:
return "Lowest Bid"
case .Alphabetical:
return "A–Z"
}
}
func sortSaleArtworks(saleArtworks: [SaleArtwork]) -> [SaleArtwork] {
switch self {
case Grid:
return saleArtworks
case LeastBids:
return saleArtworks.sort(leastBidsSort)
case MostBids:
return saleArtworks.sort(mostBidsSort)
case HighestCurrentBid:
return saleArtworks.sort(highestCurrentBidSort)
case LowestCurrentBid:
return saleArtworks.sort(lowestCurrentBidSort)
case Alphabetical:
return saleArtworks.sort(alphabeticalSort)
}
}
static func allSwitchValues() -> [SwitchValues] {
return [Grid, LeastBids, MostBids, HighestCurrentBid, LowestCurrentBid, Alphabetical]
}
static func allSwitchValueNames() -> [String] {
return allSwitchValues().map{$0.name.uppercaseString}
}
}
}
// MARK: - Sorting Functions
protocol IntOrZeroable {
var intOrZero: Int { get }
}
extension NSNumber: IntOrZeroable {
var intOrZero: Int {
return self as Int
}
}
extension Optional where Wrapped: IntOrZeroable {
var intOrZero: Int {
return self.value?.intOrZero ?? 0
}
}
func leastBidsSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return (lhs.bidCount.intOrZero) < (rhs.bidCount.intOrZero)
}
func mostBidsSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return !leastBidsSort(lhs, rhs)
}
func lowestCurrentBidSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return (lhs.highestBidCents.intOrZero) < (rhs.highestBidCents.intOrZero)
}
func highestCurrentBidSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return !lowestCurrentBidSort(lhs, rhs)
}
func alphabeticalSort(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return lhs.artwork.sortableArtistID().caseInsensitiveCompare(rhs.artwork.sortableArtistID()) == .OrderedAscending
}
func sortById(lhs: SaleArtwork, _ rhs: SaleArtwork) -> Bool {
return lhs.id.caseInsensitiveCompare(rhs.id) == .OrderedAscending
}
private func update(currentSaleArtworks: [SaleArtwork], newSaleArtworks: [SaleArtwork]) -> Bool {
assert(currentSaleArtworks.count == newSaleArtworks.count, "Arrays' counts must be equal.")
// Updating the currentSaleArtworks is easy. Both are already sorted as they came from the API (by lot #).
// Because we assume that their length is the same, we just do a linear scan through and
// copy values from the new to the existing.
let saleArtworksCount = currentSaleArtworks.count
for var i = 0; i < saleArtworksCount; i++ {
if currentSaleArtworks[i].id == newSaleArtworks[i].id {
currentSaleArtworks[i].updateWithValues(newSaleArtworks[i])
} else {
// Failure: the list was the same size but had different artworks.
return false
}
}
return true
}
| mit | 679967e00dbc7fa3c4d6f6fde0858363 | 35.678063 | 158 | 0.639972 | 5.315442 | false | false | false | false |
GenerallyHelpfulSoftware/Scalar2D | Styling/Sources/StyleBlock.swift | 1 | 5236 | //
// StyleBlock.swift
// Scalar2D
//
// Created by Glenn Howes on 11/14/16.
// Copyright © 2016-2017 Generally Helpful Software. All rights reserved.
//
//
//
//
// The MIT License (MIT)
// Copyright (c) 2016 Generally Helpful Software
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//
import Foundation
public protocol CSSContext
{
func test(_ testItem:CSSIdentifiable, for pseudoClass: PseudoClass) -> Bool
func test(_ testItem:CSSIdentifiable, for pseudoElement: PseudoElement) -> Bool
}
public struct StyleBlock
{
public let combinators:[[SelectorCombinator]]
public let styles:[GraphicStyle]
public init(combinators: [[SelectorCombinator]], styles: [GraphicStyle])
{
self.combinators = combinators
self.styles = styles
}
/**
Since many test cases involve simple, standalone StyleSelectors and not child, ancestor, sibling combinations, this constructor is provided.
*/
public init(selectors: [StyleSelector], styles: [GraphicStyle]) {
self.init(combinators: selectors.map{[SelectorCombinator.selector($0)]},styles: styles)
}
}
extension StyleBlock: Equatable
{
public static func == (lhs: StyleBlock, rhs: StyleBlock) -> Bool
{
if lhs.styles != rhs.styles
{
return false
}
if lhs.combinators.count != rhs.combinators.count
{
return false
}
for index in 0..<lhs.combinators.count
{
let lhsCombination = lhs.combinators[index]
let rhsCombination = rhs.combinators[index]
if lhsCombination != rhsCombination
{
return false
}
}
return true
}
}
fileprivate struct RankedGraphicStyle
{
let graphicStyle: GraphicStyle
let specificity: CSSSpecificity
}
extension Array where Element == SelectorCombinator
{
fileprivate func applies(toElement element: CSSIdentifiable, givenContext context: CSSContext) -> Bool
{
guard let firstElement = self.first else
{
return false
}
switch (firstElement) {
case .selector(let selector):
if selector.applies(to: element, given: context)
{
}
default:
return false
}
return false
}
}
extension Array where Element == StyleBlock
{
public func properties(for element: CSSIdentifiable, given context: CSSContext) -> [GraphicStyle]
{
var propertyMap = [PropertyKey: RankedGraphicStyle]()
for aStyleBlock in self
{
var bestSpecifity : CSSSpecificity? = nil
for aCombinator in aStyleBlock.combinators
{
if aCombinator.applies(toElement: element, givenContext: context)
{
let specificity = aCombinator.specificity
if let oldSpecificty = bestSpecifity
{
bestSpecifity = (oldSpecificty < specificity) ? specificity : oldSpecificty
}
else
{
bestSpecifity = specificity
}
}
}
if let thisSpecificity = bestSpecifity
{
for aStyle in aStyleBlock.styles
{
let key = aStyle.key
if let oldValue = propertyMap[key]
{
if aStyle.important || oldValue.specificity <= thisSpecificity
{
propertyMap[key] = RankedGraphicStyle(graphicStyle: aStyle, specificity: thisSpecificity)
}
}
else
{
propertyMap[key] = RankedGraphicStyle(graphicStyle: aStyle, specificity: thisSpecificity)
}
}
}
}
return propertyMap.map{return $0.value.graphicStyle}
}
}
| mit | cddc723474c7b8be3717e3545bbc237f | 29.976331 | 149 | 0.586628 | 4.874302 | false | false | false | false |
jeffctown/ios-automation | swift/update-podspec-version.swift | 1 | 2481 | import Foundation
import Files
import SwiftShell
import Moderator
let arguments = Moderator(description: "Update the version number in your podspecs.")
let podSpecArg = arguments.add(Argument<String>.optionWithValue("p", name: "podspec", description: "The path to the podspec."))
let versionArg = arguments.add(Argument<String>.optionWithValue("v", name: "version", description: "The version to update to."))
do {
try arguments.parse()
// check podspec argument
guard let podSpec = podSpecArg.value else {
throw ArgumentError(errormessage: "PodSpec not found.", usagetext: "use -p=Cocoapod.podspec")
}
//check version argument
guard let version = versionArg.value else {
throw ArgumentError(errormessage: "Version number not found.", usagetext: "use -v=1.0.0")
}
//check podspec exists
let podSpecFile = try File(path: podSpec)
//check podspec contents
let podSpecContents = try podSpecFile.readAsString()
print("*** Reading version number")
var versionNumber: String?
var versionUpdated = false
podSpecContents.enumerateLines(invoking: { (line, _) in
if versionUpdated { return }
if line.contains("s.version") {
let components = line.components(separatedBy: "=")
if components.count > 1 {
var value = components[1]
versionNumber = value.trimmingCharacters(in: NSCharacterSet.whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "\""))
versionUpdated = true
}
}
})
guard let versionNum = versionNumber else {
exit(Int32(1))
}
print("*** Finished Reading Version number (\(versionNum))")
print("*** Updating version number to \(version)")
let newPodSpecContents = podSpecContents.replacingOccurrences(of: versionNum, with: version)
print("*** Podspec Updated To: \(newPodSpecContents)")
print("*** Writing new Podspec (\(podSpec))")
try podSpecFile.write(string: newPodSpecContents)
print("*** Done updating version number.")
print("*** Verifying version number.")
guard try podSpecFile.readAsString().contains(version) else {
exit(Int32(1))
}
print("*** Version number found: \(version)")
print("*** Version number updated successfully.")
print("*** SUCCESS!")
} catch {
print("*** FAILURE!")
print(error)
exit(Int32(error._code))
}
| mit | 9bff987cedebd021abfebbf237292cad | 33.943662 | 145 | 0.648932 | 4.569061 | false | false | false | false |
mahuiying0126/MDemo | BangDemo/BangDemo/Modules/HomeDetail/model/CommentCellFrameModel.swift | 1 | 2997 | //
// CommentCellFrameModel.swift
// BangDemo
//
// Created by yizhilu on 2017/8/4.
// Copyright © 2017年 Magic. All rights reserved.
//
import UIKit
class CommentCellFrameModel: NSObject {
/** *评论数据 */
var model : CommentUserModel?
/** *图片位置 */
var imageFrame : CGRect?
/** *名字位置 */
var nameFrame : CGRect?
/** *评论时间位置 */
var timeFrame : CGRect?
/** *评论位置 */
var contentFrame : CGRect?
/** *分割线位置 */
var lineFrame : CGRect?
/** *行高 */
var cellHeight : CGFloat?
private let spacingM : CGFloat = 10
private let maxWith = (Screen_width - 5 * 10) * 0.5
private var font15 = UIFont.systemFont(ofSize: 15)
private var font13 = UIFont.systemFont(ofSize: 13)
func cellFrameModel(_ cellModel : CommentUserModel) -> CommentCellFrameModel {
let frameModel = CommentCellFrameModel()
frameModel.model = cellModel
///定义图片宽高是40,边距是15
///图片 frame
frameModel.imageFrame = .init(x: Spacing_width15, y: Spacing_heght15, width: 40, height: 40)
var name = ""
if ((cellModel.nickname?.deletSpaceInString().characters.count)! > 0) {
name = cellModel.nickname!
}else if((cellModel.mobile?.deletSpaceInString().characters.count)! > 0){
name = cellModel.mobile!
}else if((cellModel.email?.deletSpaceInString().characters.count)! > 0){
name = cellModel.email!
}else{
name = "匿名用户"
}
let name_x = (frameModel.imageFrame?.maxX)! + spacingM
let name_y = frameModel.imageFrame?.minY
let name_w = (name as NSString).widthForFont(font: &font15)
///昵称 frame
frameModel.nameFrame = .init(x: name_x, y: name_y!, width: name_w, height: 18)
let time_w = (cellModel.createTime! as NSString).widthForFont(font: &font13)
let time_x = Screen_width - Spacing_heght15 - time_w
///时间 frame
frameModel.timeFrame = .init(x: time_x, y: name_y!, width: time_w, height: 18)
let content_y = (frameModel.timeFrame?.maxY)! + spacingM
let conttempSize = CGSize.init(width: Screen_width - name_x - 15.0, height: CGFloat(MAXFLOAT))
let contentSize = (cellModel.content! as NSString).sizeForFont(font: &font15, size: conttempSize, lineBreakMode: .byCharWrapping)
///评论内容 frame
frameModel.contentFrame = .init(x: name_x, y: content_y, width: contentSize.width, height:contentSize.height)
let line_y = (frameModel.contentFrame?.maxY)! + Spacing_heght15
///分割线 frame
frameModel.lineFrame = CGRect.init(x: 0, y: line_y, width: Screen_width, height: 1.0)
///cell 高度 frame
frameModel.cellHeight = frameModel.lineFrame?.maxY
return frameModel
}
}
| mit | 65199950dab2ee5360a17007cf1fac2d | 35.43038 | 137 | 0.600069 | 3.811921 | false | false | false | false |
jeancarlosaps/swift | Crie Seu Primeiro App/FiltroApp(v2) - Beta/FiltroApp(v2)/SegundoViewController.swift | 2 | 1466 | //
// ViewController.swift
// FiltroApp(v2)
//
// Created by Renan Siqueira de Souza Mesquita on 26/08/15.
// Copyright (c) 2015 Mobgeek. All rights reserved.
//
import UIKit
class SegundoViewController: UIViewController {
//Implicit Unwrapped Optionals
@IBOutlet weak var imageView: UIImageView!
var imagemSemFiltro: UIImage!
var imagemComFiltro: UIImage!
var filtro: CIFilter!
let context = CIContext(options: nil)
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = imagemSemFiltro
let imagemParaFiltro = CIImage(image: imagemSemFiltro)
filtro = CIFilter(name: "CISepiaTone", withInputParameters: ["inputImage": imagemParaFiltro, "inputIntensity": 1.0])
}
override func viewWillAppear(animated: Bool) {
//Optional Chaining
self.navigationController?.toolbarHidden = false
}
@IBAction func aplicaFiltro(sender: UIBarButtonItem) {
let imagemRenderizada = context.createCGImage(filtro.outputImage, fromRect: filtro.outputImage.extent())
imagemComFiltro = UIImage(CGImage: imagemRenderizada)
imageView.image = imagemComFiltro
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a7710be2bc411205b926a25f166ffb23 | 23.032787 | 124 | 0.636426 | 4.48318 | false | false | false | false |
tad-iizuka/swift-sdk | Source/VisualRecognitionV3/Models/ClassifiedImages.swift | 2 | 3856 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** The results from classifying one or more images. */
public struct ClassifiedImages: JSONDecodable {
/// The images that were classified.
public let images: [ClassifiedImage]
/// Any warnings produced during classification.
public let warnings: [WarningInfo]?
/// Used internally to initialize a `ClassifiedImages` model from JSON.
public init(json: JSON) throws {
images = try json.decodedArray(at: "images", type: ClassifiedImage.self)
warnings = try? json.decodedArray(at: "warnings", type: WarningInfo.self)
}
}
/** A classified image. */
public struct ClassifiedImage: JSONDecodable {
/// The source URL of the image, before any redirects. This is omitted if the image was uploaded.
public let sourceURL: String?
/// The fully-resolved URL of the image, after redirects are followed.
/// This is omitted if the image was uploaded.
public let resolvedURL: String?
/// The relative path of the image file. This is omitted if the image was passed by URL.
public let image: String?
/// Information about what might have caused a failure, such as an image
/// that is too large. This omitted if there is no error or warning.
public let error: ErrorInfo?
/// Classifications of the given image by classifier.
public let classifiers: [ClassifierResults]
/// Used internally to initialize a `ClassifiedImage` model from JSON.
public init(json: JSON) throws {
sourceURL = try? json.getString(at: "source_url")
resolvedURL = try? json.getString(at: "resolved_url")
image = try? json.getString(at: "image")
error = try? json.decode(at: "error")
classifiers = try json.decodedArray(at: "classifiers", type: ClassifierResults.self)
}
}
/** A classifier's classifications for a given image. */
public struct ClassifierResults: JSONDecodable {
/// The name of the classifier.
public let name: String
/// The id of the classifier.
public let classifierID: String?
/// The classes identified by the classifier.
public let classes: [Classification]
/// Used internally to initialize a `ClassifierResults` model from JSON.
public init(json: JSON) throws {
name = try json.getString(at: "name")
classifierID = try json.getString(at: "classifier_id")
classes = try json.decodedArray(at: "classes", type: Classification.self)
}
}
/** The classification of an image. */
public struct Classification: JSONDecodable {
/// The class identified in the image.
public let classification: String
/// The confidence score of the identified class. Scores range from 0 to 1, with a higher score indicating greater confidence.
public let score: Double
/// The type hierarchy of the identified class, if found.
public let typeHierarchy: String?
/// Used internally to initialize a `Classification` model from JSON.
public init(json: JSON) throws {
classification = try json.getString(at: "class")
score = try json.getDouble(at: "score")
typeHierarchy = try? json.getString(at: "type_hierarchy")
}
}
| apache-2.0 | 5308da6dfa38a2f754b9f4aef4376cea | 36.076923 | 130 | 0.686981 | 4.452656 | false | false | false | false |
keyOfVv/KEYExtension | KEYExtension/sources/SysSingleton.swift | 1 | 598 | //
// SysSingleton.swift
// Aura
//
// Created by Ke Yang on 4/18/16.
// Copyright © 2016 com.sangebaba. All rights reserved.
//
import Foundation
import UIKit
// MARK: - system singleton
/// key and visible window
//public let KeyWindow = UIApplication.shared.keyWindow
/// notification center
//public let NotificationCenter = Foundation.NotificationCenter.default
/// main Bundle
public let MainBundle = Bundle.main
/// current device
public let CurrentDevice = UIDevice.current
/// user defaults
public let StandardUserDefaults = UserDefaults.standard
| mit | cf45d048e637235346f0ecb5c44126dc | 21.111111 | 73 | 0.713568 | 4.174825 | false | false | false | false |
QuarkX/Quark | Tests/QuarkTests/Core/Map/MapTests.swift | 1 | 36320 | import XCTest
@testable import Quark
class MapTests : XCTestCase {
func testCreation() {
let nullValue: Bool? = nil
let null = Map(nullValue)
XCTAssertEqual(null, nil)
XCTAssertEqual(null, .null)
XCTAssert(null.isNull)
XCTAssertFalse(null.isBool)
XCTAssertFalse(null.isDouble)
XCTAssertFalse(null.isInt)
XCTAssertFalse(null.isString)
XCTAssertFalse(null.isData)
XCTAssertFalse(null.isArray)
XCTAssertFalse(null.isDictionary)
XCTAssertNil(null.bool)
XCTAssertNil(null.double)
XCTAssertNil(null.int)
XCTAssertNil(null.string)
XCTAssertNil(null.data)
XCTAssertNil(null.array)
XCTAssertNil(null.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let nullArrayValue: [Bool]? = nil
let nullArray = Map(nullArrayValue)
XCTAssertEqual(nullArray, nil)
XCTAssertEqual(nullArray, .null)
XCTAssert(nullArray.isNull)
XCTAssertFalse(nullArray.isBool)
XCTAssertFalse(nullArray.isDouble)
XCTAssertFalse(nullArray.isInt)
XCTAssertFalse(nullArray.isString)
XCTAssertFalse(nullArray.isData)
XCTAssertFalse(nullArray.isArray)
XCTAssertFalse(nullArray.isDictionary)
XCTAssertNil(nullArray.bool)
XCTAssertNil(nullArray.double)
XCTAssertNil(nullArray.int)
XCTAssertNil(nullArray.string)
XCTAssertNil(nullArray.data)
XCTAssertNil(nullArray.array)
XCTAssertNil(nullArray.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let nullArrayOfNullValue: [Bool?]? = nil
let nullArrayOfNull = Map(nullArrayOfNullValue)
XCTAssertEqual(nullArrayOfNull, nil)
XCTAssertEqual(nullArrayOfNull, .null)
XCTAssert(nullArrayOfNull.isNull)
XCTAssertFalse(nullArrayOfNull.isBool)
XCTAssertFalse(nullArrayOfNull.isDouble)
XCTAssertFalse(nullArrayOfNull.isInt)
XCTAssertFalse(nullArrayOfNull.isString)
XCTAssertFalse(nullArrayOfNull.isData)
XCTAssertFalse(nullArrayOfNull.isArray)
XCTAssertFalse(nullArrayOfNull.isDictionary)
XCTAssertNil(nullArrayOfNull.bool)
XCTAssertNil(nullArrayOfNull.double)
XCTAssertNil(nullArrayOfNull.int)
XCTAssertNil(nullArrayOfNull.string)
XCTAssertNil(nullArrayOfNull.data)
XCTAssertNil(nullArrayOfNull.array)
XCTAssertNil(nullArrayOfNull.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let nullDictionaryValue: [String: Bool]? = nil
let nullDictionary = Map(nullDictionaryValue)
XCTAssertEqual(nullDictionary, nil)
XCTAssertEqual(nullDictionary, .null)
XCTAssert(nullDictionary.isNull)
XCTAssertFalse(nullDictionary.isBool)
XCTAssertFalse(nullDictionary.isDouble)
XCTAssertFalse(nullDictionary.isInt)
XCTAssertFalse(nullDictionary.isString)
XCTAssertFalse(nullDictionary.isData)
XCTAssertFalse(nullDictionary.isArray)
XCTAssertFalse(nullDictionary.isDictionary)
XCTAssertNil(nullDictionary.bool)
XCTAssertNil(nullDictionary.double)
XCTAssertNil(nullDictionary.int)
XCTAssertNil(nullDictionary.string)
XCTAssertNil(nullDictionary.data)
XCTAssertNil(nullDictionary.array)
XCTAssertNil(nullDictionary.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let nullDictionaryOfNullValue: [String: Bool?]? = nil
let nullDictionaryOfNull = Map(nullDictionaryOfNullValue)
XCTAssertEqual(nullDictionaryOfNull, nil)
XCTAssertEqual(nullDictionaryOfNull, .null)
XCTAssert(nullDictionaryOfNull.isNull)
XCTAssertFalse(nullDictionaryOfNull.isBool)
XCTAssertFalse(nullDictionaryOfNull.isDouble)
XCTAssertFalse(nullDictionaryOfNull.isInt)
XCTAssertFalse(nullDictionaryOfNull.isString)
XCTAssertFalse(nullDictionaryOfNull.isData)
XCTAssertFalse(nullDictionaryOfNull.isArray)
XCTAssertFalse(nullDictionaryOfNull.isDictionary)
XCTAssertNil(nullDictionaryOfNull.bool)
XCTAssertNil(nullDictionaryOfNull.double)
XCTAssertNil(nullDictionaryOfNull.int)
XCTAssertNil(nullDictionaryOfNull.string)
XCTAssertNil(nullDictionaryOfNull.data)
XCTAssertNil(nullDictionaryOfNull.array)
XCTAssertNil(nullDictionaryOfNull.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertThrowsError(try null.asInt())
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let boolValue = true
let bool = Map(boolValue)
XCTAssertEqual(bool, true)
XCTAssertEqual(bool, .bool(boolValue))
XCTAssertFalse(bool.isNull)
XCTAssert(bool.isBool)
XCTAssertFalse(bool.isDouble)
XCTAssertFalse(bool.isInt)
XCTAssertFalse(bool.isString)
XCTAssertFalse(bool.isData)
XCTAssertFalse(bool.isArray)
XCTAssertFalse(bool.isDictionary)
XCTAssertEqual(bool.bool, boolValue)
XCTAssertNil(bool.double)
XCTAssertNil(bool.int)
XCTAssertNil(bool.string)
XCTAssertNil(bool.data)
XCTAssertNil(bool.array)
XCTAssertNil(bool.dictionary)
XCTAssertEqual(try bool.asBool(), boolValue)
XCTAssertThrowsError(try bool.asDouble())
XCTAssertThrowsError(try bool.asInt())
XCTAssertThrowsError(try bool.asString())
XCTAssertThrowsError(try bool.asData())
XCTAssertThrowsError(try bool.asArray())
XCTAssertThrowsError(try bool.asDictionary())
let doubleValue = 4.20
let double = Map(doubleValue)
XCTAssertEqual(double, 4.20)
XCTAssertEqual(double, .double(doubleValue))
XCTAssertFalse(double.isNull)
XCTAssertFalse(double.isBool)
XCTAssert(double.isDouble)
XCTAssertFalse(double.isInt)
XCTAssertFalse(double.isString)
XCTAssertFalse(double.isData)
XCTAssertFalse(double.isArray)
XCTAssertFalse(double.isDictionary)
XCTAssertNil(double.bool)
XCTAssertEqual(double.double, doubleValue)
XCTAssertNil(double.int)
XCTAssertNil(double.string)
XCTAssertNil(double.data)
XCTAssertNil(double.array)
XCTAssertNil(double.dictionary)
XCTAssertThrowsError(try double.asBool())
XCTAssertEqual(try double.asDouble(), doubleValue)
XCTAssertThrowsError(try double.asInt())
XCTAssertThrowsError(try double.asString())
XCTAssertThrowsError(try double.asData())
XCTAssertThrowsError(try double.asArray())
XCTAssertThrowsError(try double.asDictionary())
let intValue = 1969
let int = Map(intValue)
XCTAssertEqual(int, 1969)
XCTAssertEqual(int, .int(intValue))
XCTAssertFalse(int.isNull)
XCTAssertFalse(int.isBool)
XCTAssertFalse(int.isDouble)
XCTAssert(int.isInt)
XCTAssertFalse(int.isString)
XCTAssertFalse(int.isData)
XCTAssertFalse(int.isArray)
XCTAssertFalse(int.isDictionary)
XCTAssertNil(int.bool)
XCTAssertNil(int.double)
XCTAssertEqual(int.int, intValue)
XCTAssertNil(int.string)
XCTAssertNil(int.data)
XCTAssertNil(int.array)
XCTAssertNil(int.dictionary)
XCTAssertThrowsError(try null.asBool())
XCTAssertThrowsError(try null.asDouble())
XCTAssertEqual(try int.asInt(), intValue)
XCTAssertThrowsError(try null.asString())
XCTAssertThrowsError(try null.asData())
XCTAssertThrowsError(try null.asArray())
XCTAssertThrowsError(try null.asDictionary())
let stringValue = "foo"
let string = Map(stringValue)
XCTAssertEqual(string, "foo")
XCTAssertEqual(string, .string(stringValue))
XCTAssertFalse(string.isNull)
XCTAssertFalse(string.isBool)
XCTAssertFalse(string.isDouble)
XCTAssertFalse(string.isInt)
XCTAssert(string.isString)
XCTAssertFalse(string.isData)
XCTAssertFalse(string.isArray)
XCTAssertFalse(string.isDictionary)
XCTAssertNil(string.bool)
XCTAssertNil(string.double)
XCTAssertNil(string.int)
XCTAssertEqual(string.string, stringValue)
XCTAssertNil(string.data)
XCTAssertNil(string.array)
XCTAssertNil(string.dictionary)
XCTAssertThrowsError(try string.asBool())
XCTAssertThrowsError(try string.asDouble())
XCTAssertThrowsError(try string.asInt())
XCTAssertEqual(try string.asString(), stringValue)
XCTAssertThrowsError(try string.asData())
XCTAssertThrowsError(try string.asArray())
XCTAssertThrowsError(try string.asDictionary())
let dataValue = Data("foo")
let data = Map(dataValue)
XCTAssertEqual(data, .data(dataValue))
XCTAssertFalse(data.isNull)
XCTAssertFalse(data.isBool)
XCTAssertFalse(data.isDouble)
XCTAssertFalse(data.isInt)
XCTAssertFalse(data.isString)
XCTAssert(data.isData)
XCTAssertFalse(data.isArray)
XCTAssertFalse(data.isDictionary)
XCTAssertNil(data.bool)
XCTAssertNil(data.double)
XCTAssertNil(data.int)
XCTAssertNil(data.string)
XCTAssertEqual(data.data, dataValue)
XCTAssertNil(data.array)
XCTAssertNil(data.dictionary)
XCTAssertThrowsError(try data.asBool())
XCTAssertThrowsError(try data.asDouble())
XCTAssertThrowsError(try data.asInt())
XCTAssertThrowsError(try data.asString())
XCTAssertEqual(try data.asData(), dataValue)
XCTAssertThrowsError(try data.asArray())
XCTAssertThrowsError(try data.asDictionary())
let arrayValue = 1969
let array = Map([arrayValue])
XCTAssertEqual(array, [1969])
XCTAssertEqual(array, .array([.int(arrayValue)]))
XCTAssertFalse(array.isNull)
XCTAssertFalse(array.isBool)
XCTAssertFalse(array.isDouble)
XCTAssertFalse(array.isInt)
XCTAssertFalse(array.isString)
XCTAssertFalse(array.isData)
XCTAssert(array.isArray)
XCTAssertFalse(array.isDictionary)
XCTAssertNil(array.bool)
XCTAssertNil(array.double)
XCTAssertNil(array.int)
XCTAssertNil(array.string)
XCTAssertNil(array.data)
if let a = array.array {
XCTAssertEqual(a, [.int(arrayValue)])
} else {
XCTAssertNotNil(array.array)
}
XCTAssertNil(array.dictionary)
XCTAssertThrowsError(try array.asBool())
XCTAssertThrowsError(try array.asDouble())
XCTAssertThrowsError(try array.asInt())
XCTAssertThrowsError(try array.asString())
XCTAssertThrowsError(try array.asData())
XCTAssertEqual(try array.asArray(), [.int(arrayValue)])
XCTAssertThrowsError(try array.asDictionary())
let arrayOfOptionalValue: Int? = arrayValue
let arrayOfOptional = Map([arrayOfOptionalValue])
XCTAssertEqual(arrayOfOptional, [1969])
XCTAssertEqual(arrayOfOptional, .array([.int(arrayValue)]))
XCTAssertFalse(arrayOfOptional.isNull)
XCTAssertFalse(arrayOfOptional.isBool)
XCTAssertFalse(arrayOfOptional.isDouble)
XCTAssertFalse(arrayOfOptional.isInt)
XCTAssertFalse(arrayOfOptional.isString)
XCTAssertFalse(arrayOfOptional.isData)
XCTAssert(arrayOfOptional.isArray)
XCTAssertFalse(arrayOfOptional.isDictionary)
XCTAssertNil(arrayOfOptional.bool)
XCTAssertNil(arrayOfOptional.double)
XCTAssertNil(arrayOfOptional.int)
XCTAssertNil(arrayOfOptional.string)
XCTAssertNil(arrayOfOptional.data)
if let a = arrayOfOptional.array {
XCTAssertEqual(a, [.int(arrayValue)])
} else {
XCTAssertNotNil(arrayOfOptional.array)
}
XCTAssertNil(arrayOfOptional.dictionary)
XCTAssertThrowsError(try arrayOfOptional.asBool())
XCTAssertThrowsError(try arrayOfOptional.asDouble())
XCTAssertThrowsError(try arrayOfOptional.asInt())
XCTAssertThrowsError(try arrayOfOptional.asString())
XCTAssertThrowsError(try arrayOfOptional.asData())
XCTAssertEqual(try arrayOfOptional.asArray(), [.int(arrayValue)])
XCTAssertThrowsError(try arrayOfOptional.asDictionary())
let arrayOfNullValue: Int? = nil
let arrayOfNull = Map([arrayOfNullValue])
XCTAssertEqual(arrayOfNull, [nil])
XCTAssertEqual(arrayOfNull, .array([.null]))
XCTAssertFalse(arrayOfNull.isNull)
XCTAssertFalse(arrayOfNull.isBool)
XCTAssertFalse(arrayOfNull.isDouble)
XCTAssertFalse(arrayOfNull.isInt)
XCTAssertFalse(arrayOfNull.isString)
XCTAssertFalse(arrayOfNull.isData)
XCTAssert(arrayOfNull.isArray)
XCTAssertFalse(arrayOfNull.isDictionary)
XCTAssertNil(arrayOfNull.bool)
XCTAssertNil(arrayOfNull.double)
XCTAssertNil(arrayOfNull.int)
XCTAssertNil(arrayOfNull.string)
XCTAssertNil(arrayOfNull.data)
if let a = arrayOfNull.array {
XCTAssertEqual(a, [.null])
} else {
XCTAssertNotNil(arrayOfNull.array)
}
XCTAssertNil(arrayOfNull.dictionary)
XCTAssertThrowsError(try arrayOfNull.asBool())
XCTAssertThrowsError(try arrayOfNull.asDouble())
XCTAssertThrowsError(try arrayOfNull.asInt())
XCTAssertThrowsError(try arrayOfNull.asString())
XCTAssertThrowsError(try arrayOfNull.asData())
XCTAssertEqual(try arrayOfNull.asArray(), [.null])
XCTAssertThrowsError(try arrayOfNull.asDictionary())
let dictionaryValue = 1969
let dictionary = Map(["foo": dictionaryValue])
XCTAssertEqual(dictionary, ["foo": 1969])
XCTAssertEqual(dictionary, .dictionary(["foo": .int(dictionaryValue)]))
XCTAssertFalse(dictionary.isNull)
XCTAssertFalse(dictionary.isBool)
XCTAssertFalse(dictionary.isDouble)
XCTAssertFalse(dictionary.isInt)
XCTAssertFalse(dictionary.isString)
XCTAssertFalse(dictionary.isData)
XCTAssertFalse(dictionary.isArray)
XCTAssert(dictionary.isDictionary)
XCTAssertNil(dictionary.bool)
XCTAssertNil(dictionary.double)
XCTAssertNil(dictionary.int)
XCTAssertNil(dictionary.string)
XCTAssertNil(dictionary.data)
XCTAssertNil(dictionary.array)
if let d = dictionary.dictionary {
XCTAssertEqual(d, ["foo": .int(dictionaryValue)])
} else {
XCTAssertNotNil(dictionary.dictionary)
}
XCTAssertThrowsError(try dictionary.asBool())
XCTAssertThrowsError(try dictionary.asDouble())
XCTAssertThrowsError(try dictionary.asInt())
XCTAssertThrowsError(try dictionary.asString())
XCTAssertThrowsError(try dictionary.asData())
XCTAssertThrowsError(try dictionary.asArray())
XCTAssertEqual(try dictionary.asDictionary(), ["foo": .int(dictionaryValue)])
let dictionaryOfOptionalValue: Int? = dictionaryValue
let dictionaryOfOptional = Map(["foo": dictionaryOfOptionalValue])
XCTAssertEqual(dictionaryOfOptional, ["foo": 1969])
XCTAssertEqual(dictionaryOfOptional, .dictionary(["foo": .int(dictionaryValue)]))
XCTAssertFalse(dictionaryOfOptional.isNull)
XCTAssertFalse(dictionaryOfOptional.isBool)
XCTAssertFalse(dictionaryOfOptional.isDouble)
XCTAssertFalse(dictionaryOfOptional.isInt)
XCTAssertFalse(dictionaryOfOptional.isString)
XCTAssertFalse(dictionaryOfOptional.isData)
XCTAssertFalse(dictionaryOfOptional.isArray)
XCTAssert(dictionaryOfOptional.isDictionary)
XCTAssertNil(dictionaryOfOptional.bool)
XCTAssertNil(dictionaryOfOptional.double)
XCTAssertNil(dictionaryOfOptional.int)
XCTAssertNil(dictionaryOfOptional.string)
XCTAssertNil(dictionaryOfOptional.data)
XCTAssertNil(dictionaryOfOptional.array)
if let d = dictionaryOfOptional.dictionary {
XCTAssertEqual(d, ["foo": .int(dictionaryValue)])
} else {
XCTAssertNotNil(dictionaryOfOptional.dictionary)
}
XCTAssertThrowsError(try dictionaryOfOptional.asBool())
XCTAssertThrowsError(try dictionaryOfOptional.asDouble())
XCTAssertThrowsError(try dictionaryOfOptional.asInt())
XCTAssertThrowsError(try dictionaryOfOptional.asString())
XCTAssertThrowsError(try dictionaryOfOptional.asData())
XCTAssertThrowsError(try dictionaryOfOptional.asArray())
XCTAssertEqual(try dictionaryOfOptional.asDictionary(), ["foo": .int(dictionaryValue)])
let dictionaryOfNullValue: Int? = nil
let dictionaryOfNull = Map(["foo": dictionaryOfNullValue])
XCTAssertEqual(dictionaryOfNull, ["foo": nil])
XCTAssertEqual(dictionaryOfNull, .dictionary(["foo": .null]))
XCTAssertFalse(dictionaryOfNull.isNull)
XCTAssertFalse(dictionaryOfNull.isBool)
XCTAssertFalse(dictionaryOfNull.isDouble)
XCTAssertFalse(dictionaryOfNull.isInt)
XCTAssertFalse(dictionaryOfNull.isString)
XCTAssertFalse(dictionaryOfNull.isData)
XCTAssertFalse(dictionaryOfNull.isArray)
XCTAssert(dictionaryOfNull.isDictionary)
XCTAssertNil(dictionaryOfNull.bool)
XCTAssertNil(dictionaryOfNull.double)
XCTAssertNil(dictionaryOfNull.int)
XCTAssertNil(dictionaryOfNull.string)
XCTAssertNil(dictionaryOfNull.data)
XCTAssertNil(dictionaryOfNull.array)
if let d = dictionaryOfNull.dictionary {
XCTAssertEqual(d, ["foo": .null])
} else {
XCTAssertNotNil(dictionaryOfNull.dictionary)
}
XCTAssertThrowsError(try dictionaryOfNull.asBool())
XCTAssertThrowsError(try dictionaryOfNull.asDouble())
XCTAssertThrowsError(try dictionaryOfNull.asInt())
XCTAssertThrowsError(try dictionaryOfNull.asString())
XCTAssertThrowsError(try dictionaryOfNull.asData())
XCTAssertThrowsError(try dictionaryOfNull.asArray())
XCTAssertEqual(try dictionaryOfNull.asDictionary(), ["foo": .null])
}
func testConversion() {
let null: Map = nil
XCTAssertEqual(try null.asBool(converting: true), false)
XCTAssertEqual(try null.asDouble(converting: true), 0)
XCTAssertEqual(try null.asInt(converting: true), 0)
XCTAssertEqual(try null.asString(converting: true), "null")
XCTAssertEqual(try null.asData(converting: true), Data())
XCTAssertEqual(try null.asArray(converting: true), [])
XCTAssertEqual(try null.asDictionary(converting: true), [:])
let `true`: Map = true
XCTAssertEqual(try `true`.asBool(converting: true), true)
XCTAssertEqual(try `true`.asDouble(converting: true), 1.0)
XCTAssertEqual(try `true`.asInt(converting: true), 1)
XCTAssertEqual(try `true`.asString(converting: true), "true")
XCTAssertEqual(try `true`.asData(converting: true), Data([0xff]))
XCTAssertThrowsError(try `true`.asArray(converting: true))
XCTAssertThrowsError(try `true`.asDictionary(converting: true))
let `false`: Map = false
XCTAssertEqual(try `false`.asBool(converting: true), false)
XCTAssertEqual(try `false`.asDouble(converting: true), 0.0)
XCTAssertEqual(try `false`.asInt(converting: true), 0)
XCTAssertEqual(try `false`.asString(converting: true), "false")
XCTAssertEqual(try `false`.asData(converting: true), Data([0x00]))
XCTAssertThrowsError(try `false`.asArray(converting: true))
XCTAssertThrowsError(try `false`.asDictionary(converting: true))
let double: Map = 4.20
XCTAssertEqual(try double.asBool(converting: true), true)
XCTAssertEqual(try double.asDouble(converting: true), 4.20)
XCTAssertEqual(try double.asInt(converting: true), 4)
XCTAssertEqual(try double.asString(converting: true), "4.2")
XCTAssertThrowsError(try double.asData(converting: true))
XCTAssertThrowsError(try double.asArray(converting: true))
XCTAssertThrowsError(try double.asDictionary(converting: true))
let doubleZero: Map = 0.0
XCTAssertEqual(try doubleZero.asBool(converting: true), false)
XCTAssertEqual(try doubleZero.asDouble(converting: true), 0.0)
XCTAssertEqual(try doubleZero.asInt(converting: true), 0)
XCTAssertEqual(try doubleZero.asString(converting: true), "0.0")
XCTAssertThrowsError(try doubleZero.asData(converting: true))
XCTAssertThrowsError(try doubleZero.asArray(converting: true))
XCTAssertThrowsError(try doubleZero.asDictionary(converting: true))
let int: Map = 1969
XCTAssertEqual(try int.asBool(converting: true), true)
XCTAssertEqual(try int.asDouble(converting: true), 1969.0)
XCTAssertEqual(try int.asInt(converting: true), 1969)
XCTAssertEqual(try int.asString(converting: true), "1969")
XCTAssertThrowsError(try int.asData(converting: true))
XCTAssertThrowsError(try int.asArray(converting: true))
XCTAssertThrowsError(try int.asDictionary(converting: true))
let intZero: Map = 0
XCTAssertEqual(try intZero.asBool(converting: true), false)
XCTAssertEqual(try intZero.asDouble(converting: true), 0.0)
XCTAssertEqual(try intZero.asInt(converting: true), 0)
XCTAssertEqual(try intZero.asString(converting: true), "0")
XCTAssertThrowsError(try intZero.asData(converting: true))
XCTAssertThrowsError(try intZero.asArray(converting: true))
XCTAssertThrowsError(try intZero.asDictionary(converting: true))
let string: Map = "foo"
XCTAssertThrowsError(try string.asBool(converting: true))
XCTAssertThrowsError(try string.asDouble(converting: true))
XCTAssertThrowsError(try string.asInt(converting: true))
XCTAssertEqual(try string.asString(converting: true), "foo")
XCTAssertEqual(try string.asData(converting: true), Quark.Data("foo"))
XCTAssertThrowsError(try string.asArray(converting: true))
XCTAssertThrowsError(try string.asDictionary(converting: true))
let stringTrue: Map = "TRUE"
XCTAssertEqual(try stringTrue.asBool(converting: true), true)
XCTAssertThrowsError(try stringTrue.asDouble(converting: true))
XCTAssertThrowsError(try stringTrue.asInt(converting: true))
XCTAssertEqual(try stringTrue.asString(converting: true), "TRUE")
XCTAssertEqual(try stringTrue.asData(converting: true), Quark.Data("TRUE"))
XCTAssertThrowsError(try stringTrue.asArray(converting: true))
XCTAssertThrowsError(try stringTrue.asDictionary(converting: true))
let stringFalse: Map = "FALSE"
XCTAssertEqual(try stringFalse.asBool(converting: true), false)
XCTAssertThrowsError(try stringFalse.asDouble(converting: true))
XCTAssertThrowsError(try stringFalse.asInt(converting: true))
XCTAssertEqual(try stringFalse.asString(converting: true), "FALSE")
XCTAssertEqual(try stringFalse.asData(converting: true), Quark.Data("FALSE"))
XCTAssertThrowsError(try stringFalse.asArray(converting: true))
XCTAssertThrowsError(try stringFalse.asDictionary(converting: true))
let stringDouble: Map = "4.20"
XCTAssertThrowsError(try stringDouble.asBool(converting: true))
XCTAssertEqual(try stringDouble.asDouble(converting: true), 4.20)
XCTAssertThrowsError(try stringDouble.asInt(converting: true))
XCTAssertEqual(try stringDouble.asString(converting: true), "4.20")
XCTAssertEqual(try stringDouble.asData(converting: true), Quark.Data("4.20"))
XCTAssertThrowsError(try stringDouble.asArray(converting: true))
XCTAssertThrowsError(try stringDouble.asDictionary(converting: true))
let stringInt: Map = "1969"
XCTAssertThrowsError(try stringInt.asBool(converting: true))
XCTAssertEqual(try stringInt.asDouble(converting: true), 1969.0)
XCTAssertEqual(try stringInt.asInt(converting: true), 1969)
XCTAssertEqual(try stringInt.asString(converting: true), "1969")
XCTAssertEqual(try stringInt.asData(converting: true), Quark.Data("1969"))
XCTAssertThrowsError(try stringInt.asArray(converting: true))
XCTAssertThrowsError(try stringInt.asDictionary(converting: true))
let data: Map = .data(Data("foo"))
XCTAssertEqual(try data.asBool(converting: true), true)
XCTAssertThrowsError(try data.asDouble(converting: true))
XCTAssertThrowsError(try data.asInt(converting: true))
XCTAssertEqual(try data.asString(converting: true), "foo")
XCTAssertEqual(try data.asData(converting: true), Data("foo"))
XCTAssertThrowsError(try data.asArray(converting: true))
XCTAssertThrowsError(try data.asDictionary(converting: true))
let dataEmpty: Map = .data(Data())
XCTAssertEqual(try dataEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try dataEmpty.asDouble(converting: true))
XCTAssertThrowsError(try dataEmpty.asInt(converting: true))
XCTAssertEqual(try dataEmpty.asString(converting: true), "")
XCTAssertEqual(try dataEmpty.asData(converting: true), Data())
XCTAssertThrowsError(try dataEmpty.asArray(converting: true))
XCTAssertThrowsError(try dataEmpty.asDictionary(converting: true))
let array: Map = [1969]
XCTAssertEqual(try array.asBool(converting: true), true)
XCTAssertThrowsError(try array.asDouble(converting: true))
XCTAssertThrowsError(try array.asInt(converting: true))
XCTAssertThrowsError(try array.asString(converting: true))
XCTAssertThrowsError(try array.asData(converting: true))
XCTAssertEqual(try array.asArray(converting: true), [1969])
XCTAssertThrowsError(try array.asDictionary(converting: true))
let arrayEmpty: Map = []
XCTAssertEqual(try arrayEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try arrayEmpty.asDouble(converting: true))
XCTAssertThrowsError(try arrayEmpty.asInt(converting: true))
XCTAssertThrowsError(try arrayEmpty.asString(converting: true))
XCTAssertThrowsError(try arrayEmpty.asData(converting: true))
XCTAssertEqual(try arrayEmpty.asArray(converting: true), [])
XCTAssertThrowsError(try arrayEmpty.asDictionary(converting: true))
let dictionary: Map = ["foo": "bar"]
XCTAssertEqual(try dictionary.asBool(converting: true), true)
XCTAssertThrowsError(try dictionary.asDouble(converting: true))
XCTAssertThrowsError(try dictionary.asInt(converting: true))
XCTAssertThrowsError(try dictionary.asString(converting: true))
XCTAssertThrowsError(try dictionary.asData(converting: true))
XCTAssertThrowsError(try dictionary.asArray(converting: true))
XCTAssertEqual(try dictionary.asDictionary(converting: true), ["foo": "bar"])
let dictionaryEmpty: Map = [:]
XCTAssertEqual(try dictionaryEmpty.asBool(converting: true), false)
XCTAssertThrowsError(try dictionaryEmpty.asDouble(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asInt(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asString(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asData(converting: true))
XCTAssertThrowsError(try dictionaryEmpty.asArray(converting: true))
XCTAssertEqual(try dictionaryEmpty.asDictionary(converting: true), [:])
}
func testDescription() {
let data: Map = [
"array": [
[],
true,
.data(Data("bar")),
[:],
4.20,
1969,
nil,
"foo\nbar",
],
"bool": true,
"data": .data(Data("bar")),
"dictionary": [
"array": [],
"bool": true,
"data": .data(Data("bar")),
"dictionary": [:],
"double": 4.20,
"int": 1969,
"null": nil,
"string": "foo\nbar",
],
"double": 4.20,
"int": 1969,
"null": nil,
"string": "foo\nbar",
]
let description = "{\"array\":[[],true,0x626172,{},4.2,1969,null,\"foo\\nbar\"],\"bool\":true,\"data\":0x626172,\"dictionary\":{\"array\":[],\"bool\":true,\"data\":0x626172,\"dictionary\":{},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"},\"double\":4.2,\"int\":1969,\"null\":null,\"string\":\"foo\\nbar\"}"
XCTAssertEqual(data.description, description)
}
func testEquality() {
let a: Map = "foo"
let b: Map = 1968
XCTAssertNotEqual(a, b)
}
func testIndexPath() throws {
var data: Map
data = [["foo"]]
XCTAssertEqual(try data.get(0, 0), "foo")
try data.set("bar", for: 0, 0)
XCTAssertEqual(try data.get(0, 0), "bar")
data = [["foo": "bar"]]
XCTAssertEqual(try data.get(0, "foo"), "bar")
try data.set("baz", for: 0, "foo")
XCTAssertEqual(try data.get(0, "foo"), "baz")
data = ["foo": ["bar"]]
XCTAssertEqual(try data.get("foo", 0), "bar")
try data.set("baz", for: "foo", 0)
XCTAssertEqual(try data.get("foo", 0), "baz")
data = ["foo": ["bar": "baz"]]
XCTAssertEqual(try data.get("foo", "bar"), "baz")
try data.set("buh", for: "foo", "bar")
XCTAssertEqual(try data.get("foo", "bar"), "buh")
try data.set("uhu", for: "foo", "yoo")
XCTAssertEqual(try data.get("foo", "bar"), "buh")
XCTAssertEqual(try data.get("foo", "yoo"), "uhu")
try data.remove("foo", "bar")
XCTAssertEqual(data, ["foo": ["yoo": "uhu"]])
}
func testMapInitializable() throws {
struct Bar : MapInitializable {
let bar: String
}
struct Foo : MapInitializable {
let foo: Bar
}
struct Baz {
let baz: String
}
struct Fuu : MapInitializable {
let fuu: Baz
}
struct Fou : MapInitializable {
let fou: String?
}
XCTAssertEqual(try Bar(map: ["bar": "bar"]).bar, "bar")
XCTAssertThrowsError(try Bar(map: "bar"))
XCTAssertThrowsError(try Bar(map: ["bar": nil]))
XCTAssertEqual(try Foo(map: ["foo": ["bar": "bar"]]).foo.bar, "bar")
XCTAssertThrowsError(try Fuu(map: ["fuu": ["baz": "baz"]]))
XCTAssertEqual(try Fou(map: [:]).fou, nil)
XCTAssertEqual(try Map(map: nil), nil)
XCTAssertEqual(try Bool(map: true), true)
XCTAssertThrowsError(try Bool(map: nil))
XCTAssertEqual(try Double(map: 4.2), 4.2)
XCTAssertThrowsError(try Double(map: nil))
XCTAssertEqual(try Int(map: 4), 4)
XCTAssertThrowsError(try Int(map: nil))
XCTAssertEqual(try String(map: "foo"), "foo")
XCTAssertThrowsError(try String(map: nil))
XCTAssertEqual(try Data(map: .data(Data("foo"))), Data("foo"))
XCTAssertThrowsError(try Quark.Data(map: nil))
XCTAssertEqual(try Optional<Int>(map: nil), nil)
XCTAssertEqual(try Optional<Int>(map: 1969), 1969)
XCTAssertThrowsError(try Optional<Baz>(map: nil))
XCTAssertEqual(try Array<Int>(map: [1969]), [1969])
XCTAssertThrowsError(try Array<Int>(map: nil))
XCTAssertThrowsError(try Array<Baz>(map: []))
XCTAssertEqual(try Dictionary<String, Int>(map: ["foo": 1969]), ["foo": 1969])
XCTAssertThrowsError(try Dictionary<String, Int>(map: nil))
XCTAssertThrowsError(try Dictionary<Int, Int>(map: [:]))
XCTAssertThrowsError(try Dictionary<String, Baz>(map: [:]))
let map: Map = [
"fey": [
"foo": "bar",
"fuu": "baz"
]
]
struct Fey : MapInitializable {
let foo: String
let fuu: String
}
let fey: Fey = try map.get("fey")
XCTAssertEqual(fey.foo, "bar")
XCTAssertEqual(fey.fuu, "baz")
}
func testMapRepresentable() throws {
struct Bar : MapFallibleRepresentable {
let bar: String
}
struct Foo : MapFallibleRepresentable {
let foo: Bar
}
struct Baz {
let baz: String
}
struct Fuu : MapFallibleRepresentable {
let fuu: Baz
}
XCTAssertEqual(try Foo(foo: Bar(bar: "bar")).asMap(), ["foo": ["bar": "bar"]])
XCTAssertThrowsError(try Fuu(fuu: Baz(baz: "baz")).asMap())
XCTAssertEqual(Map(1969).map, 1969)
XCTAssertEqual(true.map, true)
XCTAssertEqual(4.2.map, 4.2)
XCTAssertEqual(1969.map, 1969)
XCTAssertEqual("foo".map, "foo")
XCTAssertEqual(Data("foo").map, .data(Data("foo")))
let optional: Int? = nil
XCTAssertEqual(optional.map, nil)
XCTAssertEqual(Int?(1969).map, 1969)
XCTAssertEqual([1969].map, [1969])
XCTAssertEqual([1969].mapArray, [.int(1969)])
XCTAssertEqual(["foo": 1969].map, ["foo": 1969])
XCTAssertEqual(["foo": 1969].mapDictionary, ["foo": .int(1969)])
XCTAssertEqual(try optional.asMap(), nil)
XCTAssertEqual(try Int?(1969).asMap(), 1969)
let fuuOptional: Baz? = nil
XCTAssertThrowsError(try fuuOptional.asMap())
XCTAssertEqual(try [1969].asMap(), [1969])
let fuuArray: [Baz] = []
XCTAssertThrowsError(try fuuArray.asMap())
XCTAssertEqual(try ["foo": 1969].asMap(), ["foo": 1969])
let fuuDictionaryA: [Int: Foo] = [:]
XCTAssertThrowsError(try fuuDictionaryA.asMap())
let fuuDictionaryB: [String: Baz] = [:]
XCTAssertThrowsError(try fuuDictionaryB.asMap())
}
}
extension MapTests {
static var allTests: [(String, (MapTests) -> () throws -> Void)] {
return [
("testCreation", testCreation),
("testConversion", testConversion),
("testDescription", testDescription),
("testEquality", testEquality),
("testIndexPath", testIndexPath),
("testMapInitializable", testMapInitializable),
("testMapRepresentable", testMapRepresentable),
]
}
}
| mit | c40a1d5790d4378d1ebbb32c1692fb58 | 43.455324 | 335 | 0.666382 | 5.007583 | false | false | false | false |
wdkk/iSuperColliderKit | projects/iSCAppSwift/Codes/ViewController.swift | 1 | 2375 | /*
iSuperCollider Kit (iSCKit) - SuperCollider for iOS 7 later
Copyright (c) 2015 Kengo Watanabe <[email protected]>. All rights reserved.
http://wdkk.co.jp/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
import UIKit
class ViewController: UIViewController {
var tv_blue:TouchView?
var tv_red:TouchView?
var tv_green:TouchView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
let log_view = iSC.sharedLogView()
log_view?.frame = CGRect(x:0, y:50, width:(log_view?.frame.width)!, height:(log_view?.frame.height)!-50)
self.view.addSubview(log_view!)
tv_blue = TouchView(frame:CGRect(x:5, y:5, width:40, height:40))
tv_blue?.backgroundColor = .blue
tv_blue?.touches_began = touchesBlue
self.view.addSubview(tv_blue!)
tv_red = TouchView(frame:CGRect(x:50, y:5, width:40, height:40))
tv_red?.backgroundColor = .red
tv_red?.touches_began = touchesRed
self.view.addSubview(tv_red!)
tv_green = TouchView(frame:CGRect(x:200, y:5, width:40, height:40))
tv_green?.backgroundColor = .green
tv_green?.touches_began = touchesGreen
self.view.addSubview(tv_green!)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func touchesBlue(touches: Set<UITouch>, with event: UIEvent?)
{
iSC.interpret("a = {SinOsc.ar()}.play")
}
func touchesRed(touches: Set<UITouch>, with event: UIEvent?)
{
iSC.interpret("a.free")
}
func touchesGreen(touches: Set<UITouch>, with event: UIEvent?)
{
iSC.outputSpeaker()
}
}
| gpl-3.0 | a7b4fedf6d3fce6c0859024ae78db61e | 30.666667 | 112 | 0.665684 | 3.861789 | false | false | false | false |
EZ-NET/ESSwim | ESSwimTests/Function/StringTests.swift | 1 | 3064 | //
// StringTests.swift
// ESSwim
//
// Created by Tomohiro Kumagai on H27/05/13.
//
//
import Foundation
import XCTest
import ESTestKit
import Swim
class StringTests: XCTestCase {
let string = "Tests. Swift is a multi-paradigm, compiled programming language created by Apple Inc. for iOS and OS X development. Tests."
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testQuote() {
let string1 = "This is 'Test'."
let string2 = "This is ##Test##."
let quoted1 = string1.quote("'", escaping: "''")
let quoted2 = string2.quote("##", escaping: "**")
expected().equal(quoted1, "'This is ''Test''.'")
expected().equal(quoted2, "##This is **Test**.##")
}
func testReplace() {
let string1 = "This is 'Test'."
let string2 = "This is ##Test##."
let replaced1 = string1.replace("'", "''")
let replaced2 = string2.replace("##", "**")
expected().equal(replaced1, "This is ''Test''.")
expected().equal(replaced2, "This is **Test**.")
}
func testSplit() {
let string1 = "This is a Test."
let string2 = "A&&B&&C&&D"
let string3 = "/"
let elements1 = string1.split(" ")
let elements2 = string2.split("&&")
let elements3 = string3.split("/")
expected().equal(elements1, ["This", "is", "a", "Test."])
expected().equal(elements2, ["A", "B", "C", "D"])
expected().equal(elements3, ["", ""])
}
func testFind() {
if let found = self.string.indexOf("Tests") {
expected().equal(found, self.string.startIndex.advancedBy(0))
}
else {
failed("Not found.") as Void
}
if let found = self.string.indexOf(".") {
expected().equal(found, self.string.startIndex.advancedBy(5))
}
else {
failed("Not found.") as Void
}
if let found = self.string.indexOf("c.") {
expected().equal(found, self.string.startIndex.advancedBy(83))
}
else {
failed("Not found.") as Void
}
if let found = self.string.indexOf("t.") {
expected().equal(found, self.string.startIndex.advancedBy(113))
}
else {
failed("Not found.") as Void
}
}
func testFindFromIndex() {
if let found = self.string.indexOf("s.", fromIndex: self.string.startIndex.advancedBy(4)) {
expected().equal(found, self.string.startIndex.advancedBy(4))
}
else {
failed("Not found.") as Void
}
if let found = self.string.indexOf("s.", fromIndex: self.string.startIndex.advancedBy(5)) {
expected().equal(found, self.string.startIndex.advancedBy(120))
}
else {
failed("Not found.") as Void
}
if let found = self.string.indexOf("s.", fromIndex: self.string.startIndex.advancedBy(10)) {
expected().equal(found, self.string.startIndex.advancedBy(120))
}
else {
failed("Not found.") as Void
}
}
}
| mit | 597d3bb6fe6230081f054bd85fd9a8e8 | 21.529412 | 138 | 0.615862 | 3.393134 | false | true | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationData/NabuAuthentication/NetworkClients/NabuUserRecoveryClient.swift | 1 | 1426 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureAuthenticationDomain
import NetworkKit
protocol NabuUserRecoveryClientAPI: AnyObject {
func recoverUser(
jwt: String,
userId: String,
recoveryToken: String
) -> AnyPublisher<NabuOfflineTokenResponse, NetworkError>
}
final class NabuUserRecoveryClient: NabuUserRecoveryClientAPI {
// MARK: - Type
private enum Path {
static func recovery(userId: String) -> [String] {
["users", "recovery", userId]
}
}
// MARK: - Properties
private let requestBuilder: RequestBuilder
private let networkAdapter: NetworkAdapterAPI
// MARK: - Setup
init(
networkAdapter: NetworkAdapterAPI = resolve(tag: DIKitContext.retail),
requestBuilder: RequestBuilder = resolve(tag: DIKitContext.retail)
) {
self.networkAdapter = networkAdapter
self.requestBuilder = requestBuilder
}
func recoverUser(
jwt: String,
userId: String,
recoveryToken: String
) -> AnyPublisher<NabuOfflineTokenResponse, NetworkError> {
let request = requestBuilder.post(
path: Path.recovery(userId: userId),
body: try? NabuUserRecoveryPayload(jwt: jwt, recoveryToken: recoveryToken).encode()
)!
return networkAdapter.perform(request: request)
}
}
| lgpl-3.0 | b78fc35cc85fced3ec7b5c4da8dfe166 | 25.886792 | 95 | 0.669474 | 5.035336 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformUIKit/Foundation/InfoScreen/InfoScreenViewController.swift | 1 | 1355 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
public final class InfoScreenViewController: BaseScreenViewController {
// MARK: - IBOutlets
@IBOutlet private var thumbImageView: UIImageView!
@IBOutlet private var titleLabel: UILabel!
@IBOutlet private var descriptionLabel: UILabel!
@IBOutlet private var disclaimerTextView: InteractableTextView!
@IBOutlet private var buttonView: ButtonView!
// MARK: - Injected
private let presenter: InfoScreenPresenter
// MARK: - Lifecycle
public init(presenter: InfoScreenPresenter) {
self.presenter = presenter
super.init(nibName: InfoScreenViewController.objectName, bundle: .module)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewDidLoad() {
super.viewDidLoad()
set(
barStyle: .darkContent(background: .clear),
leadingButtonStyle: .close
)
thumbImageView.set(presenter.imageViewContent)
titleLabel.content = presenter.titleLabelContent
descriptionLabel.content = presenter.descriptionLabelContent
disclaimerTextView.viewModel = presenter.disclaimerViewModel
buttonView.viewModel = presenter.buttonViewModel
}
}
| lgpl-3.0 | 9ee33ca5bd2f04672daed1e78c3b9b63 | 32.02439 | 81 | 0.706056 | 5.394422 | false | false | false | false |
MaximilianoGaitan/MovingHelper | MovingHelper/ModelControllers/TaskLoader.swift | 1 | 1365 | //
// TaskLoader.swift
// MovingHelper
//
// Created by Ellen Shapiro on 6/7/15.
// Copyright (c) 2015 Razeware. All rights reserved.
//
import UIKit
/*
Struct to load tasks from JSON.
*/
public struct TaskLoader {
static func loadSavedTasksFromJSONFile(fileName: FileName) -> [Task]? {
let path = fileName.jsonFileName().pathInDocumentsDirectory()
if let data = NSData(contentsOfFile: path) {
return tasksFromData(data)
} else {
return nil
}
}
/**
- returns: The stock moving tasks included with the app.
*/
public static func loadStockTasks() -> [Task] {
if let path = NSBundle.mainBundle()
.pathForResource(FileName.StockTasks.rawValue, ofType: "json"),
data = NSData(contentsOfFile: path),
tasks = tasksFromData(data) {
return tasks
}
//Fall through case
NSLog("Tasks did not load!")
return [Task]()
}
private static func tasksFromData(data: NSData) -> [Task]? {
let error = NSErrorPointer()
do {
if let arrayOfTaskDictionaries = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [NSDictionary] {
return Task.tasksFromArrayOfJSONDictionaries(arrayOfTaskDictionaries)
} else {
NSLog("Error loading data: " + error.debugDescription)
return nil
}
} catch {
return nil
}
}
} | mit | df278e8b43dc2a594fbd12fbb778304d | 22.964912 | 119 | 0.647619 | 4.265625 | false | false | false | false |
Yoloabdo/CS-193P | Calculator/Calculator/GraphView.swift | 1 | 2460 | //
// GraphView.swift
// Calculator
//
// Created by abdelrahman mohamed on 2/14/16.
// Copyright © 2016 Abdulrhman dev. All rights reserved.
//
import UIKit
protocol GraphViewDataSource:class{
func scaleForGraphView(sender: GraphView) -> CGFloat
var origin:CGPoint? { get }
func y(x: CGFloat) -> CGFloat?
}
@IBDesignable
class GraphView: UIView {
weak var dataSource: GraphViewDataSource?
@IBInspectable
var color = UIColor.blackColor(){
didSet{
setNeedsDisplay()
}
}
@IBInspectable
var scale: CGFloat = 50.0 {
didSet{
setNeedsDisplay()
}
}
@IBInspectable
var lineWidth: CGFloat = 1.0 { didSet { setNeedsDisplay() } }
var origin = CGPoint() {
didSet{
setNeedsDisplay()
}
}
override var center:CGPoint{
didSet{
origin = center
}
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
scale = dataSource?.scaleForGraphView(self) ?? 50
origin = dataSource?.origin ?? center
AxesDrawer(color: color, contentScaleFactor: scale).drawAxesInRect(bounds, origin: origin, pointsPerUnit: scale)
drawFunc()
}
///Draws what ever lay there in the last parameter in calculator brain
///goes through each pixel to draw it in the view.
///Returns none.
func drawFunc(){
color.set()
let path = UIBezierPath()
path.lineWidth = lineWidth
var firstValue = true
var point = CGPoint()
for var i = 0; i <= Int(bounds.size.width * contentScaleFactor); i++ {
point.x = CGFloat(i) / contentScaleFactor
if let y = dataSource?.y((point.x - origin.x) / scale) {
if !y.isNormal && !y.isZero {
firstValue = true
continue
}
point.y = origin.y - y * scale
if firstValue {
path.moveToPoint(point)
firstValue = false
} else {
path.addLineToPoint(point)
}
} else {
firstValue = true
}
}
path.stroke()
}
}
| mit | 68c9d058f423451a154c7481b3b20f0f | 23.838384 | 120 | 0.539244 | 4.888668 | false | false | false | false |
boyXiong/XWSwiftRefresh | XWSwiftRefresh/Footer/XWRefreshFooter.swift | 7 | 1821 | //
// XWRefreshFooter.swift
// XWRefresh
//
// Created by Xiong Wei on 15/9/11.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 简书:猫爪
import UIKit
/** 抽象类,不直接使用,用于继承后,重写*/
public class XWRefreshFooter: XWRefreshComponent {
//MARK: 提供外界访问的
/** 提示没有更多的数据 */
public func noticeNoMoreData(){ self.state = XWRefreshState.NoMoreData }
/** 重置没有更多的数据(消除没有更多数据的状态) */
public func resetNoMoreData(){ self.state = XWRefreshState.Idle }
/** 忽略多少scrollView的contentInset的bottom */
public var ignoredScrollViewContentInsetBottom:CGFloat = 0
/** 自动根据有无数据来显示和隐藏(有数据就显示,没有数据隐藏) */
public var automaticallyHidden:Bool = true
//MARK: 私有的
//重写父类方法
override func prepare() {
super.prepare()
self.xw_height = XWRefreshFooterHeight
}
override public func willMoveToSuperview(newSuperview: UIView?) {
super.willMoveToSuperview(newSuperview)
if let _ = newSuperview {
//监听scrollView数据的变化
//由于闭包是Any 所以不能采用关联对象
let tmpClass = xwReloadDataClosureInClass()
tmpClass.reloadDataClosure = { (totalCount:Int) -> Void in
if self.automaticallyHidden == true {
//如果开启了自动隐藏,那就是在检查到总数量为 请求后的加载0 的时候就隐藏
self.hidden = totalCount == 0
}
}
self.scrollView.reloadDataClosureClass = tmpClass
}
}
}
| mit | 762f625a6b47d0e3023730bd8ee4a87d | 24.389831 | 76 | 0.596128 | 4.28 | false | false | false | false |
IBM-Swift/Kitura | Sources/Kitura/RouterParameterWalker.swift | 1 | 4758 | /*
* Copyright IBM Corporation 2016
*
* 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.
*/
/// A [type alias](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Declarations.html#//apple_ref/doc/uid/TP40014097-CH34-ID361) declaration to describe a handler for named parameters when using `Router.parameter(...)`. The example below shows two ways to use it, both as a function named `handler` to handle the "id" parameter and as a closure to handle the "name" parameter.
/// ### Usage Example: ###
/// ```swift
/// let router = Router()
/// func handler(request: RouterRequest, response: RouterResponse, param: String, next: @escaping () -> Void) throws -> Void {
/// //Code to handle id parameter here
/// next()
/// }
/// router.parameter("id", handler: handler)
///
/// router.parameter("name") { request, response, param, next in
/// //Code to handle name parameter here
/// next()
/// }
/// router.get("/item/:id") { request, response, next in
/// //This will be reached after the id parameter is handled by `handler`
/// }
/// router.get("/user/:name") { request, response, next in
/// //This will be reached after the name parameter is handled by the closure above
/// }
/// ```
/// - Parameter request: The `RouterRequest` object used to work with the incoming
/// HTTP request.
/// - Parameter response: The `RouterResponse` object used to respond to the
/// HTTP request.
/// - Parameter param: The named parameter to be handled.
/// - Parameter next: The closure called to invoke the next handler or middleware
/// associated with the request.
public typealias RouterParameterHandler = (RouterRequest, RouterResponse, String, @escaping () -> Void) throws -> Void
class RouterParameterWalker {
/// Collection of `RouterParameterHandler` instances for a specified parameter name.
private var parameterHandlers: [String : [RouterParameterHandler]]
init(handlers: [String : [RouterParameterHandler]]) {
self.parameterHandlers = handlers
}
/// Invoke all possible parameter handlers for the request.
///
/// - Parameter request: The `RouterRequest` object used to work with the incoming
/// HTTP request.
/// - Parameter response: The `RouterResponse` object used to respond to the
/// HTTP request.
/// - Parameter callback: The callback that will be invoked after all possible
/// handlers are invoked.
func handle(request: RouterRequest, response: RouterResponse, with callback: @escaping () -> Void) {
guard self.parameterHandlers.count > 0 else {
callback()
return
}
let filtered = request.parameters.filter { (key, _) in
self.parameterHandlers.keys.contains(key) && !request.handledNamedParameters.contains(key)
}.map { ($0, $1) }
self.handle(filtered: filtered, request: request, response: response, with: callback)
}
private func handle(filtered: [(String, String)], request: RouterRequest, response: RouterResponse, with callback: @escaping () -> Void) {
guard filtered.count > 0 else {
callback()
return
}
var parameters = filtered
let (key, value) = parameters[0]
if !request.handledNamedParameters.contains(key),
(self.parameterHandlers[key]?.count ?? 0) > 0,
let handler = self.parameterHandlers[key]?.remove(at: 0) {
do {
try handler(request, response, value) {
self.handle(filtered: parameters, request: request, response: response, with: callback)
}
} catch {
response.error = error
self.handle(filtered: parameters, request: request, response: response, with: callback)
}
} else {
request.handledNamedParameters.insert(key)
self.parameterHandlers[key] = nil
parameters.remove(at: parameters.startIndex)
self.handle(filtered: parameters, request: request, response: response, with: callback)
}
}
}
| apache-2.0 | b77bdeddb1e950f34433bc8e4e8c5540 | 43.886792 | 429 | 0.645649 | 4.535748 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/Common/FlowCommon/CAKeyframeAnimation+Extension.swift | 2 | 1585 | // Copyright © 2016-2019 JABT Labs Inc.
//
// 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
import UIKit
public extension CAKeyframeAnimation {
var reversed: CAKeyframeAnimation {
let reversed = CAKeyframeAnimation(keyPath: keyPath)
reversed.keyTimes = keyTimes?.reversed().map { NSNumber(floatLiteral: 1.0 - $0.doubleValue) }
reversed.values = values?.reversed()
reversed.timingFunctions = timingFunctions?.reversed().map { $0.reversed }
reversed.duration = duration
return reversed
}
}
| apache-2.0 | d3a1457cda47947c6a729c91c4237472 | 48.5 | 101 | 0.746212 | 4.785498 | false | false | false | false |
Vazzi/VJAutocomplete | VJAutocomplete_Swift/VJAutocomplete.swift | 2 | 11620 | //
// VJAutocomplete.m
//
// Created by Jakub Vlasák on 14/09/14.
// Copyright (c) 2014 Jakub Vlasak ( http://vlasakjakub.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 UIKit
/*! Protocol for manipulation with data
*/
protocol VJAutocompleteDataSource {
/*! Set the text of cell with given data. Data can be any object not only string.
Always return the parameter cell. Only set text. ([cell.textLabel setText:])
/param cell
/param item Source data. Data can be any object not only string that is why you have to define the cell text.
/return cell that has been given and modified
*/
func setCell(cell:UITableViewCell, withItem item:AnyObject) -> UITableViewCell
/*! Define data that should by shown by autocomplete on substring. Can be any object. Not only NSString.
/param substring
/return array of objects for substring
*/
func getItemsArrayWithSubstring(substring:String) -> [AnyObject]
}
/*! Protocol for manipulation with VJAutocomplete
*/
protocol VJAutocompleteDelegate {
/*! This is called when row was selected and autocomplete add text to text field.
/param rowIndex Selected row number
*/
func autocompleteWasSelectedRow(rowIndex: Int)
}
/*! VJAutocomplete table for text field is pinned to the text field that must be given. User starts
writing to the text field and VJAutocomplete show if has any suggestion. If there is no
suggestion then hide. User can choose suggestion by clicking on it. If user choose any suggestion
then it diseppeared and add text to text field. If user continues adding text then
VJAutocomplete start showing another suggestions or diseppead if has no.
*/
class VJAutocomplete: UITableView, UITableViewDelegate, UITableViewDataSource {
// -------------------------------------------------------------------------------
// MARK: - Public properties
// -------------------------------------------------------------------------------
// Set by init
var textField: UITextField! //!< Given text field. To this text field is autocomplete pinned to.
var parentView: UIView? //!< Parent view of text field (Change only if the current view is not what you want)
// Actions properties
var doNotShow = false //!< Do not show autocomplete
// Other properties
var maxVisibleRowsCount:UInt = 2 //!< Maximum height of autocomplete based on max visible rows
var cellHeight:CGFloat = 44.0 //!< Cell height
var minCountOfCharsToShow:UInt = 3 //!< Minimum count of characters needed to show autocomplete
var autocompleteDataSource:VJAutocompleteDataSource? //!< Manipulation with data
var autocompleteDelegate:VJAutocompleteDelegate? //!< Manipulation with autocomplete
// -------------------------------------------------------------------------------
// MARK: - Private properties
// -------------------------------------------------------------------------------
private let cellIdentifier = "VJAutocompleteCellIdentifier"
private var lastSubstring:String = "" //!< Last given substring
private var autocompleteItemsArray = [AnyObject]() //!< Current suggestions
private var autocompleteSearchQueue = dispatch_queue_create("VJAutocompleteQueue",
DISPATCH_QUEUE_SERIAL); //!< Queue for searching suggestions
private var isVisible = false //<! Is autocomplete visible
// -------------------------------------------------------------------------------
// MARK: - Init methods
// -------------------------------------------------------------------------------
init(textField: UITextField) {
super.init(frame: textField.frame, style: UITableViewStyle.Plain);
// Text field
self.textField = textField;
// Set parent view as text field super view
self.parentView = textField.superview;
// Setup table view
setupTableView()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder);
}
// -------------------------------------------------------------------------------
// MARK: - Setups
// -------------------------------------------------------------------------------
private func setupTableView() {
// Protocols
dataSource = self;
delegate = self;
// Properties
scrollEnabled = true;
// Visual properties
backgroundColor = UIColor.whiteColor();
rowHeight = cellHeight;
// Empty footer
tableFooterView = UIView(frame: CGRectZero);
}
// -------------------------------------------------------------------------------
// MARK: - Public methods
// -------------------------------------------------------------------------------
func setBorder(width: CGFloat, cornerRadius: CGFloat, color: UIColor) {
self.layer.borderWidth = width;
self.layer.cornerRadius = cornerRadius;
self.layer.borderColor = color.CGColor;
}
func searchAutocompleteEntries(WithSubstring substring: NSString) {
let lastCount = autocompleteItemsArray.count;
autocompleteItemsArray.removeAll(keepCapacity: false);
// If substring has less than min. characters then hide and return
if (UInt(substring.length) < minCountOfCharsToShow) {
hideAutocomplete();
return;
}
let substringBefore = lastSubstring;
lastSubstring = substring as String;
// If substring is the same as before and before it has no suggestions then
// do not search for suggestions
if (substringBefore == substring.substringToIndex(substring.length - 1) &&
lastCount == 0 &&
!substringBefore.isEmpty) {
return;
}
dispatch_async(autocompleteSearchQueue) { ()
// Save new suggestions
if let dataArray = self.autocompleteDataSource?.getItemsArrayWithSubstring(substring as String) {
self.autocompleteItemsArray = dataArray;
}
// Call show or hide autocomplete and reload data on main thread
dispatch_async(dispatch_get_main_queue()) { ()
if (self.autocompleteItemsArray.count != 0) {
self.showAutocomplete();
} else {
self.hideAutocomplete();
}
self.reloadData();
}
}
}
func hideAutocomplete() {
if (!isVisible) {
return;
}
removeFromSuperview();
isVisible = false;
}
func showAutocomplete() {
if (doNotShow) {
return;
}
if (isVisible) {
removeFromSuperview();
}
self.isVisible = true;
var origin = getTextViewOrigin();
setFrame(origin, height: computeHeight());
layer.zPosition = CGFloat(FLT_MAX);
parentView?.addSubview(self);
}
func shouldChangeCharacters(InRange range: NSRange, replacementString string: String) {
var substring = NSString(string: textField.text);
substring = substring.stringByReplacingCharactersInRange(range, withString: string);
searchAutocompleteEntries(WithSubstring: substring);
}
func isAutocompleteVisible() -> Bool {
return isVisible;
}
// -------------------------------------------------------------------------------
// MARK: - UITableView data source
// -------------------------------------------------------------------------------
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return autocompleteItemsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell!;
if let oldCell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? UITableViewCell {
cell = oldCell;
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier);
}
var newCell = autocompleteDataSource?.setCell(cell, withItem: autocompleteItemsArray[indexPath.row])
return cell
}
// -------------------------------------------------------------------------------
// MARK: - UITableView delegate
// -------------------------------------------------------------------------------
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// Get the cell
let selectedCell = tableView.cellForRowAtIndexPath(indexPath)
// Set text to
textField.text = selectedCell?.textLabel!.text
// Call delegate method
autocompleteDelegate?.autocompleteWasSelectedRow(indexPath.row)
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return cellHeight
}
// -------------------------------------------------------------------------------
// MARK: - Private
// -------------------------------------------------------------------------------
private func computeHeight() -> CGFloat {
// Set number of cells (do not show more than maxSuggestions)
var visibleRowsCount = autocompleteItemsArray.count as NSInteger;
if (visibleRowsCount > NSInteger(maxVisibleRowsCount)) {
visibleRowsCount = NSInteger(maxVisibleRowsCount);
}
// Calculate autocomplete height
let height = cellHeight * CGFloat(visibleRowsCount);
return height;
}
private func getTextViewOrigin() -> CGPoint {
var textViewOrigin: CGPoint;
if (parentView?.isEqual(textField.superview) != nil) {
textViewOrigin = textField.frame.origin;
} else {
textViewOrigin = textField.convertPoint(textField.frame.origin,
toView: parentView);
}
return textViewOrigin;
}
private func setFrame(textViewOrigin: CGPoint, height: CGFloat) {
var newFrame = CGRectMake(textViewOrigin.x, textViewOrigin.y + CGRectGetHeight(textField.bounds),
CGRectGetWidth(textField.bounds), height);
frame = newFrame;
}
}
| mit | 2482806afa067449cfe79a8105c746c6 | 37.220395 | 123 | 0.577933 | 5.720827 | false | false | false | false |
carabina/DDMathParser | MathParser/Expressionizer.swift | 2 | 12154 | //
// Expressionizer.swift
// DDMathParser
//
// Created by Dave DeLong on 8/17/15.
//
//
import Foundation
private extension GroupedToken {
private var groupedOperator: Operator? {
guard case .Operator(let o) = self.kind else { return nil }
return o
}
}
private enum TokenOrExpression {
case Token(GroupedToken)
case Expression(MathParser.Expression)
var token: GroupedToken? {
guard case .Token(let t) = self else { return nil }
return t
}
var expression: MathParser.Expression? {
guard case .Expression(let e) = self else { return nil }
return e
}
var isToken: Bool { return token != nil }
var range: Range<String.Index> {
switch self {
case .Token(let t): return t.range
case .Expression(let e): return e.range
}
}
}
public struct Expressionizer {
private let grouper: TokenGrouper
public init(grouper: TokenGrouper) {
self.grouper = grouper
}
public func expression() throws -> Expression {
let rootToken = try grouper.group()
return try expressionizeToken(rootToken)
}
internal func expressionizeToken(token: GroupedToken) throws -> Expression {
switch token.kind {
case .Number(let d):
return Expression(kind: .Number(d), range: token.range)
case .Variable(let v):
return Expression(kind: .Variable(v), range: token.range)
case .Function(let f, let parameters):
var parameterExpressions = Array<Expression>()
for parameter in parameters {
let info = try expressionizeToken(parameter)
parameterExpressions.append(info)
}
return Expression(kind: .Function(f, parameterExpressions), range: token.range)
case .Operator(_):
// this will ultimately result in an error,
// but we'll let the group logic take care of that
let newGroup = GroupedToken(kind: .Group([token]), range: token.range)
return try expressionizeToken(newGroup)
case .Group(let tokens):
return try expressionizeGroup(tokens)
}
}
private func expressionizeGroup(tokens: Array<GroupedToken>) throws -> Expression {
var wrappers = tokens.map { TokenOrExpression.Token($0) }
while wrappers.count > 1 || wrappers.first?.isToken == true {
let (indices, maybeOp) = operatorWithHighestPrecedence(wrappers)
guard let first = indices.first else {
let range = wrappers.first?.range ?? "".startIndex ..< "".endIndex
throw ExpressionError(kind: .InvalidFormat, range: range)
}
guard let last = indices.last else { fatalError("If there's a first, there's a last") }
guard let op = maybeOp else { fatalError("Indices but no operator??") }
let index = op.associativity == .Left ? first : last
wrappers = try collapseWrappers(wrappers, aroundOperator: op, atIndex: index)
}
guard let wrapper = wrappers.first else {
fatalError("Implementation flaw")
}
switch wrapper {
case .Token(let t):
return try expressionizeToken(t)
case .Expression(let e):
return e
}
}
private func operatorWithHighestPrecedence(wrappers: Array<TokenOrExpression>) -> (Array<Int>, Operator?) {
var indices = Array<Int>()
var precedence = Int.min
var op: Operator?
wrappers.enumerate().forEach { (index, wrapper) in
guard let token = wrapper.token else { return }
guard case let .Operator(o) = token.kind else { return }
guard let p = o.precedence else {
fatalError("Operator with unknown precedence")
}
if p == precedence {
indices.append(index)
} else if p > precedence {
precedence = p
op = o
indices.removeAll()
indices.append(index)
}
}
return (indices, op)
}
private func collapseWrappers(wrappers: Array<TokenOrExpression>, aroundOperator op: Operator, atIndex index: Int) throws -> Array<TokenOrExpression> {
switch (op.arity, op.associativity) {
case (.Binary, _):
return try collapseWrappers(wrappers, aroundBinaryOperator: op, atIndex: index)
case (.Unary, .Left):
var inoutIndex = index
return try collapseWrappers(wrappers, aroundLeftUnaryOperator: op, atIndex: &inoutIndex)
case (.Unary, .Right):
return try collapseWrappers(wrappers, aroundRightUnaryOperator: op, atIndex: index)
}
}
private func collapseWrappers(wrappers: Array<TokenOrExpression>, aroundBinaryOperator op: Operator, atIndex index: Int) throws -> Array<TokenOrExpression> {
let operatorWrapper = wrappers[index]
guard index > 0 else {
throw ExpressionError(kind: .MissingLeftOperand(op), range: operatorWrapper.range)
}
guard index < wrappers.count - 1 else {
throw ExpressionError(kind: .MissingRightOperand(op), range: operatorWrapper.range)
}
var operatorIndex = index
var rightIndex = operatorIndex + 1
var rightWrapper = wrappers[rightIndex]
var collapsedWrappers = wrappers
if let t = rightWrapper.token {
if let o = t.groupedOperator where o.associativity == .Right && o.arity == .Unary {
collapsedWrappers = try collapseWrappers(collapsedWrappers, aroundRightUnaryOperator: o, atIndex: rightIndex)
rightWrapper = collapsedWrappers[rightIndex]
} else {
rightWrapper = .Expression(try expressionizeToken(t))
}
}
collapsedWrappers[rightIndex] = rightWrapper
var leftIndex = index - 1
var leftWrapper = collapsedWrappers[leftIndex]
if let t = leftWrapper.token {
if let o = t.groupedOperator where o.associativity == .Left && o.arity == .Unary {
collapsedWrappers = try collapseWrappers(collapsedWrappers, aroundLeftUnaryOperator: o, atIndex: &leftIndex)
leftWrapper = collapsedWrappers[leftIndex]
operatorIndex = leftIndex + 1
rightIndex = operatorIndex + 1
} else {
leftWrapper = .Expression(try expressionizeToken(t))
}
}
guard let leftOperand = leftWrapper.expression else { fatalError("Never resolved left operand") }
guard let rightOperand = rightWrapper.expression else { fatalError("Never resolved right operand") }
let range = leftOperand.range.startIndex ..< rightOperand.range.endIndex
let expression = Expression(kind: .Function(op.function, [leftOperand, rightOperand]), range: range)
let replacementRange = leftIndex ... rightIndex
collapsedWrappers.replaceRange(replacementRange, with: [.Expression(expression)])
return collapsedWrappers
}
private func collapseWrappers(wrappers: Array<TokenOrExpression>, aroundLeftUnaryOperator op: Operator, inout atIndex index: Int) throws -> Array<TokenOrExpression> {
var operatorIndex = index
let operatorWrapper = wrappers[operatorIndex]
guard operatorIndex > 0 else {
throw ExpressionError(kind: .MissingLeftOperand(op), range: operatorWrapper.range) // Missing operand
}
var operandIndex = operatorIndex - 1
var operandWrapper = wrappers[operandIndex]
var collapsedWrappers = wrappers
if let t = operandWrapper.token {
if let o = t.groupedOperator where o.associativity == .Left && o.arity == .Unary {
// recursively collapse left unary operators
// technically, this should never happen, because left unary operators
// are left-associative, which means they evaluate from left-to-right
// This means that a left-assoc unary operator should never have another
// left-assoc unary operator to its left, because it would've already
// have been resolved
// Regardless, this is here for completeness
var newOperandIndex = operandIndex
collapsedWrappers = try collapseWrappers(collapsedWrappers, aroundLeftUnaryOperator: o, atIndex: &newOperandIndex)
let indexDelta = operandIndex - newOperandIndex
operatorIndex = operatorIndex - indexDelta
operandIndex = operandIndex - 1
} else {
operandWrapper = .Expression(try expressionizeToken(t))
}
}
guard let operand = operandWrapper.expression else {
fatalError("Implementation flaw")
}
let range = operandWrapper.range.startIndex ..< operatorWrapper.range.endIndex
let expression = Expression(kind: .Function(op.function, [operand]), range: range)
let replacementRange = operandIndex ... operatorIndex
collapsedWrappers.replaceRange(replacementRange, with: [.Expression(expression)])
index = operandIndex
return collapsedWrappers
}
private func collapseWrappers(wrappers: Array<TokenOrExpression>, aroundRightUnaryOperator op: Operator, atIndex index: Int) throws -> Array<TokenOrExpression> {
var collapsedWrappers = wrappers
let operatorWrapper = collapsedWrappers[index]
let operandIndex = index + 1
guard operandIndex < wrappers.count else {
throw ExpressionError(kind: .MissingRightOperand(op), range: operatorWrapper.range) // Missing operand
}
var operandWrapper = collapsedWrappers[operandIndex];
if let t = operandWrapper.token {
if let o = t.groupedOperator where o.associativity == .Right && o.arity == .Unary {
// recursively collapse right unary operators
// technically, this should never happen, because right unary operators
// are right-associative, which means they evaluate from right-to-left
// This means that a right-assoc unary operator should never have another
// right-assoc unary operator to its right, because it would've already
// have been resolved
// Regardless, this is here for completeness
collapsedWrappers = try collapseWrappers(collapsedWrappers, aroundRightUnaryOperator: o, atIndex: operandIndex)
operandWrapper = collapsedWrappers[operandIndex]
} else {
operandWrapper = .Expression(try expressionizeToken(t))
}
}
guard let operand = operandWrapper.expression else {
fatalError("Implementation flaw")
}
let range = operatorWrapper.range.startIndex ..< operand.range.endIndex
let expression: Expression
if op.builtInOperator == .UnaryPlus {
// the Unary Plus operator does nothing and should be ignored
expression = operand
} else {
expression = Expression(kind: .Function(op.function, [operand]), range: range)
}
let replacementExpressionRange = index ... operandIndex
collapsedWrappers.replaceRange(replacementExpressionRange, with: [.Expression(expression)])
return collapsedWrappers
}
}
| mit | a9eeb869c44494677b67a2406075a49e | 40.340136 | 170 | 0.598897 | 5.236536 | false | false | false | false |
joshua-d-miller/macOSLAPS | macOSLAPS/Extensions/CharacterSetExlusion.swift | 1 | 1193 | ///
/// CharacterSetExlusion.swift
/// macOSLAPS
///
/// Created by Joshua D. Miller on 7/7/17.
///
///
import Foundation
func CharacterSetExclusions(password_chars: String) -> String {
// New exclusion that will remove a specified CharacterSet
// From Using CharacterSets in Swift - https://medium.com/@jacqschweiger/using-character-sets-in-swift-945b99ba17e
let exclusion_sets = Constants.character_exclusion_sets
if !(exclusion_sets?.isEmpty)! {
var filtered_pw_chars = ""
for item in exclusion_sets! {
if item == "symbols" {
filtered_pw_chars = password_chars.components(separatedBy: CharacterSet.punctuationCharacters).joined().components(separatedBy: CharacterSet.symbols).joined()
}
else if item == "letters" {
filtered_pw_chars = password_chars.components(separatedBy: CharacterSet.letters).joined()
}
else if item == "numbers" {
filtered_pw_chars = password_chars.components(separatedBy: CharacterSet.decimalDigits).joined()
}
}
return(filtered_pw_chars)
}
else {
return(password_chars)
}
}
| mit | 3269929844287ce489815adbcf881958 | 35.151515 | 174 | 0.634535 | 4.322464 | false | false | false | false |
IvoPaunov/selfie-apocalypse | Selfie apocalypse/Selfie apocalypse/TheTrueStoryViewController.swift | 1 | 1352 | //
// TheTrueStoryViewController.swift
// Selfie apocalypse
//
// Created by Ivko on 2/8/16.
// Copyright © 2016 Ivo Paounov. All rights reserved.
//
import UIKit
class TheTrueStoryViewController: UIViewController {
let transitionManager = TransitionManager()
@IBOutlet weak var theTrueStoryLabe: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
self.setTheTrueStory()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setTheTrueStory(){
let path = NSBundle.mainBundle().pathForResource("the-true-story", ofType: "txt")
var text: String?
do{
text = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding)
}
catch{
text = "There is no stroy someting wrnog happend when reading the file."
}
self.theTrueStoryLabe.text = text
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let toViewController = segue.destinationViewController as UIViewController
self.transitionManager.toLeft = false
toViewController.transitioningDelegate = self.transitionManager
}
}
| mit | 539c226028deb4b953eb98d53e28bad2 | 27.145833 | 89 | 0.641007 | 5.003704 | false | false | false | false |
aestesis/Aether | Sources/Aether/Foundation/Size.swift | 1 | 11349 | //
// Size.swift
// Aether
//
// Created by renan jegouzo on 23/02/2016.
// Copyright © 2016 aestesis. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import SwiftyJSON
#if os(macOS) || os(iOS) || os(tvOS)
import CoreGraphics
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Size : CustomStringConvertible,JsonConvertible {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var width:Double
public var height:Double
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var w:Double {
get { return width; }
set(w) { width=w; }
}
public var h:Double {
get { return height; }
set(h) { height=h; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var ceil: Size {
return Size(Foundation.ceil(width),Foundation.ceil(height))
}
public func crop(_ ratio:Double,margin:Double=0) -> Size {
let dd = ratio
let ds = self.ratio
if ds>dd {
let h=height-margin*2;
let w=dd*h;
return Size(w,h);
} else {
let w=width-margin*2;
let h=w/dd;
return Size(w,h);
}
}
public func extend(_ border:Double) -> Size {
return Size(width+border*2,height+border*2)
}
public func extend(w:Double,h:Double) -> Size {
return Size(width+w*2,height+h*2)
}
public func extend(_ sz:Size) -> Size {
return self + sz*2
}
public var int: SizeI {
return SizeI(Int(width),Int(height))
}
public var floor: Size {
return Size(Foundation.floor(width),Foundation.floor(height))
}
public var length: Double {
return sqrt(width*width+height*height)
}
public func lerp(_ to:Size,coef:Double) -> Size {
return Size(to.width*coef+width*(1-coef),to.height*coef+height*(1-coef))
}
public var normalize: Size {
return Size(width/length,height/length)
}
public func point(_ px:Double,_ py:Double) -> Point {
return Point(width*px,height*py)
}
public var point: Point {
return Point(width,height)
}
public func point(px:Double,py:Double) -> Point {
return Point(width*px,height*py)
}
public var ratio: Double {
return width/height
}
public var round: Size {
return Size(Foundation.round(width),Foundation.round(height))
}
public var rotate: Size {
return Size(height,width)
}
public func scale(_ scale:Double) -> Size {
return Size(width*scale,height*scale)
}
public func scale(_ w:Double,_ h:Double) -> Size {
return Size(width*w,height*h)
}
public var surface:Double {
return width*height;
}
public var transposed:Size {
return Size(h,w)
}
public var description: String {
return "{w:\(width),h:\(height)}"
}
public var json: JSON {
return JSON([w:w,h:h])
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(_ s:CGSize) {
width=Double(s.width)
height=Double(s.height)
}
public init(_ s:SizeI) {
width=Double(s.width)
height=Double(s.height)
}
public init(_ p:PointI) {
width=Double(p.x)
height=Double(p.y)
}
public init(_ square:Double) {
width=square;
height=square;
}
public init(_ w:Double,_ h:Double) {
width=w;
height=h;
}
public init(_ w:Int,_ h:Int) {
width=Double(w);
height=Double(h);
}
public init(json: JSON) {
if let w=json["width"].double {
width=w
} else if let w=json["w"].double {
width=w
} else {
width=0;
}
if let h=json["height"].double {
height=h
} else if let h=json["h"].double {
height=h
} else {
height=0;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var system : CGSize {
return CGSize(width:CGFloat(w),height: CGFloat(h))
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: Size {
return Size(0,0)
}
public static var infinity: Size {
return Size(Double.infinity,Double.infinity)
}
public static var unity: Size {
return Size(1,1)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: Size, rhs: Size) -> Bool {
return (lhs.width==rhs.width)&&(lhs.height==rhs.height);
}
public func !=(lhs: Size, rhs: Size) -> Bool {
return (lhs.width != rhs.width)||(lhs.height != rhs.height);
}
public func +(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w+rhs.w),(lhs.h+rhs.h));
}
public func -(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w-rhs.w),(lhs.h-rhs.h));
}
public func *(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w*rhs.w),(lhs.h*rhs.h));
}
public func *(lhs: Size, rhs: Double) -> Size {
return Size((lhs.w*rhs),(lhs.h*rhs));
}
public func /(lhs: Size, rhs: Size) -> Size {
return Size((lhs.w/rhs.w),(lhs.h/rhs.h));
}
public func /(lhs: Size, rhs: Double) -> Size {
return Size((lhs.w/rhs),(lhs.h/rhs));
}
public prefix func - (size: Size) -> Size {
return Size(-size.w,-size.h)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct SizeI {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var width:Int
public var height:Int
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var w:Int {
get { return width; }
set(w) { width=w; }
}
public var h:Int {
get { return height; }
set(h) { height=h; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var point: PointI {
return PointI(x:width,y:height)
}
public var surface:Int {
return width*height;
}
public var description: String {
return "{w:\(width),h:\(height)}"
}
public var json: JSON {
return JSON.parse(string: description)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(_ w:Int,_ h:Int) {
width=w;
height=h;
}
public init(json: JSON) {
if let w=json["width"].number {
width=Int(truncating:w)
} else if let w=json["w"].number {
width=Int(truncating:w)
} else {
width=0;
}
if let h=json["height"].number {
height=Int(truncating:h)
} else if let h=json["h"].number {
height=Int(truncating:h)
} else {
height=0;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: SizeI {
return SizeI(0,0)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: SizeI, rhs: SizeI) -> Bool {
return (lhs.width==rhs.width)&&(lhs.height==rhs.height);
}
public func !=(lhs: SizeI, rhs: SizeI) -> Bool {
return (lhs.width != rhs.width)||(lhs.height != rhs.height);
}
public func +(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w+rhs.w),(lhs.h+rhs.h));
}
public func -(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w-rhs.w),(lhs.h-rhs.h));
}
public func *(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w*rhs.w),(lhs.h*rhs.h));
}
public func *(lhs: SizeI, rhs: Int) -> SizeI {
return SizeI((lhs.w*rhs),(lhs.h*rhs));
}
public func /(lhs: SizeI, rhs: SizeI) -> SizeI {
return SizeI((lhs.w/rhs.w),(lhs.h/rhs.h));
}
public func /(lhs: SizeI, rhs: Int) -> SizeI {
return SizeI((lhs.w/rhs),(lhs.h/rhs));
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | 297782f47036763d0b4829330b0473fb | 35.964169 | 110 | 0.370021 | 5.010155 | false | false | false | false |
yonbergman/project-atlas | atlas/YBReavealViewController.swift | 1 | 1121 | //
// YBReavealViewController.swift
// atlas
//
// Created by Yonatan Bergman on 10/20/14.
// Copyright (c) 2014 Yonatan Bergman. All rights reserved.
//
import UIKit
class YBReavealViewController: PKRevealController {
var navigationVC:UINavigationController {
return self.frontViewController as UINavigationController
}
var netrunnerDB:YBNetrunnerDB?
override func viewDidLoad() {
super.viewDidLoad()
let n = self.storyboard?.instantiateViewControllerWithIdentifier("nav") as UINavigationController?
if let frontvc = n {
let cardList = frontvc.topViewController as YBCardListViewController
if netrunnerDB != nil{
cardList.netrunnerDB = netrunnerDB!
}
self.frontViewController = frontvc
}
let m = self.storyboard?.instantiateViewControllerWithIdentifier("menu") as YBMenuTableViewController
m.netrunnerDB = netrunnerDB!
self.leftViewController = m
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 7a902967b7f691b0efa58bbedb17a898 | 27.025 | 109 | 0.671722 | 4.938326 | false | false | false | false |
Sage-Bionetworks/MoleMapper | MoleMapper/Charts/Classes/Renderers/BarChartRenderer.swift | 1 | 24245 | //
// BarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
@objc
public protocol BarChartRendererDelegate
{
func barChartRendererData(renderer: BarChartRenderer) -> BarChartData!
func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!
func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int
func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter!
func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double
func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double
func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double
func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double
func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool
func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool
func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool
func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool
}
public class BarChartRenderer: ChartDataRendererBase
{
public weak var delegate: BarChartRendererDelegate?
public init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.delegate = delegate
}
public override func drawData(context context: CGContext?)
{
let barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return
}
for (var i = 0; i < barData.dataSetCount; i++)
{
let set = barData.getDataSetByIndex(i)
if (set !== nil && set!.isVisible)
{
drawDataSet(context: context, dataSet: set as! BarChartDataSet, index: i)
}
}
}
internal func drawDataSet(context context: CGContext?, dataSet: BarChartDataSet, index: Int)
{
CGContextSaveGState(context)
let barData = delegate!.barChartRendererData(self)
let trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency)
let drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self)
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
let barWidth: CGFloat = 0.5
let phaseY = _animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
var vals = e.values
if (!containsStacks || vals == nil)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextFillRect(context, barRect)
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals!.count; k++)
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top: CGFloat, bottom: CGFloat
if isInverted
{
bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart)
top = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
top = y >= yStart ? CGFloat(y) : CGFloat(yStart)
bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
top *= phaseY
bottom *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
/// Prepares a bar for being highlighted.
internal func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
let left = x - barWidth + barspacehalf
let right = x + barWidth - barspacehalf
let top = CGFloat(y1)
let bottom = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixel(&rect, phaseY: _animator.phaseY)
}
public override func drawValues(context context: CGContext?)
{
// if values are drawn
if (passesCheck())
{
let barData = delegate!.barChartRendererData(self)
let defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self)
var dataSets = barData.dataSets
let drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self)
var posOffset: CGFloat
var negOffset: CGFloat
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
let dataSet = dataSets[i] as! BarChartDataSet
if (!dataSet.isDrawValuesEnabled)
{
continue
}
let isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueOffsetPlus: CGFloat = 4.5
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if (isInverted)
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let valueTextColor = dataSet.valueTextColor
var formatter = dataSet.valueFormatter
if (formatter === nil)
{
formatter = defaultValueFormatter
}
let trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i)
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
let val = entries[j].value
drawValue(context: context,
value: formatter!.stringFromNumber(val)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
else
{
// if we have stacks
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(e.value)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
else
{
// draw stack values
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * _animator.phaseY))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
let x = valuePoints[j].x
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(vals[k])!,
xPos: x,
yPos: y,
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
}
}
}
}
}
/// Draws a value at the specified x and y position.
internal func drawValue(context context: CGContext?, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
public override func drawExtras(context context: CGContext?)
{
}
private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint())
public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight])
{
let barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return
}
CGContextSaveGState(context)
let setCount = barData.dataSetCount
let drawHighlightArrowEnabled = delegate!.barChartIsDrawHighlightArrowEnabled(self)
var barRect = CGRect()
for (var i = 0; i < indices.count; i++)
{
let h = indices[i]
let index = h.xIndex
let dataSetIndex = h.dataSetIndex
let set = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
let barspaceHalf = set.barSpace / 2.0
let trans = delegate!.barChartRenderer(self, transformerForAxis: set.axisDependency)
CGContextSetFillColorWithColor(context, set.highlightColor.CGColor)
CGContextSetAlpha(context, set.highLightAlpha)
// check outofbounds
if (CGFloat(index) < (CGFloat(delegate!.barChartRendererChartXMax(self)) * _animator.phaseX) / CGFloat(setCount))
{
let e = set.entryForXIndex(index) as! BarChartDataEntry!
if (e === nil || e.xIndex != index)
{
continue
}
let groupspace = barData.groupSpace
let isStack = h.stackIndex < 0 ? false : true
// calculate the correct x-position
let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index)
let y1: Double
let y2: Double
if (isStack)
{
y1 = h.range?.from ?? 0.0
y2 = (h.range?.to ?? 0.0) * Double(_animator.phaseY)
}
else
{
y1 = e.value
y2 = 0.0
}
prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect)
CGContextFillRect(context, barRect)
if (drawHighlightArrowEnabled)
{
CGContextSetAlpha(context, 1.0)
// distance between highlight arrow and bar
let offsetY = _animator.phaseY * 0.07
CGContextSaveGState(context)
let pixelToValueMatrix = trans.pixelToValueMatrix
let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c))
let arrowWidth = set.barSpace / 2.0
let arrowHeight = arrowWidth * xToYRel
let yArrow = y1 > -y2 ? y1 : y1;
_highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4
_highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY
_highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight
_highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight
trans.pointValuesToPixel(&_highlightArrowPtsBuffer)
CGContextBeginPath(context)
CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y)
CGContextClosePath(context)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
}
CGContextRestoreGState(context)
}
public func getTransformedValues(trans trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY)
}
internal func passesCheck() -> Bool
{
let barData = delegate!.barChartRendererData(self)
if (barData === nil)
{
return false
}
return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX
}
} | bsd-3-clause | df5ca0056581dce74a02aa4e1904d7b5 | 40.164686 | 232 | 0.460301 | 6.442998 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/Feed/SearchedFeed/SearchedFeedVoiceCell.swift | 1 | 4021 | //
// SearchedFeedVoiceCell.swift
// Yep
//
// Created by NIX on 16/4/19.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import RealmSwift
final class SearchedFeedVoiceCell: SearchedFeedBasicCell {
override class func heightOfFeed(feed: DiscoveredFeed) -> CGFloat {
let height = super.heightOfFeed(feed) + (10 + 50)
return ceil(height)
}
lazy var voiceContainerView: FeedVoiceContainerView = {
let view = FeedVoiceContainerView()
view.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
return view
}()
var audioPlaying: Bool = false {
willSet {
voiceContainerView.audioPlaying = newValue
}
}
var playOrPauseAudioAction: (SearchedFeedVoiceCell -> Void)?
var audioPlayedDuration: NSTimeInterval = 0 {
willSet {
updateVoiceContainerView()
}
}
private func updateVoiceContainerView() {
guard let feed = feed, realm = try? Realm(), feedAudio = FeedAudio.feedAudioWithFeedID(feed.id, inRealm: realm) else {
return
}
if let (audioDuration, audioSamples) = feedAudio.audioMetaInfo {
voiceContainerView.voiceSampleView.samples = audioSamples
voiceContainerView.voiceSampleView.progress = CGFloat(audioPlayedDuration / audioDuration)
}
if let playingFeedAudio = YepAudioService.sharedManager.playingFeedAudio where playingFeedAudio.feedID == feedAudio.feedID, let onlineAudioPlayer = YepAudioService.sharedManager.onlineAudioPlayer where onlineAudioPlayer.yep_playing {
audioPlaying = true
} else {
audioPlaying = false
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(voiceContainerView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configureWithFeed(feed: DiscoveredFeed, layout: SearchedFeedCellLayout, keyword: String?) {
super.configureWithFeed(feed, layout: layout, keyword: keyword)
if let attachment = feed.attachment {
if case let .Audio(audioInfo) = attachment {
voiceContainerView.voiceSampleView.sampleColor = UIColor.leftWaveColor()
voiceContainerView.voiceSampleView.samples = audioInfo.sampleValues
let timeLengthString = audioInfo.duration.yep_feedAudioTimeLengthString
voiceContainerView.timeLengthLabel.text = timeLengthString
let audioLayout = layout.audioLayout!
voiceContainerView.frame = audioLayout.voiceContainerViewFrame
if let realm = try? Realm() {
let feedAudio = FeedAudio.feedAudioWithFeedID(audioInfo.feedID, inRealm: realm)
if let feedAudio = feedAudio, playingFeedAudio = YepAudioService.sharedManager.playingFeedAudio, audioPlayer = YepAudioService.sharedManager.audioPlayer {
audioPlaying = (feedAudio.feedID == playingFeedAudio.feedID) && audioPlayer.playing
} else {
let newFeedAudio = FeedAudio()
newFeedAudio.feedID = audioInfo.feedID
newFeedAudio.URLString = audioInfo.URLString
newFeedAudio.metadata = audioInfo.metaData
let _ = try? realm.write {
realm.add(newFeedAudio)
}
audioPlaying = false
}
voiceContainerView.playOrPauseAudioAction = { [weak self] in
if let strongSelf = self {
strongSelf.playOrPauseAudioAction?(strongSelf)
}
}
}
}
}
}
}
| mit | 8fa3aaab5480c9b9682171a4186ebe7c | 33.93913 | 241 | 0.617471 | 5.164524 | false | false | false | false |
banxi1988/Staff | Pods/BXForm/Pod/Classes/Buttons/IconButton.swift | 1 | 936 | //
// IconButton.swift
//
// Created by Haizhen Lee on 15/11/10.
//
import UIKit
public class IconButton:UIButton{
public var iconPadding = FormMetrics.iconPadding
public var cornerRadius:CGFloat = 4.0 {
didSet{
setNeedsLayout()
}
}
public var lineWidth :CGFloat = 0.5 {
didSet{
setNeedsLayout()
}
}
lazy var maskLayer:CALayer = {
let layer = CALayer()
self.layer.mask = layer
return layer
}()
public override func intrinsicContentSize() -> CGSize {
let size = super.intrinsicContentSize()
return CGSize(width: size.width + iconPadding, height: size.height)
}
public var icon:UIImage?{
set{
setImage(newValue, forState: .Normal)
titleEdgeInsets = UIEdgeInsets(top: 0, left: newValue == nil ? 0: iconPadding, bottom: 0, right: 0)
invalidateIntrinsicContentSize()
}get{
return imageForState(.Normal)
}
}
}
| mit | 84fc48d327484ef972918c98dfda16fc | 19.8 | 105 | 0.639957 | 4.178571 | false | false | false | false |
chriscox/material-components-ios | components/AppBar/examples/AppBarImageryExample.swift | 1 | 3574 | /*
Copyright 2016-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 Foundation
import MaterialComponents
class AppBarImagerySwiftExample: UITableViewController {
let appBar = MDCAppBar()
override func viewDidLoad() {
super.viewDidLoad()
let headerView = appBar.headerViewController.headerView
// Create our custom image view and add it to the header view.
let imageView = UIImageView(image: self.headerBackgroundImage())
imageView.frame = headerView.bounds
// Ensure that the image view resizes in reaction to the header view bounds changing.
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
// Ensure that the image view is below other App Bar views (headerStackView).
headerView.insertSubview(imageView, at: 0)
// Scales up the image while the header is over-extending.
imageView.contentMode = .scaleAspectFill
// The header view does not clip to bounds by default so we ensure that the image is clipped.
imageView.clipsToBounds = true
// We want navigation bar + status bar tint color to be white, so we set tint color here and
// implement -preferredStatusBarStyle.
headerView.tintColor = UIColor.white
appBar.navigationBar.titleTextAttributes =
[ NSForegroundColorAttributeName: UIColor.white ]
// Allow the header to show more of the image.
headerView.maximumHeight = 200
headerView.trackingScrollView = self.tableView
self.tableView.delegate = appBar.headerViewController
appBar.addSubviewsToParent()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
// Ensure that our status bar is white.
return .lightContent
}
// MARK: Typical configuration
init() {
super.init(nibName: nil, bundle: nil)
self.title = "Imagery (Swift)"
self.addChildViewController(appBar.headerViewController)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func headerBackgroundImage() -> UIImage {
let bundle = Bundle(for: AppBarImagerySwiftExample.self)
let imagePath = bundle.path(forResource: "mdc_theme", ofType: "png")!
return UIImage(contentsOfFile: imagePath)!
}
}
// MARK: Catalog by convention
extension AppBarImagerySwiftExample {
class func catalogBreadcrumbs() -> [String] {
return ["App Bar", "Imagery (Swift)"]
}
func catalogShouldHideNavigation() -> Bool {
return true
}
}
// MARK: - Typical application code (not Material-specific)
// MARK: UITableViewDataSource
extension AppBarImagerySwiftExample {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
override func tableView(
_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = self.tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
cell!.layoutMargins = UIEdgeInsets.zero
return cell!
}
}
| apache-2.0 | dd9c5442d2a496ed3b044ee5bdb68927 | 30.350877 | 97 | 0.735311 | 4.836265 | false | false | false | false |
Antuaaan/ECWeather | ECWeather/Pods/SwiftSky/Source/SwiftSky.swift | 1 | 8438 | //
// SwiftSky.swift
// SwiftSky
//
// Created by Luca Silverentand on 11/04/2017.
// Copyright © 2017 App Company.io. All rights reserved.
//
import Foundation
import Alamofire
import CoreLocation
/**
Describes the failure that occured during the
retrieval/processing of a `Forecast` from the Dark Sky API.
## Possible Errors
```
ApiError.noApiKey
ApiError.noDataRequested
ApiError.serverError
ApiError.invalidJSON(AFError?)
*/
public enum ApiError : Error {
/**
No API key was set on `SwiftSky`, like so:
```swift
SwiftSky.key = "your_key_here"
```
You can signup for an api key at:
[https://darksky.net/dev/register](https://darksky.net/dev/register)
*/
case noApiKey
/**
No `DataType`s are passed to `Swift.get()`.
Since this would result in an empty `Forecast`. To save resources on both
the client and api sides, the request will not be executed.
*/
case noDataRequested
/**
The LocationConvertible provided to `Swift.get()` could not be converted to a `Location`
*/
case invalidLocation
/**
A status code in the `500` range is returned
when requesting a `Forecast` from the Dark Sky API servers.
*/
case serverError
/**
Occurs when the JSON returned from the Dark Sky
API servers cannot be proccessed into a `Forecast` object.
Contains an optional `AFError` object from the underlying
`Alamofire` request. Check the `ResponseSerializationFailureReason`
of the error for more details on the failing serialization.
*/
case invalidJSON(AFError?)
}
/**
Represents the success or failure of the retrieval/processing
of a `Forecast` object from the Dark Sky API.
## Possible Implementations
__A Switch Statement (cleanest)__
```swift
switch result {
case .success(let forecast):
// do something with the `Forecast`
case .error(let error):
// do something with `Error`
}
```
__A Conditional Statement__
```swift
if let forecast = result.response as? Forecast {
// do something with `Forecast`
} else if let error = result.error as? ApiError {
// do something with `Error`
}
```
*/
public enum Result {
/// `Forecast` retrieval/processing was succesful
case success(Forecast)
/// `Forecast` retrieval/processing has failed
case failure(ApiError)
/// `Forecast` value in case of success, nil otherwise
public var response: (Forecast?) {
switch self {
case .success(let forecast):
return (forecast)
case .failure:
return (nil)
}
}
/// `ApiError` in case of failure, nil otherwise
public var error: ApiError? {
switch self {
case .success:
return nil
case .failure(let error):
return error
}
}
}
/// Specifier for the amount of desired hours in a `Forecast` object
public enum HourAmount {
/// Represents `48` hours over 2 days (first two days in a `Forecast`)
case fortyEight
/// Represents `168` hours over 7 days (max amount of days in a `Forecast`)
case hundredSixtyEight
}
/// Types adopting this protocol can be used to construct
/// a `Location` for `SwiftSky.get()` requests.
public protocol LocationConvertible {
/// Converts the adopting type into a `Location`
func asLocation() -> Location?
}
/// Represents a physical location defined by latitude and longitude degrees
public class Location : LocationConvertible {
/// Specifies the north–south position of a point on the Earth's surface
public let latitude : Double
/// Specifies the east–west position of a point on the Earth's surface
public let longitude : Double
/// Creates a `Location` from latitude and longitude
public init(latitude: Double, longitude : Double) {
self.latitude = latitude
self.longitude = longitude
}
/// :nodoc:
public func asLocation() -> Location? {
return self
}
}
/// :nodoc:
extension String : LocationConvertible {
public func asLocation() -> Location? {
let split = self.components(separatedBy: ",")
guard split.count == 2, let lat = Double(split.first!), let lon = Double(split.last!) else { return nil }
return Location(latitude: lat, longitude: lon)
}
}
/// :nodoc:
extension CLLocation : LocationConvertible {
public func asLocation() -> Location? {
return Location(latitude: self.coordinate.latitude, longitude: self.coordinate.longitude)
}
}
/// :nodoc:
extension CLLocationCoordinate2D : LocationConvertible {
public func asLocation() -> Location? {
return Location(latitude: self.latitude,longitude: self.longitude)
}
}
/// Contains settings and returns `Forecast`'s
public struct SwiftSky {
/**
The Dark Sky secret key used when making requests to the Dark Sky Servers
You can get a secret key by registering at:
[https://darksky.net/dev/register](https://darksky.net/dev/register)
*/
public static var secret : String?
/**
The units that are used for the values in the
`Forecast`'s `DataPoint` objects created by `SwiftSky.get()`
__Note:__
All values have conversion functions available
*/
public static var units : UnitProfile = UnitProfile()
/**
The language that is used for the summaries in the
`Forecast` objects generated by `SwiftSky.get()`
*/
public static var language : Language = .userPreference
/// Used to determine decimal delimiter, defaults to user's current locale
public static var locale : Locale = .autoupdatingCurrent
/// The desired amount of hours to be present in a `Forecast` (48 default)
public static var hourAmount : HourAmount = .fortyEight
/**
Used to get a `Forecast` from the Dark Sky Servers
__Example Request__
```swift
SwiftSky.get([.current,.minutes,.hours,.days],
at: Location(latitude: 0.0, longitude: 0.0)
) { result in
switch result {
case .success(let forecast):
// do something with forecast
case .failure(let error):
// handle error
}
}
```
- parameter data: array of `DataType`'s that are desired to be present
- parameter at: a `LocationConvertible` to return a `Forecast` for
- parameter on: an optional `Date` to return the `Forecast` for
- parameter completion: a completion block returning a `Result`
- returns: a `Result` in a completion block
*/
public static func get(
_ data : [DataType],
at location : LocationConvertible,
on date : Date? = nil,
_ completion : @escaping (Result) -> Void
) {
// check if location is valid
guard let located = location.asLocation()
else { return(completion(.failure(.invalidLocation))) }
// check if Dark Sky secret key is set
guard SwiftSky.secret != nil
else { return(completion(.failure(.noApiKey))) }
// check if ANY data is requested
guard !data.isEmpty
else { return(completion(.failure(.noDataRequested))) }
// construct exclude list from include list
var exclude : [DataType] = [.current,.minutes,.hours,.days,.alerts]
for type in data {
if let index = exclude.index(of: type) {
exclude.remove(at: index)
}
}
// get api url
let url = ApiUrl(located, date: date, exclude: exclude).url
// perform request
request(url, method: .get, headers: ["Accept-Encoding":"gzip"]).responseJSON { response in
switch response.result {
case .success(let data):
completion(.success(Forecast(data, headers: response.response?.allHeaderFields)))
case .failure(let error):
let code = response.response?.statusCode ?? 404
if code >= 500 && code < 600 {
completion(.failure(.serverError))
} else {
completion(.failure(.invalidJSON(error as? AFError)))
}
}
}
}
}
| mit | 9cce44a848d90f9e262034b0c12bede1 | 28.07931 | 113 | 0.618641 | 4.575692 | false | false | false | false |
AsyncNinja/AsyncNinja | Sources/AsyncNinja/Executor.swift | 1 | 10394 | //
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 Dispatch
/// Executor encapsulates asynchrounous way of execution escaped block.
public struct Executor {
/// Handler that encapsulates asynchrounous way of execution escaped block
public typealias Handler = (@escaping () -> Void) -> Void
private let _impl: ExecutorImpl
private let _nesting: Int
var dispatchQueueBasedExecutor: Executor {
switch _impl.asyncNinja_representedDispatchQueue {
case .none: return .primary
case .some: return self
}
}
var representedDispatchQueue: DispatchQueue? {
return _impl.asyncNinja_representedDispatchQueue
}
var unnested: Executor {
return Executor(impl: _impl, nesting: 0)
}
var nested: Executor? {
return _nesting < 64 ? Executor(impl: _impl, nesting: _nesting + 1) : nil
}
/// Initializes executor with specified implementation
///
/// - Parameter impl: implementation of executor
fileprivate init(impl: ExecutorImpl, nesting: Int) {
_impl = impl
_nesting = nesting
}
/// Initialiaes executor with custom handler
///
/// - Parameters:
/// - handler: encapsulates asynchrounous way of execution escaped block
public init(relaxAsyncWhenLaunchingFrom: ObjectIdentifier? = nil, handler: @escaping Handler) {
// Test: ExecutorTests.testCustomHandler
_impl = HandlerBasedExecutorImpl(relaxAsyncWhenLaunchingFrom: relaxAsyncWhenLaunchingFrom, handler: handler)
_nesting = 0
}
/// Schedules specified block for execution
///
/// - Parameter original: `Executor` you calling this method on.
/// Specifying this argument will allow to perform syncronous executions
/// on `strictAsync: false` `Executor`s.
/// Use default value or nil if you are not sure about an `Executor`
/// you calling this method on.
/// - Parameter block: to execute
func execute(from original: Executor?, _ block: @escaping (_ original: Executor) -> Void) {
if case let .some(newOrigin) = original?.nested,
_impl.asyncNinja_canImmediatelyExecute(from: newOrigin._impl) {
block(newOrigin)
} else {
_impl.asyncNinja_execute { () -> Void in block(self.unnested) }
}
}
/// Schedules specified block for execution. Execution will be asynchronous
/// on all DispatchQueue based Executors (like main or default global).
/// Immediate executor will do it synchronously.
///
/// - Parameter block: to execute
func schedule( _ block : @escaping (_ original: Executor) -> Void) {
_impl.asyncNinja_execute { block(self.unnested) }
}
func execute<T>(from original: Executor?, value: T, _ block: @escaping (_ value: T, _ original: Executor) -> Void) {
if case let .some(newOrigin) = original?.nested,
_impl.asyncNinja_canImmediatelyExecute(from: newOrigin._impl) {
block(value, newOrigin)
} else {
_impl.asyncNinja_execute { () -> Void in block(value, self.unnested) }
}
}
/// Schedules specified block for execution after timeout
///
/// - Parameters:
/// - timeout: to schedule execution of the block after
/// - block: to execute
func execute(after timeout: Double, _ block: @escaping (_ original: Executor) -> Void) {
_impl.asyncNinja_execute(after: timeout) { () -> Void in block(self.unnested) }
}
}
// MARK: - known executors
public extension Executor {
// Test: ExecutorTests.testPrimary
/// primary executor is primary because it will be used
/// as default value when executor argument is ommited
static let primary = Executor(impl: PrimaryExecutorImpl(), nesting: 0)
/// shortcut to the main queue executor
static let main = Executor(impl: MainExecutorImpl(), nesting: 0)
// Test: ExecutorTests.testUserInteractive
/// shortcut to the global concurrent user interactive queue executor
static let userInteractive = Executor.queue(.userInteractive)
// Test: ExecutorTests.testUserInitiated
/// shortcut to the global concurrent user initiated queue executor
static let userInitiated = Executor.queue(.userInitiated)
// Test: ExecutorTests.testDefault
/// shortcut to the global concurrent default queue executor
static let `default` = Executor.queue(.default)
// Test: ExecutorTests.testUtility
/// shortcut to the global concurrent utility queue executor
static let utility = Executor.queue(.utility)
// Test: ExecutorTests.testBackground
/// shortcut to the global concurrent background queue executor
static let background = Executor.queue(.background)
// Test: ExecutorTests.testImmediate
/// executes block immediately. Not suitable for long running calculations
static let immediate = Executor(impl: ImmediateExecutorImpl(), nesting: 0)
/// initializes executor based on specified queue
///
/// - Parameter queue: to execute submitted blocks on
/// - Returns: executor
static func queue(_ queue: DispatchQueue) -> Executor {
// Test: ExecutorTests.testCustomQueue
return Executor(queue: queue)
}
/// initializes executor based on specified queue
///
/// - Parameter queue: to execute submitted blocks on
init(queue: DispatchQueue) {
self.init(impl: queue, nesting: 0)
}
// Test: ExecutorTests.testCustomQoS
/// initializes executor based on global queue with specified QoS class
///
/// - Parameter qos: quality of service for submitted blocks
/// - Returns: executor
static func queue(_ qos: DispatchQoS.QoSClass) -> Executor {
return Executor(qos: qos)
}
/// initializes executor based on global queue with specified QoS class
///
/// - Parameter qos: quality of service for submitted blocks
init(qos: DispatchQoS.QoSClass) {
self.init(queue: .global(qos: qos))
}
}
// MARK: - implementations
/// **internal use only**
protocol ExecutorImpl: AnyObject {
var asyncNinja_representedDispatchQueue: DispatchQueue? { get }
var asyncNinja_canImmediatelyExecuteOnPrimaryExecutor: Bool { get }
func asyncNinja_execute(_ block: @escaping () -> Void)
func asyncNinja_execute(after timeout: Double, _ block: @escaping () -> Void)
func asyncNinja_canImmediatelyExecute(from impl: ExecutorImpl) -> Bool
}
private class PrimaryExecutorImpl: ExecutorImpl {
let queue = DispatchQueue.global()
var asyncNinja_representedDispatchQueue: DispatchQueue? { return queue }
var asyncNinja_canImmediatelyExecuteOnPrimaryExecutor: Bool { return true }
func asyncNinja_execute(_ block: @escaping () -> Void) {
queue.async(execute: block)
}
func asyncNinja_execute(after timeout: Double, _ block: @escaping () -> Void) {
let wallDeadline = DispatchWallTime.now().adding(seconds: timeout)
queue.asyncAfter(wallDeadline: wallDeadline, execute: block)
}
func asyncNinja_canImmediatelyExecute(from impl: ExecutorImpl) -> Bool {
return impl.asyncNinja_canImmediatelyExecuteOnPrimaryExecutor
}
}
private class MainExecutorImpl: ExecutorImpl {
let queue = DispatchQueue.main
var asyncNinja_representedDispatchQueue: DispatchQueue? { return queue }
var asyncNinja_canImmediatelyExecuteOnPrimaryExecutor: Bool { return true }
func asyncNinja_execute(_ block: @escaping () -> Void) {
queue.async(execute: block)
}
func asyncNinja_execute(after timeout: Double, _ block: @escaping () -> Void) {
let wallDeadline = DispatchWallTime.now().adding(seconds: timeout)
queue.asyncAfter(wallDeadline: wallDeadline, execute: block)
}
func asyncNinja_canImmediatelyExecute(from impl: ExecutorImpl) -> Bool {
return impl === self
}
}
private class ImmediateExecutorImpl: ExecutorImpl {
var asyncNinja_representedDispatchQueue: DispatchQueue? { return nil }
var asyncNinja_canImmediatelyExecuteOnPrimaryExecutor: Bool { return true }
func asyncNinja_execute(_ block: @escaping () -> Void) {
block()
}
func asyncNinja_execute(after timeout: Double, _ block: @escaping () -> Void) {
let deadline = DispatchWallTime.now().adding(seconds: timeout)
DispatchQueue.global(qos: .default)
.asyncAfter(wallDeadline: deadline, execute: block)
}
func asyncNinja_canImmediatelyExecute(from impl: ExecutorImpl) -> Bool {
return true
}
}
private class HandlerBasedExecutorImpl: ExecutorImpl {
public typealias Handler = (@escaping () -> Void) -> Void
private let _handler: Handler
private let _relaxAsyncWhenLaunchingFrom: ObjectIdentifier?
var asyncNinja_representedDispatchQueue: DispatchQueue? { return nil }
var asyncNinja_canImmediatelyExecuteOnPrimaryExecutor: Bool { return false }
init(relaxAsyncWhenLaunchingFrom: ObjectIdentifier?, handler: @escaping Handler) {
_relaxAsyncWhenLaunchingFrom = relaxAsyncWhenLaunchingFrom
_handler = handler
}
func asyncNinja_execute(_ block: @escaping () -> Void) {
_handler(block)
}
func asyncNinja_execute(after timeout: Double, _ block: @escaping () -> Void) {
let deadline = DispatchWallTime.now().adding(seconds: timeout)
let handler = _handler
DispatchQueue.global(qos: .default)
.asyncAfter(wallDeadline: deadline) {
handler(block)
}
}
func asyncNinja_canImmediatelyExecute(from impl: ExecutorImpl) -> Bool {
if let other = impl as? HandlerBasedExecutorImpl {
return _relaxAsyncWhenLaunchingFrom == other._relaxAsyncWhenLaunchingFrom
} else {
return false
}
}
}
| mit | 3e812873494e2fce8fbe62139d6a96ac | 35.858156 | 118 | 0.721378 | 4.372739 | false | true | false | false |
baiyidjp/SwiftWB | SwiftWeibo/SwiftWeibo/Classes/ViewModel(视图模型)/JPStatusListViewModel(列表视图模型).swift | 1 | 5110 | //
// JPStatusListViewModel.swift
// SwiftWeibo
//
// Created by tztddong on 2016/11/23.
// Copyright © 2016年 dongjiangpeng. All rights reserved.
//
import UIKit
import SDWebImage
//刷新失败最大次数
fileprivate let reloadFailedMaxTime = 3
/// ViewModel 处理网络请求数据 刷新
class JPStatusListViewModel: NSObject {
/// 刷新失败的当前次数
fileprivate var reloadFailesTimes = 0
/// 微博model数组
lazy var statusList = [JPStatusViewModel]()
/// 加载微博列表数据
/// - isPullup 是否是上啦刷新
/// - Parameter completion: 是否成功的回调
func loadStatusList(isPullup: Bool, completion: @escaping (_ isSuccess: Bool,_ isReloadData: Bool)->()) {
if isPullup && reloadFailesTimes == reloadFailedMaxTime {
print("次数上限")
completion(true, false)
return
}
// 取出数组的第一条数据的ID 作为下拉刷新的参数
let since_id = isPullup ? 0 : (statusList.first?.status.id ?? 0)
// 取出数组的最后一条数据的ID 作为上拉刷新的参数
let max_id = isPullup ? (statusList.last?.status.id ?? 0) : 0
//从数据访问层 请求数据
JPDALManager.loadStatus(since_id: since_id, max_id: max_id) { (status, isSuccess) in
/// 判断网络是否请求成功
if !isSuccess {
completion(false, false)
return
}
/// 字典转模型
guard let array = NSArray.yy_modelArray(with: JPStatusesModel.self, json: status ?? []) as? [JPStatusesModel] else {
return
}
// 视图模型集合
var statusViewModels = [JPStatusViewModel]()
for statusModel in array {
let statusViewModel = JPStatusViewModel(model: statusModel)
statusViewModels.append(statusViewModel)
}
/// 闭包中使用 self 拼接数组
/// 下拉刷新 最新的拼接到前面
if isPullup {
print("上拉刷新 \(array.count) 数据")
self.statusList += statusViewModels
}else{
print("下拉刷新 \(array.count) 数据")
self.statusList = statusViewModels + self.statusList
}
if isPullup && array.count == 0 {
self.reloadFailesTimes += 1
completion(isSuccess, false)
}else{
self.cacheSingleImage(statusViewModels: statusViewModels, finished: completion)
/// 完成回调 -- 应该是在所有单张图片缓存完成后再回调
// completion(isSuccess,true)
}
}
}
/// 缓存当前请求回来的微博数据中的 单张图片
///
/// - Parameter statusViewModels: 当前请求回来的微博的viewmodle列表
fileprivate func cacheSingleImage(statusViewModels: [JPStatusViewModel], finished: @escaping (_ isSuccess: Bool,_ isReloadData: Bool)->()) {
//创建调度组
let group = DispatchGroup()
//总图片的大小
var imageData = 0
//遍历数组 找出微博数据中 图片是单张的微博数据
for viewModel in statusViewModels {
//判断图片数量
if viewModel.picURLs?.count != 1 {
continue
}
//获取图像模型
guard let picUrl = viewModel.picURLs?[0].thumbnail_pic,
let url = URL(string: picUrl)
else {
continue
}
//入组(会监听最近的一个block/闭包 必须和出组配合使用)
group.enter()
//下载图片
//SDWebImage的核心下载方法 图片下载完成后会缓存在沙盒中 名字是地址的MD5
SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, url) in
if let image = image,
let data = UIImagePNGRepresentation(image) {
imageData += data.count
// print("缓存的图像是--- \(image) 大小--\(imageData) URL--\(url)")
//更新单条微博viewmodel中的配图的size
viewModel.updatePicViewSizeWithImage(image: image)
}
//出组 (一定要闭包的最后一句)
group.leave()
})
}
//监听调度组
group.notify(queue: DispatchQueue.main) {
print("图像缓存完成---\(imageData/1024)K")
/// 完成回调 -- 应该是在所有单张图片缓存完成后再回调
finished(true,true)
}
}
}
| mit | 71f78f17b9bd62052169b632e7cbb93c | 30.121429 | 144 | 0.504935 | 4.746187 | false | false | false | false |
JakeLin/ChineseZodiac | ChineseZodiac/ViewController.swift | 1 | 1100 | //
// ViewController.swift
// ChineseZodiac
//
// Created by Jake Lin on 20/08/2014.
// Copyright (c) 2014 rushjet. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var yearOfBirth: UITextField!
@IBOutlet weak var image: UIImageView!
let offset = 4
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
yearOfBirth.resignFirstResponder()
}
@IBAction func okTapped(sender: AnyObject) {
yearOfBirth.resignFirstResponder()
if let year = Int(yearOfBirth.text!) {
let number = year < 4 ? year + 8 : (year - 4) % 12
let imageName = String(number)
image.image = UIImage(named: imageName)
}
}
}
| mit | 8451ca70c7a563d3b90360a6367a878d | 26.5 | 82 | 0.621818 | 4.661017 | false | false | false | false |
prasanth223344/celapp | Cgrams/ATSketchKit/ATSmartBezierPath+Smoothing.swift | 1 | 3172 | //
// ATSmartBezierPath+Smoothing.swift
// ATSketchKit
//
// Created by Arnaud Thiercelin on 12/29/15.
// Copyright © 2015 Arnaud Thiercelin. All rights reserved.
//
// This Catmull-Rom implem was inspired by Joshua Weinberg
// http://stackoverflow.com/questions/8702696/drawing-smooth-curves-methods-needed/8731493#8731493
// who was inspired by Erica Sadun
//
// 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
import UIKit
extension ATSmartBezierPath {
func smoothPath(_ granularity: Int) -> UIBezierPath {
var points = self.points
if points.count < 4 {
let newPath = UIBezierPath()
if points.count > 0 {
for index in 0...points.count - 1 {
if index == 0 {
newPath.move(to: points[index])
} else {
newPath.addLine(to: points[index])
}
}
}
return newPath
}
// Add control points
points.insert(points[0], at: 0)
points.append(points.last!)
let newPath = UIBezierPath()
newPath.move(to: points[0])
for pointIndex in 1...points.count - 3 {
let point0 = points[pointIndex - 1]
let point1 = points[pointIndex]
let point2 = points[pointIndex + 1]
let point3 = points[pointIndex + 2]
// now we add n points starting at point1 + dx/dy up until point2 using Catmull-Rom splines
for index in 1...granularity {
let t = CGFloat(index) * (1.0 / CGFloat(granularity))
let tt = CGFloat(t * t)
let ttt = CGFloat(tt * t)
var intermediatePoint = CGPoint()
let xt = (point2.x - point0.x) * t
let xtt = (2 * point0.x - 5 * point1.x + 4 * point2.x - point3.x) * tt
let xttt = (3 * point1.x - point0.x - 3 * point2.x + point3.x) * ttt
intermediatePoint.x = 0.5 * (2 * point1.x + xt + xtt + xttt )
let yt = (point2.y - point0.y) * t
let ytt = (2 * point0.y - 5 * point1.y + 4 * point2.y - point3.y) * tt
let yttt = (3 * point1.y - point0.y - 3 * point2.y + point3.y) * ttt
intermediatePoint.y = 0.5 * (2 * point1.y + yt + ytt + yttt)
newPath.addLine(to: intermediatePoint)
}
newPath.addLine(to: point2)
}
newPath.addLine(to: points.last!)
return newPath
}
}
| mit | 530cda17b3c1e49ee6d7d456a9173bc1 | 35.448276 | 112 | 0.677073 | 3.369819 | false | false | false | false |
LeoFangQ/CMSwiftUIKit | CMSwiftUIKit/Pods/EZSwiftExtensions/Sources/StringExtensions.swift | 1 | 20907 | //
// StringExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
// swiftlint:disable line_length
// swiftlint:disable trailing_whitespace
#if os(OSX)
import AppKit
#else
import UIKit
#endif
extension String {
/// EZSE: Init string with a base64 encoded string
init ? (base64: String) {
let pad = String(repeating: "=", count: base64.length % 4)
let base64Padded = base64 + pad
if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
self.init(decodedString)
return
}
return nil
}
/// EZSE: base64 encoded of string
var base64: String {
let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue)
let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
return base64String
}
/// EZSE: Cut string from integerIndex to the end
public subscript(integerIndex: Int) -> Character {
let index = characters.index(startIndex, offsetBy: integerIndex)
return self[index]
}
/// EZSE: Cut string from range
public subscript(integerRange: Range<Int>) -> String {
let start = characters.index(startIndex, offsetBy: integerRange.lowerBound)
let end = characters.index(startIndex, offsetBy: integerRange.upperBound)
return self[start..<end]
}
/// EZSE: Cut string from closedrange
public subscript(integerClosedRange: ClosedRange<Int>) -> String {
return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)]
}
/// EZSE: Character count
public var length: Int {
return self.characters.count
}
/// EZSE: Counts number of instances of the input inside String
public func count(_ substring: String) -> Int {
return components(separatedBy: substring).count - 1
}
/// EZSE: Capitalizes first character of String
public mutating func capitalizeFirst() {
guard characters.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
}
/// EZSE: Capitalizes first character of String, returns a new string
public func capitalizedFirst() -> String {
guard characters.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized)
return result
}
/// EZSE: Uppercases first 'count' characters of String
public mutating func uppercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
}
/// EZSE: Uppercases first 'count' characters of String, returns a new string
public func uppercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased())
return result
}
/// EZSE: Uppercases last 'count' characters of String
public mutating func uppercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
}
/// EZSE: Uppercases last 'count' characters of String, returns a new string
public func uppercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased())
return result
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func uppercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased())
}
/// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func uppercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased())
return result
}
/// EZSE: Lowercases first character of String
public mutating func lowercaseFirst() {
guard characters.count > 0 else { return }
self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
}
/// EZSE: Lowercases first character of String, returns a new string
public func lowercasedFirst() -> String {
guard characters.count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased())
return result
}
/// EZSE: Lowercases first 'count' characters of String
public mutating func lowercasePrefix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased())
}
/// EZSE: Lowercases first 'count' characters of String, returns a new string
public func lowercasedPrefix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(startIndex..<characters.index(startIndex, offsetBy: min(count, length)),
with: String(self[startIndex..<characters.index(startIndex, offsetBy: min(count, length))]).lowercased())
return result
}
/// EZSE: Lowercases last 'count' characters of String
public mutating func lowercaseSuffix(_ count: Int) {
guard characters.count > 0 && count > 0 else { return }
self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
}
/// EZSE: Lowercases last 'count' characters of String, returns a new string
public func lowercasedSuffix(_ count: Int) -> String {
guard characters.count > 0 && count > 0 else { return self }
var result = self
result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex,
with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased())
return result
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex)
public mutating func lowercase(range: CountableRange<Int>) {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return }
self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to),
with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased())
}
/// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string
public func lowercased(range: CountableRange<Int>) -> String {
let from = max(range.lowerBound, 0), to = min(range.upperBound, length)
guard characters.count > 0 && (0..<length).contains(from) else { return self }
var result = self
result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to),
with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased())
return result
}
/// EZSE: Counts whitespace & new lines
@available(*, deprecated: 1.6, renamed: "isBlank")
public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool {
let characterSet = CharacterSet.whitespacesAndNewlines
let newText = self.trimmingCharacters(in: characterSet)
return newText.isEmpty
}
/// EZSE: Checks if string is empty or consists only of whitespace and newline characters
public var isBlank: Bool {
get {
let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty
}
}
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
/// EZSE: Position of begining character of substing
public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int {
if subString.isEmpty {
return -1
}
var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards
if caseInsensitive {
searchOption.insert(NSString.CompareOptions.caseInsensitive)
}
if let range = self.range(of: subString, options: searchOption), !range.isEmpty {
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
return -1
}
/// EZSE: split string using a spearator string, returns an array of string
public func split(_ separator: String) -> [String] {
return self.components(separatedBy: separator).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE: split string with delimiters, returns an array of string
public func split(_ characters: CharacterSet) -> [String] {
return self.components(separatedBy: characters).filter {
!$0.trimmed().isEmpty
}
}
/// EZSE : Returns count of words in string
public var countofWords: Int {
let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options())
return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0
}
/// EZSE : Returns count of paragraphs in string
public var countofParagraphs: Int {
let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options())
let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1
}
internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advanced(by: nsRange.location)
let to16 = from16.advanced(by: nsRange.length)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
/// EZSE: Find matches of regular expression in string
public func matchesForRegexInText(_ regex: String!) -> [String] {
let regex = try? NSRegularExpression(pattern: regex, options: [])
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? []
return results.map { self.substring(with: self.rangeFromNSRange($0.range)!) }
}
/// EZSE: Checks if String contains Email
public var isEmail: Bool {
let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length))
return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto")
}
/// EZSE: Returns if String is a number
public func isNumber() -> Bool {
if let _ = NumberFormatter().number(from: self) {
return true
}
return false
}
/// EZSE: Extracts URLS from String
public var extractURLs: [URL] {
var urls: [URL] = []
let detector: NSDataDetector?
do {
detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
} catch _ as NSError {
detector = nil
}
let text = self
if let detector = detector {
detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: {
(result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = result, let url = result.url {
urls.append(url)
}
})
}
return urls
}
/// EZSE: Checking if String contains input with comparing options
public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool {
return self.range(of: find, options: compareOption) != nil
}
/// EZSE: Converts String to Int
public func toInt() -> Int? {
if let num = NumberFormatter().number(from: self) {
return num.intValue
} else {
return nil
}
}
/// EZSE: Converts String to Double
public func toDouble() -> Double? {
if let num = NumberFormatter().number(from: self) {
return num.doubleValue
} else {
return nil
}
}
/// EZSE: Converts String to Float
public func toFloat() -> Float? {
if let num = NumberFormatter().number(from: self) {
return num.floatValue
} else {
return nil
}
}
/// EZSE: Converts String to Bool
public func toBool() -> Bool? {
let trimmedString = trimmed().lowercased()
if trimmedString == "true" || trimmedString == "false" {
return (trimmedString as NSString).boolValue
}
return nil
}
///EZSE: Returns the first index of the occurency of the character in String
public func getIndexOf(_ char: Character) -> Int? {
for (index, c) in characters.enumerated() {
if c == char {
return index
}
}
return nil
}
/// EZSE: Converts String to NSString
public var toNSString: NSString { get { return self as NSString } }
#if os(iOS)
///EZSE: Returns bold NSAttributedString
public func bold() -> NSAttributedString {
let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)])
return boldString
}
#endif
///EZSE: Returns underlined NSAttributedString
public func underline() -> NSAttributedString {
let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue])
return underlineString
}
#if os(iOS)
///EZSE: Returns italic NSAttributedString
public func italic() -> NSAttributedString {
let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)])
return italicString
}
#endif
#if os(iOS)
///EZSE: Returns hight of rendered string
func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat {
var attrib: [String: AnyObject] = [NSFontAttributeName: font]
if lineBreakMode != nil {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode!
attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName)
}
let size = CGSize(width: width, height: CGFloat(DBL_MAX))
return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height)
}
#endif
///EZSE: Returns NSAttributedString
public func color(_ color: UIColor) -> NSAttributedString {
let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color])
return colorString
}
///EZSE: Returns NSAttributedString
public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString {
var start = 0
var ranges: [NSRange] = []
while true {
let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start))
if range.location == NSNotFound {
break
} else {
ranges.append(range)
start = range.location + range.length
}
}
let attrText = NSMutableAttributedString(string: self)
for range in ranges {
attrText.addAttribute(NSForegroundColorAttributeName, value: color, range: range)
}
return attrText
}
/// EZSE: Checks if String contains Emoji
public func includesEmoji() -> Bool {
for i in 0...length {
let c: unichar = (self as NSString).character(at: i)
if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) {
return true
}
}
return false
}
#if os(iOS)
/// EZSE: copy string to pasteboard
public func addToPasteboard() {
let pasteboard = UIPasteboard.general
pasteboard.string = self
}
#endif
// EZSE: URL encode a string (percent encoding special chars)
public func urlEncoded() -> String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
// EZSE: URL encode a string (percent encoding special chars) mutating version
mutating func urlEncode() {
self = urlEncoded()
}
}
extension String {
init(_ value: Float, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
init(_ value: Double, precision: Int) {
let nFormatter = NumberFormatter()
nFormatter.numberStyle = .decimal
nFormatter.maximumFractionDigits = precision
self = nFormatter.string(from: NSNumber(value: value))!
}
}
/// EZSE: Pattern matching of strings via defined functions
public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool {
return pattern(value)
}
/// EZSE: Can be used in switch-case
public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasPrefix(prefix)
}
}
/// EZSE: Can be used in switch-case
public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool {
return { (value: String) -> Bool in
value.hasSuffix(suffix)
}
}
| mit | 2874b28dcefee5aa2d3ad671e01b1650 | 40.4 | 206 | 0.640168 | 4.816171 | false | false | false | false |
jeremiahyan/ResearchKit | samples/ORKCatalog/ORKCatalog/Charts/ChartListViewController.swift | 3 | 6529 | /*
Copyright (c) 2015, James Cox. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
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 OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import ResearchKit
class ChartListViewController: UITableViewController {
let pieChartDataSource = PieChartDataSource()
let lineGraphChartDataSource = LineGraphDataSource()
let discreteGraphChartDataSource = DiscreteGraphDataSource()
let barGraphChartDataSource = BarGraphDataSource()
let pieChartIdentifier = "PieChartCell"
let lineGraphChartIdentifier = "LineGraphChartCell"
let discreteGraphChartIdentifier = "DiscreteGraphChartCell"
let barGraphChartIdentifier = "BarGraphChartCell"
var pieChartTableViewCell: PieChartTableViewCell!
var lineGraphChartTableViewCell: LineGraphChartTableViewCell!
var discreteGraphChartTableViewCell: DiscreteGraphChartTableViewCell!
var barGraphChartTableViewCell: BarGraphChartTableViewCell!
var chartTableViewCells: [UITableViewCell]!
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
self.tableView.backgroundColor = UIColor.systemBackground
}
// ORKPieChartView
pieChartTableViewCell = (tableView.dequeueReusableCell(withIdentifier: pieChartIdentifier) as! PieChartTableViewCell)
let pieChartView = pieChartTableViewCell.pieChartView
pieChartView?.dataSource = pieChartDataSource
// Optional custom configuration
pieChartView?.title = "TITLE"
pieChartView?.text = "TEXT"
pieChartView?.lineWidth = 14
pieChartView?.radiusScaleFactor = 0.6
// ORKLineGraphChartView
lineGraphChartTableViewCell = (tableView.dequeueReusableCell(withIdentifier: lineGraphChartIdentifier) as! LineGraphChartTableViewCell)
let lineGraphChartView = lineGraphChartTableViewCell.graphView as! ORKLineGraphChartView
lineGraphChartView.dataSource = lineGraphChartDataSource
lineGraphChartView.tintColor = UIColor(red: 244 / 255, green: 190 / 255, blue: 74 / 255, alpha: 1)
// Optional custom configuration
lineGraphChartView.showsHorizontalReferenceLines = true
lineGraphChartView.showsVerticalReferenceLines = true
// ORKDiscreteGraphChartView
discreteGraphChartTableViewCell = (tableView.dequeueReusableCell(withIdentifier: discreteGraphChartIdentifier) as! DiscreteGraphChartTableViewCell)
let discreteGraphChartView = discreteGraphChartTableViewCell.graphView as! ORKDiscreteGraphChartView
discreteGraphChartView.dataSource = discreteGraphChartDataSource
discreteGraphChartView.tintColor = UIColor(red: 244 / 255, green: 190 / 255, blue: 74 / 255, alpha: 1)
// Optional custom configuration
discreteGraphChartView.showsHorizontalReferenceLines = true
discreteGraphChartView.showsVerticalReferenceLines = true
// ORKBarGraphChartView
barGraphChartTableViewCell = (tableView.dequeueReusableCell(withIdentifier: barGraphChartIdentifier) as! BarGraphChartTableViewCell)
let barGraphChartView = barGraphChartTableViewCell.graphView as! ORKBarGraphChartView
barGraphChartView.dataSource = barGraphChartDataSource
barGraphChartView.tintColor = UIColor(red: 244 / 255, green: 190 / 255, blue: 74 / 255, alpha: 1)
// Optional custom configuration
barGraphChartView.showsHorizontalReferenceLines = true
barGraphChartView.showsVerticalReferenceLines = true
chartTableViewCells = [pieChartTableViewCell, lineGraphChartTableViewCell, discreteGraphChartTableViewCell, barGraphChartTableViewCell]
if #available(iOS 13.0, *) {
pieChartView?.backgroundColor = UIColor.secondarySystemBackground
lineGraphChartView.backgroundColor = UIColor.secondarySystemBackground
discreteGraphChartView.backgroundColor = UIColor.secondarySystemBackground
barGraphChartView.backgroundColor = UIColor.secondarySystemBackground
}
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chartTableViewCells.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = chartTableViewCells[(indexPath as NSIndexPath).row]
if #available(iOS 13.0, *) {
cell.contentView.backgroundColor = UIColor.systemBackground
}
return cell
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
pieChartTableViewCell.pieChartView.animate(withDuration: 0.5)
lineGraphChartTableViewCell.graphView.animate(withDuration: 0.5)
discreteGraphChartTableViewCell.graphView.animate(withDuration: 0.5)
barGraphChartTableViewCell.graphView.animate(withDuration: 0.5)
}
}
| bsd-3-clause | 8c9a2a97db21452f5de9796613396ae3 | 48.839695 | 155 | 0.756624 | 5.618761 | false | false | false | false |
HackerEcology/BeginnerCourse | tdjackey/GuidedTour.playground/section-34.swift | 3 | 431 | func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
statistics.sum
statistics.2
| mit | dbd35400dbf4e935f016b5401b0b7260 | 21.684211 | 75 | 0.522042 | 3.652542 | false | true | false | false |
wireapp/wire-ios | Wire-iOS Share Extension/SLComposeServiceViewController+Preview.swift | 1 | 6237 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// 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 Social
import MobileCoreServices
import WireCommonComponents
/**
* The description of the preview that can be displayed for an attachment.
*/
enum PreviewItem {
case image(UIImage)
case remoteURL(URL)
case placeholder(StyleKitIcon)
}
extension SLComposeServiceViewController {
/**
* Fetches the preview item of the main attachment in the background and provided the result to the UI
* for displaying it to the user.
*
* - parameter completionHandler: The block of code that provided the result of the preview lookup.
* - parameter item: The preview item for the attachment, if it could be determined.
* - parameter displayMode: The special mode in which the preview should displayed, if any.
*/
func fetchMainAttachmentPreview(_ completionHandler: @escaping (_ item: PreviewItem?, _ displayMode: PreviewDisplayMode?) -> Void) {
func completeTask(_ result: PreviewItem?, _ preferredDisplayMode: PreviewDisplayMode?) {
DispatchQueue.main.async { completionHandler(result, preferredDisplayMode) }
}
DispatchQueue.global(qos: .userInitiated).async {
guard let attachments = self.appendLinkFromTextIfNeeded(),
let (attachmentType, attachment) = attachments.main else {
completeTask(nil, nil)
return
}
let numberOfAttachments = attachments.values.reduce(0) { $0 + $1.count }
let defaultDisplayMode: PreviewDisplayMode? = numberOfAttachments > 1 ? .mixed(numberOfAttachments, nil) : nil
switch attachmentType {
case .walletPass, .image:
self.loadSystemPreviewForAttachment(attachment, type: attachmentType) { image, preferredDisplayMode in
completeTask(image, defaultDisplayMode.combine(with: preferredDisplayMode))
}
case .video:
self.loadSystemPreviewForAttachment(attachment, type: attachmentType) { image, preferredDisplayMode in
completeTask(image, defaultDisplayMode.combine(with: preferredDisplayMode) ?? .video)
}
case .rawFile,
.fileUrl:
let fallbackIcon = self.fallbackIcon(forAttachment: attachment, ofType: .rawFile)
completeTask(.placeholder(fallbackIcon), defaultDisplayMode.combine(with: .placeholder))
case .url:
let displayMode = defaultDisplayMode.combine(with: .placeholder)
attachment.fetchURL {
if let url = $0 {
guard !url.isFileURL else {
completeTask(.placeholder(.document), displayMode)
return
}
completeTask(.remoteURL(url), displayMode)
} else {
completeTask(.placeholder(.paperclip), displayMode)
}
}
}
}
}
func appendLinkFromTextIfNeeded() -> [AttachmentType: [NSItemProvider]]? {
guard let text = self.contentText,
var attachments = self.extensionContext?.attachments else {
return nil
}
let matches = text.URLsInString
if let match = matches.first,
let item = NSItemProvider(contentsOf: match),
attachments.filter(\.hasURL).count == 0 {
attachments.append(item)
}
return attachments.sorted
}
/**
* Loads the system preview for the item, if possible.
*
* This method generally works for movies, photos, wallet passes. It does not generate any preview for items shared from the iCloud drive app.
*/
private func loadSystemPreviewForAttachment(_ item: NSItemProvider, type: AttachmentType, completionHandler: @escaping (PreviewItem, PreviewDisplayMode?) -> Void) {
item.loadPreviewImage(options: [NSItemProviderPreferredImageSizeKey: PreviewDisplayMode.pixelSize]) { container, error in
func useFallbackIcon() {
let fallbackIcon = self.fallbackIcon(forAttachment: item, ofType: type)
completionHandler(.placeholder(fallbackIcon), .placeholder)
}
guard error == nil else {
useFallbackIcon()
return
}
if let image = container as? UIImage {
completionHandler(PreviewItem.image(image), nil)
} else if let data = container as? Data {
guard let image = UIImage(data: data) else {
useFallbackIcon()
return
}
completionHandler(PreviewItem.image(image), nil)
} else {
useFallbackIcon()
}
}
}
/// Returns the placeholder icon for the attachment of the specified type.
private func fallbackIcon(forAttachment item: NSItemProvider, ofType type: AttachmentType) -> StyleKitIcon {
switch type {
case .video:
return .movie
case .image:
return .photo
case .walletPass,
.fileUrl:
return .document
case .rawFile:
if item.hasItemConformingToTypeIdentifier(kUTTypeAudio as String) {
return .microphone
} else {
return .document
}
case .url:
return .paperclip
}
}
}
| gpl-3.0 | f53a84043151b4c30405e3d9ae1fdc21 | 36.8 | 168 | 0.611512 | 5.358247 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Helpers/MenuBuilderHelper.swift | 2 | 8501 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import UIKit
import Shared
class MenuBuilderHelper {
struct MenuIdentifiers {
static let history = UIMenu.Identifier("com.mozilla.firefox.menus.history")
static let bookmarks = UIMenu.Identifier("com.mozilla.firefox.menus.bookmarks")
static let tools = UIMenu.Identifier("com.mozilla.firefox.menus.tools")
}
func mainMenu(for builder: UIMenuBuilder) {
let newPrivateTab = UICommandAlternate(title: .KeyboardShortcuts.NewPrivateTab, action: #selector(BrowserViewController.newPrivateTabKeyCommand), modifierFlags: [.shift])
let applicationMenu = UIMenu(options: .displayInline, children: [
UIKeyCommand(title: .AppSettingsTitle, action: #selector(BrowserViewController.openSettingsKeyCommand), input: ",", modifierFlags: .command, discoverabilityTitle: .AppSettingsTitle)
])
let fileMenu = UIMenu(options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.NewTab, action: #selector(BrowserViewController.newTabKeyCommand), input: "t", modifierFlags: .command, alternates: [newPrivateTab], discoverabilityTitle: .KeyboardShortcuts.NewTab),
UIKeyCommand(title: .KeyboardShortcuts.NewPrivateTab, action: #selector(BrowserViewController.newPrivateTabKeyCommand), input: "p", modifierFlags: [.command, .shift], discoverabilityTitle: .KeyboardShortcuts.NewPrivateTab),
UIKeyCommand(title: .KeyboardShortcuts.SelectLocationBar, action: #selector(BrowserViewController.selectLocationBarKeyCommand), input: "l", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.SelectLocationBar),
UIKeyCommand(title: .KeyboardShortcuts.CloseCurrentTab, action: #selector(BrowserViewController.closeTabKeyCommand), input: "w", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.CloseCurrentTab),
])
if #available(iOS 15, *) {
fileMenu.children.forEach {
($0 as! UIKeyCommand).wantsPriorityOverSystemBehavior = true
}
}
let findMenu = UIMenu(options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.Find, action: #selector(BrowserViewController.findInPageKeyCommand), input: "f", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.Find),
UIKeyCommand(title: .KeyboardShortcuts.FindAgain, action: #selector(BrowserViewController.findInPageAgainKeyCommand), input: "g", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.FindAgain),
])
if #available(iOS 15, *) {
findMenu.children.forEach {
($0 as! UIKeyCommand).wantsPriorityOverSystemBehavior = true
}
}
var viewMenuChildren: [UIMenuElement] = [
UIKeyCommand(title: .KeyboardShortcuts.ZoomIn, action: #selector(BrowserViewController.zoomIn), input: "+", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ZoomIn),
UIKeyCommand(title: .KeyboardShortcuts.ZoomOut, action: #selector(BrowserViewController.zoomOut), input: "-", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ZoomOut),
UIKeyCommand(title: .KeyboardShortcuts.ActualSize, action: #selector(BrowserViewController.resetZoom), input: "0", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ActualSize),
UIKeyCommand(title: .KeyboardShortcuts.ReloadPage, action: #selector(BrowserViewController.reloadTabKeyCommand), input: "r", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ReloadPage)
]
// UIKeyCommand.f5 is only available since iOS 13.4 - Shortcut will only work from this version
if #available(iOS 13.4, *) {
viewMenuChildren.append(
UIKeyCommand(title: .KeyboardShortcuts.ReloadWithoutCache, action: #selector(BrowserViewController.reloadTabIgnoringCacheKeyCommand), input: UIKeyCommand.f5, modifierFlags: [.control], discoverabilityTitle: .KeyboardShortcuts.ReloadWithoutCache)
)
}
let viewMenu = UIMenu(options: .displayInline, children: viewMenuChildren)
if #available(iOS 15, *) {
viewMenu.children.forEach {
($0 as! UIKeyCommand).wantsPriorityOverSystemBehavior = true
}
}
let historyMenu = UIMenu(title: .KeyboardShortcuts.Sections.History, identifier: MenuIdentifiers.history, options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.ShowHistory, action: #selector(BrowserViewController.showHistoryKeyCommand), input: "y", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ShowHistory),
UIKeyCommand(title: .KeyboardShortcuts.Back, action: #selector(BrowserViewController.goBackKeyCommand), input: "[", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.Back),
UIKeyCommand(title: .KeyboardShortcuts.Forward, action: #selector(BrowserViewController.goForwardKeyCommand), input: "]", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.Forward),
UIKeyCommand(title: .KeyboardShortcuts.ClearRecentHistory, action: #selector(BrowserViewController.openClearHistoryPanelKeyCommand), input: "\u{8}", modifierFlags: [.command, .shift], discoverabilityTitle: .KeyboardShortcuts.ClearRecentHistory)
])
let bookmarksMenu = UIMenu(title: .KeyboardShortcuts.Sections.Bookmarks, identifier: MenuIdentifiers.bookmarks, options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.ShowBookmarks, action: #selector(BrowserViewController.showBookmarksKeyCommand), input: "o", modifierFlags: [.command, .shift], discoverabilityTitle: .KeyboardShortcuts.ShowBookmarks),
UIKeyCommand(title: .KeyboardShortcuts.AddBookmark, action: #selector(BrowserViewController.addBookmarkKeyCommand), input: "d", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.AddBookmark)
])
let toolsMenu = UIMenu(title: .KeyboardShortcuts.Sections.Tools, identifier: MenuIdentifiers.tools, options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.ShowDownloads, action: #selector(BrowserViewController.showDownloadsKeyCommand), input: "j", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ShowDownloads)
])
let windowMenu = UIMenu(title: .KeyboardShortcuts.Sections.Window, options: .displayInline, children: [
UIKeyCommand(title: .KeyboardShortcuts.ShowNextTab, action: #selector(BrowserViewController.nextTabKeyCommand), input: "\t", modifierFlags: [.control], discoverabilityTitle: .KeyboardShortcuts.ShowNextTab),
UIKeyCommand(title: .KeyboardShortcuts.ShowPreviousTab, action: #selector(BrowserViewController.previousTabKeyCommand), input: "\t", modifierFlags: [.control, .shift], discoverabilityTitle: .KeyboardShortcuts.ShowPreviousTab),
UIKeyCommand(title: .KeyboardShortcuts.ShowTabTray, action: #selector(BrowserViewController.showTabTrayKeyCommand), input: "\t", modifierFlags: [.command, .alternate], discoverabilityTitle: .KeyboardShortcuts.ShowTabTray),
UIKeyCommand(action: #selector(BrowserViewController.selectFirstTab), input: "1", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ShowFirstTab),
UIKeyCommand(action: #selector(BrowserViewController.selectLastTab), input: "9", modifierFlags: .command, discoverabilityTitle: .KeyboardShortcuts.ShowLastTab),
])
if #available(iOS 15, *) {
windowMenu.children.forEach {
($0 as! UIKeyCommand).wantsPriorityOverSystemBehavior = true
}
}
builder.insertChild(applicationMenu, atStartOfMenu: .application)
builder.insertChild(fileMenu, atStartOfMenu: .file)
builder.replace(menu: .find, with: findMenu)
builder.remove(menu: .font)
builder.insertChild(viewMenu, atStartOfMenu: .view)
builder.insertSibling(historyMenu, afterMenu: .view)
builder.insertSibling(bookmarksMenu, afterMenu: MenuIdentifiers.history)
builder.insertSibling(toolsMenu, afterMenu: MenuIdentifiers.bookmarks)
builder.insertChild(windowMenu, atStartOfMenu: .window)
}
}
| mpl-2.0 | 59b815eabb8915dd404fa2ec460217d8 | 76.990826 | 261 | 0.736149 | 4.93957 | false | false | false | false |
frederik-jacques/quick-actions-3d-touch-tutorial | AppShortCut/AppDelegate.swift | 1 | 2347 | //
// AppDelegate.swift
// AppShortCut
//
// Created by Frederik Jacques on 30/09/15.
// Copyright © 2015 Frederik Jacques. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var shortcutItem: UIApplicationShortcutItem?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
print("Application did finish launching with options")
var performShortcutDelegate = true
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
print("Application launched via shortcut")
self.shortcutItem = shortcutItem
performShortcutDelegate = false
}
return performShortcutDelegate
}
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
print("Application performActionForShortcutItem")
completionHandler( handleShortcut(shortcutItem) )
}
func handleShortcut( shortcutItem:UIApplicationShortcutItem ) -> Bool {
print("Handling shortcut")
var succeeded = false
if( shortcutItem.type == "be.thenerd.appshortcut.new-user" ) {
// Add your code here
print("- Handling \(shortcutItem.type)")
// Get the view controller you want to load
let mainSB = UIStoryboard(name: "Main", bundle: nil)
let addUserVC = mainSB.instantiateViewControllerWithIdentifier("AddUserViewController") as! AddUserViewController
let navVC = self.window?.rootViewController as! UINavigationController
navVC.pushViewController(addUserVC, animated: true)
succeeded = true
}
return succeeded
}
func applicationDidBecomeActive(application: UIApplication) {
print("Application did become active")
guard let shortcut = shortcutItem else { return }
print("- Shortcut property has been set")
handleShortcut(shortcut)
self.shortcutItem = nil
}
}
| mit | a52a264f1ea680f0ce1bf1d1db360bde | 28.325 | 155 | 0.653453 | 6 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Site Creation/Web Address/WebAddressWizardContent.swift | 1 | 23011 | import UIKit
import WordPressAuthenticator
/// Contains the UI corresponding to the list of Domain suggestions.
///
final class WebAddressWizardContent: CollapsableHeaderViewController {
static let noMatchCellReuseIdentifier = "noMatchCellReuseIdentifier"
// MARK: Properties
private struct Metrics {
static let maxLabelWidth = CGFloat(290)
static let noResultsTopInset = CGFloat(64)
static let sitePromptEdgeMargin = CGFloat(50)
static let sitePromptBottomMargin = CGFloat(10)
static let sitePromptTopMargin = CGFloat(25)
}
override var separatorStyle: SeparatorStyle {
return .hidden
}
/// The creator collects user input as they advance through the wizard flow.
private let siteCreator: SiteCreator
private let service: SiteAddressService
private let selection: (DomainSuggestion) -> Void
/// Tracks the site address selected by users
private var selectedDomain: DomainSuggestion? {
didSet {
itemSelectionChanged(selectedDomain != nil)
}
}
/// The table view renders our server content
private let table: UITableView
private let searchHeader: UIView
private let searchTextField: SearchTextField
private var sitePromptView: SitePromptView!
/// The underlying data represented by the provider
var data: [DomainSuggestion] {
didSet {
contentSizeWillChange()
table.reloadData()
}
}
private var _hasExactMatch: Bool = false
var hasExactMatch: Bool {
get {
guard (lastSearchQuery ?? "").count > 0 else {
// Forces the no match cell to hide when the results are empty.
return true
}
// Return true if there is no data to supress the no match cell
return data.count > 0 ? _hasExactMatch : true
}
set {
_hasExactMatch = newValue
}
}
/// The throttle meters requests to the remote service
private let throttle = Scheduler(seconds: 0.5)
/// We track the last searched value so that we can retry
private var lastSearchQuery: String? = nil
/// Locally tracks the network connection status via `NetworkStatusDelegate`
private var isNetworkActive = ReachabilityUtils.isInternetReachable()
/// This message is shown when there are no domain suggestions to list
private let noResultsLabel: UILabel
private var noResultsLabelTopAnchor: NSLayoutConstraint?
private var isShowingError: Bool = false {
didSet {
if isShowingError {
contentSizeWillChange()
table.reloadData()
}
}
}
private var errorMessage: String {
if isNetworkActive {
return Strings.serverError
} else {
return Strings.noConnection
}
}
// MARK: WebAddressWizardContent
init(creator: SiteCreator, service: SiteAddressService, selection: @escaping (DomainSuggestion) -> Void) {
self.siteCreator = creator
self.service = service
self.selection = selection
self.data = []
self.noResultsLabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.preferredMaxLayoutWidth = Metrics.maxLabelWidth
label.font = WPStyleGuide.fontForTextStyle(.body)
label.textAlignment = .center
label.textColor = .text
label.text = Strings.noResults
label.sizeToFit()
label.isHidden = true
return label
}()
searchTextField = SearchTextField()
searchHeader = UIView(frame: .zero)
table = UITableView(frame: .zero, style: .grouped)
super.init(scrollableView: table,
mainTitle: Strings.mainTitle,
prompt: Strings.prompt,
primaryActionTitle: Strings.createSite,
accessoryView: searchHeader)
}
// MARK: UIViewController
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupTable()
WPAnalytics.track(.enhancedSiteCreationDomainsAccessed)
loadHeaderView()
addAddressHintView()
}
private func loadHeaderView() {
let top = NSLayoutConstraint(item: searchTextField, attribute: .top, relatedBy: .equal, toItem: searchHeader, attribute: .top, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: searchTextField, attribute: .bottom, relatedBy: .equal, toItem: searchHeader, attribute: .bottom, multiplier: 1, constant: 0)
let leading = NSLayoutConstraint(item: searchTextField, attribute: .leading, relatedBy: .equal, toItem: searchHeader, attribute: .leadingMargin, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: searchTextField, attribute: .trailing, relatedBy: .equal, toItem: searchHeader, attribute: .trailingMargin, multiplier: 1, constant: 0)
searchHeader.addSubview(searchTextField)
searchHeader.addConstraints([top, bottom, leading, trailing])
searchHeader.addTopBorder(withColor: .divider)
searchHeader.addBottomBorder(withColor: .divider)
searchHeader.backgroundColor = searchTextField.backgroundColor
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
observeNetworkStatus()
prepareViewIfNeeded()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchTextField.resignFirstResponder()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
restoreSearchIfNeeded()
postScreenChangedForVoiceOver()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
clearContent()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
updateNoResultsLabelTopInset()
coordinator.animate(alongsideTransition: nil) { [weak self] (_) in
guard let `self` = self else { return }
if !self.sitePromptView.isHidden {
self.updateTitleViewVisibility(true)
}
}
}
override func estimatedContentSize() -> CGSize {
guard !isShowingError else { return CGSize(width: view.frame.width, height: 44) }
guard data.count > 0 else { return .zero }
let estimatedSectionHeaderHeight: CGFloat = 85
let cellCount = hasExactMatch ? data.count : data.count + 1
let height = estimatedSectionHeaderHeight + (CGFloat(cellCount) * AddressCell.estimatedSize.height)
return CGSize(width: view.frame.width, height: height)
}
// MARK: Private behavior
private func clearContent() {
throttle.cancel()
itemSelectionChanged(false)
data = []
lastSearchQuery = nil
setAddressHintVisibility(isHidden: false)
noResultsLabel.isHidden = true
expandHeader()
}
private func fetchAddresses(_ searchTerm: String) {
isShowingError = false
updateIcon(isLoading: true)
service.addresses(for: searchTerm) { [weak self] results in
DispatchQueue.main.async {
self?.handleResult(results)
}
}
}
private func handleResult(_ results: Result<SiteAddressServiceResult, Error>) {
updateIcon(isLoading: false)
switch results {
case .failure(let error):
handleError(error)
case .success(let data):
hasExactMatch = data.hasExactMatch
handleData(data.domainSuggestions, data.invalidQuery)
}
}
private func handleData(_ data: [DomainSuggestion], _ invalidQuery: Bool) {
setAddressHintVisibility(isHidden: true)
let resultsHavePreviousSelection = data.contains { (suggestion) -> Bool in self.selectedDomain?.domainName == suggestion.domainName }
if !resultsHavePreviousSelection {
clearSelectionAndCreateSiteButton()
}
self.data = data
if data.isEmpty {
if invalidQuery {
noResultsLabel.text = Strings.invalidQuery
} else {
noResultsLabel.text = Strings.noResults
}
noResultsLabel.isHidden = false
} else {
noResultsLabel.isHidden = true
}
postSuggestionsUpdateAnnouncementForVoiceOver(listIsEmpty: data.isEmpty, invalidQuery: invalidQuery)
}
private func handleError(_ error: Error) {
SiteCreationAnalyticsHelper.trackError(error)
isShowingError = true
}
private func performSearchIfNeeded(query: String) {
guard !query.isEmpty else {
clearContent()
return
}
lastSearchQuery = query
guard isNetworkActive == true else {
isShowingError = true
return
}
throttle.debounce { [weak self] in
guard let self = self else { return }
self.fetchAddresses(query)
}
}
override func primaryActionSelected(_ sender: Any) {
guard let selectedDomain = selectedDomain else {
return
}
trackDomainsSelection(selectedDomain)
selection(selectedDomain)
}
private func setupCells() {
let cellName = AddressCell.cellReuseIdentifier()
let nib = UINib(nibName: cellName, bundle: nil)
table.register(nib, forCellReuseIdentifier: cellName)
table.register(InlineErrorRetryTableViewCell.self, forCellReuseIdentifier: InlineErrorRetryTableViewCell.cellReuseIdentifier())
table.cellLayoutMarginsFollowReadableWidth = true
}
private func restoreSearchIfNeeded() {
search(withInputFrom: searchTextField)
}
private func prepareViewIfNeeded() {
searchTextField.becomeFirstResponder()
}
private func setupHeaderAndNoResultsMessage() {
searchTextField.addTarget(self, action: #selector(textChanged), for: .editingChanged)
searchTextField.delegate = self
searchTextField.accessibilityTraits = .searchField
let placeholderText = Strings.searchPlaceholder
let attributes = WPStyleGuide.defaultSearchBarTextAttributesSwifted(.textPlaceholder)
let attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: attributes)
searchTextField.attributedPlaceholder = attributedPlaceholder
searchTextField.accessibilityHint = Strings.searchAccessibility
view.addSubview(noResultsLabel)
let noResultsLabelTopAnchor = noResultsLabel.topAnchor.constraint(equalTo: searchHeader.bottomAnchor)
self.noResultsLabelTopAnchor = noResultsLabelTopAnchor
NSLayoutConstraint.activate([
noResultsLabel.widthAnchor.constraint(equalTo: table.widthAnchor, constant: -50),
noResultsLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
noResultsLabelTopAnchor
])
updateNoResultsLabelTopInset()
}
/// Sets the top inset for the noResultsLabel based on layout orientation
private func updateNoResultsLabelTopInset() {
noResultsLabelTopAnchor?.constant = UIDevice.current.orientation.isPortrait ? Metrics.noResultsTopInset : 0
}
private func setupTable() {
table.dataSource = self
table.estimatedRowHeight = AddressCell.estimatedSize.height
setupTableBackground()
setupTableSeparator()
setupCells()
setupHeaderAndNoResultsMessage()
table.showsVerticalScrollIndicator = false
table.separatorStyle = .none // Remove Seperator from from section headers we'll add in seperators when creating cells.
}
private func setupTableBackground() {
table.backgroundColor = .basicBackground
}
private func setupTableSeparator() {
table.separatorColor = .divider
}
private func query(from textField: UITextField?) -> String? {
guard let text = textField?.text,
!text.isEmpty else {
return siteCreator.information?.title
}
return text
}
@objc
private func textChanged(sender: UITextField) {
search(withInputFrom: sender)
}
private func clearSelectionAndCreateSiteButton() {
selectedDomain = nil
table.deselectSelectedRowWithAnimation(true)
itemSelectionChanged(false)
}
private func trackDomainsSelection(_ domainSuggestion: DomainSuggestion) {
let domainSuggestionProperties: [String: AnyObject] = [
"chosen_domain": domainSuggestion.domainName as AnyObject,
"search_term": lastSearchQuery as AnyObject
]
WPAnalytics.track(.enhancedSiteCreationDomainsSelected, withProperties: domainSuggestionProperties)
}
// MARK: - Search logic
func updateIcon(isLoading: Bool) {
searchTextField.setIcon(isLoading: isLoading)
}
private func search(withInputFrom textField: UITextField) {
guard let query = query(from: textField), query.isEmpty == false else {
clearContent()
return
}
performSearchIfNeeded(query: query)
}
// MARK: - Search logic
private func setAddressHintVisibility(isHidden: Bool) {
sitePromptView.isHidden = isHidden
}
private func addAddressHintView() {
sitePromptView = SitePromptView(frame: .zero)
sitePromptView.isUserInteractionEnabled = false
sitePromptView.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(sitePromptView)
NSLayoutConstraint.activate([
sitePromptView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: Metrics.sitePromptEdgeMargin),
sitePromptView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -Metrics.sitePromptEdgeMargin),
sitePromptView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: Metrics.sitePromptBottomMargin),
sitePromptView.topAnchor.constraint(equalTo: searchHeader.bottomAnchor, constant: Metrics.sitePromptTopMargin)
])
setAddressHintVisibility(isHidden: true)
}
// MARK: - Others
private enum Strings {
static let suggestionsUpdated = NSLocalizedString("Suggestions updated",
comment: "Announced by VoiceOver when new domains suggestions are shown in Site Creation.")
static let noResults = NSLocalizedString("No available addresses matching your search",
comment: "Advises the user that no Domain suggestions could be found for the search query.")
static let invalidQuery = NSLocalizedString("Your search includes characters not supported in WordPress.com domains. The following characters are allowed: A–Z, a–z, 0–9.",
comment: "This is shown to the user when their domain search query contains invalid characters.")
static let noConnection: String = NSLocalizedString("No connection",
comment: "Displayed during Site Creation, when searching for Verticals and the network is unavailable.")
static let serverError: String = NSLocalizedString("There was a problem",
comment: "Displayed during Site Creation, when searching for Verticals and the server returns an error.")
static let mainTitle: String = NSLocalizedString("Choose a domain",
comment: "Select domain name. Title")
static let prompt: String = NSLocalizedString("This is where people will find you on the internet.",
comment: "Select domain name. Subtitle")
static let createSite: String = NSLocalizedString("Create Site",
comment: "Button to progress to the next step")
static let searchPlaceholder: String = NSLocalizedString("Type a name for your site",
comment: "Site creation. Seelect a domain, search field placeholder")
static let searchAccessibility: String = NSLocalizedString("Searches for available domains to use for your site.",
comment: "Accessibility hint for the domains search field in Site Creation.")
static let suggestions: String = NSLocalizedString("Suggestions",
comment: "Suggested domains")
static let noMatch: String = NSLocalizedString("This domain is unavailable",
comment: "Notifies the user that the a domain matching the search term wasn't returned in the results")
}
}
// MARK: - NetworkStatusDelegate
extension WebAddressWizardContent: NetworkStatusDelegate {
func networkStatusDidChange(active: Bool) {
isNetworkActive = active
}
}
// MARK: - UITextFieldDelegate
extension WebAddressWizardContent: UITextFieldDelegate {
func textFieldShouldClear(_ textField: UITextField) -> Bool {
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
clearSelectionAndCreateSiteButton()
return true
}
}
// MARK: - VoiceOver
private extension WebAddressWizardContent {
func postScreenChangedForVoiceOver() {
UIAccessibility.post(notification: .screenChanged, argument: table.tableHeaderView)
}
func postSuggestionsUpdateAnnouncementForVoiceOver(listIsEmpty: Bool, invalidQuery: Bool) {
var message: String
if listIsEmpty {
message = invalidQuery ? Strings.invalidQuery : Strings.noResults
} else {
message = Strings.suggestionsUpdated
}
UIAccessibility.post(notification: .announcement, argument: message)
}
}
// MARK: UITableViewDataSource
extension WebAddressWizardContent: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard !isShowingError else { return 1 }
return (!hasExactMatch && section == 0) ? 1 : data.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
guard data.count > 0 else { return nil }
return (!hasExactMatch && section == 0) ? nil : Strings.suggestions
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return (!hasExactMatch && indexPath.section == 0) ? 60 : UITableView.automaticDimension
}
func numberOfSections(in tableView: UITableView) -> Int {
return hasExactMatch ? 1 : 2
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return (!hasExactMatch && section == 0) ? UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 3)) : nil
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if isShowingError {
return configureErrorCell(tableView, cellForRowAt: indexPath)
} else if !hasExactMatch && indexPath.section == 0 {
return configureNoMatchCell(table, cellForRowAt: indexPath)
} else {
return configureAddressCell(tableView, cellForRowAt: indexPath)
}
}
func configureNoMatchCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WebAddressWizardContent.noMatchCellReuseIdentifier) ?? {
// Create and configure a new TableView cell if one hasn't been queued yet
let newCell = UITableViewCell(style: .subtitle, reuseIdentifier: WebAddressWizardContent.noMatchCellReuseIdentifier)
newCell.detailTextLabel?.text = Strings.noMatch
newCell.detailTextLabel?.font = WPStyleGuide.fontForTextStyle(.body, fontWeight: .regular)
newCell.detailTextLabel?.textColor = .textSubtle
newCell.addBottomBorder(withColor: .divider)
return newCell
}()
cell.textLabel?.attributedText = AddressCell.processName("\(lastSearchQuery ?? "").wordpress.com")
return cell
}
func configureAddressCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: AddressCell.cellReuseIdentifier()) as? AddressCell else {
assertionFailure("This is a programming error - AddressCell has not been properly registered!")
return UITableViewCell()
}
let domainSuggestion = data[indexPath.row]
cell.model = domainSuggestion
cell.isSelected = domainSuggestion.domainName == selectedDomain?.domainName
cell.addBorder(isFirstCell: (indexPath.row == 0), isLastCell: (indexPath.row == data.count - 1))
return cell
}
func configureErrorCell(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: InlineErrorRetryTableViewCell.cellReuseIdentifier()) as? InlineErrorRetryTableViewCell else {
assertionFailure("This is a programming error - InlineErrorRetryTableViewCell has not been properly registered!")
return UITableViewCell()
}
cell.setMessage(errorMessage)
return cell
}
}
// MARK: UITableViewDelegate
extension WebAddressWizardContent: UITableViewDelegate {
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
// Prevent selection if it's the no matches cell
return (!hasExactMatch && indexPath.section == 0) ? nil : indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard !isShowingError else {
retry()
return
}
let domainSuggestion = data[indexPath.row]
self.selectedDomain = domainSuggestion
searchTextField.resignFirstResponder()
}
func retry() {
let retryQuery = lastSearchQuery ?? ""
performSearchIfNeeded(query: retryQuery)
}
}
| gpl-2.0 | 06d13048d95a2b46dcdbad931087a094 | 38.939236 | 183 | 0.659118 | 5.598686 | false | false | false | false |
ericvergnaud/antlr4 | runtime/Swift/Sources/Antlr4/tree/pattern/ParseTreePattern.swift | 10 | 5076 | /* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
///
/// A pattern like `<ID> = <expr>;` converted to a _org.antlr.v4.runtime.tree.ParseTree_ by
/// _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher#compile(String, int)_.
///
public class ParseTreePattern {
///
/// This is the backing field for _#getPatternRuleIndex()_.
///
private let patternRuleIndex: Int
///
/// This is the backing field for _#getPattern()_.
///
private let pattern: String
///
/// This is the backing field for _#getPatternTree()_.
///
private let patternTree: ParseTree
///
/// This is the backing field for _#getMatcher()_.
///
private let matcher: ParseTreePatternMatcher
///
/// Construct a new instance of the _org.antlr.v4.runtime.tree.pattern.ParseTreePattern_ class.
///
/// - Parameter matcher: The _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this
/// tree pattern.
/// - Parameter pattern: The tree pattern in concrete syntax form.
/// - Parameter patternRuleIndex: The parser rule which serves as the root of the
/// tree pattern.
/// - Parameter patternTree: The tree pattern in _org.antlr.v4.runtime.tree.ParseTree_ form.
///
public init(_ matcher: ParseTreePatternMatcher,
_ pattern: String, _ patternRuleIndex: Int, _ patternTree: ParseTree) {
self.matcher = matcher
self.patternRuleIndex = patternRuleIndex
self.pattern = pattern
self.patternTree = patternTree
}
///
/// Match a specific parse tree against this tree pattern.
///
/// - Parameter tree: The parse tree to match against this tree pattern.
/// - Returns: A _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ object describing the result of the
/// match operation. The _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch#succeeded()_ method can be
/// used to determine whether or not the match was successful.
///
public func match(_ tree: ParseTree) throws -> ParseTreeMatch {
return try matcher.match(tree, self)
}
///
/// Determine whether or not a parse tree matches this tree pattern.
///
/// - Parameter tree: The parse tree to match against this tree pattern.
/// - Returns: `true` if `tree` is a match for the current tree
/// pattern; otherwise, `false`.
///
public func matches(_ tree: ParseTree) throws -> Bool {
return try matcher.match(tree, self).succeeded()
}
///
/// Find all nodes using XPath and then try to match those subtrees against
/// this tree pattern.
///
/// - Parameter tree: The _org.antlr.v4.runtime.tree.ParseTree_ to match against this pattern.
/// - Parameter xpath: An expression matching the nodes
///
/// - Returns: A collection of _org.antlr.v4.runtime.tree.pattern.ParseTreeMatch_ objects describing the
/// successful matches. Unsuccessful matches are omitted from the result,
/// regardless of the reason for the failure.
///
/*public func findAll(tree : ParseTree, _ xpath : String) -> Array<ParseTreeMatch> {
var subtrees : Array<ParseTree> = XPath.findAll(tree, xpath, matcher.getParser());
var matches : Array<ParseTreeMatch> = Array<ParseTreeMatch>();
for t : ParseTree in subtrees {
var match : ParseTreeMatch = match(t);
if ( match.succeeded() ) {
matches.add(match);
}
}
return matches;
}*/
///
/// Get the _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this tree pattern.
///
/// - Returns: The _org.antlr.v4.runtime.tree.pattern.ParseTreePatternMatcher_ which created this tree
/// pattern.
///
public func getMatcher() -> ParseTreePatternMatcher {
return matcher
}
///
/// Get the tree pattern in concrete syntax form.
///
/// - Returns: The tree pattern in concrete syntax form.
///
public func getPattern() -> String {
return pattern
}
///
/// Get the parser rule which serves as the outermost rule for the tree
/// pattern.
///
/// - Returns: The parser rule which serves as the outermost rule for the tree
/// pattern.
///
public func getPatternRuleIndex() -> Int {
return patternRuleIndex
}
///
/// Get the tree pattern as a _org.antlr.v4.runtime.tree.ParseTree_. The rule and token tags from
/// the pattern are present in the parse tree as terminal nodes with a symbol
/// of type _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ or _org.antlr.v4.runtime.tree.pattern.TokenTagToken_.
///
/// - Returns: The tree pattern as a _org.antlr.v4.runtime.tree.ParseTree_.
///
public func getPatternTree() -> ParseTree {
return patternTree
}
}
| bsd-3-clause | 717e66bfcb72e53d6ede0c0720cd5c00 | 34.006897 | 118 | 0.637904 | 4.331058 | false | false | false | false |
tzef/BmoViewPager | BmoViewPager/Classes/BmoPageItemList.swift | 1 | 21984 | //
// BmoPageItemList.swift
// Pods
//
// Created by LEE ZHE YU on 2017/4/2.
//
//
import UIKit
private let reuseIdentifier = "reuseIdentifier"
protocol BmoPageItemListDelegate: AnyObject {
func bmoViewPageItemList(didSelectItemAt index: Int, previousIndex: Int?)
}
class BmoPageItemList: UIView, UICollectionViewDelegate, UICollectionViewDataSource, BmoPageItemListLayoutDelegate {
var collectionView: UICollectionView? = nil
let collectionLayout = BmoPageItemListLayout(orientation: .horizontal, direction: .leftToRight)
weak var bmoViewPager: BmoViewPager?
weak var bmoDelegate: BmoPageItemListDelegate?
weak var bmoDataSource: BmoViewPagerDataSource?
weak var bmoViewPgaerNavigationBar: BmoViewPagerNavigationBar?
var focusCell, nextCell, previousCell: BmoPageItemCell?
var bmoViewPagerCount = 0
// for calcualte string size
var calculateSizeLabel = UILabel()
// for auto focus
var autoFocus = true
var collectionOffSet: CGFloat = 0
var previousDistance: CGFloat = 0
var nextDistance: CGFloat = 0
var lastProgress: CGFloat = 0
var previousIndex = -1
var focusIndex = -1
var nextIndex = -1
// for interpolation
let percentageLayer = PercentageLayer()
// for userInterfaceLayoutDirection direction
var layoutDirection = UIUserInterfaceLayoutDirection.leftToRight
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(viewPager: BmoViewPager, navigationBar: BmoViewPagerNavigationBar, delegate: BmoPageItemListDelegate) {
self.init()
self.bmoDelegate = delegate
self.bmoViewPager = viewPager
self.bmoViewPgaerNavigationBar = navigationBar
self.backgroundColor = .white
self.layer.addSublayer(percentageLayer)
}
override var bounds: CGRect {
didSet {
if oldValue != bounds {
collectionLayout.layoutChanged = true
}
}
}
func setCollectionView() {
collectionLayout.delegate = self
if bmoViewPgaerNavigationBar?.orientation == .vertical {
collectionLayout.orientation = .vertical
}
if BmoViewPager.isRTL {
collectionLayout.direction = .rightToLeft
layoutDirection = .rightToLeft
}
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionLayout)
collectionView!.register(BmoPageItemCell.classForCoder(), forCellWithReuseIdentifier: reuseIdentifier)
collectionView!.showsHorizontalScrollIndicator = false
collectionView!.showsVerticalScrollIndicator = false
collectionView!.backgroundColor = .clear
collectionView!.dataSource = self
collectionView!.delegate = self
self.addSubview(collectionView!)
collectionView!.bmoVP.autoFit(self)
}
// MARK: - Public
func reloadData() {
guard let bmoViewPager = bmoViewPager else {
bmoViewPagerCount = 0
return
}
bmoViewPagerCount = bmoDataSource?.bmoViewPagerDataSourceNumberOfPage(in: bmoViewPager) ?? 0
if collectionView == nil {
self.setCollectionView()
}
collectionView?.reloadData()
if autoFocus {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.focusToTargetItem()
}
}
}
func focusToTargetItem() {
self.bmoPageItemListLayoutAttributesChanged(collectionLayout.attributesList, animated: true)
}
func focusFrom(index: Int) {
guard let viewPager = bmoViewPager else {
return
}
var progress: CGFloat = 0.0
percentageLayer.percentage = 0.0
percentageLayer.displayDo = { [weak self] (percentage) in
let interpolation = Int(percentage)
progress = percentage - CGFloat(interpolation)
if self?.layoutDirection == .rightToLeft && viewPager.orientation == .horizontal {
progress *= -1
}
self?.updateFocusProgress(&progress, index: index + interpolation, enabledAutoFocusIfNeed: false)
if index < viewPager.presentedPageIndex {
if percentage == 1.0 * CGFloat(viewPager.presentedPageIndex - index) {
self?.percentageLayer.displayDo = nil
self?.reloadData()
}
}
if index > viewPager.presentedPageIndex {
if percentage == -1.0 * CGFloat(index - viewPager.presentedPageIndex) {
self?.percentageLayer.displayDo = nil
self?.reloadData()
}
}
}
if viewPager.presentedPageIndex > index {
percentageLayer.percentage = 1.0 * CGFloat(viewPager.presentedPageIndex - index)
} else if viewPager.presentedPageIndex < index {
percentageLayer.percentage = -1.0 * CGFloat(index - viewPager.presentedPageIndex)
} else {
self.reloadData()
}
}
func updateFocusProgress(_ progress: inout CGFloat, index: Int, enabledAutoFocusIfNeed: Bool = true) {
guard let collectionView = collectionView, let viewPager = bmoViewPager, let navigationBar = bmoViewPgaerNavigationBar else {
return
}
if collectionLayout.attributesList.count == 0 {
return
}
if self.layoutDirection == .rightToLeft && viewPager.orientation == .horizontal {
progress *= -1
}
if focusIndex != index {
focusIndex = index
if navigationBar.orientation == .horizontal {
collectionOffSet = collectionView.contentOffset.x
} else {
collectionOffSet = collectionView.contentOffset.y
}
focusCell = collectionView.cellForItem(at: IndexPath(row: index, section: 0)) as? BmoPageItemCell
if index < bmoViewPagerCount - 1 {
nextIndex = index + 1
nextCell = collectionView.cellForItem(at: IndexPath(row: nextIndex, section: 0)) as? BmoPageItemCell
} else {
if viewPager.infinitScroll {
nextIndex = 0
nextCell = collectionView.cellForItem(at: IndexPath(row: nextIndex, section: 0)) as? BmoPageItemCell
} else {
nextCell = nil
}
}
if index > 0 {
previousIndex = index - 1
previousCell = collectionView.cellForItem(at: IndexPath(row: previousIndex, section: 0)) as? BmoPageItemCell
} else {
if viewPager.infinitScroll {
previousIndex = bmoViewPagerCount - 1
previousCell = collectionView.cellForItem(at: IndexPath(row: previousIndex, section: 0)) as? BmoPageItemCell
} else {
previousCell = nil
}
}
var positionNextIndex = nextIndex
var positionPreviousIndex = previousIndex
if self.layoutDirection == .rightToLeft && bmoViewPgaerNavigationBar?.orientation == .horizontal {
positionNextIndex = (bmoViewPagerCount - 1) - nextIndex
positionPreviousIndex = (bmoViewPagerCount - 1) - previousIndex
}
if let nextAttribute = collectionLayout.attributesList[safe: positionNextIndex] {
if navigationBar.orientation == .horizontal {
nextDistance = nextAttribute.center.x - collectionView.center.x - collectionOffSet
} else {
nextDistance = nextAttribute.center.y - collectionView.center.y - collectionOffSet
}
}
if let previousAttribute = collectionLayout.attributesList[safe: positionPreviousIndex] {
if navigationBar.orientation == .horizontal {
previousDistance = collectionView.center.x + collectionOffSet - previousAttribute.center.x
} else {
previousDistance = collectionView.center.y + collectionOffSet - previousAttribute.center.y
}
}
previousCell?.titleLabel.maskProgress = 0.0
focusCell?.titleLabel.maskProgress = 1.0
nextCell?.titleLabel.maskProgress = 0.0
} else {
nextCell = collectionView.cellForItem(at: IndexPath(row: nextIndex, section: 0)) as? BmoPageItemCell
focusCell = collectionView.cellForItem(at: IndexPath(row: focusIndex, section: 0)) as? BmoPageItemCell
previousCell = collectionView.cellForItem(at: IndexPath(row: previousIndex, section: 0)) as? BmoPageItemCell
if progress >= 1.0 || progress <= -1.0 {
progress = lastProgress
}
if autoFocus && enabledAutoFocusIfNeed {
var willSetOffSet: CGFloat = collectionOffSet
if progress > 0 {
willSetOffSet += nextDistance * progress
} else if progress < 0 {
willSetOffSet += previousDistance * progress
}
if navigationBar.orientation == .horizontal {
if willSetOffSet > collectionView.contentSize.width - collectionView.bounds.width {
willSetOffSet = collectionView.contentSize.width - collectionView.bounds.width
}
} else {
if willSetOffSet > collectionView.contentSize.height - collectionView.bounds.height {
willSetOffSet = collectionView.contentSize.height - collectionView.bounds.height
}
}
if willSetOffSet < 0 {
willSetOffSet = 0
}
if navigationBar.orientation == .horizontal {
collectionView.setContentOffset(CGPoint(x: willSetOffSet, y: collectionView.contentOffset.y), animated: false)
} else {
collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x, y: willSetOffSet), animated: false)
}
}
if progress > 0 {
previousCell?.titleLabel.maskProgress = 0.0
if self.layoutDirection == .rightToLeft && bmoViewPgaerNavigationBar?.orientation == .horizontal {
nextCell?.titleLabel.maskProgress = -1 * (1 - abs(progress))
focusCell?.titleLabel.maskProgress = 1 - abs(progress)
} else {
nextCell?.titleLabel.maskProgress = progress
focusCell?.titleLabel.maskProgress = -1 * progress
}
} else if progress < 0 {
nextCell?.titleLabel.maskProgress = 0.0
if self.layoutDirection == .rightToLeft && bmoViewPgaerNavigationBar?.orientation == .horizontal {
previousCell?.titleLabel.maskProgress = -1 * progress
focusCell?.titleLabel.maskProgress = progress
} else {
previousCell?.titleLabel.maskProgress = -1 * (1 - abs(progress))
focusCell?.titleLabel.maskProgress = 1 - abs(progress)
}
} else {
nextCell?.titleLabel.maskProgress = 0.0
previousCell?.titleLabel.maskProgress = 0.0
focusCell?.titleLabel.maskProgress = 1.0
}
}
lastProgress = progress
}
// MAKR: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if percentageLayer.animation(forKey: "percentage") == nil {
bmoDelegate?.bmoViewPageItemList(didSelectItemAt: indexPath.row, previousIndex: nil)
}
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return bmoViewPagerCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? BmoPageItemCell, let viewPager = bmoViewPager, let navigationBar = bmoViewPgaerNavigationBar else {
return UICollectionViewCell()
}
let title = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemTitle?(viewPager, navigationBar: navigationBar, forPageListAt: indexPath.row) ?? ""
var fraction: CGFloat = 0.0
if indexPath.row == viewPager.presentedPageIndex {
fraction = 1.0
}
if indexPath.row == viewPager.presentedPageIndex - 1 {
if previousCell == nil {
previousCell = cell
}
}
if indexPath.row == viewPager.presentedPageIndex + 1 {
if nextCell == nil {
nextCell = cell
}
}
let rearAttributed = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemNormalAttributed?(viewPager, navigationBar: navigationBar, forPageListAt: indexPath.row)
let backgroundView = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemNormalBackgroundView?(viewPager, navigationBar: navigationBar, forPageListAt: indexPath.row)
let foreAttributed = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemHighlightedAttributed?(viewPager, navigationBar: navigationBar, forPageListAt: indexPath.row)
let foreBackgroundView = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemHighlightedBackgroundView?(viewPager, navigationBar: navigationBar, forPageListAt: indexPath.row)
cell.configureCell(title: title, focusProgress: fraction,
orientation: navigationBar.orientation,
rearAttributed: rearAttributed, foreAttributed: foreAttributed,
backgroundView: backgroundView, foreBackgroundView: foreBackgroundView)
return cell
}
// MARK: - BmoPageItemListLayoutDelegate
func bmoPageItemListLayoutAttributesChanged(_ attributes: [UICollectionViewLayoutAttributes], animated: Bool) {
guard let collectionView = collectionView, let viewPager = bmoViewPager, let navigationBar = bmoViewPgaerNavigationBar else {
return
}
var positionIndex = viewPager.presentedPageIndex
if self.layoutDirection == .rightToLeft && bmoViewPgaerNavigationBar?.orientation == .horizontal {
positionIndex = (bmoViewPagerCount - 1) - positionIndex
}
guard let attribute = collectionLayout.attributesList[safe: positionIndex] else {
return
}
switch navigationBar.orientation {
case .horizontal:
if collectionView.contentSize.width < collectionView.bounds.width {
return
}
var targetX: CGFloat = 0.0
let distance = attribute.center.x - collectionView.center.x
switch distance {
case ...0:
targetX = 0
case 0..<collectionView.contentSize.width - collectionView.bounds.width:
targetX = distance
case (collectionView.contentSize.width - collectionView.bounds.width)...:
targetX = collectionView.contentSize.width - collectionView.bounds.width
default:
break
}
self.focusIndex = -1
collectionOffSet = targetX
collectionView.setContentOffset(CGPoint(x: targetX, y: collectionView.contentOffset.y), animated: animated)
case .vertical:
if collectionView.contentSize.height < collectionView.bounds.height {
return
}
var targetY: CGFloat = 0.0
let distance = attribute.center.y - collectionView.center.y
switch distance {
case ...0:
targetY = 0
case 0..<collectionView.contentSize.height - collectionView.bounds.height:
targetY = distance
case (collectionView.contentSize.height - collectionView.bounds.height)...:
targetY = collectionView.contentSize.height - collectionView.bounds.height
default:
break
}
self.focusIndex = -1
collectionOffSet = targetY
collectionView.setContentOffset(CGPoint(x: collectionView.contentOffset.x, y: targetY), animated: animated)
@unknown default:
fatalError("shouldn't been executed")
}
}
func bmoPageItemListLayout(sizeForItemAt index: Int) -> CGSize {
guard let collectionView = collectionView, let bmoViewPager = bmoViewPager, let navigationBar = bmoViewPgaerNavigationBar else {
return CGSize.zero
}
if let size = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemSize?(bmoViewPager, navigationBar: navigationBar, forPageListAt: index), size != .zero {
return size
}
var itemSpace: CGFloat = 32.0
if let dataSourceItemSpace = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemSpace?(bmoViewPager, navigationBar: navigationBar, forPageListAt: index) {
itemSpace = dataSourceItemSpace
}
guard let title = bmoDataSource?.bmoViewPagerDataSourceNaviagtionBarItemTitle?(bmoViewPager, navigationBar: navigationBar, forPageListAt: index) else {
return CGSize.zero
}
calculateSizeLabel.text = title
calculateSizeLabel.sizeToFit()
let size = calculateSizeLabel.bounds.size
if navigationBar.orientation == .horizontal {
return CGSize(width: size.width + itemSpace, height: collectionView.bounds.size.height)
} else {
return CGSize(width: collectionView.bounds.size.width, height: size.height + itemSpace)
}
}
}
class BmoPageItemCell: UICollectionViewCell {
let titleLabel = BmoDoubleLabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.commonInit()
}
func commonInit() {
titleLabel.textAlignment = .center
self.contentView.addSubview(titleLabel)
titleLabel.bmoVP.autoFit(self.contentView)
}
func configureCell(title: String, focusProgress: CGFloat, orientation: UIPageViewController.NavigationOrientation,
rearAttributed: [NSAttributedString.Key : Any]?, foreAttributed: [NSAttributedString.Key : Any]?,
backgroundView: UIView?, foreBackgroundView: UIView?) {
titleLabel.text = title
titleLabel.orientation = orientation
if let view = backgroundView {
titleLabel.setRearBackgroundView(view)
}
if let view = foreBackgroundView {
titleLabel.setForeBackgroundView(view)
}
if let attributed = rearAttributed {
let mutableAttributedText = NSMutableAttributedString(attributedString: titleLabel.rearLabel.attributedText ?? NSAttributedString())
mutableAttributedText.addAttributes(attributed, range: NSRange(location: 0, length: title.count))
titleLabel.rearAttributedText = mutableAttributedText
} else {
titleLabel.textColor = UIColor.lightGray
}
if let attributed = foreAttributed {
let mutableAttributedText = NSMutableAttributedString(attributedString: titleLabel.foreLabel.attributedText ?? NSAttributedString())
mutableAttributedText.addAttributes(attributed, range: NSRange(location: 0, length: title.count))
titleLabel.foreAttributedText = mutableAttributedText
} else {
titleLabel.foreColor = UIColor.black
}
titleLabel.maskProgress = focusProgress
}
}
class PercentageLayer: CALayer {
var displayDo: ((_ percentage: CGFloat) -> Void)?
@NSManaged var percentage: CGFloat
override init() {
super.init()
}
override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? PercentageLayer {
percentage = layer.percentage
} else {
percentage = 0.0
}
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
}
override class func needsDisplay(forKey key: String) -> Bool {
var needsDisplay = super.needsDisplay(forKey: key)
if key == "percentage" {
needsDisplay = true
}
return needsDisplay
}
override func action(forKey key: String) -> CAAction? {
if displayDo == nil {
return super.action(forKey: key)
}
guard let presentationLayer = presentation() else {
return super.action(forKey: key)
}
if key == "percentage" {
let animation = CABasicAnimation(keyPath: key)
#if swift(>=4.2)
animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
#else
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
#endif
animation.fromValue = presentationLayer.percentage
animation.duration = 0.33
return animation
}
return super.action(forKey: key)
}
override func display() {
guard let presentationLayer = presentation() else { return }
displayDo?(presentationLayer.percentage)
}
}
| mit | 5a7aed1417e4f8af591a2039f55e9af4 | 44.515528 | 217 | 0.624636 | 5.421455 | false | false | false | false |
audrl1010/EasyMakePhotoPicker | EasyMakePhotoPicker/Classes/PhotoAsset.swift | 1 | 1643 | //
// PhotoAsset.swift
// KaKaoChatInputView
//
// Created by myung gi son on 2017. 5. 30..
// Copyright © 2017년 grutech. All rights reserved.
//
import Foundation
import Photos
import RxSwift
public enum AssetType {
case camera
case photo
case video
case livePhoto
}
public struct PhotoAsset: Equatable {
public var localIdentifier: String {
return asset.localIdentifier
}
public var asset: PHAsset
public var isSelected: Bool = false
public var selectedOrder: Int = 0
public var playerItem: AVPlayerItem?
public var livePhoto: PHLivePhoto?
public var type: AssetType {
if asset.mediaSubtypes.contains(.photoLive) {
return .livePhoto
}
else if asset.mediaType == .video {
return .video
}
else if asset.mediaType == .image {
return .photo
}
else {
return .camera
}
}
public var disposeBag = DisposeBag()
public var fullResolutionImage: UIImage {
var fullImage = UIImage()
PhotoManager.shared.fullResolutionImage(for: self.asset)
.subscribeOn(MainScheduler.instance)
.subscribe(onNext: { image in
fullImage = image
})
.disposed(by: disposeBag)
return fullImage
}
public var originalFileName: String? {
if let resource = PHAssetResource.assetResources(for: asset).first {
return resource.originalFilename
}
return nil
}
public init(asset: PHAsset) {
self.asset = asset
}
public static func == (
lhs: PhotoAsset,
rhs: PhotoAsset) -> Bool {
return lhs.asset.localIdentifier ==
rhs.asset.localIdentifier
}
}
| mit | 557b2a63be3344c7fd3e4ebe0ac99979 | 17.850575 | 72 | 0.657317 | 4.293194 | false | false | false | false |
kingsic/SGSegmentedControl | Sources/PagingContent/SGPagingContentCollectionView.swift | 2 | 6952 | //
// SGPagingContentCollectionView.swift
// SGPagingView
//
// Created by kingsic on 2020/12/23.
// Copyright © 2020 kingsic. All rights reserved.
//
import UIKit
public class SGPagingContentCollectionView: SGPagingContentView {
@objc public init(frame: CGRect, parentVC: UIViewController, childVCs: [UIViewController]) {
super.init(frame: frame)
parentViewController = parentVC
childViewControllers = childVCs
addSubview(collectionView)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override var isScrollEnabled: Bool {
willSet {
collectionView.isScrollEnabled = newValue
}
}
public override var isBounces: Bool {
willSet {
collectionView.bounces = newValue
}
}
public override func setPagingContentView(index: Int) {
setPagingContentCollectionView(index: index)
}
// MARK: 内部属性
private weak var parentViewController: UIViewController?
private var childViewControllers: [UIViewController] = []
private var startOffsetX: CGFloat = 0.0
private var previousChildVC: UIViewController?
private var previousChildVCIndex: Int = -1
private var scroll: Bool = false
private lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = bounds.size
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
flowLayout.scrollDirection = .horizontal
let tempCollectionView = UICollectionView(frame: bounds, collectionViewLayout: flowLayout)
tempCollectionView.showsVerticalScrollIndicator = false
tempCollectionView.showsHorizontalScrollIndicator = false
tempCollectionView.isPagingEnabled = true
tempCollectionView.bounces = isBounces
tempCollectionView.backgroundColor = .white
tempCollectionView.delegate = self
tempCollectionView.dataSource = self
tempCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
return tempCollectionView
}()
}
extension SGPagingContentCollectionView {
func setPagingContentCollectionView(index: Int) {
let offsetX = CGFloat(index) * collectionView.frame.size.width
startOffsetX = offsetX
if previousChildVCIndex != index {
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: isAnimated)
}
previousChildVCIndex = index
if delegate != nil && ((delegate?.responds(to: #selector(delegate?.pagingContentView(index:)))) != nil) {
delegate?.pagingContentView?(index: index)
}
}
}
private let cellID = "cellID"
extension SGPagingContentCollectionView: UICollectionViewDataSource {
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childViewControllers.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
cell.contentView.subviews.forEach { (subView) in
subView.removeFromSuperview()
}
let childVC = childViewControllers[indexPath.item]
parentViewController?.addChild(childVC)
cell.contentView.addSubview(childVC.view)
childVC.view.frame = cell.contentView.frame
childVC.didMove(toParent: parentViewController)
return cell
}
}
extension SGPagingContentCollectionView: UICollectionViewDelegate {
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffsetX = scrollView.contentOffset.x
scroll = true
if delegate != nil && ((delegate?.responds(to: #selector(delegate?.pagingContentViewWillBeginDragging))) != nil) {
delegate?.pagingContentViewWillBeginDragging?()
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scroll = false
let offsetX = scrollView.contentOffset.x
previousChildVCIndex = Int(offsetX / scrollView.frame.size.width)
if delegate != nil && ((delegate?.responds(to: #selector(delegate?.pagingContentView(index:)))) != nil) {
delegate?.pagingContentView?(index: previousChildVCIndex)
}
if delegate != nil && ((delegate?.responds(to: #selector(delegate?.pagingContentViewDidEndDecelerating))) != nil) {
delegate?.pagingContentViewDidEndDecelerating?()
}
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isAnimated == true && scroll == false {
return
}
// 1、定义获取需要的数据
var progress: CGFloat = 0.0
var currentIndex: Int = 0
var targetIndex: Int = 0
// 2、判断是左滑还是右滑
let currentOffsetX: CGFloat = scrollView.contentOffset.x
let scrollViewW: CGFloat = scrollView.bounds.size.width
if currentOffsetX > startOffsetX { // 左滑
if currentOffsetX > CGFloat(childViewControllers.count - 1) * scrollViewW && isBounces == true {
return
}
// 1、计算 progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW);
// 2、计算 currentIndex
currentIndex = Int(currentOffsetX / scrollViewW);
// 3、计算 targetIndex
targetIndex = currentIndex + 1;
if targetIndex >= childViewControllers.count {
progress = 1;
targetIndex = currentIndex;
}
// 4、如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1;
targetIndex = currentIndex;
}
} else { // 右滑
if currentOffsetX < 0 && isBounces == true {
return
}
// 1、计算 progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW));
// 2、计算 targetIndex
targetIndex = Int(currentOffsetX / scrollViewW);
// 3、计算 currentIndex
currentIndex = targetIndex + 1;
if currentIndex >= childViewControllers.count {
currentIndex = childViewControllers.count - 1;
}
}
if delegate != nil && ((delegate?.responds(to: #selector(delegate?.pagingContentView(contentView:progress:currentIndex:targetIndex:)))) != nil) {
delegate?.pagingContentView?(contentView: self, progress: progress, currentIndex: currentIndex, targetIndex: targetIndex)
}
}
}
| mit | 417487fd913854eff9bc93a676ec8ffd | 38.327586 | 153 | 0.651323 | 5.693012 | false | false | false | false |
naithar/Kitura-net | Sources/KituraNet/HTTPParser/HTTPParserStatus.swift | 1 | 1675 | /*
* Copyright IBM Corporation 2016
*
* 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
/// List of parser states
enum HTTPParserState {
case initial
case headersComplete
case messageComplete
case reset
}
/// HTTP parser error types
enum HTTPParserErrorType {
case parsedLessThanRead
case unexpectedEOF
case internalError // TODO
}
extension HTTPParserErrorType: CustomStringConvertible {
public var description: String {
switch self {
case .internalError:
return "An internal error occurred"
case .parsedLessThanRead:
return "Parsed fewer bytes than were passed to the HTTP parser"
case .unexpectedEOF:
return "Unexpectedly got an EOF when reading the request"
}
}
}
struct HTTPParserStatus {
init() {}
var state = HTTPParserState.initial
var error: HTTPParserErrorType? = nil
var keepAlive = false
var upgrade = false
var bytesLeft = 0
mutating func reset() {
state = HTTPParserState.initial
error = nil
keepAlive = false
upgrade = false
}
}
| apache-2.0 | 6c9ea38032923509e14bfb4b36e993b4 | 24.769231 | 75 | 0.678209 | 4.827089 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/01115-swift-lexer-lexidentifier.swift | 11 | 526 | // 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
// RUN: not %target-swift-frontend %s -parse
class func b() {
atic let d: String = {
init <A: A where A.B == D>(e: A.B) {
}
}
struct d<f : e, g: e where g.h == f.h> {
self.init()
| apache-2.0 | 58c7a7e3b5f9b9cf68a0fba83d8a82ea | 34.066667 | 78 | 0.692015 | 3.246914 | false | false | false | false |
Valbrand/tibei | Sources/Tibei/connection/Connection.swift | 1 | 5955 | //
// Connection.swift
// connectivityTest
//
// Created by DANIEL J OLIVEIRA on 11/16/16.
// Copyright © 2016 Daniel de Jesus Oliveira. All rights reserved.
//
import UIKit
/**
Represents a single connection between server and client. The same class is used on either side.
*/
public class Connection: NSObject, StreamDelegate {
let outwardMessagesQueue: OperationQueue = OperationQueue()
/// An unique identifier for the connection
public let identifier: ConnectionID
var input: InputStream
var output: OutputStream
var isWriteable: Bool = false {
didSet {
self.outwardMessagesQueue.isSuspended = !self.isWriteable
}
}
var isReady: Bool = false
var pingTimer = Timer()
/// :nodoc:
override public var hashValue: Int {
return self.identifier.id.hashValue
}
var delegate: ConnectionDelegate?
init(input: InputStream, output: OutputStream, identifier: ConnectionID? = nil) {
self.input = input
self.output = output
self.outwardMessagesQueue.maxConcurrentOperationCount = 1
self.outwardMessagesQueue.isSuspended = true
self.identifier = identifier ?? ConnectionID()
}
func open() {
self.openStream(self.input)
self.openStream(self.output)
}
func close() {
self.closeStream(self.input)
self.closeStream(self.output)
}
private func openStream(_ stream: Stream) {
stream.delegate = self
stream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)
stream.open()
}
private func closeStream(_ stream: Stream) {
stream.remove(from: RunLoop.current, forMode: .defaultRunLoopMode)
stream.close()
}
func sendMessage<Message: JSONConvertibleMessage>(_ message: Message) {
self.outwardMessagesQueue.addOperation {
do {
_ = try self.output.writeMessage(message)
} catch {
self.delegate?.connection(self, raisedError: error)
}
}
}
func dataFromInput(_ stream: InputStream) throws -> IncomingData {
var lengthInBytes = Array<UInt8>(repeating: 0, count: MemoryLayout<Constants.MessageLength>.size)
_ = stream.read(&lengthInBytes, maxLength: lengthInBytes.count)
let length: Constants.MessageLength = UnsafePointer(lengthInBytes).withMemoryRebound(to: Constants.MessageLength.self, capacity: 1) {
$0.pointee
}
guard length > 0 else {
return .nilMessage
}
var actualDataBuffer = Array<UInt8>(repeating: 0, count: Int(length))
let readBytesCount = stream.read(&actualDataBuffer, maxLength: actualDataBuffer.count)
if readBytesCount < 0 {
throw ConnectionError.inputError
}
let payloadData = Data(bytes: actualDataBuffer)
do {
let payload = try JSONSerialization.jsonObject(with: payloadData, options: []) as! [String:Any]
if let messageType = payload[Fields.messageTypeField] as? String, messageType == KeepAliveMessage.type {
let keepAliveMessage = self.keepAliveMessage(jsonObject: payload)
if !keepAliveMessage.hasMoreData {
return .keepAliveMessage
}
}
print("Received payload:")
print(payload)
return .data(payload)
}
}
func keepAliveMessage(jsonObject: [String: Any]) -> KeepAliveMessage {
return KeepAliveMessage(jsonObject: jsonObject)
}
// MARK: - keeping connection alive
func startKeepAliveRoutine() {
self.pingTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(Connection.sendKeepAliveMessage), userInfo: nil, repeats: true)
}
@objc private func sendKeepAliveMessage() throws {
do {
self.outwardMessagesQueue.addOperation {
do {
try self.output.writeMessage(KeepAliveMessage())
} catch {
self.delegate?.connection(self, raisedError: error)
}
}
}
}
func stopKeepAliveRoutine() {
self.pingTimer.invalidate()
}
// MARK: - StreamDelegate protocol
/// :nodoc:
public func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
switch eventCode {
case Stream.Event.errorOccurred:
self.stopKeepAliveRoutine()
self.delegate?.connection(self, hasEndedWithErrors: true)
case Stream.Event.endEncountered:
self.stopKeepAliveRoutine()
self.delegate?.connection(self, hasEndedWithErrors: false)
case Stream.Event.openCompleted:
let wasReady = self.isReady
let inputIsOpen = self.input.streamStatus == Stream.Status.open
let outputIsOpen = self.output.streamStatus == Stream.Status.open
self.isReady = inputIsOpen && outputIsOpen
if !wasReady && self.isReady {
self.startKeepAliveRoutine()
self.delegate?.connectionOpened(self)
}
case Stream.Event.hasBytesAvailable:
do {
let incomingData: IncomingData = try self.dataFromInput(self.input)
if case .data(let payload) = incomingData {
self.delegate?.connection(self, receivedData: payload)
}
} catch {
self.stopKeepAliveRoutine()
self.delegate?.connection(self, raisedError: error)
}
case Stream.Event.hasSpaceAvailable:
self.isWriteable = true
default:
return
}
}
}
| mit | 17eaf44b7c3a95f015a97d09dc6a5f75 | 32.829545 | 162 | 0.59691 | 5.032967 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/CompanyCard/MyCompanyController.swift | 1 | 2421 | //
// MyCompanyController.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/8.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
class MyCompanyController: UIViewController {
static let formViewHeight: CGFloat = 434
private lazy var formView: FormView = {
let formView = FormView()
let headerView = MyCompanyFormHeaderView(frame: CGSize(width: SCREEN_WIDTH, height: 0.1).rect)
formView.tableHeaderView = headerView
headerView.alpha = 0
formView.separatorStyle = .none
formView.isScrollEnabled = false
formView.backgroundColor = .white
formView.delegate = self
formView.rows = [
[
Row<MyCoInfoCell>(viewData: NoneItem()),
Row<MyCoRightsCell>(viewData: NoneItem()),
Row<MyCoRightsActiveCell>(viewData: NoneItem()),
Row<MyCoRightsRecommendTitleCell>(viewData: NoneItem())
]
]
return formView
}()
private let myCoRightsRecommendView = MyCoRightsRecommendView(frame: .zero)
override func viewDidLoad() {
super.viewDidLoad()
myCoRightsRecommendView.addHeaderView(formView)
let items = (0...4).map { $0.description }
myCoRightsRecommendView.data = items
view.addSubview(myCoRightsRecommendView)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(showReminderView))
}
@objc
func showReminderView() {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(0.3)
UIView.setAnimationCurve(.easeInOut)
formView.beginUpdates()
self.formView.tableHeaderView?.alpha = 1
self.formView.tableHeaderView?.frame.size.height = 63
formView.endUpdates()
UIView.commitAnimations()
self.formView.frame.size.height += 63
myCoRightsRecommendView.freshView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
formView.frame = CGSize(width: view.bounds.width, height: type(of: self).formViewHeight).rect
myCoRightsRecommendView.frame = view.bounds
}
}
extension MyCompanyController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(#function)
}
}
| mit | 5d6e90d0032b9deb3ba0d255c32ca660 | 29.075 | 138 | 0.657523 | 4.754941 | false | false | false | false |
steelwheels/KiwiScript | KiwiShell/Source/KHPreference.swift | 1 | 1868 | /**
* @file KHPreference.swift
* @brief Extend KLPreference class
* @par Copyright
* Copyright (C) 2020 Steel Wheels Project
*/
import CoconutData
import KiwiLibrary
import KiwiEngine
import JavaScriptCore
import Foundation
extension CNPreference
{
public var shellPreference: CNShellPreference {
return get(name: CNShellPreference.PreferenceName, allocator: {
() -> CNShellPreference in
return CNShellPreference()
})
}
}
public class CNShellPreference: CNPreferenceTable
{
public static let PreferenceName = "shell"
public static let PromptItem = "prompt"
public init() {
super.init(sectionName: "shell")
}
public var prompt: JSValue? {
get {
if let val = super.scriptValue(forKey: CNShellPreference.PromptItem) {
return val
} else {
return nil
}
}
set(newval) {
if let val = newval {
super.set(scriptValue: val, forKey: CNShellPreference.PromptItem)
}
}
}
}
@objc public protocol KHPreferenceProtocol: JSExport
{
var shell: JSValue { get }
}
@objc public class KHPreference: KLPreference, KHPreferenceProtocol
{
public var shell: JSValue {
get {
let newpref = KHShellPreference(context: super.context)
return JSValue(object: newpref, in: self.context)
}
}
}
@objc public protocol KHShellPreferenceProtocol: JSExport
{
var prompt: JSValue { set get }
}
@objc public class KHShellPreference: NSObject, KHShellPreferenceProtocol
{
public static let preferenceName = "shell"
private var mContext: KEContext
public init(context ctxt: KEContext) {
mContext = ctxt
}
public var prompt: JSValue {
set(newval){
let shellpref = CNPreference.shared.shellPreference
shellpref.prompt = newval
}
get {
let shellpref = CNPreference.shared.shellPreference
if let val = shellpref.prompt {
return val
} else {
return JSValue(nullIn: mContext)
}
}
}
}
| lgpl-2.1 | f45f17788f4629aa82fe95ee1d261ed7 | 18.663158 | 73 | 0.719486 | 3.329768 | false | false | false | false |
onurersel/anim | src/Settings.swift | 1 | 1127 | //
// Settings.swift
// anim
//
// Created by Onur Ersel on 2017-02-16.
// Copyright (c) 2017 Onur Ersel. All rights reserved.
import Foundation
/// Animation settings.
public struct animSettings {
init(delay: TimeInterval = 0, duration: TimeInterval = 1, ease: animEase = .easeOutQuint, completion: (animClosure)? = nil, isUserInteractionsEnabled: Bool = false) {
self.delay = delay
self.duration = duration
self.ease = ease
self.completion = completion
self.isUserInteractionsEnabled = isUserInteractionsEnabled
}
/// Delay before animation starts.
public var delay: TimeInterval
/// Duration of animation.
public var duration: TimeInterval
/// Easing of animation.
public var ease: animEase
/// Completion block which runs after animation.
public var completion: (animClosure)?
/// Preferred animator used for the animation.
lazy public var preferredAnimator: AnimatorType = AnimatorType.default
/// Enables user interactions on views while animating. Not available on macOS.
public var isUserInteractionsEnabled: Bool
}
| mit | 6809a39ee9cfb0e1924e8f04284f26ca | 34.21875 | 170 | 0.705413 | 4.63786 | false | false | false | false |
svd-zp/SDPagingViewController | SDPagingViewController/SDPagingViewController/RootViewController.swift | 1 | 5195 | //
// RootViewController.swift
// SDPagingViewController
//
// Created by SvD on 09.12.15.
// Copyright © 2015 SvD. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
pageViewRect = CGRectInset(pageViewRect, 40.0, 40.0)
}
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
title = "test"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
if (orientation == .Portrait) || (orientation == .PortraitUpsideDown) || (UIDevice.currentDevice().userInterfaceIdiom == .Phone) {
// In portrait orientation or on iPhone: Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers![0]
let viewControllers = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = true
return .Min
}
// In landscape orientation: Set set the spine location to "mid" and the page view controller's view controllers array to contain two view controllers. If the current page is even, set it to contain the current and next view controllers; if it is odd, set the array to contain the previous and current view controllers.
let currentViewController = self.pageViewController!.viewControllers![0] as! DataViewController
var viewControllers: [UIViewController]
let indexOfCurrentViewController = self.modelController.indexOfViewController(currentViewController)
if (indexOfCurrentViewController == 0) || (indexOfCurrentViewController % 2 == 0) {
let nextViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerAfterViewController: currentViewController)
viewControllers = [currentViewController, nextViewController!]
} else {
let previousViewController = self.modelController.pageViewController(self.pageViewController!, viewControllerBeforeViewController: currentViewController)
viewControllers = [previousViewController!, currentViewController]
}
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
return .Mid
}
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
if let vc = pageViewController.viewControllers?[0] {
title = vc.title
}
}
}
| mit | 5d8d2a60d3fa96fdd0e21313214914d0 | 50.425743 | 333 | 0.731228 | 5.922463 | false | false | false | false |
atrick/swift | test/SILOptimizer/cross-module-effects.swift | 4 | 5578 | // RUN: %empty-directory(%t)
// First test: computed effects should be serialized if a module is _not_ compiled with -enable-library-evolution.
// RUN: %target-swift-frontend -parse-as-library -emit-module -emit-module-path=%t/Module.swiftmodule -module-name=Module -DMODULE %s -O -Xllvm -sil-disable-pass=cmo -c -o module.o
// RUN: %target-sil-opt %t/Module.swiftmodule | %FileCheck --check-prefix=CHECK-FR-MODULE %s
// RUN: %target-swift-frontend -parse-as-library -I%t -module-name=Main -DMAIN %s -O -emit-sil | %FileCheck --check-prefix=CHECK-MAIN --check-prefix=CHECK-FR-MAIN %s
// Second test: computed effects should _not_ be serialized if a module is compiled with -enable-library-evolution.
// RUN: %target-swift-frontend -parse-as-library -emit-module -emit-module-path=%t/Module.swiftmodule -module-name=Module -DMODULE %s -O -enable-library-evolution -c -o module.o
// RUN: %target-sil-opt %t/Module.swiftmodule | %FileCheck --check-prefix=CHECK-LE-MODULE %s
// RUN: %target-swift-frontend -parse-as-library -I%t -module-name=Main -DMAIN %s -O -emit-sil | %FileCheck --check-prefix=CHECK-MAIN --check-prefix=CHECK-LE-MAIN %s
// REQUIRES: swift_in_compiler
#if MODULE
public final class X {
@usableFromInline
var i = 27
public init() { }
}
// CHECK-FR-MODULE-DAG: sil [escapes !%0.**] [canonical] @$s6Module17noInlineNoEffectsySiAA1XCF :
// CHECK-LE-MODULE-NOT: @$s6Module17noInlineNoEffectsySiAA1XCF
public func noInlineNoEffects(_ x: X) -> Int {
return x.i
}
// CHECK-FR-MODULE-DAG: sil [escapes !%0.**] [canonical] @$s6Module14internalCalleeySiAA1XCF :
// CHECK-LE-MODULE-DAG: sil [canonical] @$s6Module14internalCalleeySiAA1XCF :
@usableFromInline
func internalCallee(_ x: X) -> Int {
return x.i
}
// CHECK-FR-MODULE-DAG: sil [serialized] [noinline] [defined_escapes !%0.**] [canonical] @$s6Module17inlineWithEffectsySiAA1XCF :
// CHECK-LE-MODULE-DAG: sil [serialized] [noinline] [defined_escapes !%0.**] [canonical] @$s6Module17inlineWithEffectsySiAA1XCF :
@inlinable
@inline(never)
@_effects(notEscaping x.**)
public func inlineWithEffects(_ x: X) -> Int {
return internalCallee(x)
}
// CHECK-FR-MODULE-DAG: sil [serialized] [noinline] [escapes !%0.**] [canonical] @$s6Module15inlineNoEffectsySiAA1XCF :
// CHECK-LE-MODULE-DAG: sil [serialized] [noinline] [canonical] @$s6Module15inlineNoEffectsySiAA1XCF :
@inlinable
@inline(never)
public func inlineNoEffects(_ x: X) -> Int {
return internalCallee(x)
}
// CHECK-FR-MODULE-DAG: sil [defined_escapes !%0.**] [canonical] @$s6Module19noInlineWithEffectsySiAA1XCF :
// CHECK-LE-MODULE-NOT: @$s6Module19noInlineWithEffectsySiAA1XCF
@_effects(notEscaping x.**)
public func noInlineWithEffects(_ x: X) -> Int {
return x.i
}
// CHECK-FR-MODULE-DAG: sil [serialized] [noinline] [escapes !%0.**] [canonical] @$s6Module12simpleInlineySiAA1XCF :
// CHECK-LE-MODULE-DAG: sil [serialized] [noinline] [canonical] @$s6Module12simpleInlineySiAA1XCF :
@inlinable
@inline(never)
public func simpleInline(_ x: X) -> Int {
return x.i
}
#else
import Module
// CHECK-MAIN-LABEL: sil [noinline] @$s4Main7callit1SiyF :
// CHECK-FR-MAIN: alloc_ref [stack] $X
// CHECK-EV-MAIN: alloc_ref $X
// CHECK-MAIN: } // end sil function '$s4Main7callit1SiyF'
@inline(never)
public func callit1() -> Int {
let x = X()
return noInlineNoEffects(x)
}
// CHECK-FR-MAIN: sil [escapes !%0.**] @$s6Module17noInlineNoEffectsySiAA1XCF :
// CHECK-EV-MAIN: sil @$s6Module17noInlineNoEffectsySiAA1XCF :
// CHECK-MAIN-LABEL: sil [noinline] @$s4Main7callit2SiyF :
// CHECK-FR-MAIN: alloc_ref [stack] $X
// CHECK-EV-MAIN: alloc_ref $X
// CHECK-MAIN: } // end sil function '$s4Main7callit2SiyF'
@inline(never)
public func callit2() -> Int {
let x = X()
return inlineNoEffects(x)
}
// CHECK-FR-MAIN: sil public_external [noinline] [escapes !%0.**] @$s6Module15inlineNoEffectsySiAA1XCF :
// CHECK-EV-MAIN: sil public_external [noinline] @$s6Module15inlineNoEffectsySiAA1XCF :
// CHECK-MAIN-LABEL: sil [noinline] @$s4Main7callit3SiyF :
// CHECK-FR-MAIN: alloc_ref [stack] $X
// CHECK-EV-MAIN: alloc_ref [stack] $X
// CHECK-MAIN: } // end sil function '$s4Main7callit3SiyF'
@inline(never)
public func callit3() -> Int {
let x = X()
return noInlineWithEffects(x)
}
// CHECK-FR-MAIN: sil [defined_escapes !%0.**] @$s6Module19noInlineWithEffectsySiAA1XCF
// CHECK-EV-MAIN: sil @$s6Module17noInlineNoEffectsySiAA1XCF :
// CHECK-MAIN-LABEL: sil [noinline] @$s4Main7callit4SiyF :
// CHECK-FR-MAIN: alloc_ref [stack] $X
// CHECK-EV-MAIN: alloc_ref [stack] $X
// CHECK-MAIN: } // end sil function '$s4Main7callit4SiyF'
@inline(never)
public func callit4() -> Int {
let x = X()
return inlineWithEffects(x)
}
// CHECK-FR-MAIN: sil public_external [noinline] [defined_escapes !%0.**] @$s6Module17inlineWithEffectsySiAA1XCF :
// CHECK-EV-MAIN: sil public_external [noinline] @$s6Module17inlineWithEffectsySiAA1XCF :
// CHECK-MAIN-LABEL: sil [noinline] @$s4Main7callit5SiyF :
// CHECK-FR-MAIN: alloc_ref [stack] $X
// CHECK-EV-MAIN: alloc_ref $X
// CHECK-MAIN: } // end sil function '$s4Main7callit5SiyF'
@inline(never)
public func callit5() -> Int {
let x = X()
return simpleInline(x)
}
// CHECK-FR-MAIN: sil public_external [noinline] [escapes !%0.**] @$s6Module12simpleInlineySiAA1XCF :
// CHECK-EV-MAIN: sil public_external [noinline] @$s6Module12simpleInlineySiAA1XCF :
// CHECK-FR-MAIN: sil [escapes !%0.**] @$s6Module14internalCalleeySiAA1XCF :
// CHECK-EV-MAIN: sil @$s6Module14internalCalleeySiAA1XCF :
#endif
| apache-2.0 | 2df604800d695005fe19fa0884328fab | 37.468966 | 180 | 0.706884 | 2.86492 | false | false | false | false |
scoremedia/Fisticuffs | Sources/Fisticuffs/BidirectionalBindableProperty.swift | 1 | 9001 | // The MIT License (MIT)
//
// Copyright (c) 2015 theScore Inc.
//
// 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 BidirectionalBindableProperty<Control: AnyObject, ValueType> {
public typealias Getter = (Control) -> ValueType
public typealias Setter = (Control, ValueType) -> Void
weak var control: Control?
let getter: Getter
let setter: Setter
let uiChangeEvent: Event<Void> = Event()
var currentBinding: Disposable?
// Provides an easy way of setting up additional cleanup that should be done
// after the binding has died (ie, removing UIControl target-actions, deregistering
// NSNotifications, deregistering KVO notifications)
var extraCleanup: Disposable?
public init(control: Control, getter: @escaping Getter, setter: @escaping Setter, extraCleanup: Disposable? = nil) {
self.control = control
self.getter = getter
self.setter = setter
self.extraCleanup = extraCleanup
}
deinit {
currentBinding?.dispose()
extraCleanup?.dispose()
}
}
extension BidirectionalBindableProperty {
// Should be called when something results in the underlying value being changed
// (ie., when a user types in a UITextField)
public func pushChangeToObservable() {
uiChangeEvent.fire(())
}
}
//MARK: - Binding
public extension BidirectionalBindableProperty {
//MARK: Two way binding
/// Bind property to observable
///
/// - Parameters:
/// - observable: The `Observable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ observable: Observable<ValueType>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(observable, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - observable: The `Observable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ observable: Observable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
let disposables = DisposableBag()
bindingHandler.setup(control, propertySetter: setter, subscribable: observable, receiveOn: scheduler)
disposables.add(bindingHandler)
bindingHandler.setup(getter, changeEvent: uiChangeEvent).subscribe { [weak observable] _, data in
observable?.value = data
}.addTo(disposables)
currentBinding = disposables
}
//MARK: One way binding
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ subscribable: Subscribable<ValueType>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(subscribable, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ subscribable: Subscribable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
bindingHandler.setup(control, propertySetter: setter, subscribable: subscribable, receiveOn: scheduler)
currentBinding = bindingHandler
}
}
//MARK: - Binding - Optionals
public extension BidirectionalBindableProperty where ValueType: OptionalType {
//MARK: Two way binding
/// Bind property to subscribable
///
/// - Parameters:
/// - observable: The `Observable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ observable: Observable<ValueType.Wrapped>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(observable, receiveOn: scheduler, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - observable: The `Observable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ observable: Observable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType.Wrapped>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
let disposables = DisposableBag()
let outerBindingHandler = OptionalTypeBindingHandler<Control, Data, ValueType>(innerHandler: bindingHandler)
outerBindingHandler.setup(control, propertySetter: setter, subscribable: observable, receiveOn: scheduler)
disposables.add(outerBindingHandler)
outerBindingHandler.setup(getter, changeEvent: uiChangeEvent).subscribe { [weak observable] _, data in
observable?.value = data
}.addTo(disposables)
currentBinding = disposables
}
//MARK: One way binding
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
func bind(_ subscribable: Subscribable<ValueType.Wrapped>, receiveOn scheduler: Scheduler = MainThreadScheduler()) {
bind(subscribable, DefaultBindingHandler())
}
/// Bind property to subscribable
///
/// - Parameters:
/// - subscribable: The `Subscribable`
/// - receiveOn: The `Scheduler` for the call back. Defaults to `MainThreadScheduler`
/// - bindingHandler: The custom `BindingHandler`
func bind<Data>(
_ subscribable: Subscribable<Data>,
receiveOn scheduler: Scheduler = MainThreadScheduler(),
_ bindingHandler: BindingHandler<Control, Data, ValueType.Wrapped>
) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
let outerBindingHandler = OptionalTypeBindingHandler<Control, Data, ValueType>(innerHandler: bindingHandler)
outerBindingHandler.setup(control, propertySetter: setter, subscribable: subscribable, receiveOn: scheduler)
currentBinding = outerBindingHandler
}
}
//MARK: - Deprecated
public extension BidirectionalBindableProperty {
@available(*, deprecated, message: "Use BidirectionBindableProperty(subscribable, BindingHandlers.transform(...)) instead")
func bind<OtherType>(_ subscribable: Subscribable<OtherType>, transform: @escaping (OtherType) -> ValueType) {
bind(subscribable, BindingHandlers.transform(transform))
}
@available(*, deprecated, message: "Use a Computed in place of the `block`")
func bind(_ block: @escaping () -> ValueType) {
currentBinding?.dispose()
currentBinding = nil
guard let control = control else { return }
var computed: Computed<ValueType>? = Computed<ValueType>(block: block)
let bindingHandler = DefaultBindingHandler<Control, ValueType>()
bindingHandler.setup(control, propertySetter: setter, subscribable: computed!)
currentBinding = DisposableBlock {
computed = nil // keep a strong reference to the Computed
bindingHandler.dispose()
}
}
}
| mit | ab644e3df160067672f944f177029e2b | 37.302128 | 127 | 0.682146 | 4.810796 | false | false | false | false |
AugustRush/Stellar | Sources/DynamicItem+Behavior.swift | 1 | 6946 | //Copyright (c) 2016
//
//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
enum PhysicalDirection {
case left
case right
case up
case down
case Angle(CGFloat)
case vector(CGFloat,CGFloat)
func angle() -> CGFloat {
switch self {
case .Angle(let a):
return a
case .vector(let x, let y):
return atan2(y, x)
case .left:
return atan2(0, -1)
case .right:
return atan2(0, 1)
case .up:
return atan2(-1, 0)
case .down:
return atan2(1, 0)
}
}
}
extension UIDynamicItem {
//gravity
func gravityBehavior(_ magnitude: CGFloat = 1.0, direction: PhysicalDirection = .down) -> UIGravityBehavior {
let gravity = UIGravityBehavior()
switch direction {
case .Angle(let a):
gravity.setAngle(a, magnitude: magnitude)
case .left:
gravity.gravityDirection = CGVector(dx: -1, dy: 0)
case .right:
gravity.gravityDirection = CGVector(dx: 1, dy: 0)
case .up:
gravity.gravityDirection = CGVector(dx: 0, dy: -1)
case .down:
gravity.gravityDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
gravity.gravityDirection = CGVector(dx: x, dy: y)
}
gravity.magnitude = magnitude
gravity.addItem(self)
return gravity
}
//snap
func snapBehavior(_ toPoint: CGPoint, damping: CGFloat = 0.5) -> UISnapBehavior {
let snap = UISnapBehavior(item: self,snapTo: toPoint)
snap.damping = damping
return snap
}
//attachment
func attachmentBehavior(_ toAnchor: CGPoint, length: CGFloat = 0.0, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedToAnchor: toAnchor)
attachment.length = length
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.frequency = frequency
return attachment
}
func attachmentBehavior(_ toItem: UIDynamicItem, damping: CGFloat = 0.5, frequency: CGFloat = 1.0, length: CGFloat = 0.0) -> UIAttachmentBehavior {
let attachment = UIAttachmentBehavior(item: self,attachedTo: toItem)
attachment.damping = damping
attachment.length = length
attachment.frequency = frequency
return attachment
}
//push
func pushBehavior(_ direction: CGVector, mode:UIPushBehavior.Mode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.pushDirection = direction
push.magnitude = magnitude
return push
}
func pushBehavior(_ direction: PhysicalDirection, mode:UIPushBehavior.Mode = .continuous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
switch direction {
case .Angle(let a):
push.setAngle(a, magnitude: magnitude)
case .left:
push.pushDirection = CGVector(dx: -1, dy: 0)
case .right:
push.pushDirection = CGVector(dx: 1, dy: 0)
case .up:
push.pushDirection = CGVector(dx: 0, dy: -1)
case .down:
push.pushDirection = CGVector(dx: 0, dy: 1)
case .vector(let x, let y):
push.pushDirection = CGVector(dx: x, dy: y)
}
push.magnitude = magnitude
return push
}
func pushBehavior(_ angle: CGFloat, mode:UIPushBehavior.Mode = .instantaneous, magnitude: CGFloat = 1.0) -> UIPushBehavior {
let push = UIPushBehavior(items: [self], mode: mode)
push.angle = angle
push.magnitude = magnitude
return push
}
//collision
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries, path: UIBezierPath) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, for: path)
collision.addItem(self)
return collision
}
func collisionBehavior(_ mode: UICollisionBehavior.Mode = .boundaries, fromPoint: CGPoint, toPoint: CGPoint) -> UICollisionBehavior {
let collision = UICollisionBehavior()
collision.collisionMode = mode
let identifier = String(describing: Unmanaged.passUnretained(self).toOpaque())
collision.addBoundary(withIdentifier: identifier as NSCopying, from: fromPoint, to: toPoint)
collision.addItem(self)
return collision
}
//itemBehavior
func itemBehavior(_ elasticity: CGFloat = 0.5, friction: CGFloat = 0.5, density: CGFloat = 1, resistance: CGFloat = 0, angularResistance: CGFloat = 0, allowsRotation: Bool = true) -> UIDynamicItemBehavior {
let behavior = UIDynamicItemBehavior()
behavior.addItem(self)
behavior.elasticity = elasticity
behavior.friction = friction
behavior.density = density
behavior.resistance = resistance
behavior.angularResistance = angularResistance
behavior.allowsRotation = allowsRotation
return behavior
}
}
| mit | 5ea53bf98f04d7b1990b65507918a4f0 | 40.592814 | 462 | 0.65275 | 4.803596 | false | false | false | false |
neonichu/NBMaterialDialogIOS | Example/Pods/Nimble/Nimble/Matchers/BeLogical.swift | 2 | 3156 | import Foundation
internal func beBool(expectedValue expectedValue: BooleanType, stringValue: String, falseMatchesNil: Bool) -> MatcherFunc<BooleanType> {
return MatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "be \(stringValue)"
let actual = actualExpression.evaluate()
if expectedValue {
return actual?.boolValue == expectedValue.boolValue
} else if !falseMatchesNil {
return actual != nil && actual!.boolValue != !expectedValue.boolValue
} else {
return actual?.boolValue != !expectedValue.boolValue
}
}
}
// MARK: beTrue() / beFalse()
/// A Nimble matcher that succeeds when the actual value is exactly true.
/// This matcher will not match against nils.
public func beTrue() -> NonNilMatcherFunc<Bool> {
return basicMatcherWithFailureMessage(equal(true)) { failureMessage in
failureMessage.postfixMessage = "be true"
}
}
/// A Nimble matcher that succeeds when the actual value is exactly false.
/// This matcher will not match against nils.
public func beFalse() -> NonNilMatcherFunc<Bool> {
return basicMatcherWithFailureMessage(equal(false)) { failureMessage in
failureMessage.postfixMessage = "be false"
}
}
// MARK: beTruthy() / beFalsy()
/// A Nimble matcher that succeeds when the actual value is not logically false.
public func beTruthy() -> MatcherFunc<BooleanType> {
return beBool(expectedValue: true, stringValue: "truthy", falseMatchesNil: true)
}
/// A Nimble matcher that succeeds when the actual value is logically false.
/// This matcher will match against nils.
public func beFalsy() -> MatcherFunc<BooleanType> {
return beBool(expectedValue: false, stringValue: "falsy", falseMatchesNil: true)
}
extension NMBObjCMatcher {
public class func beTruthyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? }
return beTruthy().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalsyMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as BooleanType? }
return beFalsy().matches(expr, failureMessage: failureMessage)
}
}
public class func beTrueMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? }
return beTrue().matches(expr, failureMessage: failureMessage)
}
}
public class func beFalseMatcher() -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
let expr = actualExpression.cast { ($0 as? NSNumber)?.boolValue ?? false as Bool? }
return beFalse().matches(expr, failureMessage: failureMessage)
}
}
}
| mit | bd19ca1305662cfe9eee9b15e441f899 | 40.526316 | 136 | 0.692015 | 5.131707 | false | false | false | false |
mlibai/XZKit | XZKit/Code/Category/UIKit/Swift/WKWebView+XZKit.swift | 1 | 3661 | //
// WKWebView.swift
// XZKit
//
// Created by Xezun on 2017/5/17.
// Copyright © 2017年 XEZUN INC. All rights reserved.
//
import UIKit
import WebKit
extension WKWebView {
/// 在 UserDefaults 中记录原始 UserAgent 所用的键。
public static let defaultUserAgentUserDefaultsKey = "com.xezun.XZKit.userAgent.default"
/// 在 UserDefaults 中记录已设置的 UserAgent 所用的键。
public static let currentUserAgentUserDefaultsKey = "com.xezun.XZKit.userAgent.current"
/// 默认的 UserAgent 。
/// - Note: WKWebView 在 iOS 9.0 以后,默认设置属性 customUserAgent 或 configuration.applicationNameForUserAgent 所覆盖。
/// - Note: 此属性在第一次调用时,可能耗时较长,建议在启动是预调用一次。
@objc(xz_defaultUserAgent) open class var defaultUserAgent: String {
get {
if let userAgent = objc_getAssociatedObject(self, &AssociationKey.userAgent) as? String {
return userAgent
}
if let userAgent = UserDefaults.standard.volatileDomain(forName: UserDefaults.registrationDomain)["UserAgent"] as? String {
objc_setAssociatedObject(self, &AssociationKey.userAgent, userAgent, .OBJC_ASSOCIATION_COPY_NONATOMIC)
return userAgent
}
if let userAgent = UserDefaults.standard.string(forKey: WKWebView.currentUserAgentUserDefaultsKey) {
objc_setAssociatedObject(self, &AssociationKey.userAgent, userAgent, .OBJC_ASSOCIATION_COPY_NONATOMIC)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
return userAgent
}
if let userAgent = UserDefaults.standard.string(forKey: WKWebView.defaultUserAgentUserDefaultsKey) {
objc_setAssociatedObject(self, &AssociationKey.userAgent, userAgent, .OBJC_ASSOCIATION_COPY_NONATOMIC)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
return userAgent
}
if let userAgent = UIWebView().stringByEvaluatingJavaScript(from: "window.navigator.userAgent") {
objc_setAssociatedObject(self, &AssociationKey.userAgent, userAgent, .OBJC_ASSOCIATION_COPY_NONATOMIC)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
UserDefaults.standard.set(userAgent, forKey: WKWebView.defaultUserAgentUserDefaultsKey)
return userAgent
}
let systemVersion = UIDevice.current.systemVersion
let userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS \(systemVersion) like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
objc_setAssociatedObject(self, &AssociationKey.userAgent, userAgent, .OBJC_ASSOCIATION_COPY_NONATOMIC)
UserDefaults.standard.register(defaults: ["UserAgent": userAgent])
return userAgent;
}
set {
objc_setAssociatedObject(self, &AssociationKey.userAgent, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
UserDefaults.standard.set(newValue, forKey: WKWebView.currentUserAgentUserDefaultsKey)
UserDefaults.standard.register(defaults: ["UserAgent": newValue])
}
}
}
extension UIWebView {
/// 与 WKWebView.defaultUserAgent 相同。
@objc(xz_userAgent) open class var userAgent: String {
get {
return WKWebView.defaultUserAgent
}
set {
WKWebView.defaultUserAgent = newValue
}
}
}
private struct AssociationKey {
static var userAgent = 0
}
| mit | 0a5a555821c34295bbbffd7e31e90db8 | 42.8 | 151 | 0.667523 | 4.942172 | false | false | false | false |
cwwise/CWWeChat | CWWeChat/MainClass/Contacts/ContactsDetailController/CWContactDetailController.swift | 2 | 4372 | //
// CWContactDetailController.swift
// CWWeChat
//
// Created by wei chen on 2017/4/3.
// Copyright © 2017年 cwcoder. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class CWContactDetailController: CWBaseTableViewController {
var userId: String
init(userId: String) {
self.userId = userId
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let bag = DisposeBag()
fileprivate var contact: CWUserModel!
lazy var tableViewManager: CWTableViewManager = {
let tableViewManager = CWTableViewManager(tableView: self.tableView)
tableViewManager.delegate = self
tableViewManager.dataSource = self
return tableViewManager
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "详细资料"
CWContactHelper.share.fetchContactById(userId, complete: { (contact, error) in
self.contact = contact
self.tableView.reloadData()
})
let style = CWTableViewStyle()
style.titleTextFont = UIFont.systemFont(ofSize: 15)
style.titleTextColor = UIColor(hex: "333333")
style.detailTextFont = UIFont.systemFont(ofSize: 15)
style.detailTextColor = UIColor(hex: "333333")
tableViewManager.style = style
self.tableView.register(CWContactInfoCell.self, forCellReuseIdentifier: CWContactInfoCell.identifier)
self.tableView.register(CWContactDetailAlbumCell.self, forCellReuseIdentifier: CWContactDetailAlbumCell.identifier)
setupData()
let barItemImage = UIImage(named: "barbuttonicon_more")
let rightBarItem = UIBarButtonItem(image: barItemImage, style: .done, target: self, action: #selector(rightBarItemClick))
self.navigationItem.rightBarButtonItem = rightBarItem
}
func setupData() {
let item1 = CWTableViewItem(title: "信息")
item1.cellHeight = 87
tableViewManager.addSection(itemsOf: [item1])
let item2 = CWTableViewItem(title: "设置备注和标签")
tableViewManager.addSection(itemsOf: [item2])
let item3 = CWTableViewItem(title: "地区")
let item4 = CWTableViewItem(title: "个人相册")
item4.cellHeight = 87
let item5 = CWTableViewItem(title: "更多")
tableViewManager.addSection(itemsOf: [item3, item4, item5])
let frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 100)
let footerView = CWContactDetailFooterView(frame: frame)
footerView.button.rx.tap
.subscribe(onNext: { [weak self] in
self?.goChatController()
}).disposed(by: bag)
self.tableView.tableFooterView = footerView
}
func goChatController() {
let chatVC = CWChatMessageController(targetId: userId)
self.navigationController?.pushViewController(chatVC, animated: true)
}
@objc func rightBarItemClick() {
let settingVC = CWContactSettingController()
self.navigationController?.pushViewController(settingVC, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension CWContactDetailController: CWTableViewManagerDataSource {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell? {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: CWContactInfoCell.identifier,
for: indexPath) as! CWContactInfoCell
if contact != nil {
cell.userModel = contact
}
return cell
} else if indexPath.section == 2 && indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: CWContactDetailAlbumCell.identifier,
for: indexPath)
return cell
} else {
return nil
}
}
}
extension CWContactDetailController: CWTableViewManagerDelegate {
}
| mit | c45137edca456fea78f637818090182a | 31.291045 | 129 | 0.63254 | 4.979287 | false | false | false | false |
paulz/PerspectiveTransform | Example/Tests/CompareTransformSpecConfiguration.swift | 1 | 2214 | //
// CompareTransformSpecConfiguration.swift
// Application Specs
//
// Created by Paul Zabelin on 4/10/19.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Quick
import Nimble
class CompareTransformSpecConfiguration: QuickConfiguration {
override class func configure(_ configuration: Configuration) {
sharedExamples("transformer") { sharedContext in
var transformer: TransformMatrixCalculator!
let points = [
CGPoint(x: 108.315837, y: 80.1687782),
CGPoint(x: 377.282671, y: 41.4352201),
CGPoint(x: 193.321418, y: 330.023027),
CGPoint(x: 459.781253, y: 251.836131)
]
let frame = CGRect(origin: CGPoint.zero,
size: CGSize(width: 20, height: 10))
beforeEach {
transformer = sharedContext()["method"] as? TransformMatrixCalculator
}
it("should be identity for same start and destination") {
let toItself = transformer.transform(frame: frame, points: frame.corners())
expect(toItself) ≈ CATransform3DIdentity
}
it("produce the same solution as the algebraic method") {
let algebra = AlgebraMethod()
expect(transformer.transform(frame: frame, points: points)) ≈ algebra.transform(frame: frame, points: points)
}
}
}
}
protocol TransformMatrixCalculator {
func transform(frame: CGRect, points: [CGPoint]) -> CATransform3D
}
struct AlgebraMethod: TransformMatrixCalculator {
func transform(frame: CGRect, points: [CGPoint]) -> CATransform3D {
let destination = QuadrilateralCalc()
destination.topLeft = points[0]
destination.topRight = points[1]
destination.bottomLeft = points[2]
destination.bottomRight = points[3]
let start = QuadrilateralCalc()
let corners = frame.corners()
start.topLeft = corners[0]
start.topRight = corners[1]
start.bottomLeft = corners[2]
start.bottomRight = corners[3]
return start.rectToQuad(rect: start.box(), quad: destination)
}
}
| mit | 31041765ec6bfb4c3c5e92c60ee4d943 | 34.063492 | 125 | 0.615663 | 4.535934 | false | true | false | false |
AndrewBennet/readinglist | ReadingList/ViewControllers/Lists/ManageLists.swift | 1 | 5051 | import Foundation
import UIKit
import CoreData
final class ManageLists: UITableViewController {
var books: [Book]!
var onComplete: (() -> Void)?
private var candidateListsExist = false
override func viewDidLoad() {
super.viewDidLoad()
if books.isEmpty { preconditionFailure() }
if books.count == 1 {
NotificationCenter.default.addObserver(self, selector: #selector(saveOccurred(_:)), name: .NSManagedObjectContextDidSave, object: PersistentStoreManager.container.viewContext)
}
updateCandidateListPresenceCache()
}
private func updateCandidateListPresenceCache() {
let fetchRequest = NSManagedObject.fetchRequest(List.self, limit: 1)
fetchRequest.predicate = NSPredicate.or(books.map {
NSPredicate(format: "SELF IN %@", $0.lists).not()
})
candidateListsExist = !(try! PersistentStoreManager.container.viewContext.fetch(fetchRequest)).isEmpty
}
@objc private func saveOccurred(_ notification: Notification) {
// In case the book's list membership changes, reload the table so that the second section is shown or hidden accordingly
updateCandidateListPresenceCache()
tableView.reloadData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
if books.count > 1 || books[0].lists.isEmpty { return 1 }
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 && !candidateListsExist {
return super.tableView(tableView, numberOfRowsInSection: section) - 1
} else {
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 && indexPath.row == 0 {
present(ManageLists.newListAlertController(books) { [unowned self] _ in
self.navigationController?.dismiss(animated: true, completion: self.onComplete)
}, animated: true) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
if let addToExistingLists = segue.destination as? AddToExistingLists {
addToExistingLists.books = Set<Book>(books)
addToExistingLists.onComplete = onComplete
} else if let removeFromExistingLists = segue.destination as? RemoveFromExistingLists {
guard books.count == 1 else { preconditionFailure() }
guard !books[0].lists.isEmpty else { assertionFailure(); return }
removeFromExistingLists.book = books[0]
}
}
@IBAction private func doneTapped(_ sender: Any) {
navigationController?.dismiss(animated: true)
}
static func newListAlertController(_ books: [Book], onComplete: ((List) -> Void)? = nil) -> UIAlertController {
let existingListNames = List.names(fromContext: PersistentStoreManager.container.viewContext)
func textValidator(listName: String?) -> Bool {
guard let listName = listName, !listName.isEmptyOrWhitespace else { return false }
return !existingListNames.contains(listName)
}
return TextBoxAlert(title: "Add New List", message: "Enter a name for your list", placeholder: "Enter list name", textValidator: textValidator) { listName in
guard let listName = listName else { preconditionFailure() }
let childContext = PersistentStoreManager.container.viewContext.childContext()
let createdList = List(context: childContext, name: listName)
createdList.addBooks(books.map { $0.inContext(childContext) })
childContext.saveAndLogIfErrored()
onComplete?(createdList)
}
}
/*
Returns the appropriate View Controller for adding a book (or books) to a list. If there are no lists, this
will be a UIAlertController; otherwise, a UINavigationController. onComplete only called if some action was
taken (rather than just cancelling the dialog, for example).
*/
static func getAppropriateVcForManagingLists(_ booksToAdd: [Book], onComplete: (() -> Void)? = nil) -> UIViewController {
let listCount = NSManagedObject.fetchRequest(List.self, limit: 1)
if try! PersistentStoreManager.container.viewContext.count(for: listCount) > 0 {
let rootAddToList = UIStoryboard.ManageLists.instantiateRoot(withStyle: .formSheet) as! UINavigationController
let manageLists = rootAddToList.viewControllers[0] as! ManageLists
manageLists.books = booksToAdd
manageLists.onComplete = onComplete
return rootAddToList
} else {
return ManageLists.newListAlertController(booksToAdd) { _ in
onComplete?()
}
}
}
}
| gpl-3.0 | b6b8736c268cb882b2bc7d7beac2e22c | 44.098214 | 187 | 0.66858 | 5.096872 | false | false | false | false |
troystribling/BlueCap | Examples/Beacon/Beacon/UIAlertControllerExtensions.swift | 1 | 1342 | //
// UIAlertViewExtensions.swift
// BlueCap
//
// Created by Troy Stribling on 7/6/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
extension UIAlertController {
class func alertOnError(_ error: Swift.Error, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: handler))
return alert
}
class func alertOnErrorWithMessage(_ message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Error", message:message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:handler))
return alert
}
class func alertWithMessage(_ message: String, handler: ((UIAlertAction?) -> Void)? = nil) -> UIAlertController {
let alert = UIAlertController(title: "Alert", message:message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:handler))
return alert
}
}
| mit | d7b5e26f5f1c29a51bae2cefe923e0d3 | 42.290323 | 137 | 0.705663 | 4.580205 | false | false | false | false |
visenze/visearch-sdk-swift | Example/Example/SearchResultsCollectionViewController.swift | 1 | 4378 | //
// SearchResultsCollectionViewController.swift
// Example
//
// Created by Hung on 7/10/16.
// Copyright © 2016 ViSenze. All rights reserved.
//
import UIKit
private let reuseIdentifier = "searchColViewCell"
import ViSearchSDK
class SearchResultsCollectionViewController: UICollectionViewController {
public var photoResults: [ViImageResult] = []
public var reqId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Do any additional setup after loading the view.
// collectionView?.reloadData()
setupCollectionViewLayout()
}
func setupCollectionViewLayout() {
let layout = UICollectionViewFlowLayout()
let column = 3
let itemWidth = floor((view.bounds.size.width - CGFloat(column - 1)) / CGFloat(column))
layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
layout.minimumInteritemSpacing = 1.0
layout.minimumLineSpacing = 1.0
layout.footerReferenceSize = CGSize(width: collectionView!.bounds.size.width, height: 100.0)
collectionView!.collectionViewLayout = layout
}
//MARK: hud methods
private func showHud(){
KRProgressHUD.show()
}
private func dismissHud() {
KRProgressHUD.dismiss()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoResults.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImgCollectionViewCell
// Configure the cell
if let imageURL = photoResults[indexPath.row].im_url {
cell.imgView.load(imageURL)
}
if let score = photoResults[indexPath.row].score {
let percent = Int(score * 100)
cell.similarityLabel.text = "Similarity: \(percent)%"
}
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
//showHud()
let im_name = photoResults[indexPath.row].im_name
// call tracking api here to register the click
// alternately, you can present similar images or recommend them to users in the image detail page
// let params = ViTrackParams(reqId: self.reqId, action: "click")
// params?.imName = im_name
//
// ViSearch.sharedInstance.track(params: params!) { (success, error) in
// DispatchQueue.main.async {
// self.alert(message: "Click event sent!")
// self.dismissHud()
// }
//
// }
}
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment this method to specify if the specified item should be selected
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
return true
}
*/
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return false
}
override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
}
*/
}
| mit | b9af3217fa21ea4e329a6f41240279d6 | 32.669231 | 170 | 0.667124 | 5.403704 | false | false | false | false |
belkhadir/firefox-ios | Providers/Profile.swift | 1 | 27478 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
private let log = Logger.syncLogger
public let ProfileDidStartSyncingNotification = "ProfileDidStartSyncingNotification"
public let ProfileDidFinishSyncingNotification = "ProfileDidFinishSyncingNotification"
public protocol SyncManager {
var isSyncing: Bool { get }
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
func syncEverything() -> Success
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func onRemovedAccount(account: FirefoxAccount?) -> Success
func onAddedAccount() -> Success
}
typealias EngineIdentifier = String
typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult
class ProfileFileAccessor: FileAccessor {
init(profile: Profile) {
let profileDirName = "profile.\(profile.localName())"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: NSString
if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path as NSString
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString
}
super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName))
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init() {
profile = BrowserProfile(localName: "profile", app: nil)
}
func displaySentTabForURL(URL: NSURL, title: String) {
let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil)
self.profile.queue.addToQueue(item)
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
if let currentSettings = app.currentUserNotificationSettings() {
if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
log.info("Displaying notification for URL \(URL.absoluteString)")
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString)
notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title]
notification.alertAction = nil
notification.category = TabSendCategory
app.presentLocalNotificationNow(notification)
}
}
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: protocol<BrowserHistory, SyncableHistory> { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: protocol<BrowserLogins, SyncableLogins> { get }
func shutdown()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
// Do we have an account at all?
func hasAccount() -> Bool
// Do we have an account that (as far as we know) is in a syncable state?
func hasSyncableAccount() -> Bool
func getAccount() -> FirefoxAccount?
func removeAccount()
func setAccount(account: FirefoxAccount)
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func sendItems(items: [ShareItem], toClients clients: [RemoteClient])
var syncManager: SyncManager { get }
}
public class BrowserProfile: Profile {
private let name: String
weak private var app: UIApplication?
init(localName: String, app: UIApplication?) {
self.name = localName
self.app = app
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil)
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
KeychainWrapper.serviceName = baseBundleIdentifier
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
}
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account data.")
removeAccount()
prefs.clearAll()
}
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func shutdown() {
if dbCreated {
db.close()
}
if loginsDBCreated {
loginsDB.close()
}
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString,
let tabIsPrivate = notification.userInfo!["isPrivate"] as? Bool {
// Only record local vists if the change notification originated from a non-private tab
if !tabIsPrivate {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType)
log.debug("Recording visit for \(url) with type \(v).")
history.addLocalVisit(visit)
}
} else {
let url = notification.userInfo!["url"] as? NSURL
log.debug("Ignoring navigation for \(url).")
}
}
deinit {
self.syncManager.endTimedSyncs()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func localName() -> String {
return name
}
var files: FileAccessor {
return ProfileFileAccessor(profile: self)
}
lazy var queue: TabQueue = {
return SQLiteQueue(db: self.db)
}()
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "browser.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory> = {
return SQLiteHistory(db: self.db)!
}()
var favicons: Favicons {
return self.places
}
var history: protocol<BrowserHistory, SyncableHistory> {
return self.places
}
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let _ = self.places
return SQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var syncManager: SyncManager = {
return BrowserSyncManager(profile: self)
}()
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandStoringSyncDelegate()
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
let commands = items.map { item in
SyncCommand.fromShareItem(item, withAction: "displayURI")
}
self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() }
}
lazy var logins: protocol<BrowserLogins, SyncableLogins> = {
return SQLiteLogins(db: self.loginsDB)
}()
private lazy var loginsKey: String? = {
let key = "sqlcipher.key.logins.db"
if KeychainWrapper.hasValueForKey(key) {
return KeychainWrapper.stringForKey(key)
}
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
KeychainWrapper.setString(secret, forKey: key)
return secret
}()
private var loginsDBCreated = false
private lazy var loginsDB: BrowserDB = {
self.loginsDBCreated = true
return BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.None
}
func getAccount() -> FirefoxAccount? {
return account
}
func removeAccount() {
let old = self.account
prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
KeychainWrapper.removeObjectForKey(name + ".account")
self.account = nil
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount(old)
// deregister for remote notifications
app?.unregisterForRemoteNotifications()
}
func setAccount(account: FirefoxAccount) {
KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account")
self.account = account
// register for notifications for the account
registerForNotifications()
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
self.syncManager.onAddedAccount()
}
func registerForNotifications() {
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.View.rawValue
viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
viewAction.activationMode = UIUserNotificationActivationMode.Foreground
viewAction.destructive = false
viewAction.authenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.Bookmark.rawValue
bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground
bookmarkAction.destructive = false
bookmarkAction.authenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.ReadingList.rawValue
readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
readingListAction.activationMode = UIUserNotificationActivationMode.Foreground
readingListAction.destructive = false
readingListAction.authenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default)
sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal)
app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory]))
app?.registerForRemoteNotifications()
}
// Extends NSObject so we can use timers.
class BrowserSyncManager: NSObject, SyncManager {
unowned private let profile: BrowserProfile
let FifteenMinutes = NSTimeInterval(60 * 15)
let OneMinute = NSTimeInterval(60)
private var syncTimer: NSTimer? = nil
/**
* Locking is managed by withSyncInputs. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
var syncLock = OSSpinLock() {
didSet {
if oldValue == syncLock {
return
}
let notification = syncLock == 0 ? ProfileDidFinishSyncingNotification : ProfileDidStartSyncingNotification
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil))
}
}
// According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value
// and a locked lock is a non-zero value
var isSyncing: Bool {
return syncLock != 0
}
private func beginSyncing() -> Bool {
return OSSpinLockTry(&syncLock)
}
private func endSyncing() {
OSSpinLockUnlock(&syncLock)
}
init(profile: BrowserProfile) {
self.profile = profile
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil)
}
deinit {
// Remove 'em all.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(notification: NSNotification) {
log.debug("Login did change.")
if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = NSDate.now()
// Give it a few seconds.
let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered)
// Trigger on the main queue. The bulk of the sync work runs in the background.
dispatch_after(when, dispatch_get_main_queue()) {
self.syncLogins()
}
}
}
var prefsForSync: Prefs {
return self.profile.prefs.branch("sync")
}
func onAddedAccount() -> Success {
return self.syncEverything()
}
func onRemovedAccount(account: FirefoxAccount?) -> Success {
let h: SyncableHistory = self.profile.history
let flagHistory = { h.onRemovedAccount() }
let clearTabs = { self.profile.remoteClientsAndTabs.onRemovedAccount() }
// Run these in order, because they both write to the same DB!
return accumulate([flagHistory, clearTabs])
>>> {
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
return succeed()
}
}
private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = Selector("syncOnTimer")
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info)
}
private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
}
private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing history to storage.")
let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs)
return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info)
}
private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing logins to storage.")
let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs)
return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info)
}
/**
* Returns nil if there's no account.
*/
private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? {
if let account = profile.account {
if !beginSyncing() {
log.info("Not syncing \(label); already syncing something.")
return deferMaybe(AlreadySyncingError())
}
if let label = label {
log.info("Syncing \(label).")
}
let authState = account.syncAuthState
let syncPrefs = profile.prefs.branch("sync")
let readyDeferred = SyncStateMachine.toReady(authState, prefs: syncPrefs)
let delegate = profile.getSyncDelegate()
let go = readyDeferred >>== { ready in
function(delegate, syncPrefs, ready)
}
// Always unlock when we're done.
go.upon({ res in self.endSyncing() })
return go
}
log.warning("No account; can't sync.")
return nil
}
/**
* Runs the single provided synchronization function and returns its status.
*/
private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult {
return self.withSyncInputs(label, function: function) ??
deferMaybe(.NotStarted(.NoAccount))
}
/**
* Runs each of the provided synchronization functions with the same inputs.
* Returns an array of IDs and SyncStatuses the same length as the input.
*/
private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
typealias Pair = (EngineIdentifier, SyncStatus)
let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in
let thunks = synchronizers.map { (i, f) in
return { () -> Deferred<Maybe<Pair>> in
log.debug("Syncing \(i)…")
return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) }
}
}
return accumulate(thunks)
}
return self.withSyncInputs(nil, function: combined) ??
deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) })
}
func syncEverything() -> Success {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate),
("logins", self.syncLoginsWithDelegate),
("history", self.syncHistoryWithDelegate)
) >>> succeed
}
@objc func syncOnTimer() {
log.debug("Running timed logins sync.")
// Note that we use .upon here rather than chaining with >>> precisely
// to allow us to sync subsequent engines regardless of earlier failures.
// We don't fork them in parallel because we want to limit perf impact
// due to background syncs, and because we're cautious about correctness.
self.syncLogins().upon { result in
if let success = result.successValue {
log.debug("Timed logins sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed logins sync failed. Reason: \(reason).")
}
log.debug("Running timed history sync.")
self.syncHistory().upon { result in
if let success = result.successValue {
log.debug("Timed history sync succeeded. Status: \(success.description).")
} else {
let reason = result.failureValue?.description ?? "none"
log.debug("Timed history sync failed. Reason: \(reason).")
}
}
}
}
func syncClients() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("clients", function: syncClientsWithDelegate)
}
func syncClientsThenTabs() -> SyncResult {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate)
) >>== { statuses in
let tabsStatus = statuses[1].1
return deferMaybe(tabsStatus)
}
}
func syncLogins() -> SyncResult {
return self.sync("logins", function: syncLoginsWithDelegate)
}
func syncHistory() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("history", function: syncHistoryWithDelegate)
}
}
}
class AlreadySyncingError: MaybeErrorType {
var description: String {
return "Already syncing."
}
}
| mpl-2.0 | cbc50802552b24f512d298540a07a7e3 | 37.80791 | 238 | 0.639467 | 5.309372 | false | false | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/Namespaces/Media/MediaStatistics.swift | 2 | 2803 | //
// MediaStatistics.swift
//
// Copyright (c) 2016 - 2018 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
/// This element specifies various statistics about a media object like the
/// view count and the favorite count. Valid attributes are views and favorites.
public class MediaStatistics {
/// The element's attributes.
public class Attributes {
/// The number of views.
public var views: Int?
/// The number fo favorites.
public var favorites: Int?
}
/// The element's attributes.
public var attributes: Attributes?
public init() { }
}
// MARK: - Initializers
extension MediaStatistics {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaStatistics.Attributes(attributes: attributeDict)
}
}
extension MediaStatistics.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.views = Int(attributeDict["views"] ?? "")
self.favorites = Int(attributeDict["favorites"] ?? "")
}
}
// MARK: - Equatable
extension MediaStatistics: Equatable {
public static func ==(lhs: MediaStatistics, rhs: MediaStatistics) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension MediaStatistics.Attributes: Equatable {
public static func ==(lhs: MediaStatistics.Attributes, rhs: MediaStatistics.Attributes) -> Bool {
return
lhs.views == rhs.views &&
lhs.favorites == rhs.favorites
}
}
| mit | 1c2a542c06654de7c9e42d5470ec777b | 28.197917 | 101 | 0.667142 | 4.70302 | false | false | false | false |
xcodeswift/xcproj | Sources/XcodeProj/Objects/SwiftPackage/XCSwiftPackageProductDependency.swift | 1 | 2546 | import Foundation
/// This element is an abstract parent for specialized targets.
public class XCSwiftPackageProductDependency: PBXContainerItem, PlistSerializable {
/// Product name.
public var productName: String
/// Package reference.
var packageReference: PBXObjectReference?
/// Package the product dependency refers to.
public var package: XCRemoteSwiftPackageReference? {
get {
packageReference?.getObject()
}
set {
packageReference = newValue?.reference
}
}
// MARK: - Init
public init(productName: String,
package: XCRemoteSwiftPackageReference? = nil) {
self.productName = productName
packageReference = package?.reference
super.init()
}
public required init(from decoder: Decoder) throws {
let objects = decoder.context.objects
let repository = decoder.context.objectReferenceRepository
let container = try decoder.container(keyedBy: CodingKeys.self)
productName = try container.decode(String.self, forKey: .productName)
if let packageString: String = try container.decodeIfPresent(.package) {
packageReference = repository.getOrCreate(reference: packageString, objects: objects)
} else {
packageReference = nil
}
try super.init(from: decoder)
}
func plistKeyAndValue(proj: PBXProj, reference: String) throws -> (key: CommentedString, value: PlistValue) {
var dictionary = try super.plistValues(proj: proj, reference: reference)
dictionary["isa"] = .string(CommentedString(XCSwiftPackageProductDependency.isa))
if let package = package {
dictionary["package"] = .string(.init(package.reference.value, comment: "XCRemoteSwiftPackageReference \"\(package.name ?? "")\""))
}
dictionary["productName"] = .string(.init(productName))
return (key: CommentedString(reference, comment: productName),
value: .dictionary(dictionary))
}
// MARK: - Codable
fileprivate enum CodingKeys: String, CodingKey {
case productName
case package
}
// MARK: - Equatable
@objc override public func isEqual(to object: Any?) -> Bool {
guard let rhs = object as? XCSwiftPackageProductDependency else { return false }
if packageReference != rhs.packageReference { return false }
if productName != rhs.productName { return false }
return super.isEqual(to: rhs)
}
}
| mit | 15dd83076577b5668235d13b1af587b3 | 35.371429 | 143 | 0.65868 | 5.217213 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Main Categories/General/Models/Semester.swift | 1 | 3374 | //
// Semester.swift
// HTWDD
//
// Created by Benjamin Herzog on 05/01/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import Foundation
import Marshal
enum Semester: Hashable, CustomStringConvertible, Comparable {
case summer(year: Int)
case winter(year: Int)
var year: Int {
switch self {
case .summer(let year):
return year
case .winter(let year):
return year
}
}
var localized: String {
switch self {
case .summer(let year):
return Loca.summerSemester + " \(year)"
case .winter(let year):
return Loca.winterSemester + " \(year)"
}
}
var description: String {
switch self {
case .summer(let year):
return "SS_\(year)"
case .winter(let year):
return "WS_\(year)"
}
}
func hash(into hasher: inout Hasher) {
hasher.combine(description.hashValue)
}
static func <(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 < year2
case (.winter(let year1), .winter(let year2)):
return year1 < year2
case (.summer(let year1), .winter(let year2)):
if year1 == year2 {
return true
} else {
return year1 < year2
}
case (.winter(let year1), .summer(let year2)):
if year1 == year2 {
return false
} else {
return year1 < year2
}
}
}
static func ==(lhs: Semester, rhs: Semester) -> Bool {
switch (lhs, rhs) {
case (.summer(let year1), .summer(let year2)):
return year1 == year2
case (.winter(let year1), .winter(let year2)):
return year1 == year2
default:
return false
}
}
}
extension Semester: ValueType {
static func value(from object: Any) throws -> Semester {
guard let number = object as? Int else {
throw MarshalError.typeMismatch(expected: Int.self, actual: type(of: object))
}
let rawValue = "\(number)"
guard rawValue.count == 5 else {
throw MarshalError.typeMismatch(expected: 5, actual: rawValue.count)
}
var raw = rawValue
let rawType = raw.removeLast()
guard let year = Int(raw) else {
throw MarshalError.typeMismatch(expected: Int.self, actual: raw)
}
if rawType == "1" {
return .summer(year: year)
} else if rawType == "2" {
return .winter(year: year)
} else {
throw MarshalError.typeMismatch(expected: "1 or 2", actual: rawType)
}
}
}
extension Semester: Codable {
func encode(to encoder: Encoder) throws {
let semesterNumber: Int
switch self {
case .summer(_): semesterNumber = 1
case .winter(_): semesterNumber = 2
}
var container = encoder.singleValueContainer()
try container.encode(self.year*10 + semesterNumber)
}
init(from decoder: Decoder) throws {
let number = try decoder.singleValueContainer().decode(Int.self)
self = try Semester.value(from: number)
}
}
| gpl-2.0 | c8f6c89b7ac60790db23e98ed5f1899a | 25.351563 | 89 | 0.539875 | 4.335476 | false | false | false | false |
pixlwave/Stingtk-iOS | Source/Extends.swift | 1 | 4596 | import Foundation
import AVFoundation
import MediaPlayer
extension URL {
var isMediaItem: Bool { scheme == "ipod-library" }
var isFileInsideInbox: Bool {
guard isFileURL, let inboxURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("Inbox") else {
return false
}
let directoryURL = resolvingSymlinksInPath().deletingLastPathComponent() // resolve symlinks to match /private/var with /var
return directoryURL == inboxURL
}
func songTitle() -> String? {
if isMediaItem {
return mediaItem()?.title
} else if isFileURL {
if let metadata = metadata() {
let title = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .commonIdentifierTitle).first
return title?.stringValue
}
}
return nil
}
func songArtist() -> String? {
if isMediaItem {
return mediaItem()?.artist
} else if isFileURL {
if let metadata = metadata() {
let artist = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .commonIdentifierArtist).first
return artist?.stringValue
}
}
return nil
}
func songAlbum() -> String? {
if isMediaItem {
return mediaItem()?.albumTitle
} else if isFileURL {
if let metadata = metadata() {
let album = AVMetadataItem.metadataItems(from: metadata, filteredByIdentifier: .commonIdentifierAlbumName).first
return album?.stringValue
}
}
return nil
}
func mediaItem() -> MPMediaItem? {
guard
let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
let idQuery = components.queryItems?.filter({ $0.name == "id" }).first,
let persistentID = idQuery.value
else {
return nil
}
let mediaQuery = MPMediaQuery(filterPredicates: [MPMediaPropertyPredicate(value: persistentID, forProperty: MPMediaItemPropertyPersistentID)])
return mediaQuery.items?.first
}
func metadata() -> [AVMetadataItem]? {
let asset = AVAsset(url: self)
return asset.metadata
}
}
extension AVAudioPCMBuffer {
convenience init?(for audioFile: AVAudioFile) {
self.init(pcmFormat: audioFile.processingFormat, frameCapacity: AVAudioFrameCount(audioFile.length))
}
}
extension Notification.Name {
static let addStingFromLibrary = Notification.Name("Add Sting From Library")
static let addStingFromFiles = Notification.Name("Add Sting From Files")
static let stingsDidChange = Notification.Name("Stings Did Change")
static let waveformViewDidLayoutSubviews = Notification.Name("Waveform View Did Layout Subviews")
static let didFinishEditing = Notification.Name("Did Finish Editing")
}
extension TimeInterval {
static let lengthFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.zeroFormattingBehavior = .pad
return formatter
}()
static let remainingFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.minute, .second]
formatter.includesTimeRemainingPhrase = true
formatter.zeroFormattingBehavior = .pad
return formatter
}()
func formattedAsLength() -> String? {
return TimeInterval.lengthFormatter.string(from: self)
}
func formattedAsRemaining() -> String? {
return TimeInterval.remainingFormatter.string(from: self)
}
}
extension UIColor {
static let backgroundColor = UIColor(named: "Background Color")!
static let borderColor = UIColor(named: "Border Color")!
static let tintColor = UIColor(named: "Tint Color")!
}
extension UserDefaults {
static let presets = UserDefaults(suiteName: "uk.pixlwave.StingPad.Presets")!
}
extension UIProgressView {
func reset() {
progress = 0
layoutIfNeeded()
}
}
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
| mpl-2.0 | a0609232b0a318e04f7d0b49b5f4bf1c | 30.696552 | 156 | 0.633594 | 5.204983 | false | false | false | false |
miracl/amcl | version3/swift/rom_ed25519.swift | 1 | 2792 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
//
// rom.swift
//
// Created by Michael Scott on 12/06/2015.
// Copyright (c) 2015 Michael Scott. All rights reserved.
//
public struct ROM{
#if D32
// Base Bits= 29
// C25519 Curve Modulus
static public let Modulus:[Chunk] = [0x1FFFFFED,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x1FFFFFFF,0x7FFFFF]
static let R2modp:[Chunk] = [0x169000,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let MConst:Chunk = 0x13;
// ED25519 Curve
static let CURVE_Cof_I:Int = 8
static let CURVE_Cof:[Chunk] = [0x8,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = -1
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0x135978A3,0xF5A6E50,0x10762ADD,0x149A82,0x1E898007,0x3CBBBC,0x19CE331D,0x1DC56DFF,0x52036C]
static public let CURVE_Order:[Chunk] = [0x1CF5D3ED,0x9318D2,0x1DE73596,0x1DF3BD45,0x14D,0x0,0x0,0x0,0x100000]
static public let CURVE_Gx:[Chunk] = [0xF25D51A,0xAB16B04,0x969ECB2,0x198EC12A,0xDC5C692,0x1118FEEB,0xFFB0293,0x1A79ADCA,0x216936]
static public let CURVE_Gy:[Chunk] = [0x6666658,0x13333333,0x19999999,0xCCCCCCC,0x6666666,0x13333333,0x19999999,0xCCCCCCC,0x666666]
#endif
#if D64
// Base Bits= 56
// C25519 Curve Modulus
static public let Modulus:[Chunk] = [0xFFFFFFFFFFFFED,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0xFFFFFFFFFFFFFF,0x7FFFFFFF]
static let R2modp:[Chunk] = [0xA4000000000000,0x5,0x0,0x0,0x0]
static let MConst:Chunk = 0x13
// ED25519 Curve
static let CURVE_Cof_I:Int = 8
static let CURVE_Cof:[Chunk] = [0x8,0x0,0x0,0x0,0x0]
static let CURVE_A:Int = -1
static let CURVE_B_I:Int = 0
static let CURVE_B:[Chunk] = [0xEB4DCA135978A3,0xA4D4141D8AB75,0x797779E8980070,0x2B6FFE738CC740,0x52036CEE]
static public let CURVE_Order:[Chunk] = [0x12631A5CF5D3ED,0xF9DEA2F79CD658,0x14DE,0x0,0x10000000]
static public let CURVE_Gx:[Chunk] = [0x562D608F25D51A,0xC7609525A7B2C9,0x31FDD6DC5C692C,0xCD6E53FEC0A4E2,0x216936D3]
static public let CURVE_Gy:[Chunk] = [0x66666666666658,0x66666666666666,0x66666666666666,0x66666666666666,0x66666666]
#endif
}
| apache-2.0 | cb18d5e1a44e669f8fc1968acd3dcb18 | 37.777778 | 135 | 0.775788 | 2.470796 | false | false | false | false |
Tsiems/mobile-sensing-apps | AirDrummer/AirDrummer/gesture.swift | 1 | 1482 | //
// gesture.swift
// AirDrummer
//
// Created by chinkpad on 12/8/16.
// Copyright © 2016 Danh Nguyen. All rights reserved.
//
import Foundation
import UIKit
class Gesture: NSObject, NSCoding{
let id : String
let gesture_name : String
let gif_name : String
var instrument : String
var inUse : Bool
// let gif : UIImage
init(id: String, gesture_name:String,gif_name: String,instrument: String,inUse:Bool=false) {
self.id = id
self.gesture_name = gesture_name
self.gif_name = gif_name
self.instrument = instrument
self.inUse = inUse
//self.gif = UIImage(named: self.gif_name + ".gif")!
// self.gif = UIImage.gifImageWithName(name: self.gif_name)!
}
required convenience init(coder aDecoder: NSCoder) {
let gid = aDecoder.decodeObject(forKey: "gid") as! String
let gesture_name = aDecoder.decodeObject(forKey: "gesture_name") as! String
let gif_name = aDecoder.decodeObject(forKey: "gif_name") as! String
let instrument = aDecoder.decodeObject(forKey: "instrument") as! String
self.init(id: gid, gesture_name:gesture_name, gif_name:gif_name,instrument:instrument)
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "gid")
aCoder.encode(gesture_name, forKey: "gesture_name")
aCoder.encode(gif_name, forKey: "gif_name")
aCoder.encode(instrument, forKey: "instrument")
}
}
| mit | 47562924d2148c022c3683b5f7ea05e0 | 32.659091 | 96 | 0.648211 | 3.768448 | false | false | false | false |
PravinNagargoje/CustomCalendar | Pods/JTAppleCalendar/Sources/UICollectionViewDelegates.swift | 3 | 9730 | //
// UICollectionViewDelegates.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.
//
extension JTAppleCalendarView: UICollectionViewDelegate, UICollectionViewDataSource {
/// Asks your data source object to provide a
/// supplementary view to display in the collection view.
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard
let validDate = monthInfoFromSection(indexPath.section),
let delegate = calendarDelegate else {
developerError(string: "Either date could not be generated or delegate was nil")
assert(false, "Date could not be generated for section. This is a bug. Contact the developer")
return UICollectionReusableView()
}
let headerView = delegate.calendar(self, headerViewForDateRange: validDate.range, at: indexPath)
headerView.transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1
return headerView
}
/// Asks your data source object for the cell that corresponds
/// to the specified item in the collection view.
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let delegate = calendarDelegate else {
print("Your delegate does not conform to JTAppleCalendarViewDelegate")
assert(false)
return UICollectionViewCell()
}
restoreSelectionStateForCellAtIndexPath(indexPath)
let cellState = cellStateFromIndexPath(indexPath)
let configuredCell = delegate.calendar(self, cellForItemAt: cellState.date, cellState: cellState, indexPath: indexPath)
configuredCell.transform.a = semanticContentAttribute == .forceRightToLeft ? -1 : 1
return configuredCell
}
/// Asks your data sourceobject for the number of sections in
/// the collection view. The number of sections in collectionView.
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return monthMap.count
}
/// Asks your data source object for the number of items in the
/// specified section. The number of rows in section.
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if calendarViewLayout.cellCache.isEmpty {return 0}
guard let count = calendarViewLayout.cellCache[section]?.count else {
developerError(string: "cellCacheSection does not exist.")
return 0
}
return count
}
/// Asks the delegate if the specified item should be selected.
/// true if the item should be selected or false if it should not.
public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
if let
delegate = calendarDelegate,
let infoOfDateUserSelected = dateOwnerInfoFromPath(indexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? JTAppleCell
let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateUserSelected)
return delegate.calendar(self, shouldSelectDate: infoOfDateUserSelected.date, cell: cell, cellState: cellState)
}
return false
}
/// Asks the delegate if the specified item should be deselected.
/// true if the item should be deselected or false if it should not.
public func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool {
if
let delegate = calendarDelegate,
let infoOfDateDeSelectedByUser = dateOwnerInfoFromPath(indexPath) {
let cell = collectionView.cellForItem(at: indexPath) as? JTAppleCell
let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateDeSelectedByUser)
return delegate.calendar(self, shouldDeselectDate: infoOfDateDeSelectedByUser.date, cell: cell, cellState: cellState)
}
return false
}
/// Tells the delegate that the item at the specified index
/// path was selected. The collection view calls this method when the
/// user successfully selects an item in the collection view.
/// It does not call this method when you programmatically
/// set the selection.
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard
let delegate = calendarDelegate,
let infoOfDateSelectedByUser = dateOwnerInfoFromPath(indexPath) else {
return
}
// Update model
addCellToSelectedSetIfUnselected(indexPath, date: infoOfDateSelectedByUser.date)
let selectedCell = collectionView.cellForItem(at: indexPath) as? JTAppleCell
// If cell has a counterpart cell, then select it as well
let cellState = cellStateFromIndexPath(indexPath, withDateInfo: infoOfDateSelectedByUser, cell: selectedCell)
// index paths to be reloaded should be index to the left and right of the selected index
var pathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: indexPath)) : []
if let selectedCounterPartIndexPath = selectCounterPartCellIndexPathIfExists(indexPath,
date: infoOfDateSelectedByUser.date,
dateOwner: cellState.dateBelongsTo) {
pathsToReload.insert(selectedCounterPartIndexPath)
let counterPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: selectedCounterPartIndexPath)) : []
pathsToReload.formUnion(counterPathsToReload)
}
delegate.calendar(self, didSelectDate: infoOfDateSelectedByUser.date, cell: selectedCell, cellState: cellState)
if !pathsToReload.isEmpty {
self.batchReloadIndexPaths(Array(pathsToReload))
}
}
/// Tells the delegate that the item at the specified path was deselected.
/// The collection view calls this method when the user successfully
/// deselects an item in the collection view.
/// It does not call this method when you programmatically deselect items.
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
if
let delegate = calendarDelegate,
let dateInfoDeselectedByUser = dateOwnerInfoFromPath(indexPath) {
// Update model
deleteCellFromSelectedSetIfSelected(indexPath)
let selectedCell = collectionView.cellForItem(at: indexPath) as? JTAppleCell
var indexPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: indexPath)) : []
if selectedCell == nil { indexPathsToReload.insert(indexPath) }
// Cell may be nil if user switches month sections
// Although the cell may be nil, we still want to
// return the cellstate
let cellState = cellStateFromIndexPath(indexPath, withDateInfo: dateInfoDeselectedByUser, cell: selectedCell)
let deselectedCell = deselectCounterPartCellIndexPath(indexPath, date: dateInfoDeselectedByUser.date, dateOwner: cellState.dateBelongsTo)
if let unselectedCounterPartIndexPath = deselectedCell {
deleteCellFromSelectedSetIfSelected(unselectedCounterPartIndexPath)
indexPathsToReload.insert(unselectedCounterPartIndexPath)
let counterPathsToReload = isRangeSelectionUsed ? Set(validForwardAndBackwordSelectedIndexes(forIndexPath: unselectedCounterPartIndexPath)) : []
indexPathsToReload.formUnion(counterPathsToReload)
}
delegate.calendar(self, didDeselectDate: dateInfoDeselectedByUser.date, cell: selectedCell, cellState: cellState)
if indexPathsToReload.count > 0 {
self.batchReloadIndexPaths(Array(indexPathsToReload))
}
}
}
public func sizeOfDecorationView(indexPath: IndexPath) -> CGRect {
guard let size = calendarDelegate?.sizeOfDecorationView(indexPath: indexPath) else { return .zero }
return size
}
}
| mit | 40a20b9e16fd1335ad4407258a14c5c5 | 56.573964 | 169 | 0.697945 | 5.585534 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/CoreData/CoreDataMigrations/Change20170228.swift | 1 | 900 | //
// Change20170228.swift
// MEGameTracker
//
// Created by Emily Ivie on 2/28/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
public struct Change20170228: CoreDataMigrationType {
/// Correct some mis-saved game data
public func run() {
// only run if prior bad data may have been saved
guard App.current.lastBuild > 0 else { return }
// notes were note saved to cloudkit properly, so change them so they are stored to cloudkit next time
let notes = Note.getAll().map { (n: Note) -> Note in var n = n; n.markChanged(); return n }
_ = Note.saveAll(items: notes)
// all game data was not dated properly in core date store
// fix games and shepards because they rely on date
let shepards = Shepard.getAll()
_ = Shepard.saveAll(items: shepards)
let games = GameSequence.getAll()
_ = GameSequence.saveAll(items: games)
}
}
| mit | 17f312d744406284371749204ccfcc3c | 30 | 104 | 0.705228 | 3.56746 | false | false | false | false |
vincentSuwenliang/Mechandising | MerchandisingSystem/LanguageManager.swift | 1 | 2353 | //
// LanguageManager.swift
// ccconnected
//
// Created by SuVincent on 4/2/2017.
// Copyright © 2017 hk.com.cloudpillar. All rights reserved.
//
import UIKit
class LanguageManager: NSObject {
static let sharedInstance = LanguageManager() // singleton
var availableLocales: [LanguageCode] = [.ChineseSimplified, .ChineseTraditional, .English]
var lprojBasePath: LanguageCode = .ChineseTraditional
override fileprivate init() {
super.init()
self.lprojBasePath = getSelectedLocale()
}
fileprivate func getSelectedLocale() -> LanguageCode {
let lang = Locale.preferredLanguages
let languageComponents: [String : String] = Locale.components(fromIdentifier: lang[0])
// use the system default language as language but can reset in-app
if let languageCode = languageComponents["kCFLocaleLanguageCodeKey"]{
let scriptCode = languageComponents["kCFLocaleScriptCodeKey"]
var fullLocaleCode = languageCode
if scriptCode != nil {
fullLocaleCode = "\(languageCode)-\(scriptCode!)"
}
print("lprojBasePath fsadfas",fullLocaleCode)
for availableLocale in availableLocales {
if(availableLocale.code == fullLocaleCode){
return availableLocale
}
}
}
return .ChineseTraditional
}
// pubilc function
func getCurrentBundle() -> Bundle {
if let bundle = Bundle.main.path(forResource: lprojBasePath.code, ofType: "lproj"){
return Bundle(path: bundle)!
}else{
fatalError("lproj files not found on project directory. /n Hint:Localize your strings file")
}
}
func setLocale(langCode:String){
UserDefaults.standard.set([langCode], forKey: "AppleLanguages")//replaces Locale.preferredLanguages
self.lprojBasePath = getSelectedLocale()
}
// get country name base on current setting language and country code
func getCountryName(by countryCode: String) -> String? {
let currentlocal = Locale(identifier: lprojBasePath.code)
let countryName = currentlocal.localizedString(forRegionCode: countryCode)
return countryName
}
}
| mit | 1454cce1c5a96c48f92a90e743d1f724 | 30.783784 | 107 | 0.635204 | 5.180617 | false | false | false | false |
nakajijapan/NKJMovieComposer | NKJMovieComposerDemo/Classes/LoadingImageView.swift | 1 | 1808 | //
// LoadingImageView.swift
// NKJMovieComposerDemo
//
// Created by nakajijapan on 2014/06/11.
// Copyright (c) 2014 net.nakajijapan. All rights reserved.
//
import UIKit
class LoadingImageView: UIImageView {
var progressView: UIProgressView!
init(frame: CGRect, useProgress: Bool) {
super.init(frame: frame);
backgroundColor = UIColor.black
if useProgress {
let width = frame.size.width
let height = frame.size.height
progressView = UIProgressView(progressViewStyle: UIProgressView.Style.default)
progressView.frame = CGRect(x: 20, y: height / 2, width: width - 20 * 2, height: 3)
progressView.progressTintColor = UIColor.red
progressView.progress = 0.0
addSubview(progressView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func start() {
DispatchQueue.main.async { [weak self] in
self?.alpha = 0.0
UIView.animate(
withDuration: 0.2,
delay: 0.0,
options: UIView.AnimationOptions.curveEaseIn,
animations: { [weak self] in
self?.alpha = 0.8
},
completion: { [weak self] _ in
self?.alpha = 0.8
})
}
}
func stop() {
DispatchQueue.main.async { [weak self] in
UIView.animate(
withDuration: 0.2,
animations: { [weak self] in
self?.alpha = 0
},
completion: { [weak self] _ in
self?.removeFromSuperview()
})
}
}
}
| mit | 12dd78a96494c1120b92afcdbed0d1a0 | 26.393939 | 95 | 0.513827 | 4.795756 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.