repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
matthewpurcell/firefox-ios
Storage/Bookmarks.swift
1
19023
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import Shared import Deferred // A small structure to encapsulate all the possible data that we can get // from an application sharing a web page or a URL. public struct ShareItem { public let url: String public let title: String? public let favicon: Favicon? public init(url: String, title: String?, favicon: Favicon?) { self.url = url self.title = title self.favicon = favicon } } public protocol ShareToDestination { func shareItem(item: ShareItem) } public protocol SearchableBookmarks { func bookmarksByURL(url: NSURL) -> Deferred<Maybe<Cursor<BookmarkItem>>> } public struct BookmarkMirrorItem { public let guid: GUID public let type: BookmarkNodeType let serverModified: Timestamp let isDeleted: Bool let hasDupe: Bool let parentID: GUID? let parentName: String? // Livemarks. public let feedURI: String? public let siteURI: String? // Separators. let pos: Int? // Folders, livemarks, bookmarks and queries. let title: String? let description: String? // Bookmarks and queries. let bookmarkURI: String? let tags: String? let keyword: String? // Queries. let folderName: String? let queryID: String? // Folders. let children: [GUID]? // The places root is a folder but has no parentName. public static func folder(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, children: [GUID]) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Folder, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: children) } public static func livemark(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String?, description: String?, feedURI: String, siteURI: String) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Livemark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: feedURI, siteURI: siteURI, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil) } public static func separator(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, pos: Int) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Separator, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: pos, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil) } public static func bookmark(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, title: String, description: String?, URI: String, tags: String, keyword: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Bookmark, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: nil, queryID: nil, children: nil) } public static func query(guid: GUID, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String, title: String, description: String?, URI: String, tags: String, keyword: String?, folderName: String?, queryID: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .Query, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: folderName, queryID: queryID, children: nil) } public static func deleted(type: BookmarkNodeType, guid: GUID, modified: Timestamp) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) return BookmarkMirrorItem(guid: id, type: type, serverModified: modified, isDeleted: true, hasDupe: false, parentID: nil, parentName: nil, feedURI: nil, siteURI: nil, pos: nil, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil) } } public protocol BookmarkMirrorStorage { func applyRecords(records: [BookmarkMirrorItem]) -> Success func doneApplyingRecordsAfterDownload() -> Success } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" public static let FakeDesktopFolderGUID = "desktop_____" // Pseudo. Never mentioned in a real record. /** * Sync records are a horrible mess of Places-native GUIDs and Sync-native IDs. * For example: * {"id":"places", * "type":"folder", * "title":"", * "description":null, * "children":["menu________","toolbar_____", * "tags________","unfiled_____", * "jKnyPDrBQSDg","T6XK5oJMU8ih"], * "parentid":"2hYxKgBwvkEH"}" * * We thus normalize on the extended Places IDs (with underscores) for * local storage, and translate to the Sync IDs when creating an outbound * record. * We translate the record's ID and also its parent. Evidence suggests that * we don't need to translate children IDs. * * TODO: We don't create outbound records yet, so that's why there's no * translation in that direction yet! */ public static func translateIncomingRootGUID(guid: GUID) -> GUID { return [ "places": RootGUID, "root": RootGUID, "mobile": MobileFolderGUID, "menu": MenuFolderGUID, "toolbar": ToolbarFolderGUID, "unfiled": UnfiledFolderGUID ][guid] ?? guid } /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This partly matches Places's nsINavBookmarksService, just for sanity. * * It is further extended to support the types that exist in Sync, so we can use * this to store mirrored rows. * * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case Bookmark = 1 case Folder = 2 case Separator = 3 case DynamicContainer = 4 case Livemark = 5 case Query = 6 // No microsummary: those turn into bookmarks. } /** * The immutable base interface for bookmarks and folders. */ public class BookmarkNode { public var id: Int? = nil public var guid: String public var title: String public var favicon: Favicon? = nil init(guid: String, title: String) { self.guid = guid self.title = title } } /** * An immutable item representing a bookmark. * * To modify this, issue changes against the backing store and get an updated model. */ public class BookmarkItem: BookmarkNode { public let url: String! public init(guid: String, title: String, url: String) { self.url = url super.init(guid: guid, title: title) } } /** * A folder is an immutable abstraction over a named * thing that can return its child nodes by index. */ public class BookmarkFolder: BookmarkNode { public var count: Int { return 0 } public subscript(index: Int) -> BookmarkNode? { return nil } public func itemIsEditableAtIndex(index: Int) -> Bool { return false } } /** * A model is a snapshot of the bookmarks store, suitable for backing a table view. * * Navigation through the folder hierarchy produces a sequence of models. * * Changes to the backing store implicitly invalidates a subset of models. * * 'Refresh' means requesting a new model from the store. */ public class BookmarksModel { let modelFactory: BookmarksModelFactory public let current: BookmarkFolder public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) { self.modelFactory = modelFactory self.current = root } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return modelFactory.modelForFolder(folder) } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ public func selectFolder(guid: String) -> Deferred<Maybe<BookmarksModel>> { return modelFactory.modelForFolder(guid) } /** * Produce a new model rooted at the base of the hierarchy. Should never fail. */ public func selectRoot() -> Deferred<Maybe<BookmarksModel>> { return modelFactory.modelForRoot() } /** * Produce a new model rooted at the same place as this model. Can fail if * the folder has been deleted from the backing store. */ public func reloadData() -> Deferred<Maybe<BookmarksModel>> { return modelFactory.modelForFolder(current) } } public protocol BookmarksModelFactory { func modelForFolder(folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(guid: GUID) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> func modelForRoot() -> Deferred<Maybe<BookmarksModel>> // Whenever async construction is necessary, we fall into a pattern of needing // a placeholder that behaves correctly for the period between kickoff and set. var nullModel: BookmarksModel { get } func isBookmarked(url: String) -> Deferred<Maybe<Bool>> func remove(bookmark: BookmarkNode) -> Success func removeByURL(url: String) -> Success func clearBookmarks() -> Success } /* * A folder that contains an array of children. */ public class MemoryBookmarkFolder: BookmarkFolder, SequenceType { let children: [BookmarkNode] public init(guid: GUID, title: String, children: [BookmarkNode]) { self.children = children super.init(guid: guid, title: title) } public struct BookmarkNodeGenerator: GeneratorType { public typealias Element = BookmarkNode let children: [BookmarkNode] var index: Int = 0 init(children: [BookmarkNode]) { self.children = children } public mutating func next() -> BookmarkNode? { return index < children.count ? children[index++] : nil } } override public var favicon: Favicon? { get { if let path = NSBundle.mainBundle().pathForResource("bookmarkFolder", ofType: "png") { let url = NSURL(fileURLWithPath: path) return Favicon(url: url.absoluteString, date: NSDate(), type: IconType.Local) } return nil } set { } } override public var count: Int { return children.count } override public subscript(index: Int) -> BookmarkNode { get { return children[index] } } override public func itemIsEditableAtIndex(index: Int) -> Bool { return true } public func generate() -> BookmarkNodeGenerator { return BookmarkNodeGenerator(children: self.children) } /** * Return a new immutable folder that's just like this one, * but also contains the new items. */ func append(items: [BookmarkNode]) -> MemoryBookmarkFolder { if (items.isEmpty) { return self } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items) } } public class MemoryBookmarksSink: ShareToDestination { var queue: [BookmarkNode] = [] public init() { } public func shareItem(item: ShareItem) { let title = item.title == nil ? "Untitled" : item.title! func exists(e: BookmarkNode) -> Bool { if let bookmark = e as? BookmarkItem { return bookmark.url == item.url; } return false; } // Don't create duplicates. if (!queue.contains(exists)) { queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url)) } } } private extension SuggestedSite { func asBookmark() -> BookmarkNode { let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url) b.favicon = self.icon return b } } public class PrependedBookmarkFolder: BookmarkFolder { private let main: BookmarkFolder private let prepend: BookmarkNode init(main: BookmarkFolder, prepend: BookmarkNode) { self.main = main self.prepend = prepend super.init(guid: main.guid, title: main.guid) } override public var count: Int { return self.main.count + 1 } override public subscript(index: Int) -> BookmarkNode? { if index == 0 { return self.prepend } return self.main[index - 1] } override public func itemIsEditableAtIndex(index: Int) -> Bool { return index > 0 && self.main.itemIsEditableAtIndex(index - 1) } } public class BookmarkFolderWithDefaults: BookmarkFolder { private let folder: BookmarkFolder private let sites: SuggestedSitesCursor init(folder: BookmarkFolder, sites: SuggestedSitesCursor) { self.folder = folder self.sites = sites super.init(guid: folder.guid, title: folder.title) } override public var count: Int { return self.folder.count + self.sites.count } override public subscript(index: Int) -> BookmarkNode? { if index < self.folder.count { return self.folder[index] } if let site = self.sites[index - self.folder.count] { return site.asBookmark() } return nil } override public func itemIsEditableAtIndex(index: Int) -> Bool { return index < self.folder.count } } /** * A trivial offline model factory that represents a simple hierarchy. */ public class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination { let mobile: MemoryBookmarkFolder let root: MemoryBookmarkFolder var unsorted: MemoryBookmarkFolder let sink: MemoryBookmarksSink public init() { let res = [BookmarkItem]() mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res) unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: []) sink = MemoryBookmarksSink() root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted]) } public func modelForFolder(folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(folder.guid, title: folder.title) } public func modelForFolder(guid: GUID) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(guid, title: "") } public func modelForFolder(guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> { var m: BookmarkFolder switch (guid) { case BookmarkRoots.MobileFolderGUID: // Transparently merges in any queued items. m = self.mobile.append(self.sink.queue) break; case BookmarkRoots.RootGUID: m = self.root break; case BookmarkRoots.UnfiledFolderGUID: m = self.unsorted break; default: return deferMaybe(DatabaseError(description: "No such folder \(guid).")) } return deferMaybe(BookmarksModel(modelFactory: self, root: m)) } public func modelForRoot() -> Deferred<Maybe<BookmarksModel>> { return deferMaybe(BookmarksModel(modelFactory: self, root: self.root)) } /** * This class could return the full data immediately. We don't, because real DB-backed code won't. */ public var nullModel: BookmarksModel { let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: []) return BookmarksModel(modelFactory: self, root: f) } public func shareItem(item: ShareItem) { self.sink.shareItem(item) } public func isBookmarked(url: String) -> Deferred<Maybe<Bool>> { return deferMaybe(DatabaseError(description: "Not implemented")) } public func remove(bookmark: BookmarkNode) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } public func removeByURL(url: String) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } public func clearBookmarks() -> Success { return succeed() } }
mpl-2.0
899e808998b9c36ccf284cb667410a70
32.373684
257
0.647795
4.629594
false
false
false
false
xedin/swift
test/type/opaque.swift
1
10834
// RUN: %target-swift-frontend -disable-availability-checking -typecheck -verify -enable-opaque-result-types %s protocol P { func paul() mutating func priscilla() } protocol Q { func quinn() } extension Int: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension String: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } extension Array: P, Q { func paul() {}; mutating func priscilla() {}; func quinn() {} } class C {} class D: C, P, Q { func paul() {}; func priscilla() {}; func quinn() {} } // TODO: Should be valid let property: some P = 1 // TODO expected-error{{cannot convert}} let deflessProperty: some P // TODO e/xpected-error{{butz}} struct GenericProperty<T: P> { var x: T var property: some P { return x } } let (bim, bam): some P = (1, 2) // expected-error{{'some' type can only be declared on a single property declaration}} var computedProperty: some P { get { return 1 } set { _ = newValue + 1 } // TODO expected-error{{}} expected-note{{}} } struct SubscriptTest { subscript(_ x: Int) -> some P { return x } } func bar() -> some P { return 1 } func bas() -> some P & Q { return 1 } func zim() -> some C { return D() } func zang() -> some C & P & Q { return D() } func zung() -> some AnyObject { return D() } func zoop() -> some Any { return D() } func zup() -> some Any & P { return D() } func zip() -> some AnyObject & P { return D() } func zorp() -> some Any & C & P { return D() } func zlop() -> some C & AnyObject & P { return D() } // Don't allow opaque types to propagate by inference into other global decls' // types struct Test { let inferredOpaque = bar() // expected-error{{inferred type}} let inferredOpaqueStructural = Optional(bar()) // expected-error{{inferred type}} let inferredOpaqueStructural2 = (bar(), bas()) // expected-error{{inferred type}} } //let zingle = {() -> some P in 1 } // FIXME ex/pected-error{{'some' types are only implemented}} // Invalid positions typealias Foo = some P // expected-error{{'some' types are only implemented}} func blibble(blobble: some P) {} // expected-error{{'some' types are only implemented}} let blubble: () -> some P = { 1 } // expected-error{{'some' types are only implemented}} func blib() -> P & some Q { return 1 } // expected-error{{'some' should appear at the beginning}} func blab() -> (P, some Q) { return (1, 2) } // expected-error{{'some' types are only implemented}} func blob() -> (some P) -> P { return { $0 } } // expected-error{{'some' types are only implemented}} func blorb<T: some P>(_: T) { } // expected-error{{'some' types are only implemented}} func blub<T>() -> T where T == some P { return 1 } // expected-error{{'some' types are only implemented}} expected-error{{cannot convert}} protocol OP: some P {} // expected-error{{'some' types are only implemented}} func foo() -> some P { let x = (some P).self // expected-error*{{}} return 1 } // Invalid constraints let zug: some Int = 1 // FIXME expected-error{{must specify only}} let zwang: some () = () // FIXME expected-error{{must specify only}} let zwoggle: some (() -> ()) = {} // FIXME expected-error{{must specify only}} // Type-checking of expressions of opaque type func alice() -> some P { return 1 } func bob() -> some P { return 1 } func grace<T: P>(_ x: T) -> some P { return x } func typeIdentity() { do { var a = alice() a = alice() a = bob() // expected-error{{}} a = grace(1) // expected-error{{}} a = grace("two") // expected-error{{}} } do { var af = alice af = alice af = bob // expected-error{{}} af = grace // expected-error{{}} } do { var b = bob() b = alice() // expected-error{{}} b = bob() b = grace(1) // expected-error{{}} b = grace("two") // expected-error{{}} } do { var gi = grace(1) gi = alice() // expected-error{{}} gi = bob() // expected-error{{}} gi = grace(2) gi = grace("three") // expected-error{{}} } do { var gs = grace("one") gs = alice() // expected-error{{}} gs = bob() // expected-error{{}} gs = grace(2) // expected-error{{}} gs = grace("three") } // The opaque type should conform to its constraining protocols do { let gs = grace("one") var ggs = grace(gs) ggs = grace(gs) } // The opaque type should expose the members implied by its protocol // constraints // TODO: associated types do { var a = alice() a.paul() a.priscilla() } } func recursion(x: Int) -> some P { if x == 0 { return 0 } return recursion(x: x - 1) } // FIXME: We need to emit a better diagnostic than the failure to convert Never to opaque. func noReturnStmts() -> some P { fatalError() } // expected-error{{cannot convert return expression of type 'Never' to return type 'some P'}} expected-error{{no return statements}} func mismatchedReturnTypes(_ x: Bool, _ y: Int, _ z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } var mismatchedReturnTypesProperty: some P { // expected-error{{do not have matching underlying types}} if true { return 0 // expected-note{{underlying type 'Int'}} } else { return "" // expected-note{{underlying type 'String'}} } } struct MismatchedReturnTypesSubscript { subscript(x: Bool, y: Int, z: String) -> some P { // expected-error{{do not have matching underlying types}} if x { return y // expected-note{{underlying type 'Int'}} } else { return z // expected-note{{underlying type 'String'}} } } } func jan() -> some P { return [marcia(), marcia(), marcia()] } func marcia() -> some P { return [marcia(), marcia(), marcia()] // expected-error{{defines the opaque type in terms of itself}} } protocol R { associatedtype S: P, Q // expected-note*{{}} func r_out() -> S func r_in(_: S) } extension Int: R { func r_out() -> String { return "" } func r_in(_: String) {} } func candace() -> some R { return 0 } func doug() -> some R { return 0 } func gary<T: R>(_ x: T) -> some R { return x } func sameType<T>(_: T, _: T) {} func associatedTypeIdentity() { let c = candace() let d = doug() var cr = c.r_out() cr = candace().r_out() cr = doug().r_out() // expected-error{{}} var dr = d.r_out() dr = candace().r_out() // expected-error{{}} dr = doug().r_out() c.r_in(cr) c.r_in(c.r_out()) c.r_in(dr) // expected-error{{}} c.r_in(d.r_out()) // expected-error{{}} d.r_in(cr) // expected-error{{}} d.r_in(c.r_out()) // expected-error{{}} d.r_in(dr) d.r_in(d.r_out()) cr.paul() cr.priscilla() cr.quinn() dr.paul() dr.priscilla() dr.quinn() sameType(cr, c.r_out()) sameType(dr, d.r_out()) sameType(cr, dr) // expected-error{{}} sameType(gary(candace()).r_out(), gary(candace()).r_out()) sameType(gary(doug()).r_out(), gary(doug()).r_out()) sameType(gary(doug()).r_out(), gary(candace()).r_out()) // expected-error{{}} } func redeclaration() -> some P { return 0 } // expected-note{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} struct RedeclarationTest { func redeclaration() -> some P { return 0 } // expected-note{{previously declared}} func redeclaration() -> some P { return 0 } // expected-error{{redeclaration}} func redeclaration() -> some Q { return 0 } func redeclaration() -> P { return 0 } var redeclaredProp: some P { return 0 } // expected-note 3{{previously declared}} var redeclaredProp: some P { return 0 } // expected-error{{redeclaration}} var redeclaredProp: some Q { return 0 } // expected-error{{redeclaration}} var redeclaredProp: P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some P { return 0 } // expected-note{{previously declared}} subscript(redeclared _: Int) -> some P { return 0 } // expected-error{{redeclaration}} subscript(redeclared _: Int) -> some Q { return 0 } subscript(redeclared _: Int) -> P { return 0 } } func diagnose_requirement_failures() { struct S { var foo: some P { return S() } // expected-note {{declared here}} // expected-error@-1 {{return type of property 'foo' requires that 'S' conform to 'P'}} subscript(_: Int) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of subscript 'subscript(_:)' requires that 'S' conform to 'P'}} } func bar() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of instance method 'bar()' requires that 'S' conform to 'P'}} } static func baz(x: String) -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of static method 'baz(x:)' requires that 'S' conform to 'P'}} } } func fn() -> some P { // expected-note {{declared here}} return S() // expected-error@-1 {{return type of local function 'fn()' requires that 'S' conform to 'P'}} } } func global_function_with_requirement_failure() -> some P { // expected-note {{declared here}} return 42 as Double // expected-error@-1 {{return type of global function 'global_function_with_requirement_failure()' requires that 'Double' conform to 'P'}} } func recursive_func_is_invalid_opaque() { func rec(x: Int) -> some P { // expected-error@-1 {{function declares an opaque return type, but has no return statements in its body from which to infer an underlying type}} if x == 0 { return rec(x: 0) } return rec(x: x - 1) } } func closure() -> some P { _ = { return "test" } return 42 } protocol HasAssocType { associatedtype Assoc func assoc() -> Assoc } struct GenericWithOpaqueAssoc<T>: HasAssocType { func assoc() -> some Any { return 0 } } struct OtherGeneric<X, Y, Z> { var x: GenericWithOpaqueAssoc<X>.Assoc var y: GenericWithOpaqueAssoc<Y>.Assoc var z: GenericWithOpaqueAssoc<Z>.Assoc } protocol P_51641323 { associatedtype T var foo: Self.T { get } } func rdar_51641323() { struct Foo: P_51641323 { var foo: some P_51641323 { {} } // expected-error@-1 {{return type of property 'foo' requires that '() -> ()' conform to 'P_51641323'}} // expected-note@-2 {{opaque return type declared here}} } }
apache-2.0
401f154c4c1efcf4ce395177626b6a86
27.361257
180
0.620823
3.400502
false
false
false
false
Accountabilibuddy/hustle
Hustle/Hustle/JobSearchController.swift
1
6106
// // JobSearchController.swift // Hustle // // Created by Kyle Hillman on 4/10/17. // Copyright © 2017 Eve Denison. All rights reserved. // import UIKit class JobSearchController: UIViewController, UITextViewDelegate, BEMCheckBoxDelegate { var jobSearch : JobSearch! // @IBOutlet weak var didHighVolumeSearch: UISwitch! // @IBOutlet weak var targetedSearch: UISwitch! // @IBOutlet weak var targetedEvents: UISwitch! // @IBOutlet weak var infoCoffee: UISwitch! // @IBOutlet weak var meetUp: UISwitch! // @IBOutlet weak var visitCompanies: UISwitch! // @IBOutlet weak var followUp: UISwitch! // @IBOutlet weak var commitToGitHub: UISwitch! // @IBOutlet weak var codingWars: UISwitch! // @IBOutlet weak var whiteBoarding: UISwitch! // @IBOutlet weak var interviewQuestions: UISwitch! @IBOutlet weak var textFieldNotes: UITextView! @IBOutlet weak var didHighVolumeSearchBox: BEMCheckBox! @IBOutlet weak var targetedSearch: BEMCheckBox! @IBOutlet weak var targetedEvents: BEMCheckBox! @IBOutlet weak var infoCoffee: BEMCheckBox! @IBOutlet weak var meetUp: BEMCheckBox! @IBOutlet weak var visitCompanies: BEMCheckBox! @IBOutlet weak var followUp: BEMCheckBox! @IBOutlet weak var commitToGitHub: BEMCheckBox! @IBOutlet weak var codingWars: BEMCheckBox! @IBOutlet weak var whiteBoarding: BEMCheckBox! @IBOutlet weak var interviewQuestions: BEMCheckBox! override func viewDidLoad() { super.viewDidLoad() didHighVolumeSearchBox.delegate = self targetedSearch.delegate = self targetedEvents.delegate = self infoCoffee.delegate = self meetUp.delegate = self visitCompanies.delegate = self followUp.delegate = self commitToGitHub.delegate = self codingWars.delegate = self whiteBoarding.delegate = self interviewQuestions.delegate = self textFieldNotes.placeholder = "Place notes here" } func didTap(_ checkBox: BEMCheckBox) { print("User tapped \(checkBox.on)") } @IBAction func saveJobSearch(_ sender: Any) { let didHighVolumeSearch = self.didHighVolumeSearchBox.on let targetedSearch = self.targetedSearch.on let targetedEvents = self.targetedEvents.on let committedToGitHub = self.commitToGitHub.on let codingWars = self.codingWars.on let whiteBoarding = self.whiteBoarding.on let interviewQuestions = self.interviewQuestions.on let infoCoffee = self.infoCoffee.on let meetUps = self.meetUp.on let visitCompanies = self.visitCompanies.on let followUp = self.followUp.on let textFieldNotes = self.textFieldNotes.text ?? "" let currentJobSearch = JobSearch.init(didHighVolumeSearch: didHighVolumeSearch, targetedSearch: targetedSearch, targetedEvents: targetedEvents, committedToGitHub: committedToGitHub, codingWars: codingWars, whiteBoarding: whiteBoarding, interviewQuestions: interviewQuestions, infoCoffee: infoCoffee, meetupEvents: meetUps, visitCompanies: visitCompanies, followUp: followUp, textFieldNotes: textFieldNotes) if let recordSaved = JobSearch.recordFor(jobSearch: currentJobSearch){ CloudKit.shared.save(record: recordSaved, completion: { (success) in print("Saving Record: \(success)") }) } self.navigationController?.popToRootViewController(animated: true) } } /// Credit to Tijme Gommers for placeholder text extension UITextView: UITextViewDelegate { /// Resize the placeholder when the UITextView bounds change override open var bounds: CGRect { didSet { self.resizePlaceholder() } } /// The UITextView placeholder text public var placeholder: String? { get { var placeholderText: String? if let placeholderLabel = self.viewWithTag(100) as? UILabel { placeholderText = placeholderLabel.text } return placeholderText } set { if let placeholderLabel = self.viewWithTag(100) as! UILabel? { placeholderLabel.text = newValue placeholderLabel.sizeToFit() } else { self.addPlaceholder(newValue!) } } } /// When the UITextView did change, show or hide the label based on if the UITextView is empty or not /// /// - Parameter textView: The UITextView that got updated public func textViewDidChange(_ textView: UITextView) { if let placeholderLabel = self.viewWithTag(100) as? UILabel { placeholderLabel.isHidden = self.text.characters.count > 0 } } /// Resize the placeholder UILabel to make sure it's in the same position as the UITextView text private func resizePlaceholder() { if let placeholderLabel = self.viewWithTag(100) as! UILabel? { let labelX = self.textContainer.lineFragmentPadding let labelY = self.textContainerInset.top - 2 let labelWidth = self.frame.width - (labelX * 2) let labelHeight = placeholderLabel.frame.height placeholderLabel.frame = CGRect(x: labelX, y: labelY, width: labelWidth, height: labelHeight) } } /// Adds a placeholder UILabel to this UITextView private func addPlaceholder(_ placeholderText: String) { let placeholderLabel = UILabel() placeholderLabel.text = placeholderText placeholderLabel.sizeToFit() placeholderLabel.font = self.font placeholderLabel.textColor = UIColor.lightGray placeholderLabel.tag = 100 placeholderLabel.isHidden = self.text.characters.count > 0 self.addSubview(placeholderLabel) self.resizePlaceholder() self.delegate = self } }
mit
e7a75b958a65ef9e78b26e6ca33dc6a4
34.911765
414
0.655037
4.927361
false
false
false
false
segmentio/analytics-swift
Examples/apps/SegmentExtensionsExample/Supporting Files/KeychainItem.swift
1
5616
// // KeychainItem.swift // SegmentExtensionsExample // // Created by Alan Charles on 8/10/21. // import Foundation struct KeychainItem { // MARK: Types enum KeychainError: Error { case noPassword case unexpectedPasswordData case unexpectedItemData case unhandledError } // MARK: Properties let service: String private(set) var account: String let accessGroup: String? // MARK: Intialization init(service: String, account: String, accessGroup: String? = nil) { self.service = service self.account = account self.accessGroup = accessGroup } // MARK: Keychain access func readItem() throws -> String { /* Build a query to find the item that matches the service, account and access group. */ var query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) query[kSecMatchLimit as String] = kSecMatchLimitOne query[kSecReturnAttributes as String] = kCFBooleanTrue query[kSecReturnData as String] = kCFBooleanTrue // Try to fetch the existing keychain item that matches the query. var queryResult: AnyObject? let status = withUnsafeMutablePointer(to: &queryResult) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) } // Check the return status and throw an error if appropriate. guard status != errSecItemNotFound else { throw KeychainError.noPassword } guard status == noErr else { throw KeychainError.unhandledError } // Parse the password string from the query result. guard let existingItem = queryResult as? [String: AnyObject], let passwordData = existingItem[kSecValueData as String] as? Data, let password = String(data: passwordData, encoding: String.Encoding.utf8) else { throw KeychainError.unexpectedPasswordData } return password } func saveItem(_ password: String) throws { // Encode the password into an Data object. let encodedPassword = password.data(using: String.Encoding.utf8)! do { // Check for an existing item in the keychain. try _ = readItem() // Update the existing item with the new password. var attributesToUpdate = [String: AnyObject]() attributesToUpdate[kSecValueData as String] = encodedPassword as AnyObject? let query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) let status = SecItemUpdate(query as CFDictionary, attributesToUpdate as CFDictionary) // Throw an error if an unexpected status was returned. guard status == noErr else { throw KeychainError.unhandledError } } catch KeychainError.noPassword { /* No password was found in the keychain. Create a dictionary to save as a new keychain item. */ var newItem = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) newItem[kSecValueData as String] = encodedPassword as AnyObject? // Add a the new item to the keychain. let status = SecItemAdd(newItem as CFDictionary, nil) // Throw an error if an unexpected status was returned. guard status == noErr else { throw KeychainError.unhandledError } } } func deleteItem() throws { // Delete the existing item from the keychain. let query = KeychainItem.keychainQuery(withService: service, account: account, accessGroup: accessGroup) let status = SecItemDelete(query as CFDictionary) // Throw an error if an unexpected status was returned. guard status == noErr || status == errSecItemNotFound else { throw KeychainError.unhandledError } } // MARK: Convenience private static func keychainQuery(withService service: String, account: String? = nil, accessGroup: String? = nil) -> [String: AnyObject] { var query = [String: AnyObject]() query[kSecClass as String] = kSecClassGenericPassword query[kSecAttrService as String] = service as AnyObject? if let account = account { query[kSecAttrAccount as String] = account as AnyObject? } if let accessGroup = accessGroup { query[kSecAttrAccessGroup as String] = accessGroup as AnyObject? } return query } /* For the purpose of this demo app, the user identifier will be stored in the device keychain. You should store the user identifier in your account management system. */ static var currentUserIdentifier: String { do { let storedIdentifier = try KeychainItem(service: "co.alancharles.SegmentExtensionsExample", account: "userIdentifier").readItem() return storedIdentifier } catch { return "" } } static func deleteUserIdentifierFromKeychain() { do { try KeychainItem(service: "co.alancharles.SegmentExtensionsExample", account: "userIdentifier").deleteItem() } catch { analytics?.log(message: "Unable to delete userIdentifier from keychain", kind: .error) } } }
mit
e3151017f06936ddfbaced5c196bdd5f
36.691275
143
0.628205
5.538462
false
false
false
false
vooooo/CP_Yelp
Yelp/FiltersViewController.swift
1
23430
// // FiltersViewController.swift // Yelp // // Created by vu on 9/23/15. // Copyright © 2015 Timothy Lee. All rights reserved. // import UIKit @objc protocol FiltersViewControllerDelegate { optional func filtersViewController(filtersViewController: FiltersViewController, didUpdateFilters filters: [String:AnyObject]) } class FiltersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SwitchCellDelegate, RadioCellDelegate { @IBOutlet weak var tableView: UITableView! var yelpFilters: Dictionary<String,[[String:String]]>! var yelpFiltersTitles: [String]! var categorySwitchStates = [Int:Bool]() var distanceSwitchStates = [Int:Bool]() var sortSwitchStates = [Int:Bool]() var dealsFilter = Bool() var categoriesCollapse = true weak var delegate: FiltersViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self let filters = [ "Deals" : yelpDeals(), "Distance" : yelpDistance(), "Sort By" : yelpSortyBy(), "Categories" : yelpCategories() ] yelpFilters = filters let filtersKeys = ["Deals","Distance","Sort By","Categories"] yelpFiltersTitles = filtersKeys self.navigationController!.navigationBar.barTintColor = UIColor(red: 0xaf/255, green: 0x06/255, blue: 0x06/255, alpha: 1.0) self.navigationController!.navigationBar.translucent = false; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onCancelButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func onSearchButton(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) let categories = yelpCategoriesFull() let distance = yelpDistance() var filters = [String:AnyObject]() // CATEGORIES var selectedCategories = [String]() for (row,isSelected) in categorySwitchStates { if isSelected { selectedCategories.append(categories[row]["code"]!) } } if selectedCategories.count > 0 { filters["categories"] = selectedCategories } // DEALS if (dealsFilter) { filters["deals"] = true } else { filters["deals"] = false } // DISTANCE var distanceFilter:Int? = 10000 for (row,isSelected) in distanceSwitchStates { if isSelected { let radius = distance[row]["code"] distanceFilter = Int(radius!) } } filters["distance"] = distanceFilter // SORT BY var sortFilter = Int() for (row,isSelected) in sortSwitchStates { if isSelected { sortFilter = row } } filters["sortby"] = sortFilter delegate?.filtersViewController?(self, didUpdateFilters: filters) } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return yelpFiltersTitles.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let filterTitle = yelpFiltersTitles[section] return (yelpFilters[filterTitle]?.count)! } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return yelpFiltersTitles[section] } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("SwitchCell", forIndexPath: indexPath) as! SwitchCell let filterTitle = yelpFiltersTitles[indexPath.section] var filtername = String() if let filter = yelpFilters?[filterTitle]?[indexPath.row] { filtername = filter["name"]! cell.switchLabel.text = filtername //If Categories and Showall process cell differently swiching categories list if (indexPath.section == 3) { if filtername == "Show All" { cell.onSwitch.hidden = true let singleTap = UITapGestureRecognizer(target: self, action: Selector("showAllCategories")) singleTap.numberOfTapsRequired = 1 cell.switchLabel.userInteractionEnabled = true cell.switchLabel.addGestureRecognizer(singleTap) cell.switchLabel.textColor = UIColor.grayColor() } else { cell.onSwitch.hidden = false cell.switchLabel.textColor = UIColor.blackColor() } } } cell.delegate = self if (indexPath.section == 0) { cell.onSwitch.on = dealsFilter ?? false } else if (indexPath.section == 1) { cell.onSwitch.on = distanceSwitchStates[indexPath.row] ?? false } else if (indexPath.section == 2) { cell.onSwitch.on = sortSwitchStates[indexPath.row] ?? false } else if (indexPath.section == 3) { cell.onSwitch.on = categorySwitchStates[indexPath.row] ?? false } return cell } func showAllCategories() { print("in show all") self.yelpFilters["Categories"] = yelpCategoriesFull() tableView.reloadData() } func switchCell(switchCell: SwitchCell, didChangeValue value: Bool) { let indexPath = tableView.indexPathForCell(switchCell)! if (indexPath.section == 0) { dealsFilter = value } else if (indexPath.section == 1) { distanceSwitchStates = [Int:Bool]() distanceSwitchStates[indexPath.row] = value tableView.reloadData() } else if (indexPath.section == 2) { sortSwitchStates = [Int:Bool]() sortSwitchStates[indexPath.row] = value tableView.reloadData() } else if (indexPath.section == 3) { categorySwitchStates[indexPath.row] = value } } func yelpDeals() -> [[String:String]] { return [["name": "Offering Deals", "code": "true"]] } func yelpDistance() -> [[String:String]] { return [["name": "Auto", "code": "0"], ["name": "0.3 mi", "code": "482"], ["name": "1 mi", "code": "1609"], ["name": "5 mi", "code": "8046"], ["name": "20 mi", "code": "32186"]] } func yelpSortyBy() -> [[String:String]] { return [["name": "Best Match", "code": "0"], ["name": "Distance", "code": "1"], ["name": "Ratings", "code": "2"]] } func yelpCategories() -> [[String:String]] { return [["name": "Afghan", "code": "afghani"], ["name": "African", "code": "african"], ["name": "Senegalese", "code": "senegalese"], ["name": "South African", "code": "southafrican"], ["name": "American (New)", "code": "newamerican"], ["name": "Show All", "code": "showall"]] } func yelpCategoriesFull() -> [[String:String]] { return [["name": "Afghan", "code": "afghani"], ["name": "African", "code": "african"], ["name": "Senegalese", "code": "senegalese"], ["name": "South African", "code": "southafrican"], ["name": "American (New)", "code": "newamerican"], ["name": "American (Traditional)", "code": "tradamerican"], ["name": "Andalusian", "code": "andalusian"], ["name": "Arabian", "code": "arabian"], ["name": "Argentine", "code": "argentine"], ["name": "Armenian", "code": "armenian"], ["name": "Asian Fusion", "code": "asianfusion"], ["name": "Australian", "code": "australian"], ["name": "Austrian", "code": "austrian"], ["name": "Baguettes", "code": "baguettes"], ["name": "Bangladeshi", "code": "bangladeshi"], ["name": "Barbeque", "code": "bbq"], ["name": "Basque", "code": "basque"], ["name": "Bavarian", "code": "bavarian"], ["name": "Beer Garden", "code": "beergarden"], ["name": "Beer Hall", "code": "beerhall"], ["name": "Beisl", "code": "beisl"], ["name": "Belgian", "code": "belgian"], ["name": "Flemish", "code": "flemish"], ["name": "Bistros", "code": "bistros"], ["name": "Black Sea", "code": "blacksea"], ["name": "Brasseries", "code": "brasseries"], ["name": "Brazilian", "code": "brazilian"], ["name": "Brazilian Empanadas", "code": "brazilianempanadas"], ["name": "Central Brazilian", "code": "centralbrazilian"], ["name": "Northeastern Brazilian", "code": "northeasternbrazilian"], ["name": "Northern Brazilian", "code": "northernbrazilian"], ["name": "Rodizios", "code": "rodizios"], ["name": "Breakfast & Brunch", "code": "breakfast_brunch"], ["name": "British", "code": "british"], ["name": "Buffets", "code": "buffets"], ["name": "Bulgarian", "code": "bulgarian"], ["name": "Burgers", "code": "burgers"], ["name": "Burmese", "code": "burmese"], ["name": "Cafes", "code": "cafes"], ["name": "Cafeteria", "code": "cafeteria"], ["name": "Cajun/Creole", "code": "cajun"], ["name": "Cambodian", "code": "cambodian"], ["name": "Canadian (New)", "code": "newcanadian"], ["name": "Canteen", "code": "canteen"], ["name": "Caribbean", "code": "caribbean"], ["name": "Dominican", "code": "dominican"], ["name": "Haitian", "code": "haitian"], ["name": "Puerto Rican", "code": "puertorican"], ["name": "Trinidadian", "code": "trinidadian"], ["name": "Catalan", "code": "catalan"], ["name": "Cheesesteaks", "code": "cheesesteaks"], ["name": "Chicken Shop", "code": "chickenshop"], ["name": "Chicken Wings", "code": "chicken_wings"], ["name": "Chilean", "code": "chilean"], ["name": "Chinese", "code": "chinese"], ["name": "Cantonese", "code": "cantonese"], ["name": "Congee", "code": "congee"], ["name": "Dim Sum", "code": "dimsum"], ["name": "Fuzhou", "code": "fuzhou"], ["name": "Hakka", "code": "hakka"], ["name": "Henghwa", "code": "henghwa"], ["name": "Hokkien", "code": "hokkien"], ["name": "Hunan", "code": "hunan"], ["name": "Pekinese", "code": "pekinese"], ["name": "Shanghainese", "code": "shanghainese"], ["name": "Szechuan", "code": "szechuan"], ["name": "Teochew", "code": "teochew"], ["name": "Comfort Food", "code": "comfortfood"], ["name": "Corsican", "code": "corsican"], ["name": "Creperies", "code": "creperies"], ["name": "Cuban", "code": "cuban"], ["name": "Curry Sausage", "code": "currysausage"], ["name": "Cypriot", "code": "cypriot"], ["name": "Czech", "code": "czech"], ["name": "Czech/Slovakian", "code": "czechslovakian"], ["name": "Danish", "code": "danish"], ["name": "Delis", "code": "delis"], ["name": "Diners", "code": "diners"], ["name": "Dumplings", "code": "dumplings"], ["name": "Eastern European", "code": "eastern_european"], ["name": "Ethiopian", "code": "ethiopian"], ["name": "Fast Food", "code": "hotdogs"], ["name": "Filipino", "code": "filipino"], ["name": "Fischbroetchen", "code": "fischbroetchen"], ["name": "Fish & Chips", "code": "fishnchips"], ["name": "Fondue", "code": "fondue"], ["name": "Food Court", "code": "food_court"], ["name": "Food Stands", "code": "foodstands"], ["name": "French", "code": "french"], ["name": "Alsatian", "code": "alsatian"], ["name": "Auvergnat", "code": "auvergnat"], ["name": "Berrichon", "code": "berrichon"], ["name": "Bourguignon", "code": "bourguignon"], ["name": "Nicoise", "code": "nicois"], ["name": "Provencal", "code": "provencal"], ["name": "French Southwest", "code": "sud_ouest"], ["name": "Galician", "code": "galician"], ["name": "Gastropubs", "code": "gastropubs"], ["name": "Georgian", "code": "georgian"], ["name": "German", "code": "german"], ["name": "Baden", "code": "baden"], ["name": "Eastern German", "code": "easterngerman"], ["name": "Hessian", "code": "hessian"], ["name": "Northern German", "code": "northerngerman"], ["name": "Palatine", "code": "palatine"], ["name": "Rhinelandian", "code": "rhinelandian"], ["name": "Giblets", "code": "giblets"], ["name": "Gluten-Free", "code": "gluten_free"], ["name": "Greek", "code": "greek"], ["name": "Halal", "code": "halal"], ["name": "Hawaiian", "code": "hawaiian"], ["name": "Heuriger", "code": "heuriger"], ["name": "Himalayan/Nepalese", "code": "himalayan"], ["name": "Hong Kong Style Cafe", "code": "hkcafe"], ["name": "Hot Dogs", "code": "hotdog"], ["name": "Hot Pot", "code": "hotpot"], ["name": "Hungarian", "code": "hungarian"], ["name": "Iberian", "code": "iberian"], ["name": "Indian", "code": "indpak"], ["name": "Indonesian", "code": "indonesian"], ["name": "International", "code": "international"], ["name": "Irish", "code": "irish"], ["name": "Island Pub", "code": "island_pub"], ["name": "Israeli", "code": "israeli"], ["name": "Italian", "code": "italian"], ["name": "Abruzzese", "code": "abruzzese"], ["name": "Altoatesine", "code": "altoatesine"], ["name": "Apulian", "code": "apulian"], ["name": "Calabrian", "code": "calabrian"], ["name": "Cucina campana", "code": "cucinacampana"], ["name": "Emilian", "code": "emilian"], ["name": "Friulan", "code": "friulan"], ["name": "Ligurian", "code": "ligurian"], ["name": "Lumbard", "code": "lumbard"], ["name": "Napoletana", "code": "napoletana"], ["name": "Piemonte", "code": "piemonte"], ["name": "Roman", "code": "roman"], ["name": "Sardinian", "code": "sardinian"], ["name": "Sicilian", "code": "sicilian"], ["name": "Tuscan", "code": "tuscan"], ["name": "Venetian", "code": "venetian"], ["name": "Japanese", "code": "japanese"], ["name": "Blowfish", "code": "blowfish"], ["name": "Conveyor Belt Sushi", "code": "conveyorsushi"], ["name": "Donburi", "code": "donburi"], ["name": "Gyudon", "code": "gyudon"], ["name": "Oyakodon", "code": "oyakodon"], ["name": "Hand Rolls", "code": "handrolls"], ["name": "Horumon", "code": "horumon"], ["name": "Izakaya", "code": "izakaya"], ["name": "Japanese Curry", "code": "japacurry"], ["name": "Kaiseki", "code": "kaiseki"], ["name": "Kushikatsu", "code": "kushikatsu"], ["name": "Oden", "code": "oden"], ["name": "Okinawan", "code": "okinawan"], ["name": "Okonomiyaki", "code": "okonomiyaki"], ["name": "Onigiri", "code": "onigiri"], ["name": "Ramen", "code": "ramen"], ["name": "Robatayaki", "code": "robatayaki"], ["name": "Soba", "code": "soba"], ["name": "Sukiyaki", "code": "sukiyaki"], ["name": "Takoyaki", "code": "takoyaki"], ["name": "Tempura", "code": "tempura"], ["name": "Teppanyaki", "code": "teppanyaki"], ["name": "Tonkatsu", "code": "tonkatsu"], ["name": "Udon", "code": "udon"], ["name": "Unagi", "code": "unagi"], ["name": "Western Style Japanese Food", "code": "westernjapanese"], ["name": "Yakiniku", "code": "yakiniku"], ["name": "Yakitori", "code": "yakitori"], ["name": "Jewish", "code": "jewish"], ["name": "Kebab", "code": "kebab"], ["name": "Kopitiam", "code": "kopitiam"], ["name": "Korean", "code": "korean"], ["name": "Kosher", "code": "kosher"], ["name": "Kurdish", "code": "kurdish"], ["name": "Laos", "code": "laos"], ["name": "Laotian", "code": "laotian"], ["name": "Latin American", "code": "latin"], ["name": "Colombian", "code": "colombian"], ["name": "Salvadoran", "code": "salvadoran"], ["name": "Venezuelan", "code": "venezuelan"], ["name": "Live/Raw Food", "code": "raw_food"], ["name": "Lyonnais", "code": "lyonnais"], ["name": "Malaysian", "code": "malaysian"], ["name": "Mamak", "code": "mamak"], ["name": "Nyonya", "code": "nyonya"], ["name": "Meatballs", "code": "meatballs"], ["name": "Mediterranean", "code": "mediterranean"], ["name": "Falafel", "code": "falafel"], ["name": "Mexican", "code": "mexican"], ["name": "Eastern Mexican", "code": "easternmexican"], ["name": "Jaliscan", "code": "jaliscan"], ["name": "Northern Mexican", "code": "northernmexican"], ["name": "Oaxacan", "code": "oaxacan"], ["name": "Pueblan", "code": "pueblan"], ["name": "Tacos", "code": "tacos"], ["name": "Tamales", "code": "tamales"], ["name": "Yucatan", "code": "yucatan"], ["name": "Middle Eastern", "code": "mideastern"], ["name": "Egyptian", "code": "egyptian"], ["name": "Lebanese", "code": "lebanese"], ["name": "Milk Bars", "code": "milkbars"], ["name": "Modern Australian", "code": "modern_australian"], ["name": "Modern European", "code": "modern_european"], ["name": "Mongolian", "code": "mongolian"], ["name": "Moroccan", "code": "moroccan"], ["name": "New Zealand", "code": "newzealand"], ["name": "Night Food", "code": "nightfood"], ["name": "Norcinerie", "code": "norcinerie"], ["name": "Open Sandwiches", "code": "opensandwiches"], ["name": "Oriental", "code": "oriental"], ["name": "PF/Comercial", "code": "pfcomercial"], ["name": "Pakistani", "code": "pakistani"], ["name": "Parent Cafes", "code": "eltern_cafes"], ["name": "Parma", "code": "parma"], ["name": "Persian/Iranian", "code": "persian"], ["name": "Peruvian", "code": "peruvian"], ["name": "Pita", "code": "pita"], ["name": "Pizza", "code": "pizza"], ["name": "Polish", "code": "polish"], ["name": "Pierogis", "code": "pierogis"], ["name": "Portuguese", "code": "portuguese"], ["name": "Alentejo", "code": "alentejo"], ["name": "Algarve", "code": "algarve"], ["name": "Azores", "code": "azores"], ["name": "Beira", "code": "beira"], ["name": "Fado Houses", "code": "fado_houses"], ["name": "Madeira", "code": "madeira"], ["name": "Minho", "code": "minho"], ["name": "Ribatejo", "code": "ribatejo"], ["name": "Tras-os-Montes", "code": "tras_os_montes"], ["name": "Potatoes", "code": "potatoes"], ["name": "Poutineries", "code": "poutineries"], ["name": "Pub Food", "code": "pubfood"], ["name": "Rice", "code": "riceshop"], ["name": "Romanian", "code": "romanian"], ["name": "Rotisserie Chicken", "code": "rotisserie_chicken"], ["name": "Rumanian", "code": "rumanian"], ["name": "Russian", "code": "russian"], ["name": "Salad", "code": "salad"], ["name": "Sandwiches", "code": "sandwiches"], ["name": "Scandinavian", "code": "scandinavian"], ["name": "Scottish", "code": "scottish"], ["name": "Seafood", "code": "seafood"], ["name": "Serbo Croatian", "code": "serbocroatian"], ["name": "Signature Cuisine", "code": "signature_cuisine"], ["name": "Singaporean", "code": "singaporean"], ["name": "Slovakian", "code": "slovakian"], ["name": "Soul Food", "code": "soulfood"], ["name": "Soup", "code": "soup"], ["name": "Southern", "code": "southern"], ["name": "Spanish", "code": "spanish"], ["name": "Arroceria / Paella", "code": "arroceria_paella"], ["name": "Sri Lankan", "code": "srilankan"], ["name": "Steakhouses", "code": "steak"], ["name": "Supper Clubs", "code": "supperclubs"], ["name": "Sushi Bars", "code": "sushi"], ["name": "Swabian", "code": "swabian"], ["name": "Swedish", "code": "swedish"], ["name": "Swiss Food", "code": "swissfood"], ["name": "Syrian", "code": "syrian"], ["name": "Tabernas", "code": "tabernas"], ["name": "Taiwanese", "code": "taiwanese"], ["name": "Tapas Bars", "code": "tapas"], ["name": "Tapas/Small Plates", "code": "tapasmallplates"], ["name": "Tex-Mex", "code": "tex-mex"], ["name": "Thai", "code": "thai"], ["name": "Traditional Norwegian", "code": "norwegian"], ["name": "Traditional Swedish", "code": "traditional_swedish"], ["name": "Trattorie", "code": "trattorie"], ["name": "Turkish", "code": "turkish"], ["name": "Chee Kufta", "code": "cheekufta"], ["name": "Gozleme", "code": "gozleme"], ["name": "Homemade Food", "code": "homemadefood"], ["name": "Lahmacun", "code": "lahmacun"], ["name": "Turkish Ravioli", "code": "turkishravioli"], ["name": "Ukrainian", "code": "ukrainian"], ["name": "Uzbek", "code": "uzbek"], ["name": "Vegan", "code": "vegan"], ["name": "Vegetarian", "code": "vegetarian"], ["name": "Venison", "code": "venison"], ["name": "Vietnamese", "code": "vietnamese"], ["name": "Wok", "code": "wok"], ["name": "Wraps", "code": "wraps"], ["name": "Yugoslav", "code": "yugoslav"]] } }
mit
d99684acf89054fe441689506c991812
44.759766
131
0.493491
3.673985
false
false
false
false
Journey321/xiaorizi
xiaorizi/Classes/Play/Mine/view/MyCustomBtn.swift
2
1793
// // MyCustomBtn.swift // xiaorizi // // Created by zhike on 16/9/1. // Copyright © 2016年 zhike. All rights reserved. // import Foundation class MyCustomBtn: UIButton { var iconImg = UIImageView() var nameLable = UILabel() override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.whiteColor() // icon iconImg = UIImageView.init() self.addSubview(iconImg) iconImg.backgroundColor = UIColor.clearColor() // name nameLable = UILabel.init() self.addSubview(nameLable) nameLable.text = "测试" nameLable.textColor = UIColor.init(rgbByFFFFFF: 0x4d4d4d) nameLable.font = UIFont.systemFontOfSize(16) nameLable.textAlignment = NSTextAlignment.Center } override func layoutSubviews() { super.layoutSubviews() // icon frame let iconWidth = (kScreenWidth == 320 ? 25 : kScreenWidth * (30/667) ) let iconSize = CGSizeMake(iconWidth, iconWidth) let topInterval = (self.height() - iconWidth - 30)/2 iconImg.autoSetDimensionsToSize(iconSize) iconImg.autoPinEdgeToSuperviewEdge(.Top, withInset: topInterval) iconImg.autoPinEdgeToSuperviewEdge(.Left, withInset: ((kScreenWidth - 1)/2 - iconWidth)/2.0) // name frame let nameSize = CGSizeMake((kScreenWidth - 1)/2, 20) nameLable.autoSetDimensionsToSize(nameSize) nameLable.autoPinEdgeToSuperviewEdge(.Left, withInset: 0) nameLable.autoPinEdge(.Top, toEdge:.Bottom, ofView: iconImg, withOffset: 10) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
a765a783f3d7d4a3e8f591de4e928abf
29.288136
100
0.62766
4.498741
false
false
false
false
vbudhram/firefox-ios
Client/Frontend/Browser/BrowserTrayAnimators.swift
2
14899
/* 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 TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: .to) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: .from) as? TabTrayController { transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension TrayToBrowserAnimator { func transitionFromTray(_ tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let expandFromIndex = displayedTabs.index(of: selectedTab) else { return } bvc.view.frame = transitionContext.finalFrame(for: bvc) // Hide browser components bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.isHidden = true bvc.webViewContainerBackdrop.isHidden = true bvc.statusBarOverlay.isHidden = false if let url = selectedTab.url, !url.isReaderModeURL { bvc.hideReaderModeBar(animated: false) } // Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: false)! tabTray.collectionView.alpha = 0 tabCollectionViewSnapshot.frame = tabTray.collectionView.frame container.insertSubview(tabCollectionViewSnapshot, at: 0) // Create a fake cell to use for the upscaling animation let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: startingFrame) cell.backgroundHolder.layer.cornerRadius = 0 container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot) container.insertSubview(cell, aboveSubview: bvc.view) // Flush any pending layout/animation code in preperation of the animation call container.layoutIfNeeded() let finalFrame = calculateExpandedCellFrameFromBVC(bvc) bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0 bvc.urlBar.isTransitioning = true // Re-calculate the starting transforms for header/footer views in case we switch orientation resetTransformsForViews([bvc.header, bvc.readerModeBar, bvc.footer]) transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { // Scale up the cell and reset the transforms for the header/footers cell.frame = finalFrame container.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.height) bvc.tabTrayDidDismiss(tabTray) UIApplication.shared.windows.first?.backgroundColor = UIConstants.AppBackgroundColor tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight) tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) tabCollectionViewSnapshot.alpha = 0 }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() bvc.footer.alpha = 1 bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.webViewContainerBackdrop.isHidden = false bvc.homePanelController?.view.isHidden = false bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning { func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let bvc = transitionContext.viewController(forKey: .from) as? BrowserViewController, let tabTray = transitionContext.viewController(forKey: .to) as? TabTrayController { transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext) } } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } } private extension BrowserToTrayAnimator { func transitionFromBrowser(_ bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView guard let selectedTab = bvc.tabManager.selectedTab else { return } let tabManager = bvc.tabManager let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs guard let scrollToIndex = displayedTabs.index(of: selectedTab) else { return } tabTray.view.frame = transitionContext.finalFrame(for: tabTray) // Insert tab tray below the browser and force a layout so the collection view can get it's frame right container.insertSubview(tabTray.view, belowSubview: bvc.view) // Force subview layout on the collection view so we can calculate the correct end frame for the animation tabTray.view.layoutSubviews() tabTray.collectionView.scrollToItem(at: IndexPath(item: scrollToIndex, section: 0), at: .centeredVertically, animated: false) // Build a tab cell that we will use to animate the scaling of the browser to the tab let expandedFrame = calculateExpandedCellFrameFromBVC(bvc) let cell = createTransitionCellFromTab(bvc.tabManager.selectedTab, withFrame: expandedFrame) cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius // Take a snapshot of the collection view to perform the scaling/alpha effect let tabCollectionViewSnapshot = tabTray.collectionView.snapshotView(afterScreenUpdates: true)! tabCollectionViewSnapshot.frame = tabTray.collectionView.frame tabCollectionViewSnapshot.transform = CGAffineTransform(scaleX: 0.9, y: 0.9) tabCollectionViewSnapshot.alpha = 0 tabTray.view.insertSubview(tabCollectionViewSnapshot, belowSubview: tabTray.toolbar) if let toast = bvc.clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } container.addSubview(cell) cell.layoutIfNeeded() cell.title.transform = CGAffineTransform(translationX: 0, y: -cell.title.frame.size.height) // Hide views we don't want to show during the animation in the BVC bvc.homePanelController?.view.isHidden = true bvc.statusBarOverlay.isHidden = true bvc.toggleSnackBarVisibility(show: false) toggleWebViewVisibility(false, usingTabManager: bvc.tabManager) bvc.urlBar.isTransitioning = true // Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update, // the screenshot ends up being blank unless we set the collection view hidden after the screen update happens. // To work around this, we dispatch the setting of collection view to hidden after the screen update is completed. DispatchQueue.main.async { tabTray.collectionView.isHidden = true let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: scrollToIndex) tabTray.toolbar.transform = CGAffineTransform(translationX: 0, y: UIConstants.BottomToolbarHeight) UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0, options: [], animations: { cell.frame = finalFrame cell.title.transform = .identity cell.layoutIfNeeded() UIApplication.shared.windows.first?.backgroundColor = TabTrayControllerUX.BackgroundColor tabTray.navigationController?.setNeedsStatusBarAppearanceUpdate() transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container) bvc.urlBar.updateAlphaForSubviews(0) bvc.footer.alpha = 0 tabCollectionViewSnapshot.alpha = 1 tabTray.toolbar.transform = .identity resetTransformsForViews([tabCollectionViewSnapshot]) }, completion: { finished in // Remove any of the views we used for the animation cell.removeFromSuperview() tabCollectionViewSnapshot.removeFromSuperview() tabTray.collectionView.isHidden = false bvc.toggleSnackBarVisibility(show: true) toggleWebViewVisibility(true, usingTabManager: bvc.tabManager) bvc.homePanelController?.view.isHidden = false bvc.urlBar.isTransitioning = false transitionContext.completeTransition(true) }) } } } private func transformHeaderFooterForBVC(_ bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) { let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container) let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container) bvc.footer.transform = footerForTransform bvc.header.transform = headerForTransform bvc.readerModeBar?.transform = headerForTransform } private func footerTransform( _ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.maxY - (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform: CGAffineTransform = .identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } private func headerTransform(_ frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform { let frame = container.convert(frame, to: container) let endY = finalFrame.minY + (frame.size.height / 2) let endX = finalFrame.midX let translation = CGPoint(x: endX - frame.midX, y: endY - frame.midY) let scaleX = finalFrame.width / frame.width var transform: CGAffineTransform = .identity transform = transform.translatedBy(x: translation.x, y: translation.y) transform = transform.scaledBy(x: scaleX, y: scaleX) return transform } //MARK: Private Helper Methods private func calculateCollapsedCellFrameUsingCollectionView(_ collectionView: UICollectionView, atIndex index: Int) -> CGRect { if let attr = collectionView.collectionViewLayout.layoutAttributesForItem(at: IndexPath(item: index, section: 0)) { return collectionView.convert(attr.frame, to: collectionView.superview) } else { return .zero } } private func calculateExpandedCellFrameFromBVC(_ bvc: BrowserViewController) -> CGRect { var frame = bvc.webViewContainer.frame // If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since // there is no toolbar for home panels if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { return frame } else if let url = bvc.tabManager.selectedTab?.url, url.isAboutURL && bvc.toolbar == nil { frame.size.height += UIConstants.BottomToolbarHeight } return frame } private func shouldDisplayFooterForBVC(_ bvc: BrowserViewController) -> Bool { if bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) { if let url = bvc.tabManager.selectedTab?.url { return !url.isAboutURL } } return false } private func toggleWebViewVisibility(_ show: Bool, usingTabManager tabManager: TabManager) { for i in 0..<tabManager.count { if let tab = tabManager[i] { tab.webView?.isHidden = !show } } } private func resetTransformsForViews(_ views: [UIView?]) { for view in views { // Reset back to origin view?.transform = .identity } } private func transformToolbarsToFrame(_ toolbars: [UIView?], toRect endRect: CGRect) { for toolbar in toolbars { // Reset back to origin toolbar?.transform = .identity // Transform from origin to where we want them to end up if let toolbarFrame = toolbar?.frame { toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect) } } } private func createTransitionCellFromTab(_ tab: Tab?, withFrame frame: CGRect) -> TabCell { let cell = TabCell(frame: frame) cell.screenshotView.image = tab?.screenshot cell.titleText.text = tab?.displayTitle if let tab = tab, tab.isPrivate { cell.style = .dark } if let favIcon = tab?.displayFavicon { cell.favicon.sd_setImage(with: URL(string: favIcon.url)!) } else { let defaultFavicon = UIImage(named: "defaultFavicon") if tab?.isPrivate ?? false { cell.favicon.image = defaultFavicon cell.favicon.tintColor = (tab?.isPrivate ?? false) ? UIColor.white : UIColor.darkGray } else { cell.favicon.image = defaultFavicon } } return cell }
mpl-2.0
da5ac0fbcee81f7157f0abacb2c249d3
45.270186
170
0.702329
5.542783
false
false
false
false
jamming/FrameworkBenchmarks
frameworks/Swift/hummingbird/src-postgres/Sources/server/Controllers/WorldController.swift
3
2635
import Hummingbird import PostgresKit class WorldController { func add(to router: HBRouter) { router.get("db", use: single) router.get("queries", use: multiple) router.get("updates", use: updates) } func single(request: HBRequest) -> EventLoopFuture<World> { let id = Int32.random(in: 1...10_000) return request.db.query("SELECT id, randomnumber FROM World WHERE id = $1", [ PostgresData(int32: id) ]).flatMapThrowing { result -> World in guard let firstResult = result.first else { throw HBHTTPError(.notFound) } return World( id: id, randomNumber: firstResult.column("randomnumber")?.int32 ?? 0 ) } } func multiple(request: HBRequest) -> EventLoopFuture<[World]> { let queries = (request.uri.queryParameters.get("queries", as: Int.self) ?? 1).bound(1, 500) let futures: [EventLoopFuture<World>] = (0 ..< queries).map { _ -> EventLoopFuture<World> in let id = Int32.random(in: 1...10_000) return request.db.query("SELECT id, randomnumber FROM World WHERE id = $1", [ PostgresData(int32: id) ]).flatMapThrowing { result -> World in guard let firstResult = result.first else { throw HBHTTPError(.notFound) } return World( id: id, randomNumber: firstResult.column("randomnumber")?.int32 ?? 0 ) } } return EventLoopFuture.whenAllSucceed(futures, on: request.eventLoop) } func updates(request: HBRequest) -> EventLoopFuture<[World]> { let queries = (request.uri.queryParameters.get("queries", as: Int.self) ?? 1).bound(1, 500) let ids = (0 ..< queries).map { _ in Int32.random(in: 1...10_000) } let futures: [EventLoopFuture<World>] = ids.map { _ -> EventLoopFuture<World> in let id = Int32.random(in: 1...10_000) let randomNumber = Int32.random(in: 1...10_000) return request.db.query("SELECT id, randomnumber FROM World WHERE id = $1", [ PostgresData(int32: id) ]).flatMap { result in return request.db.query("UPDATE World SET randomnumber = $1 WHERE id = $2", [ PostgresData(int32: randomNumber), PostgresData(int32: id) ]) }.map { _ in return World(id: id, randomNumber: randomNumber) } } return EventLoopFuture.whenAllSucceed(futures, on: request.eventLoop) } }
bsd-3-clause
23d08420b73791469f7159f400f1e504
42.916667
100
0.565465
4.243156
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Adapters/Transactions/TransactionsAdapter.swift
1
7219
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import FeatureTransactionUI import MoneyKit import PlatformKit import UIKit /// Represents all types of transactions the user can perform. enum TransactionType: Equatable { /// Performs a buy. If `CrytoAccount` is `nil`, the users will be presented with a crypto currency selector. case buy(CryptoAccount?) /// Performs a sell. If `CrytoCurrency` is `nil`, the users will be presented with a crypto currency selector. case sell(CryptoAccount?) /// Performs a swap. If `CrytoCurrency` is `nil`, the users will be presented with a crypto currency selector. case swap(CryptoAccount?) /// Shows details to receive crypto. case receive(CryptoAccount?) /// Performs an interest transfer. case interestTransfer(CryptoInterestAccount) /// Performs an interest withdraw. case interestWithdraw(CryptoInterestAccount) case sign(sourceAccount: CryptoAccount, destination: TransactionTarget) static func == (lhs: TransactionType, rhs: TransactionType) -> Bool { switch (lhs, rhs) { case (.buy(let lhsAccount), .buy(let rhsAccount)): return lhsAccount?.identifier == rhsAccount?.identifier case (.sell(let lhsAccount), .sell(let rhsAccount)): return lhsAccount?.identifier == rhsAccount?.identifier case (.swap(let lhsAccount), .swap(let rhsAccount)): return lhsAccount?.identifier == rhsAccount?.identifier case (.receive(let lhsAccount), .receive(let rhsAccount)): return lhsAccount?.identifier == rhsAccount?.identifier case (.interestTransfer(let lhsAccount), .interestTransfer(let rhsAccount)): return lhsAccount.identifier == rhsAccount.identifier case (.interestWithdraw(let lhsAccount), .interestWithdraw(let rhsAccount)): return lhsAccount.identifier == rhsAccount.identifier case (.sign(let lhsSourceAccount, let lhsDestination), .sign(let rhsSourceAccount, let rhsDestination)): return lhsSourceAccount.identifier == rhsSourceAccount.identifier && lhsDestination.label == rhsDestination.label default: return false } } } /// Represents the possible outcomes of going through the transaction flow. enum TransactionResult: Equatable { case abandoned case completed } /// A protocol defining the API for the app's entry point to any `Transaction Flow`. The app should only use this interface to let users perform any kind of transaction. /// NOTE: Presenting a Transaction Flow can never fail because it's expected for any error to be handled within the flow. Non-recoverable errors should force the user to abandon the flow. protocol TransactionsAdapterAPI { /// Presents a Transactions Flow for the passed-in type of transaction to perform using the `presenter` as a starting point. /// - Parameters: /// - transactionToPerform: The desireed type of transaction to be performed. /// - presenter: The `ViewController` used to present the Transaction Flow. /// - completion: A closure called when the user has completed or abandoned the Transaction Flow. func presentTransactionFlow( to transactionToPerform: TransactionType, from presenter: UIViewController, completion: @escaping (TransactionResult) -> Void ) /// Presents a Transactions Flow for the passed-in type of transaction to perform using the `presenter` as a starting point. /// - Parameters: /// - transactionToPerform: The desireed type of transaction to be performed. /// - presenter: The `ViewController` used to present the Transaction Flow. /// - Returns: A `Combine.Publisher` that publishes a `TransactionResult` once and never fails. func presentTransactionFlow( to transactionToPerform: TransactionType, from presenter: UIViewController ) -> AnyPublisher<TransactionResult, Never> } // MARK: - Interface Implementation extension TransactionType { fileprivate var transactionFlowActionValue: TransactionFlowAction { switch self { case .buy(let cryptoAccount): return .buy(cryptoAccount) case .sell(let cryptoAccount): return .sell(cryptoAccount) case .swap(let cryptoAccount): return .swap(cryptoAccount) case .receive(let cryptoAccount): return .receive(cryptoAccount) case .interestTransfer(let cryptoInterestAccount): return .interestTransfer(cryptoInterestAccount) case .interestWithdraw(let cryptoInterestAccount): return .interestWithdraw(cryptoInterestAccount) case .sign(let sourceAccount, let destination): return .sign(sourceAccount: sourceAccount, destination: destination) } } } extension TransactionResult { fileprivate init(_ transactionFlowResult: TransactionFlowResult) { switch transactionFlowResult { case .abandoned: self = .abandoned case .completed: self = .completed } } } final class TransactionsAdapter: TransactionsAdapterAPI { private let router: FeatureTransactionUI.TransactionsRouterAPI private let coincore: CoincoreAPI private let app: AppProtocol private var cancellables = Set<AnyCancellable>() init( router: FeatureTransactionUI.TransactionsRouterAPI, coincore: CoincoreAPI, app: AppProtocol ) { self.router = router self.coincore = coincore self.app = app } func presentTransactionFlow( to transactionToPerform: TransactionType, from presenter: UIViewController, completion: @escaping (TransactionResult) -> Void ) { presentTransactionFlow(to: transactionToPerform, from: presenter) .sink(receiveValue: completion) .store(in: &cancellables) } func presentTransactionFlow( to transactionToPerform: TransactionType, from presenter: UIViewController ) -> AnyPublisher<TransactionResult, Never> { router.presentTransactionFlow( to: transactionToPerform.transactionFlowActionValue, from: presenter ) .map(TransactionResult.init) .eraseToAnyPublisher() } func presentTransactionFlow( toBuy cryptoCurrency: CryptoCurrency, from presenter: UIViewController ) -> AnyPublisher<TransactionResult, Never> { app.modePublisher() .flatMap { [coincore] appMode in coincore.cryptoAccounts( for: .bitcoin, supporting: .buy, filter: appMode.filter ) } .replaceError(with: []) .receive(on: DispatchQueue.main) .flatMap { [weak self] accounts -> AnyPublisher<TransactionResult, Never> in guard let self = self else { return .empty() } return self.presentTransactionFlow(to: .buy(accounts.first), from: presenter) } .eraseToAnyPublisher() } }
lgpl-3.0
38c5914d67142161d563f9ae9f482c73
39.1
187
0.674702
5.14469
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/ACCourseCategory.swift
1
1070
// // ACCourseCategories.swift // AwesomeCore-iOS10.0 // // Created by Emmanuel on 28/06/2018. // import Foundation public struct ACCourseCategory: Codable, Equatable { public let id: Int public let name: String public let ancestorId: String? public let ancestorName: String? public init(id: Int, name: String, ancestorId: String? = nil, ancestorName: String? = nil ) { self.id = id self.name = name self.ancestorId = ancestorId self.ancestorName = ancestorName } } // MARK: - Equatable extension ACCourseCategory { static public func ==(lhs: ACCourseCategory, rhs: ACCourseCategory) -> Bool { if lhs.id != rhs.id { return false } else if lhs.name != rhs.name { return false } else if lhs.ancestorId != rhs.ancestorId { return false } else if lhs.ancestorName != rhs.ancestorName { return false } return true } }
mit
f84a26714ed6b1f956479214322e8f09
21.291667
81
0.559813
4.196078
false
false
false
false
lukecharman/so-many-games
SoManyGames/Classes/Views/ActionButton.swift
1
2108
// // ActionButton.swift // SoManyGames // // Created by Luke Charman on 30/03/2017. // Copyright © 2017 Luke Charman. All rights reserved. // import UIKit class ActionButton: UIButton { enum ActionButtonAnchor { case topLeft, topCenter, topRight case bottomLeft, bottomCenter, bottomRight } static let spacing: CGFloat = 16 static let side: CGFloat = iPad ? 60 : 44 convenience init(title: String) { self.init() setTitle(title, for: UIControl.State.normal) } func anchor(to view: UIView, at anchor: ActionButtonAnchor) { translatesAutoresizingMaskIntoConstraints = false widthAnchor.constraint(equalToConstant: ActionButton.side * 1.75).isActive = true heightAnchor.constraint(equalToConstant: ActionButton.side).isActive = true switch anchor { case .topLeft, .topCenter, .topRight: topAnchor.constraint(equalTo: view.topAnchor, constant: ActionButton.spacing).isActive = true case .bottomLeft, .bottomCenter, .bottomRight: bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -ActionButton.spacing).isActive = true } switch anchor { case .topLeft, .bottomLeft: leftAnchor.constraint(equalTo: view.leftAnchor, constant: ActionButton.spacing).isActive = true case .topCenter, .bottomCenter: centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true case .topRight, .bottomRight: rightAnchor.constraint(equalTo: view.rightAnchor, constant: -ActionButton.spacing).isActive = true } } override func draw(_ rect: CGRect) { setTitleColor(Colors.darkest, for: UIControl.State.normal) setBackgroundImage(UIImage(named: "Button"), for: UIControl.State.normal) titleLabel?.font = UIFont(name: fontName, size: Sizes.button) layer.shadowColor = Colors.darkest.cgColor layer.shadowOffset = CGSize(width: 0, height: 4) layer.shadowRadius = 6 layer.shadowOpacity = 0.5 super.draw(rect) } }
mit
4096faddf8d761a204e31c6a4670b36a
32.444444
112
0.672046
4.67184
false
false
false
false
ccadena/swift_example_app
iosSearchApp/ViewControllers/AddCityViewController.swift
1
5157
// // AddCityViewController.swift // iosSearchApp // // Created by Camilo Cadena on 9/29/15. // Copyright © 2015 Camilo Cadena. All rights reserved. // import UIKit class AddCityViewController: UIViewController, UITextFieldDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var selectButton: UIButton! @IBOutlet var cityName: UITextField! @IBOutlet var cityDescription: UITextView! @IBOutlet var saveButton: UIBarButtonItem! var cityImage: UIImage! let imagePicker = UIImagePickerController() var itemsArray = [Item]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initialSetUp() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: -Initial Vc Setup properties func initialSetUp() { self.saveButton.enabled = false imagePicker.delegate = self self.cityDescription.text = "" self.cityName.text = "" self.cityName.placeholder = "City name" self.selectButton.layer.cornerRadius = self.selectButton.frame.size.width/2 self.selectButton.clipsToBounds = true } // MARK: - UIImagePickerControllerDelegate func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage self.cityImage = selectedImage self.selectButton.setBackgroundImage(self.cityImage, forState: UIControlState.Normal) self.selectButton.setTitleColor(UIColor.clearColor(), forState: UIControlState.Normal) self.saveButton.enabled = validateInformation() dismissViewControllerAnimated(true, completion:nil) } // MARK: -IBActions @IBAction func loadImageButtonTapped(sender: UIButton) { imagePicker.allowsEditing = false imagePicker.sourceType = .PhotoLibrary presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func addCity() { self.cityName.resignFirstResponder() self.cityDescription.resignFirstResponder() let currentItem = Item(titleText: self.cityName.text!, iconPhoto: self.cityImage , descriptionText: self.cityDescription.text!, index: itemsArray.count)! self.itemsArray.append(currentItem) archiveItems(){ result in if result { // index city if CoreSpotlight API is off if(!GlobalConstants.kActivateCoreSpotlightAPI) { self.indexNewCity(currentItem) } self.navigationController?.popViewControllerAnimated(true) } else { print("*** IOS9 SEARCHAPP ***") print("Error saving City! No index actions were performed") } } } // MARK: - TextField Delegate func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { self.saveButton.enabled = validateInformation() return true } // MARK: - TextView Delegate func textViewDidChange(textView: UITextView) { self.saveButton.enabled = validateInformation() } // MARK: - Validation Method func validateInformation() -> Bool { var completeInformation = false if (self.cityName.text != "" && self.cityDescription.text != "" && self.cityImage != nil) { completeInformation = true } return completeInformation } // MARK: NSCoding func archiveItems(completion:(result:Bool)->Void) { let isSaveCompleted = NSKeyedArchiver.archiveRootObject(itemsArray, toFile: Item.ArchiveURL.path!) if isSaveCompleted { print("*** IOS9 SEARCHAPP ***") print("City saved") completion(result: true) } else { completion(result: false) } } //MARK: - NSUserActivity func indexNewCity(item: Item) { self.userActivity = UserActivityHelper.sharedInstance.indexItemForSearch(item) self.userActivity!.becomeCurrent() updateUserActivityState(self.userActivity!) } override func updateUserActivityState(activity: NSUserActivity) { activity.addUserInfoEntriesFromDictionary([UserActivityConstants.kcityNameKey: self.cityName.text! as String, UserActivityConstants.kcityDescriptionKey: self.cityDescription.text as String, UserActivityConstants.kcityIndexKey: itemsArray.count-1 as Int]) super.updateUserActivityState(activity) } }
gpl-3.0
4ebfc79fbe5b7dc6b9ed4547ebd2511c
31.632911
262
0.648759
5.490948
false
false
false
false
mrchenhao/American-TV-Series-Calendar
American-tv-series-calendar/EpisodeCell.swift
1
3298
// // EpisodeCell.swift // American-tv-series-calendar // // Created by ChenHao on 10/25/15. // Copyright © 2015 HarriesChen. All rights reserved. // import UIKit import EventKit enum episodeState { case added case notAdd } class EpisodeCell: UITableViewCell { @IBOutlet weak var addButton: UIButton! @IBOutlet weak var episodeNameLabel: UILabel! @IBOutlet weak var episodeDateLabel: UILabel! var episode: Episode! override func awakeFromNib() { super.awakeFromNib() } func configWithEpisode(episode: Episode) { self.episode = episode let dateFormat: NSDateFormatter = NSDateFormatter() dateFormat.dateFormat = "yyyy-MM-dd" let dateString: String = dateFormat.stringFromDate(episode.date) self.episodeDateLabel.text = dateString if episode.hasAdd { changeState(.added) } else { changeState(.notAdd) } } func clockButtonTouch() { let alertView = SCLAlertView() alertView.addButton("确定", target:self, selector:Selector("addToCalendar")) alertView.addButton("取消") { } alertView.showCloseButton = false alertView.showInfo("添加", subTitle: String(format: "是否将%@添加到日历中", arguments: [episode.name])) } func trashButtonTouch() { let alertView = SCLAlertView() alertView.addButton("确定", target:self, selector:Selector("removeFromCalendar")) alertView.addButton("取消") { } alertView.showCloseButton = false alertView.showWarning("删除", subTitle: String(format: "是否将%@从日历中删除", arguments: [episode.name])) } func changeState(state: episodeState) { switch state { case .added: addButton.setImage(UIImage(named: "trash"), forState: .Normal) addButton.removeTarget(self, action: Selector("clockButtonTouch"), forControlEvents: .TouchUpInside) addButton.addTarget(self, action: Selector("trashButtonTouch"), forControlEvents: .TouchUpInside) case .notAdd: addButton.setImage(UIImage(named: "clock"), forState: .Normal) addButton.removeTarget(self, action: Selector("trashButtonTouch"), forControlEvents: .TouchUpInside) addButton.addTarget(self, action: Selector("clockButtonTouch"), forControlEvents: .TouchUpInside) } } func addToCalendar() { let success:Bool = EKManager.sharedInstance.addEventToDefauCalendarWithMovie(episode) if success { // let alertView = SCLAlertView() // alertView.showSuccess("添加成功", subTitle: String(format: "成功将添加到日历中,祝你欣赏愉快!", arguments: [episode.name])) changeState(.added) } } func removeFromCalendar() { if let id = episode.eventIdentifer { EKManager.sharedInstance.removeEventWithEventIdentifer(id) changeState(.notAdd) } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
a6b3844484f75875e136214efa9ab73a
31.622449
117
0.633719
4.640058
false
false
false
false
taka0125/AddressBookSync
Example/AddressBookSyncSample/ViewController.swift
1
1574
// // ViewController.swift // AddressBookSync // // Created by Takahiro Ooishi // Copyright (c) 2015 Takahiro Ooishi. All rights reserved. // Released under the MIT license. // import UIKit import AddressBookSync class ViewController: UIViewController { @IBAction func scan() { let status = AddressBook.sharedInstance.authorizationStatus() switch status { case .Authorized: fetchAll() return default: break } AddressBook.sharedInstance.requestAccess { [weak self] (granted, _) -> Void in if granted { self?.fetchAll() } else { print("Access denied") } } } @IBAction func sync() { let addressBookRecords = AddressBook.sharedInstance.fetchAll() print("===== all records =====") print(addressBookRecords.count) SyncHistory.sharedInstance.verifyUpdating(addressBookRecords) let deletedRecordIds = SyncHistory.sharedInstance.fetchAllDeletedRecordIds() print("===== deleted count =====") print(deletedRecordIds.count) let records = SyncHistory.sharedInstance.extractNeedSyncRecords(addressBookRecords) print("===== extracted count =====") print(records.count) SyncHistory.sharedInstance.markAsSynced(records) SyncHistory.sharedInstance.destoryAllDeletedRecords(deletedRecordIds) } @IBAction func remove() { ABSRealm.removeStore() } } extension ViewController { private func fetchAll() { let addressBookRecords = AddressBook.sharedInstance.fetchAll() print(addressBookRecords) } }
mit
d81ff73fd2043dde1550e7db65420fca
23.984127
87
0.682338
4.712575
false
false
false
false
ashleybrgr/surfPlay
surfPlay/Pods/Koloda/Pod/Classes/KolodaView/KolodaViewAnimatior.swift
6
4770
// // KolodaViewAnimatior.swift // Koloda // // Created by Eugene Andreyev on 3/30/16. // // import Foundation import UIKit import pop open class KolodaViewAnimator { public typealias AnimationCompletionBlock = ((Bool) -> Void)? private weak var koloda: KolodaView? public init(koloda: KolodaView) { self.koloda = koloda } open func animateAppearanceWithCompletion(_ completion: AnimationCompletionBlock = nil) { let kolodaAppearScaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) kolodaAppearScaleAnimation?.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearScaleAnimation?.duration = 0.8 kolodaAppearScaleAnimation?.fromValue = NSValue(cgPoint: CGPoint(x: 0.1, y: 0.1)) kolodaAppearScaleAnimation?.toValue = NSValue(cgPoint: CGPoint(x: 1.0, y: 1.0)) kolodaAppearScaleAnimation?.completionBlock = { (_, finished) in completion?(finished) } let kolodaAppearAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) kolodaAppearAlphaAnimation?.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearAlphaAnimation?.fromValue = NSNumber(value: 0.0) kolodaAppearAlphaAnimation?.toValue = NSNumber(value: 1.0) kolodaAppearAlphaAnimation?.duration = 0.8 koloda?.pop_add(kolodaAppearAlphaAnimation, forKey: "kolodaAppearScaleAnimation") koloda?.layer.pop_add(kolodaAppearScaleAnimation, forKey: "kolodaAppearAlphaAnimation") } open func applyReverseAnimation(_ card: DraggableCardView, completion: AnimationCompletionBlock = nil) { let firstCardAppearAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) firstCardAppearAnimation?.toValue = NSNumber(value: 1.0) firstCardAppearAnimation?.fromValue = NSNumber(value: 0.0) firstCardAppearAnimation?.duration = 1.0 firstCardAppearAnimation?.completionBlock = { _, finished in completion?(finished) card.alpha = 1.0 } card.pop_add(firstCardAppearAnimation, forKey: "reverseCardAlphaAnimation") } open func applyScaleAnimation(_ card: DraggableCardView, scale: CGSize, frame: CGRect, duration: TimeInterval, completion: AnimationCompletionBlock = nil) { let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) scaleAnimation?.duration = duration scaleAnimation?.toValue = NSValue(cgSize: scale) card.layer.pop_add(scaleAnimation, forKey: "scaleAnimation") let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) frameAnimation?.duration = duration frameAnimation?.toValue = NSValue(cgRect: frame) if let completion = completion { frameAnimation?.completionBlock = { _, finished in completion(finished) } } card.pop_add(frameAnimation, forKey: "frameAnimation") } open func applyAlphaAnimation(_ card: DraggableCardView, alpha: CGFloat, duration: TimeInterval = 0.2, completion: AnimationCompletionBlock = nil) { let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnimation?.toValue = alpha alphaAnimation?.duration = duration alphaAnimation?.completionBlock = { _, finished in completion?(finished) } card.pop_add(alphaAnimation, forKey: "alpha") } open func applyInsertionAnimation(_ cards: [DraggableCardView], completion: AnimationCompletionBlock = nil) { cards.forEach { $0.alpha = 0.0 } UIView.animate( withDuration: 0.2, animations: { cards.forEach { $0.alpha = 1.0 } }, completion: { finished in completion?(finished) } ) } open func applyRemovalAnimation(_ cards: [DraggableCardView], completion: AnimationCompletionBlock = nil) { UIView.animate( withDuration: 0.05, animations: { cards.forEach { $0.alpha = 0.0 } }, completion: { finished in completion?(finished) } ) } internal func resetBackgroundCardsWithCompletion(_ completion: AnimationCompletionBlock = nil) { UIView.animate( withDuration: 0.2, delay: 0.0, options: .curveLinear, animations: { self.koloda?.moveOtherCardsWithPercentage(0) }, completion: { finished in completion?(finished) }) } }
apache-2.0
5ccef33988429a44d15eac7161d9e134
37.467742
160
0.643606
5.565928
false
false
false
false
aleph7/HDF5Kit
Tests/HDF5KitTests/AttributeTests.swift
1
2527
// Copyright © 2016 Alejandro Isaza. // // This file is part of HDF5Kit. The full HDF5Kit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. import XCTest import HDF5Kit class AttributeTests: XCTestCase { func testName() { let filePath = tempFilePath() guard let file = File.create(filePath, mode: .truncate) else { fatalError("Failed to create file") } let group = file.createGroup("group") XCTAssertEqual(group.name, "/group") let dataspace = Dataspace(dims: [4]) guard let attribute = group.createIntAttribute("attribute", dataspace: dataspace) else { XCTFail() return } XCTAssertEqual(attribute.name, "attribute") } func testWriteReadInt() { let filePath = tempFilePath() guard let file = File.create(filePath, mode: .truncate) else { fatalError("Failed to create file") } let group = file.createGroup("group") XCTAssertEqual(group.name, "/group") let dataspace = Dataspace(dims: [4]) guard let attribute = group.createIntAttribute("attribute", dataspace: dataspace) else { XCTFail() return } do { let writeData = [1, 2, 3, 4] try attribute.write(writeData) XCTAssertEqual(try attribute.read(), writeData) } catch { XCTFail() } } func testWriteReadString() throws { let filePath = tempFilePath() guard let file = File.create(filePath, mode: .truncate) else { fatalError("Failed to create file") } let group = file.createGroup("group") let attribute = try XCTUnwrap(group.createStringAttribute("attribute")) let writeData = "ABCD😀" try attribute.write(writeData) XCTAssertEqual(try attribute.read(), [writeData]) } func testWriteReadFixedString() throws { let filePath = tempFilePath() guard let file = File.create(filePath, mode: .truncate) else { fatalError("Failed to create file") } let group = file.createGroup("group") let attribute = try XCTUnwrap(group.createFixedStringAttribute("attribute", size: 50)) let writeData = "ABCD😀" try attribute.write(writeData) XCTAssertEqual(try attribute.read(), [writeData]) } }
mit
89ae0a6792ccae57fe1cede002e14bae
32.157895
96
0.614286
4.658041
false
true
false
false
cam-hop/APIUtility
RxSwiftFluxDemo/Carthage/Checkouts/RxAlamofire/Sources/Cocoa/URLSession+RxAlamofire.swift
2
4055
// // URLSession+RxAlamofire.swift // RxAlamofire // // Created by Junior B. on 04/11/15. // Copyright © 2015 Bonto.ch. All rights reserved. // import Foundation import Alamofire import RxSwift import RxCocoa // MARK: NSURLSession extensions extension Reactive where Base: URLSession { /** Creates an observable returning a decoded JSON object as `AnyObject`. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of a decoded JSON object as `AnyObject` */ public func json(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Any> { do { let request = try RxAlamofire.urlRequest( method, url, parameters: parameters, encoding: encoding, headers: headers) return json(request: request) } catch let error { return Observable.error(error) } } /** Creates an observable returning a tuple of `(NSData!, NSURLResponse)`. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of a tuple containing data and the request */ public func response(method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: Any]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<(HTTPURLResponse, Data)> { do { let request = try RxAlamofire.urlRequest(method, url, parameters: parameters, encoding: encoding, headers: headers) return response(request: request) } catch let error { return Observable.error(error) } } /** Creates an observable of response's content as `NSData`. - parameter method: Alamofire method object - parameter url: An object adopting `URLConvertible` - parameter parameters: A dictionary containing all necessary options - parameter encoding: The kind of encoding used to process parameters - parameter header: A dictionary containing all the additional headers - returns: An observable of a data */ public func data(_ method: Alamofire.HTTPMethod, _ url: URLConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: [String: String]? = nil) -> Observable<Data> { do { let request = try RxAlamofire.urlRequest(method, url, parameters: parameters, encoding: encoding, headers: headers) return data(request: request) } catch let error { return Observable.error(error) } } }
mit
50bf601c95f25c01386bfea1d8cd20a7
37.245283
82
0.551554
5.926901
false
false
false
false
justinhester/hacking-with-swift
src/Project26/Project26/GameScene.swift
1
9003
// // GameScene.swift // Project26 // // Created by Justin Lawrence Hester on 2/16/16. // Copyright (c) 2016 Justin Lawrence Hester. All rights reserved. // import CoreMotion import SpriteKit enum CollisionTypes: UInt32 { case Player = 1 case Wall = 2 case Star = 4 case Vortex = 8 case Finish = 16 } class GameScene: SKScene, SKPhysicsContactDelegate { var motionManager: CMMotionManager! var player: SKSpriteNode! var lastTouchPosition: CGPoint? var scoreLabel: SKLabelNode! var score: Int = 0 { didSet { scoreLabel.text = "Score: \(score)" } } var gameOver = false override func didMoveToView(view: SKView) { /* Setup your scene here */ let background = SKSpriteNode(imageNamed: "background.jpg") background.position = CGPoint( x: CGRectGetMidX(frame), y: CGRectGetMidY(frame) ) background.blendMode = .Replace background.zPosition = -1 addChild(background) loadLevel() createPlayer() physicsWorld.gravity = CGVector(dx: 0, dy: 0) motionManager = CMMotionManager() motionManager.startAccelerometerUpdates() scoreLabel = SKLabelNode(fontNamed: "Chalkduster") scoreLabel.text = "Score: 0" scoreLabel.horizontalAlignmentMode = .Left scoreLabel.position = CGPoint(x: 16, y: 16) addChild(scoreLabel) physicsWorld.contactDelegate = self } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ if let touch = touches.first { let location = touch.locationInNode(self) lastTouchPosition = location } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { let location = touch.locationInNode(self) lastTouchPosition = location } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { lastTouchPosition = nil } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { lastTouchPosition = nil } func loadLevel() { if let levelPath = NSBundle.mainBundle().pathForResource("level1", ofType: "txt") { if let levelString = try? String(contentsOfFile: levelPath, usedEncoding: nil) { /* Read lines into elements of an array separated by newline. */ let lines = levelString.componentsSeparatedByString("\n") /* SpriteKit uses an inverted Y axis to UIKit, which means the level rows must be read in reverse so that the last line is created at the bottom of the screen. */ for (row, line) in lines.reverse().enumerate() { for (column, letter) in line.characters.enumerate() { /* Each square in the game world occupies a 64x64 space, so we can find its position by multiplying its row and column by 64. SpriteKit calculates its positions from the center of objects, so we need to add 32 to the X and Y coordinates in order to make everything line up on our screen. */ let position = CGPoint( x: (64 * column) + 32, y: (64 * row) + 32 ) if letter == "x" { loadWall(position) } else if letter == "v" { loadVortex(position) } else if letter == "s" { loadStar(position) } else if letter == "f" { loadFinish(position) } } } } } } func loadWall(position: CGPoint) { let node = SKSpriteNode(imageNamed: "block") node.position = position node.physicsBody = SKPhysicsBody(rectangleOfSize: node.size) node.physicsBody!.categoryBitMask = CollisionTypes.Wall.rawValue node.physicsBody!.dynamic = false addChild(node) } func loadVortex(position: CGPoint) { let node = SKSpriteNode(imageNamed: "vortex") node.name = "vortex" node.position = position node.runAction( SKAction.repeatActionForever( SKAction.rotateByAngle( CGFloat(M_PI), duration: 1 ) ) ) node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2) node.physicsBody!.dynamic = false node.physicsBody!.categoryBitMask = CollisionTypes.Vortex.rawValue node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue node.physicsBody!.collisionBitMask = 0 addChild(node) } func loadStar(position: CGPoint) { let node = SKSpriteNode(imageNamed: "star") node.name = "star" node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2) node.physicsBody!.dynamic = false node.physicsBody!.categoryBitMask = CollisionTypes.Star.rawValue node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue node.physicsBody!.collisionBitMask = 0 node.position = position addChild(node) } func loadFinish(position: CGPoint) { let node = SKSpriteNode(imageNamed: "finish") node.name = "finish" node.physicsBody = SKPhysicsBody(circleOfRadius: node.size.width / 2) node.physicsBody!.dynamic = false node.physicsBody!.categoryBitMask = CollisionTypes.Finish.rawValue node.physicsBody!.contactTestBitMask = CollisionTypes.Player.rawValue node.physicsBody!.collisionBitMask = 0 node.position = position addChild(node) } func createPlayer() { player = SKSpriteNode(imageNamed: "player") player.position = CGPoint(x: 96, y: 672) player.physicsBody = SKPhysicsBody(circleOfRadius: player.size.width / 2) player.physicsBody!.allowsRotation = false player.physicsBody!.linearDamping = 0.5 player.physicsBody!.categoryBitMask = CollisionTypes.Player.rawValue player.physicsBody!.contactTestBitMask = CollisionTypes.Star.rawValue | CollisionTypes.Vortex.rawValue | CollisionTypes.Finish.rawValue player.physicsBody!.collisionBitMask = CollisionTypes.Wall.rawValue addChild(player) } func didBeginContact(contact: SKPhysicsContact) { if contact.bodyA.node == player { playerCollidedWithNode(contact.bodyB.node!) } else if contact.bodyB.node == player { playerCollidedWithNode(contact.bodyA.node!) } } func playerCollidedWithNode(node: SKNode) { if node.name == "vortex" { playerCollidedWithVortex(node) } else if node.name == "star" { playerCollidedWithStar(node) } else if node.name == "finish" { playerCollidedWithFinish() } } func playerCollidedWithVortex(node: SKNode) { player.physicsBody!.dynamic = false gameOver = true score -= 1 let move = SKAction.moveTo(node.position, duration: 0.25) let scale = SKAction.scaleTo(0.0001, duration: 0.25) let remove = SKAction.removeFromParent() let sequence = SKAction.sequence([move, scale, remove]) player.runAction(sequence) { [unowned self] in self.createPlayer() self.gameOver = false } } func playerCollidedWithStar(node: SKNode) { node.removeFromParent() score += 1 } func playerCollidedWithFinish() { } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ if !gameOver { #if (arch(i386) || arch(x86_64)) if let currentTouch = lastTouchPosition { let diff = CGPoint( x: currentTouch.x - player.position.x, y: currentTouch.y - player.position.y ) physicsWorld.gravity = CGVector(dx: diff.x / 100, dy: diff.y / 100) } #else if let accelerometerData = motionManager.accelerometerData { physicsWorld.gravity = CGVector( dx: accelerometerData.acceleration.y * -50, dy: accelerometerData.acceleration.x * -50 ) } #endif } } }
gpl-3.0
82b2460f344f6375dae9d5efd00da938
32.973585
92
0.574586
5.126993
false
false
false
false
hovansuit/FoodAndFitness
FoodAndFitness/Model/1.0/Tracking.swift
1
1719
// // Tracking.swift // FoodAndFitness // // Created by Mylo Ho on 4/9/17. // Copyright © 2017 SuHoVan. All rights reserved. // import RealmSwift import ObjectMapper import RealmS final class Tracking: Object, Mappable { private(set) dynamic var id = 0 private(set) dynamic var active: String = "" private(set) dynamic var duration: Int = 0 private(set) dynamic var distance: Int = 0 private(set) dynamic var userHistory: UserHistory? private(set) dynamic var createdAt: Date = Date() let locations = List<Location>() override class func primaryKey() -> String? { return "id" } convenience required init?(map: Map) { self.init() id <- map["id"] assert(id > 0, "Tracking `id` must be greater than 0") } func mapping(map: Map) { active <- map["active"] duration <- map["duration"] distance <- map["distance"] userHistory <- map["user_history"] createdAt <- (map["created_at"], DataTransform.fullDate) locations <- map["locations"] } } // MARK: - Utils extension Tracking { var velocity: Double { return (Double(distance) / 1000) / (Double(duration) / 3600) } var caloriesBurn: Int { guard let userHistory = userHistory else { return 0 } let bmr = userHistory.caloriesToday let activeTracking = ActiveTracking.active(title: active) let burned = caloriesBurned(bmr: bmr, velocity: velocity, active: activeTracking, duration: Double(duration) / 3600) if burned == 0 { return 1 } return burned } } // MARK: - Int extension Int { var toMinutes: Int { return self / 60 } }
mit
3a07317c483fc8b3b9d13b25786a8e0e
25.030303
124
0.61234
4.023419
false
false
false
false
ins-wing/Apptoms
Apptoms/Classes/Hydrogen/Extensions_Hydrogen.swift
1
1895
// // Extensions_Hydrogen.swift // Hydrogen // // Created by WinG@Apptoms on 1/7/2017. // Copyright (c) 2017 Apptoms. All rights reserved. // import Foundation public extension UIColor { public convenience init(hex: String) { var color: String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if (color.hasPrefix("#")) { color.remove(at: color.startIndex) } if ((color.characters.count) != 6 && (color.characters.count) != 8) { self.init(white: 0, alpha: 0) } else { var rgb: UInt32 = 0 Scanner(string: color).scanHexInt32(&rgb) if ((color.characters.count) == 6) { self.init(codeWithRed: CGFloat((rgb & 0xFF0000) >> 16), green: CGFloat((rgb & 0x00FF00) >> 8), blue: CGFloat(rgb & 0x0000FF)) } else { self.init(codeWithRed: CGFloat((rgb & 0xFF000000) >> 24), green: CGFloat((rgb & 0x00FF0000) >> 16), blue: CGFloat((rgb & 0x0000FF00) >> 8), alpha: CGFloat(rgb & 0x000000FF)) } } } public convenience init(codeWithRed red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat = 255.0) { self.init(red: red / 255.0, green: green / 255.0, blue: blue / 255.0, alpha: alpha / 255.0) } public static var placeholder: UIColor { get { return UIColor(hex: "C7C7CD") } } } public extension String { public var json: Any? { get { let object = try? JSONSerialization.jsonObject(with: self.data(using: .utf8)!, options: .allowFragments) return object } } public init?(json: Any) { do { let data = try JSONSerialization.data(withJSONObject: json, options: .init(rawValue: 0)) self = String(data: data, encoding: .utf8)! } catch { return nil } } } public extension Array where Element: Equatable { mutating public func remove(object: Element) -> Int? { let removeIndex = index(of: object) if (removeIndex != nil) { self.remove(at: removeIndex!) } return removeIndex } }
mit
75a60e83e878c8cda9a2a8404e32efc2
24.958904
177
0.658575
3.007937
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Maps Tab/Map/MapLocationsList.swift
1
6853
// // MapLocationsList.swift // MEGameTracker // // Created by Emily Ivie on 1/15/17. // Copyright © 2017 Emily Ivie. All rights reserved. // import UIKit public struct MapLocationsList { public var inMapId: String? public var inView: UIView? public var isSplitMenu: Bool = false // if the map is really a menu to other maps public var baseZoomScale: CGFloat = 1.0 // public var onClick: ((MapLocationButtonNib) -> Void) = { _ in } var locations: [MapLocationPointKey: [MapLocationable]] = [:] var buttons: [MapLocationPointKey: MapLocationButtonNib] = [:] var initialZoomScale: CGFloat? var startingZoomScaleAdjustment: CGFloat? let mapTitlesVisibleZoomScales: [UIUserInterfaceIdiom: CGFloat] = [.phone: CGFloat(2.0), .pad: CGFloat(1.1)] // public init( // inMapId: String?, // inView: UIView? = nil, // isSplitMenu: Bool = false, // onClick: @escaping ((MapLocationButton) -> Void) = { _ in } // ) { // self.inMapId = inMapId // self.inView = inView // self.isSplitMenu = isSplitMenu // self.onClick = onClick // } public func insertAll(inView view: UIView) { for (_, button) in buttons { if button.superview == nil { view.addSubview(button) } } view.layoutIfNeeded() } public func insert(button: MapLocationButtonNib, inView view: UIView) { if button.superview == nil { view.addSubview(button) } view.layoutIfNeeded() } public func isFound(location: MapLocationable) -> Bool { guard let point = location.mapLocationPoint else { return false } return locations[point.key]?.contains(where: { $0.isEqual(location) }) ?? false } public func getButton(atPoint point: MapLocationPoint) -> MapLocationButtonNib? { return buttons[point.key] } public func getButtonTouched(gestureRecognizer: UITapGestureRecognizer) -> MapLocationButtonNib? { return buttons.values.filter { let point = gestureRecognizer.location(in: $0.button) return $0.button?.point(inside: point, with: nil) == true }.first } public func getLocations(atPoint point: MapLocationPoint) -> [MapLocationable] { return locations[point.key] ?? [] } public func getLocations(fromButton button: MapLocationButtonNib) -> [MapLocationable] { guard let key = button.mapLocationPoint?.key else { return [] } return locations[key] ?? [] } public mutating func add(locations: [MapLocationable]) -> Bool { var isAdded = true for location in locations { isAdded = add(location: location) && isAdded } return isAdded } public mutating func add(location: MapLocationable, isIgnoreAvailabilityRules: Bool = false) -> Bool { guard let key = location.mapLocationPoint?.key else { return false } guard isVisible(location: location, isIgnoreAvailabilityRules: isIgnoreAvailabilityRules) else { remove(location: location) return false } if locations[key] == nil { locations[key] = [location] } else { if let index = locations[key]?.firstIndex(where: { $0.isEqual(location) }) { locations[key]?[index] = location } else { locations[key]?.append(location) locations[key] = locations[key]?.sorted(by: MapLocation.sort) } } addButton(atKey: key) return true } public mutating func removeAll() { for (_, button) in buttons { button.removeFromSuperview() } locations = [:] buttons = [:] } public mutating func remove(location: MapLocationable) { guard let point = location.mapLocationPoint else { return } if let index = locations[point.key]?.firstIndex(where: { $0.isEqual(location) }) { locations[point.key]?.remove(at: index) if locations[point.key]?.isEmpty == true { removeButton(atKey: point.key) } } } mutating func addButton(atKey key: MapLocationPointKey) { guard let location = locations[key]?[0] else { return } if buttons[key] == nil, let button = MapLocationButtonNib.loadNib(key: key) { buttons[key] = button } if let button = buttons[key] { // (we can only do this because UIButton is reference type) let isShowPin = location.isShowPin && (location.inMapId == inMapId || location.shownInMapId == inMapId) button.set(location: location, isShowPin: isShowPin) if isSplitMenu { // move to zoom? // (button.title as? UILabel)?.identifier = "Body.NormalColor" button.titleWidthConstraint?.isActive = false } // button.onClick = self.onClick if let locationGroup: [MapLocationable] = locations[key], locationGroup.count > 1 { button.mapLocationPoint = locationGroup.compactMap { $0.mapLocationPoint }.reduce(MapLocationPoint(x: 0, y: 0, radius: 0)) { $0.width > $1.width && $0.height > $1.height ? $0 : $1 } button.isShowPin = locationGroup.reduce(false) { $0 || ($1.isShowPin && ($1.inMapId == inMapId || $1.shownInMapId == inMapId)) } } } } mutating func removeButton(atKey key: MapLocationPointKey) { buttons[key]?.removeFromSuperview() buttons.removeValue(forKey: key) } func resizeButtons(fromSize: CGSize, toSize: CGSize) { for (key, _) in buttons { resizeButton(atKey: key, fromSize: fromSize, toSize: toSize) } } func resizeButton(atKey key: MapLocationPointKey, fromSize: CGSize, toSize: CGSize) { guard let button = buttons[key] else { return } if let sizedMapLocationPoint = button.mapLocationPoint?.fromSize(fromSize, toSize: toSize), button.sizedMapLocationPoint != sizedMapLocationPoint { buttons[key]?.sizedMapLocationPoint = sizedMapLocationPoint if button.superview != nil { buttons[key]?.size(isForce: true) } } } mutating func zoomButtons(zoomScale: CGFloat) { for (key, _) in buttons { zoomButton(atKey: key, zoomScale: zoomScale) } } mutating func zoomButton(atKey key: MapLocationPointKey, zoomScale: CGFloat) { buttons[key]?.zoomScale = zoomScale if isSplitMenu { buttons[key]?.title?.contentScaleFactor = zoomScale } else { let deviceKind = UIDevice.current.userInterfaceIdiom guard let visibleZoomScale = mapTitlesVisibleZoomScales[deviceKind] else { return } let isVisible = (zoomScale / baseZoomScale) > visibleZoomScale buttons[key]?.title?.isHidden = !isVisible buttons[key]?.title?.contentScaleFactor = zoomScale buttons[key]?.titleWidthConstraint?.constant = max(50, ((inView?.bounds.width ?? 500.0) / 5.0)) } } func isVisible(location: MapLocationable, isIgnoreAvailabilityRules: Bool) -> Bool { if isFound(location: location) { // if we've already approved it, allow it return true } guard location.shownInMapId == inMapId || location.inMapId == inMapId else { return false } if isSplitMenu == true || isIgnoreAvailabilityRules { return true } if location.mapLocationPoint != nil && location is Map { return true } if (location as? Mission)?.isCompleted == false || (location as? Item)?.isAcquired == false { return location.isAvailable } return false } }
mit
d78bac46f28b996762dcaecee8307db4
30.576037
109
0.69892
3.530139
false
false
false
false
oneCup/MyWeiBo
MyWeiBoo/MyWeiBoo/Class/Module/Main/YFVisitorView.swift
1
9266
// // YFVisitorView.swift // MyWeiBoo // // Created by 李永方 on 15/10/8. // Copyright © 2015年 李永方. All rights reserved. // import UIKit // MARK:登录协议 protocol VisitorLoginDelegate: NSObjectProtocol { /// 将要登录 func visitorWillLogin() /// 将要注册 func visitorWillRegester() } class YFVisitorView: UIView { //定义代理属性--一定要使用weak weak var delegate : VisitorLoginDelegate? override init(frame: CGRect) { super.init(frame: frame) //创建视图 setUpUI() } // MARK: 设置视图信息 func setUpViewInfo(isHome:Bool, imageNamed:String, messageText:String) { iconView.image = UIImage(named: imageNamed) messageLable.text = messageText HomeIconView.hidden = !isHome //判断是否有动画,如果没有,没有就讲遮罩放在最底层,如果有就开始动画 isHome ? StartAnimated() : sendSubviewToBack(maskIconView) } // MARK: 设置动画 func StartAnimated() { //设置核心动画 let animated = CABasicAnimation(keyPath: "transform.rotation") animated.toValue = 2 * M_PI animated.repeatCount = MAXFLOAT animated.duration = 20.0 //为了防止将切换界面时动画丢失,设置动画属性 animated.removedOnCompletion = false iconView.layer.addAnimation(animated, forKey: nil) } required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // 禁止用 sb / xib 使用本类 // fatalError("init(coder:) has not been implemented") super.init(coder: aDecoder) setUpUI() } //登录事件 func clickLoginButton () { //代理执行代理方法 delegate?.visitorWillLogin() print(__FUNCTION__) } //注册事件 func clickResignButton() { //代理执行代理方法 delegate?.visitorWillRegester() print(__FUNCTION__) } //设置界面元素 private func setUpUI() { //将图标加载到视图 addSubview(iconView) addSubview(maskIconView) addSubview(HomeIconView) addSubview(messageLable) addSubview(regestorButton) addSubview(loginButton) //自动布局 //1>图标 iconView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: -40)) //2>小房子 HomeIconView.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: HomeIconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: HomeIconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0)) //3>描述文字 messageLable.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: messageLable, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: messageLable, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16)) addConstraint(NSLayoutConstraint(item: messageLable, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 224)) //4>注册按钮 regestorButton.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: regestorButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLable, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: regestorButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLable, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16)) addConstraint(NSLayoutConstraint(item: regestorButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100)) addConstraint(NSLayoutConstraint(item: regestorButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35)) //5>登录按钮 loginButton.translatesAutoresizingMaskIntoConstraints = false addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLable, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: 0)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLable, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 16)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 100)) addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1.0, constant: 35)) //6>遮罩视图 maskIconView.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["subview":maskIconView])) addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[subview]-(-35)-[regButton]", options:NSLayoutFormatOptions(rawValue: 0), metrics: nil, views:["subview": maskIconView, "regButton": regestorButton])) //设置背景图片 backgroundColor = UIColor(white: 237.0 / 255.0, alpha: 1.0) } /// 图标 private lazy var iconView: UIImageView = { let icon = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon")) return icon }() private lazy var maskIconView: UIImageView = { let icon = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon")) return icon }() /** 首页小房子 */ private lazy var HomeIconView: UIImageView = { let icon = UIImageView(image: UIImage(named: "visitordiscover_feed_image_house")) return icon }() /** 描述文字 */ private lazy var messageLable: UILabel = { let label = UILabel() label.text = "关注一些人,回这里看看有什么惊喜" label.font = UIFont.systemFontOfSize(14) label.textColor = UIColor.darkGrayColor() label.textAlignment = NSTextAlignment.Center label.numberOfLines = 0 return label }() /** 注册按钮 */ private lazy var regestorButton : UIButton = { let button = UIButton() button.setTitle("注册", forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) button.addTarget(self, action: "clickResignButton", forControlEvents: UIControlEvents.TouchUpInside) return button }() /** 登录按钮 */ private lazy var loginButton : UIButton = { let button = UIButton() button.setTitle("登录", forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal) button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //注册监听事件 button.addTarget(self, action: "clickLoginButton", forControlEvents: UIControlEvents.TouchUpInside) return button }() }
mit
e95bd5088a5a32e5b621e5edd2d40b4b
37.030172
227
0.677661
5.064868
false
false
false
false
inevs/Timepiece
Tests/DurationTests.swift
1
777
// // DurationTests.swift // Timepiece // // Created by Naoto Kaneko on 2014/08/17. // Copyright (c) 2014年 Naoto Kaneko. All rights reserved. // import Timepiece import XCTest class DurationTestCase: XCTestCase { func testAgo() { let today = NSDate() let oneDay = Duration(value: 1, unit: .Day) let yesterday = today - 1.day XCTAssertEqualWithAccuracy(oneDay.ago(from: today).timeIntervalSince1970, yesterday.timeIntervalSince1970, 0.01, "") } func testLater() { let today = NSDate() let oneDay = Duration(value: 1, unit: .Day) let tomorrow = today + 1.day XCTAssertEqualWithAccuracy(oneDay.later(from: today).timeIntervalSince1970, tomorrow.timeIntervalSince1970, 0.01, "") } }
mit
e55b70f3f5204d58308445597fe243a5
27.703704
125
0.655484
4.12234
false
true
false
false
kenwilcox/Crypticker
Crypticker/ViewController.swift
1
2877
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit import CryptoCurrencyKit class ViewController: CurrencyDataViewController { @IBOutlet var priceOnDayLabel: UILabel! let dateFormatter: NSDateFormatter required init(coder aDecoder: NSCoder) { dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE M/d" super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() lineChartView.dataSource = self lineChartView.delegate = self priceOnDayLabel.text = "" dayLabel.text = "" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchPrices{ error in if error == nil { self.updatePriceLabel() self.updatePriceChangeLabel() self.updatePriceHistoryLineChart() } } } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { coordinator.animateAlongsideTransition(nil) { _ in self.lineChartView.reloadData() } } func updatePriceOnDayLabel(price: BitCoinPrice) { priceOnDayLabel.text = dollarNumberFormatter.stringFromNumber(price.value) } func updateDayLabel(price: BitCoinPrice) { dayLabel.text = dateFormatter.stringFromDate(price.time) } // MARK: - JBLineChartViewDataSource & JBLineChartViewDelegate func lineChartView(lineChartView: JBLineChartView!, didSelectLineAtIndex lineIndex: UInt, horizontalIndex: UInt) { if let prices = prices { let price = prices[Int(horizontalIndex)] updatePriceOnDayLabel(price) updateDayLabel(price) } } func didUnselectLineInLineChartView(lineChartView: JBLineChartView!) { priceOnDayLabel.text = "" dayLabel.text = "" } }
mit
127706276f43b50fcd2a7bfc0e30b0cf
30.615385
134
0.73375
4.755372
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Scenes/Create terrain surface from a local tile package/CreateTerrainSurfaceFromLocalTilePackageViewController.swift
1
1924
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class CreateTerrainSurfaceFromLocalTilePackageViewController: UIViewController { @IBOutlet weak var sceneView: AGSSceneView! { didSet { // Initialize the scene with imagery basemap. sceneView.scene = makeScene() // Set initial scene viewpoint. let camera = AGSCamera(latitude: 36.525, longitude: -121.80, altitude: 300.0, heading: 180, pitch: 80, roll: 0) sceneView.setViewpointCamera(camera) } } func makeScene() -> AGSScene { let scene = AGSScene(basemapStyle: .arcGISImagery) // Create an elevation source using the path to the tile package. let surface = AGSSurface() let tpkURL = Bundle.main.url(forResource: "MontereyElevation", withExtension: "tpkx")! let elevationSource = AGSArcGISTiledElevationSource(url: tpkURL) surface.elevationSources.append(elevationSource) scene.baseSurface = surface return scene } override func viewDidLoad() { super.viewDidLoad() // Add the source code button item to the right of navigation bar. (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["CreateTerrainSurfaceFromLocalTilePackageViewController"] } }
apache-2.0
1155dc383cb8acef338893d94f09e570
38.265306
147
0.683992
4.658596
false
false
false
false
nate-parrott/PatternPicker
PatternPicker/PatternView.swift
1
1246
// // PatternView.swift // PatternPicker // // Created by Nate Parrott on 11/15/15. // Copyright © 2015 Nate Parrott. All rights reserved. // import UIKit class PatternView: UIView { var pattern: Pattern = Pattern(type: .SolidColor, primaryColor: UIColor.greenColor(), secondaryColor: nil) { didSet { _contentView = pattern.renderAsView(_contentView) let s = patternScale patternScale = s } } private var _contentView: UIView? { willSet(newVal) { if newVal !== _contentView { if let old = _contentView { old.removeFromSuperview() } if let view = newVal { insertSubview(view, atIndex: 0) } } } } override func layoutSubviews() { super.layoutSubviews() _contentView?.frame = bounds } var patternScale: CGFloat = 1 { didSet { if let v = _contentView { v.transform = CGAffineTransformMakeScale(patternScale, patternScale) v.bounds = CGRectMake(0, 0, bounds.size.width / patternScale, bounds.size.height / patternScale) } } } }
mit
7678a31c5a133e19afad280285665254
27.953488
112
0.544578
4.715909
false
false
false
false
rodrigosoldi/XCTestsExample
XCTestsExampleTests/SearchSongsInteractorTests.swift
1
2552
// // SearchSongsInteractorTests.swift // XCTestsExample // // Created by Emannuel Fernandes de Oliveira Carvalho on 9/7/16. // Copyright © 2016 Rodrigo Soldi Lopes. All rights reserved. // import XCTest @testable import XCTestsExample class MockSearchSongWorker: SearchSongWorker { var searchSongCalled = false var requestSearchParameter: String? override func searchSong(search: String, completionHandler: (songs: [Song]?) -> Void) { searchSongCalled = true requestSearchParameter = search let songs = [ Song(name: "song 1", singer: "singer 1"), Song(name: "song 2", singer: "singer 2"), Song(name: "song 3", singer: "singer 3") ] completionHandler(songs: songs) } } class MockInteractorOutput: SearchSongInteractorOutput { var presentSearchSongsCalled = false func presentSearchedSongs(response: SearchSong.Response) { presentSearchSongsCalled = true } } class SearchSongsInteractorTests: XCTestCase { func testCallingWorker() { // Arrange let interactor = SearchSongInteractor() let worker = MockSearchSongWorker() let output = MockInteractorOutput() interactor.worker = worker interactor.output = output // Act interactor.searchSong(SearchSong.Request(search: "anything")) // Assert XCTAssert(worker.searchSongCalled, "It should have called searchSong()") } func testPassingParameters() { // Arrange let interactor = SearchSongInteractor() let worker = MockSearchSongWorker() let output = MockInteractorOutput() interactor.worker = worker interactor.output = output let myString = "my favorite string" // Act interactor.searchSong(SearchSong.Request(search: myString)) // Assert XCTAssert(worker.requestSearchParameter == myString, "It should have called with the right string") } func testCallingOutput() { let interactor = SearchSongInteractor() let worker = MockSearchSongWorker() let output = MockInteractorOutput() interactor.worker = worker interactor.output = output interactor.searchSong(SearchSong.Request(search: "My string")) XCTAssert(output.presentSearchSongsCalled, "It should have called the output") } }
mit
7b2fdb7f35737b12bc53b87b479053b2
27.988636
91
0.625245
4.915222
false
true
false
false
kunsy/DYZB
DYZB/DYZB/Classes/Home/View/RecommandCycleView.swift
1
4156
// // RecommandCycleView.swift // DYZB // // Created by Anyuting on 2017/9/1. // Copyright © 2017年 Anyuting. All rights reserved. // import UIKit private let kEdgeInsetMargin : CGFloat = 10 class RecommandCycleView: UIView { var cycleTimer : Timer? var cycleModels : [CycleModel]? { didSet { collectionView.reloadData() //set pagecontrol pageControl.numberOfPages = cycleModels?.count ?? 0 //初始滚动到中间位置 let indexPath = IndexPath(item: (cycleModels?.count ?? 0) * 10, section: 0) collectionView.scrollToItem(at: indexPath, at: .left, animated: false) //add Timer removeCycleTimer() addCycleTimer() } } //控件属性 @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! fileprivate let kCycleCellID = "kCycleCellID" //系统回调函数 override func awakeFromNib() { super.awakeFromNib() //拒绝随着父类拉伸 //autoresizingMask = .flexibleBottomMargin autoresizingMask = UIViewAutoresizing(rawValue: 0) //注册cell collectionView.register(UINib(nibName: "CollectionCycleCell", bundle: nil), forCellWithReuseIdentifier: kCycleCellID) //添加内边距,cell太靠边了 //collectionView.contentInset = UIEdgeInsets(top: 0, left: kEdgeInsetMargin, bottom: 0, right: kEdgeInsetMargin) } override func layoutSubviews() { super.layoutSubviews() //set cell layout let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = collectionView.bounds.size layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal collectionView.isPagingEnabled = true } } //提供快速创建的类方法 extension RecommandCycleView { class func recommandCycleView() -> RecommandCycleView { return Bundle.main.loadNibNamed("RecommandCycleView", owner: nil, options: nil)?.first as! RecommandCycleView } } extension RecommandCycleView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (cycleModels?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleCellID, for: indexPath) as! CollectionCycleCell cell.cycleModel = cycleModels![indexPath.item % (cycleModels?.count)!] //cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.red : UIColor.blue return cell } } extension RecommandCycleView : UICollectionViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5 pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1) } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { removeCycleTimer() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { addCycleTimer() } } //定时滚动操作 extension RecommandCycleView { fileprivate func addCycleTimer() { cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(self.scrollToNext), userInfo: nil, repeats: true) //RunLoop.main.add(cycleTiemr, forMode: CFRunLoopCommonMode) RunLoop.main.add(cycleTimer!, forMode: RunLoopMode.commonModes) } fileprivate func removeCycleTimer() { cycleTimer?.invalidate() cycleTimer = nil } @objc fileprivate func scrollToNext() { let currentOffsetX = collectionView.contentOffset.x let offsetX = currentOffsetX + collectionView.bounds.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true) } }
mit
7da85e06848c38888914f4dd5d77638e
35.754545
129
0.679446
5.237047
false
false
false
false
owenzhao/Localization-Helper
Modify NSLocalizedString/ReadMe.playground/Contents.swift
1
886
import Foundation //: # Below code works //: ## 1. `NSLocalizedString` with single \\(foo) let count = 10 let says = NSLocalizedString("It runs \(count) times", comment: "run times") //: ## 2. `NSLocalizedString` with multiple \\(foo)s let days = 3 let hours = 5 let newSays = NSLocalizedString("I have been here for \(days) days, \(hours) hours.", comment: "stay time") //: ## 3. in function func putString(a:String="", _ s:String) { print(s) } putString(a:"", NSLocalizedString("It runs \(count) times", comment: "run times")) //: ## 4. in closure let p = { (a:String) -> () in print(a) } p(NSLocalizedString("It runs \(count) times", comment: "run times")) //: # Known issues //: 1. /* */ in one single line is not supported. //: 2. Multiple `NSLocalizedStrings`in one line is not supported as Apple suggest to use on `NSLocalizedString` instead of composite them together.
bsd-2-clause
351e915d5bf135a008624d101495d497
37.521739
147
0.668172
3.631148
false
false
false
false
ReactiveKit/ReactiveUIKit
Sources/UISlider.swift
1
2462
// // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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) import ReactiveKit import UIKit extension UISlider { private struct AssociatedKeys { static var ValueKey = "r_ValueKey" } public var rValue: Property<Float> { if let rValue: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.ValueKey) { return rValue as! Property<Float> } else { let rValue = Property<Float>(self.value) objc_setAssociatedObject(self, &AssociatedKeys.ValueKey, rValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) var updatingFromSelf: Bool = false rValue.observeNext { [weak self] value in if !updatingFromSelf { self?.value = value } }.disposeIn(rBag) self.rControlEvent .filter { $0 == UIControlEvents.ValueChanged } .observeNext { [weak self] event in guard let unwrappedSelf = self else { return } updatingFromSelf = true unwrappedSelf.rValue.value = unwrappedSelf.value updatingFromSelf = false }.disposeIn(rBag) return rValue } } } extension UISlider: BindableType { public func observer(disconnectDisposable: Disposable) -> (StreamEvent<Float> -> ()) { return self.rValue.observer(disconnectDisposable) } } #endif
mit
bc1dbd2dd87097d9a26539556ff0eebc
33.194444
128
0.695776
4.45208
false
false
false
false
cdmx/MiniMancera
miniMancera/View/Option/ReformaCrossing/Node/VOptionReformaCrossingPlayer.swift
1
2396
import SpriteKit class VOptionReformaCrossingPlayer:ViewGameNode<MOptionReformaCrossing> { private let kPhysicsWidth:CGFloat = 12 private let kPhysicsHeight:CGFloat = 10 private let kPhysicsYPos:CGFloat = -10 override init(controller:ControllerGame<MOptionReformaCrossing>) { let texture:MGameTexture = controller.model.textures.playerStand super.init( controller:controller, texture:texture) isHidden = true startPhysics() } required init?(coder:NSCoder) { return nil } //MARK: private private func startPhysics() { let physicsSize:CGSize = CGSize(width:kPhysicsWidth, height:kPhysicsHeight) let physicsCenter:CGPoint = CGPoint(x:0, y:kPhysicsYPos) let physicsBody:SKPhysicsBody = SKPhysicsBody( rectangleOf:physicsSize, center:physicsCenter) physicsBody.isDynamic = true physicsBody.friction = 0 physicsBody.angularVelocity = 0 physicsBody.allowsRotation = true physicsBody.restitution = 1 physicsBody.categoryBitMask = MOptionReformaCrossingPhysicsStruct.Player physicsBody.contactTestBitMask = MOptionReformaCrossingPhysicsStruct.Foe physicsBody.collisionBitMask = MOptionReformaCrossingPhysicsStruct.Foe self.physicsBody = physicsBody } //MARK: public func timeOut() { removeAllActions() let texture:MGameTexture = controller.model.textures.playerTimeout self.texture = texture.texture } func success() { removeAllActions() let texture:MGameTexture = controller.model.textures.playerSuccess self.texture = texture.texture } func hitAndRun() { removeAllActions() let texture:MGameTexture = controller.model.textures.playerHitAndRun self.texture = texture.texture size = texture.size } func animateWalk() { removeAllActions() let action:SKAction = controller.model.actions.actionPlayerWalkAnimation run(action) } func animateStop() { removeAllActions() let action:SKAction = controller.model.actions.actionPlayerStopAnimation run(action) } }
mit
423f6854ba1cac4ae14a02de45d56bbe
25.921348
83
0.638982
5.396396
false
false
false
false
seivan/TimingFunctions
TestsAndSample/Game/GameScene.swift
1
2722
// // GameScene.swift // TestsAndSample // // Created by Seivan Heidari on 15/07/14. // Copyright (c) 2014 Seivan Heidari. All rights reserved. // import SpriteKit class GameScene: SKScene { let rect = CGRectMake(0, 0, 240, 120) var rectanglePath = UIBezierPath(roundedRect: CGRectMake(0, 0, 240, 120), byRoundingCorners: UIRectCorner.fromMask(UIRectCorner.TopRight.toRaw() | UIRectCorner.BottomLeft.toRaw()), cornerRadii: CGSizeMake(1, 1)) var toggle = true let sprite = SKShapeNode() override func didMoveToView(view: SKView) { self.sprite.path = self.rectanglePath.CGPath self.sprite.position = CGPoint(x: self.frame.midX/1.25, y: self.frame.midY) self.sprite.fillColor = SKColor.redColor() self.sprite.strokeColor = SKColor.blueColor() self.addChild(self.sprite) } func eventOnCGPoint(location:CGPoint) { var cornerRadius = 1.0 if(self.toggle) { cornerRadius = 60.0 self.toggle = false } else { cornerRadius = 1.0 self.toggle = true } let duration = 1.0 let action = SKAction.customActionWithDuration(duration) { node, elapsedTime in if(self.toggle) { var percentage:Double = TimingFunctions.exponentialEaseOut(Double(elapsedTime) / Double(duration)) cornerRadius = (60.0-(60.0 * percentage))+(1*percentage) self.rectanglePath = UIBezierPath(roundedRect: self.rect, byRoundingCorners: UIRectCorner.fromMask(UIRectCorner.TopRight.toRaw() | UIRectCorner.BottomLeft.toRaw()), cornerRadii: CGSizeMake(cornerRadius, cornerRadius)) self.sprite.path = self.rectanglePath.CGPath } else { var percentage:Double = TimingFunctions.elasticEaseOut(Double(elapsedTime) / Double(duration)) let newCornerRadius = cornerRadius * percentage self.rectanglePath = UIBezierPath(roundedRect: self.rect, byRoundingCorners: UIRectCorner.fromMask(UIRectCorner.TopRight.toRaw() | UIRectCorner.BottomLeft.toRaw()), cornerRadii: CGSizeMake(newCornerRadius, newCornerRadius)) } self.sprite.path = self.rectanglePath.CGPath } self.sprite.runAction(action) } #if os(iOS) override func touchesEnded(touches:NSSet, withEvent:UIEvent) { let withEvent:UITouch = touches.allObjects[0] as UITouch let location = withEvent.locationInNode(self) self.eventOnCGPoint(location) } #endif #if os(OSX) override func mouseDown(theEvent: NSEvent) { let location = theEvent.locationInNode(self) self.eventOnCGPoint(location) } #endif override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } }
mit
a9e544b42d273d4d4d96bab878807d42
31.023529
233
0.688464
4.273155
false
false
false
false
remobjects/Marzipan
CodeGen4/TypeDefinitions.swift
1
14383
/* Types */ public enum CGTypeVisibilityKind { case Unspecified case Unit case Assembly case Public } public __abstract class CGTypeDefinition : CGEntity { public var GenericParameters = List<CGGenericParameterDefinition>() public var Name: String public var Members = List<CGMemberDefinition>() public var Visibility: CGTypeVisibilityKind = .Unspecified //in delphi, types with .Unit will be put into implementation section public var Static = false public var Sealed = false public var Abstract = false public var Comment: CGCommentStatement? public var Attributes = List<CGAttribute>() public var Condition: CGConditionalDefine? public init(_ name: String) { Name = name } } public final class CGGlobalTypeDefinition : CGTypeDefinition { private init() { super.init("<Globals>") Static = true } public static lazy let GlobalType = CGGlobalTypeDefinition() } public class CGTypeAliasDefinition : CGTypeDefinition { public var ActualType: CGTypeReference public init(_ name: String, _ actualType: CGTypeReference) { super.init(name) ActualType = actualType } } public class CGBlockTypeDefinition : CGTypeDefinition { public var Parameters = List<CGParameterDefinition>() public var ReturnType: CGTypeReference? public var IsPlainFunctionPointer = false } public class CGEnumTypeDefinition : CGTypeDefinition { public var BaseType: CGTypeReference? } public __abstract class CGClassOrStructTypeDefinition : CGTypeDefinition { public var Ancestors: List<CGTypeReference> public var ImplementedInterfaces: List<CGTypeReference> public var Partial = false public init(_ name: String) { super.init(name) Ancestors = List<CGTypeReference>() ImplementedInterfaces = List<CGTypeReference>() } public init(_ name: String, _ ancestor: CGTypeReference) { super.init(name) Ancestors = List<CGTypeReference>() Ancestors.Add(ancestor) ImplementedInterfaces = List<CGTypeReference>() } public init(_ name: String, _ ancestors: List<CGTypeReference>) { super.init(name) Ancestors = ancestors ImplementedInterfaces = List<CGTypeReference>() } public init(_ name: String, _ ancestor: CGTypeReference, _ interfaces: List<CGTypeReference>) { super.init(name) Ancestors = List<CGTypeReference>() Ancestors.Add(ancestor) ImplementedInterfaces = interfaces } public init(_ name: String, _ ancestors: List<CGTypeReference>, _ interfaces: List<CGTypeReference>) { super.init(name) Ancestors = ancestors ImplementedInterfaces = interfaces } } public class CGClassTypeDefinition : CGClassOrStructTypeDefinition { } public class CGStructTypeDefinition : CGClassOrStructTypeDefinition { } public class CGInterfaceTypeDefinition : CGClassOrStructTypeDefinition { public var InterfaceGuid: Guid?;// legacy delphi only. declaration is : // type interfaceName = interface (ancestorInterface) ['{GUID}'] memberList end; } public class CGExtensionTypeDefinition : CGClassOrStructTypeDefinition { } /* Type members */ public enum CGMemberVisibilityKind { case Unspecified case Private case Unit case UnitOrProtected case UnitAndProtected case Assembly case AssemblyOrProtected case AssemblyAndProtected case Protected case Public case Published /* Delphi only */ } public enum CGMemberVirtualityKind { case None case Virtual case Abstract case Override case Final } public __abstract class CGMemberDefinition: CGEntity { public var Name: String public var Visibility: CGMemberVisibilityKind = .Private public var Virtuality: CGMemberVirtualityKind = .None public var Reintroduced = false public var Static = false public var Overloaded = false public var Locked = false /* Oxygene only */ public var LockedOn: CGExpression? /* Oxygene only */ public var Comment: CGCommentStatement? public var Attributes = List<CGAttribute>() public var Condition: CGConditionalDefine? public var ThrownExceptions: List<CGTypeReference>? // nil means unknown; empty list means known to not throw. public var ImplementsInterface: CGTypeReference? public var ImplementsInterfaceMember: String? public init(_ name: String) { Name = name } } public class CGEnumValueDefinition: CGMemberDefinition { public var Value: CGExpression? public init(_ name: String) { super.init(name) } public convenience init(_ name: String, _ value: CGExpression) { init(name) Value = value } } // // Methods & Co // public enum CGCallingConventionKind { case CDecl /* C++ and Delphi */ case Pascal /* C++ and Delphi */ case StdCall /* C++ and Delphi */ case FastCall /* C++ */ case SafeCall /* C++ and Delphi */ case ClrCall /* VC++ */ case ThisCall /* VC++ */ case VectorCall /* VC++ */ case Register /* C++Builder and Delphi */ } public __abstract class CGMethodLikeMemberDefinition: CGMemberDefinition { public var Parameters = List<CGParameterDefinition>() public var ReturnType: CGTypeReference? public var Inline = false public var External = false public var Empty = false public var Partial = false /* Oxygene only */ public var Async = false /* Oxygene only */ public var Awaitable = false /* C# only */ public var Throws = false /* Swift and Java only */ public var Optional = false /* Swift only */ public var CallingConvention: CGCallingConventionKind? /* Delphi and C++Builder only */ public var Statements: List<CGStatement> public var LocalVariables: List<CGVariableDeclarationStatement>? // Legacy Delphi only. public var LocalTypes: List<CGTypeDefinition>? // Legacy Delphi only. public var LocalMethods: List<CGMethodDefinition>? // Pascal only. public init(_ name: String) { super.init(name) Statements = List<CGStatement>() } public init(_ name: String, _ statements: List<CGStatement>) { super.init(name) Statements = statements } public init(_ name: String, _ statements: CGStatement...) { super.init(name) Statements = statements.ToList() } } public class CGMethodDefinition: CGMethodLikeMemberDefinition { public var GenericParameters: List<CGGenericParameterDefinition>? } public class CGConstructorDefinition: CGMethodLikeMemberDefinition { public var Nullability = CGTypeNullabilityKind.NotNullable /* Swift only. currently. */ public init() { super.init("") } public init(_ name: String, _ statements: List<CGStatement>) { var name = name if name == ".ctor" || name == ".cctor" { name = "" } super.init(name, statements) } convenience public init(_ name: String, _ statements: CGStatement...) { init(name, statements.ToList()) } } public class CGDestructorDefinition: CGMethodLikeMemberDefinition { } public class CGFinalizerDefinition: CGMethodLikeMemberDefinition { public init() { super.init("Finalizer") } public init(_ name: String, _ statements: List<CGStatement>) { super.init("Finalizer", statements) } public init(_ name: String, _ statements: CGStatement...) { super.init("Finalizer", statements.ToList()) } } public class CGCustomOperatorDefinition: CGMethodLikeMemberDefinition { } // // Fields & Co // public __abstract class CGFieldLikeMemberDefinition: CGMemberDefinition { public var `Type`: CGTypeReference? public init(_ name: String) { super.init(name) } public init(_ name: String, _ type: CGTypeReference) { super.init(name) `Type` = type } } public __abstract class CGFieldOrPropertyDefinition: CGFieldLikeMemberDefinition { public var Initializer: CGExpression? public var ReadOnly = false public var WriteOnly = false public var StorageModifier: CGStorageModifierKind = CGStorageModifierKind.Strong } public class CGFieldDefinition: CGFieldOrPropertyDefinition { public var Constant = false public var Volatile = false } public class CGPropertyDefinition: CGFieldOrPropertyDefinition { public var Lazy = false public var Atomic = false public var Dynamic = false public var Default = false public var Parameters = List<CGParameterDefinition>() public var GetStatements: List<CGStatement>? public var SetStatements: List<CGStatement>? public var GetExpression: CGExpression? public var SetExpression: CGExpression? public var GetterVisibility: CGMemberVisibilityKind? public var SetterVisibility: CGMemberVisibilityKind? public init(_ name: String) { super.init(name) } public init(_ name: String, _ type: CGTypeReference) { super.init(name, type) } public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: List<CGStatement>, _ setStatements: List<CGStatement>? = nil) { init(name, type) GetStatements = getStatements SetStatements = setStatements } public convenience init(_ name: String, _ type: CGTypeReference, _ getStatements: CGStatement[], _ setStatements: CGStatement[]? = nil) { init(name, type, getStatements.ToList(), setStatements?.ToList()) } public convenience init(_ name: String, _ type: CGTypeReference, _ getExpression: CGExpression, _ setExpression: CGExpression? = nil) { init(name, type) GetExpression = getExpression SetExpression = setExpression } internal func GetterMethodDefinition(`prefix`: String = "get__") -> CGMethodDefinition? { if let getStatements = GetStatements, let type = `Type` { let method = CGMethodDefinition(`prefix`+Name, getStatements) method.ReturnType = type method.Parameters = Parameters method.Static = Static return method } else if let getExpression = GetExpression, let type = `Type` { let method = CGMethodDefinition(`prefix`+Name) method.ReturnType = type method.Parameters = Parameters method.Statements.Add(getExpression.AsReturnStatement()) method.Static = Static return method } return nil } public static let MAGIC_VALUE_PARAMETER_NAME = "___value___" internal func SetterMethodDefinition(`prefix`: String = "set__") -> CGMethodDefinition? { if let setStatements = SetStatements, let type = `Type` { let method = CGMethodDefinition(`prefix`+Name, setStatements) method.Parameters.Add(Parameters) method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) return method } else if let setExpression = SetExpression, let type = `Type` { let method = CGMethodDefinition(`prefix`+Name) method.Parameters.Add(Parameters) method.Parameters.Add(CGParameterDefinition(MAGIC_VALUE_PARAMETER_NAME, type)) method.Statements.Add(CGAssignmentStatement(setExpression, CGLocalVariableAccessExpression(MAGIC_VALUE_PARAMETER_NAME))) return method } return nil } public var IsShortcutProperty: Boolean { get { return GetStatements == nil && SetStatements == nil && GetExpression == nil && SetExpression == nil } } } public class CGEventDefinition: CGFieldLikeMemberDefinition { public var AddStatements: List<CGStatement>? public var RemoveStatements: List<CGStatement>? //public var RaiseStatements: List<CGStatement>? public init(_ name: String, _ type: CGTypeReference) { super.init(name, type) } public convenience init(_ name: String, _ type: CGTypeReference, _ addStatements: List<CGStatement>, _ removeStatements: List<CGStatement>/*, _ raiseStatements: List<CGStatement>? = nil*/) { init(name, type) AddStatements = addStatements RemoveStatements = removeStatements //RaiseStatements = raiseStatements } internal func AddMethodDefinition() -> CGMethodDefinition? { if let addStatements = AddStatements, let type = `Type` { let method = CGMethodDefinition("add__"+Name, addStatements) method.Parameters.Add(CGParameterDefinition("___value", type)) return method } return nil } internal func RemoveMethodDefinition() -> CGMethodDefinition? { if let removeStatements = RemoveStatements, let type = `Type` { let method = CGMethodDefinition("remove__"+Name, removeStatements) method.Parameters.Add(CGParameterDefinition("___value", type)) return method } return nil } /*internal func RaiseMethodDefinition() -> CGMethodDefinition? { if let raiseStatements = RaiseStatements, type = `Type` { let method = CGMethodDefinition("raise__"+Name, raisetatements) //todo: this would need the same parameters as the block, which we don't have return method } return nil }*/ } public class CGNestedTypeDefinition: CGMemberDefinition { public var `Type`: CGTypeDefinition public init(_ type: CGTypeDefinition) { super.init(type.Name) `Type` = type } } // // Parameters // public enum CGParameterModifierKind { case In case Out case Var case Const case Params } public class CGParameterDefinition : CGEntity { public var Name: String public var ExternalName: String? public var `Type`: CGTypeReference? public var Modifier: CGParameterModifierKind = .In public var DefaultValue: CGExpression? public var Attributes = List<CGAttribute>() public init(_ name: String) { Name = name } public init(_ name: String, _ type: CGTypeReference) { Name = name `Type` = type } } @Obsolete("Use CGParameterDefinition") public typealias CGAnonymousMethodParameterDefinition = CGParameterDefinition public class CGGenericParameterDefinition : CGEntity { public var Constraints = List<CGGenericConstraint>() public var Name: String public var Variance: CGGenericParameterVarianceKind? public init(_ name: String) { Name = name } } public enum CGGenericParameterVarianceKind { case Covariant case Contravariant } public __abstract class CGGenericConstraint : CGEntity { } public class CGGenericHasConstructorConstraint : CGGenericConstraint { } public class CGGenericIsSpecificTypeConstraint : CGGenericConstraint { public var `Type`: CGTypeReference public init(_ type: CGTypeReference) { `Type` = type } } public class CGGenericIsSpecificTypeKindConstraint : CGGenericConstraint { public var Kind: CGGenericConstraintTypeKind public init(_ kind: CGGenericConstraintTypeKind) { Kind = kind } } public enum CGGenericConstraintTypeKind { case Class case Struct case Interface } public class CGAttribute: CGEntity { public var `Type`: CGTypeReference public var Parameters: List<CGCallParameter>? public var Comment: CGSingleLineCommentStatement? public var Condition: CGConditionalDefine? public init(_ type: CGTypeReference) { `Type` = type } public init(_ type: CGTypeReference,_ parameters: List<CGCallParameter>) { `Type` = type Parameters = parameters } public convenience init(_ type: CGTypeReference,_ parameters: CGCallParameter...) { init(type, parameters.ToList()) } }
bsd-3-clause
92ef1c462a3497dd904f81e8e6342c7b
28.291242
191
0.750296
3.706443
false
false
false
false
hulinSun/Better
better/Pods/SnapKit/Source/ConstraintItem.swift
3
2059
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif open class ConstraintItem: Equatable { internal weak var target: AnyObject? internal let attributes: ConstraintAttributes internal init(target: AnyObject?, attributes: ConstraintAttributes) { self.target = target self.attributes = attributes } internal var view: ConstraintView? { return self.target as? ConstraintView } } public func ==(lhs: ConstraintItem, rhs: ConstraintItem) -> Bool { // pointer equality guard lhs !== rhs else { return true } // must both have valid targets and identical attributes guard let target1 = lhs.target, let target2 = rhs.target, target1 === target2 && lhs.attributes == rhs.attributes else { return false } return true }
mit
27831ce188de9407233a05a772a86d7e
32.754098
81
0.696455
4.535242
false
false
false
false
danielmartin/swift
test/IRGen/dead_method.swift
2
1673
// RUN: %target-swift-frontend %s -emit-ir -O | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize // Test to make sure that methods removed by dead code elimination still appear // in the vtable in both the nominal type descriptor and class metadata. // // We should be dropping the implementation, not the actual entry -- it is still // there but filled in with a placeholder. public class Class { public init() {} public func live() {} private func dead() {} } // CHECK-LABEL: @"$s11dead_method5ClassCMn" ={{( dllexport)?}}{{( protected)?}} constant <{{.*}}> <{ // -- metadata accessor // CHECK-SAME: "$s11dead_method5ClassCMa" // -- vtable // CHECK-SAME: %swift.method_descriptor { // CHECK-SAME: i32 1, // CHECK-SAME: @"$s11dead_method5ClassCACycfC" // CHECK-SAME: } // CHECK-SAME: %swift.method_descriptor { // CHECK-SAME: i32 16, // CHECK-SAME: @"$s11dead_method5ClassC4liveyyF" // CHECK-SAME: } // CHECK-SAME: %swift.method_descriptor { i32 16, i32 0 } // CHECK-SAME: }> // CHECK-LABEL: @"$s11dead_method5ClassCMf" = internal global <{{.*}}> <{ // -- destructor // CHECK-SAME: void (%T11dead_method5ClassC*)* @"$s11dead_method5ClassCfD", // -- value witness table // CHECK-SAME: i8** @"$sBoWV", // -- nominal type descriptor // CHECK-SAME: @"$s11dead_method5ClassCMn", // -- ivar destroyer // CHECK-SAME: i8* null, // -- vtable // CHECK-SAME: %T11dead_method5ClassC* (%swift.type*)* @"$s11dead_method5ClassCACycfC", // CHECK-SAME: void (%T11dead_method5ClassC*)* @"$s11dead_method5ClassC4liveyyF", // CHECK-SAME: i8* bitcast (void ()* @swift_deletedMethodError to i8*) // CHECK-SAME: }>
apache-2.0
316af60b1de02d82fd249001c5a01194
30.566038
142
0.670054
3.192748
false
false
false
false
dangnguyenhuu/JSQMessagesSwift
Sources/Categories/UIColor.swift
1
2290
// // UIColor.swift // JSQMessagesViewController // // Created by Sylvain FAY-CHATELARD on 19/08/2015. // Copyright (c) 2015 Dviance. All rights reserved. // import UIKit extension UIColor { public class func jsq_messageBubbleGreenColor() -> UIColor { return UIColor(hue: 130/360, saturation:0.68, brightness:0.84, alpha:1) } public class func jsq_messageBubbleBlueColor() -> UIColor { return UIColor(hue: 210/360, saturation:0.94, brightness:1, alpha:1) } public class func jsq_messageBubbleRedColor() -> UIColor { return UIColor(hue: 0, saturation:0.79, brightness:1, alpha:1) } public class func jsq_messageBubbleLightGrayColor() -> UIColor { return UIColor(hue: 240.0/360.0, saturation:0.02, brightness:0.94, alpha:1) } // MARK: - Utilities public func jsq_colorByDarkeningColorWithValue(_ value: CGFloat) -> UIColor { let totalComponents = self.cgColor.numberOfComponents let isGreyscale = (totalComponents == 2) ? true : false let oldComponents = self.cgColor.components var newComponents: [CGFloat] = [] if isGreyscale { newComponents.append((oldComponents?[0])! - value < 0.0 ? 0.0 : (oldComponents?[0])! - value) newComponents.append((oldComponents?[0])! - value < 0.0 ? 0.0 : (oldComponents?[0])! - value) newComponents.append((oldComponents?[0])! - value < 0.0 ? 0.0 : (oldComponents?[0])! - value) newComponents.append((oldComponents?[1])!) } else { newComponents.append((oldComponents?[0])! - value < 0.0 ? 0.0 : (oldComponents?[0])! - value) newComponents.append((oldComponents?[1])! - value < 0.0 ? 0.0 : (oldComponents?[1])! - value) newComponents.append((oldComponents?[2])! - value < 0.0 ? 0.0 : (oldComponents?[2])! - value) newComponents.append((oldComponents?[3])!) } let colorSpace = CGColorSpaceCreateDeviceRGB() let newColor = CGColor(colorSpace: colorSpace, components: newComponents) if let newColor = newColor { return UIColor(cgColor: newColor) } return self } }
apache-2.0
dfc3480f385d6692777a0c5b2e1a8b35
33.69697
105
0.599127
4.194139
false
false
false
false
codefiesta/GitHubCodingChallenge
CodingChallenge/Classes/Controllers/DiffController.swift
1
7000
// // DiffController.swift // CodingChallenge // // Created by Kevin McKee on 10/11/17. // Copyright © 2017 Procore. All rights reserved. // import GitHub class DiffController: UITableViewController { var activityIndicatorView: UIActivityIndicatorView! let maxCellsLoading: Int = 3 let cellIdentifier = "Cell" let headerIdentifier = "Header" var pullRequest: GitHubPullRequest? var queue = [IndexPath: Bool]() var files = [GitHubPullRequestFile]() let cache = NSCache<NSNumber, FileTableViewCell>() override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print("🙀 Received memory warning") } override func viewDidLoad() { super.viewDidLoad() prepareNavigationItems() prepareActivityIndicatorView() prepareTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) prepareData() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) cache.removeAllObjects() } fileprivate func prepareActivityIndicatorView() { activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicatorView.hidesWhenStopped = true activityIndicatorView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(activityIndicatorView) view.bringSubview(toFront: activityIndicatorView) activityIndicatorView.center() } fileprivate func prepareTableView() { //tableView.prefetchDataSource = self tableView.rowHeight = UITableViewAutomaticDimension tableView.sectionHeaderHeight = 44 tableView.estimatedRowHeight = 100 tableView.tableFooterView = UIView() tableView.register(FileTableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.register(FileTableViewHeaderView.self, forHeaderFooterViewReuseIdentifier: headerIdentifier) } fileprivate func prepareData() { guard let pullRequest = pullRequest else { return } title = "#\(pullRequest.number)" activityIndicatorView.startAnimating() DispatchQueue.global(qos: .background).async { GitHubClient.files(pullRequest) { (data, error) in guard let data = data else { DispatchQueue.main.async { self.activityIndicatorView.stopAnimating() self.dataError() } return } self.queue.removeAll() self.files = data DispatchQueue.main.async { self.tableView.reloadData() self.activityIndicatorView.stopAnimating() } } } } override func numberOfSections(in tableView: UITableView) -> Int { guard !files.isEmpty else { return 0 } return files.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: headerIdentifier) as? FileTableViewHeaderView else { return nil } let file = files[section] header.titleLabel.text = "\(file.name)" header.descLabel.text = "\(file.additions) additions & \(file.deletions) deletions" return header } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard !files.isEmpty else { return 0 } return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cacheKey = NSNumber(value: indexPath.section) // if let cell = cache.object(forKey: cacheKey) { // print("🐙 Found cached cell \(indexPath)") // return cell // } guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? FileTableViewCell, !files.isEmpty else { return UITableViewCell() } // Use the indexPath.section instead of row since I am building section headers for each file let file = files[indexPath.section] cell.prepare(file) // cache.setObject(cell, forKey: cacheKey) return cell } } extension DiffController: UITableViewDataSourcePrefetching { fileprivate func createCell(_ indexPath: IndexPath) { let cacheKey = NSNumber(value: indexPath.section) if cache.object(forKey: cacheKey) == nil, let _ = queue[indexPath] { let file = files[indexPath.section] print("🙊 Prefetching \(file.name)") DispatchQueue.main.async { guard let cell = self.tableView.dequeueReusableCell(withIdentifier: self.cellIdentifier, for: indexPath) as? FileTableViewCell else { return } cell.prepare(file) self.cache.setObject(cell, forKey: cacheKey) self.queue.removeValue(forKey: indexPath) } } else { print("🦄 Already cached") } } func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { guard !files.isEmpty else { return } indexPaths.forEach { (indexPath) in DispatchQueue.global(qos: .background).async { self.queue[indexPath] = true self.createCell(indexPath) } } } func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) { indexPaths.forEach { (indexPath) in DispatchQueue.global(qos: .background).async { print("🙊 Cancelling prefetch \(indexPath)") self.queue.removeValue(forKey: indexPath) } } } } extension DiffController { fileprivate func dataError() { let title = "API Error" let message = "Oops. The request may have timed out. Try again?" let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Try Again", style: .default, handler: { (alert: UIAlertAction) -> Void in self.prepareData() })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (alert: UIAlertAction) -> Void in self.navigationController?.popViewController(animated: true) })) present(alert, animated: true, completion: nil) } }
mit
b571f930d2166e10b64d597cd31bfe11
32.576923
149
0.604238
5.632258
false
false
false
false
optimizely/swift-sdk
Sources/Utils/HandlerRegistryService.swift
1
5315
// // Copyright 2019, 2021, Optimizely, Inc. and contributors // // 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 class HandlerRegistryService { static let shared = HandlerRegistryService() struct ServiceKey: Hashable { var service: String var sdkKey: String? } var binders = AtomicProperty(property: [ServiceKey: BinderProtocol]()) private init() {} func registerBinding(binder: BinderProtocol) { let sk = ServiceKey(service: "\(type(of: binder.service))", sdkKey: binder.sdkKey) binders.performAtomic { prop in if prop[sk] == nil { prop[sk] = binder } } } func injectComponent(service: Any, sdkKey: String? = nil, isReintialize: Bool = false) -> Any? { var result: Any? // service key is shared for all sdkKeys when sdkKey is nil let sk = ServiceKey(service: "\(type(of: service))", sdkKey: sdkKey) let binderToUse = binders.property?[sk] func updateBinder(b: BinderProtocol) { binders.performAtomic { prop in prop[sk] = b } } if var binder = binderToUse { if isReintialize && binder.strategy == .reCreate { binder.instance = binder.factory() result = binder.instance updateBinder(b: binder) } else if let inst = binder.instance, binder.isSingleton { result = inst } else { if !binder.isSingleton { return binder.factory() } let inst = binder.factory() binder.instance = inst result = inst updateBinder(b: binder) } } return result } func reInitializeComponent(service: Any, sdkKey: String? = nil) { _ = injectComponent(service: service, sdkKey: sdkKey, isReintialize: true) } func lookupComponents(sdkKey: String)->[Any]? { if let value = self.binders.property?.keys .filter({$0.sdkKey == sdkKey}) .compactMap({ self.injectComponent(service: self.binders.property![$0]!.service, sdkKey: sdkKey) }) { return value } return nil } } enum ReInitializeStrategy { case reCreate case reUse } protocol BinderProtocol { var sdkKey: String? { get } var strategy: ReInitializeStrategy { get } var service: Any { get } var isSingleton: Bool { get } var factory: () -> Any? { get } var instance: Any? { get set } } struct Binder<T>: BinderProtocol { var sdkKey: String? var service: Any var strategy: ReInitializeStrategy = .reCreate var factory: () -> Any? var isSingleton = false var inst: T? var instance: Any? { get { return inst as Any? } set { if let v = newValue as? T { inst = v } } } init(sdkKey: String? = nil, service: Any, strategy: ReInitializeStrategy = .reCreate, factory: (() -> Any?)? = nil, isSingleton: Bool = false, inst: T? = nil) { self.sdkKey = sdkKey self.service = service self.strategy = strategy self.factory = factory ?? { return nil as Any? } self.isSingleton = isSingleton self.inst = inst } } extension HandlerRegistryService { func injectLogger(sdkKey: String? = nil, isReintialize: Bool = false) -> OPTLogger? { return injectComponent(service: OPTLogger.self, sdkKey: sdkKey, isReintialize: isReintialize) as! OPTLogger? } func injectNotificationCenter(sdkKey: String? = nil, isReintialize: Bool = false) -> OPTNotificationCenter? { return injectComponent(service: OPTNotificationCenter.self, sdkKey: sdkKey, isReintialize: isReintialize) as! OPTNotificationCenter? } func injectDecisionService(sdkKey: String? = nil, isReintialize: Bool = false) -> OPTDecisionService? { return injectComponent(service: OPTDecisionService.self, sdkKey: sdkKey, isReintialize: isReintialize) as! OPTDecisionService? } func injectEventDispatcher(sdkKey: String? = nil, isReintialize: Bool = false) -> OPTEventDispatcher? { return injectComponent(service: OPTEventDispatcher.self, sdkKey: sdkKey, isReintialize: isReintialize) as! OPTEventDispatcher? } func injectDatafileHandler(sdkKey: String? = nil, isReintialize: Bool = false) -> OPTDatafileHandler? { return injectComponent(service: OPTDatafileHandler.self, sdkKey: sdkKey, isReintialize: isReintialize) as! OPTDatafileHandler? } }
apache-2.0
079ea3729e979110889c6098bceb41bb
32.853503
140
0.607526
4.566151
false
false
false
false
khose/EasyPeasy
Sources/UILayoutGuide+Easy.swift
1
3957
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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 /** Operator which applies the attribute given to the `UILayoutGuide` located in the left hand side of it - parameter lhs: `UILayoutGuide` the attributes will apply to - parameter rhs: Attribute applied to the `UILayoutGuide` - returns: The array of `NSLayoutConstraints` applied */ @available (iOS 9.0, *) public func <- (lhs: UILayoutGuide, rhs: Attribute) -> [NSLayoutConstraint] { return lhs <- [rhs] } /** Opeator which applies the attributes given to the `UILayoutGuide` located in the left hand side of it - parameter lhs: `UILayoutGuide` the attributes will apply to - parameter rhs: Attributes applied to the `UILayoutGuide` - returns: The array of `NSLayoutConstraints` applied */ @available (iOS 9.0, *) public func <- (lhs: UILayoutGuide, rhs: [Attribute]) -> [NSLayoutConstraint] { // Create constraints to install var constraintsToInstall: [NSLayoutConstraint] = [] for attribute in rhs { // Create the constraint let newConstraints = attribute.createConstraintsForItem(lhs) constraintsToInstall.appendContentsOf(newConstraints) } // Install these constraints NSLayoutConstraint.activateConstraints(constraintsToInstall) // Return the installed `NSLayoutConstraints` return constraintsToInstall } /** Convenience methods applicable to `UIView` and subclasses */ @available (iOS 9.0, *) public extension UILayoutGuide { /** This method will trigger the recreation of the constraints created using *EasyPeasy* for the current `UILayoutGuide`. `Condition` closures will be evaluated again */ public func easy_reload() { var storedAttributes: [Attribute] = [] // Reload attributes owned by the superview if let attributes = (self.owningView?.attributes.filter { $0.createItem === self }) { storedAttributes.appendContentsOf(attributes) } // Reload attributes owned by the current view let attributes = self.attributes.filter { $0.createItem === self } storedAttributes.appendContentsOf(attributes) // Apply self <- storedAttributes } /** Clears all the constraints applied with EasyPeasy to the current `UILayoutGuide` */ public func easy_clear() { // Remove from the stored Attribute objects of the superview // those which createItem is the current UIView if let owningView = self.owningView { owningView.attributes = owningView.attributes.filter { $0.createItem !== self } } // Remove from the stored Attribute objects of the current view // those which createItem is the current UIView self.attributes = self.attributes.filter { $0.createItem !== self } // Now uninstall those constraints var constraintsToUninstall: [NSLayoutConstraint] = [] // Gather NSLayoutConstraints with self as createItem for constraint in self.constraints { if let attribute = constraint.easy_attribute where attribute.createItem === self { constraintsToUninstall.append(constraint) } } // Deactive the constraints NSLayoutConstraint.deactivateConstraints(constraintsToUninstall) } }
mit
650292bc0301060c7e83b7a9fb4c5dff
36.330189
94
0.673237
5.179319
false
false
false
false
mrdekk/DataKernel
DataKernel/AppDelegate.swift
1
6107
// // AppDelegate.swift // DataKernel // // Created by Denis Malykh on 30/04/16. // Copyright © 2016 mrdekk. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: URL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "ru.mrdekk.DataKernel" in the application's documents Application Support directory. let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = Bundle.main.url(forResource: "DataKernel", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject? dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject? dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
9ebb28fadd5928153015be382b76c2e3
54.009009
291
0.717
5.815238
false
false
false
false
rlisle/ParticleIoT
iOS/Patriot/Patriot/Models/DeviceModel.swift
1
513
// // DeviceModel.swift // Patriot // // Created by Ron Lisle on 5/31/18. // Copyright © 2018 Ron Lisle. All rights reserved. // import UIKit class Device { let name: String var onImage: UIImage var offImage: UIImage var percent: Int init(name: String, percent: Int = 0) { self.name = name self.percent = percent self.onImage = #imageLiteral(resourceName: "LightOn") self.offImage = #imageLiteral(resourceName: "LightOff") } }
mit
304b4e68d4f14f8cb4d74371c0982d3e
19.48
63
0.603516
3.555556
false
false
false
false
cp3hnu/CPImageViewer
Classes/CPImageViewerInteractiveTransition.swift
1
7542
// // InteractiveTransition.swift // CPImageViewer // // Created by ZhaoWei on 16/2/27. // Copyright © 2016年 cp3hnu. All rights reserved. // import UIKit final class CPImageViewerInteractiveTransition: NSObject, UIViewControllerInteractiveTransitioning { /// Be true when Present, and false when Push var isPresented = true /// Whether is interaction in progress. Default is false private(set) var interactionInProgress = false private weak var imageViewer: CPImageViewer! private let distance = UIScreen.main.bounds.height/2 private var shouldCompleteTransition = false private var startInteractive = false private var transitionContext: UIViewControllerContextTransitioning? private var toVC: UIViewController! private var newImageView: UIImageView! private var backgroundView: UIView! private var toImageView: UIImageView! private var fromFrame: CGRect = CGRect.zero private var toFrame: CGRect = CGRect.zero private var style = UIModalPresentationStyle.fullScreen /** Install the pan gesture recognizer on view of *vc* - parameter vc: The *CPImageViewer* view controller */ func wireToImageViewer(_ imageViewer: CPImageViewer) { self.imageViewer = imageViewer let panGesture = UIPanGestureRecognizer(target: self, action: #selector(CPImageViewerInteractiveTransition.handlePan(_:))) panGesture.maximumNumberOfTouches = 1 panGesture.minimumNumberOfTouches = 1 panGesture.delegate = self imageViewer.view.addGestureRecognizer(panGesture) } func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { startInteractive = true self.transitionContext = transitionContext style = transitionContext.presentationStyle toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containerView = transitionContext.containerView let finalFrame = transitionContext.finalFrame(for: toVC) // Solving the error of location of image view after rotating device and returning to previous controller. See CPImageViewer.init() // The overFullScreen style don't need add toVC.view // The style is none when CPImageViewer.style is CPImageViewer.Style.push if style != .overFullScreen { containerView.addSubview(toVC.view) containerView.sendSubviewToBack(toVC.view) toVC.view.frame = finalFrame toVC.view.setNeedsLayout() toVC.view.layoutIfNeeded() } backgroundView = UIView(frame: finalFrame) backgroundView.backgroundColor = UIColor.black containerView.addSubview(backgroundView) let fromImageView: UIImageView! = imageViewer.animationImageView toImageView = (toVC as! CPImageViewerProtocol).animationImageView fromFrame = fromImageView.convert(fromImageView.bounds, to: containerView) toFrame = toImageView.convert(toImageView.bounds, to: containerView) // Solving the error of location of image view in UICollectionView after rotating device and returning to previous controller if let frame = (toVC as! CPImageViewerProtocol).originalFrame { //print("frame = ", frame) toFrame = toVC.view.convert(frame, to: containerView) //print("toFrame = ", toFrame) } newImageView = UIImageView(frame: fromFrame) newImageView.image = fromImageView.image newImageView.contentMode = .scaleAspectFit containerView.addSubview(newImageView) imageViewer.view.alpha = 0.0 } } // MARK: - UIPanGestureRecognizer private extension CPImageViewerInteractiveTransition { @objc func handlePan(_ gesture: UIPanGestureRecognizer) { let currentPoint = gesture.translation(in: imageViewer.view) switch (gesture.state) { case .began: interactionInProgress = true if isPresented { imageViewer.dismiss(animated: true, completion: nil) } else { _ = imageViewer.navigationController?.popViewController(animated: true) } case .changed: updateInteractiveTransition(currentPoint) case .ended, .cancelled: interactionInProgress = false if (!shouldCompleteTransition || gesture.state == .cancelled) { cancelTransition() } else { completeTransition() } default: break } } } // MARK: - Update & Complete & Cancel private extension CPImageViewerInteractiveTransition { func updateInteractiveTransition(_ currentPoint: CGPoint) { guard startInteractive else { return } let percent = min(abs(currentPoint.y) / distance, 1) shouldCompleteTransition = (percent > 0.3) transitionContext?.updateInteractiveTransition(percent) backgroundView.alpha = 1 - percent newImageView.frame.origin.y = fromFrame.origin.y + currentPoint.y if (fromFrame.width > UIScreen.main.bounds.size.width - 60) { newImageView.frame.size.width = fromFrame.width - percent * 60.0 newImageView.frame.origin.x = fromFrame.origin.x + percent * 30.0 } } func completeTransition() { guard startInteractive else { return } let duration = 0.3 UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: { self.newImageView.frame = self.toFrame self.backgroundView.alpha = 0.0 }, completion: { finished in self.startInteractive = false self.newImageView.removeFromSuperview() self.backgroundView.removeFromSuperview() self.toImageView.alpha = 1.0 self.transitionContext?.finishInteractiveTransition() self.transitionContext?.completeTransition(true) }) } func cancelTransition() { guard startInteractive else { return } let duration = 0.3 UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: { self.newImageView.frame = self.fromFrame self.backgroundView.alpha = 1.0 }, completion: { finished in self.startInteractive = false self.newImageView.removeFromSuperview() self.backgroundView.removeFromSuperview() self.imageViewer.view.alpha = 1.0 if self.style != .overFullScreen { self.toVC.view.removeFromSuperview() } self.transitionContext?.cancelInteractiveTransition() self.transitionContext?.completeTransition(false) }) } } // MARK: - UIGestureRecognizerDelegate extension CPImageViewerInteractiveTransition: UIGestureRecognizerDelegate { func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let panGesture = gestureRecognizer as? UIPanGestureRecognizer { let currentPoint = panGesture.translation(in: imageViewer.view) return abs(currentPoint.y) > abs(currentPoint.x) } return true } }
mit
2a58933599d825fe77b6413bd9461ff9
37.661538
139
0.651545
5.768171
false
false
false
false
dymx101/Gamers
Gamers/Views/SearchController.swift
1
16439
// // SeachController.swift // Gamers // // Created by 虚空之翼 on 15/7/20. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit import MJRefresh import Bolts import MBProgressHUD import Social class SearchController: UITableViewController, UITableViewDataSource, UITableViewDelegate { let userDefaults = NSUserDefaults.standardUserDefaults() //用户全局登入信息 var searchContentView: UIView! var searchBackgroundView: UIView! var autocompleteView: UITableView! var searchBarView: UIView! var searchBar: UISearchBar! var tapGesture: UITapGestureRecognizer! // 搜索变量 var videoListData = [Video]() var videoPageOffset = 0 var videoPageCount = 20 var order = "date" var keyword = "" var isNoMoreData: Bool = false //解决控件不能自己判断BUG // 下拉刷新数据 func loadNewData() { keyword = searchBar.text videoPageOffset = 0 VideoBL.sharedSingleton.getSearchVideo(keyword: keyword, offset: videoPageOffset, count: videoPageCount, order: order).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in self!.videoListData = (task.result as? [Video])! self!.videoPageOffset += self!.videoPageCount self!.tableView.reloadData() if self!.videoListData.count < self!.videoPageCount { self?.tableView.footer.noticeNoMoreData() } else { self?.tableView.footer.resetNoMoreData() } return nil }).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in self?.tableView.header.endRefreshing() self!.isNoMoreData = false return nil }) } // 上拉获取更多数据 func loadMoreData() { keyword = searchBar.text VideoBL.sharedSingleton.getSearchVideo(keyword: keyword, offset: videoPageOffset, count: videoPageCount, order: order).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in var newData = (task.result as? [Video])! if newData.isEmpty { self?.tableView.footer.noticeNoMoreData() self!.isNoMoreData = true } else { if newData.count < self!.videoPageCount { self!.isNoMoreData = true } self!.videoListData += newData self!.videoPageOffset += self!.videoPageCount self!.tableView.reloadData() } return nil }).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in if !self!.isNoMoreData { self?.tableView.footer.endRefreshing() } return nil }) } override func viewDidLoad() { super.viewDidLoad() // 上拉下拉刷新功能 self.tableView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData") self.tableView.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "loadMoreData") // 导航栏添加搜索框 searchBarView = UIView(frame: CGRectMake(45, 0, self.view.frame.size.width, 44)) searchBarView.backgroundColor = UIColor.whiteColor() searchBar = UISearchBar(frame: CGRectMake(0, 0, self.view.frame.size.width-85, 44)) searchBar.searchBarStyle = UISearchBarStyle.Minimal searchBar.tintColor = self.navigationController?.navigationBar.barTintColor searchBar.showsBookmarkButton = false //searchBar.showsCancelButton = true searchBar.delegate = self searchBar.tag = 601 //searchBar.becomeFirstResponder() searchBarView.addSubview(searchBar) //self.navigationController?.view.addSubview(searchBarView) self.navigationItem.titleView = searchBarView self.navigationItem.titleView?.sizeToFit() // autocomplete 界面 searchContentView = UIView(frame: CGRectMake(0, 64, self.view.frame.size.width, 160)) searchContentView.backgroundColor = UIColor.whiteColor() searchContentView.layer.borderWidth = 1 searchContentView.layer.borderColor = UIColor.grayColor().CGColor autocompleteView = UITableView(frame: CGRectMake(0, 0, self.view.frame.size.width, 160)) autocompleteView.delegate = self autocompleteView.dataSource = self autocompleteView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "autocompleteCell") searchContentView.addSubview(autocompleteView) // 灰色背景 searchBackgroundView = UIView(frame: CGRectMake(0, 224, self.view.frame.size.width, self.view.frame.size.height-224)) searchBackgroundView.backgroundColor = UIColor.grayColor() searchBackgroundView.alpha = 0.7 // TODO: 搜索关键字自动查询 //self.navigationController?.view.addSubview(searchContentView) //self.navigationController?.view.addSubview(searchBackgroundView) // 默认隐藏搜索界面 searchContentView.hidden = true searchBackgroundView.hidden = true // 设置tableview顶部不在导航栏下 self.edgesForExtendedLayout = UIRectEdge.None // 隐藏底部工具栏 //self.tabBarController!.tabBar.hidden = true // UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in // searchContentView.frame.size.height = 224 // // }, completion: nil) // 子页面PlayerView的导航栏返回按钮文字,可为空(去掉按钮文字) self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) // 删除多余的分割线 self.tableView.tableFooterView = UIView(frame: CGRectZero) // cell分割线边距,ios8处理 if self.tableView.respondsToSelector("setSeparatorInset:") { self.tableView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5) } if self.tableView.respondsToSelector("setLayoutMargins:") { self.tableView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5) } if autocompleteView.respondsToSelector("setSeparatorInset:") { autocompleteView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5) } if autocompleteView.respondsToSelector("setLayoutMargins:") { autocompleteView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5) } } // 卸载界面 override func viewWillDisappear(animated: Bool) { // 返回等切换页面,删除搜索界面 searchContentView.removeFromSuperview() searchBackgroundView.removeFromSuperview() } // 跳转传值 override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // 定义列表控制器 var playerViewController = segue.destinationViewController as! PlayerViewController // 提取选中的游戏视频,把值传给列表页面 var indexPath = self.tableView.indexPathForSelectedRow()! playerViewController.videoData = videoListData[indexPath.row] } override func viewWillAppear(animated: Bool) { // 播放页面返回后,重置导航条的透明属性,//todo:image_1.jpg需求更换下 self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "image_1.jpg"),forBarMetrics: UIBarMetrics.CompactPrompt) self.navigationController?.navigationBar.shadowImage = UIImage(named: "image_1.jpg") self.navigationController?.navigationBar.translucent = false } override func dismissViewControllerAnimated(flag: Bool, completion: (() -> Void)?) { searchBar.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - 表格代理协议 extension SearchController: UITableViewDataSource, UITableViewDelegate { // 表格行高度 override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch tableView { case autocompleteView: return 32 default: if videoListData.isEmpty { return view.frame.size.height } else { return 100 } } } // 行数 override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if videoListData.isEmpty { return 1 } else { return videoListData.count } } // 单元格内容 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch tableView { case autocompleteView: let cell = tableView.dequeueReusableCellWithIdentifier("autocompleteCell", forIndexPath: indexPath) as! UITableViewCell return cell default: if videoListData.isEmpty { var cell = tableView.dequeueReusableCellWithIdentifier("SearchVideoNoDataCell", forIndexPath: indexPath) as! UITableViewCell return cell } else { var cell = tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath) as! SearchCell cell.setVideo(self.videoListData[indexPath.row]) cell.delegate = self return cell } } } // cell分割线的边距 override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("setSeparatorInset:") { cell.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5) } if cell.respondsToSelector("setLayoutMargins:") { cell.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5) } } } // MARK: - 搜索代理 extension SearchController: UISearchBarDelegate { // 第一响应者时触发 func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { // 显示搜索界面 searchContentView.hidden = false searchBackgroundView.hidden = false //self.tableView.addGestureRecognizer(tapGesture) return true } // 点击搜索 func searchBarSearchButtonClicked(searchBar: UISearchBar) { let hub = MBProgressHUD.showHUDAddedTo(self.navigationController!.view, animated: true) hub.labelText = "加載中..." keyword = searchBar.text videoPageOffset = 0 VideoBL.sharedSingleton.getSearchVideo(keyword: keyword, offset: videoPageOffset, count: videoPageCount, order: order).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in self!.videoListData = (task.result as? [Video])! self!.videoPageOffset += self!.videoPageCount self!.tableView.reloadData() if self!.videoListData.count < self!.videoPageCount { self?.tableView.footer.noticeNoMoreData() } else { self?.tableView.footer.resetNoMoreData() } return nil }).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in //self?.tableView.footer.endRefreshing() MBProgressHUD.hideHUDForView(self!.navigationController!.view, animated: true) return nil }) // 隐藏搜索界面 searchContentView.hidden = true searchBackgroundView.hidden = true // 搜索提交后,收起键盘 searchBar.resignFirstResponder() } // 点击取消时触发事件 func searchBarCancelButtonClicked(searchBar: UISearchBar) { //println("canncel") } // 搜索内容发生变化时触发事件 func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // 显示搜索界面 searchContentView.hidden = false searchBackgroundView.hidden = false } // 搜索范围标签变化时 func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { } } // MARK: - 表格行Cell代理 extension SearchController: MyCellDelegate { // 隐藏键盘 func hideKeyboard(cell: UITableViewCell) { searchBar.resignFirstResponder() } // 分享按钮 func clickCellButton(sender: UITableViewCell) { var index: NSIndexPath = self.tableView.indexPathForCell(sender)! //println("表格行:\(index.row)") var video = self.videoListData[index.row] // 退出 var actionSheetController: UIAlertController = UIAlertController() actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: UIAlertActionStyle.Cancel) { (alertAction) -> Void in //code }) // 关注频道 actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Follow", comment: "追随"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in if self.userDefaults.boolForKey("isLogin") { UserBL.sharedSingleton.setFollow(channelId: video.ownerId) } else { var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Please Login", comment: "请先登入"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } }) // 分享到Facebook actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Facebook", comment: "分享到Facebook"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook) slComposerSheet.setInitialText(video.videoTitle) slComposerSheet.addImage(UIImage(named: video.imageSource)) slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)")) self.presentViewController(slComposerSheet, animated: true, completion: nil) SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in if result == .Done { var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } } }) // 分享到Twitter actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Twitter", comment: "分享到Twitter"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter) slComposerSheet.setInitialText(video.videoTitle) slComposerSheet.addImage(UIImage(named: video.imageSource)) slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)")) self.presentViewController(slComposerSheet, animated: true, completion: nil) slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in if result == .Done { var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定")) alertView.show() } } }) // 显示Sheet self.presentViewController(actionSheetController, animated: true, completion: nil) } }
apache-2.0
50b719c92cd521c8d0142bab6a44a4b7
38.946565
206
0.637111
5.238238
false
false
false
false
benlangmuir/swift
benchmark/single-source/DictTest2.swift
10
1988
//===--- DictTest2.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let benchmarks = [ BenchmarkInfo(name: "Dictionary2", runFunction: run_Dictionary2, tags: [.validation, .api, .Dictionary], legacyFactor: 5), BenchmarkInfo(name: "Dictionary2OfObjects", runFunction: run_Dictionary2OfObjects, tags: [.validation, .api, .Dictionary], legacyFactor: 5), ] @inline(never) public func run_Dictionary2(_ n: Int) { let size = 500 let ref_result = 199 var res = 0 for _ in 1...n { var x: [String: Int] = [:] for i in 1...size { x[String(i, radix:16)] = i } res = 0 for i in 0..<size { let i2 = size-i if x[String(i2)] != nil { res += 1 } } if res != ref_result { break } } check(res == ref_result) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } func hash(into hasher: inout Hasher) { hasher.combine(value) } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_Dictionary2OfObjects(_ n: Int) { let size = 500 let ref_result = 199 var res = 0 for _ in 1...n { var x: [Box<String>:Box<Int>] = [:] for i in 1...size { x[Box(String(i, radix:16))] = Box(i) } res = 0 for i in 0..<size { let i2 = size-i if x[Box(String(i2))] != nil { res += 1 } } if res != ref_result { break } } check(res == ref_result) }
apache-2.0
ae05bc3e8873a115fac01a5f00e00471
20.846154
80
0.542254
3.556351
false
false
false
false
Douvi/SlideMenuDovi
SlideMenu/Extension/UIViewController+SilderMenu.swift
1
2696
// // UIViewController+SilderMenu.swift // carrefour // // Created by Edouard Roussillon on 5/31/16. // Copyright © 2016 Concrete Solutions. All rights reserved. // import UIKit extension UIViewController { public func slideMenuController() -> SliderMenuViewController? { var viewController: UIViewController? = self while viewController != nil { if let slider = viewController as? SliderMenuViewController { return slider } viewController = viewController?.parentViewController } return nil } public func toggleSlideMenuLeft() { slideMenuController()?.toggleSlideMenuLeft() } public func toggleSlideMenuRight() { slideMenuController()?.toggleSlideMenuRight() } public func openSlideMenuLeft() { slideMenuController()?.openSlideMenuLeft() } public func openSlideMenuRight() { slideMenuController()?.openSlideMenuRight() } public func closeSlideMenuLeft() { slideMenuController()?.closeSlideMenuLeft() } public func closeSlideMenuRight() { slideMenuController()?.closeSlideMenuRight() } public func isSlideMenuLeftOpen() -> Bool { return slideMenuController()?.isSlideMenuLeftOpen() ?? false } public func isSlideMenuRightOpen() -> Bool { return slideMenuController()?.isSlideMenuRightOpen() ?? false } // Please specify if you want menu gesuture give priority to than targetScrollView public func addPriorityToMenuGesuture(targetScrollView: UIScrollView) { if let slideControlelr = slideMenuController() { guard let recognizers = slideControlelr.view.gestureRecognizers else { return } for recognizer in recognizers where recognizer is UIPanGestureRecognizer { targetScrollView.panGestureRecognizer.requireGestureRecognizerToFail(recognizer) } } } public func addPriorityToMenuGesuture() { if let slideControlelr = slideMenuController() { guard let recognizers = slideControlelr.view.gestureRecognizers else { return } for recognizer in recognizers { self.view.addGestureRecognizer(recognizer) } } } public func addPriorityToMenuGesuturePage(pageController: UIPageViewController) { if let item = pageController.view.subviews.filter ({ $0 is UIScrollView }).first as? UIScrollView { self.addPriorityToMenuGesuture(item) } } }
mit
d3c00187a50323bbce5c3801401ce445
29.988506
107
0.63525
5.833333
false
false
false
false
avaidyam/Parrot
Mocha/KeyValueStore.swift
1
8007
import Foundation import Security // FIXME: Cannot import this here! /* TODO: Switch KeyValueStore to strongly-typed struct instead of String for Key. */ /* TODO: Find a way to do SecKeychain* snapshot(). */ /* TODO: Switch to SecItem API instead of SecKeychain API. */ /* TODO: Use kSecAttrSynchronizable for iCloud Keychain. */ /// A KeyValueStore is a container layer that stores values for given keys /// and supports specific application-defined or special/protected domains. public protocol KeyValueStore { subscript(key: String) -> Any? { get set } subscript(key: String, domain domain: String) -> Any? { get set } func snapshot() -> [String : Any] func snapshot(domain: String) -> [String : Any] } /// A KeyValueStore that encodes its contents in the OS defaults database. public final class SettingsStore: KeyValueStore { fileprivate init() {} /// A special protected SettingsStore domain. /// In case this is used as the domain for the SettingsStore, it will read from /// the system-wide KeyValueStore internally. It cannot be used to set values. public static let globalDomain = UserDefaults.globalDomain /// A special protected SettingsStore domain. /// In the case this is used as the domain for the SettingsStore, it will read /// and write from the user's global iCloud KeyValueStore. public static let ubiquitousDomain = "SettingsStore.UbiquitousKeyValueDomain" /// Set or get a key's value with the default domain (global search list). /// Note: setting a key's value to nil will delete the key from the store. public subscript(key: String) -> Any? { get { return UserDefaults.standard.value(forKey: key) } set (value) { UserDefaults.standard.setValue(value, forKey: key) } } /// Set or get a key's value with a custom specified domain. /// Note: setting a key's value to nil will delete the key from the store. public subscript(key: String, domain domain: String) -> Any? { get { if domain == SettingsStore.globalDomain { return UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain)?[key] } else if domain == SettingsStore.ubiquitousDomain { NSUbiquitousKeyValueStore.default.synchronize() return NSUbiquitousKeyValueStore.default.object(forKey: key) } else { return UserDefaults(suiteName: domain)?.value(forKey: key) } } set (value) { if domain == SettingsStore.globalDomain { // FIXME: Unsupported. } else if domain == SettingsStore.ubiquitousDomain { NSUbiquitousKeyValueStore.default.set(value, forKey: key) NSUbiquitousKeyValueStore.default.synchronize() } else { UserDefaults(suiteName: domain)?.setValue(value, forKey: key) } } } public func snapshot() -> [String : Any] { return UserDefaults.standard.dictionaryRepresentation() } public func snapshot(domain: String) -> [String : Any] { if domain == SettingsStore.globalDomain { return UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain) ?? [:] } else if domain == SettingsStore.ubiquitousDomain { NSUbiquitousKeyValueStore.default.synchronize() return NSUbiquitousKeyValueStore.default.dictionaryRepresentation } else { return UserDefaults(suiteName: domain)?.dictionaryRepresentation() ?? [:] } } } /// A KeyValueStore that encodes its contents in a PropertyList file. /// The domain maps to a file URL, and if none is provided, the read-only /// Bundle "Info.plist" domain is used (writing to it will cause an assertion). public final class FileStore: KeyValueStore { private let infoPlist = Bundle.main.bundlePath + "/Contents/Info.plist" /// Set or get a file key's value with the default domain (the Info plist). /// Note: this domain cannot be written to. public subscript(key: String) -> Any? { get { return self[key, domain: infoPlist] } set { fatalError("Cannot write to the default FileStore domain.") } } /// Set or get a file key's value with a custom domain (as a file URL). /// Note: setting a key's value to nil will delete the key from the store. public subscript(key: String, domain domain: String) -> Any? { get { return NSDictionary(contentsOfFile: domain)?[key] } set { if let dict = NSDictionary(contentsOfFile: domain) { dict.setValue(newValue, forKey: key) dict.write(toFile: domain, atomically: true) } } } public func snapshot() -> [String : Any] { return snapshot(domain: infoPlist) } public func snapshot(domain: String) -> [String : Any] { return (NSDictionary(contentsOfFile: domain) as? [String: Any]) ?? [:] } } /// A KeyValueStore that securely encodes its contents in the OS keychain. @available(macOS 10.2, *) public final class SecureSettingsStore: KeyValueStore { fileprivate init() {} private var _defaultDomain = Bundle.main.bundleIdentifier ?? "SecureSettings:ERR" /// Set or get a secure key's value with the default domain (the bundle identifier). /// Note: setting a key's value to nil will delete the key from the store. public subscript(key: String) -> Any? { get { return self[key, domain: _defaultDomain] } set (value) { self[key, domain: _defaultDomain] = value } } /// Set or get a secure key's value with a custom specified domain. /// Note: setting a key's value to nil will delete the key from the store. public subscript(key: String, domain domain: String) -> Any? { get { var passwordLength: UInt32 = 0 var passwordPtr: UnsafeMutableRawPointer? = nil let status = SecKeychainFindGenericPassword(nil, UInt32(domain.utf8.count), domain, UInt32(key.utf8.count), key, &passwordLength, &passwordPtr, nil) if status == OSStatus(errSecSuccess) { return NSString(bytes: passwordPtr!, length: Int(passwordLength), encoding: String.Encoding.utf8.rawValue) } else { return nil } } set (_value) { if _value == nil { var itemRef: SecKeychainItem? = nil let status = SecKeychainFindGenericPassword(nil, UInt32(domain.utf8.count), domain, UInt32(key.utf8.count), key, nil, nil, &itemRef) if let item = itemRef , status == OSStatus(errSecSuccess) { SecKeychainItemDelete(item) } } else { guard let value = _value as? String else { return } SecKeychainAddGenericPassword(nil, UInt32(domain.utf8.count), domain, UInt32(key.utf8.count), key, UInt32(value.utf8.count), value, nil) } } } public func snapshot() -> [String : Any] { return snapshot(domain: _defaultDomain) } public func snapshot(domain: String) -> [String : Any] { NSLog("SecureSettingsStore: SecKeychain cannot be queried for a snapshot!") return [:] } } /// Aliased singleton for SettingsStore. //public let Settings = SettingsStore() /// Aliased singleton for SecureSettingsStore. @available(macOS 10.2, *) public let SecureSettings = SecureSettingsStore()
mpl-2.0
8e50e3850adae6a216e9ddc4db069a11
40.921466
100
0.608218
4.682456
false
false
false
false
rivetlogic/liferay-mobile-directory-ios
Liferay-Screens/Source/DDL/FormScreenlet/ServerOperations/LiferayDDLFormUploadOperation.swift
1
3030
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library 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 Lesser General Public License for more * details. */ import UIKit public class LiferayDDLFormUploadOperation: ServerOperation, LRCallback, LRProgressDelegate { var document: DDLFieldDocument? var filePrefix: String? var repositoryId: Int64? var folderId: Int64? var onUploadedBytes: ((DDLFieldDocument, UInt, Int64, Int64) -> Void)? var uploadResult: [String:AnyObject]? internal override var hudFailureMessage: HUDMessage? { return (LocalizedString("ddlform-screenlet", "uploading-error", self), details: nil) } internal var formData: DDLFormData { return screenlet.screenletView as! DDLFormData } private var requestSemaphore: dispatch_semaphore_t? //MARK: ServerOperation override func validateData() -> Bool { if document == nil { return false } if document!.currentValue == nil { return false } if filePrefix == nil { return false } if repositoryId == nil { return false } if folderId == nil { return false } return true } override internal func doRun(#session: LRSession) { session.callback = self let fileName = "\(filePrefix!)\(NSUUID().UUIDString)" var size:Int64 = 0 let stream = document!.getStream(&size) let uploadData = LRUploadData( inputStream: stream, length: size, fileName: fileName, mimeType: document!.mimeType) uploadData.progressDelegate = self let service = LRDLAppService_v62(session: session) requestSemaphore = dispatch_semaphore_create(0) service.addFileEntryWithRepositoryId(repositoryId!, folderId: folderId!, sourceFileName: fileName, mimeType: document!.mimeType, title: fileName, description: LocalizedString("ddlform-screenlet", "upload-metadata-description", self), changeLog: LocalizedString("ddlform-screenlet", "upload-metadata-changelog", self), file: uploadData, serviceContext: nil, error: &lastError) dispatch_semaphore_wait(requestSemaphore!, DISPATCH_TIME_FOREVER) } //MARK: LRProgressDelegate public func onProgressBytes(bytes: UInt, sent: Int64, total: Int64) { document!.uploadStatus = .Uploading(UInt(sent), UInt(total)) onUploadedBytes?(document!, bytes, sent, total) } //MARK: LRCallback public func onFailure(error: NSError?) { lastError = error uploadResult = nil dispatch_semaphore_signal(requestSemaphore!) } public func onSuccess(result: AnyObject?) { lastError = nil uploadResult = result as? [String:AnyObject] dispatch_semaphore_signal(requestSemaphore!) } }
gpl-3.0
65b76bb0795c85a3cc76c4134c44e9c1
23.836066
93
0.732013
3.726937
false
false
false
false
borglab/SwiftFusion
Sources/BeeDataset/BeeVideo.swift
1
4236
// Copyright 2020 The SwiftFusion 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 _Differentiation import Foundation import ModelSupport import SwiftFusion import TensorFlow /// A video of bees, with tracking labels. public struct BeeVideo { /// The frames of the video, as tensors of shape `[height, width, channels]`. public var frames: [Tensor<Double>] /// Labeled tracks for this video. public var tracks: [[BeeTrackPoint]] var directory: URL? } /// The location of a bee within a frame of a `BeeVideo`. public struct BeeTrackPoint { /// The frame within the video. public var frameIndex: Int /// The location of the bee. public var location: OrientedBoundingBox } extension BeeVideo { /// Creates an instance from the video named `videoName`. public init?(videoName: String, deferLoadingFrames: Bool = false) { let dataset = Self.downloadDatasetIfNotPresent() self.init(directory: dataset.appendingPathComponent(videoName), deferLoadingFrames: deferLoadingFrames) } /// Creates an instance from the data in the given `directory`. /// /// The directory must contain: /// - Frames named "frame0.jpeg", "frame1.jpeg", etc, consecutively. /// - Zero or more tracks named "track0.txt", "track1.txt", etc, consecutively. /// /// The format of a track file is: /// - A line "<height> <width>" specifying the size of the bounding boxes in the track. /// - Followed by arbitrarily many lines "<frame index> <x> <y> <theta>". public init?(directory: URL, deferLoadingFrames: Bool = false) { self.frames = [] self.tracks = [] self.directory = directory while let frame = loadFrame(self.frames.count) { self.frames.append(frame) } func loadTrack(_ index: Int) -> [BeeTrackPoint]? { let path = directory.appendingPathComponent("track\(index).txt") guard let track = try? String(contentsOf: path) else { return nil } let lines = track.split(separator: "\n") let bbSize = lines.first!.split(separator: " ") let bbHeight = Int(bbSize[0])! let bbWidth = Int(bbSize[1])! return lines.dropFirst().map { line in let split = line.split(separator: " ") return BeeTrackPoint( frameIndex: Int(split[0])!, location: OrientedBoundingBox( center: Pose2( Rot2(Double(split[3])!), Vector2(Double(split[1])!, Double(split[2])!)), rows: bbHeight, cols: bbWidth)) } } while let track = loadTrack(self.tracks.count) { self.tracks.append(track) } } public func loadFrame(_ index: Int) -> Tensor<Double>? { let path = self.directory!.appendingPathComponent("frame\(index).jpeg") guard FileManager.default.fileExists(atPath: path.path) else { return nil } return Tensor<Double>(Image(contentsOf: path).tensor) } private static func downloadDatasetIfNotPresent() -> URL { let downloadDir = DatasetUtilities.defaultDirectory.appendingPathComponent( "bee_videos", isDirectory: true) let directoryExists = FileManager.default.fileExists(atPath: downloadDir.path) let contentsOfDir = try? FileManager.default.contentsOfDirectory(atPath: downloadDir.path) let directoryEmpty = (contentsOfDir == nil) || (contentsOfDir!.isEmpty) guard !directoryExists || directoryEmpty else { return downloadDir } let remoteRoot = URL( string: "https://storage.googleapis.com/swift-tensorflow-misc-files/beetracking")! let _ = DatasetUtilities.downloadResource( filename: "bee_videos", fileExtension: "tar.gz", remoteRoot: remoteRoot, localStorageDirectory: downloadDir ) return downloadDir } }
apache-2.0
0b8231b9ba589a1f7ecb58587e7da25e
35.834783
107
0.689093
4.169291
false
false
false
false
rxwei/cuda-swift
Package.swift
1
1101
import PackageDescription let package = Package( name: "CUDA", targets: [ Target(name: "CUDADriver"), Target(name: "CUDARuntime", dependencies: [ "CUDADriver" ]), Target(name: "NVRTC", dependencies: [ "CUDADriver" ]), Target(name: "CuBLAS", dependencies: [ "CUDADriver", "CUDARuntime" ]), Target(name: "Warp", dependencies: [ "CUDADriver", "CUDARuntime", "CuBLAS", "NVRTC" ]) ], dependencies: [ .Package(url: "https://github.com/rxwei/CCUDA", majorVersion: 1, minor: 5) ] ) /// Product specification works differently (more formally) in Swift 3.1+ #if (os(Linux) || os(macOS)) && !swift(>=3.1) let dylib = Product( name: "CUDA", type: .Library(.Dynamic), modules: [ "CUDADriver", "CUDARuntime", "NVRTC", "CuBLAS", ] ) products.append(dylib) let a = Product( name: "CUDA", type: .Library(.Static), modules: [ "CUDADriver", "CUDARuntime", "NVRTC", "CuBLAS", ] ) products.append(a) let warpA = Product( name: "Warp", type: .Library(.Static), modules: [ "Warp" ] ) products.append(warpA) #endif
mit
a9da71f7344f6740a0c8193afeadb728
25.853659
94
0.610354
2.951743
false
false
false
false
szweier/SZUtilities
SZUtilities/Classes/UIView/Animations/UIView+Animations.swift
1
652
public extension UIView { @discardableResult public func szBeginPulsing(withToValue toValue: NSNumber) -> CABasicAnimation { let animation: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale") animation.duration = 1.0 animation.toValue = toValue animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) animation.autoreverses = true animation.repeatCount = FLT_MAX layer.add(animation, forKey: "szPulseAnimation") return animation } public func szEndPulsing() { layer.removeAnimation(forKey: "szPulseAnimation") } }
mit
eb7404dd34a7699211767a5b4186a7e8
37.352941
102
0.710123
5.433333
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/HotSpot.swift
1
1073
// // HotSpot.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML HotSpot /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="hotSpot" type="kml:vec2Type"/> public class HotSpot:SPXMLElement, HasXMLElementValue { public static var elementName: String = "hotSpot" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as IconStyle: v.value.hotSpot = self default: break } } } } public var value: Vec2Type = Vec2Type() // attributes public required init(attributes:[String:String]){ self.value = Vec2Type(attributes: attributes) super.init(attributes: attributes) } }
mit
bbbc2aa222c540c1bbfce9bd557d8334
28.028571
71
0.598425
3.708029
false
false
false
false
nalexn/ViewInspector
Sources/ViewInspector/SwiftUI/Toggle.swift
1
4249
import SwiftUI @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension ViewType { struct Toggle: KnownViewType { public static var typePrefix: String = "Toggle" } } // MARK: - Extraction from SingleViewContent parent @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View: SingleViewContent { func toggle() throws -> InspectableView<ViewType.Toggle> { return try .init(try child(), parent: self) } } // MARK: - Extraction from MultipleViewContent parent @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View: MultipleViewContent { func toggle(_ index: Int) throws -> InspectableView<ViewType.Toggle> { return try .init(try child(at: index), parent: self, index: index) } } // MARK: - Non Standard Children @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) extension ViewType.Toggle: SupplementaryChildrenLabelView { static var labelViewPath: String { if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) { return "label" } else { return "_label" } } } // MARK: - Custom Attributes @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView where View == ViewType.Toggle { func labelView() throws -> InspectableView<ViewType.ClassifiedView> { return try View.supplementaryChildren(self).element(at: 0) .asInspectableView(ofType: ViewType.ClassifiedView.self) } func tap() throws { try guardIsResponsive() try isOnBinding().wrappedValue.toggle() } func isOn() throws -> Bool { return try isOnBinding().wrappedValue } private func isOnBinding() throws -> Binding<Bool> { if #available(iOS 16.0, macOS 13.0, tvOS 16.0, watchOS 9.0, *) { throw InspectionError.notSupported( """ Toggle's tap() and isOn() are currently unavailable for \ inspection on iOS 16. Situation may change with a minor \ OS version update. In the meanwhile, please add XCTSkip \ for iOS 16 and use an earlier OS version for testing. """) } if let binding = try? Inspector .attribute(label: "__isOn", value: content.view, type: Binding<Bool>.self) { return binding } return try Inspector .attribute(label: "_isOn", value: content.view, type: Binding<Bool>.self) } } // MARK: - Global View Modifiers @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension InspectableView { func toggleStyle() throws -> Any { let modifier = try self.modifier({ modifier -> Bool in return modifier.modifierType.hasPrefix("ToggleStyleModifier") }, call: "toggleStyle") return try Inspector.attribute(path: "modifier|style", value: modifier) } } // MARK: - ToggleStyle inspection @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) public extension ToggleStyle { func inspect(isOn: Bool) throws -> InspectableView<ViewType.ClassifiedView> { let config = ToggleStyleConfiguration(isOn: isOn) let view = try makeBody(configuration: config).inspect() return try .init(view.content, parent: nil, index: nil) } } // MARK: - Style Configuration initializer @available(iOS 13.0, macOS 10.15, tvOS 13.0, *) internal extension ToggleStyleConfiguration { private struct Allocator17 { let isOn: Binding<Bool> init(isOn: Bool) { self.isOn = .init(wrappedValue: isOn) } } private struct Allocator42 { let isOn: Binding<Bool> let isMixed = Binding<Bool>(wrappedValue: false) let flag: Bool = false init(isOn: Bool) { self.isOn = .init(wrappedValue: isOn) } } init(isOn: Bool) { switch MemoryLayout<Self>.size { case 17: self = unsafeBitCast(Allocator17(isOn: isOn), to: Self.self) case 42: self = unsafeBitCast(Allocator42(isOn: isOn), to: Self.self) default: fatalError(MemoryLayout<Self>.actualSize()) } } }
mit
1e8a2939318bca7f3e17c2031462e066
30.474074
88
0.621323
4.194472
false
false
false
false
fastred/IBAnalyzer
Pods/SourceKittenFramework/Source/SourceKittenFramework/Request.swift
1
26528
// // Request.swift // SourceKitten // // Created by JP Simard on 2015-01-03. // Copyright (c) 2015 JP Simard. All rights reserved. // import Dispatch import Foundation #if SWIFT_PACKAGE import SourceKit #endif // swiftlint:disable file_length // This file could easily be split up public protocol SourceKitRepresentable { func isEqualTo(_ rhs: SourceKitRepresentable) -> Bool } extension Array: SourceKitRepresentable {} extension Dictionary: SourceKitRepresentable {} extension String: SourceKitRepresentable {} extension Int64: SourceKitRepresentable {} extension Bool: SourceKitRepresentable {} extension SourceKitRepresentable { public func isEqualTo(_ rhs: SourceKitRepresentable) -> Bool { switch self { case let lhs as [SourceKitRepresentable]: for (idx, value) in lhs.enumerated() { if let rhs = rhs as? [SourceKitRepresentable], rhs[idx].isEqualTo(value) { continue } return false } return true case let lhs as [String: SourceKitRepresentable]: for (key, value) in lhs { if let rhs = rhs as? [String: SourceKitRepresentable], let rhsValue = rhs[key], rhsValue.isEqualTo(value) { continue } return false } return true case let lhs as String: return lhs == rhs as? String case let lhs as Int64: return lhs == rhs as? Int64 case let lhs as Bool: return lhs == rhs as? Bool default: fatalError("Should never happen because we've checked all SourceKitRepresentable types") } } } private func fromSourceKit(_ sourcekitObject: sourcekitd_variant_t) -> SourceKitRepresentable? { switch sourcekitd_variant_get_type(sourcekitObject) { case SOURCEKITD_VARIANT_TYPE_ARRAY: var array = [SourceKitRepresentable]() _ = withUnsafeMutablePointer(to: &array) { arrayPtr in sourcekitd_variant_array_apply_f(sourcekitObject, { index, value, context in if let value = fromSourceKit(value), let context = context { let localArray = context.assumingMemoryBound(to: [SourceKitRepresentable].self) localArray.pointee.insert(value, at: Int(index)) } return true }, arrayPtr) } return array case SOURCEKITD_VARIANT_TYPE_DICTIONARY: var dict = [String: SourceKitRepresentable]() _ = withUnsafeMutablePointer(to: &dict) { dictPtr in sourcekitd_variant_dictionary_apply_f(sourcekitObject, { key, value, context in if let key = String(sourceKitUID: key!), let value = fromSourceKit(value), let context = context { let localDict = context.assumingMemoryBound(to: [String: SourceKitRepresentable].self) localDict.pointee[key] = value } return true }, dictPtr) } return dict case SOURCEKITD_VARIANT_TYPE_STRING: return String(bytes: sourcekitd_variant_string_get_ptr(sourcekitObject)!, length: sourcekitd_variant_string_get_length(sourcekitObject)) case SOURCEKITD_VARIANT_TYPE_INT64: return sourcekitd_variant_int64_get_value(sourcekitObject) case SOURCEKITD_VARIANT_TYPE_BOOL: return sourcekitd_variant_bool_get_value(sourcekitObject) case SOURCEKITD_VARIANT_TYPE_UID: return String(sourceKitUID: sourcekitd_variant_uid_get_value(sourcekitObject)!) case SOURCEKITD_VARIANT_TYPE_NULL: return nil default: fatalError("Should never happen because we've checked all SourceKitRepresentable types") } } /// Lazily and singly computed Void constants to initialize SourceKit once per session. private let initializeSourceKit: Void = { sourcekitd_initialize() }() private let initializeSourceKitFailable: Void = { initializeSourceKit sourcekitd_set_notification_handler { response in if !sourcekitd_response_is_error(response!) { fflush(stdout) fputs("sourcekitten: connection to SourceKitService restored!\n", stderr) sourceKitWaitingRestoredSemaphore.signal() } sourcekitd_response_dispose(response!) } }() /// dispatch_semaphore_t used when waiting for sourcekitd to be restored. private var sourceKitWaitingRestoredSemaphore = DispatchSemaphore(value: 0) private extension String { /** Cache SourceKit requests for strings from UIDs - returns: Cached UID string if available, nil otherwise. */ init?(sourceKitUID: sourcekitd_uid_t) { let length = sourcekitd_uid_get_length(sourceKitUID) let bytes = sourcekitd_uid_get_string_ptr(sourceKitUID) if let uidString = String(bytes: bytes!, length: length) { /* `String` created by `String(UTF8String:)` is based on `NSString`. `NSString` base `String` has performance penalty on getting `hashValue`. Everytime on getting `hashValue`, it calls `decomposedStringWithCanonicalMapping` for "Unicode Normalization Form D" and creates autoreleased `CFString (mutable)` and `CFString (store)`. Those `CFString` are created every time on using `hashValue`, such as using `String` for Dictionary's key or adding to Set. For avoiding those penalty, replaces with enum's rawValue String if defined in SourceKitten. That does not cause calling `decomposedStringWithCanonicalMapping`. */ self = String(uidString: uidString) return } return nil } /** Assigns SourceKitten defined enum's rawValue String from string. rawValue String if defined in SourceKitten, nil otherwise. - parameter uidString: String created from sourcekitd_uid_get_string_ptr(). */ init(uidString: String) { if let rawValue = SwiftDocKey(rawValue: uidString)?.rawValue { self = rawValue } else if let rawValue = SwiftDeclarationKind(rawValue: uidString)?.rawValue { self = rawValue } else if let rawValue = SyntaxKind(rawValue: uidString)?.rawValue { self = rawValue } else { self = "\(uidString)" } } /** Returns Swift's native String from NSUTF8StringEncoding bytes and length `String(bytesNoCopy:length:encoding:)` creates `String` based on `NSString`. That is slower than Swift's native String on some scene. - parameter bytes: UnsafePointer<Int8> - parameter length: length of bytes - returns: String Swift's native String */ init?(bytes: UnsafePointer<Int8>, length: Int) { let pointer = UnsafeMutablePointer<Int8>(mutating: bytes) // It seems SourceKitService returns string in other than NSUTF8StringEncoding. // We'll try another encodings if fail. for encoding in [String.Encoding.utf8, .nextstep, .ascii] { if let string = String(bytesNoCopy: pointer, length: length, encoding: encoding, freeWhenDone: false) { self = "\(string)" return } } return nil } } /// Represents a SourceKit request. public enum Request { /// An `editor.open` request for the given File. case editorOpen(file: File) /// A `cursorinfo` request for an offset in the given file, using the `arguments` given. case cursorInfo(file: String, offset: Int64, arguments: [String]) /// A custom request by passing in the sourcekitd_object_t directly. case customRequest(request: sourcekitd_object_t) /// A request generated by sourcekit using the yaml representation. case yamlRequest(yaml: String) /// A `codecomplete` request by passing in the file name, contents, offset /// for which to generate code completion options and array of compiler arguments. case codeCompletionRequest(file: String, contents: String, offset: Int64, arguments: [String]) /// ObjC Swift Interface case interface(file: String, uuid: String, arguments: [String]) /// Find USR case findUSR(file: String, usr: String) /// Index case index(file: String, arguments: [String]) /// Format case format(file: String, line: Int64, useTabs: Bool, indentWidth: Int64) /// ReplaceText case replaceText(file: String, offset: Int64, length: Int64, sourceText: String) /// A documentation request for the given source text. case docInfo(text: String, arguments: [String]) /// A documentation request for the given module. case moduleInfo(module: String, arguments: [String]) fileprivate var sourcekitObject: sourcekitd_object_t { let dict: [sourcekitd_uid_t: sourcekitd_object_t?] switch self { case .editorOpen(let file): if let path = file.path { dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.open")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(path), sourcekitd_uid_get_from_cstr("key.sourcefile")!: sourcekitd_request_string_create(path) ] } else { dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.open")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(String(file.contents.hash)), sourcekitd_uid_get_from_cstr("key.sourcetext")!: sourcekitd_request_string_create(file.contents) ] } case .cursorInfo(let file, let offset, let arguments): var compilerargs = arguments.map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.cursorinfo")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.sourcefile")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.offset")!: sourcekitd_request_int64_create(offset), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count) ] case .customRequest(let request): return request case .yamlRequest(let yaml): return sourcekitd_request_create_from_yaml(yaml, nil)! case .codeCompletionRequest(let file, let contents, let offset, let arguments): var compilerargs = arguments.map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.codecomplete")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.sourcefile")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.sourcetext")!: sourcekitd_request_string_create(contents), sourcekitd_uid_get_from_cstr("key.offset")!: sourcekitd_request_int64_create(offset), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count) ] case .interface(let file, let uuid, var arguments): if !arguments.contains("-x") { arguments.append(contentsOf: ["-x", "objective-c"]) } if !arguments.contains("-isysroot") { arguments.append(contentsOf: ["-isysroot", sdkPath()]) } var compilerargs = ([file] + arguments).map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.open.interface.header")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(uuid), sourcekitd_uid_get_from_cstr("key.filepath")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count) ] case .findUSR(let file, let usr): dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.find_usr")!), sourcekitd_uid_get_from_cstr("key.usr")!: sourcekitd_request_string_create(usr), sourcekitd_uid_get_from_cstr("key.sourcefile")!: sourcekitd_request_string_create(file) ] case .index(let file, let arguments): var compilerargs = arguments.map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.indexsource")!), sourcekitd_uid_get_from_cstr("key.sourcefile")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count) ] case .format(let file, let line, let useTabs, let indentWidth): let formatOptions = [ sourcekitd_uid_get_from_cstr("key.editor.format.indentwidth")!: sourcekitd_request_int64_create(indentWidth), sourcekitd_uid_get_from_cstr("key.editor.format.tabwidth")!: sourcekitd_request_int64_create(indentWidth), sourcekitd_uid_get_from_cstr("key.editor.format.usetabs")!: sourcekitd_request_int64_create(useTabs ? 1 : 0) ] var formatOptionsKeys = Array(formatOptions.keys.map({ $0 as sourcekitd_uid_t? })) var formatOptionsValues = Array(formatOptions.values) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.formattext")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.line")!: sourcekitd_request_int64_create(line), sourcekitd_uid_get_from_cstr("key.editor.format.options")!: sourcekitd_request_dictionary_create(&formatOptionsKeys, &formatOptionsValues, formatOptions.count) ] case .replaceText(let file, let offset, let length, let sourceText): dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.replacetext")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(file), sourcekitd_uid_get_from_cstr("key.offset")!: sourcekitd_request_int64_create(offset), sourcekitd_uid_get_from_cstr("key.length")!: sourcekitd_request_int64_create(length), sourcekitd_uid_get_from_cstr("key.sourcetext")!: sourcekitd_request_string_create(sourceText) ] case .docInfo(let text, let arguments): var compilerargs = arguments.map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.docinfo")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(NSUUID().uuidString), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count), sourcekitd_uid_get_from_cstr("key.sourcetext")!: sourcekitd_request_string_create(text) ] case .moduleInfo(let module, let arguments): var compilerargs = arguments.map({ sourcekitd_request_string_create($0) }) dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.docinfo")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(NSUUID().uuidString), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count), sourcekitd_uid_get_from_cstr("key.modulename")!: sourcekitd_request_string_create(module) ] } var keys = Array(dict.keys.map({ $0 as sourcekitd_uid_t? })) var values = Array(dict.values) return sourcekitd_request_dictionary_create(&keys, &values, dict.count)! } /** Create a Request.CursorInfo.sourcekitObject() from a file path and compiler arguments. - parameter filePath: Path of the file to create request. - parameter arguments: Compiler arguments. - returns: sourcekitd_object_t representation of the Request, if successful. */ internal static func cursorInfoRequest(filePath: String?, arguments: [String]) -> sourcekitd_object_t? { if let path = filePath { return Request.cursorInfo(file: path, offset: 0, arguments: arguments).sourcekitObject } return nil } /** Send a Request.CursorInfo by updating its offset. Returns SourceKit response if successful. - parameter cursorInfoRequest: sourcekitd_object_t representation of Request.CursorInfo - parameter offset: Offset to update request. - returns: SourceKit response if successful. */ internal static func send(cursorInfoRequest: sourcekitd_object_t, atOffset offset: Int64) -> [String: SourceKitRepresentable]? { if offset == 0 { return nil } sourcekitd_request_dictionary_set_int64(cursorInfoRequest, sourcekitd_uid_get_from_cstr(SwiftDocKey.offset.rawValue)!, offset) return try? Request.customRequest(request: cursorInfoRequest).send() } /** Sends the request to SourceKit and return the response as an [String: SourceKitRepresentable]. - returns: SourceKit output as a dictionary. - throws: Request.Error on fail () */ public func send() throws -> [String: SourceKitRepresentable] { initializeSourceKitFailable let response = sourcekitd_send_request_sync(sourcekitObject) defer { sourcekitd_response_dispose(response!) } if sourcekitd_response_is_error(response!) { let error = Request.Error(response: response!) if case .connectionInterrupted = error { _ = sourceKitWaitingRestoredSemaphore.wait(timeout: DispatchTime.now() + 10) } throw error } return fromSourceKit(sourcekitd_response_get_value(response!)) as! [String: SourceKitRepresentable] } /// A enum representation of SOURCEKITD_ERROR_* public enum Error: Swift.Error, CustomStringConvertible { case connectionInterrupted(String?) case invalid(String?) case failed(String?) case cancelled(String?) case unknown(String?) /// A textual representation of `self`. public var description: String { return getDescription() ?? "no description" } private func getDescription() -> String? { switch self { case .connectionInterrupted(let string): return string case .invalid(let string): return string case .failed(let string): return string case .cancelled(let string): return string case .unknown(let string): return string } } fileprivate init(response: sourcekitd_response_t) { let description = String(validatingUTF8: sourcekitd_response_error_get_description(response)!) switch sourcekitd_response_error_get_kind(response) { case SOURCEKITD_ERROR_CONNECTION_INTERRUPTED: self = .connectionInterrupted(description) case SOURCEKITD_ERROR_REQUEST_INVALID: self = .invalid(description) case SOURCEKITD_ERROR_REQUEST_FAILED: self = .failed(description) case SOURCEKITD_ERROR_REQUEST_CANCELLED: self = .cancelled(description) default: self = .unknown(description) } } } /** Sends the request to SourceKit and return the response as an [String: SourceKitRepresentable]. - returns: SourceKit output as a dictionary. - throws: Request.Error on fail () */ @available(*, deprecated, renamed: "send()") public func failableSend() throws -> [String: SourceKitRepresentable] { return try send() } } // MARK: CustomStringConvertible extension Request: CustomStringConvertible { /// A textual representation of `Request`. public var description: String { return String(validatingUTF8: sourcekitd_request_description_copy(sourcekitObject)!)! } } private func interfaceForModule(_ module: String, compilerArguments: [String]) throws -> [String: SourceKitRepresentable] { var compilerargs = compilerArguments.map { sourcekitd_request_string_create($0) } let dict = [ sourcekitd_uid_get_from_cstr("key.request")!: sourcekitd_request_uid_create(sourcekitd_uid_get_from_cstr("source.request.editor.open.interface")!), sourcekitd_uid_get_from_cstr("key.name")!: sourcekitd_request_string_create(NSUUID().uuidString), sourcekitd_uid_get_from_cstr("key.compilerargs")!: sourcekitd_request_array_create(&compilerargs, compilerargs.count), sourcekitd_uid_get_from_cstr("key.modulename")!: sourcekitd_request_string_create("SourceKittenFramework.\(module)") ] var keys = Array(dict.keys.map({ $0 as sourcekitd_uid_t? })) var values = Array(dict.values) return try Request.customRequest(request: sourcekitd_request_dictionary_create(&keys, &values, dict.count)!).send() } extension String { private func nameFromFullFunctionName() -> String { return String(self[..<range(of: "(")!.lowerBound]) } fileprivate func extractFreeFunctions(inSubstructure substructure: [[String: SourceKitRepresentable]]) -> [String] { return substructure.filter({ SwiftDeclarationKind(rawValue: SwiftDocKey.getKind($0)!) == .functionFree }).flatMap { function -> String? in let name = (function["key.name"] as! String).nameFromFullFunctionName() let unsupportedFunctions = [ "clang_executeOnThread", "sourcekitd_variant_dictionary_apply", "sourcekitd_variant_array_apply" ] guard !unsupportedFunctions.contains(name) else { return nil } let parameters = SwiftDocKey.getSubstructure(function)?.map { parameterStructure in return (parameterStructure as! [String: SourceKitRepresentable])["key.typename"] as! String } ?? [] var returnTypes = [String]() if let offset = SwiftDocKey.getOffset(function), let length = SwiftDocKey.getLength(function) { let start = index(startIndex, offsetBy: Int(offset)) let end = index(start, offsetBy: Int(length)) #if swift(>=4.0) let functionDeclaration = String(self[start..<end]) #else let functionDeclaration = self[start..<end] #endif if let startOfReturnArrow = functionDeclaration.range(of: "->", options: .backwards)?.lowerBound { let adjustedDistance = distance(from: startIndex, to: startOfReturnArrow) let adjustedReturnTypeStartIndex = functionDeclaration.index(functionDeclaration.startIndex, offsetBy: adjustedDistance + 3) returnTypes.append(String(functionDeclaration[adjustedReturnTypeStartIndex...])) } } let joinedParameters = parameters.map({ $0.replacingOccurrences(of: "!", with: "?") }).joined(separator: ", ") let joinedReturnTypes = returnTypes.map({ $0.replacingOccurrences(of: "!", with: "?") }).joined(separator: ", ") let lhs = "internal let \(name): @convention(c) (\(joinedParameters)) -> (\(joinedReturnTypes))" let rhs = "library.load(symbol: \"\(name)\")" return "\(lhs) = \(rhs)".replacingOccurrences(of: "SourceKittenFramework.", with: "") } } } internal func libraryWrapperForModule(_ module: String, loadPath: String, linuxPath: String?, spmModule: String, compilerArguments: [String]) throws -> String { let sourceKitResponse = try interfaceForModule(module, compilerArguments: compilerArguments) let substructure = SwiftDocKey.getSubstructure(Structure(sourceKitResponse: sourceKitResponse).dictionary)!.map({ $0 as! [String: SourceKitRepresentable] }) let source = sourceKitResponse["key.sourcetext"] as! String let freeFunctions = source.extractFreeFunctions(inSubstructure: substructure) let spmImport = "#if SWIFT_PACKAGE\nimport \(spmModule)\n#endif\n" let library: String if let linuxPath = linuxPath { library = "#if os(Linux)\n" + "private let path = \"\(linuxPath)\"\n" + "#else\n" + "private let path = \"\(loadPath)\"\n" + "#endif\n" + "private let library = toolchainLoader.load(path: path)\n" } else { library = "private let library = toolchainLoader.load(path: \"\(loadPath)\")\n" } let startPlatformCheck: String let endPlatformCheck: String if linuxPath == nil { startPlatformCheck = "#if !os(Linux)\n" endPlatformCheck = "\n#endif\n" } else { startPlatformCheck = "" endPlatformCheck = "\n" } return startPlatformCheck + spmImport + library + freeFunctions.joined(separator: "\n") + endPlatformCheck }
mit
4943cd9d5b824f404e7fb5578fb3de82
49.43346
160
0.643697
4.590414
false
false
false
false
foxswang/PureLayout
PureLayout/Example-iOS/Demos/iOSDemo10ViewController.swift
20
4776
// // iOSDemo10ViewController.swift // PureLayout Example-iOS // // Copyright (c) 2015 Tyler Fox // https://github.com/PureLayout/PureLayout // import UIKit import PureLayout @objc(iOSDemo10ViewController) class iOSDemo10ViewController: UIViewController { let blueView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .blueColor() return view }() let redView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .redColor() return view }() let yellowView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .yellowColor() return view }() let greenView: UIView = { let view = UIView.newAutoLayoutView() view.backgroundColor = .greenColor() return view }() let toggleConstraintsButton: UIButton = { let button = UIButton.newAutoLayoutView() button.setTitle("Toggle Constraints", forState: .Normal) button.setTitleColor(.whiteColor(), forState: .Normal) button.setTitleColor(.grayColor(), forState: .Highlighted) return button }() var didSetupConstraints = false // Flag that we use to know which layout we're currently in. We start with the horizontal layout. var isHorizontalLayoutActive = true // Properties to store the constraints for each of the two layouts. Only one set of these will be installed at any given time. var horizontalLayoutConstraints: NSArray? var verticalLayoutConstraints: NSArray? override func loadView() { view = UIView() view.backgroundColor = UIColor(white: 0.1, alpha: 1.0) view.addSubview(blueView) view.addSubview(redView) view.addSubview(yellowView) view.addSubview(greenView) view.addSubview(toggleConstraintsButton) toggleConstraintsButton.addTarget(self, action: "toggleConstraints:", forControlEvents: .TouchUpInside) view.setNeedsUpdateConstraints() // bootstrap Auto Layout } override func updateViewConstraints() { if (!didSetupConstraints) { let views: NSArray = [redView, blueView, yellowView, greenView] // Create and install the constraints that define the horizontal layout, because this is the one we're starting in. // Note that we use autoCreateAndInstallConstraints() here in order to easily collect all the constraints into a single array. horizontalLayoutConstraints = NSLayoutConstraint.autoCreateAndInstallConstraints { views.autoSetViewsDimension(.Height, toSize: 40.0) views.autoDistributeViewsAlongAxis(.Horizontal, alignedTo: .Horizontal, withFixedSpacing: 10.0, insetSpacing: true, matchedSizes: true) self.redView.autoAlignAxisToSuperviewAxis(.Horizontal) } // Create the constraints that define the vertical layout, but don't install any of them - just store them for now. // Note that we use autoCreateConstraintsWithoutInstalling() here in order to both prevent the constraints from being installed automatically, // and to easily collect all the constraints into a single array. verticalLayoutConstraints = NSLayoutConstraint.autoCreateConstraintsWithoutInstalling { views.autoSetViewsDimension(.Width, toSize: 60.0) views.autoDistributeViewsAlongAxis(.Vertical, alignedTo: .Vertical, withFixedSpacing: 70.0, insetSpacing: true, matchedSizes: true) self.redView.autoAlignAxisToSuperviewAxis(.Vertical) } toggleConstraintsButton.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 10.0) toggleConstraintsButton.autoAlignAxisToSuperviewAxis(.Vertical) didSetupConstraints = true } super.updateViewConstraints() } /** Callback when the "Toggle Constraints" button is tapped. */ func toggleConstraints(sender: UIButton) { isHorizontalLayoutActive = !isHorizontalLayoutActive if (isHorizontalLayoutActive) { verticalLayoutConstraints?.autoRemoveConstraints() horizontalLayoutConstraints?.autoInstallConstraints() } else { horizontalLayoutConstraints?.autoRemoveConstraints() verticalLayoutConstraints?.autoInstallConstraints() } /** Uncomment the below code if you want the transitions to be animated! */ // UIView.animateWithDuration(0.2) { // self.view.layoutIfNeeded() // } } }
mit
f573afc4a303f7b4f9abce7574f66152
39.474576
154
0.657663
5.502304
false
false
false
false
Imgur/IMGTreeTableViewController
IMGTreeTableViewDemo/ViewController.swift
1
2674
import UIKit import IMGTreeTableView class ViewController: UIViewController, IMGTreeTableControllerDelegate, UITableViewDelegate { var tree: IMGTree! var controller: IMGTreeTableController! @IBOutlet var tableView: UITableView! let backgroundColors = [UIColor.turquoiseColor(), UIColor.greenSeaColor(), UIColor.emeraldColor(), UIColor.nephritisColor(), UIColor.peterRiverColor(), UIColor.belizeHoleColor(), UIColor.amethystColor(), UIColor.wisteriaColor(), UIColor.wetAsphaltColor(), UIColor.midnightBlueColor()] // MARK: Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = .greenSeaColor() tableView.delegate = self tableView.tintColor = UIColor.whiteColor() view.backgroundColor = .greenSeaColor() let construction = IMGSampleTreeConstructor() tree = construction.sampleCommentTree() controller = IMGTreeTableController(tableView: tableView, delegate: self) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) controller.tree = tree //zoom to a bottom node // let node = tree.rootNode.children[1].children[2].children[1].children[2].children[0].children[2].children[1] // controller.zoomTo(node) } // MARK: IMGTreeTableControllerDelegate func cell(node: IMGTreeNode, indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell cell.accessoryType = .None switch node { case let commentNode as IMGCommentNode: cell.textLabel?.text = commentNode.comment case is IMGTreeSelectionNode: cell.textLabel?.text = "selection" cell.accessoryType = .DetailButton case is IMGTreeActionNode: cell.textLabel?.text = "action" case is IMGTreeCollapsedSectionNode: cell.textLabel?.text = "collapsed" default: break } cell.backgroundColor = backgroundColors[(node.depth) % backgroundColors.count] cell.textLabel?.textColor = UIColor.cloudsColor() cell.selectionStyle = .None return cell } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { controller.didSelectRow(indexPath) } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { controller.didTriggerActionFromIndex(indexPath) } }
mit
39441df13cd0818f5f3ecb7b7d8e29ae
36.661972
288
0.68175
5.016886
false
false
false
false
jdbateman/Lendivine
OAuthSwift-master/OAuthSwiftDemo/KivaOauth.swift
1
11276
// // KivaOauth.swift // OAuthSwift // // Created by john bateman on 10/28/15. // Copyright © 2015 Dongri Jin. All rights reserved. // // This class implements the client portion of the OAuth 1.0a protocol for the Kiva.org service. import Foundation import OAuthSwift class KivaOAuth { var oAuthAccessToken: String? var oAuthSecret: String? var kivaAPI: KivaAPI? init() { } func doOAuthKiva(completionHandler: (success: Bool, error: NSError?, kivaAPI: KivaAPI?) -> Void){ let oauthswift = OAuth1Swift( consumerKey: Kiva["consumerKey"]!, consumerSecret: Kiva["consumerSecret"]!, requestTokenUrl: "https://api.kivaws.org/oauth/request_token", authorizeUrl: "https://www.kiva.org/oauth/authorize", accessTokenUrl: "https://api.kivaws.org/oauth/access_token" ) // Request an unauthorized oauth Request Token. Upon receipt of the request token from Kiva use it to redirect to Kiva.org for user authentication and user authorization of app. If the user authorizes this app then Kiva.org redirects to the callback url below by appending an oauth_verifier code. The app will exchange the unauthorized oauth request token and oauth_verifier code for a long lived Access Token that can be used to make Kiva API calls to access protected resources. oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/kiva")!, success: { credential, response in print("oauth_token:\(credential.oauth_token)\n\noauth_token_secret:\(credential.oauth_token_secret)") //self.showAlertView("Kiva", message: "oauth_token:\(credential.oauth_token)\n\noauth_token_secret:\(credential.oauth_token_secret)") // TODO: securely store the access credentials // get the kivaAPI handle self.kivaAPI = KivaAPI(oAuthAccessToken: credential.oauth_token, oAuth1: oauthswift) completionHandler(success: true, error: nil, kivaAPI: self.kivaAPI) }, failure: { (error:NSError!) -> Void in print(error.localizedDescription) completionHandler(success: false, error: error, kivaAPI: nil) } ) } func testKivaAPI() { /* kivaAPI.kivaGetUserAccount() { success, error, userAccount in if success { print("success: userAccount{ name:\(userAccount?.firstName) \(userAccount?.lastName) lenderID:\(userAccount?.lenderID) id:(userAccount?.id) developer:\(userAccount?.isDeveloper) public:\(userAccount?.isPublic)}") } else { print("failed") } } kivaAPI.kivaGetUserBalance() { success, error, balance in if success { print("success: balance = \(balance)") } else { print("failed") } } kivaAPI.kivaGetUserEmail() { success, error, email in if success { print("success: email = \(email)") } else { print("failed") } } kivaAPI.kivaGetUserExpectedRepayment() { success, error, expectedRepayment in if success { print("success: expected repayment = \(expectedRepayment)") } else { print("failed") } } kivaAPI.kivaGetLender() { success, error, lender in if success { print("lender: \(lender)") } else { print("failed") } } kivaAPI.kivaGetLoans() { success, error, loans in if success { print("loans: \(loans)") if let loans = loans { let loan = loans.first let loanID = loan!.id // TODO: fix kivaGetLoanBalances kivaAPI.kivaGetLoanBalances(loanID) { success, error, balances in if success { print("loans: \(balances)") } else { print("failed") } } } } else { print("failed") } } kivaAPI.kivaGetMyLenderStatistics() { success, error, statistics in if success { print("statistics: \(statistics)") } else { print("failed") } } */ // kivaAPI.kivaGetLoanBalances() { success, error, balances in // if success { // print("loans: \(balances)") // } else { // print("failed") // } // } /* kivaAPI.kivaGetMyTeams() { success, error, teams in if success { if let teams = teams { print("teams: \(teams)") } } else { print("failed") } } kivaAPI.kivaGetPartners() { success, error, partners in if success { print("statistics: \(partners)") } else { print("failed") } } kivaAPI.kivaGetNewestLoans() { success, error, newestLoans in if success { print("newest loans: \(newestLoans)") } else { print("failed") } } let regions = "ca,sa,af,as,me,ee,we,an,oc" let countries = "TD,TG,TH,TJ,TL,TR,TZ" kivaAPI.kivaSearchLoans(queryMatch: "family", status: KivaAPI.LoanStatus.fundraising.rawValue, gender: nil, regions: regions, countries: nil, sector: KivaAPI.LoanSector.Agriculture, borrowerType: KivaAPI.LoanBorrowerType.individuals.rawValue, maxPartnerRiskRating: KivaAPI.PartnerRiskRatingMaximum.medLow, maxPartnerDelinquency: KivaAPI.PartnerDelinquencyMaximum.medium, maxPartnerDefaultRate: KivaAPI.PartnerDefaultRateMaximum.medium, includeNonRatedPartners: true, includedPartnersWithCurrencyRisk: true, page: 1, perPage: 20, sortBy: KivaAPI.LoanSortBy.popularity.rawValue) { success, error, loanResults in if success { print("search loans results: \(loanResults)") } else { print("failed") } } */ // self.testCheckout(self.kivaAPI!) } func testCheckout(kivaAPI: KivaAPI) { // search some loans //var loans = [KivaLoan]() findLoans(kivaAPI) { success, error, loanResults in if success { if let loans = loanResults { // put the first loan into the cart let loanId = loans[0].id kivaAPI.KivaAddItemToCart(loanId, amount: 25.00 ) // call checkout kivaAPI.KivaCheckout() } print("search loans results: \(loanResults)") } else { print("failed") } } } // helper function that searches for loans func findLoans(kivaAPI: KivaAPI, completionHandler: (success: Bool, error: NSError?, loans: [KivaLoan]?) -> Void) { let regions = "ca,sa,af,as,me,ee,we,an,oc" let countries = "TD,TG,TH,TJ,TL,TR,TZ" kivaAPI.kivaSearchLoans(queryMatch: "family", status: KivaAPI.LoanStatus.fundraising.rawValue, gender: nil, regions: regions, countries: nil, sector: KivaAPI.LoanSector.Agriculture, borrowerType: KivaAPI.LoanBorrowerType.individuals.rawValue, maxPartnerRiskRating: KivaAPI.PartnerRiskRatingMaximum.medLow, maxPartnerDelinquency: KivaAPI.PartnerDelinquencyMaximum.medium, maxPartnerDefaultRate: KivaAPI.PartnerDefaultRateMaximum.medium, includeNonRatedPartners: true, includedPartnersWithCurrencyRisk: true, page: 1, perPage: 20, sortBy: KivaAPI.LoanSortBy.popularity.rawValue) { success, error, loanResults in if success { // print("search loans results: \(loanResults)") completionHandler(success: success, error: error, loans: loanResults) } else { // print("kivaSearchLoans failed") completionHandler(success: success, error: error, loans: nil) } } } // func doOAuthKiva(){ // // let oauthswift = OAuth1Swift( // consumerKey: Kiva["consumerKey"]!, // consumerSecret: Kiva["consumerSecret"]!, // requestTokenUrl: "https://api.kivaws.org/oauth/request_token", // authorizeUrl: "https://www.kiva.org/oauth/authorize", // accessTokenUrl: "https://api.kivaws.org/oauth/access_token" // ) // // // Request an unauthorized oauth Request Token. Upon receipt of the request token from Kiva use it to redirect to Kiva.org for user authentication and user authorization of app. If the user authorizes this app then Kiva.org redirects to the callback url below by appending an oauth_verifier code. The app will exchange the unauthorized oauth request token and oauth_verifier code for a long lived Access Token that can be used to make Kiva API calls to access protected resources. // oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/kiva")!, success: { // credential, response in // // print("bravo. Now make a call to the Kiva api") // // print("oauth_token:\(credential.oauth_token)\n\noauth_token_secret:\(credential.oauth_token_secret)") // //self.showAlertView("Kiva", message: "oauth_token:\(credential.oauth_token)\n\noauth_token_secret:\(credential.oauth_token_secret)") // // // TODO: securely store the access credentials // // // TODO: make a call to a Kiva API using the access credentials. // // print("") // print("****************************************************************************") // print("Step 4: Make Kiva API request with Access Token") // //print("") // // let url :String = "https://api.kivaws.org/v1/my/account.json" // // // set the oauth_token parameter. remove any existing URL encoding (% escaped characters) // var parameters = Dictionary<String, AnyObject>() // var oauthToken = credential.oauth_token // oauthToken = oauthToken.stringByRemovingPercentEncoding! // parameters = [ // "oauth_token" : oauthToken // ] // // oauthswift.client.get(url, parameters: parameters, // success: { // data, response in // print("Kiva API request succeeded.") // let jsonDict: AnyObject! = try? NSJSONSerialization.JSONObjectWithData(data, options: []) // print(jsonDict) // }, failure: {(error:NSError!) -> Void in // print("Kiva API request failed.") // print(error) // }) // }, failure: {(error:NSError!) -> Void in // print(error.localizedDescription) // } // ) // } }
mit
b06c58f21daa7d0c43291f3e405690bb
40.608856
617
0.565322
4.303435
false
false
false
false
syershov/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/Cian/CianElement.swift
2
5268
final class CianElement : UICollectionViewCell { enum State { case pending(onButtonAction: () -> Void) case offer(model: CianItemModel?, onButtonAction: (CianItemModel?) -> Void) case error(onButtonAction: () -> Void) } @IBOutlet private var contentViews: [UIView]! @IBOutlet private weak var pendingView: UIView! @IBOutlet private weak var offerView: UIView! @IBOutlet private weak var more: UIButton! @IBOutlet private weak var price: UILabel! { didSet { price.font = UIFont.medium14() price.textColor = UIColor.linkBlue() } } @IBOutlet private weak var descr: UILabel! { didSet { descr.font = UIFont.medium14() descr.textColor = UIColor.blackPrimaryText() } } @IBOutlet private weak var address: UILabel! { didSet { address.font = UIFont.regular12() address.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var details: UIButton! { didSet { details.setTitleColor(UIColor.linkBlue(), for: .normal) details.setBackgroundColor(UIColor.blackOpaque(), for: .normal) } } private var isLastCell = false { didSet { more.isHidden = !isLastCell price.isHidden = isLastCell descr.isHidden = isLastCell address.isHidden = isLastCell details.isHidden = isLastCell } } @IBOutlet private weak var pendingSpinnerView: UIImageView! { didSet { pendingSpinnerView.tintColor = UIColor.linkBlue() } } @IBOutlet private weak var pendingTitleTopOffset: NSLayoutConstraint! @IBOutlet private weak var pendingTitle: UILabel! { didSet { pendingTitle.font = UIFont.medium14() pendingTitle.textColor = UIColor.blackPrimaryText() pendingTitle.text = L("preloader_cian_title") } } @IBOutlet private weak var pendingDescription: UILabel! { didSet { pendingDescription.font = UIFont.regular12() pendingDescription.textColor = UIColor.blackSecondaryText() pendingDescription.text = L("preloader_cian_message") } } @IBAction func onButtonAction() { switch state! { case let .pending(action): action() case let .offer(model, action): action(model) case let .error(action): action() } } var state: State! { didSet { setupAppearance() setNeedsLayout() contentViews.forEach { $0.isHidden = false } let visibleView: UIView var pendingSpinnerViewAlpha: CGFloat = 1 switch state! { case .pending: visibleView = pendingView configPending() case let .offer(model, _): visibleView = offerView configOffer(model: model) case .error: pendingSpinnerViewAlpha = 0 visibleView = pendingView configError() } UIView.animate(withDuration: kDefaultAnimationDuration, animations: { self.pendingSpinnerView.alpha = pendingSpinnerViewAlpha self.contentViews.forEach { $0.alpha = 0 } visibleView.alpha = 1 self.layoutIfNeeded() }, completion: { _ in self.contentViews.forEach { $0.isHidden = true } visibleView.isHidden = false }) } } private var isSpinning = false { didSet { let animationKey = "SpinnerAnimation" if isSpinning { let animation = CABasicAnimation(keyPath: "transform.rotation.z") animation.fromValue = NSNumber(value: 0) animation.toValue = NSNumber(value: 2 * Double.pi) animation.duration = 0.8 animation.repeatCount = Float.infinity pendingSpinnerView.layer.add(animation, forKey: animationKey) } else { pendingSpinnerView.layer.removeAnimation(forKey: animationKey) } } } private func setupAppearance() { backgroundColor = UIColor.white() layer.cornerRadius = 6 layer.borderWidth = 1 layer.borderColor = UIColor.blackDividers().cgColor } private func configPending() { isSpinning = true details.setTitle(L("preloader_cian_button"), for: .normal) pendingTitleTopOffset.priority = UILayoutPriorityDefaultLow } private func configError() { isSpinning = false details.setTitle(L("preloader_cian_button"), for: .normal) pendingTitleTopOffset.priority = UILayoutPriorityDefaultHigh } private func configOffer(model: CianItemModel?) { isSpinning = false if let model = model { isLastCell = false let priceFormatter = NumberFormatter() priceFormatter.usesGroupingSeparator = true if let priceString = priceFormatter.string(from: NSNumber(value: model.priceRur)) { price.text = "\(priceString) \(L("rub_month"))" } else { price.isHidden = true } let descrFormat = L("room").replacingOccurrences(of: "%s", with: "%@") descr.text = String(format: descrFormat, arguments:["\(model.roomsCount)"]) address.text = model.address details.setTitle(L("details"), for: .normal) } else { isLastCell = true more.setBackgroundImage(UIColor.isNightMode() ? #imageLiteral(resourceName: "btn_float_more_dark") : #imageLiteral(resourceName: "btn_float_more_light"), for: .normal) backgroundColor = UIColor.clear layer.borderColor = UIColor.clear.cgColor } } }
apache-2.0
f51190cd7faf194d9880ed93f29068ea
29.275862
173
0.662491
4.491049
false
false
false
false
Shvier/QuickPlayer-Swift
QuickPlayer/QuickPlayer/Cache/CacheFile/QuickPlayerItemCacheFile.swift
1
1490
// // QuickPlayerItemCacheFile.swift // QuickPlayer // // Created by Shvier on 2018/5/28. // Copyright © 2018 Shvier. All rights reserved. // import UIKit class QuickPlayerItemCacheFile: NSObject { var cacheFilePath: String! var serializationFilePath: String! var fileLength: UInt! var readOffset: UInt! var responseHeader: [String: String]! var isFinished: Bool! var isEOF: Bool! var isFileLengthValid: Bool! var cachedDataBound: UInt! var ranges: [NSRange]! var readFileHandle: FileHandle! var writeFileHandle: FileHandle! // MARK: Constructor init(cacheFileName: String, fileExtension: String? = "mp4") { let cacheFileInfo = QuickCacheManager.getOrCreateCacheFile(fileName: cacheFileName, fileExtension: fileExtension) let serializationFileInfo = QuickCacheManager.getOrCreateCacheFile(fileName: cacheFileName, fileExtension: SerializationFileExtension) if !cacheFileInfo.1 && serializationFileInfo.1 { return } self.cacheFilePath = cacheFileInfo.0 self.serializationFilePath = serializationFileInfo.0 self.ranges = [NSRange]() self.readFileHandle = FileHandle.init(forReadingAtPath: self.cacheFilePath)! self.writeFileHandle = FileHandle.init(forWritingAtPath: self.cacheFilePath)! } // MARK: Life Cycle deinit { self.writeFileHandle.closeFile() self.readFileHandle.closeFile() } }
mit
e0d5b0cd38a95ac068edd11e7b8e9ebb
30.680851
142
0.694426
4.697161
false
false
false
false
oacastefanita/PollsFramework
Example/PollsFramework-mac/SingleTextPollViewController.swift
1
8913
// // SingleTextPollViewController.swift // PollsFramework // // Created by Stefanita Oaca on 31/08/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Cocoa import PollsFramework enum PollScreenType { case view case edit case create case draft } class SingleTextPollViewController: NSViewController, CategoriesViewControllerDelegate { var poll: Poll! var screenType: PollScreenType! = .create var viewObjects = [Any]() @IBOutlet weak var txtTitle: NSTextField! @IBOutlet weak var txtOverview: NSTextField! @IBOutlet weak var txtKeywords: NSTextField! @IBOutlet weak var txtAssgnmentDuration: NSTextField! @IBOutlet weak var txtLifetimeDuration: NSTextField! @IBOutlet weak var txtQuestion: NSTextView! @IBOutlet weak var btnAllowComments: NSButton! @IBOutlet weak var btnAdultComments: NSButton! @IBOutlet weak var btnEnableFilters: NSButton! @IBOutlet weak var btnPublic: NSButton! @IBOutlet weak var btnDraft: NSButton! @IBOutlet weak var btnExtend: NSButton! @IBOutlet weak var btnExpire: NSButton! override func viewDidLoad() { super.viewDidLoad() if screenType == .create{ btnExpire.isHidden = true btnExtend.isHidden = true } if poll == nil { poll = (NSEntityDescription.insertNewObject(forEntityName: "Poll", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Poll) poll.pollTypeId = PollTypes.singleText.rawValue } fillViewData() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } @IBAction func onAddFilter(_ sender: Any) { self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "showCategories"), sender: self) } @IBAction func onExtend(_ sender: Any) { PollsFrameworkController.sharedInstance.extendExpireTimeWith(3600, pollId: (Int(poll.pollId))){ (success, response) in if !success { } else { } } } @IBAction func onExpire(_ sender: Any) { PollsFrameworkController.sharedInstance.expirePoll(Int(poll.pollId)){ (success, response) in if !success { } else { } } } @IBAction func onDelete(_ sender: Any) { self.fillPollData() switch screenType! { case .view: break case .edit: PollsFrameworkController.sharedInstance.deletePoll(Int(poll.pollId)){ (success, response) in if !success { } else { } self.view.window?.close() } break case .create: break case .draft: PollsFrameworkController.sharedInstance.deleteDraftPoll(Int(poll.pollId)){ (success, response) in if !success { } else { } self.view.window?.close() } break } } @IBAction func onDone(_ sender: Any) { self.fillPollData() switch screenType! { case .view: self.view.window?.close() break case .edit: PollsFrameworkController.sharedInstance.updatePublishedPoll(Int(poll.pollId), keywords: txtKeywords.stringValue, pollOverview: txtOverview.stringValue){ (success, response) in if !success { } else { } self.view.window?.close() } break case .create: PollsFrameworkController.sharedInstance.createTextPoll(poll: poll){ (success, response) in if !success { } else { } self.view.window?.close() } break case .draft: PollsFrameworkController.sharedInstance.createTextPoll(poll: poll){ (success, response) in if !success { } else { } self.view.window?.close() } break } } @IBAction func onResults(_ sender: Any) { let getObj = PollsFactory.createGetPollsViewModel() getObj.pollId = self.poll.pollId PollsFrameworkController.sharedInstance.getPollsResults(getPolls: getObj){ (success, response) in if !success { } else { self.viewObjects = response self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "viewObjectsListFromPoll"), sender: self) } } } @IBAction func onAnswer(_ sender: Any) { self.performSegue(withIdentifier: NSStoryboardSegue.Identifier(rawValue: "viewObjectDetailsFromPoll"), sender: self) } func fillPollData(){ poll.isFilterOption = btnEnableFilters.state == .on poll.isEnablePublic = btnPublic.state == .on poll.isAdult = btnAdultComments.state == .on poll.isEnabledComments = btnAllowComments.state == .on poll.lifeTimeInSeconds = Int64(txtLifetimeDuration.stringValue)! poll.assignmentDurationInSeconds = Int64(txtAssgnmentDuration.stringValue)! poll.keywords = txtKeywords.stringValue poll.pollOverview = txtOverview.stringValue poll.question = txtQuestion.string poll.pollTitle = txtTitle.stringValue poll.isPublished = btnDraft.state == .on } func fillViewData(){ btnEnableFilters.state = poll.isFilterOption ? .on : .off btnDraft.state = poll.isPublished ? .on : .off btnPublic.state = poll.isEnablePublic ? .on : .off btnAdultComments.state = poll.isAdult ? .on : .off btnAllowComments.state = poll.isEnabledComments ? .on : .off txtLifetimeDuration.stringValue = "\(poll.lifeTimeInSeconds)" txtAssgnmentDuration.stringValue = "\(poll.assignmentDurationInSeconds)" txtKeywords.stringValue = poll.keywords ?? "" txtOverview.stringValue = poll.pollOverview ?? "" txtQuestion.string = poll.question ?? "" txtTitle.stringValue = poll.pollTitle ?? "" if self.screenType == .edit{ btnEnableFilters.isEnabled = false btnDraft.isEnabled = false btnPublic.isEnabled = false btnAdultComments.isEnabled = false btnAllowComments.isEnabled = false txtLifetimeDuration.isEnabled = false txtAssgnmentDuration.isEnabled = false txtKeywords.isEnabled = false txtOverview.isEnabled = false txtQuestion.isEditable = false txtTitle.isEnabled = false } } func selectedCategoryAndFilter(_ filters: [FilterNameValue], category: PollCategory?) { if category != nil{ poll.catId = category?.catId as! Int64 } for filter in filters{ poll.addToFilterNameValue(filter) } } func selectedFilter(_ filter: FilterNameValue) { poll.addToFilterNameValue(filter) } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier!.rawValue == "addFilters"{ // (segue.destinationController as! FiltersViewController).delegate = self } else if segue.identifier!.rawValue == "showCategories"{ (segue.destinationController as! CategoriesViewController).delegate = self } else if segue.identifier!.rawValue == "viewObjectDetailsFromPoll"{ let answer = (NSEntityDescription.insertNewObject(forEntityName: "PollAnswer", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! PollAnswer) answer.pollId = self.poll.pollId answer.workerUserId = PollsFrameworkController.sharedInstance.user?.userId (segue.destinationController as! ViewObjectViewController).object = answer (segue.destinationController as! ViewObjectViewController).screenType = .edit (segue.destinationController as! ViewObjectViewController).objectType = .pollAnswer } else if segue.identifier!.rawValue == "viewObjectsListFromPoll"{ (segue.destinationController as! ViewObjectsListViewController).objects = self.viewObjects } } }
mit
02f521a3af52fba80bfdc5fc83f70775
34.225296
192
0.588308
5.052154
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Linked List/83_Remove Duplicates from Sorted List.swift
1
955
// 83_Remove Duplicates from Sorted List // https://leetcode.com/problems/remove-duplicates-from-sorted-list/ // // Created by Honghao Zhang on 9/7/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a sorted linked list, delete all duplicates such that each element appear only once. // //Example 1: // //Input: 1->1->2 //Output: 1->2 //Example 2: // //Input: 1->1->2->3->3 //Output: 1->2->3 // import Foundation class Num83 { // Check if current val is same as the previous value, if so, remove it. func deleteDuplicates(_ head: ListNode?) -> ListNode? { let root: ListNode? = ListNode(0) root?.next = head var prev = root var current = head while current != nil { if prev !== root, current?.val == prev!.val { prev?.next = current?.next current = current?.next continue } prev = current current = current?.next } return root?.next } }
mit
11eb0b2a6900ac194daf6b5a9987a09e
22.268293
93
0.625786
3.6
false
false
false
false
Alexander-Ignition/OCR
OCR/ai_queue.swift
1
692
// // AI_gcd.swift // OCR // // Created by Alexander Ignition on 19.03.15. // Copyright (c) 2015 Alexander Ignition. All rights reserved. // import Foundation struct ai_queue { static let main = dispatch_get_main_queue() static let user_interactive = dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.value), 0) static let user_initiated = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0) static let default_q = dispatch_get_global_queue(Int(QOS_CLASS_DEFAULT.value), 0) static let utility = dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0) static let background = dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0) }
mit
c48b141588daae046e2541c0923e42f7
37.5
101
0.725434
3.311005
false
false
false
false
cyanzhong/xTextHandler
xLibrary/xTextModifier.swift
1
6067
// // ██╗ ██╗████████╗███████╗██╗ ██╗████████╗ // ╚██╗██╔╝╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝ // ╚███╔╝ ██║ █████╗ ╚███╔╝ ██║ // ██╔██╗ ██║ ██╔══╝ ██╔██╗ ██║ // ██╔╝ ██╗ ██║ ███████╗██╔╝ ██╗ ██║ // ╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ // // xTextModifier.swift // xTextHandler (https://github.com/cyanzhong/xTextHandler/) // // Created by cyan on 16/7/4. // Copyright © 2016年 cyan. All rights reserved. // import XcodeKit import AppKit /// Text matching & handling class xTextModifier { /// Regular expressions private static let xTextHandlerStringPattern = "\"(.+)\"" // match "abc" private static let xTextHandlerHexPattern = "([0-9a-fA-F]+)" // match 00FFFF private static let xTextHandlerRGBPattern = "([0-9]+.+[0-9]+.+[0-9]+)" // match 20, 20, 20 | 20 20 20 ... private static let xTextHandlerRadixPattern = "([0-9]+)" // match numbers /// Select text with regex & default option /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter pattern: regex pattern /// - parameter handler: handler static func select(invocation: XCSourceEditorCommandInvocation, pattern: String?, handler: xTextModifyHandler) { select(invocation: invocation, pattern: pattern, options: [.selected], handler: handler) } /// Select text with regex /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter pattern: regex pattern /// - parameter options: xTextMatchOptions /// - parameter handler: handler static func select(invocation: XCSourceEditorCommandInvocation, pattern: String?, options: xTextMatchOptions, handler: xTextModifyHandler) { var regex: NSRegularExpression? if pattern != nil { do { try regex = NSRegularExpression(pattern: pattern!, options: .caseInsensitive) } catch { xTextLog(string: "Create regex failed") } } // enumerate selections for i in 0..<invocation.buffer.selections.count { let range = invocation.buffer.selections[i] as! XCSourceTextRange // match clipped text let match = xTextMatcher.match(selection: range, invocation: invocation, options: options) if match.clipboard { // handle clipboard text if match.text.characters.count > 0 { let pasteboard = NSPasteboard.general() pasteboard.declareTypes([NSPasteboardTypeString], owner: nil) pasteboard.setString(handler(match.text), forType: NSPasteboardTypeString) } continue } if match.text.characters.count == 0 { continue } // handle selected text var texts: Array<String> = [] if regex != nil { // match using regex regex!.enumerateMatches(in: match.text, options: [], range: match.range, using: { result, flags, stop in if let range = result?.rangeAt(1) { texts.append((match.text as NSString).substring(with: range)) } }) } else { // match all texts.append((match.text as NSString).substring(with: match.range)) } if texts.count == 0 { continue } var replace = match.text for text in texts { // replace each matched text with handler block if let textRange = replace.range(of: text) { replace.replaceSubrange(textRange, with: handler(text)) } } // separate text to lines using newline charset var lines = replace.components(separatedBy: NSCharacterSet.newlines) lines.removeLast() // update buffer invocation.buffer.lines.replaceObjects(in: NSMakeRange(range.start.line, range.end.line - range.start.line + 1), withObjectsFrom: lines) // cancel selection let newRange = XCSourceTextRange() newRange.start = range.start newRange.end = range.start invocation.buffer.selections[i] = newRange } } /// Select any text with default option /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func any(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { any(invocation: invocation, options: [.selected], handler: handler) } /// Select any text /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter options: xTextMatchOptions /// - parameter handler: handler static func any(invocation: XCSourceEditorCommandInvocation, options: xTextMatchOptions, handler: xTextModifyHandler) { select(invocation: invocation, pattern: nil, options: options, handler: handler) } /// Select numbers /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func radix(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerRadixPattern, handler: handler) } /// Select hex color /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func hex(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerHexPattern, handler: handler) } /// Select RGB color /// /// - parameter invocation: XCSourceEditorCommandInvocation /// - parameter handler: handler static func rgb(invocation: XCSourceEditorCommandInvocation, handler: xTextModifyHandler) { select(invocation: invocation, pattern: xTextHandlerRGBPattern, handler: handler) } }
mit
a352fb3ad2395170433432f24dd51686
36.5
142
0.633158
4.513064
false
false
false
false
ffried/FFFoundation
Sources/FFFoundation/Extensions/Predicate+StringInterpolation.swift
1
4735
// // Predicate+StringInterpolation.swift // FFFoundation // // Created by Florian Friedrich on 25.07.19. // // 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. // // KVC is only available on Darwin platforms #if canImport(ObjectiveC) import Foundation extension NSPredicate { public struct Format: ExpressibleByStringInterpolation { public typealias StringLiteralType = String @usableFromInline let format: String @usableFromInline let args: Array<Any>? public init(stringLiteral value: StringLiteralType) { format = value args = nil } public init(stringInterpolation: StringInterpolation) { format = stringInterpolation.format args = stringInterpolation.args } } @inlinable public convenience init(_ format: Format) { self.init(format: format.format, argumentArray: format.args) } } extension NSPredicate.Format { public struct StringInterpolation: StringInterpolationProtocol { public typealias StringLiteralType = NSPredicate.Format.StringLiteralType private enum ValueKind: String { case key = "K" case object = "@" case string = "s" case bool = "u" case signedInteger = "ld" case unsingedInteger = "lu" case float = "f" var formatSpecifier: String { "%" + rawValue } } fileprivate private(set) var format: String fileprivate private(set) var args: Array<Any> public init(literalCapacity: Int, interpolationCount: Int) { format = .init() args = .init() format.reserveCapacity(literalCapacity + interpolationCount * 2) args.reserveCapacity(interpolationCount) } public mutating func appendLiteral(_ literal: StringLiteralType) { format.append(literal) } private mutating func addNull() { format.append("NULL") } private mutating func add(arg: Any?, as valueKind: ValueKind) { if let arg = arg { format.append(valueKind.formatSpecifier) args.append(arg) } else { addNull() } } // MARK: Keys public mutating func appendInterpolation(_ key: NSPredicate.Key) { add(arg: key.rawValue, as: .key) } public mutating func appendInterpolation(key: NSPredicate.Key) { add(arg: key.rawValue, as: .key) } public mutating func appendInterpolation(key: NSPredicate.Key.RawValue) { add(arg: key, as: .key) } #if canImport(ObjectiveC) public mutating func appendInterpolation(_ key: AnyKeyPath) { guard let kvcString = key._kvcKeyPathString else { fatalError("Cannot get key value coding string from \(key)!") } add(arg: kvcString, as: .key) } #endif // MARK: Values public mutating func appendInterpolation(_ any: Any?) { add(arg: any, as: .object) } public mutating func appendInterpolation(_ bool: Bool?) { add(arg: bool, as: .bool) } public mutating func appendInterpolation<Bridged: ReferenceConvertible>(_ bridgeable: Bridged?) { add(arg: bridgeable.map { $0 as! Bridged.ReferenceType }, as: .object) } public mutating func appendInterpolation<Integer: SignedInteger>(_ integer: Integer?) { add(arg: integer, as: .signedInteger) } public mutating func appendInterpolation<Integer: UnsignedInteger>(_ integer: Integer?) { add(arg: integer, as: .unsingedInteger) } public mutating func appendInterpolation<Float: FloatingPoint>(_ float: Float?) { add(arg: float, as: .float) } public mutating func appendInterpolation(_ number: NSNumber?) { add(arg: number, as: .object) } } } #endif
apache-2.0
db910c80c03c556cb7330f54d3103064
32.111888
126
0.59113
5.047974
false
false
false
false
matrix-org/matrix-ios-sdk
MatrixSDK/Utils/Logs/MXAnalyticsDestination.swift
1
1653
// // MXAnalyticsDestination.swift // MatrixSDK // // Created by Element on 22/08/2022. // import Foundation import SwiftyBeaver /// SwiftyBeaver log destination that sends errors to analytics tracker class MXAnalyticsDestination: BaseDestination { override var asynchronously: Bool { get { return false } set { assertionFailure("Cannot be used asynchronously to preserve strack trace") } } override var minLevel: SwiftyBeaver.Level { get { return .error } set { assertionFailure("Analytics should not track anything less severe than errors") } } override func send(_ level: SwiftyBeaver.Level, msg: String, thread: String, file: String, function: String, line: Int, context: Any? = nil) -> String? { let message = super.send(level, msg: msg, thread: thread, file: file, function: function, line: line, context: context) #if !DEBUG MXSDKOptions.sharedInstance().analyticsDelegate?.trackNonFatalIssue(msg, details: formattedDetails(from: context)) #endif return message } private func formattedDetails(from context: Any?) -> [String: Any]? { guard let context = context else { return nil } if let dictionary = context as? [String: Any] { return dictionary } else if let error = context as? Error { return [ "error": error ] } else { return [ "context": String(describing: context) ] } } }
apache-2.0
bf8cf131318ce3f37076d49899e6e78d
28.517857
157
0.583182
4.833333
false
false
false
false
benlangmuir/swift
stdlib/public/core/RandomAccessCollection.swift
5
15176
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection that supports efficient random-access index traversal. /// /// Random-access collections can move indices any distance and /// measure the distance between indices in O(1) time. Therefore, the /// fundamental difference between random-access and bidirectional collections /// is that operations that depend on index movement or distance measurement /// offer significantly improved efficiency. For example, a random-access /// collection's `count` property is calculated in O(1) instead of requiring /// iteration of an entire collection. /// /// Conforming to the RandomAccessCollection Protocol /// ================================================= /// /// The `RandomAccessCollection` protocol adds further constraints on the /// associated `Indices` and `SubSequence` types, but otherwise imposes no /// additional requirements over the `BidirectionalCollection` protocol. /// However, in order to meet the complexity guarantees of a random-access /// collection, either the index for your custom type must conform to the /// `Strideable` protocol or you must implement the `index(_:offsetBy:)` and /// `distance(from:to:)` methods with O(1) efficiency. public protocol RandomAccessCollection<Element>: BidirectionalCollection where SubSequence: RandomAccessCollection, Indices: RandomAccessCollection { // FIXME: Associated type inference requires these. override associatedtype Element override associatedtype Index override associatedtype SubSequence override associatedtype Indices /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be nonuniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can result in an unexpected copy of the collection. To avoid /// the unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) override var indices: Indices { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) override subscript(bounds: Range<Index>) -> SubSequence { get } // FIXME: Associated type inference requires these. @_borrowed override subscript(position: Index) -> Element { get } override var startIndex: Index { get } override var endIndex: Index { get } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. override func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. override func formIndex(before i: inout Index) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. override func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. override func formIndex(after i: inout Index) /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) @_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @_nonoverride func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) @_nonoverride func distance(from start: Index, to end: Index) -> Int } // TODO: swift-3-indexing-model - (By creating an ambiguity?), try to // make sure RandomAccessCollection models implement // index(_:offsetBy:) and distance(from:to:), or they will get the // wrong complexity. /// Default implementation for random access collections. extension RandomAccessCollection { /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` should be greater than `i` to have any /// effect. Likewise, if `distance < 0`, `limit` should be less than `i` /// to have any effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: tests. let l = self.distance(from: i, to: limit) if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return index(i, offsetBy: distance) } } // Provides an alternative default associated type witness for Indices // for random access collections with strideable indices. extension RandomAccessCollection where Index: Strideable, Index.Stride == Int { @_implements(Collection, Indices) public typealias _Default_Indices = Range<Index> } extension RandomAccessCollection where Index: Strideable, Index.Stride == Int, Indices == Range<Index> { /// The indices that are valid for subscripting the collection, in ascending /// order. @inlinable public var indices: Range<Index> { return startIndex..<endIndex } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. @inlinable public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( i, bounds: Range(uncheckedBounds: (startIndex, endIndex))) return i.advanced(by: 1) } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. @inlinable // protocol-only public func index(before i: Index) -> Index { let result = i.advanced(by: -1) // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( result, bounds: Range(uncheckedBounds: (startIndex, endIndex))) return result } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) @inlinable public func index(_ i: Index, offsetBy distance: Index.Stride) -> Index { let result = i.advanced(by: distance) // This range check is not precise, tighter bounds exist based on `n`. // Unfortunately, we would need to perform index manipulation to // compute those bounds, which is probably too slow in the general // case. // FIXME: swift-3-indexing-model: tests for the trap. _failEarlyRangeCheck( result, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) return result } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. /// /// - Complexity: O(1) @inlinable public func distance(from start: Index, to end: Index) -> Index.Stride { // FIXME: swift-3-indexing-model: tests for traps. _failEarlyRangeCheck( start, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) _failEarlyRangeCheck( end, bounds: ClosedRange(uncheckedBounds: (startIndex, endIndex))) return start.distance(to: end) } }
apache-2.0
042f49adb69d75fe877241d60ae11a91
39.90566
80
0.650962
4.259332
false
false
false
false
mozilla-mobile/firefox-ios
Client/BottomSheet/BottomSheetViewModel.swift
2
1762
// 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 public struct BottomSheetViewModel { private struct UX { static let cornerRadius: CGFloat = 8 static let animationTransitionDuration: CGFloat = 0.3 } public var cornerRadius: CGFloat public var animationTransitionDuration: TimeInterval public var backgroundColor: UIColor public var sheetLightThemeBackgroundColor: UIColor public var sheetDarkThemeBackgroundColor: UIColor public var shouldDismissForTapOutside: Bool public init() { cornerRadius = BottomSheetViewModel.UX.cornerRadius animationTransitionDuration = BottomSheetViewModel.UX.animationTransitionDuration backgroundColor = .clear sheetLightThemeBackgroundColor = UIColor.Photon.LightGrey10 sheetDarkThemeBackgroundColor = UIColor.Photon.DarkGrey40 shouldDismissForTapOutside = true } public init(cornerRadius: CGFloat, animationTransitionDuration: TimeInterval, backgroundColor: UIColor, sheetLightThemeBackgroundColor: UIColor, sheetDarkThemeBackgroundColor: UIColor, shouldDismissForTapOutside: Bool) { self.cornerRadius = cornerRadius self.animationTransitionDuration = animationTransitionDuration self.backgroundColor = backgroundColor self.sheetLightThemeBackgroundColor = sheetLightThemeBackgroundColor self.sheetDarkThemeBackgroundColor = sheetDarkThemeBackgroundColor self.shouldDismissForTapOutside = shouldDismissForTapOutside } }
mpl-2.0
255baac8a0126af32bbc8c20e6d134c8
39.976744
89
0.736095
5.777049
false
false
false
false
sharath-cliqz/browser-ios
Extensions/ShareTo/InitialViewController.swift
2
6105
/* 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 import Storage private let LastUsedShareDestinationsKey = "LastUsedShareDestinations" @objc(InitialViewController) class InitialViewController: UIViewController, ShareControllerDelegate { var shareDialogController: ShareDialogController! lazy var profile: Profile = { return BrowserProfile(localName: "profile", app: nil) }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.66) // TODO: Is the correct color documented somewhere? } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in if let item = item, error == nil { DispatchQueue.main.async { guard item.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.finish() }) self.present(alert, animated: true, completion: nil) return } self.presentShareDialog(item) } } else { self.extensionContext!.completeRequestReturningItems([], completionHandler: nil); } }) } func shareControllerDidCancel(_ shareController: ShareDialogController) { UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() self.finish() }) } func finish() { self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil) } func shareController(_ shareController: ShareDialogController, didShareItem item: ShareItem, toDestinations destinations: NSSet) { setLastUsedShareDestinations(destinations) UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 0.0 }, completion: { (Bool) -> Void in self.dismissShareDialog() if destinations.contains(ShareDestinationReadingList) { self.shareToReadingList(item) } if destinations.contains(ShareDestinationBookmarks) { self.shareToBookmarks(item) } self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil); }) } // // TODO: use Set. func getLastUsedShareDestinations() -> NSSet { if let destinations = UserDefaults.standard.object(forKey: LastUsedShareDestinationsKey) as? NSArray { return NSSet(array: destinations as [AnyObject]) } return NSSet(object: ShareDestinationBookmarks) } func setLastUsedShareDestinations(_ destinations: NSSet) { UserDefaults.standard.set(destinations.allObjects, forKey: LastUsedShareDestinationsKey) UserDefaults.standard.synchronize() } func presentShareDialog(_ item: ShareItem) { shareDialogController = ShareDialogController() shareDialogController.delegate = self shareDialogController.item = item shareDialogController.initialShareDestinations = getLastUsedShareDestinations() self.addChildViewController(shareDialogController) shareDialogController.view.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(shareDialogController.view) shareDialogController.didMove(toParentViewController: self) // Setup constraints for the dialog. We keep the dialog centered with 16 points of padding on both // sides. The dialog grows to max 380 points wide so that it does not look too big on landscape or // iPad devices. let views: NSDictionary = ["dialog": shareDialogController.view] view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(16@751)-[dialog(<=380@1000)]-(16@751)-|", options: NSLayoutFormatOptions(), metrics: nil, views: (views as? [String : AnyObject])!)) let cx = NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0) cx.priority = 1000 // TODO: Why does UILayoutPriorityRequired give a linker error? SDK Bug? view.addConstraint(cx) view.addConstraint(NSLayoutConstraint(item: shareDialogController.view, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0)) // Fade the dialog in shareDialogController.view.alpha = 0.0 UIView.animate(withDuration: 0.25, animations: { () -> Void in self.shareDialogController.view.alpha = 1.0 }, completion: nil) } func dismissShareDialog() { shareDialogController.willMove(toParentViewController: nil) shareDialogController.view.removeFromSuperview() shareDialogController.removeFromParentViewController() } // func shareToReadingList(_ item: ShareItem) { profile.readingList?.createRecordWithURL(item.url, title: item.title ?? "", addedBy: UIDevice.currentDevice().name) } func shareToBookmarks(_ item: ShareItem) { profile.bookmarks.shareItem(item) } }
mpl-2.0
9d3a2eea138f5af54286484a129a6c26
41.395833
147
0.658313
5.369393
false
false
false
false
mozilla-mobile/firefox-ios
Shared/Extensions/KeychainWrapperExtensions.swift
2
2397
// 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 MozillaAppServices private let log = Logger.keychainLogger public extension MZKeychainWrapper { static var sharedClientAppContainerKeychain: MZKeychainWrapper { let baseBundleIdentifier = AppInfo.baseBundleIdentifier let accessGroupPrefix = Bundle.main.object(forInfoDictionaryKey: "MozDevelopmentTeam") as! String let accessGroupIdentifier = AppInfo.keychainAccessGroupWithPrefix(accessGroupPrefix) return MZKeychainWrapper(serviceName: baseBundleIdentifier, accessGroup: accessGroupIdentifier) } } public extension MZKeychainWrapper { func ensureClientStringItemAccessibility(_ accessibility: MZKeychainItemAccessibility, forKey key: String) { if self.hasValue(forKey: key) { if self.accessibilityOfKey(key) != .afterFirstUnlock { log.debug("updating item \(key) with \(accessibility)") guard let value = self.string(forKey: key) else { log.error("failed to get item \(key)") return } if !self.removeObject(forKey: key) { log.warning("failed to remove item \(key)") } if !self.set(value, forKey: key, withAccessibility: accessibility) { log.warning("failed to update item \(key)") } } } } func ensureObjectItemAccessibility(_ accessibility: MZKeychainItemAccessibility, forKey key: String) { if self.hasValue(forKey: key) { if self.accessibilityOfKey(key) != .afterFirstUnlock { log.debug("updating item \(key) with \(accessibility)") guard let value = self.object(forKey: key) else { log.error("failed to get item \(key)") return } if !self.removeObject(forKey: key) { log.warning("failed to remove item \(key)") } if !self.set(value, forKey: key, withAccessibility: accessibility) { log.warning("failed to update item \(key)") } } } } }
mpl-2.0
aca902424e4e08218fcf2cabeeb27a05
38.295082
112
0.604506
5.067653
false
false
false
false
DaveWoodCom/XCGLogger
Sources/XCGLogger/Misc/Optional/UserInfoHelpers.swift
3
5873
// // UserInfoHelpers.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2016-09-19. // Copyright © 2016 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // /// Protocol for creating tagging objects (ie, a tag, a developer, etc) to filter log messages by public protocol UserInfoTaggingProtocol { /// The name of the tagging object var name: String { get set } /// Convert the object to a userInfo compatible dictionary var dictionary: [String: String] { get } /// initialize the object with a name init(_ name: String) } /// Struction for tagging log messages with Tags public struct Tag: UserInfoTaggingProtocol { /// The name of the tag public var name: String /// Dictionary representation compatible with the userInfo paramater of log messages public var dictionary: [String: String] { return [XCGLogger.Constants.userInfoKeyTags: name] } /// Initialize a Tag object with a name public init(_ name: String) { self.name = name } /// Create a Tag object with a name public static func name(_ name: String) -> Tag { return Tag(name) } /// Generate a userInfo compatible dictionary for the array of tag names public static func names(_ names: String...) -> [String: [String]] { var tags: [String] = [] for name in names { tags.append(name) } return [XCGLogger.Constants.userInfoKeyTags: tags] } } /// Struction for tagging log messages with Developers public struct Dev: UserInfoTaggingProtocol { /// The name of the developer public var name: String /// Dictionary representation compatible with the userInfo paramater of log messages public var dictionary: [String: String] { return [XCGLogger.Constants.userInfoKeyDevs: name] } /// Initialize a Dev object with a name public init(_ name: String) { self.name = name } /// Create a Dev object with a name public static func name(_ name: String) -> Dev { return Dev(name) } /// Generate a userInfo compatible dictionary for the array of dev names public static func names(_ names: String...) -> [String: [String]] { var tags: [String] = [] for name in names { tags.append(name) } return [XCGLogger.Constants.userInfoKeyDevs: tags] } } /// Overloaded operator to merge userInfo compatible dictionaries together /// Note: should correctly handle combining single elements of the same key, or an element and an array, but will skip sets public func |<Key: Any, Value: Any> (lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Dictionary<Key, Any> { var mergedDictionary: Dictionary<Key, Any> = lhs rhs.forEach { key, rhsValue in guard let lhsValue = lhs[key] else { mergedDictionary[key] = rhsValue; return } guard !(rhsValue is Set<AnyHashable>) else { return } guard !(lhsValue is Set<AnyHashable>) else { return } if let lhsValue = lhsValue as? [Any], let rhsValue = rhsValue as? [Any] { // array, array -> array var mergedArray: [Any] = lhsValue mergedArray.append(contentsOf: rhsValue) mergedDictionary[key] = mergedArray } else if let lhsValue = lhsValue as? [Any] { // array, item -> array var mergedArray: [Any] = lhsValue mergedArray.append(rhsValue) mergedDictionary[key] = mergedArray } else if let rhsValue = rhsValue as? [Any] { // item, array -> array var mergedArray: [Any] = rhsValue mergedArray.append(lhsValue) mergedDictionary[key] = mergedArray } else { // two items -> array mergedDictionary[key] = [lhsValue, rhsValue] } } return mergedDictionary } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: UserInfoTaggingProtocol, rhs: UserInfoTaggingProtocol) -> Dictionary<String, Any> { return lhs.dictionary | rhs.dictionary } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: UserInfoTaggingProtocol, rhs: Dictionary<String, Any>) -> Dictionary<String, Any> { return lhs.dictionary | rhs } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: Dictionary<String, Any>, rhs: UserInfoTaggingProtocol) -> Dictionary<String, Any> { return rhs.dictionary | lhs } /// Extend UserInfoFilter to be able to use UserInfoTaggingProtocol objects public extension UserInfoFilter { /// Initializer to create an inclusion list of tags to match against /// /// Note: Only log messages with a specific tag will be logged, all others will be excluded /// /// - Parameters: /// - tags: Array of UserInfoTaggingProtocol objects to match against. /// convenience init(includeFrom tags: [UserInfoTaggingProtocol]) { var names: [String] = [] for tag in tags { names.append(tag.name) } self.init(includeFrom: names) } /// Initializer to create an exclusion list of tags to match against /// /// Note: Log messages with a specific tag will be excluded from logging /// /// - Parameters: /// - tags: Array of UserInfoTaggingProtocol objects to match against. /// convenience init(excludeFrom tags: [UserInfoTaggingProtocol]) { var names: [String] = [] for tag in tags { names.append(tag.name) } self.init(excludeFrom: names) } }
mit
ecdebc68f7b5d809398ad80d6966c904
32.554286
123
0.648331
4.562549
false
false
false
false
fakerabbit/LucasBot
Pods/SwiftyGif/SwiftyGif/UIImage+SwiftyGif.swift
1
9525
// // UIImage+SwiftyGif.swift // import ImageIO import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func <= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l <= r default: return !(rhs < lhs) } } let _imageSourceKey = malloc(4) let _displayRefreshFactorKey = malloc(4) let _imageCountKey = malloc(4) let _displayOrderKey = malloc(4) let _imageSizeKey = malloc(4) let _imageDataKey = malloc(4) let defaultLevelOfIntegrity: Float = 0.8 public extension UIImage{ // PRAGMA - Inits /** Convenience initializer. Creates a gif with its backing data. Defaulted level of integrity. - Parameter gifData: The actual gif data */ public convenience init(gifData:Data) { self.init() setGifFromData(gifData,levelOfIntegrity: defaultLevelOfIntegrity) } /** Convenience initializer. Creates a gif with its backing data. - Parameter gifData: The actual gif data - Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping */ public convenience init(gifData:Data, levelOfIntegrity:Float) { self.init() setGifFromData(gifData,levelOfIntegrity: levelOfIntegrity) } /** Convenience initializer. Creates a gif with its backing data. Defaulted level of integrity. - Parameter gifName: Filename */ public convenience init(gifName: String) { self.init() setGif(gifName, levelOfIntegrity: defaultLevelOfIntegrity) } /** Convenience initializer. Creates a gif with its backing data. - Parameter gifName: Filename - Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping */ public convenience init(gifName: String, levelOfIntegrity: Float) { self.init() setGif(gifName, levelOfIntegrity: levelOfIntegrity) } /** Set backing data for this gif. Overwrites any existing data. - Parameter data: The actual gif data - Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping */ public func setGifFromData(_ data:Data,levelOfIntegrity:Float) { self.imageData = data imageSource = CGImageSourceCreateWithData(data as CFData, nil) calculateFrameDelay(delayTimes(imageSource), levelOfIntegrity: levelOfIntegrity) calculateFrameSize() } /** Set backing data for this gif. Overwrites any existing data. - Parameter name: Filename */ public func setGif(_ name: String) { setGif(name, levelOfIntegrity: defaultLevelOfIntegrity) } /** Check the number of frame for this gif - Return number of frames */ public func framesCount() -> Int{ if let orders = self.displayOrder{ return orders.count } return 0 } /** Set backing data for this gif. Overwrites any existing data. - Parameter name: Filename - Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping */ public func setGif(_ name: String, levelOfIntegrity: Float) { if let url = Bundle.main.url(forResource: name, withExtension: "gif") { if let data = try? Data(contentsOf: url) { setGifFromData(data,levelOfIntegrity: levelOfIntegrity) } else { print("Error : Invalid GIF data for \(name).gif") } } else { print("Error : Gif file \(name).gif not found") } } // PRAGMA - Logic /** Get delay times for each frames - Parameter imageSource: reference to the gif image source - Returns array of delays */ fileprivate func delayTimes(_ imageSource:CGImageSource?)->[Float]{ let imageCount = CGImageSourceGetCount(imageSource!) var imageProperties = [CFDictionary]() for i in 0..<imageCount{ imageProperties.append(CGImageSourceCopyPropertiesAtIndex(imageSource!, i, nil)!) } let frameProperties = imageProperties.map(){ unsafeBitCast( CFDictionaryGetValue($0, Unmanaged.passUnretained(kCGImagePropertyGIFDictionary).toOpaque()),to: CFDictionary.self) } let EPS:Float = 1e-6 let frameDelays:[Float] = frameProperties.map(){ var delayObject: AnyObject = unsafeBitCast( CFDictionaryGetValue($0, Unmanaged.passUnretained(kCGImagePropertyGIFUnclampedDelayTime).toOpaque()), to: AnyObject.self) if(delayObject.floatValue<EPS){ delayObject = unsafeBitCast(CFDictionaryGetValue($0, Unmanaged.passUnretained(kCGImagePropertyGIFDelayTime).toOpaque()), to: AnyObject.self) } return delayObject as! Float } return frameDelays } /** Compute backing data for this gif - Parameter delaysArray: decoded delay times for this gif - Parameter levelOfIntegrity: 0 to 1, 1 meaning no frame skipping */ fileprivate func calculateFrameDelay(_ delaysArray:[Float],levelOfIntegrity:Float){ var delays = delaysArray //Factors send to CADisplayLink.frameInterval let displayRefreshFactors = [60,30,20,15,12,10,6,5,4,3,2,1] //maxFramePerSecond,default is 60 let maxFramePerSecond = displayRefreshFactors.first //frame numbers per second let displayRefreshRates = displayRefreshFactors.map{maxFramePerSecond!/$0} //time interval per frame let displayRefreshDelayTime = displayRefreshRates.map{1.0/Float($0)} //caclulate the time when each frame should be displayed at(start at 0) for i in 1..<delays.count{ delays[i] += delays[i-1] } //find the appropriate Factors then BREAK for i in 0..<displayRefreshDelayTime.count{ let displayPosition = delays.map{Int($0/displayRefreshDelayTime[i])} var framelosecount: Float = 0 for j in 1..<displayPosition.count{ if displayPosition[j] == displayPosition[j-1] { framelosecount += 1 } } if framelosecount <= Float(displayPosition.count) * (1.0 - levelOfIntegrity) || i == displayRefreshDelayTime.count-1 { self.imageCount = displayPosition.last! self.displayRefreshFactor = displayRefreshFactors[i] self.displayOrder = [Int]() var indexOfold = 0 var indexOfnew = 1 while indexOfnew <= imageCount { if indexOfnew <= displayPosition[indexOfold] { self.displayOrder!.append(indexOfold) indexOfnew += 1 }else{ indexOfold += 1 } } break } } } /** Compute frame size for this gif */ fileprivate func calculateFrameSize(){ let image = UIImage(cgImage: CGImageSourceCreateImageAtIndex(self.imageSource!,0,nil)!) self.imageSize = Int(image.size.height*image.size.width*4)*self.imageCount!/1000000 } // PRAGMA - get / set associated values public var imageSource: CGImageSource? { get { return (objc_getAssociatedObject(self, _imageSourceKey) as! CGImageSource?) } set { objc_setAssociatedObject(self, _imageSourceKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } public var displayRefreshFactor: Int?{ get { return (objc_getAssociatedObject(self, _displayRefreshFactorKey) as! Int) } set { objc_setAssociatedObject(self, _displayRefreshFactorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } public var imageSize: Int?{ get { return (objc_getAssociatedObject(self, _imageSizeKey) as! Int) } set { objc_setAssociatedObject(self, _imageSizeKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } public var imageCount: Int?{ get { return (objc_getAssociatedObject(self, _imageCountKey) as! Int) } set { objc_setAssociatedObject(self, _imageCountKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } public var displayOrder: [Int]?{ get { return (objc_getAssociatedObject(self, _displayOrderKey) as! [Int]) } set { objc_setAssociatedObject(self, _displayOrderKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } public var imageData: Data { get { return (objc_getAssociatedObject(self, _imageDataKey) as! Data) } set { objc_setAssociatedObject(self, _imageDataKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN); } } }
gpl-3.0
fa4e1c4d7835818b4cd6f6bc7c86e399
32.421053
152
0.593176
4.849796
false
false
false
false
mtransitapps/mtransit-for-ios
MonTransit/Source/SQL/SQLObject/TripObject.swift
1
1580
// // TripObject.swift // SidebarMenu // // Created by Thibault on 15-12-17. // Copyright © 2015 Thibault. All rights reserved. // import UIKit class TripObject: NSObject { private var mTripId:Int! private var mDirection:String! private var mRouteId:Int! override init() { mTripId = 0 mRouteId = 0 mDirection = "" } init(iTripId:Int, iDirection:String, iRouteId:Int) { self.mTripId = iTripId self.mDirection = iDirection self.mRouteId = iRouteId } func getTripId() -> Int{ return self.mTripId } func getRouteId() -> Int{ return self.mRouteId } func getTripDirection() -> String{ return getDirection(self.mDirection) } private func getDirection(iDirection:String) -> String { let wLangId = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! var wDirection = "" switch iDirection { case "N": wDirection = wLangId as! String == "fr" ? "Nord" : "North" break case "S": wDirection = wLangId as! String == "fr" ? "Sud" : "South" break case "E": wDirection = wLangId as! String == "fr" ? "Est" : "East" break case "W": wDirection = wLangId as! String == "fr" ? "Ouest" : "West" break default: wDirection = iDirection } return wDirection } }
apache-2.0
439b3eea96b37765049ff5ac20660925
22.924242
82
0.518683
4.090674
false
false
false
false
snoms/FinalProject
Trip/Trip/AppDelegate.swift
1
8774
// // AppDelegate.swift // Trip // // Created by bob on 07/06/16. // Copyright © 2016 bob. All rights reserved. // import UIKit import GoogleMaps import CoreLocation import SwiftLocation import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var newlocationManager: CLLocationManager! var seenError : Bool = false var locationFixAchieved : Bool = false var locationStatus : NSString = "Not Started" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // provide the Google API key for the Google Maps Service GMSServices.provideAPIKey(GoogleAPIkey) // enable IQ Keyboard manager IQKeyboardManager.sharedManager().enable = true // initialize location manager initLocationManager() // from http://stackoverflow.com/questions/33008072/register-notification-in-ios-9 if application.respondsToSelector("registerUserNotificationSettings:") { if #available(iOS 8.0, *) { let types:UIUserNotificationType = ([.Alert, .Sound]) let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } else { application.registerForRemoteNotificationTypes([.Alert, .Sound]) } } else { // Register for Push Notifications before iOS 8 application.registerForRemoteNotificationTypes([.Alert, .Sound]) } LocationManager.shared.allowsBackgroundEvents = true return true } // from http://stackoverflow.com/questions/34869507/device-rotation-in-a-specific-uiviewcontroller-within-uitabbarcontroller-and-uin/34869508#34869508 func application (application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask { return checkOrientation(self.window?.rootViewController) } func checkOrientation (viewController: UIViewController?) -> UIInterfaceOrientationMask { if viewController is PlannerViewController { return UIInterfaceOrientationMask.Portrait } else if viewController == nil { return UIInterfaceOrientationMask.All } else if viewController is JourneyViewController { return UIInterfaceOrientationMask.All } else if viewController is UITabBarController { if let tabBarController = viewController as? UITabBarController, navigationViewControllers = tabBarController.viewControllers as? [UINavigationController] { return checkOrientation(navigationViewControllers[tabBarController.selectedIndex].visibleViewController) } else { return UIInterfaceOrientationMask.Portrait } } else { return checkOrientation(viewController!.presentedViewController) } } // Location manager from http://stackoverflow.com/questions/24252645/how-to-get-location-user-whith-cllocationmanager-in-swift func initLocationManager() { seenError = false locationFixAchieved = false newlocationManager = CLLocationManager() newlocationManager.delegate = self CLLocationManager.locationServicesEnabled() newlocationManager.desiredAccuracy = kCLLocationAccuracyBest newlocationManager.requestAlwaysAuthorization() } func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { newlocationManager.stopUpdatingLocation() if ((error) != nil) { if (seenError == false) { seenError = true print(error) } } } func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [CLLocation]) { if (locationFixAchieved == false) { locationFixAchieved = true let locationArray = locations as NSArray let locationObj = locationArray.lastObject as! CLLocation let coord = locationObj.coordinate print(coord.latitude) print(coord.longitude) } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var shouldIAllow = false switch status { case CLAuthorizationStatus.Restricted: locationStatus = "Restricted Access to location" case CLAuthorizationStatus.Denied: locationStatus = "User denied access to location" case CLAuthorizationStatus.NotDetermined: locationStatus = "Status not determined" default: locationStatus = "Allowed to location Access" shouldIAllow = true } NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) if (shouldIAllow == true) { NSLog("Location to Allowed") // Start location services newlocationManager.startUpdatingLocation() } else { NSLog("Denied access: \(locationStatus)") } } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. LocationManager.shared.allowsBackgroundEvents = true LocationManager.shared.observeLocations(.Block, frequency: .Continuous, onSuccess: { (location) in print("background monitored: \(location)") }) { (error) in print("background error: \(error)") } } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. RouteManager.sharedInstance.clearRoute() } func handleRegionEvent(region: CLRegion!) { if UIApplication.sharedApplication() .applicationState != UIApplicationState.Active { let notification = UILocalNotification() notification.alertBody = "Wake up, you're approaching \(region.identifier). Get ready!" notification.alertAction = "Open Trip" notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["message":region.identifier] UIApplication.sharedApplication().presentLocalNotificationNow(notification) } else { let nc = NSNotificationCenter.defaultCenter() nc.postNotificationName("fenceProx", object: nil, userInfo: ["message":region.identifier]) } } func locationManager(manager: CLLocationManager, didEnterRegion region: CLRegion) { if region is CLCircularRegion { handleRegionEvent(region) print("Entered") } } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { if region is CLCircularRegion { print("Region Exited") } } }
mit
3403b61c7b0937620aafff41914aa493
42.651741
285
0.67514
6.050345
false
false
false
false
i-schuetz/SwiftCharts
SwiftCharts/Layers/ChartShowCoordsLinesLayer.swift
3
2673
// // ChartShowCoordsLinesLayer.swift // swift_charts // // Created by ischuetz on 19/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit // TODO improve behaviour during zooming and panning - line has to be only translated, not scaled. Needs .translate behaviour of ChartPointsViewsLayer, maybe we can extend this layer? open class ChartShowCoordsLinesLayer<T: ChartPoint>: ChartPointsLayer<T> { fileprivate var view: UIView? fileprivate var activeChartPoint: T? public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints: [T]) { super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints) } open func showChartPointLines(_ chartPoint: T, chart: Chart) { if let view = self.view { activeChartPoint = chartPoint for v in view.subviews { v.removeFromSuperview() } let screenLoc = chartPointScreenLoc(chartPoint) let hLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1)) let vLine = UIView(frame: CGRect(x: screenLoc.x, y: screenLoc.y, width: 0, height: 1)) for lineView in [hLine, vLine] { lineView.backgroundColor = UIColor.black view.addSubview(lineView) } func animations() { let axisOriginX = modelLocToScreenLoc(x: xAxis.first) let axisOriginY = modelLocToScreenLoc(y: yAxis.first) let axisLengthY = axisOriginY - modelLocToScreenLoc(y: yAxis.last) hLine.frame = CGRect(x: axisOriginX, y: screenLoc.y, width: screenLoc.x - axisOriginX, height: 1) vLine.frame = CGRect(x: screenLoc.x, y: screenLoc.y, width: 1, height: axisLengthY - screenLoc.y) } UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: { animations() }, completion: nil) } } override open func display(chart: Chart) { let view = UIView(frame: chart.bounds) view.isUserInteractionEnabled = true chart.addSubview(view) self.view = view } open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) { super.zoom(x, y: y, centerX: centerX, centerY: centerY) updateChartPointsScreenLocations() } open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) { super.pan(deltaX, deltaY: deltaY) updateChartPointsScreenLocations() } }
apache-2.0
be27538d0ab1f523708cf32776a4f9e3
35.616438
183
0.599701
4.522843
false
false
false
false
jhurray/SQLiteModel-Example-Project
tvOS+SQLiteModel/Pods/SQLite.swift/SQLite/Extensions/FTS4.swift
12
5574
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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 Module { @warn_unused_result public static func FTS4(column: Expressible, _ more: Expressible...) -> Module { return FTS4([column] + more) } @warn_unused_result public static func FTS4(columns: [Expressible] = [], tokenize tokenizer: Tokenizer? = nil) -> Module { var columns = columns if let tokenizer = tokenizer { columns.append("=".join([Expression<Void>(literal: "tokenize"), Expression<Void>(literal: tokenizer.description)])) } return Module(name: "fts4", arguments: columns) } } extension VirtualTable { /// Builds an expression appended with a `MATCH` query against the given /// pattern. /// /// let emails = VirtualTable("emails") /// /// emails.filter(emails.match("Hello")) /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: An expression appended with a `MATCH` query against the given /// pattern. @warn_unused_result public func match(pattern: String) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(pattern: Expression<String>) -> Expression<Bool> { return "MATCH".infix(tableName(), pattern) } @warn_unused_result public func match(pattern: Expression<String?>) -> Expression<Bool?> { return "MATCH".infix(tableName(), pattern) } /// Builds a copy of the query with a `WHERE … MATCH` clause. /// /// let emails = VirtualTable("emails") /// /// emails.match("Hello") /// // SELECT * FROM "emails" WHERE "emails" MATCH 'Hello' /// /// - Parameter pattern: A pattern to match. /// /// - Returns: A query with the given `WHERE … MATCH` clause applied. @warn_unused_result public func match(pattern: String) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(pattern: Expression<String>) -> QueryType { return filter(match(pattern)) } @warn_unused_result public func match(pattern: Expression<String?>) -> QueryType { return filter(match(pattern)) } } public struct Tokenizer { public static let Simple = Tokenizer("simple") public static let Porter = Tokenizer("porter") @warn_unused_result public static func Unicode61(removeDiacritics removeDiacritics: Bool? = nil, tokenchars: Set<Character> = [], separators: Set<Character> = []) -> Tokenizer { var arguments = [String]() if let removeDiacritics = removeDiacritics { arguments.append("removeDiacritics=\(removeDiacritics ? 1 : 0)".quote()) } if !tokenchars.isEmpty { let joined = tokenchars.map { String($0) }.joinWithSeparator("") arguments.append("tokenchars=\(joined)".quote()) } if !separators.isEmpty { let joined = separators.map { String($0) }.joinWithSeparator("") arguments.append("separators=\(joined)".quote()) } return Tokenizer("unicode61", arguments) } @warn_unused_result public static func Custom(name: String) -> Tokenizer { return Tokenizer(Tokenizer.moduleName.quote(), [name.quote()]) } public let name: String public let arguments: [String] private init(_ name: String, _ arguments: [String] = []) { self.name = name self.arguments = arguments } private static let moduleName = "SQLite.swift" } extension Tokenizer : CustomStringConvertible { public var description: String { return ([name] + arguments).joinWithSeparator(" ") } } extension Connection { public func registerTokenizer(submoduleName: String, next: String -> (String, Range<String.Index>)?) throws { try check(_SQLiteRegisterTokenizer(handle, Tokenizer.moduleName, submoduleName) { input, offset, length in let string = String.fromCString(input)! guard let (token, range) = next(string) else { return nil } let view = string.utf8 offset.memory += string.substringToIndex(range.startIndex).utf8.count length.memory = Int32(range.startIndex.samePositionIn(view).distanceTo(range.endIndex.samePositionIn(view))) return token }) } }
mit
ef378d0073d5e0639b42dd47511c6eb0
34.246835
181
0.654516
4.458767
false
false
false
false
MessageKit/MessageKit
Plugins/SwiftLintCommandPlugin/SwiftLintCommandPlugin.swift
1
2043
// MIT License // // Copyright (c) 2017-2022 MessageKit // // 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 PackagePlugin // MARK: - SwiftLintCommandPlugin @main struct SwiftLintCommandPlugin: CommandPlugin { func performCommand(context: PackagePlugin.PluginContext, arguments _: [String]) async throws { let swiftLintTool = try context.tool(named: "swiftlint") let swiftLintPath = URL(fileURLWithPath: swiftLintTool.path.string) let swiftLintArgs = [ "lint", "--path", context.package.directory.string, "--config", context.package.directory.string + "/.swiftlint.yml", "--strict", ] let task = try Process.run(swiftLintPath, arguments: swiftLintArgs) task.waitUntilExit() if task.terminationStatus == 0 || task.terminationStatus == 2 { // no-op } else { throw CommandError.unknownError(exitCode: task.terminationStatus) } } } // MARK: - CommandError enum CommandError: Error { case unknownError(exitCode: Int32) }
mit
09ea7a792f6af4006b6c31db8aac6848
36.833333
97
0.736172
4.45098
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/Delegate List/DelegateListViewController.swift
1
4318
// Copyright (c) 2016 Ark // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit import SwiftyArk class DelegateListViewController: ArkViewController { fileprivate var tableView : ArkTableView! fileprivate var delegates = [Delegate]() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Delegates" tableView = ArkTableView(CGRect.zero) tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) tableView.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } NotificationCenter.default.addObserver(self, selector: #selector(updateDelegates), name: NSNotification.Name(rawValue: ArkNotifications.delegateListUpdated.rawValue), object: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) setNeedsStatusBarAppearanceUpdate() updateDelegates() } @objc private func updateDelegates() { guard let currentDelegates = ArkDataManager.currentDelegates else { return } self.delegates = currentDelegates tableView.reloadData() } } // MARK: UITableViewDelegate extension DelegateListViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 35.0 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = DelegateListSectionHeaderView(frame: CGRect(x: 0.0, y: 0.0, width: _screenWidth, height: 35.0)) return header } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 45.0 } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if let aCell = cell as? DelegateTableViewCell { aCell.update(delegates[indexPath.row]) } } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat.leastNormalMagnitude } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return nil } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let vc = DelegateDetailViewController(delegates[indexPath.row]) navigationController?.pushViewController(vc, animated: true) } } // MARK: UITableViewDatasource extension DelegateListViewController : UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let count = delegates.count return count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "delegate") if cell == nil { cell = DelegateTableViewCell(style: .default, reuseIdentifier: "delegate") } return cell! } }
mit
0ea305711aa442d5e316090ee78ced24
37.900901
187
0.692913
5.311193
false
false
false
false
WEzou/weiXIn
swift-zw/MainViewController.swift
1
2677
// // MainViewController.swift // swift-zw // // Created by ymt on 2017/12/12. // Copyright © 2017年 ymt. All rights reserved. // import UIKit import Alamofire class MainViewController: UITabBarController,loginProtocol { //一定要强引用 var sessionManager : SessionManager! override func viewDidLoad() { super.viewDidLoad() configuration() setupSubview() } func configuration(){ UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(0x999999),NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], for: .normal) UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor(0x2d2d2d),NSAttributedStringKey.font:UIFont.systemFont(ofSize: 11)], for: .selected) //shadowImage与backgroundImage不会自动索引提示,要自己打出来 UITabBar.appearance().shadowImage = UIImage() UITabBar.appearance().backgroundImage = UIImage.imageWithColor(UIColor(0xf5f5f5)) } func setupSubview(){ childViewController(CommonViewController(), title: "首页", image: "home_normal", select: "home_select") childViewController(PersonViewController(), title: "个人中心", image: "user_normal", select: "user_select") let count = self.viewControllers?.count let customTabBar = CustomTabBar(count!) { (_ size: CGSize) -> UIView in let customTabBarItemView = CustomTabBarItemView(frame:CGRect(x:0,y:0,width:size.width,height:size.height)) customTabBarItemView.delegate = self as loginProtocol return customTabBarItemView } self.setValue(customTabBar, forKeyPath: "tabBar") } func childViewController(_ viewC: UIViewController,title: String,image: String,select: String){ let baseNav = BaseNavigationController(rootViewController: viewC) let image_normal = UIImage(named:image)?.withRenderingMode(.alwaysOriginal) let image_select = UIImage(named:select)?.withRenderingMode(.alwaysOriginal) baseNav.tabBarItem = UITabBarItem.init(title: title, image: image_normal, selectedImage: image_select) //一定要用调用addChildViewController,不能使用viewControllers,会有按钮的选中的问题 self.addChildViewController(baseNav) } func loginAction() { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
3482a3a1df2d0fc3f7ce06554bc168e9
35.8
189
0.661491
5.111111
false
false
false
false
rudkx/swift
stdlib/private/StdlibUnicodeUnittest/UnicodeScalarProperties.swift
1
17285
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 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 // //===----------------------------------------------------------------------===// // Unicode scalar tests are currently only avaible on Darwin, awaiting a sensible // file API... #if _runtime(_ObjC) import Foundation // Cache of opened files var cachedFiles: [String: String] = [:] func readInputFile(_ filename: String) -> String { let path = CommandLine.arguments[2] do { guard let cache = cachedFiles[filename] else { let contents = try String(contentsOfFile: path + filename, encoding: .utf8) cachedFiles[filename] = contents return contents } return cache } catch { fatalError(error.localizedDescription) } } func parseScalars(_ string: String) -> ClosedRange<UInt32> { // If we have . appear, it means we have a legitimate range. Otherwise, // it's a singular scalar. if string.contains(".") { let range = string.split(separator: ".") return UInt32(range[0], radix: 16)! ... UInt32(range[1], radix: 16)! } else { let scalar = UInt32(string, radix: 16)! return scalar ... scalar } } //===----------------------------------------------------------------------===// // Binary Properties //===----------------------------------------------------------------------===// // Note: If one ever updates this list, be it adding new properties, removing, // etc., please update the same list found in: // 'stdlib/public/core/UnicodeScalarProperties.swift'. let availableBinaryProperties: Set<String> = [ "Alphabetic", "ASCII_Hex_Digit", "Bidi_Control", "Bidi_Mirrored", "Cased", "Case_Ignorable", "Changes_When_Casefolded", "Changes_When_Casemapped", "Changes_When_Lowercased", "Changes_When_NFKC_Casefolded", "Changes_When_Titlecased", "Changes_When_Uppercased", "Dash", "Default_Ignorable_Code_Point", "Deprecated", "Diacritic", "Emoji", "Emoji_Modifier", "Emoji_Modifier_Base", "Emoji_Presentation", "Extender", "Full_Composition_Exclusion", "Grapheme_Base", "Grapheme_Extend", "Hex_Digit", "ID_Continue", "ID_Start", "Ideographic", "IDS_Binary_Operator", "IDS_Trinary_Operator", "Join_Control", "Logical_Order_Exception", "Lowercase", "Math", "Noncharacter_Code_Point", "Other_Alphabetic", "Other_Default_Ignorable_Code_Point", "Other_Grapheme_Extend", "Other_ID_Continue", "Other_ID_Start", "Other_Lowercase", "Other_Math", "Other_Uppercase", "Pattern_Syntax", "Pattern_White_Space", "Quotation_Mark", "Radical", "Sentence_Terminal", "Soft_Dotted", "Terminal_Punctuation", "Unified_Ideograph", "Uppercase", "Variation_Selector", "White_Space", "XID_Continue", "XID_Start" ] func parseBinaryProperties( _ data: String, into result: inout [String: Set<Unicode.Scalar>] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") // Get the property first because we may not care about it. let filteredProperty = components[1].filter { !$0.isWhitespace } guard availableBinaryProperties.contains(filteredProperty) else { continue } let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) for scalar in scalars { result[filteredProperty, default: []].insert(Unicode.Scalar(scalar)!) } } } // A dictionary of all currently exposed Unicode Scalar Properties. Keyed by // the literal property name and values being the set of scalars who all conform // to said property. public let binaryProperties: [String: Set<Unicode.Scalar>] = { var result: [String: Set<Unicode.Scalar>] = [:] #if canImport(Darwin) let derivedCoreProps = readInputFile("Apple/DerivedCoreProperties.txt") #else let derivedCoreProps = readInputFile("DerivedCoreProperties.txt") #endif parseBinaryProperties(derivedCoreProps, into: &result) let derivedNormalizationProps = readInputFile("DerivedNormalizationProps.txt") parseBinaryProperties(derivedNormalizationProps, into: &result) let derivedBinaryProperties = readInputFile("DerivedBinaryProperties.txt") parseBinaryProperties(derivedBinaryProperties, into: &result) let propList = readInputFile("PropList.txt") parseBinaryProperties(propList, into: &result) let emojiData = readInputFile("emoji-data.txt") parseBinaryProperties(emojiData, into: &result) return result }() //===----------------------------------------------------------------------===// // Numeric Properties //===----------------------------------------------------------------------===// func parseNumericTypes( _ data: String, into result: inout [Unicode.Scalar: Unicode.NumericType] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") let filteredProperty = components[1].filter { !$0.isWhitespace } let numericType: Unicode.NumericType switch filteredProperty { case "Numeric": numericType = .numeric case "Decimal": numericType = .decimal case "Digit": numericType = .digit default: continue } let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) for scalar in scalars { result[Unicode.Scalar(scalar)!] = numericType } } } func parseNumericValues( _ data: String, into result: inout [Unicode.Scalar: Double] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") let filteredProperty = components[3].filter { !$0.isWhitespace } let value: Double // If we have a division, split the numerator and denominator and perform // the division ourselves to get the correct double value. if filteredProperty.contains("/") { let splitDivision = filteredProperty.split(separator: "/") let numerator = Double(splitDivision[0])! let denominator = Double(splitDivision[1])! value = numerator / denominator } else { value = Double(filteredProperty)! } let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) for scalar in scalars { result[Unicode.Scalar(scalar)!] = value } } } // A dictionary of every scalar who has a numeric type and it's value. public let numericTypes: [Unicode.Scalar: Unicode.NumericType] = { var result: [Unicode.Scalar: Unicode.NumericType] = [:] let derivedNumericType = readInputFile("DerivedNumericType.txt") parseNumericTypes(derivedNumericType, into: &result) return result }() // A dictionary of scalar to numeric value. public let numericValues: [Unicode.Scalar: Double] = { var result: [Unicode.Scalar: Double] = [:] let derivedNumericValues = readInputFile("DerivedNumericValues.txt") parseNumericValues(derivedNumericValues, into: &result) return result }() //===----------------------------------------------------------------------===// // Scalar Mappings //===----------------------------------------------------------------------===// func parseMappings( _ data: String, into result: inout [Unicode.Scalar: [String: String]] ) { for line in data.split(separator: "\n") { let components = line.split(separator: ";", omittingEmptySubsequences: false) let scalarStr = components[0] guard let scalar = Unicode.Scalar(UInt32(scalarStr, radix: 16)!) else { continue } if let upper = UInt32(components[12], radix: 16) { let mapping = String(Unicode.Scalar(upper)!) result[scalar, default: [:]]["upper"] = mapping } if let lower = UInt32(components[13], radix: 16) { let mapping = String(Unicode.Scalar(lower)!) result[scalar, default: [:]]["lower"] = mapping } if let title = UInt32(components[14], radix: 16) { let mapping = String(Unicode.Scalar(title)!) result[scalar, default: [:]]["title"] = mapping } } } func parseSpecialMappings( _ data: String, into result: inout [Unicode.Scalar: [String: String]] ) { for line in data.split(separator: "\n") { guard !line.hasPrefix("#") else { continue } let components = line.split(separator: ";", omittingEmptySubsequences: false) // Conditional mappings have an extra component with the conditional name. // Ignore those. guard components.count == 5 else { continue } guard let scalar = Unicode.Scalar(UInt32(components[0], radix: 16)!) else { continue } let lower = components[1].split(separator: " ").map { Character(Unicode.Scalar(UInt32($0, radix: 16)!)!) } let title = components[2].split(separator: " ").map { Character(Unicode.Scalar(UInt32($0, radix: 16)!)!) } let upper = components[3].split(separator: " ").map { Character(Unicode.Scalar(UInt32($0, radix: 16)!)!) } if lower.count != 1 { result[scalar, default: [:]]["lower"] = String(lower) } if title.count != 1 { result[scalar, default: [:]]["title"] = String(title) } if upper.count != 1 { result[scalar, default: [:]]["upper"] = String(upper) } } } // A dictionary of every scalar mapping keyed by the scalar and returning another // dictionary who is then keyed by either "lower", "upper", or "title". public let mappings: [Unicode.Scalar: [String: String]] = { var result: [Unicode.Scalar: [String: String]] = [:] #if canImport(Darwin) let unicodeData = readInputFile("Apple/UnicodeData.txt") #else let unicodeData = readInputFile("UnicodeData.txt") #endif let specialCasing = readInputFile("SpecialCasing.txt") parseMappings(unicodeData, into: &result) parseSpecialMappings(specialCasing, into: &result) return result }() //===----------------------------------------------------------------------===// // Scalar Age //===----------------------------------------------------------------------===// func parseAge( _ data: String, into result: inout [Unicode.Scalar: Unicode.Version] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) let version = components[1].filter { !$0.isWhitespace } let parts = version.split(separator: ".") let major = Int(parts[0])! let minor = Int(parts[1])! for scalar in scalars { guard let scalar = Unicode.Scalar(scalar) else { continue } result[scalar] = (major, minor) } } } public let ages: [Unicode.Scalar: Unicode.Version] = { var result: [Unicode.Scalar: Unicode.Version] = [:] let derivedAge = readInputFile("DerivedAge.txt") parseAge(derivedAge, into: &result) return result }() //===----------------------------------------------------------------------===// // Scalar General Category //===----------------------------------------------------------------------===// func parseGeneralCategory( _ data: String, into result: inout [Unicode.Scalar: Unicode.GeneralCategory] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") let filteredCategory = components[1].filter { !$0.isWhitespace } let category: Unicode.GeneralCategory switch filteredCategory { case "Lu": category = .uppercaseLetter case "Ll": category = .lowercaseLetter case "Lt": category = .titlecaseLetter case "Lm": category = .modifierLetter case "Lo": category = .otherLetter case "Mn": category = .nonspacingMark case "Mc": category = .spacingMark case "Me": category = .enclosingMark case "Nd": category = .decimalNumber case "Nl": category = .letterNumber case "No": category = .otherNumber case "Pc": category = .connectorPunctuation case "Pd": category = .dashPunctuation case "Ps": category = .openPunctuation case "Pe": category = .closePunctuation case "Pi": category = .initialPunctuation case "Pf": category = .finalPunctuation case "Po": category = .otherPunctuation case "Sm": category = .mathSymbol case "Sc": category = .currencySymbol case "Sk": category = .modifierSymbol case "So": category = .otherSymbol case "Zs": category = .spaceSeparator case "Zl": category = .lineSeparator case "Zp": category = .paragraphSeparator case "Cc": category = .control case "Cf": category = .format case "Cs": category = .surrogate case "Co": category = .privateUse case "Cn": category = .unassigned default: continue } let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) for scalar in scalars { guard let scalar = Unicode.Scalar(scalar) else { continue } result[scalar] = category } } } public let generalCategories: [Unicode.Scalar: Unicode.GeneralCategory] = { var result: [Unicode.Scalar: Unicode.GeneralCategory] = [:] let derivedGeneralCategory = readInputFile("DerivedGeneralCategory.txt") parseGeneralCategory(derivedGeneralCategory, into: &result) return result }() //===----------------------------------------------------------------------===// // Scalar Name Alias //===----------------------------------------------------------------------===// func parseNameAliases( _ data: String, into result: inout [Unicode.Scalar: String] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") // Name aliases are only found with correction attribute. guard components[2] == "correction" else { continue } let filteredScalars = components[0].filter { !$0.isWhitespace } guard let scalar = Unicode.Scalar(UInt32(filteredScalars, radix: 16)!) else { continue } let nameAlias = String(components[1]) result[scalar] = nameAlias } } public let nameAliases: [Unicode.Scalar: String] = { var result: [Unicode.Scalar: String] = [:] let nameAliases = readInputFile("NameAliases.txt") parseNameAliases(nameAliases, into: &result) return result }() //===----------------------------------------------------------------------===// // Scalar Name //===----------------------------------------------------------------------===// func parseNames( _ data: String, into result: inout [Unicode.Scalar: String] ) { for line in data.split(separator: "\n") { // Skip comments guard !line.hasPrefix("#") else { continue } let info = line.split(separator: "#") let components = info[0].split(separator: ";") let filteredScalars = components[0].filter { !$0.isWhitespace } let scalars = parseScalars(String(filteredScalars)) // If our scalar is a range of scalars, then the name is usually something // like NAME-HERE-* where * is the scalar value. if scalars.count > 1 { for scalar in scalars { guard let scalar = Unicode.Scalar(scalar) else { continue } var name = String(components[1]) // There's leftover spacing in the beginning of the name that we need to // get rid of. name.removeFirst() name.removeLast() name += "\(String(scalar.value, radix: 16, uppercase: true))" result[scalar] = name } } else { guard let scalar = Unicode.Scalar(scalars.lowerBound) else { continue } var name = String(components[1]) // There's leftover spacing in the beginning of the name that we need to // get rid of. name.removeFirst() result[scalar] = name } } } public let names: [Unicode.Scalar: String] = { var result: [Unicode.Scalar: String] = [:] let derivedName = readInputFile("DerivedName.txt") parseNames(derivedName, into: &result) return result }() #endif
apache-2.0
064f81084c25cbd6687eb871db2b0045
26.092476
81
0.60457
4.311549
false
false
false
false
ddimitrov90/EverliveSDK
Tests/Pods/EverliveSDK/EverliveSDK/Sorting.swift
2
1063
// // Sorting.swift // EverliveSwift // // Created by Dimitar Dimitrov on 3/22/16. // Copyright © 2016 ddimitrov. All rights reserved. // import Foundation import SwiftyJSON public enum OrderDirection: Int { case Ascending = 1 case Descending = -1 } public class Sorting { var sortFields:[String:Int] //private var fieldsOrder: [String] public required init(fieldName: String, orderDirection: OrderDirection){ self.sortFields = [:] //self.fieldsOrder = [] self.addSortField(fieldName, orderDirection: orderDirection) } public func addSortField(fieldName:String, orderDirection: OrderDirection){ self.sortFields[fieldName] = orderDirection.rawValue //self.fieldsOrder.append(fieldName) } public func getSortObject() -> String { if self.sortFields.count > 0 { let sortObject:JSON = JSON(self.sortFields) return sortObject.rawString(NSUTF8StringEncoding, options: NSJSONWritingOptions(rawValue: 0))! } return "" } }
mit
d94048e6c614e0be60aac273a90f1556
26.25641
106
0.664783
4.231076
false
false
false
false
luckymore0520/leetcode
Spiral Matrix.playground/Contents.swift
1
1619
//: Playground - noun: a place where people can play import UIKit // //Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. // //For example, //Given the following matrix: // //[ //[ 1, 2, 3 ], //[ 4, 5, 6 ], //[ 7, 8, 9 ] //] //You should return [1,2,3,6,9,8,7,4,5]. class Solution { func spiralOrder(_ matrix: [[Int]]) -> [Int] { var result:[Int] = [] let row = matrix.count if (row == 0) { return result } let column = matrix[0].count for i in 0...(min(row,column) + 1) / 2 - 1 { if (column - i - 1 >= i) { for j in i...column - i - 1 { result.append(matrix[i][j]) } } // print(result) if (row - i - 1 >= i+1) { for j in i+1...row - i - 1 { result.append(matrix[j][column-i-1]) } } // print(result) if (row - i - 1 > i && column - i - 2 >= i) { for j in (i...column - i - 2).reversed() { result.append(matrix[row-i-1][j]) } } // print(result) if (column-i-1 > i && row - i - 2 >= i+1) { for j in (i+1...row - i - 2).reversed() { result.append(matrix[j][i]) } } // print(result) } return result } } let solution = Solution() solution.spiralOrder([[1,2,3],[4,5,6],[7,8,9]])
mit
bcafb73d375e864ae5123bc24538987f
23.923077
106
0.398394
3.550439
false
false
false
false
qvik/qvik-network-ios
QvikNetwork/Download.swift
1
3171
// The MIT License (MIT) // // Copyright (c) 2015-2016 Qvik (www.qvik.fi) // // 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 func == (lhs: Download, rhs: Download) -> Bool { return lhs === rhs } /** A single download handle. Do not create Download objects directly but instead through a DownloadManager/DownloadGroup instances. All callbacks are called on the main (UI) thread (main queue). All the methods in this class are thread safe. */ open class Download: Equatable { public enum State { case notInitialized case starting case inProgress case failed case completed } public enum Errors: Error { case badResponse(statusCode: Int) } /// Download progress callback open var progressCallback: DownloadProgressCallback? /// Download completion callback open var completionCallback: DownloadCompletionCallback? /// Arbitrary user data for use by the caller open var userData: AnyObject? /// URL of this download fileprivate(set) open var url: String /// Download group of this download or nil if single download internal(set) open var group: DownloadGroup? /// State of this download internal(set) open var state: State /// Number of bytes downloaded internal(set) open var bytesDownloaded: UInt64 /// Total size of the download internal(set) open var totalSize: UInt64? /// The Content-Type of this download. Set upon completion. internal(set) open var contentType: String? /// Error that occurred while downloading or nil if none internal(set) open var error: Error? init(url: String) { self.url = url self.state = .notInitialized self.bytesDownloaded = 0 } } extension Download: CustomDebugStringConvertible { public var debugDescription: String { return "Download(url: \(self.url), state: \(state))" } } extension Download: CustomStringConvertible { public var description: String { return "Download(url: \(self.url), state: \(state))" } }
mit
03e16b5f82394694de7dec06c762ada0
31.357143
103
0.699149
4.704748
false
false
false
false
gokush/GKAddressKit
GKAddressKitExample/Address/CityEntity.swift
1
2107
// // CityEntity.swift // GKAddressKit // // Created by 童小波 on 15/1/19. // Copyright (c) 2015年 tongxiaobo. All rights reserved. // import Foundation import CoreData @objc(CityEntity) class CityEntity: NSManagedObject { @NSManaged var cityId: NSNumber @NSManaged var name: String @NSManaged var pinyin: String @NSManaged var refresh: Bool @NSManaged var addresses: NSMutableSet @NSManaged var province: ProvinceEntity! @NSManaged var districts: NSMutableSet class func insertCity(cityId: Int, cityName: String, pinyin: String, managedObjectContext: NSManagedObjectContext) -> CityEntity{ let city = NSEntityDescription.insertNewObjectForEntityForName("CityEntity", inManagedObjectContext: managedObjectContext) as CityEntity city.cityId = cityId city.name = cityName city.pinyin = pinyin return city } class func selectWithId(cityId: Int, managedObjectContext: NSManagedObjectContext) -> CityEntity?{ let predicate = NSPredicate(format: "cityId == \(cityId)") let city = fetchItems(predicate!, managedObjectContext: managedObjectContext) as? CityEntity return city } func updateCity(cityId: Int?, name: String?, pinyin: String?){ if cityId != nil{ self.cityId = cityId! } if name != nil{ self.name = name! } if pinyin != nil{ self.pinyin = pinyin! } } } extension CityEntity{ func addProvinceObject(value: NSManagedObject){ self.province = value as ProvinceEntity } } extension CityEntity{ func addDistrictsObject(value: NSManagedObject){ self.districts.addObject(value) } func removeDistrictsObject(value: NSManagedObject){ self.districts.removeObject(value) } func removeDistricts(values: [NSManagedObject]){ for item in values{ self.removeDistrictsObject(item) } } } extension CityEntity{ func addAddressesObject(value: AddressEntity){ self.addresses.addObject(value) } }
mit
1db04e12a95840a4761f97ea02514864
27.753425
144
0.666508
4.465957
false
false
false
false
yanagiba/swift-ast
Sources/AST/Declaration/FunctionDeclaration.swift
2
2391
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ public class FunctionDeclaration : ASTNode, Declaration { public let attributes: Attributes public let modifiers: DeclarationModifiers public let name: Identifier public let genericParameterClause: GenericParameterClause? public private(set) var signature: FunctionSignature public let genericWhereClause: GenericWhereClause? public let body: CodeBlock? public init( attributes: Attributes = [], modifiers: DeclarationModifiers = [], name: Identifier, genericParameterClause: GenericParameterClause? = nil, signature: FunctionSignature, genericWhereClause: GenericWhereClause? = nil, body: CodeBlock? = nil ) { self.attributes = attributes self.modifiers = modifiers self.name = name self.genericParameterClause = genericParameterClause self.signature = signature self.genericWhereClause = genericWhereClause self.body = body } // MARK: - Node Mutations public func replaceSignature(with newSignature: FunctionSignature) { signature = newSignature } // MARK: - ASTTextRepresentable override public var textDescription: String { let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) " let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) " let headText = "\(attrsText)\(modifiersText)func" let genericParameterClauseText = genericParameterClause?.textDescription ?? "" let signatureText = signature.textDescription let genericWhereClauseText = genericWhereClause.map({ " \($0.textDescription)" }) ?? "" let bodyText = body.map({ " \($0.textDescription)" }) ?? "" return "\(headText) \(name)\(genericParameterClauseText)\(signatureText)\(genericWhereClauseText)\(bodyText)" } }
apache-2.0
a0dd4ed775e1b50d7d5a6f16d4b609bd
37.564516
113
0.73944
5.289823
false
false
false
false
banDedo/BDModules
HarnessModules/FavoritesViewController/FavoritesViewController.swift
1
7470
// // FavoritesViewController.swift // BDModules // // Created by Patrick Hogan on 1/11/15. // Copyright (c) 2015 bandedo. All rights reserved. // import UIKit public class FavoritesViewController: LifecycleViewController, UITableViewDataSource, UITableViewDelegate { // MARK:- Enumerate type public enum Section: Int { case Collection = 0 case Loading = 1 static var count: Int { var max: Int = 0 while let _ = self(rawValue: ++max) {} return max } } // MARK:- Injectable public lazy var accountUserProvider = AccountUserProvider() public lazy var imageViewLazyLoader = ImageViewLazyLoader() public lazy var favoriteLocationRepository = Repository<Location>() public lazy var oAuth2SessionManager = OAuth2SessionManager() public lazy var mainFactory = MainFactory() weak public var delegate: MenuNavigationControllerDelegate? // MARK:- Properties private lazy var tableView: UITableView = { let tableView = UITableView(frame: CGRectZero) tableView.allowsSelection = false tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.delaysContentTouches = true tableView.backgroundColor = Color.whiteColor tableView.dataSource = self tableView.delegate = self tableView.registerClass(FavoriteLocationCell.self, forCellReuseIdentifier: FavoriteLocationCell.identifier) tableView.registerClass(LoadingCell.self, forCellReuseIdentifier: LoadingCell.identifier) return tableView }() // MARK:- Cleanup deinit { tableView.dataSource = nil tableView.delegate = nil } // MARK:- View lifecycle public override func viewDidLoad() { super.viewDidLoad() title = "Favorites" view.backgroundColor = Color.whiteColor view.addSubview(tableView) tableView.snp_makeConstraints { make in make.edges.equalTo(UIEdgeInsetsZero) } } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NavigationBar.addMenuButton(target: self, action: "handleButtonTap:") } // MARK:- UI Update public func updateUI(animated: Bool = false, newElements: [ Location ]? = nil) { if animated && newElements != nil && count(newElements!) > 0 { switch favoriteLocationRepository.fetchState { case .Fetched: tableView.beginUpdates() var currentIndex = favoriteLocationRepository.elementCount - count(newElements!) for newElement in newElements! { tableView.insertRowsAtIndexPaths( [ NSIndexPath(forRow: currentIndex, inSection: Section.Collection.rawValue) ], withRowAnimation: UITableViewRowAnimation.Automatic ) currentIndex++ } if favoriteLocationRepository.atEnd { tableView.deleteRowsAtIndexPaths( [ NSIndexPath(forRow: 0, inSection: Section.Loading.rawValue) ], withRowAnimation: UITableViewRowAnimation.Automatic ) } tableView.endUpdates() break case .NotFetched, .Fetching, .Error: break } } else { tableView.reloadData() } } // MARK:- Favorite Locations private func fetchFavoriteLocations(handler: ([ Location ]?, NSError?) -> Void = { $0 }) { if favoriteLocationRepository.atEnd { return } let isEmptyLocationRepository = favoriteLocationRepository.elementCount == 0 favoriteLocationRepository.fetch() { [weak self] locations, error in if let strongSelf = self { if error != nil { let alertController = UIAlertController( title: "Error", message: error!.description, preferredStyle: UIAlertControllerStyle.Alert ) alertController.addAction( UIAlertAction( title: "OK", style: UIAlertActionStyle.Cancel) { action in strongSelf.dismissViewControllerAnimated(true, completion: nil) } ) strongSelf.presentViewController(alertController, animated: true, completion: nil) } strongSelf.updateUI(animated: !isEmptyLocationRepository, newElements: locations) handler(locations, error) } } } // MARK:- Action Handlers public func handleButtonTap(sender: UIButton) { delegate?.viewController(self, didTapMenuButton: sender) } // MARK:- Status Bar public override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.Default } // MARK:- UITableViewDataSource/UITableViewDelegate public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return Section.count } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch Section(rawValue: section)! { case .Collection: return favoriteLocationRepository.elementCount case .Loading: return favoriteLocationRepository.atEnd ? 0 : 1 } } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { switch Section(rawValue: indexPath.section)! { case .Collection: let cell = tableView.dequeueReusableCellWithIdentifier(FavoriteLocationCell.identifier, forIndexPath: indexPath) as! FavoriteLocationCell cell.tag = indexPath.row let location = favoriteLocationRepository.elements[indexPath.row] imageViewLazyLoader.setImage( URLString: location.imageUrl, imageView: cell.backgroundImageView, animated: true ) cell.primaryLabel.text = location.title cell.secondaryLabel.text = location.subtitle return cell case .Loading: let cell = tableView.dequeueReusableCellWithIdentifier(LoadingCell.identifier, forIndexPath: indexPath) as! LoadingCell cell.activityIndicatorView.startAnimating() fetchFavoriteLocations() return cell } } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch Section(rawValue: indexPath.section)! { case .Collection: return Layout.largeCellHeight case .Loading: return Layout.mediumCellHeight } } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
apache-2.0
33938590893b5bfb48b07553a9e6d03e
34.741627
149
0.595448
6.240602
false
false
false
false
frootloops/swift
benchmark/single-source/PopFront.swift
3
1745
//===--- PopFront.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import TestsUtils public let PopFront = [ BenchmarkInfo(name: "PopFrontArray", runFunction: run_PopFrontArray, tags: [.validation, .api, .Array]), BenchmarkInfo(name: "PopFrontUnsafePointer", runFunction: run_PopFrontUnsafePointer, tags: [.validation, .api]), ] let reps = 1 let arrayCount = 1024 @inline(never) public func run_PopFrontArray(_ N: Int) { let orig = Array(repeating: 1, count: arrayCount) var a = [Int]() for _ in 1...20*N { for _ in 1...reps { var result = 0 a.append(contentsOf: orig) while a.count != 0 { result += a[0] a.remove(at: 0) } CheckResults(result == arrayCount) } } } @inline(never) public func run_PopFrontUnsafePointer(_ N: Int) { var orig = Array(repeating: 1, count: arrayCount) let a = UnsafeMutablePointer<Int>.allocate(capacity: arrayCount) for _ in 1...100*N { for _ in 1...reps { for i in 0..<arrayCount { a[i] = orig[i] } var result = 0 var count = arrayCount while count != 0 { result += a[0] a.assign(from: a + 1, count: count - 1) count -= 1 } CheckResults(result == arrayCount) } } a.deallocate(capacity: arrayCount) }
apache-2.0
c39aa5ec5cecea2776be52c8e3f7f8b1
27.606557
114
0.582235
3.93018
false
false
false
false
WildDogTeam/lib-ios-streambase
StreamBaseExample/StreamBaseKit/Util/Inflight.swift
1
1592
// // Inflight.swift // StreamBaseKit // // Created by IMacLi on 15/10/12. // Copyright © 2015年 liwuyang. All rights reserved. // import UIKit /** RAII interface for network activity indicator: simply keep an Inflight object in scope for the duration of the request. As long as you're not leaking Inflight objects, the underlying counter will remain accurate. There are a few ways to make sure this works with closures. Example usage: var inflight : Inflight? = Inflight() doSomethingInBackground() { inflight = nil } */ public class Inflight { /** Indicates that some work is happening and network activity indicator should appear. */ public init() { InflightManager.sharedManager.increment() } deinit { InflightManager.sharedManager.decrement() } func hold() { } } private class InflightManager { private static let sharedManager = InflightManager() var counter: UnsafeMutablePointer<Int32> init() { counter = UnsafeMutablePointer<Int32>.alloc(1) counter.initialize(0) } deinit { counter.dealloc(1) } func increment() { OSAtomicIncrement32(counter) UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func decrement() { let newValue = OSAtomicDecrement32(counter) assert(newValue >= 0) if newValue == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } }
mit
a0331ca22343ffe4d853851f7c3c8f3d
23.84375
87
0.638767
4.786145
false
false
false
false
gkaimakas/SwiftyFormsUI
Example/Tests/Tests.swift
1
749
// https://github.com/Quick/Quick import Quick import Nimble import SwiftyFormsUI class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } } } } }
mit
80fe65166033e73fb9c5131aedaf2ec5
20.228571
60
0.391655
5.02027
false
false
false
false
mikaoj/BSImagePicker
Example/ViewController.swift
1
5270
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import BSImagePicker import Photos class ViewController: UIViewController { @IBAction func showImagePicker(_ sender: UIButton) { let imagePicker = ImagePickerController() imagePicker.settings.selection.max = 5 imagePicker.settings.theme.selectionStyle = .numbered imagePicker.settings.fetch.assets.supportedMediaTypes = [.image, .video] imagePicker.settings.selection.unselectOnReachingMax = true let start = Date() self.presentImagePicker(imagePicker, select: { (asset) in print("Selected: \(asset)") }, deselect: { (asset) in print("Deselected: \(asset)") }, cancel: { (assets) in print("Canceled with selections: \(assets)") }, finish: { (assets) in print("Finished with selections: \(assets)") }, completion: { let finish = Date() print(finish.timeIntervalSince(start)) }) } @IBAction func showCustomImagePicker(_ sender: UIButton) { let imagePicker = ImagePickerController() imagePicker.settings.selection.max = 1 imagePicker.settings.selection.unselectOnReachingMax = true imagePicker.settings.fetch.assets.supportedMediaTypes = [.image, .video] imagePicker.albumButton.tintColor = UIColor.green imagePicker.cancelButton.tintColor = UIColor.red imagePicker.doneButton.tintColor = UIColor.purple imagePicker.navigationBar.barTintColor = .black imagePicker.settings.theme.backgroundColor = .black imagePicker.settings.theme.selectionFillColor = UIColor.gray imagePicker.settings.theme.selectionStrokeColor = UIColor.yellow imagePicker.settings.theme.selectionShadowColor = UIColor.red imagePicker.settings.theme.previewTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),NSAttributedString.Key.foregroundColor: UIColor.white] imagePicker.settings.theme.previewSubtitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12),NSAttributedString.Key.foregroundColor: UIColor.white] imagePicker.settings.theme.albumTitleAttributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 18),NSAttributedString.Key.foregroundColor: UIColor.white] imagePicker.settings.list.cellsPerRow = {(verticalSize: UIUserInterfaceSizeClass, horizontalSize: UIUserInterfaceSizeClass) -> Int in switch (verticalSize, horizontalSize) { case (.compact, .regular): // iPhone5-6 portrait return 2 case (.compact, .compact): // iPhone5-6 landscape return 2 case (.regular, .regular): // iPad portrait/landscape return 3 default: return 2 } } self.presentImagePicker(imagePicker, select: { (asset) in print("Selected: \(asset)") }, deselect: { (asset) in print("Deselected: \(asset)") }, cancel: { (assets) in print("Canceled with selections: \(assets)") }, finish: { (assets) in print("Finished with selections: \(assets)") }) } @IBAction func showImagePickerWithSelectedAssets(_ sender: UIButton) { let allAssets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil) var evenAssets = [PHAsset]() allAssets.enumerateObjects({ (asset, idx, stop) -> Void in if idx % 2 == 0 { evenAssets.append(asset) } }) let imagePicker = ImagePickerController(selectedAssets: evenAssets) imagePicker.settings.fetch.assets.supportedMediaTypes = [.image] self.presentImagePicker(imagePicker, select: { (asset) in print("Selected: \(asset)") }, deselect: { (asset) in print("Deselected: \(asset)") }, cancel: { (assets) in print("Canceled with selections: \(assets)") }, finish: { (assets) in print("Finished with selections: \(assets)") }) } }
mit
dc794c6a3cca8854d558302b9d79ebb6
44.817391
177
0.666161
4.952068
false
false
false
false
srn214/Floral
Floral/Pods/WCDB.swift/swift/source/util/RWLock.swift
1
2208
/* * Tencent is pleased to support the open source community by making * WCDB available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. * All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use * this file except in compliance with the License. You may obtain a copy of * the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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 final class RWLock { var mutex = pthread_mutex_t() var cond = pthread_cond_t() var reader = 0 var writer = 0 var pending = 0 init() { pthread_mutex_init(&mutex, nil) pthread_cond_init(&cond, nil) } deinit { pthread_cond_destroy(&cond) pthread_mutex_destroy(&mutex) } func lockRead() { pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } while writer>0 || pending>0 { pthread_cond_wait(&cond, &mutex) } reader += 1 } func unlockRead() { pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } reader -= 1 if reader == 0 { pthread_cond_broadcast(&cond) } } func lockWrite() { pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } pending += 1 while writer>0||reader>0 { pthread_cond_wait(&cond, &mutex) } pending -= 1 writer += 1 } func unlockWrite() { pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } writer -= 1 pthread_cond_broadcast(&cond) } var isWriting: Bool { pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } return writer>0 } // var isReading: Bool { // pthread_mutex_lock(&mutex); defer { pthread_mutex_unlock(&mutex) } // return reader>0 // } }
mit
7e2561e726615a22e32c66f9f956dc31
26.259259
76
0.606884
3.928826
false
false
false
false
srn214/Floral
Floral/Pods/SwiftyUserDefaults/Sources/DefaultsObserver.swift
2
3742
// // SwiftyUserDefaults // // Copyright (c) 2015-present Radosław Pietruszewski, Łukasz Mróz // // 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 DefaultsDisposable { func dispose() } #if !os(Linux) public final class DefaultsObserver<T: DefaultsSerializable>: NSObject, DefaultsDisposable { public struct Update { public let kind: NSKeyValueChange public let indexes: IndexSet? public let isPrior: Bool public let newValue: T.T? public let oldValue: T.T? init(dict: [NSKeyValueChangeKey: Any], key: DefaultsKey<T>) { // swiftlint:disable:next force_cast kind = NSKeyValueChange(rawValue: dict[.kindKey] as! UInt)! indexes = dict[.indexesKey] as? IndexSet isPrior = dict[.notificationIsPriorKey] as? Bool ?? false oldValue = Update.deserialize(dict[.oldKey], for: key) ?? key.defaultValue newValue = Update.deserialize(dict[.newKey], for: key) ?? key.defaultValue } private static func deserialize(_ value: Any?, for key: DefaultsKey<T>) -> T.T? { guard let value = value else { return nil } let bridge = T._defaults if bridge.isSerialized() { return bridge.deserialize(value) } else { return value as? T.T } } } private let key: DefaultsKey<T> private let userDefaults: UserDefaults private let handler: ((Update) -> Void) private var didRemoveObserver = false init(key: DefaultsKey<T>, userDefaults: UserDefaults, options: NSKeyValueObservingOptions, handler: @escaping ((Update) -> Void)) { self.key = key self.userDefaults = userDefaults self.handler = handler super.init() userDefaults.addObserver(self, forKeyPath: key._key, options: options, context: nil) } deinit { dispose() } // swiftlint:disable:next block_based_kvo public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { guard let change = change, object != nil, keyPath == key._key else { return } let update = Update(dict: change, key: key) handler(update) } public func dispose() { // We use this local property because when you use `removeObserver` when you are // not actually observing anymore, you'll receive a runtime error. if didRemoveObserver { return } didRemoveObserver = true userDefaults.removeObserver(self, forKeyPath: key._key, context: nil) } } #endif
mit
36f160aa9b9e6606b403e3ae948d0831
36.767677
157
0.669698
4.685464
false
false
false
false
aschwaighofer/swift
stdlib/public/core/Runtime.swift
2
19717
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// /// This file contains Swift wrappers for functions defined in the C++ runtime. /// //===----------------------------------------------------------------------===// import SwiftShims //===----------------------------------------------------------------------===// // Atomics //===----------------------------------------------------------------------===// @_transparent public // @testable func _stdlib_atomicCompareExchangeStrongPtr( object target: UnsafeMutablePointer<UnsafeRawPointer?>, expected: UnsafeMutablePointer<UnsafeRawPointer?>, desired: UnsafeRawPointer? ) -> Bool { // We use Builtin.Word here because Builtin.RawPointer can't be nil. let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word( target._rawValue, UInt(bitPattern: expected.pointee)._builtinWordValue, UInt(bitPattern: desired)._builtinWordValue) expected.pointee = UnsafeRawPointer(bitPattern: Int(oldValue)) return Bool(won) } /// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially /// consistent memory ordering. Precise semantics are defined in C++11 or C11. /// /// - Warning: This operation is extremely tricky to use correctly because of /// writeback semantics. /// /// It is best to use it directly on an /// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point /// directly to the memory where the value is stored. /// /// In a call like this: /// /// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...) /// /// you need to manually make sure that: /// /// - all properties in the chain are physical (to make sure that no writeback /// happens; the compare-and-exchange instruction should operate on the /// shared memory); and /// /// - the shared memory that you are accessing is located inside a heap /// allocation (a class instance property, a `_BridgingBuffer`, a pointer to /// an `Array` element etc.) /// /// If the conditions above are not met, the code will still compile, but the /// compare-and-exchange instruction will operate on the writeback buffer, and /// you will get a *race* while doing writeback into shared memory. @_transparent public // @testable func _stdlib_atomicCompareExchangeStrongPtr<T>( object target: UnsafeMutablePointer<UnsafeMutablePointer<T>>, expected: UnsafeMutablePointer<UnsafeMutablePointer<T>>, desired: UnsafeMutablePointer<T> ) -> Bool { let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound( to: Optional<UnsafeRawPointer>.self) let rawExpected = UnsafeMutableRawPointer(expected).assumingMemoryBound( to: Optional<UnsafeRawPointer>.self) return _stdlib_atomicCompareExchangeStrongPtr( object: rawTarget, expected: rawExpected, desired: UnsafeRawPointer(desired)) } /// Atomic compare and exchange of `UnsafeMutablePointer<T>` with sequentially /// consistent memory ordering. Precise semantics are defined in C++11 or C11. /// /// - Warning: This operation is extremely tricky to use correctly because of /// writeback semantics. /// /// It is best to use it directly on an /// `UnsafeMutablePointer<UnsafeMutablePointer<T>>` that is known to point /// directly to the memory where the value is stored. /// /// In a call like this: /// /// _stdlib_atomicCompareExchangeStrongPtr(&foo.property1.property2, ...) /// /// you need to manually make sure that: /// /// - all properties in the chain are physical (to make sure that no writeback /// happens; the compare-and-exchange instruction should operate on the /// shared memory); and /// /// - the shared memory that you are accessing is located inside a heap /// allocation (a class instance property, a `_BridgingBuffer`, a pointer to /// an `Array` element etc.) /// /// If the conditions above are not met, the code will still compile, but the /// compare-and-exchange instruction will operate on the writeback buffer, and /// you will get a *race* while doing writeback into shared memory. @_transparent public // @testable func _stdlib_atomicCompareExchangeStrongPtr<T>( object target: UnsafeMutablePointer<UnsafeMutablePointer<T>?>, expected: UnsafeMutablePointer<UnsafeMutablePointer<T>?>, desired: UnsafeMutablePointer<T>? ) -> Bool { let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound( to: Optional<UnsafeRawPointer>.self) let rawExpected = UnsafeMutableRawPointer(expected).assumingMemoryBound( to: Optional<UnsafeRawPointer>.self) return _stdlib_atomicCompareExchangeStrongPtr( object: rawTarget, expected: rawExpected, desired: UnsafeRawPointer(desired)) } @_transparent @discardableResult public // @testable func _stdlib_atomicInitializeARCRef( object target: UnsafeMutablePointer<AnyObject?>, desired: AnyObject ) -> Bool { var expected: UnsafeRawPointer? let desiredPtr = Unmanaged.passRetained(desired).toOpaque() let rawTarget = UnsafeMutableRawPointer(target).assumingMemoryBound( to: Optional<UnsafeRawPointer>.self) let wonRace = _stdlib_atomicCompareExchangeStrongPtr( object: rawTarget, expected: &expected, desired: desiredPtr) if !wonRace { // Some other thread initialized the value. Balance the retain that we // performed on 'desired'. Unmanaged.passUnretained(desired).release() } return wonRace } @_transparent public // @testable func _stdlib_atomicLoadARCRef( object target: UnsafeMutablePointer<AnyObject?> ) -> AnyObject? { let value = Builtin.atomicload_seqcst_Word(target._rawValue) if let unwrapped = UnsafeRawPointer(bitPattern: Int(value)) { return Unmanaged<AnyObject>.fromOpaque(unwrapped).takeUnretainedValue() } return nil } //===----------------------------------------------------------------------===// // Conversion of primitive types to `String` //===----------------------------------------------------------------------===// /// A 32 byte buffer. internal struct _Buffer32 { internal init() {} internal var _x0: UInt8 = 0 internal var _x1: UInt8 = 0 internal var _x2: UInt8 = 0 internal var _x3: UInt8 = 0 internal var _x4: UInt8 = 0 internal var _x5: UInt8 = 0 internal var _x6: UInt8 = 0 internal var _x7: UInt8 = 0 internal var _x8: UInt8 = 0 internal var _x9: UInt8 = 0 internal var _x10: UInt8 = 0 internal var _x11: UInt8 = 0 internal var _x12: UInt8 = 0 internal var _x13: UInt8 = 0 internal var _x14: UInt8 = 0 internal var _x15: UInt8 = 0 internal var _x16: UInt8 = 0 internal var _x17: UInt8 = 0 internal var _x18: UInt8 = 0 internal var _x19: UInt8 = 0 internal var _x20: UInt8 = 0 internal var _x21: UInt8 = 0 internal var _x22: UInt8 = 0 internal var _x23: UInt8 = 0 internal var _x24: UInt8 = 0 internal var _x25: UInt8 = 0 internal var _x26: UInt8 = 0 internal var _x27: UInt8 = 0 internal var _x28: UInt8 = 0 internal var _x29: UInt8 = 0 internal var _x30: UInt8 = 0 internal var _x31: UInt8 = 0 internal mutating func withBytes<Result>( _ body: (UnsafeMutablePointer<UInt8>) throws -> Result ) rethrows -> Result { return try withUnsafeMutablePointer(to: &self) { try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self)) } } } /// A 72 byte buffer. internal struct _Buffer72 { internal init() {} internal var _x0: UInt8 = 0 internal var _x1: UInt8 = 0 internal var _x2: UInt8 = 0 internal var _x3: UInt8 = 0 internal var _x4: UInt8 = 0 internal var _x5: UInt8 = 0 internal var _x6: UInt8 = 0 internal var _x7: UInt8 = 0 internal var _x8: UInt8 = 0 internal var _x9: UInt8 = 0 internal var _x10: UInt8 = 0 internal var _x11: UInt8 = 0 internal var _x12: UInt8 = 0 internal var _x13: UInt8 = 0 internal var _x14: UInt8 = 0 internal var _x15: UInt8 = 0 internal var _x16: UInt8 = 0 internal var _x17: UInt8 = 0 internal var _x18: UInt8 = 0 internal var _x19: UInt8 = 0 internal var _x20: UInt8 = 0 internal var _x21: UInt8 = 0 internal var _x22: UInt8 = 0 internal var _x23: UInt8 = 0 internal var _x24: UInt8 = 0 internal var _x25: UInt8 = 0 internal var _x26: UInt8 = 0 internal var _x27: UInt8 = 0 internal var _x28: UInt8 = 0 internal var _x29: UInt8 = 0 internal var _x30: UInt8 = 0 internal var _x31: UInt8 = 0 internal var _x32: UInt8 = 0 internal var _x33: UInt8 = 0 internal var _x34: UInt8 = 0 internal var _x35: UInt8 = 0 internal var _x36: UInt8 = 0 internal var _x37: UInt8 = 0 internal var _x38: UInt8 = 0 internal var _x39: UInt8 = 0 internal var _x40: UInt8 = 0 internal var _x41: UInt8 = 0 internal var _x42: UInt8 = 0 internal var _x43: UInt8 = 0 internal var _x44: UInt8 = 0 internal var _x45: UInt8 = 0 internal var _x46: UInt8 = 0 internal var _x47: UInt8 = 0 internal var _x48: UInt8 = 0 internal var _x49: UInt8 = 0 internal var _x50: UInt8 = 0 internal var _x51: UInt8 = 0 internal var _x52: UInt8 = 0 internal var _x53: UInt8 = 0 internal var _x54: UInt8 = 0 internal var _x55: UInt8 = 0 internal var _x56: UInt8 = 0 internal var _x57: UInt8 = 0 internal var _x58: UInt8 = 0 internal var _x59: UInt8 = 0 internal var _x60: UInt8 = 0 internal var _x61: UInt8 = 0 internal var _x62: UInt8 = 0 internal var _x63: UInt8 = 0 internal var _x64: UInt8 = 0 internal var _x65: UInt8 = 0 internal var _x66: UInt8 = 0 internal var _x67: UInt8 = 0 internal var _x68: UInt8 = 0 internal var _x69: UInt8 = 0 internal var _x70: UInt8 = 0 internal var _x71: UInt8 = 0 internal mutating func withBytes<Result>( _ body: (UnsafeMutablePointer<UInt8>) throws -> Result ) rethrows -> Result { return try withUnsafeMutablePointer(to: &self) { try body(UnsafeMutableRawPointer($0).assumingMemoryBound(to: UInt8.self)) } } } // Note that this takes a Float32 argument instead of Float16, because clang // doesn't have _Float16 on all platforms yet. @_silgen_name("swift_float16ToString") internal func _float16ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: Float32, _ debug: Bool ) -> Int @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) internal func _float16ToString( _ value: Float16, debug: Bool ) -> (buffer: _Buffer32, length: Int) { _internalInvariant(MemoryLayout<_Buffer32>.size == 32) var buffer = _Buffer32() let length = buffer.withBytes { (bufferPtr) in _float16ToStringImpl(bufferPtr, 32, Float(value), debug) } return (buffer, length) } // Returns a UInt64, but that value is the length of the string, so it's // guaranteed to fit into an Int. This is part of the ABI, so we can't // trivially change it to Int. Callers can safely convert the result // to any integer type without checks, however. @_silgen_name("swift_float32ToString") internal func _float32ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: Float32, _ debug: Bool ) -> UInt64 internal func _float32ToString( _ value: Float32, debug: Bool ) -> (buffer: _Buffer32, length: Int) { _internalInvariant(MemoryLayout<_Buffer32>.size == 32) var buffer = _Buffer32() let length = buffer.withBytes { (bufferPtr) in Int( truncatingIfNeeded: _float32ToStringImpl(bufferPtr, 32, value, debug) )} return (buffer, length) } // Returns a UInt64, but that value is the length of the string, so it's // guaranteed to fit into an Int. This is part of the ABI, so we can't // trivially change it to Int. Callers can safely convert the result // to any integer type without checks, however. @_silgen_name("swift_float64ToString") internal func _float64ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: Float64, _ debug: Bool ) -> UInt64 internal func _float64ToString( _ value: Float64, debug: Bool ) -> (buffer: _Buffer32, length: Int) { _internalInvariant(MemoryLayout<_Buffer32>.size == 32) var buffer = _Buffer32() let length = buffer.withBytes { (bufferPtr) in Int( truncatingIfNeeded: _float64ToStringImpl(bufferPtr, 32, value, debug) )} return (buffer, length) } #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) // Returns a UInt64, but that value is the length of the string, so it's // guaranteed to fit into an Int. This is part of the ABI, so we can't // trivially change it to Int. Callers can safely convert the result // to any integer type without checks, however. @_silgen_name("swift_float80ToString") internal func _float80ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: Float80, _ debug: Bool ) -> UInt64 internal func _float80ToString( _ value: Float80, debug: Bool ) -> (buffer: _Buffer32, length: Int) { _internalInvariant(MemoryLayout<_Buffer32>.size == 32) var buffer = _Buffer32() let length = buffer.withBytes { (bufferPtr) in Int( truncatingIfNeeded: _float80ToStringImpl(bufferPtr, 32, value, debug) )} return (buffer, length) } #endif // Returns a UInt64, but that value is the length of the string, so it's // guaranteed to fit into an Int. This is part of the ABI, so we can't // trivially change it to Int. Callers can safely convert the result // to any integer type without checks, however. @_silgen_name("swift_int64ToString") internal func _int64ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: Int64, _ radix: Int64, _ uppercase: Bool ) -> UInt64 internal func _int64ToString( _ value: Int64, radix: Int64 = 10, uppercase: Bool = false ) -> String { if radix >= 10 { var buffer = _Buffer32() return buffer.withBytes { (bufferPtr) in let actualLength = _int64ToStringImpl(bufferPtr, 32, value, radix, uppercase) return String._fromASCII(UnsafeBufferPointer( start: bufferPtr, count: Int(truncatingIfNeeded: actualLength) )) } } else { var buffer = _Buffer72() return buffer.withBytes { (bufferPtr) in let actualLength = _int64ToStringImpl(bufferPtr, 72, value, radix, uppercase) return String._fromASCII(UnsafeBufferPointer( start: bufferPtr, count: Int(truncatingIfNeeded: actualLength) )) } } } // Returns a UInt64, but that value is the length of the string, so it's // guaranteed to fit into an Int. This is part of the ABI, so we can't // trivially change it to Int. Callers can safely convert the result // to any integer type without checks, however. @_silgen_name("swift_uint64ToString") internal func _uint64ToStringImpl( _ buffer: UnsafeMutablePointer<UTF8.CodeUnit>, _ bufferLength: UInt, _ value: UInt64, _ radix: Int64, _ uppercase: Bool ) -> UInt64 public // @testable func _uint64ToString( _ value: UInt64, radix: Int64 = 10, uppercase: Bool = false ) -> String { if radix >= 10 { var buffer = _Buffer32() return buffer.withBytes { (bufferPtr) in let actualLength = _uint64ToStringImpl(bufferPtr, 32, value, radix, uppercase) return String._fromASCII(UnsafeBufferPointer( start: bufferPtr, count: Int(truncatingIfNeeded: actualLength) )) } } else { var buffer = _Buffer72() return buffer.withBytes { (bufferPtr) in let actualLength = _uint64ToStringImpl(bufferPtr, 72, value, radix, uppercase) return String._fromASCII(UnsafeBufferPointer( start: bufferPtr, count: Int(truncatingIfNeeded: actualLength) )) } } } @inlinable internal func _rawPointerToString(_ value: Builtin.RawPointer) -> String { var result = _uint64ToString( UInt64( UInt(bitPattern: UnsafeRawPointer(value))), radix: 16, uppercase: false ) for _ in 0..<(2 * MemoryLayout<UnsafeRawPointer>.size - result.utf16.count) { result = "0" + result } return "0x" + result } #if _runtime(_ObjC) // At runtime, these classes are derived from `__SwiftNativeNSXXXBase`, // which are derived from `NSXXX`. // // The @swift_native_objc_runtime_base attribute // allows us to subclass an Objective-C class and still use the fast Swift // memory allocator. // // NOTE: older runtimes called these _SwiftNativeNSXXX. The two must // coexist, so they were renamed. The old names must not be used in the // new runtime. @_fixed_layout @usableFromInline @objc @_swift_native_objc_runtime_base(__SwiftNativeNSArrayBase) internal class __SwiftNativeNSArray { @inlinable @nonobjc internal init() {} // @objc public init(coder: AnyObject) {} @inlinable deinit {} } @_fixed_layout @usableFromInline @objc @_swift_native_objc_runtime_base(__SwiftNativeNSMutableArrayBase) internal class _SwiftNativeNSMutableArray { @inlinable @nonobjc internal init() {} // @objc public init(coder: AnyObject) {} @inlinable deinit {} } @_fixed_layout @usableFromInline @objc @_swift_native_objc_runtime_base(__SwiftNativeNSDictionaryBase) internal class __SwiftNativeNSDictionary { @nonobjc internal init() {} @objc public init(coder: AnyObject) {} deinit {} } @_fixed_layout @usableFromInline @objc @_swift_native_objc_runtime_base(__SwiftNativeNSSetBase) internal class __SwiftNativeNSSet { @nonobjc internal init() {} @objc public init(coder: AnyObject) {} deinit {} } @objc @_swift_native_objc_runtime_base(__SwiftNativeNSEnumeratorBase) internal class __SwiftNativeNSEnumerator { @nonobjc internal init() {} @objc public init(coder: AnyObject) {} deinit {} } //===----------------------------------------------------------------------===// // Support for reliable testing of the return-autoreleased optimization //===----------------------------------------------------------------------===// @objc internal class __stdlib_ReturnAutoreleasedDummy { @objc internal init() {} // Use 'dynamic' to force Objective-C dispatch, which uses the // return-autoreleased call sequence. @objc internal dynamic func returnsAutoreleased(_ x: AnyObject) -> AnyObject { return x } } /// This function ensures that the return-autoreleased optimization works. /// /// On some platforms (for example, x86_64), the first call to /// `objc_autoreleaseReturnValue` will always autorelease because it would fail /// to verify the instruction sequence in the caller. On x86_64 certain PLT /// entries would be still pointing to the resolver function, and sniffing /// the call sequence would fail. /// /// This code should live in the core stdlib dylib because PLT tables are /// separate for each dylib. /// /// Call this function in a fresh autorelease pool. public func _stdlib_initializeReturnAutoreleased() { #if arch(x86_64) // On x86_64 it is sufficient to perform one cycle of return-autoreleased // call sequence in order to initialize all required PLT entries. let dummy = __stdlib_ReturnAutoreleasedDummy() _ = dummy.returnsAutoreleased(dummy) #endif } #else @_fixed_layout @usableFromInline internal class __SwiftNativeNSArray { @inlinable internal init() {} @inlinable deinit {} } @_fixed_layout @usableFromInline internal class __SwiftNativeNSDictionary { @inlinable internal init() {} @inlinable deinit {} } @_fixed_layout @usableFromInline internal class __SwiftNativeNSSet { @inlinable internal init() {} @inlinable deinit {} } #endif
apache-2.0
e76382b4b9268a36260b4756ff94a118
31.164763
84
0.682558
3.935529
false
false
false
false
brightdigit/speculid
scripts/mfizz.swift
1
1889
//// swiftlint:disable all //import Cocoa // //struct LCGroupIcon : Codable { // let iconName : String? // let iconSet : String? //} // //let mfizzPath = "/Users/leo/Documents/Projects/lansingcodes-iOS-app/graphics/mfizz" //let mfizzURL = URL(fileURLWithPath: mfizzPath, isDirectory: true) //let svgsURL = mfizzURL.appendingPathComponent("svgs") //let speculidDirURL = mfizzURL.appendingPathComponent("speculid") //let imageSetPath = URL(fileURLWithPath: "/Users/leo/Documents/Projects/lansingcodes-iOS-app/lansingcodes-iOS-app/Image.imageset", isDirectory: true) //let destinationFolder = URL(fileURLWithPath: "/Users/leo/Documents/Projects/lansingcodes-iOS-app/lansingcodes-iOS-app/Assets.xcassets/Group Icons", isDirectory: true) //if FileManager.default.fileExists(atPath: speculidDirURL.path) { // try! FileManager.default.removeItem(at: speculidDirURL) // //} //try! FileManager.default.createDirectory(at: speculidDirURL, withIntermediateDirectories: true, attributes: nil) //let speculidContents = """ //{ // "set" : "../../../lansingcodes-iOS-app/Assets.xcassets/Group Icons/%@.imageset", // "source" : "../svgs/%@", // "geometry" : "32" //} //""" //let files = try! FileManager.default.contentsOfDirectory(at: svgsURL, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions()) // //for file in files { // guard file.pathExtension == "svg" else { // continue // } // let fullName = "mfizz."+file.deletingPathExtension().lastPathComponent // let speculidJSON = String(format: speculidContents, fullName, file.lastPathComponent) // // try? FileManager.default.copyItem(at: imageSetPath, to: destinationFolder.appendingPathComponent(fullName).appendingPathExtension("imageset")) // try! speculidJSON.write(to: speculidDirURL.appendingPathComponent(fullName).appendingPathExtension("speculid"), atomically: true, encoding: .utf8) //} // //
mit
08ddf45364a04b7a0c5c0530f662d99d
46.225
168
0.747485
3.725838
false
false
false
false
jpsim/SourceKitten
Source/SourceKittenFramework/Clang+SourceKitten.swift
1
10409
#if !os(Linux) #if SWIFT_PACKAGE import Clang_C #endif import Foundation import SWXMLHash private var _interfaceUUIDMap = [String: String]() private var _interfaceUUIDMapLock = NSLock() /// Thread safe read from sourceKitUID map private func uuidString(`for` sourceKitUID: String) -> String? { _interfaceUUIDMapLock.lock() defer { _interfaceUUIDMapLock.unlock() } return _interfaceUUIDMap[sourceKitUID] } /// Thread safe write from sourceKitUID map private func setUUIDString(uidString: String, `for` file: String) { _interfaceUUIDMapLock.lock() defer { _interfaceUUIDMapLock.unlock() } _interfaceUUIDMap[file] = uidString } struct ClangIndex { private let index = clang_createIndex(0, 1) func open(file: String, args: [UnsafePointer<Int8>?]) -> CXTranslationUnit { return clang_createTranslationUnitFromSourceFile(index, file, Int32(args.count), args, 0, nil)! } } public struct ClangAvailability { public let alwaysDeprecated: Bool public let alwaysUnavailable: Bool public let deprecationMessage: String? public let unavailableMessage: String? } extension CXString: CustomStringConvertible { func str() -> String? { if let cString = clang_getCString(self) { return String(validatingUTF8: cString) } return nil } public var description: String { return str() ?? "<null>" } } extension CXTranslationUnit { func cursor() -> CXCursor { return clang_getTranslationUnitCursor(self) } } extension CXCursor { func location() -> SourceLocation { return SourceLocation(clangLocation: clang_getCursorLocation(self)) } func extent() -> (start: SourceLocation, end: SourceLocation) { let extent = clang_getCursorExtent(self) let start = SourceLocation(clangLocation: clang_getRangeStart(extent)) let end = SourceLocation(clangLocation: clang_getRangeEnd(extent)) return (start, end) } func shouldDocument() -> Bool { return clang_isDeclaration(kind) != 0 && kind != CXCursor_ParmDecl && kind != CXCursor_TemplateTypeParameter && clang_Location_isInSystemHeader(clang_getCursorLocation(self)) == 0 } func declaration() -> String? { let comment = parsedComment() if comment.kind() == CXComment_Null { return str() } let commentXML = clang_FullComment_getAsXML(comment).str() ?? "" guard let rootXML = XMLHash.parse(commentXML).children.first else { fatalError("couldn't parse XML") } guard let text = rootXML["Declaration"].element?.text, !text.isEmpty else { return nil } return text .replacingOccurrences(of: "\n@end", with: "") .replacingOccurrences(of: "@property(", with: "@property (") } func objCKind() -> ObjCDeclarationKind { return ObjCDeclarationKind(kind) } func str() -> String? { let cursorExtent = extent() guard FileManager.default.fileExists(atPath: cursorExtent.start.file) else { return nil } guard let content = try? String(contentsOfFile: cursorExtent.start.file, encoding: .utf8) else { return nil } let contents = StringView(content) return contents.substringWithSourceRange(start: cursorExtent.start, end: cursorExtent.end) } func name() -> String? { let type = objCKind() if type == .category, let usrNSString = usr() as NSString? { let ext = (usrNSString.range(of: "c:objc(ext)").location == 0) let regex = try! NSRegularExpression(pattern: "(\\w+)@(\\w+)", options: []) let range = NSRange(location: 0, length: usrNSString.length) let matches = regex.matches(in: usrNSString as String, options: [], range: range) if matches.isEmpty { return nil } else { let categoryOn = usrNSString.substring(with: matches[0].range(at: 1)) let categoryName = ext ? "" : usrNSString.substring(with: matches[0].range(at: 2)) return "\(categoryOn)(\(categoryName))" } } let spelling = clang_getCursorSpelling(self).str()! if type == .methodInstance { return "-" + spelling } else if type == .methodClass { return "+" + spelling } return spelling } func usr() -> String? { return clang_getCursorUSR(self).str() } func platformAvailability() -> ClangAvailability { var alwaysDeprecated: Int32 = 0 var alwaysUnavailable: Int32 = 0 var deprecationString = CXString() var unavailableString = CXString() _ = clang_getCursorPlatformAvailability(self, &alwaysDeprecated, &deprecationString, &alwaysUnavailable, &unavailableString, nil, 0) return ClangAvailability(alwaysDeprecated: alwaysDeprecated != 0, alwaysUnavailable: alwaysUnavailable != 0, deprecationMessage: deprecationString.description, unavailableMessage: unavailableString.description) } func visit(_ block: @escaping (CXCursor, CXCursor) -> CXChildVisitResult) { _ = clang_visitChildrenWithBlock(self, block) } func parsedComment() -> CXComment { return clang_Cursor_getParsedComment(self) } func compactMap<T>(_ block: @escaping (CXCursor) -> T?) -> [T] { var ret = [T]() visit { cursor, _ in if let val = block(cursor) { ret.append(val) } return CXChildVisit_Continue } return ret } func commentBody() -> String? { let rawComment = clang_Cursor_getRawCommentText(self).str() let replacements = [ "@param ": "- parameter: ", "@return ": "- returns: ", "@warning ": "- warning: ", "@see ": "- see: ", "@note ": "- note: ", "@code": "```", "@endcode": "```" ] var commentBody = rawComment?.commentBody() for (original, replacement) in replacements { commentBody = commentBody?.replacingOccurrences(of: original, with: replacement) } // Replace "@c word" with "`word`" commentBody = commentBody?.replacingOccurrences(of: "@c\\s+(\\S+)", with: "`$1`", options: .regularExpression) return commentBody } func swiftDeclarationAndName(compilerArguments: [String]) -> (swiftDeclaration: String?, swiftName: String?) { let file = location().file let swiftUUID: String if let uuid = uuidString(for: file) { swiftUUID = uuid } else { swiftUUID = NSUUID().uuidString setUUIDString(uidString: swiftUUID, for: file) // Generate Swift interface, associating it with the UUID do { _ = try Request.interface(file: file, uuid: swiftUUID, arguments: compilerArguments).send() } catch { return (nil, nil) } } guard let usr = usr(), let findUSR = try? Request.findUSR(file: swiftUUID, usr: usr).send(), let usrOffset = SwiftDocKey.getOffset(findUSR) else { return (nil, nil) } guard let cursorInfo = try? Request.cursorInfo(file: swiftUUID, offset: usrOffset, arguments: compilerArguments).send() else { return (nil, nil) } let swiftDeclaration = (cursorInfo[SwiftDocKey.annotatedDeclaration.rawValue] as? String) .flatMap(XMLHash.parse)?.element?.recursiveText let swiftName = cursorInfo[SwiftDocKey.name.rawValue] as? String return (swiftDeclaration, swiftName) } } extension CXComment { func paramName() -> String? { guard clang_Comment_getKind(self) == CXComment_ParamCommand else { return nil } return clang_ParamCommandComment_getParamName(self).str() } func paragraph() -> CXComment { return clang_BlockCommandComment_getParagraph(self) } func paragraphToString(kindString: String? = nil) -> [Text] { if kind() == CXComment_VerbatimLine { return [.verbatim(clang_VerbatimLineComment_getText(self).str()!)] } else if kind() == CXComment_BlockCommand { return (0..<count()).reduce([]) { returnValue, childIndex in return returnValue + self[childIndex].paragraphToString() } } guard kind() == CXComment_Paragraph else { print("not a paragraph: \(kind())") return [] } let paragraphString = (0..<count()).reduce("") { paragraphString, childIndex in let child = self[childIndex] if let text = clang_TextComment_getText(child).str() { return paragraphString + (paragraphString != "" ? "\n" : "") + text } else if child.kind() == CXComment_InlineCommand { // @autoreleasepool etc. get parsed as commands when not in code blocks let inlineCommand = child.commandName().map { "@" + $0 } return paragraphString + (inlineCommand ?? "") } // Inline child content like `CXComment_HTMLStartTag` can be ignored b/c subsequent children will contain the html. return paragraphString } return [.para(paragraphString.removingCommonLeadingWhitespaceFromLines(), kindString)] } func kind() -> CXCommentKind { return clang_Comment_getKind(self) } func commandName() -> String? { return clang_BlockCommandComment_getCommandName(self).str() ?? clang_InlineCommandComment_getCommandName(self).str() } func count() -> UInt32 { return clang_Comment_getNumChildren(self) } subscript(idx: UInt32) -> CXComment { return clang_Comment_getChild(self, idx) } } #endif
mit
28c7e4a8d2be072a0fb9f0d4eab2673d
34.284746
134
0.583533
4.64895
false
false
false
false
rabotyaga/bars-ios
baranov/MainViewController.swift
1
12403
// // MainViewController.swift // baranov // // Created by Ivan on 06/07/15. // Copyright (c) 2015 Rabotyaga. All rights reserved. // import UIKit class MainViewController: UIViewController, UISearchBarDelegate, ArticleLoaderDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var toolBar: UIToolbar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var progressActivityIndicator: UIActivityIndicatorView! var searchBar: UISearchBar! var navHairline: UIImageView? var segmentedControl: UISegmentedControl! var tableHeaderLabel: UILabel! var toolBarShown: Bool = false var prevOrientation: UIDeviceOrientation = UIDevice.current.orientation var searchAutocomplete = SearchAutocompleteTableViewController() let articleDataSourceDelegate = ArticleDataSourceDelegate() var articleLoader : ArticleLoader! var query: AQuery { get { if (segmentedControl.selectedSegmentIndex == 0) { return AQuery.like(searchBar.text!.format_for_query()) } else { return AQuery.exact(searchBar.text!.format_for_query()) } } } override func viewDidLoad() { super.viewDidLoad() // loader setup articleLoader = ArticleLoader(delegate: self) // search bar setup searchBar = UISearchBar() searchBar.searchBarStyle = .minimal searchBar.placeholder = NSLocalizedString("searchPlaceholder", comment: "") searchBar.delegate = self navigationItem.titleView = searchBar // toolbar setup segmentedControl = UISegmentedControl(items: [NSLocalizedString("searchLike", comment: ""), NSLocalizedString("searchExact", comment: "")]) segmentedControl.setTitle(NSLocalizedString("searchLike", comment: ""), forSegmentAt: 0) segmentedControl.setTitle(NSLocalizedString("searchExact", comment: ""), forSegmentAt: 1) segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(MainViewController.segmentedControlChanged(_:)), for: .valueChanged) let barb = UIBarButtonItem(customView: segmentedControl) let flex = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) toolBar.items = [flex, barb, flex] // hide navigationController's builtin toolbar at start navigationController?.isToolbarHidden = true // special imageView with 0.5px height line at the bottom of navbar // find & store it for later hiding/showing // when showing/hiding toolbar // to make toolbat visually extend navbar navHairline = findNavBarHairline() // main table view setup tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 180 tableView.delegate = self.articleDataSourceDelegate tableView.dataSource = self.articleDataSourceDelegate // results count indicator // as a main table header self.makeTableHeaderView() //?? //definesPresentationContext = true NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.orientationChanged(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) searchAutocomplete.setup(view, searchBarDelegate: self, searchBar: searchBar) prevOrientation = UIDevice.current.orientation if #available(iOS 13.0, *) { overrideUserInterfaceStyle = .light } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // submit new search after search type changed // if there is some text in search bar @objc func segmentedControlChanged(_ sender: AnyObject) { if (!searchBar.text!.isEmpty) { searchBarSearchButtonClicked(searchBar) } } func findNavBarHairline() -> UIImageView? { for a in (navigationController?.navigationBar.subviews)! as [UIView] { for b in a.subviews { if (b.isKind(of: UIImageView.self) && b.bounds.size.width == self.navigationController?.navigationBar.frame.size.width && b.bounds.size.height < 2) { return b as? UIImageView } } } return nil } func makeTableHeaderView() { let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 22)) view.autoresizingMask = UIView.AutoresizingMask.flexibleWidth let label = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 22)) label.autoresizingMask = UIView.AutoresizingMask.flexibleWidth view.addSubview(label) label.textAlignment = .center tableHeaderLabel = label tableView.tableHeaderView = view } func updateResultsIndicator(_ count : Int) { self.tableHeaderLabel.text = String(format: NSLocalizedString("results", comment: ""), arguments: [count]) } // MARK: - Storyboard connected actions @IBAction func menuButtonClicked(_ sender: AnyObject) { if (sideMenuController()?.sideMenu?.isMenuOpen == true) { hideSideMenuView() } else { showSideMenuView() } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { hideSideMenuView() if let detailsViewController = segue.destination as? DetailsViewController { if let cell = sender as? ArticleTableViewCell { if let indexPath = self.tableView.indexPath(for: cell) { let article = self.articleDataSourceDelegate.articleForIndexPath(indexPath) detailsViewController.articleToLoad = article } } } } // MARK: - UISearchBarDelegate func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { hideSideMenuView() searchBar.text = searchBar.text!.format_for_query() if (searchBar.text!.length == 0) { return } searchBar.resignFirstResponder() if (searchBar.text!.count == 1 && segmentedControl.selectedSegmentIndex == 0) { let title = NSLocalizedString("youEnteredOnlyOneCharacter", comment: "") let message = NSLocalizedString("theSearchWillBeMadeInExactMode", comment: "") let cancelButtonTitle = NSLocalizedString("OK", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .cancel) { action in // do nothing } alertController.addAction(cancelAction) segmentedControl.selectedSegmentIndex = 1 present(alertController, animated: true, completion: nil) } if (articleLoader.queryResult?.query != query) { articleLoader.loadArticlesByQuery(query) } } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { hideSideMenuView() showToolBar() searchAutocomplete.textDidChange(searchBar.text!) } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { hideToolBar() searchAutocomplete.hideAutocompleteTable() } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { searchAutocomplete.textDidChange(searchText) } // MARK: - ArtcileLoaderDelegate func loaderWillLoad() { showProgressIndicator() } func loaderDidLoad(_ queryResult: QueryResult) { hideProgressIndicator() articleDataSourceDelegate.articles_count = queryResult.articles.count articleDataSourceDelegate.sections = queryResult.sections tableView.reloadData() updateResultsIndicator(articleDataSourceDelegate.articles_count) tableView.setContentOffset(CGPoint.zero, animated: true) if (queryResult.articles.count == 0) && (segmentedControl.selectedSegmentIndex == 1) && (searchBar.text!.length > 1) { let title = NSLocalizedString("nothingFound", comment: "") let message = NSLocalizedString("youDidSearchUsingExactMode", comment: "") let okButtonTitle = NSLocalizedString("OK", comment: "") let cancelButtonTitle = NSLocalizedString("Cancel", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: okButtonTitle, style: .cancel) { action in // resubmit query in Like mode self.segmentedControl.selectedSegmentIndex = 0 self.searchBarSearchButtonClicked(self.searchBar) } let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .default) { action in // make searchBar active self.searchBar.becomeFirstResponder() } alertController.addAction(okAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } if let firstArticle = queryResult.sections.first?.articles.first { // save search history var detailsString = firstArticle.ar_inf.string.bidiWrapped() + ": " if (firstArticle.translation.string.length > 30) { detailsString += "\((firstArticle.translation.string as NSString).substring(to: 30))...".bidiWrapped(true) } else { detailsString += firstArticle.translation.string.bidiWrapped(true) } let sh = SearchHistory(searchString: getStringFromQuery(queryResult.query), details: detailsString.bidiWrapped(true)) searchAutocomplete.saveSearchHistory(sh) } } // MARK: - UIDeviceOrientationDidChangeNotification @objc func orientationChanged(_ notification: Notification) { if (UIDevice.current.orientation.isValidInterfaceOrientation && UIDevice.current.orientation != prevOrientation) { // orientation change while toolBar is shown // should recalc its frame and redraw it if (toolBarShown) { toolBarShown = false showToolBar() } prevOrientation = UIDevice.current.orientation } } // MARK: - UI Show & Hide func showToolBar() { // slide down top tool bar that extends nav bar if (!toolBarShown) { // slide down top tool bar that extends nav bar UIView.animate(withDuration: 0.3, animations: { self.toolBar.transform = CGAffineTransform(translationX: 0, y: self.toolBar.frame.height) self.navHairline?.alpha = 0.0 self.toolBar.alpha = 1.0 }) toolBarShown = true } } func hideToolBar() { // slide up top tool bar that extends nav bar if (toolBarShown) { UIView.animate(withDuration: 0.3, animations: { self.toolBar.transform = CGAffineTransform(translationX: 0, y: -self.toolBar.frame.height) self.navHairline?.alpha = 1.0 self.toolBar.alpha = 0.0 }) toolBarShown = false } } func showProgressIndicator() { progressActivityIndicator.startAnimating() tableView.isHidden = true } func hideProgressIndicator() { progressActivityIndicator.stopAnimating() tableView.isHidden = false } func selectMenuButton(_ selected: Bool) { if (selected) { searchBar.resignFirstResponder() menuButton.tintColor = UIColor.tintSelected() } else { menuButton.tintColor = self.view.tintColor } } }
isc
4b248c5a20255f60ebb8a15d8f5db4de
38.126183
178
0.629364
5.5569
false
false
false
false
carlh/ExercisesForProgrammers
Swift/Chapter 2/EFP3/EFP3/ViewController.swift
1
1158
// // ViewController.swift // EFP3 // // Created by Carl Hinkle on 7/3/16. // Copyright © 2016 Carl Hinkle. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var authorInput: UITextField! @IBOutlet weak var quoteInput: UITextField! @IBOutlet weak var outputLabel: UILabel! @IBAction func editingChanged(sender: UITextField) { let name: String let quote: String if let authorName = self.authorInput.text where authorName.characters.count > 0 { name = authorName } else { name = "No one" } if let quoteValue = self.quoteInput.text where quoteValue.characters.count > 0 { quote = "\"" + quoteValue + "\"" } else { quote = "nothing" } outputLabel.text = name + " said " + quote } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.outputLabel.text = "Tell us who said something..." } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
df5e4b4c9677152bbb021ff943c02057
22.612245
85
0.659464
4.176895
false
false
false
false
EZ-NET/CodePiece
CodePiece/SNS/PostData+Twitter.swift
1
5115
// // PostDataExtensionForTwitter.swift // CodePiece // // Created by Tomohiro Kumagai on H27/11/24. // Copyright © 平成27年 EasyStyle G.K. All rights reserved. // import ESGists import ESTwitter import CodePieceCore extension PostDataContainer.TwitterState { var isPosted: Bool { return postedStatus != nil } } extension PostDataContainer { var isPostedToTwitter: Bool { return twitterState.isPosted } var appendAppTagToTwitter: Bool { return data.appendAppTagToTwitter } var appendLangTagToTwitter: Bool { return hasCode } var postedTwitterText: String? { return twitterState.postedStatus?.text } func descriptionLengthForTwitter(includesGistsLink: Bool) -> Int { let countsForGistsLink = includesGistsLink ? Twitter.SpecialCounting.media.length + Twitter.SpecialCounting.httpsUrl.length + 2 : 0 return Int(makeDescriptionForTwitter(forCountingLength: true).twitterCharacterView.wordCountForPost + countsForGistsLink) } func makeDescriptionForTwitter(forCountingLength: Bool = false) -> String { func internalErrorUnexpectedRange<R>(_ range: NSRange, for text: String, note: String?, result: @autoclosure () -> R) -> R { let message = "Unexpected range '\(range)' for \(text) \(note != nil ? "(\(note!))" : "")" #if DEBUG fatalError(message) #else NSLog("INTERNAL ERROR: %@", message) return result() #endif } func replacingDescriptionWithPercentEscapingUrl(_ text: String) -> String { var result = text let urlPattern = try! NSRegularExpression(pattern: #"(?:^|\s)((http(?:s|)):\/\/([^\/\s]+?)/([^\?\s]*?)(?:|\?([^\s]*?)))(?:\s|$)"# , options: []) for match in urlPattern.matches(in: result, options: [], range: NSRange(location: 0, length: text.count)).reversed() { guard let targetRange = Range(match.range(at: 1), for: result) else { return internalErrorUnexpectedRange(match.range(at: 1), for: text, note: #function, result: text) } guard let schemeRange = Range(match.range(at: 2), for: result) else { return internalErrorUnexpectedRange(match.range(at: 2), for: text, note: #function, result: text) } guard let hostRange = Range(match.range(at: 3), for: result) else { return internalErrorUnexpectedRange(match.range(at: 3), for: text, note: #function, result: text) } let scheme = String(result[schemeRange]) let host = String(result[hostRange]) var uri = Range(match.range(at: 4), for: result).map { String(result[$0]) } ?? "" var query = Range(match.range(at: 5), for: result).map { String(result[$0]) } ?? "" let uriPattern = try! NSRegularExpression(pattern: #"[^\/\.]+"#) let queryPattern = try! NSRegularExpression(pattern: #"[^=&]+"#) /// When non-escaped character is found in text, consider '%' is not escaped. func needsToEscape(_ text: String) -> Bool { var text = text let escapedPattern = try! NSRegularExpression(pattern: #"%\d\d"#) let allowedWordPattern = try! NSRegularExpression(pattern: #"[A-Za-z0-9-_\.\?:#/@%!\$&'\(\)\*\+,;=~]"#) escapedPattern.replaceAllMatches(onto: &text, with: "") allowedWordPattern.replaceAllMatches(onto: &text, with: "") print(text, text.isEmpty) return !text.isEmpty } uriPattern.replaceAllMatches(onto: &uri) { guard needsToEscape($0) else { return $0 } return $0.addingPercentEncoding(withAllowedCharacters: .alphanumerics)! } queryPattern.replaceAllMatches(onto: &query) { guard needsToEscape($0) else { return $0 } return $0.addingPercentEncoding(withAllowedCharacters: .alphanumerics)! } // FIXME: ここのパッと見て複雑な印象を解消した。 result = result.replacingCharacters(in: targetRange, with: "\(scheme)://\(host)/\(uri)\(query.isEmpty ? "" : "?")\(query)") } return result } func replacingDescriptionWithUrlToDummyText(_ text: String) -> String { var result = text let urlWord = #"A-Za-z0-9-_\.\?:#/@%!\$&'\(\)\*\+,;=~"# let urlPattern = try! NSRegularExpression(pattern: #"(^|\s)(http(s|):\/\/[\#(urlWord)]+)(\s|$)"# , options: []) urlPattern.replaceAllMatches(onto: &result) { item, range, match in guard let newRange = Range(match.range(at: 2), for: text) else { return internalErrorUnexpectedRange(match.range(at: 2), for: text, note: #function, result: item) } range = newRange return "xxxxxxxxxxxxxxxxxxxxxxx" } return result } let description = makeDescriptionWithEffectiveHashtags(hashtags: effectiveHashtagsForTwitter, appendString: gistPageUrl) let escapedDescription = replacingDescriptionWithPercentEscapingUrl(description) switch forCountingLength { case true: return replacingDescriptionWithUrlToDummyText(escapedDescription) case false: return escapedDescription } } var effectiveHashtagsForTwitter: [Hashtag] { return effectiveHashtags(withAppTag: appendAppTagToTwitter, withLangTag: appendLangTagToTwitter) } }
gpl-3.0
6272df90497bf23721067d03af792e64
27.324022
133
0.663314
3.603412
false
false
false
false
bangslosan/Easy-Game-Center-Swift
Easy-Game-Center-Swift/MainViewController.swift
1
6271
// // ViewController.swift // Easy-Game-Center-Swift // // Created by DaRk-_-D0G on 19/03/2558 E.B.. // Copyright (c) 2558 ère b. DaRk-_-D0G. All rights reserved. // import UIKit /*####################################################################################################*/ /* Add >>> EasyGameCenterDelegate <<< for delegate */ /*####################################################################################################*/ class MainViewController: UIViewController,EasyGameCenterDelegate { @IBOutlet weak var Name: UILabel! @IBOutlet weak var PlayerID: UILabel! @IBOutlet weak var PlayerAuthentified: UILabel! @IBOutlet weak var PlayerProfil: UIImageView! /*####################################################################################################*/ /* in ViewDidLoad, Set Delegate UIViewController */ /*####################################################################################################*/ override func viewDidLoad() { super.viewDidLoad() /* Set Delegate UIViewController */ EasyGameCenter.sharedInstance(self) /** If you want not message just delete this ligne **/ EasyGameCenter.debugMode = true self.navigationItem.title = "Easy Game Center" /** Hidden automatique page for login to Game Center if player not login */ //EasyGameCenter.showLoginPage = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /*####################################################################################################*/ /* Set New view controller delegate, is when you change you change UIViewControlle */ /*####################################################################################################*/ override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) /** Set New view controller delegate, when you change UIViewController */ EasyGameCenter.delegate = self /* Recall if you change page and activate network for refresh text*/ if EasyGameCenter.isPlayerIdentifiedToGameCenter() { easyGameCenterAuthentified() } } /*####################################################################################################*/ /* Delegate Func Easy Game Center */ /*####################################################################################################*/ /** Player conected to Game Center, Delegate Func of Easy Game Center */ func easyGameCenterAuthentified() { println("\n[MainViewController] Player Authentified\n") EasyGameCenter.getlocalPlayerInformation { (playerInformationTuple) -> () in //playerInformationTuple:(playerID:String,alias:String,profilPhoto:UIImage?) if let typleInformationPlayer = playerInformationTuple { self.PlayerID.text = "Player ID : \(typleInformationPlayer.playerID)" self.Name.text = "Name : \(typleInformationPlayer.alias)" self.PlayerAuthentified.text = "Player Authentified : True" if let haveProfilPhoto = typleInformationPlayer.profilPhoto { self.PlayerProfil.image = haveProfilPhoto } } } } /** Player not connected to Game Center, Delegate Func of Easy Game Center */ func easyGameCenterNotAuthentified() { println("\n[MainViewController] Player not authentified\n") self.PlayerAuthentified.text = "Player Authentified : False" } /** When GkAchievement & GKAchievementDescription in cache, Delegate Func of Easy Game Center */ func easyGameCenterInCache() { println("\n[MainViewController] GkAchievement & GKAchievementDescription in cache\n") } /*####################################################################################################*/ /* Button */ /*####################################################################################################*/ @IBAction func ShowGameCenterAchievements(sender: AnyObject) { EasyGameCenter.showGameCenterAchievements { (isShow) -> Void in if isShow { println("\n[MainViewController] Game Center Achievements Is show\n") } } } @IBAction func ShowGameCenterLeaderboards(sender: AnyObject) { EasyGameCenter.showGameCenterLeaderboard(leaderboardIdentifier: "International_Classement") { (isShow) -> Void in println("\n[MainViewController] Game Center Leaderboards Is show\n") } } @IBAction func ShowGameCenterChallenges(sender: AnyObject) { EasyGameCenter.showGameCenterChallenges { (result) -> Void in if result { println("\n[MainViewController] Game Center Challenges Is show\n") } } } @IBAction func ShowCustomBanner(sender: AnyObject) { EasyGameCenter.showCustomBanner(title: "Title", description: "My Description...") { () -> Void in println("\n[MainViewController] Custom Banner is finish to Show\n") } } @IBAction func ActionOpenDialog(sender: AnyObject) { EasyGameCenter.openDialogGameCenterAuthentication(title: "Open Game Center", message: "Open Game Center authentification ?", buttonOK: "No", buttonOpenGameCenterLogin: "Yes") { (openGameCenterAuthentification) -> Void in if openGameCenterAuthentification { println("\n[MainViewController] Open Game Center Authentification\n") } else { println("\n[MainViewController] Not open Game Center Authentification\n") } } } }
mit
8ca5e0cf7478d88ed1e5cc584600c5cb
43.785714
184
0.492026
5.892857
false
false
false
false
narner/AudioKit
AudioKit/Common/MIDI/AKMIDI+ReceivingMIDI.swift
1
7340
// // AKMIDI+ReceivingMIDI.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // internal struct MIDISources: Collection { typealias Index = Int typealias Element = MIDIEndpointRef init() { } var endIndex: Index { return MIDIGetNumberOfSources() } subscript (index: Index) -> Element { return MIDIGetSource(index) } } internal func GetMIDIObjectStringProperty(ref: MIDIObjectRef, property: CFString) -> String { var string: Unmanaged<CFString>? MIDIObjectGetStringProperty(ref, property, &string) if let returnString = string?.takeRetainedValue() { return returnString as String } else { return "" } } extension AKMIDI { /// Array of input names public var inputNames: [String] { return MIDISources().names } /// Add a listener to the listeners public func addListener(_ listener: AKMIDIListener) { listeners.append(listener) } /// Remove all listeners public func clearListeners() { listeners.removeAll() } /// Add a transformer to the transformers list public func addTransformer(_ transformer: AKMIDITransformer) { transformers.append(transformer) } /// Remove all transformers public func clearTransformers() { transformers.removeAll() } /// Open a MIDI Input port /// /// - parameter namedInput: String containing the name of the MIDI Input /// public func openInput(_ namedInput: String = "") { for (name, src) in zip(inputNames, MIDISources()) { if namedInput.isEmpty || namedInput == name { inputPorts[namedInput] = MIDIPortRef() var port = inputPorts[namedInput]! let result = MIDIInputPortCreateWithBlock(client, inputPortName, &port) { packetList, _ in for packet in packetList.pointee { // a CoreMIDI packet may contain multiple MIDI events - // treat it like an array of events that can be transformed let transformedMIDIEventList = self.transformMIDIEventList([AKMIDIEvent](packet)) for transformedEvent in transformedMIDIEventList { self.handleMIDIMessage(transformedEvent) } } } inputPorts[namedInput] = port if result != noErr { AKLog("Error creating MIDI Input Port : \(result)") } MIDIPortConnectSource(port, src, nil) endpoints[namedInput] = src } } } /// Close a MIDI Input port /// /// - parameter namedInput: String containing the name of the MIDI Input /// public func closeInput(_ namedInput: String = "") { var result = noErr for key in inputPorts.keys { if namedInput.isEmpty || key == namedInput { if let port = inputPorts[key], let endpoint = endpoints[key] { result = MIDIPortDisconnectSource(port, endpoint) if result == noErr { endpoints.removeValue(forKey: namedInput) inputPorts.removeValue(forKey: namedInput) } else { AKLog("Error closing midiInPort : \(result)") } } } } // The below code is not working properly - error closing MIDI port // for (key, endpoint) in inputPorts { // if namedInput.isEmpty || key == namedInput { // if let port = inputPorts[key] { // // the next line is returning error -50, either port or endpoint is not right // let result = MIDIPortDisconnectSource(port, endpoint) // if result == noErr { // endpoints.removeValue(forKey: namedInput) // inputPorts.removeValue(forKey: namedInput) // } else { // AKLog("Error closing midiInPort : \(result)") // } // } // } // } } /// Close all MIDI Input ports public func closeAllInputs() { closeInput() } internal func handleMIDIMessage(_ event: AKMIDIEvent) { for listener in listeners { guard let eventChannel = event.channel else { AKLog("No channel detected in handleMIDIMessage") return } guard let type = event.status else { AKLog("No status detected in handleMIDIMessage") return } switch type { case .controllerChange: listener.receivedMIDIController(event.internalData[1], value: event.internalData[2], channel: MIDIChannel(eventChannel)) case .channelAftertouch: listener.receivedMIDIAfterTouch(event.internalData[1], channel: MIDIChannel(eventChannel)) case .noteOn: listener.receivedMIDINoteOn(noteNumber: MIDINoteNumber(event.internalData[1]), velocity: MIDIVelocity(event.internalData[2]), channel: MIDIChannel(eventChannel)) case .noteOff: listener.receivedMIDINoteOff(noteNumber: MIDINoteNumber(event.internalData[1]), velocity: MIDIVelocity(event.internalData[2]), channel: MIDIChannel(eventChannel)) case .pitchWheel: listener.receivedMIDIPitchWheel(MIDIWord(Int(event.wordData)), channel: MIDIChannel(eventChannel)) case .polyphonicAftertouch: listener.receivedMIDIAftertouch(noteNumber: MIDINoteNumber(event.internalData[1]), pressure: event.internalData[2], channel: MIDIChannel(eventChannel)) case .programChange: listener.receivedMIDIProgramChange(event.internalData[1], channel: MIDIChannel(eventChannel)) case .systemCommand: listener.receivedMIDISystemCommand(event.internalData) default: break } } } internal func transformMIDIEventList(_ eventList: [AKMIDIEvent]) -> [AKMIDIEvent] { var eventsToProcess = eventList var processedEvents = eventList for transformer in transformers { processedEvents = transformer.transform(eventList: eventsToProcess) // prepare for next transformer eventsToProcess = processedEvents } return processedEvents } }
mit
e399f479fc6293e7c6b33bc9384bb7aa
37.424084
107
0.533179
5.654083
false
false
false
false
whiteshadow-gr/HatForIOS
Pods/SwiftyRSA/Source/SwiftyRSA+ObjC.swift
1
8908
// // SwiftyRSA+ObjC.swift // SwiftyRSA // // Created by Lois Di Qual on 3/6/17. // Copyright © 2017 Scoop. All rights reserved. // import Foundation /// This files allows the ObjC runtime to access SwiftyRSA classes while keeping the swift code Swiftyish. /// Things like protocol extensions or throwing and returning booleans are not well supported by ObjC, so instead /// of giving access to the Swift classes directly, we're wrapping then their `_objc_*` counterpart. /// They are exposed under the same name to the ObjC runtime, and all methods are present – they're just delegated /// to the wrapped swift value. private protocol ObjcBridgeable { associatedtype SwiftType var swiftValue: SwiftType { get } init(swiftValue: SwiftType) } // MARK: - PublicKey @objc(PublicKey) public class _objc_PublicKey: NSObject, Key, ObjcBridgeable { // swiftlint:disable:this type_name fileprivate let swiftValue: PublicKey @objc public var reference: SecKey { return swiftValue.reference } @objc public var originalData: Data? { return swiftValue.originalData } @objc public func pemString() throws -> String { return try swiftValue.pemString() } @objc public func data() throws -> Data { return try swiftValue.data() } @objc public func base64String() throws -> String { return try swiftValue.base64String() } required public init(swiftValue: PublicKey) { self.swiftValue = swiftValue } @objc required public init(data: Data) throws { self.swiftValue = try PublicKey(data: data) } @objc public required init(reference: SecKey) throws { self.swiftValue = try PublicKey(reference: reference) } @objc public required init(base64Encoded base64String: String) throws { self.swiftValue = try PublicKey(base64Encoded: base64String) } @objc public required init(pemEncoded pemString: String) throws { self.swiftValue = try PublicKey(pemEncoded: pemString) } @objc public required init(pemNamed pemName: String, in bundle: Bundle) throws { self.swiftValue = try PublicKey(pemNamed: pemName, in: bundle) } @objc public required init(derNamed derName: String, in bundle: Bundle) throws { self.swiftValue = try PublicKey(derNamed: derName, in: bundle) } @objc public static func publicKeys(pemEncoded pemString: String) -> [_objc_PublicKey] { return PublicKey.publicKeys(pemEncoded: pemString).map { _objc_PublicKey(swiftValue: $0) } } } // MARK: - PrivateKey @objc(PrivateKey) public class _objc_PrivateKey: NSObject, Key, ObjcBridgeable { // swiftlint:disable:this type_name fileprivate let swiftValue: PrivateKey @objc public var reference: SecKey { return swiftValue.reference } @objc public var originalData: Data? { return swiftValue.originalData } @objc public func pemString() throws -> String { return try swiftValue.pemString() } @objc public func data() throws -> Data { return try swiftValue.data() } @objc public func base64String() throws -> String { return try swiftValue.base64String() } public required init(swiftValue: PrivateKey) { self.swiftValue = swiftValue } @objc public required init(data: Data) throws { self.swiftValue = try PrivateKey(data: data) } @objc public required init(reference: SecKey) throws { self.swiftValue = try PrivateKey(reference: reference) } @objc public required init(base64Encoded base64String: String) throws { self.swiftValue = try PrivateKey(base64Encoded: base64String) } @objc public required init(pemEncoded pemString: String) throws { self.swiftValue = try PrivateKey(pemEncoded: pemString) } @objc public required init(pemNamed pemName: String, in bundle: Bundle) throws { self.swiftValue = try PrivateKey(pemNamed: pemName, in: bundle) } @objc public required init(derNamed derName: String, in bundle: Bundle) throws { self.swiftValue = try PrivateKey(derNamed: derName, in: bundle) } } // MARK: - VerificationResult @objc(VerificationResult) public class _objc_VerificationResult: NSObject { // swiftlint:disable:this type_name @objc public let isSuccessful: Bool init(isSuccessful: Bool) { self.isSuccessful = isSuccessful } } // MARK: - ClearMessage @objc(ClearMessage) public class _objc_ClearMessage: NSObject, Message, ObjcBridgeable { // swiftlint:disable:this type_name fileprivate let swiftValue: ClearMessage @objc public var base64String: String { return swiftValue.base64String } @objc public var data: Data { return swiftValue.data } public required init(swiftValue: ClearMessage) { self.swiftValue = swiftValue } @objc public required init(data: Data) { self.swiftValue = ClearMessage(data: data) } @objc public required init(string: String, using rawEncoding: UInt) throws { let encoding = String.Encoding(rawValue: rawEncoding) self.swiftValue = try ClearMessage(string: string, using: encoding) } @objc public required init(base64Encoded base64String: String) throws { self.swiftValue = try ClearMessage(base64Encoded: base64String) } @objc public func string(encoding rawEncoding: UInt) throws -> String { let encoding = String.Encoding(rawValue: rawEncoding) return try swiftValue.string(encoding: encoding) } @objc public func encrypted(with key: _objc_PublicKey, padding: Padding) throws -> _objc_EncryptedMessage { let encryptedMessage = try swiftValue.encrypted(with: key.swiftValue, padding: padding) return _objc_EncryptedMessage(swiftValue: encryptedMessage) } @objc public func signed(with key: _objc_PrivateKey, digestType: _objc_Signature.DigestType) throws -> _objc_Signature { let signature = try swiftValue.signed(with: key.swiftValue, digestType: digestType.swiftValue) return _objc_Signature(swiftValue: signature) } @objc public func verify(with key: _objc_PublicKey, signature: _objc_Signature, digestType: _objc_Signature.DigestType) throws -> _objc_VerificationResult { let isSuccessful = try swiftValue.verify(with: key.swiftValue, signature: signature.swiftValue, digestType: digestType.swiftValue) return _objc_VerificationResult(isSuccessful: isSuccessful) } } // MARK: - EncryptedMessage @objc(EncryptedMessage) public class _objc_EncryptedMessage: NSObject, Message, ObjcBridgeable { // swiftlint:disable:this type_name fileprivate let swiftValue: EncryptedMessage @objc public var base64String: String { return swiftValue.base64String } @objc public var data: Data { return swiftValue.data } public required init(swiftValue: EncryptedMessage) { self.swiftValue = swiftValue } @objc public required init(data: Data) { self.swiftValue = EncryptedMessage(data: data) } @objc public required init(base64Encoded base64String: String) throws { self.swiftValue = try EncryptedMessage(base64Encoded: base64String) } @objc public func decrypted(with key: _objc_PrivateKey, padding: Padding) throws -> _objc_ClearMessage { let clearMessage = try swiftValue.decrypted(with: key.swiftValue, padding: padding) return _objc_ClearMessage(swiftValue: clearMessage) } } // MARK: - Signature @objc(Signature) public class _objc_Signature: NSObject, ObjcBridgeable { // swiftlint:disable:this type_name @objc public enum DigestType: Int { case sha1 case sha224 case sha256 case sha384 case sha512 fileprivate var swiftValue: Signature.DigestType { switch self { case .sha1: return .sha1 case .sha224: return .sha224 case .sha256: return .sha256 case .sha384: return .sha384 case .sha512: return .sha512 } } } fileprivate let swiftValue: Signature @objc public var base64String: String { return swiftValue.base64String } @objc public var data: Data { return swiftValue.data } public required init(swiftValue: Signature) { self.swiftValue = swiftValue } @objc public init(data: Data) { self.swiftValue = Signature(data: data) } @objc public required init(base64Encoded base64String: String) throws { self.swiftValue = try Signature(base64Encoded: base64String) } }
mpl-2.0
10842cd70f94be3796b5057bd67425e9
30.803571
160
0.669175
4.499747
false
false
false
false
petester42/PMCoreDataStack
Pod/CoreDataStorage.swift
1
8851
import CoreData import LlamaKit public enum StoreType { case Sqlite case Binary case Memory func toString() -> NSString { switch self { case .Sqlite: return NSSQLiteStoreType case .Binary: return NSBinaryStoreType case .Memory: return NSInMemoryStoreType } } } public class CoreDataStorage: NSObject { private let modelName: String private let storeType: StoreType private let storeOptions: [NSObject : AnyObject]? let managedObjectModel: NSManagedObjectModel = NSManagedObjectModel() let persistentStoreCoordinator: NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: NSManagedObjectModel()) let managedObjectContext: NSManagedObjectContext = NSManagedObjectContext() public init(modelName name: String, storeType type: StoreType, storeOptions options: [NSObject : AnyObject]?) { modelName = name storeType = type super.init() if type == StoreType.Memory { storeOptions = nil } else { if let _storeOptions = options { storeOptions = _storeOptions } else { storeOptions = defaultStoreOptions(storeType) } } managedObjectModel = managedObjectModel(managedObjectModelPath(modelName)) persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let persistancePath = storePathForFilename(persistentFilePath(persistentStoreDirectory(directoryPath()), fileName: sqliteFileName(modelName))) addPersistanceStoreWithPath(persistentStoreCoordinator, storePath: persistancePath, options: storeOptions) managedObjectContext = managedObjectContext(persistentStoreCoordinator) NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext) NSNotificationCenter.defaultCenter().addObserver(self, selector: "managedObjectContextDidSave:", name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: managedObjectContext) } private func sqliteFileName(filePath: String) -> String { if filePath.pathExtension == "sqlite" { return filePath } if let path = filePath.stringByDeletingPathExtension.stringByAppendingPathExtension("sqlite") { return path } return filePath } private func defaultStoreOptions(storeType: StoreType) -> [NSObject : AnyObject]? { if (storeType != StoreType.Memory) { return [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] } return nil } private func directoryPath() -> String { if let displayName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as String? { return displayName } return "CoreDataStorage" } private func persistentStoreDirectory(directoryPath: String) -> String { let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.ApplicationSupportDirectory, NSSearchPathDomainMask.UserDomainMask, true) let basePath = (paths.count > 0) ? paths[0] as String : NSTemporaryDirectory() let fullPath = basePath.stringByAppendingPathComponent(directoryPath) let fileManager = NSFileManager.defaultManager() if !fileManager.fileExistsAtPath(fullPath) { fileManager.createDirectoryAtPath(fullPath, withIntermediateDirectories: true, attributes: nil, error: nil) } return fullPath } private func persistentFilePath(directory: String, fileName: String) -> String { return directory.stringByAppendingPathComponent(fileName) } private func addPersistanceStoreWithPath(persistentStoreCoordinator: NSPersistentStoreCoordinator, storePath: NSURL?, options: [NSObject : AnyObject]?) -> NSPersistentStore? { if let aStorePath = storePath { return persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: aStorePath, options: options, error: nil); } else { return persistentStoreCoordinator.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: nil) } } private func managedObjectModelPath(name: String) -> String? { if let path = NSBundle.mainBundle().pathForResource(name, ofType: "mom") { return path } if let path = NSBundle.mainBundle().pathForResource(name, ofType: "momd") { return path } return nil } private func managedObjectModel(path: String?) -> NSManagedObjectModel { if let momPath = path { if let momURL = NSURL(fileURLWithPath: momPath) { if let managedObject = NSManagedObjectModel(contentsOfURL: momURL) { return managedObject } } } return NSManagedObjectModel() } private func storePathForFilename(filePath: String?) -> NSURL? { if let _filePath = filePath { if let storePath = NSURL(fileURLWithPath: _filePath) { return storePath } } return nil } private func managedObjectContext(persistentStoreCoordinator: NSPersistentStoreCoordinator) -> NSManagedObjectContext { //TODO: check for queue let managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator; managedObjectContext.undoManager = nil; return managedObjectContext } private func managedObjectContextDidSave(notification: NSNotification) { //TODO: check for queue let sender = notification.object as NSManagedObjectContext; if sender != managedObjectContext && sender.persistentStoreCoordinator == managedObjectContext.persistentStoreCoordinator { if let dictionary = notification.userInfo as [NSObject : AnyObject]? { if let array = dictionary[NSUpdatedObjectsKey] as [NSManagedObject]? { for object:NSManagedObject in array { managedObjectContext.objectWithID(object.objectID) } } } managedObjectContext.mergeChangesFromContextDidSaveNotification(notification) } } } extension NSManagedObject { convenience public init(name: String, context: NSManagedObjectContext) { let entity = NSEntityDescription.entityForName(name, inManagedObjectContext: context) self.init(entity: entity!, insertIntoManagedObjectContext: context) } } extension NSManagedObjectContext { public func save() -> Result<Void> { if persistentStoreCoordinator?.persistentStores.count <= 0 { return failure(CoreDataStorage.noPersistentStoresError()) } var error: NSError? save(&error) if let _error = error { return failure(_error) } else { return success() } } } extension NSFetchedResultsController { public func performFetch() -> Result<Void> { var error: NSError? performFetch(&error) if let _error = error { return failure(_error) } else { return success() } } } extension CoreDataStorage { public class func noPersistentStoresError() -> NSError { return NSError(domain: "CoreDataStorage", code: 1, userInfo: [NSLocalizedDescriptionKey: "This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation."]) } }
mit
0ed2aaf44df3752ea18e0ee8bd9861bf
31.424908
196
0.619817
6.914844
false
false
false
false