repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
711k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
crossroadlabs/Markdown
|
refs/heads/master
|
Tests/MarkdownTests/MarkdownTests.swift
|
gpl-3.0
|
1
|
//===--- MarkdownTests.swift ----------------------------------------------------===//
//
//Copyright (c) 2015-2016 Daniel Leping (dileping)
//
//This file is part of Markdown.
//
//Swift Express 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 3 of the License, or
//(at your option) any later version.
//
//Swift Express 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.
//
//You should have received a copy of the GNU Lesser General Public License
//along with Swift Express. If not, see <http://www.gnu.org/licenses/>.
//
//===----------------------------------------------------------------------===//
import XCTest
import Foundation
@testable import Markdown
#if !os(Linux) || dispatch
import Dispatch
#endif
class MarkdownTests: XCTestCase {
func testHeader() {
do {
let md = try Markdown(string:"% test\n% daniel\n% 02.03.2016\n")
let title = md.title
XCTAssertNotNil(title)
XCTAssertEqual(title!, "test")
let author = md.author
XCTAssertNotNil(author)
XCTAssertEqual(author!, "daniel")
let date = md.date
XCTAssertNotNil(date)
XCTAssertEqual(date!, "02.03.2016")
} catch {
XCTFail("Exception caught")
}
}
func testBody() {
do {
let md = try Markdown(string:"# test header")
let document = try md.document()
XCTAssertEqual(document, "<h1>test header</h1>")
} catch {
XCTFail("Exception caught")
}
}
func testTableOfContents() {
do {
let md = try Markdown(string:"# test header", options: .TableOfContents)
let document = try md.document()
XCTAssertEqual(document, "<a name=\"test.header\"></a>\n<h1>test header</h1>")
let toc = try md.tableOfContents()
XCTAssertEqual(toc, "<ul>\n <li><a href=\"#test.header\">test header</a></li>\n</ul>\n")
} catch {
XCTFail("Exception caught")
}
}
func testStyle() {
do {
let md = try Markdown(string:"<style>background-color: yellow;</style>\n# test header")
let document = try md.document()
XCTAssertEqual(document, "\n\n<h1>test header</h1>")
let css = try md.css()
XCTAssertEqual(css, "<style>background-color: yellow;</style>\n")
} catch {
XCTFail("Exception caught")
}
}
#if !os(Linux) || dispatch
// no dispatch
func testStress() {
let id = UUID().uuidString
let queue = DispatchQueue(label: id, attributes: .concurrent)
for i in 0...10000 {
let expectation = self.expectation(description: "OK " + String(i))
queue.async {
do {
let markdown = try Markdown(string: "# test line " + String(i), options: .None)
let html = try markdown.document()
XCTAssertEqual(html, "<h1>test line " + String(i) + "</h1>")
expectation.fulfill()
} catch {
XCTFail("Exception caught")
}
}
}
self.waitForExpectations(timeout: 60, handler: nil)
}
#endif
}
#if os(Linux)
extension MarkdownTests {
static var allTests : [(String, (MarkdownTests) -> () throws -> Void)] {
var tests:[(String, (MarkdownTests) -> () throws -> Void)] = [
("testHeader", testHeader),
("testBody", testBody),
("testTableOfContents", testTableOfContents),
("testStyle", testStyle),
]
#if dispatch
tests.append(("testStress", testStress))
#endif
return tests
}
}
#endif
|
93bfe23ec9674e1779ed624c34e1b5d9
| 30.666667 | 100 | 0.538756 | false | true | false | false |
SirapatBoonyasiwapong/grader
|
refs/heads/master
|
Sources/App/Database/Seeders/SeedDatabase.swift
|
mit
|
1
|
import Vapor
import Console
final class SeedCommand: Command {
public let id = "seed"
public let help = ["Seed the database."]
public let console: ConsoleProtocol
public init(console: ConsoleProtocol) {
self.console = console
}
public func run(arguments: [String]) throws {
try deleteAll()
try insertUsers()
try insertProblems()
try insertEvents()
}
private func deleteAll() throws {
try ResultCase.all().forEach { try $0.delete() }
try Submission.all().forEach { try $0.delete() }
try EventProblem.all().forEach { try $0.delete() }
try Event.all().forEach { try $0.delete() }
try ProblemCase.all().forEach { try $0.delete() }
try Problem.all().forEach { try $0.delete() }
try User.all().forEach { try $0.delete() }
}
private func insertProblems() throws {
let problem1 = Problem(name: "Hello", description: "Print \"Hello Mor Nor\" (without quotes).")
try problem1.save()
try ProblemCase(input: "", output: "Hello Mor Nor", visible: true, problemID: problem1.id).save()
let problem2 = Problem(name: "Fibonacci", description: "Print the Fibonacci sequence. The number of items to print is determined by an integer read in on the input. If the input is 0 then print nothing.")
try problem2.save()
try ProblemCase(input: "3", output: "1 1 2", visible: true, problemID: problem2.id).save()
try ProblemCase(input: "8", output: "1 1 2 3 5 8 13 21", problemID: problem2.id).save()
try ProblemCase(input: "1", output: "1", problemID: problem2.id).save()
try ProblemCase(input: "0", output: "", problemID: problem2.id).save()
let problem3 = Problem(name: "FizzBuzz 4.0", description: "Print FizzBuzz from 1 to 20. Read the Fizz value and the Buzz value from the input.")
try problem3.save()
try ProblemCase(input: "3\n5", output: "1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n16\n17\nFizz\n19\nBuzz", visible: true, problemID: problem3.id).save()
try ProblemCase(input: "6\n8", output: "1\n2\n3\n4\n5\nFizz\n7\nBuzz\n9\n10\n11\nFizz\n13\n14\n15\nBuzz\n17\nFizz\n19\n20", problemID: problem3.id).save()
try ProblemCase(input: "10\n20", output: "1\n2\n3\n4\n5\n6\n7\n8\n9\nFizz\n11\n12\n13\n14\n15\n16\n17\n18\n19\nFizzBuzz", problemID: problem3.id).save()
try ProblemCase(input: "10\n5", output: "1\n2\n3\n4\nBuzz\n6\n7\n8\n9\nFizzBuzz\n11\n12\n13\n14\nBuzz\n16\n17\n18\n19\nFizzBuzz", visible: true, problemID: problem3.id).save()
let problem4 = Problem(name: "Plus Seven", description: "Read in a number, add 7, and print it out.")
try problem4.save()
try ProblemCase(input: "1", output: "8", visible: true, problemID: problem4.id).save()
try ProblemCase(input: "9", output: "16", visible: true, problemID: problem4.id).save()
try ProblemCase(input: "100", output: "107", problemID: problem4.id).save()
try ProblemCase(input: "0", output: "7", problemID: problem4.id).save()
let problem5 = Problem(name: "Semi-Diagonal Alphabet", description: "First, you take the position of the letter in the alphabet, P (P is 1-indexed here). Then, you print each letter until the input (inclusive) on a line, preceded by P-1 and repeat that letter P times, interleaving with spaces.")
try problem5.save()
try ProblemCase(input: "A", output: "A", problemID: problem5.id).save()
try ProblemCase(input: "B", output: "A\n B B", visible: true, problemID: problem5.id).save()
try ProblemCase(input: "F", output: "A\n B B\n C C C\n D D D D\n E E E E E\n F F F F F F", visible: true, problemID: problem5.id).save()
try ProblemCase(input: "K", output: "A\n B B\n C C C\n D D D D\n E E E E E\n F F F F F F\n G G G G G G G\n H H H H H H H H\n I I I I I I I I I\n J J J J J J J J J J\n K K K K K K K K K K K", problemID: problem5.id).save()
let problem6 = Problem(name: "Palindrome Numbers", description: "Read in a number and check if it is a palindrome or not.")
try problem6.save()
try ProblemCase(input: "1221", output: "true", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "3345433", output: "true", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "1212", output: "false", visible: true, problemID: problem6.id).save()
try ProblemCase(input: "98712421789", output: "true", problemID: problem6.id).save()
}
private func insertUsers() throws {
let admin = User(name: "Administrator", username: "admin", password: "1234", role: .admin)
try admin.save()
let teacher = User(name: "Antony Harfield", username: "ant", password: "1234", role: .teacher)
try teacher.save()
let student1 = User(name: "Arya Stark", username: "student1", password: "1234", role: .student)
try student1.save()
let student2 = User(name: "Jon Snow", username: "student2", password: "1234", role: .student)
try student2.save()
let myClass: [(String, String)] = [("58312020", "Pimonrat Mayoo"),
("58313942", "Kamolporn Khankhai"),
("58313959", "Kamonphon Chaihan"),
("58313973", "Kettanok Yodsunthon"),
("58314024", "Julalak Phumket"),
("58314048", "Chanisara Uttamawetin"),
("58314062", "Titawan Laksukthom"),
("58314079", "Natdanai Phoopheeyo"),
("58314086", "Nattapon Phothima"),
("58314093", "Nattaphon Yooson"),
("58314109", "Nattawan Chomchuen"),
("58314116", "Nattawat Ruamsuk"),
("58314123", "Tuangporn Kaewchue"),
("58314130", "Tawanrung Keawjeang"),
("58314154", "Thodsaphon Phimket"),
("58314178", "Thanaphong Rittem"),
("58314185", "Thanaphon Wetchaphon"),
("58314192", "Thanawat Makenin"),
("58314222", "Tansiri Saetung"),
("58314246", "Thirakan Jeenduang"),
("58314277", "Nadia Nusak"),
("58314284", "Nitiyaporn Pormin"),
("58314321", "Bunlung Korkeattomrong"),
("58314338", "Patiphan Bunaum"),
("58314345", "Pathompong Jankom"),
("58314352", "Piyapong Ruengsiri"),
("58314369", "Pongchakorn Kanthong"),
("58314376", "Phongsiri Mahingsa"),
("58314406", "Phatcharaphon Naun-Ngam"),
("58314420", "Pittaya Boonyam"),
("58314444", "Peeraphon Khoeitui"),
("58314475", "Pakaporn Kiewpuampuang"),
("58314499", "Panusorn Banlue"),
("58314550", "Ronnachai Kammeesawang"),
("58314574", "Ratree Onchana"),
("58314581", "Lisachol Srichomchun"),
("58314628", "Vintaya Prasertsit"),
("58314642", "Witthaya Ngamprong"),
("58314659", "Winai Kengthunyakarn"),
("58314666", "Wisit Soontron"),
("58314697", "Sakchai Yotthuean"),
("58314703", "Sansanee Yimyoo"),
("58314710", "Siripaporn Kannga"),
("58314734", "Supawit Kiewbanyang"),
("58314741", "Supisara Wongkhamma"),
("58314789", "Suchada Buathong"),
("58314802", "Supicha Tejasan"),
("58314819", "Surachai Detmee"),
("58314826", "Surasit Yerpui"),
("58314840", "Athit Saenwaet"),
("58314857", "Anucha Thavorn"),
("58314864", "Apichai Noihilan"),
("58314895", "Akarapon Thaidee"),
("58314901", "Auravee Malha")]
for x in myClass {
try User(name: x.1, username: x.0, password: "1234", role: .student).save()
}
}
private func insertChaz() throws {
// Teacher
let chaz = User(name: "Charles Allen", username: "chaz", password: "cave of wonders", role: .teacher)
try chaz.save()
// Dump student users here
let myClass: [(String, String, String)] = [
("58244888", "Punyapat Supakong", "dwe7qw"),
("58344281", "Kanokwan Noppakun", "w32mqb"),
("58344298", "Krit Fumin", "9cv6rx"),
("58344311", "Kollawat Sonchai", "ky92eg"),
("58344342", "Kittinan Sukkasem", "4dvuqn"),
("58344458", "Chanthaapha Chaemchon", "mc4cns"),
("58344519", "Nuttapong Laoanantasap", "szptc7"),
("58344526", "Natthamol Unboon", "a2d32d"),
("58344571", "Tawatpong Tongmuang", "cgdv64"),
("58344588", "Tarin Gurin", "erj9sb"),
("58344625", "Photsawee Phomsawat", "zxa8ed"),
("58344632", "Pittaya Pinmanee", "7dsbp2"),
("58344656", "Peerada Sornchai", "63vxya"),
("58344724", "Chavakorn Wongnuch", "p75wza"),
("58344748", "Siripron Muangprem", "p7e246"),
("58344779", "Sarawut Poree", "gvs5pr"),
("58344830", "Sumitta Siriwat", "4ce78s"),
("58344847", "Suranart Seemarksuk", "4z9v72"),
("58344854", "Saowalak Aeamsamang", "pbf5rq"),
("58344892", "Aniwat Prakart", "r3bza4"),
("58344915", "Areeya Aongsan", "dt9p5a"),
("58348005", "Suchada Rodthongdee", "af3753"),
("58364678", "Somrak Boonkerdma", "ngw75b"),
("58364692", "Sorawit Phuthirangsriwong", "rz25dp"),
("58344328", "Kanjana Healong", "u5va4f"),
("58344373", "Kasem Senket", "2sq6n3"),
("58344403", "Jinnipa Keschai", "2rejxq"),
("58344410", "Jiradet Bunyim", "s957zk"),
("58344427", "Jirawat Nutmee", "e69g3v"),
("58344434", "Jutamad Boonmark", "fa72s2"),
("58344441", "Jutamas Duangmalai", "jw5nbt"),
("58344465", "Channarong Rodthong", "rf2n7w"),
("58344472", "Chutipong Kitsanakun", "3cpa3k"),
("58344489", "Chaowat Thaiprayun", "fxcdq5"),
("58344496", "Tanawan Kietbunditkun", "3x74zs"),
("58344533", "Duangkamon Boonrot", "7ej6z5"),
("58344557", "Tanatip Kiawngam", "6j3q6t"),
("58344564", "Thanaruk Promchai", "x5kh34"),
("58344595", "Naratorn Payaksri", "76wge6"),
("58344649", "Pawis Fuenton", "gmu47t"),
("58344694", "Rattanawalee Songwattana", "rxzwm4"),
("58344700", "Ramet Natphu", "gqhs77"),
("58344717", "Laddawan Somrak", "7ezj99"),
("58344755", "Supanida Yatopama", "f9aedk"),
("58344762", "Sanphet Duanhkham", "6u3wz6"),
("58344786", "Savinee Thaworanant", "5a6h2j"),
("58344793", "Sitanan Rodcharoen", "82zbtd"),
("58344809", "Sirikhwan Homsuwan", "5yftnm"),
("58344816", "Sukanya Iambu", "7y8wbh"),
("58344823", "Suphattra Piluek", "e98tb9"),
("58344885", "Anonset Natsaphat", "5sy756"),
("58344908", "Anucha Kaewmongkonh", "aj7gk9"),
("58344922", "Aittiporn Meekaew", "m5yw73"),
("58344946", "Opas Sakulpram", "dx5upp"),
("58347930", "Chamaiporn Rhianthong", "e8thgk"),
("58347954", "Pornpan Rungsri", "v7xb6f"),
("58347961", "Patsakon Junvee", "wxrtu5"),
("58347978", "Pawin Potijinda", "69de5h"),
]
// Save students
for x in myClass {
try User(name: x.1, username: x.0, password: x.2, role: .student).save()
}
}
private func insertEvents() throws {
guard let teacher = try User.all().first, let teacherID = teacher.id else {
console.print("Cannot find teacher or it's id")
return
}
guard let problems = try? Problem.all(), problems.count >= 3 else {
console.print("Problems not found")
return
}
let event1 = Event(name: "Swift Warm-up (Week 2)", userID: teacherID)
try event1.save()
try EventProblem(eventID: event1.id!, problemID: problems[0].id!, sequence: 1).save()
try EventProblem(eventID: event1.id!, problemID: problems[1].id!, sequence: 4).save()
try EventProblem(eventID: event1.id!, problemID: problems[2].id!, sequence: 3).save()
try EventProblem(eventID: event1.id!, problemID: problems[3].id!, sequence: 2).save()
try EventProblem(eventID: event1.id!, problemID: problems[4].id!, sequence: 5).save()
try EventProblem(eventID: event1.id!, problemID: problems[5].id!, sequence: 6).save()
// let event2 = Event(name: "Swift Mini-test 1", userID: teacherID)
// try event2.save()
// try EventProblem(eventID: event2.id!, problemID: problems[1].id!, sequence: 2).save()
// try EventProblem(eventID: event2.id!, problemID: problems[2].id!, sequence: 3).save()
}
private func insertSubmissions() throws {
guard let student = try User.makeQuery().filter("role", Role.student.rawValue).first() else {
console.print("Student not found")
return
}
guard let problem = try EventProblem.makeQuery().first() else {
console.print("Problem not found")
return
}
let submission1 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .compileFailed, compilerOutput: "Missing semicolon")
try submission1.save()
let submission2 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .graded, score: 200)
try submission2.save()
let submission3 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .submitted)
try submission3.save()
let submission4 = Submission(eventProblemID: problem.id!, userID: student.id!, language: .swift, files: ["hello.swift"], state: .submitted)
try submission4.save()
}
}
extension SeedCommand: ConfigInitializable {
public convenience init(config: Config) throws {
self.init(console: try config.resolveConsole())
}
}
|
ab30669b3f69790d3154ad5f0ee6cf4e
| 58.227941 | 304 | 0.518436 | false | false | false | false |
wuyezhiguhun/DDMusicFM
|
refs/heads/master
|
DDMusicFM/DDFound/Helper/DDFindRecommendHelper.swift
|
apache-2.0
|
1
|
//
// DDFindRecommendHelper.swift
// DDMusicFM
//
// Created by yutongmac on 2017/9/14.
// Copyright © 2017年 王允顶. All rights reserved.
//
import UIKit
class DDFindRecommendHelper: NSObject {
static let helper = DDFindRecommendHelper()
var findRecommendHeaderTimer: Timer?
//MARK: == 头部定时器相关 ==
func startHeadTimer() -> Void {
self.destoryHeaderTimer()
self.findRecommendHeaderTimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(headerTimerChanged), userInfo: nil, repeats: true)
RunLoop.current.add(self.findRecommendHeaderTimer!, forMode: RunLoopMode.commonModes)
}
func destoryHeaderTimer() -> Void {
if self.findRecommendHeaderTimer != nil {
self.findRecommendHeaderTimer?.fireDate = NSDate.distantFuture
self.findRecommendHeaderTimer?.invalidate()
self.findRecommendHeaderTimer = nil
}
}
func headerTimerChanged() -> Void {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationFindRecommendHeaderTimer), object: nil)
}
}
|
445bfe42b1f55729c1cea965a8a56994
| 32.818182 | 164 | 0.698029 | false | false | false | false |
RiBj1993/CodeRoute
|
refs/heads/master
|
DemoExpandingCollection/ViewControllers/DemoViewController/DemoViewController.swift
|
apache-2.0
|
1
|
//
// DemoViewController.swift
// TestCollectionView
//
// Created by Alex K. on 12/05/16.
// Copyright © 2016 Alex K. All rights reserved.
//
import UIKit
class DemoViewController: ExpandingViewController {
typealias ItemInfo = (imageName: String, title: String)
fileprivate var cellsIsOpen = [Bool]()
fileprivate let items: [ItemInfo] = [("item0", "Boston"),("item1", "New York"),("item2", "San Francisco"),("item3", "Washington")]
@IBOutlet weak var pageLabel: UILabel!
}
// MARK: life cicle
extension DemoViewController {
override func viewDidLoad() {
itemSize = CGSize(width: 256, height: 335)
super.viewDidLoad()
registerCell()
fillCellIsOpeenArry()
addGestureToView(collectionView!)
configureNavBar()
}
}
// MARK: Helpers
extension DemoViewController {
fileprivate func registerCell() {
let nib = UINib(nibName: String(describing: DemoCollectionViewCell.self), bundle: nil)
collectionView?.register(nib, forCellWithReuseIdentifier: String(describing: DemoCollectionViewCell.self))
}
fileprivate func fillCellIsOpeenArry() {
for _ in items {
cellsIsOpen.append(false)
}
}
fileprivate func getViewController() -> ExpandingTableViewController {
let storyboard = UIStoryboard(storyboard: .Main)
let toViewController: DemoTableViewController = storyboard.instantiateViewController()
return toViewController
}
fileprivate func configureNavBar() {
navigationItem.leftBarButtonItem?.image = navigationItem.leftBarButtonItem?.image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
}
}
/// MARK: Gesture
extension DemoViewController {
fileprivate func addGestureToView(_ toView: UIView) {
let gesutereUp = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
$0.direction = .up
}
let gesutereDown = Init(UISwipeGestureRecognizer(target: self, action: #selector(DemoViewController.swipeHandler(_:)))) {
$0.direction = .down
}
toView.addGestureRecognizer(gesutereUp)
toView.addGestureRecognizer(gesutereDown)
}
func swipeHandler(_ sender: UISwipeGestureRecognizer) {
let indexPath = IndexPath(row: currentIndex, section: 0)
guard let cell = collectionView?.cellForItem(at: indexPath) as? DemoCollectionViewCell else { return }
// double swipe Up transition
if cell.isOpened == true && sender.direction == .up {
pushToViewController(getViewController())
if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
rightButton.animationSelected(true)
}
}
let open = sender.direction == .up ? true : false
cell.cellIsOpen(open)
cellsIsOpen[(indexPath as NSIndexPath).row] = cell.isOpened
}
}
// MARK: UIScrollViewDelegate
extension DemoViewController {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageLabel.text = "\(currentIndex+1)/\(items.count)"
}
}
// MARK: UICollectionViewDataSource
extension DemoViewController {
override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
guard let cell = cell as? DemoCollectionViewCell else { return }
let index = (indexPath as NSIndexPath).row % items.count
let info = items[index]
cell.backgroundImageView?.image = UIImage(named: info.imageName)
cell.customTitle.text = info.title
cell.cellIsOpen(cellsIsOpen[index], animated: false)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? DemoCollectionViewCell
, currentIndex == (indexPath as NSIndexPath).row else { return }
if cell.isOpened == false {
cell.cellIsOpen(true)
} else {
pushToViewController(getViewController())
if let rightButton = navigationItem.rightBarButtonItem as? AnimatingBarButton {
rightButton.animationSelected(true)
}
}
}
}
// MARK: UICollectionViewDataSource
extension DemoViewController {
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: DemoCollectionViewCell.self), for: indexPath)
}
}
|
ae03c70798e077d9494952e7a33ae995
| 30.938356 | 141 | 0.726142 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS
|
refs/heads/master
|
HoelangTotTrein2/Services/AppLocationService.swift
|
mit
|
1
|
//
// LocationService.swift
// HoelangTotTrein2
//
// Created by Tomas Harkema on 03-10-15.
// Copyright © 2015 Tomas Harkema. All rights reserved.
//
import CoreLocation
import Foundation
import Promissum
import RxSwift
#if os(watchOS)
import HoelangTotTreinAPIWatch
import HoelangTotTreinCoreWatch
#elseif os(iOS)
import HoelangTotTreinAPI
import HoelangTotTreinCore
#endif
struct SignificantLocation: Equatable {
let location: CLLocation
let neighbouringStations: [Station]
}
func == (lhs: SignificantLocation, rhs: SignificantLocation) -> Bool {
lhs.location == rhs.location
}
class AppLocationService: NSObject, CLLocationManagerDelegate, LocationService {
let manager: CLLocationManager
let significantLocationChangeObservable = Variable<SignificantLocation?>(nil).asObservable()
override init() {
manager = CLLocationManager()
super.init()
manager.delegate = self
initialize()
}
func initialize() {}
deinit {
requestAuthorizationPromise = nil
currentLocationPromise = nil
}
func locationManager(_: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
requestAuthorizationPromise?.resolve(status)
switch status {
case .authorizedAlways:
initialize()
default:
break
}
}
fileprivate var requestAuthorizationPromise: PromiseSource<CLAuthorizationStatus, Error>?
func requestAuthorization() -> Promise<CLAuthorizationStatus, Error> {
let currentState = CLLocationManager.authorizationStatus()
switch currentState {
case .authorizedAlways:
return Promise(value: currentState)
default:
requestAuthorizationPromise = PromiseSource<CLAuthorizationStatus, Error>()
manager.requestAlwaysAuthorization()
return requestAuthorizationPromise?.promise ?? Promise(error: NSError(domain: "HLTT", code: 500, userInfo: nil))
}
}
fileprivate var currentLocationPromise: PromiseSource<CLLocation, Error>?
func currentLocation() -> Promise<CLLocation, Error> {
if let location = manager.location, DateInterval(start: location.timestamp, end: Date()).duration < 560 {
return Promise(value: location)
}
if currentLocationPromise?.promise.result != nil || currentLocationPromise == nil {
currentLocationPromise = PromiseSource<CLLocation, Error>()
}
manager.requestLocation()
return currentLocationPromise!.promise
}
func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let closestLocation = locations.sorted { lhs, rhs in
(lhs.horizontalAccuracy + lhs.verticalAccuracy) > (rhs.horizontalAccuracy + rhs.verticalAccuracy)
}.first
if let closestLocation = closestLocation {
currentLocationPromise?.resolve(closestLocation)
} else {
currentLocationPromise?.reject(NSError(domain: "HLTT", code: 500, userInfo: nil))
}
}
}
extension AppLocationService {
func locationManager(_: CLLocationManager, didFailWithError error: Error) {
currentLocationPromise?.reject(error)
}
}
|
2ed1ff16382dc9852462939c3e376b2d
| 27.598131 | 118 | 0.741176 | false | false | false | false |
manavgabhawala/UberSDK
|
refs/heads/master
|
Shared/UberProduct.swift
|
apache-2.0
|
1
|
//
// UberProduct.swift
// UberSDK
//
// Created by Manav Gabhawala on 6/12/15.
//
//
import Foundation
/// The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.
@objc public final class UberProduct : NSObject, JSONCreateable, UberObjectHasImage
{
/// Unique identifier representing a specific product for a given latitude & longitude.
@objc public let productID: String
/// Display name of product.
@objc public let name: String
/// Image URL representing the product. Depending on the platform you are using you can ask the UberProduct class to download the image `asynchronously` for you too.
@objc public let imageURL : NSURL?
/// Description of product.
@objc public let productDescription: String
/// Capacity of product. For example, 4 people.
@objc public let capacity : Int
/// The basic price details (not including any surge pricing adjustments). If null, the price is a metered fare such as a taxi service.
@objc public var priceDetails : UberPriceDetails?
@objc public override var description : String { get { return "\(name): \(productDescription)" } }
private init?(productID: String? = nil, name: String? = nil, productDescription: String? = nil, capacity: Int? = nil, imageURL: String? = nil)
{
guard let id = productID, let name = name, let description = productDescription, let capacity = capacity
else
{
self.productID = ""; self.name = ""; self.productDescription = ""; self.capacity = 0; self.imageURL = nil
super.init()
return nil
}
self.productID = id
self.name = name
self.productDescription = description
self.capacity = capacity
if let URL = imageURL
{
self.imageURL = NSURL(string: URL)
}
else
{
self.imageURL = nil
}
super.init()
}
public convenience required init?(JSON: [NSObject: AnyObject])
{
self.init(productID: JSON["product_id"] as? String, name: JSON["display_name"] as? String, productDescription: JSON["description"] as? String, capacity: JSON["capacity"] as? Int, imageURL: JSON["image"] as? String)
if self.productID.isEmpty
{
return nil
}
self.priceDetails = UberPriceDetails(JSON: JSON["price_details"] as? [NSObject: AnyObject])
}
}
|
6c2593e65bf5f5b2c5711e6203b68022
| 34.515152 | 227 | 0.719283 | false | false | false | false |
ellipse43/v2ex
|
refs/heads/master
|
v2ex/SimpleAnimate.swift
|
mit
|
1
|
//
// SimpleAnimate.swift
// v2ex
//
// Created by ellipse42 on 15/8/17.
// Copyright (c) 2015年 ellipse42. All rights reserved.
//
import Foundation
import Refresher
import QuartzCore
import UIKit
class SimpleAnimator: UIView, PullToRefreshViewDelegate {
let layerLoader = CAShapeLayer()
let imageLayer = CALayer()
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func pullToRefresh(_ view: PullToRefreshView, progressDidChange progress: CGFloat) {
layerLoader.strokeEnd = progress
}
func pullToRefresh(_ view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) {
}
func pullToRefreshAnimationDidEnd(_ view: PullToRefreshView) {
layerLoader.removeAllAnimations()
}
func pullToRefreshAnimationDidStart(_ view: PullToRefreshView) {
if layerLoader.strokeEnd != 0.6 {
layerLoader.strokeEnd = 0.6
}
let pathAnimationEnd = CABasicAnimation(keyPath: "transform.rotation")
pathAnimationEnd.duration = 1.5
pathAnimationEnd.repeatCount = HUGE
pathAnimationEnd.isRemovedOnCompletion = false
pathAnimationEnd.fromValue = 0
pathAnimationEnd.toValue = 2 * M_PI
layerLoader.add(pathAnimationEnd, forKey: "strokeEndAnimation")
}
override func layoutSubviews() {
super.layoutSubviews()
if let superview = superview {
if layerLoader.superlayer == nil {
layerLoader.lineWidth = 1
layerLoader.strokeColor = UIColor.black.cgColor
layerLoader.fillColor = UIColor.clear.cgColor
layerLoader.strokeEnd = 0.6
layerLoader.lineCap = kCALineCapRound
superview.layer.addSublayer(layerLoader)
}
if imageLayer.superlayer == nil {
imageLayer.cornerRadius = 10.0
imageLayer.contents = UIImage(named:"refresh")?.cgImage
imageLayer.masksToBounds = true
imageLayer.frame = CGRect(x: superview.frame.size.width / 2 - 10, y: superview.frame.size.height / 2 - 10, width: 20.0, height: 20.0)
superview.layer.addSublayer(imageLayer)
}
let center = CGPoint(x: superview.frame.size.width / 2, y: superview.frame.size.height / 2)
let bezierPathLoader = UIBezierPath(arcCenter: center, radius: CGFloat(10), startAngle: CGFloat(0), endAngle: CGFloat(2 * M_PI), clockwise: true)
layerLoader.path = bezierPathLoader.cgPath
layerLoader.bounds = bezierPathLoader.cgPath.boundingBox
layerLoader.frame = bezierPathLoader.cgPath.boundingBox
}
}
}
|
77ed4ddeb1c6e51f379451a50cbdd3f7
| 35.820513 | 157 | 0.637535 | false | false | false | false |
efeconirulez/daily-affirmation
|
refs/heads/master
|
Daily Affirmation/Models/Affirmation.swift
|
apache-2.0
|
1
|
//
// Affirmation.swift
// Daily Affirmation
//
// Created by Efe Helvacı on 22.10.2017.
// Copyright © 2017 efehelvaci. All rights reserved.
//
import Foundation
class Affirmation {
struct AffirmationStoreKeys {
static let BannedAffirmationsKey = "BannedAffirmations"
static let FavoriteAffirmationKey = "FavoriteAffirmations"
static let SeenAffirmationKey = "SeenAffirmations"
static let LastSeenAffirmationID = "LastSeenAffirmationID"
static let LastLaunchDate = "LastLaunchDate"
}
var id: Int
var clause: String
var isFavorite: Bool {
willSet {
guard isFavorite != newValue else {
return
}
Affirmation.isChanged = true
var favoriteAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.FavoriteAffirmationKey) as? [Int] ?? [Int]()
if newValue {
favoriteAffirmations.append(self.id)
} else {
if let index = favoriteAffirmations.index(of: self.id) {
favoriteAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(favoriteAffirmations, forKey: AffirmationStoreKeys.FavoriteAffirmationKey)
UserDefaults.standard.synchronize()
}
}
var isBanned: Bool {
willSet {
Affirmation.isChanged = true
var bannedAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.BannedAffirmationsKey) as? [Int] ?? [Int]()
if newValue {
bannedAffirmations.append(self.id)
} else {
if let index = bannedAffirmations.index(of: self.id) {
bannedAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(bannedAffirmations, forKey: AffirmationStoreKeys.BannedAffirmationsKey)
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.LastLaunchDate)
UserDefaults.standard.synchronize()
}
}
var isSeen: Bool {
willSet {
guard isSeen != newValue else {
return
}
Affirmation.isChanged = true
var seenAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.SeenAffirmationKey) as? [Int] ?? [Int]()
if newValue {
seenAffirmations.append(self.id)
} else {
if let index = seenAffirmations.index(of: self.id) {
seenAffirmations.remove(at: index)
}
}
UserDefaults.standard.set(seenAffirmations, forKey: AffirmationStoreKeys.SeenAffirmationKey)
UserDefaults.standard.synchronize()
}
}
init(id: Int, clause: String, isFavorite: Bool, isBanned: Bool, isSeen: Bool) {
self.id = id
self.clause = clause
self.isFavorite = isFavorite
self.isBanned = isBanned
self.isSeen = isSeen
}
}
extension Affirmation {
static fileprivate var shared: [Affirmation]?
static fileprivate var isChanged: Bool = true
static func getAffirmations(shouldUpdate update: Bool = isChanged) -> [Affirmation] {
if let affirmations = shared, !update {
return affirmations
}
if let plistFile = Bundle.main.path(forResource: "Affirmations", ofType: "plist"),
let affirmationObjects = NSArray(contentsOfFile: plistFile) as? [NSDictionary] {
var affirmations = [Affirmation]()
for affirmationObject in affirmationObjects {
let id = affirmationObject["id"] as! Int
let clause = affirmationObject["clause"] as! String
var isBanned = false
var isFavorite = false
var isSeen = false
if let bannedAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.BannedAffirmationsKey) as? [Int] {
isBanned = bannedAffirmations.contains(id)
}
if let seenAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.SeenAffirmationKey) as? [Int] {
isSeen = seenAffirmations.contains(id)
}
if let favoriteAffirmations = UserDefaults.standard.array(forKey: AffirmationStoreKeys.FavoriteAffirmationKey) as? [Int] {
isFavorite = favoriteAffirmations.contains(id)
}
affirmations.append(Affirmation(id: id, clause: clause, isFavorite: isFavorite, isBanned: isBanned, isSeen: isSeen))
}
shared = affirmations
isChanged = false
return affirmations
}
return [Affirmation]()
}
// Affirmations that can be shown
static private func validAffirmations() -> [Affirmation] {
var affirmations = getAffirmations()
affirmations = affirmations.filter{ !$0.isBanned }
if affirmations.count == 0 {
print("All clauses are banned!!!")
// TODO show message to notify user
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.BannedAffirmationsKey)
affirmations = getAffirmations(shouldUpdate: true)
}
affirmations = affirmations.filter{ !$0.isSeen }
if affirmations.count == 0 {
print("All clauses are seen!!!")
// TODO show message to notify user
UserDefaults.standard.removeObject(forKey: AffirmationStoreKeys.SeenAffirmationKey)
affirmations = getAffirmations(shouldUpdate: true)
}
return affirmations
}
static private func storeLastAffirmation(_ affirmation: Affirmation) {
UserDefaults.standard.set(affirmation.id, forKey: AffirmationStoreKeys.LastSeenAffirmationID)
UserDefaults.standard.set(Date(), forKey: AffirmationStoreKeys.LastLaunchDate)
UserDefaults.standard.synchronize()
}
static private func random() -> Affirmation {
let affirmations = validAffirmations()
let randomAffirmation = affirmations.randomItem!
storeLastAffirmation(randomAffirmation)
return randomAffirmation
}
class public var favorites: [Affirmation] {
let affirmations = getAffirmations()
return affirmations.filter { $0.isFavorite && !$0.isBanned }
}
class public func daily() -> Affirmation {
if let previousdate = UserDefaults.standard.object(forKey: AffirmationStoreKeys.LastLaunchDate) as? Date, previousdate.isInToday {
let affirmations = getAffirmations()
let affirmationID = UserDefaults.standard.integer(forKey: AffirmationStoreKeys.LastSeenAffirmationID)
if let index = affirmations.index(where: { $0.id == affirmationID }) {
return affirmations[index]
}
}
return Affirmation.random()
}
}
|
61150abe7a14387179f52f86837caccd
| 35.202899 | 140 | 0.581799 | false | false | false | false |
itsaboutcode/WordPress-iOS
|
refs/heads/develop
|
WordPress/WordPressTest/PostCompactCellTests.swift
|
gpl-2.0
|
2
|
import UIKit
import XCTest
@testable import WordPress
class PostCompactCellTests: XCTestCase {
var postCell: PostCompactCell!
override func setUp() {
postCell = postCellFromNib()
}
func testShowImageWhenAvailable() {
let post = PostBuilder().withImage().build()
postCell.configure(with: post)
XCTAssertFalse(postCell.featuredImageView.isHidden)
}
func testHideImageWhenNotAvailable() {
let post = PostBuilder().build()
postCell.configure(with: post)
XCTAssertTrue(postCell.featuredImageView.isHidden)
}
func testShowPostTitle() {
let post = PostBuilder().with(title: "Foo bar").build()
postCell.configure(with: post)
XCTAssertEqual(postCell.titleLabel.text, "Foo bar")
}
func testShowDate() {
let post = PostBuilder().with(remoteStatus: .sync)
.with(dateCreated: Date()).build()
postCell.configure(with: post)
XCTAssertEqual(postCell.timestampLabel.text, "now")
}
func testMoreAction() {
let postActionSheetDelegateMock = PostActionSheetDelegateMock()
let post = PostBuilder().published().build()
postCell.configure(with: post)
postCell.setActionSheetDelegate(postActionSheetDelegateMock)
postCell.menuButton.sendActions(for: .touchUpInside)
XCTAssertEqual(postActionSheetDelegateMock.calledWithPost, post)
XCTAssertEqual(postActionSheetDelegateMock.calledWithView, postCell.menuButton)
}
func testStatusAndBadgeLabels() {
let post = PostBuilder().with(remoteStatus: .sync)
.with(dateCreated: Date()).is(sticked: true).build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "Sticky")
}
func testHideBadgesWhenEmpty() {
let post = PostBuilder().build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "Uploading post...")
XCTAssertFalse(postCell.badgesLabel.isHidden)
}
func testShowBadgesWhenNotEmpty() {
let post = PostBuilder()
.with(remoteStatus: .sync)
.build()
postCell.configure(with: post)
XCTAssertEqual(postCell.badgesLabel.text, "")
XCTAssertTrue(postCell.badgesLabel.isHidden)
}
func testShowProgressView() {
let post = PostBuilder()
.with(remoteStatus: .pushing)
.published().build()
postCell.configure(with: post)
XCTAssertFalse(postCell.progressView.isHidden)
}
func testHideProgressView() {
let post = PostBuilder()
.with(remoteStatus: .sync)
.published().build()
postCell.configure(with: post)
XCTAssertTrue(postCell.progressView.isHidden)
}
func testShowsWarningMessageForFailedPublishedPosts() {
// Given
let post = PostBuilder().published().with(remoteStatus: .failed).confirmedAutoUpload().build()
// When
postCell.configure(with: post)
// Then
XCTAssertEqual(postCell.badgesLabel.text, i18n("We'll publish the post when your device is back online."))
XCTAssertEqual(postCell.badgesLabel.textColor, UIColor.warning)
}
private func postCellFromNib() -> PostCompactCell {
let bundle = Bundle(for: PostCompactCell.self)
guard let postCell = bundle.loadNibNamed("PostCompactCell", owner: nil)?.first as? PostCompactCell else {
fatalError("PostCompactCell does not exist")
}
return postCell
}
}
|
dc5692ef73bf4ee5a1f72f8328769c1b
| 26.914729 | 114 | 0.655374 | false | true | false | false |
jameslinjl/SHPJavaGrader
|
refs/heads/master
|
Sources/App/Controllers/AssignmentController.swift
|
mit
|
1
|
import HTTP
import Vapor
final class AssignmentController {
func create(_ req: Request) throws -> ResponseRepresentable {
if let labNumberString = req.data["labNumber"]?.string {
if let labNumber = Int(labNumberString) {
// ensure that a lab with this number exists
let assignmentMapping = try AssignmentMapping.query().filter(
"lab_number",
labNumber
).first()
if assignmentMapping != nil {
if let username = try req.session().data["username"]?.string {
var assignment = Assignment(
username: username,
labNumber: labNumber,
content: ""
)
try assignment.save()
return assignment
}
}
}
}
return Response(status: .badRequest)
}
func show(_ req: Request, _ assignment: Assignment) -> ResponseRepresentable {
return assignment
}
func update(_ req: Request, _ assignment: Assignment) throws -> ResponseRepresentable {
var assignment = assignment
assignment.merge(patch: req.json?.node)
try assignment.save()
return assignment
}
func destroy(_ req: Request, _ assignment: Assignment) throws -> ResponseRepresentable {
// delete all grades associated with that assignment
let grades = try GradingResult.query().filter(
"assignmentId",
assignment.id!
).all()
for grade in grades {
try grade.delete()
}
try assignment.delete()
return Response(status: .noContent)
}
}
extension AssignmentController: ResourceRepresentable {
func makeResource() -> Resource<Assignment> {
return Resource(
store: create,
show: show,
modify: update,
destroy: destroy
)
}
}
|
4d97254d8bc388b4a80c07e8baddbf2f
| 24.47619 | 89 | 0.683489 | false | false | false | false |
jverkoey/FigmaKit
|
refs/heads/main
|
Sources/FigmaKit/Effect.swift
|
apache-2.0
|
1
|
/// A Figma effect.
///
/// "A visual effect such as a shadow or blur."
/// https://www.figma.com/developers/api#effect-type
public class Effect: PolymorphicDecodable {
/// The Type of effect.
public let type: EffectType
/// Is the effect active?
public let visible: Bool
/// Radius of the blur effect (applies to shadows as well).
public let radius: Double
private enum CodingKeys: String, CodingKey {
case type
case visible
case radius
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.type = try keyedDecoder.decode(EffectType.self, forKey: .type)
self.visible = try keyedDecoder.decode(Bool.self, forKey: .visible)
self.radius = try keyedDecoder.decode(Double.self, forKey: .radius)
}
public static func decodePolymorphicArray(from decoder: UnkeyedDecodingContainer) throws -> [Effect] {
return try decodePolyType(from: decoder, keyedBy: Effect.CodingKeys.self, key: .type, typeMap: Effect.typeMap)
}
static let typeMap: [EffectType: Effect.Type] = [
.innerShadow: Shadow.self,
.dropShadow: DropShadow.self,
.layerBlur: Effect.self,
.backgroundBlur: Effect.self,
]
public enum EffectType: String, Codable {
case innerShadow = "INNER_SHADOW"
case dropShadow = "DROP_SHADOW"
case layerBlur = "LAYER_BLUR"
case backgroundBlur = "BACKGROUND_BLUR"
}
public var description: String {
return """
<\(Swift.type(of: self))
- type: \(type)
- visible: \(visible)
- radius: \(radius)
\(effectDescription.isEmpty ? "" : "\n" + effectDescription)
>
"""
}
var effectDescription: String {
return ""
}
}
extension Effect {
/// A Figma shadow effect.
public final class Shadow: Effect {
/// The color of the shadow.
public let color: Color
/// The blend mode of the shadow.
public let blendMode: BlendMode
/// How far the shadow is projected in the x and y directions.
public let offset: Vector
/// How far the shadow spreads.
public let spread: Double
private enum CodingKeys: String, CodingKey {
case color
case blendMode
case offset
case spread
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.color = try keyedDecoder.decode(Color.self, forKey: .color)
self.blendMode = try keyedDecoder.decode(BlendMode.self, forKey: .blendMode)
self.offset = try keyedDecoder.decode(Vector.self, forKey: .offset)
self.spread = try keyedDecoder.decodeIfPresent(Double.self, forKey: .spread) ?? 0
try super.init(from: decoder)
}
override var effectDescription: String {
return """
- color: \(color)
- blendMode: \(blendMode)
- offset: \(offset)
- spread: \(spread)
"""
}
}
/// A Figma drop shadow effect.
public final class DropShadow: Effect {
/// Whether to show the shadow behind translucent or transparent pixels.
public let showShadowBehindNode: Bool
private enum CodingKeys: String, CodingKey {
case showShadowBehindNode
}
public required init(from decoder: Decoder) throws {
let keyedDecoder = try decoder.container(keyedBy: Self.CodingKeys)
self.showShadowBehindNode = try keyedDecoder.decode(Bool.self, forKey: .showShadowBehindNode)
try super.init(from: decoder)
}
override var effectDescription: String {
return super.effectDescription + """
- showShadowBehindNode: \(showShadowBehindNode)
"""
}
}
}
|
31c33482e1b588b6b2723ca0dd5b3517
| 28.880952 | 114 | 0.651262 | false | false | false | false |
keitaoouchi/RxAudioVisual
|
refs/heads/master
|
RxAudioVisualTests/AVPlayer+RxSpec.swift
|
mit
|
1
|
import Quick
import Nimble
import RxSwift
import AVFoundation
@testable import RxAudioVisual
class AVPlayerSpec: QuickSpec {
override func spec() {
describe("KVO through rx") {
var player: AVPlayer!
var disposeBag: DisposeBag!
beforeEach {
player = AVPlayer(url: TestHelper.sampleURL)
disposeBag = DisposeBag()
}
it("should load status") {
var e: AVPlayerStatus?
player.rx.status.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerStatus.readyToPlay))
}
it("should load timeControlStatus") {
player.pause()
var e: AVPlayerTimeControlStatus?
player.rx.timeControlStatus.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerTimeControlStatus.paused))
player.play()
expect(e).toEventually(equal(AVPlayerTimeControlStatus.playing))
}
it("should load rate") {
var e: Float?
player.rx.rate.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(0.0))
player.rate = 1.0
expect(e).toEventually(equal(1.0))
}
it("should load currentItem") {
var e: AVPlayerItem?
player.rx.currentItem.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
}
it("should load actionAtItemEnd") {
var e: AVPlayerActionAtItemEnd?
player.rx.actionAtItemEnd.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(AVPlayerActionAtItemEnd.pause))
}
it("should load volume") {
var e: Float?
player.rx.volume.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(equal(1.0))
player.volume = 0.0
expect(e).toEventually(equal(0.0))
}
it("should load muted") {
var e: Bool?
player.rx.muted.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
player.isMuted = true
expect(e).toEventually(beTrue())
}
it("should load closedCaptionDisplayEnabled") {
var e: Bool?
player.rx.closedCaptionDisplayEnabled.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load allowsExternalPlayback") {
var e: Bool?
player.rx.allowsExternalPlayback.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beTrue())
}
it("should load externalPlaybackActive") {
var e: Bool?
player.rx.externalPlaybackActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
it("should load usesExternalPlaybackWhileExternalScreenIsActive") {
var e: Bool?
player.rx.usesExternalPlaybackWhileExternalScreenIsActive.subscribe(onNext: { v in e = v }).disposed(by: disposeBag)
expect(e).toEventuallyNot(beNil())
expect(e).toEventually(beFalse())
}
}
}
}
|
0ac0c051f04e8c8e47f5762762c059dc
| 32.240741 | 124 | 0.627298 | false | false | false | false |
SymbolLong/Photo
|
refs/heads/master
|
photo-ios/photo-ios/Common.swift
|
apache-2.0
|
1
|
//
// File.swift
// photo-ios
//
// Created by 张圣龙 on 2017/4/14.
// Copyright © 2017年 张圣龙. All rights reserved.
//
import Foundation
class Common{
static let HOST_KEY = "host"
static let PORT_KEY = "port"
static let ID_KEY = "id"
static let API_GET = "/api/get?id="
}
|
1b14d74edaf24853b9c58d3a3c6d6890
| 17.125 | 47 | 0.613793 | false | false | false | false |
tgu/HAP
|
refs/heads/master
|
Sources/HAP/Endpoints/pairSetup().swift
|
mit
|
1
|
import Cryptor
import func Evergreen.getLogger
import Foundation
import SRP
fileprivate let logger = getLogger("hap.pairSetup")
fileprivate typealias Session = PairSetupController.Session
fileprivate let SESSION_KEY = "hap.pair-setup.session"
fileprivate enum Error: Swift.Error {
case noSession
}
// swiftlint:disable:next cyclomatic_complexity
func pairSetup(device: Device) -> Application {
let group = Group.N3072
let algorithm = Digest.Algorithm.sha512
let username = "Pair-Setup"
let (salt, verificationKey) = createSaltedVerificationKey(username: username,
password: device.setupCode,
group: group,
algorithm: algorithm)
let controller = PairSetupController(device: device)
func createSession() -> Session {
return Session(server: SRP.Server(username: username,
salt: salt,
verificationKey: verificationKey,
group: group,
algorithm: algorithm))
}
func getSession(_ connection: Server.Connection) throws -> Session {
guard let session = connection.context[SESSION_KEY] as? Session else {
throw Error.noSession
}
return session
}
return { connection, request in
var body = Data()
guard
(try? request.readAllData(into: &body)) != nil,
let data: PairTagTLV8 = try? decode(body),
let sequence = data[.state]?.first.flatMap({ PairSetupStep(rawValue: $0) })
else {
return .badRequest
}
let response: PairTagTLV8?
do {
switch sequence {
// M1: iOS Device -> Accessory -- `SRP Start Request'
case .startRequest:
let session = createSession()
response = try controller.startRequest(data, session)
connection.context[SESSION_KEY] = session
// M3: iOS Device -> Accessory -- `SRP Verify Request'
case .verifyRequest:
let session = try getSession(connection)
response = try controller.verifyRequest(data, session)
// M5: iOS Device -> Accessory -- `Exchange Request'
case .keyExchangeRequest:
let session = try getSession(connection)
response = try controller.keyExchangeRequest(data, session)
// Unknown state - return error and abort
default:
throw PairSetupController.Error.invalidParameters
}
} catch {
logger.warning(error)
connection.context[SESSION_KEY] = nil
try? device.changePairingState(.notPaired)
switch error {
case PairSetupController.Error.invalidParameters:
response = [
(.state, Data(bytes: [PairSetupStep.waiting.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.alreadyPaired:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.unavailable.rawValue]))
]
case PairSetupController.Error.alreadyPairing:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.busy.rawValue]))
]
case PairSetupController.Error.invalidSetupState:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.authenticationFailed:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.authenticationFailed.rawValue]))
]
default:
response = nil
}
}
if let response = response {
return Response(status: .ok, data: encode(response), mimeType: "application/pairing+tlv8")
} else {
return .badRequest
}
}
}
|
ffd49b5ebdd321f6943252676c77b155
| 41.738318 | 102 | 0.542314 | false | false | false | false |
xiaoleixy/Cocoa_swift
|
refs/heads/master
|
RaiseMan/RaiseMan/Document.swift
|
mit
|
1
|
//
// Document.swift
// RaiseMan
//
// Created by michael on 15/2/14.
// Copyright (c) 2015年 michael. All rights reserved.
//
import Cocoa
//忘记加前缀了, 看着这不要有疑惑 就是RMDocument
class Document: NSDocument {
@objc(employees)
var employees:[Person] = [Person]() {
willSet {
for person in employees {
self.stopObservingPerson(person as Person)
}
}
didSet {
for person in employees {
self.startObservingPerson(person as Person)
}
}
}
@IBOutlet var tableView: NSTableView!
@IBOutlet var employeeController: NSArrayController!
private var RMDocumentKVOContext = 0
override init() {
super.init()
// Add your subclass-specific initialization here.
NSNotificationCenter.defaultCenter().addObserver(self, selector:"handleColorChange:" , name: BNRColorChangedNotification, object: nil)
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
tableView.backgroundColor = PreferenceController.preferenceTableBgColor()
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "Document"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
// return nil
//保存
tableView.window?.endEditingFor(nil)
return NSKeyedArchiver.archivedDataWithRootObject(employees)
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
if let newArray = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Person] {
self.employees = newArray
return true
}else
{
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if (context != &RMDocumentKVOContext)
{
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
return
}
let undo = self.undoManager
var oldValue: AnyObject? = change[NSKeyValueChangeOldKey]
undo?.prepareWithInvocationTarget(self).changeKeyPath(keyPath, ofObject: object, toValue: oldValue!)
undo?.setActionName("Edit")
}
@IBAction func onCheck(sender: AnyObject) {
println(self.employees)
}
@IBAction func createEmployee(sender: AnyObject)
{
let w: NSWindow = self.tableView.window!
//准备结束正在发生的编辑动作
let editingEnded = w.makeFirstResponder(w)
if (!editingEnded)
{
println("Unable to end editing")
return
}
let undo = self.undoManager
if undo?.groupingLevel > 0 {
undo?.endUndoGrouping()
undo?.beginUndoGrouping()
}
let p = self.employeeController.newObject() as Person
self.employeeController.addObject(p)
//重新排序
self.employeeController.rearrangeObjects()
//排序后的数组
var a = self.employeeController.arrangedObjects as NSArray
let row = a.indexOfObjectIdenticalTo(p)
self.tableView.editColumn(0, row: row, withEvent: nil, select: true)
}
func startObservingPerson(person: Person)
{
person.addObserver(self, forKeyPath: "personName", options: NSKeyValueObservingOptions.Old, context: &RMDocumentKVOContext)
person.addObserver(self, forKeyPath: "expectedRaise", options: NSKeyValueObservingOptions.Old, context: &RMDocumentKVOContext)
}
func stopObservingPerson(person: Person)
{
person.removeObserver(self, forKeyPath: "personName", context: &RMDocumentKVOContext)
person.removeObserver(self, forKeyPath: "expectedRaise", context: &RMDocumentKVOContext)
}
func changeKeyPath(keyPath:NSString, ofObject obj: AnyObject, toValue newValue:AnyObject)
{
obj.setValue(newValue, forKeyPath: keyPath)
}
func insertObject(p: Person, inEmployeesAtIndex index: Int){
println("adding \(p) to \(self.employees)")
let undo = self.undoManager
undo?.prepareWithInvocationTarget(self).removeObjectFromEmployeesAtIndex(index)
if (false == undo?.undoing) {
undo?.setActionName("Add Person")
}
self.employees.insert(p, atIndex: index)
}
func removeObjectFromEmployeesAtIndex(index: Int) {
let p: Person = self.employees[index] as Person
println("removing \(p) to \(self.employees)")
let undo = self.undoManager
undo?.prepareWithInvocationTarget(self).insertObject(p, inEmployeesAtIndex: index)
if (false == undo?.undoing) {
undo?.setActionName("Remove Person")
}
self.employees.removeAtIndex(index)
}
func handleColorChange(notification: NSNotification)
{
tableView.backgroundColor = PreferenceController.preferenceTableBgColor()
}
}
|
8a5988168797952e7b281e5b8f28c099
| 35.33871 | 198 | 0.648321 | false | false | false | false |
tise/SwipeableViewController
|
refs/heads/master
|
SwipeableViewController/Source/SwipeableNavigationBar.swift
|
mit
|
1
|
//
// SwipeableNavigationBar.swift
// SwipingViewController
//
// Created by Oscar Apeland on 12.10.2017.
// Copyright © 2017 Tise. All rights reserved.
//
import UIKit
open class SwipeableNavigationBar: UINavigationBar {
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
if #available(iOS 11.0, *) {
largeTitleTextAttributes = [.foregroundColor: UIColor.clear]
prefersLargeTitles = true
}
}
// MARK: Properties
lazy var largeTitleView: UIView? = {
return subviews.first {
String(describing: type(of: $0)) == "_UINavigationBarLargeTitleView"
}
}()
var largeTitleLabel: UILabel? {
return largeTitleView?.subviews.first { $0 is UILabel } as? UILabel
}
lazy var collectionView: SwipeableCollectionView = {
$0.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
return $0
}(SwipeableCollectionView(frame: largeTitleView!.bounds,
collectionViewLayout: SwipeableCollectionViewFlowLayout()))
}
|
891a03600962e55809956ebbc1124705
| 26.608696 | 89 | 0.615748 | false | false | false | false |
narner/AudioKit
|
refs/heads/master
|
Playgrounds/AudioKitPlaygrounds/Playgrounds/Filters.playground/Pages/Resonant Filter.xcplaygroundpage/Contents.swift
|
mit
|
1
|
//: ## Resonant Filter
//:
import AudioKitPlaygrounds
import AudioKit
let file = try AKAudioFile(readFileName: playgroundAudioFiles[0])
let player = try AKAudioPlayer(file: file)
player.looping = true
var filter = AKResonantFilter(player)
filter.frequency = 5_000 // Hz
filter.bandwidth = 600 // Cents
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
import AudioKitUI
class LiveView: AKLiveViewController {
override func viewDidLoad() {
addTitle("Resonant Filter")
addView(AKResourcesAudioFileLoaderView(player: player, filenames: playgroundAudioFiles))
addView(AKButton(title: "Stop") { button in
filter.isStarted ? filter.stop() : filter.play()
button.title = filter.isStarted ? "Stop" : "Start"
})
addView(AKSlider(property: "Frequency",
value: filter.frequency,
range: 20 ... 22_050,
taper: 5,
format: "%0.1f Hz"
) { sliderValue in
filter.frequency = sliderValue
})
addView(AKSlider(property: "Bandwidth",
value: filter.bandwidth,
range: 100 ... 1_200,
format: "%0.1f Hz"
) { sliderValue in
filter.bandwidth = sliderValue
})
}
}
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = LiveView()
|
9aa5b235ced717b8ee1aa84f9f7fba6e
| 26.563636 | 96 | 0.600264 | false | false | false | false |
ikesyo/Swiftz
|
refs/heads/master
|
Swiftz/State.swift
|
bsd-3-clause
|
3
|
//
// State.swift
// Swiftz
//
// Created by Robert Widmann on 2/21/15.
// Copyright (c) 2015 TypeLift. All rights reserved.
//
/// The State Monad represents a computation that threads a piece of state through each step.
public struct State<S, A> {
public let runState : S -> (A, S)
/// Creates a new State Monad given a function from a piece of state to a value and an updated
/// state.
public init(_ runState : S -> (A, S)) {
self.runState = runState
}
/// Evaluates the computation given an initial state then returns a final value after running
/// each step.
public func eval(s : S) -> A {
return self.runState(s).0
}
/// Evaluates the computation given an initial state then returns the final state after running
/// each step.
public func exec(s : S) -> S {
return self.runState(s).1
}
/// Executes an action that can modify the inner state.
public func withState(f : S -> S) -> State<S, A> {
return State(self.runState • f)
}
}
/// Fetches the current value of the state.
public func get<S>() -> State<S, S> {
return State<S, S> { ($0, $0) }
}
/// Sets the state.
public func put<S>(s : S) -> State<S, ()> {
return State<S, ()> { _ in ((), s) }
}
/// Gets a specific component of the state using a projection function.
public func gets<S, A>(f : S -> A) -> State<S, A> {
return State { s in (f(s), s) }
}
/// Updates the state with the result of executing the given function.
public func modify<S>(f : S -> S) -> State<S, ()> {
return State<S, ()> { s in ((), f(s)) }
}
extension State : Functor {
public typealias B = Swift.Any
public typealias FB = State<S, B>
public func fmap<B>(f : A -> B) -> State<S, B> {
return State<S, B> { s in
let (val, st2) = self.runState(s)
return (f(val), st2)
}
}
}
public func <^> <S, A, B>(f : A -> B, s : State<S, A>) -> State<S, B> {
return s.fmap(f)
}
extension State : Pointed {
public static func pure(x : A) -> State<S, A> {
return State { s in (x, s) }
}
}
extension State : Applicative {
public typealias FAB = State<S, A -> B>
public func ap<B>(stfn : State<S, A -> B>) -> State<S, B> {
return stfn.bind { f in
return self.bind { a in
return State<S, B>.pure(f(a))
}
}
}
}
public func <*> <S, A, B>(f : State<S, A -> B> , s : State<S, A>) -> State<S, B> {
return s.ap(f)
}
extension State : ApplicativeOps {
public typealias C = Any
public typealias FC = State<S, C>
public typealias D = Any
public typealias FD = State<S, D>
public static func liftA<B>(f : A -> B) -> State<S, A> -> State<S, B> {
return { a in State<S, A -> B>.pure(f) <*> a }
}
public static func liftA2<B, C>(f : A -> B -> C) -> State<S, A> -> State<S, B> -> State<S, C> {
return { a in { b in f <^> a <*> b } }
}
public static func liftA3<B, C, D>(f : A -> B -> C -> D) -> State<S, A> -> State<S, B> -> State<S, C> -> State<S, D> {
return { a in { b in { c in f <^> a <*> b <*> c } } }
}
}
extension State : Monad {
public func bind<B>(f : A -> State<S, B>) -> State<S, B> {
return State<S, B> { s in
let (a, s2) = self.runState(s)
return f(a).runState(s2)
}
}
}
public func >>- <S, A, B>(xs : State<S, A>, f : A -> State<S, B>) -> State<S, B> {
return xs.bind(f)
}
extension State : MonadOps {
public static func liftM<B>(f : A -> B) -> State<S, A> -> State<S, B> {
return { m1 in m1 >>- { x1 in State<S, B>.pure(f(x1)) } }
}
public static func liftM2<B, C>(f : A -> B -> C) -> State<S, A> -> State<S, B> -> State<S, C> {
return { m1 in { m2 in m1 >>- { x1 in m2 >>- { x2 in State<S, C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3<B, C, D>(f : A -> B -> C -> D) -> State<S, A> -> State<S, B> -> State<S, C> -> State<S, D> {
return { m1 in { m2 in { m3 in m1 >>- { x1 in m2 >>- { x2 in m3 >>- { x3 in State<S, D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <S, A, B, C>(f : A -> State<S, B>, g : B -> State<S, C>) -> (A -> State<S, C>) {
return { x in f(x) >>- g }
}
public func <<-<< <S, A, B, C>(g : B -> State<S, C>, f : A -> State<S, B>) -> (A -> State<S, C>) {
return f >>->> g
}
|
829e8723e4cd2bbbe08c1d2ca5985e37
| 26.493243 | 121 | 0.557877 | false | false | false | false |
TotalDigital/People-iOS
|
refs/heads/master
|
People at Total/Profile.swift
|
apache-2.0
|
1
|
//
// Profile.swift
// justOne
//
// Created by Florian Letellier on 29/01/2017.
// Copyright © 2017 Florian Letellier. All rights reserved.
//
import Foundation
class Profile: NSObject, NSCoding {
var id: Int = 0
var user: User!
var jobs: [Job] = []
var degree: [Degree] = []
var projects: [Project] = []
var relations: Relation = Relation()
var skills: Skill = Skill()
var langues: Language = Language()
var contact: Contact = Contact()
override init() {
}
init(id: Int, user: User, jobs: [Job],projects: [Project],relations: Relation,skills: Skill,langues: Language,contact: Contact) {
self.id = id
self.user = user
self.jobs = jobs
self.projects = projects
self.relations = relations
self.skills = skills
self.langues = langues
self.contact = contact
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeInteger(forKey: "id")
let user = aDecoder.decodeObject(forKey: "user") as! User
let jobs = aDecoder.decodeObject(forKey: "jobs") as! [Job]
let projects = aDecoder.decodeObject(forKey: "projects") as! [Project]
let relations = aDecoder.decodeObject(forKey: "relations") as! Relation
let skills = aDecoder.decodeObject(forKey: "skills") as! Skill
let langues = aDecoder.decodeObject(forKey: "langues") as! Language
let contact = aDecoder.decodeObject(forKey: "contact") as! Contact
self.init(id: id, user: user, jobs: jobs,projects: projects,relations: relations,skills: skills,langues: langues,contact: contact)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(user, forKey: "user")
aCoder.encode(jobs, forKey: "jobs")
aCoder.encode(projects, forKey: "projects")
aCoder.encode(relations, forKey: "relations")
aCoder.encode(skills, forKey: "skills")
aCoder.encode(langues, forKey: "langues")
aCoder.encode(contact, forKey: "contact")
}
}
|
1ee9ab276b073b601054506dde2c0b44
| 34.216667 | 138 | 0.62991 | false | false | false | false |
iwufan/SocketServerDemo
|
refs/heads/master
|
SocketDemo-Server/SocketDemo/Custom/Extensions/UIButton+Extension.swift
|
mit
|
1
|
//
// UIButton+Extension.swift
// MusicWorld
//
// Created by David Jia on 15/8/2017.
// Copyright © 2017 David Jia. All rights reserved.
//
import UIKit
// MARK: - init method
extension UIButton {
/// quick way to create a button with image and background image
convenience init (normalImage: UIImage? = nil, selectedImage: UIImage? = nil, backgroundImage: UIImage? = nil) {
self.init()
setImage(normalImage, for: .normal)
setImage(selectedImage, for: .selected)
setBackgroundImage(backgroundImage, for: .normal)
}
/// create a button with title/fontSize/TitleColor/bgColor
convenience init (title: String, fontSize: CGFloat, titleColor: UIColor, selTitleColor: UIColor? = nil, bgColor: UIColor = UIColor.clear, isBold: Bool = false) {
self.init()
setTitle(title, for: .normal)
titleLabel?.font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
setTitleColor(titleColor, for: .normal)
setTitleColor(selTitleColor == nil ? titleColor : selTitleColor, for: .selected)
backgroundColor = bgColor
}
}
// MARK: - instance method
extension UIButton {
func setup(title: String, selTitle: String? = nil, fontSize: CGFloat, isBold: Bool = false, titleColor: UIColor, bgColor: UIColor = UIColor.clear, titleOffset: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0)) {
setTitle(title, for: .normal)
setTitle(selTitle == nil ? title : selTitle, for: .selected)
titleLabel?.font = isBold ? UIFont.boldSystemFont(ofSize: fontSize) : UIFont.systemFont(ofSize: fontSize)
setTitleColor(titleColor, for: .normal)
backgroundColor = bgColor
titleEdgeInsets = titleOffset
}
}
|
7453d7b709dd6d7c9cccc6c7168d4224
| 35.979592 | 210 | 0.6617 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
refs/heads/master
|
Swift/LeetCode/Array/492_Construct the Rectangle.swift
|
mit
|
1
|
// 492_Construct the Rectangle
// https://leetcode.com/problems/construct-the-rectangle/
//
// Created by Honghao Zhang on 9/20/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// For a web developer, it is very important to know how to design a web page's size. So, given a specific rectangular web page’s area, your job by now is to design a rectangular web page, whose length L and width W satisfy the following requirements:
//
//1. The area of the rectangular web page you designed must equal to the given target area.
//
//2. The width W should not be larger than the length L, which means L >= W.
//
//3. The difference between length L and width W should be as small as possible.
//You need to output the length L and the width W of the web page you designed in sequence.
//Example:
//
//Input: 4
//Output: [2, 2]
//Explanation: The target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1].
//But according to requirement 2, [1,4] is illegal; according to requirement 3, [4,1] is not optimal compared to [2,2]. So the length L is 2, and the width W is 2.
//Note:
//
//The given area won't exceed 10,000,000 and is a positive integer
//The web page's width and length you designed must be positive integers.
//
import Foundation
class Num492 {
// Easy one
func constructRectangle(_ area: Int) -> [Int] {
guard area > 0 else {
return []
}
var width = Int(sqrt(Double(area)))
while width > 0 {
let height = area / width
if width * height == area {
return [height, width]
}
width -= 1
}
assertionFailure()
return []
}
}
|
87dbdc5288c931769855058f707c8375
| 33.416667 | 251 | 0.677361 | false | false | false | false |
applivery/applivery-ios-sdk
|
refs/heads/master
|
AppliverySDK/Applivery/Coordinators/FeedbackCoordinator.swift
|
mit
|
1
|
//
// FeedbackCoordinator.swift
// AppliverySDK
//
// Created by Alejandro Jiménez on 28/2/16.
// Copyright © 2016 Applivery S.L. All rights reserved.
//
import Foundation
protocol PFeedbackCoordinator {
func showFeedack()
func closeFeedback()
}
class FeedbackCoordinator: PFeedbackCoordinator {
var feedbackVC: FeedbackView!
fileprivate var app: AppProtocol
fileprivate var isFeedbackPresented = false
// MARK: - Initializers
init(app: AppProtocol = App()) {
self.app = app
}
func showFeedack() {
guard !self.isFeedbackPresented else {
logWarn("Feedback view is already presented")
return
}
self.isFeedbackPresented = true
let feedbackVC = FeedbackVC.viewController()
self.feedbackVC = feedbackVC
feedbackVC.presenter = FeedbackPresenter(
view: self.feedbackVC,
feedbackInteractor: Configurator.feedbackInteractor(),
feedbackCoordinator: self,
screenshotInteractor: Configurator.screenshotInteractor()
)
self.app.presentModal(feedbackVC, animated: false)
}
func closeFeedback() {
self.feedbackVC.dismiss(animated: true) {
self.isFeedbackPresented = false
}
}
}
|
11b1723b057b9013468b9aa383143350
| 19.672727 | 60 | 0.740545 | false | false | false | false |
WagnerUmezaki/SwiftCharts
|
refs/heads/master
|
SwiftCharts/DiscreteLineChartView.swift
|
mit
|
1
|
import UIKit
@IBDesignable public class DiscreteLineChartView: UIView {
@IBInspectable public var startColor: UIColor = UIColor.red
@IBInspectable public var endColor: UIColor = UIColor.orange
private var graphPoints:[Int] = []
override public init(frame: CGRect) {
super.init(frame: frame)
}
convenience public init( graphPoints: [Int] ) {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override public func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
//set up background clipping area
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.allCorners,
cornerRadii: CGSize(width: 8.0, height: 8.0))
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor] as CFArray
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradient(colorsSpace: colorSpace,
colors: colors,
locations: colorLocations)
//6 - draw the gradient
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:0, y:self.bounds.height)
context!.drawLinearGradient(gradient!,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions(rawValue: 0))
let margin:CGFloat = 20.0
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
let topBorder:CGFloat = 20
let bottomBorder:CGFloat = 20
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max() ?? 0
let columnYPoint = { (graphPoint:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint) /
CGFloat(maxValue) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
if(graphPoints.count > 0){
// draw the line graph
UIColor.white.setFill()
UIColor.white.setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.move(to: CGPoint(x:columnXPoint(0), y:columnYPoint(graphPoints[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
context!.saveGState()
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLine(to: CGPoint(
x: columnXPoint(graphPoints.count - 1),
y:height))
clippingPath.addLine(to: CGPoint(
x:columnXPoint(0),
y:height))
clippingPath.close()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
context!.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context!.restoreGState()
//draw the line on top of the clipped gradient
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalIn:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.move(to: CGPoint(x:margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin,
y:topBorder))
//center line
linePath.move(to: CGPoint(x:margin,
y: graphHeight/2 + topBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:graphHeight/2 + topBorder))
//bottom line
linePath.move(to: CGPoint(x:margin,
y:height - bottomBorder))
linePath.addLine(to: CGPoint(x:width - margin,
y:height - bottomBorder))
let color = UIColor(white: 1.0, alpha: 0.3)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
public func setChartData(data: [Int]) {
self.graphPoints = data
self.setNeedsDisplay()
}
}
|
3946adde481efe50eadc18d3b02d1f02
| 36.825581 | 132 | 0.516446 | false | false | false | false |
SakuragiTen/DYTV
|
refs/heads/master
|
DYTV/DYTV/Classes/Home/Controllers/HomeViewController.swift
|
mit
|
1
|
//
// HomeViewController.swift
// DYTV
//
// Created by gongsheng on 16/11/13.
// Copyright © 2016年 gongsheng. All rights reserved.
//
import UIKit
import Alamofire
private let kTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
//懒加载属性
fileprivate lazy var pageTieleView : PageTitleView = {[weak self] in
let frame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let titleView = PageTitleView(frame: frame, titles: titles)
// titleView.backgroundColor = UIColor.cyan;
titleView.delegate = self
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
var childVcs = [UIViewController]()
let recommend = RecommendViewController()
recommend.view.backgroundColor = UIColor.cyan
let game = UIViewController()
game.view.backgroundColor = UIColor.red
let amuse = UIViewController()
amuse.view.backgroundColor = UIColor.blue
let funny = UIViewController()
funny.view.backgroundColor = UIColor.purple
childVcs.append(recommend)
childVcs.append(game)
childVcs.append(amuse)
childVcs.append(funny)
let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabBarH
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
// Alamofire.request("http://capi.douyucdn.cn/api/v1/getbigDataRoom", method : .get, parameters: ["time" : Date.getCurrentTime()]).responseJSON { (response) in
// guard let result = response.result.value else {
//
// print("erro : \(response.result.error)")
// return
// }
// print("resulf = \(result) ")
//
// }
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 设置UI界面
extension HomeViewController {
fileprivate func setupUI() {
automaticallyAdjustsScrollViewInsets = false
//设置导航栏
setupNavigationBar()
//添加titleView
view.addSubview(pageTieleView)
//添加contentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.orange
}
fileprivate func setupNavigationBar() {
// navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo", target: self, action: #selector(self.leftItemClicked))
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size, target: self, action: #selector(self.historyItemClicked))
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size, target : self, action : #selector(self.seachItemClicked))
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size, target : self, action : #selector(self.qrcodeItemClicked))
navigationItem.rightBarButtonItems = [historyItem, searchItem, qrcodeItem]
}
@objc func leftItemClicked() {
print("左侧的按钮点击了")
}
@objc private func historyItemClicked() {
print("点击历史记录")
}
@objc func seachItemClicked() {
print("点击搜索")
}
@objc func qrcodeItemClicked() {
print("点击扫描二维码")
}
}
//Mark - 遵守PageTitleViewDelegate
extension HomeViewController : PageTitleViewDelegate {
func pageTitleView(titleView: PageTitleView, selectIndex: Int) {
pageContentView.scrollToIndex(index: selectIndex)
}
}
extension HomeViewController : PageContentViewDelegate {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTieleView.setCurrentTitle(sourceIndex: sourceIndex, targetIndex: targetIndex, progress: progress)
}
}
|
6bba8c1d1ec0d642673716ccf3487799
| 25.772727 | 183 | 0.630306 | false | false | false | false |
voucherifyio/voucherify-ios-sdk
|
refs/heads/master
|
VoucherifySwiftSdk/Classes/Models/Customer.swift
|
mit
|
1
|
import Foundation
import ObjectMapper
public struct Customer: Mappable {
public var id: String?
public var sourceId: String?
public var name: String?
public var email: String?
public var description: String?
public var createdAt: Date?
public var metadata: Dictionary<String, AnyObject>?
public var object: String?
public init(id: String, sourceId: String?) {
self.id = id
self.sourceId = sourceId
}
public init?(map: Map) {
mapping(map: map)
}
mutating public func mapping(map: Map) {
id <- map["id"]
sourceId <- map["source_id"]
name <- map["name"]
email <- map["email"]
description <- map["description"]
createdAt <- (map["created_at"], ISO8601DateTransform())
metadata <- map["metadata"]
object <- map["object"]
}
}
extension Customer: Querable {
func asDictionary() -> Dictionary<String, Any> {
var queryItems: [String: Any] = [:]
queryItems["customer[id]"] = id
queryItems["customer[source_id]"] = sourceId
queryItems["customer[name]"] = name
queryItems["customer[email]"] = email
queryItems["customer[created_at]"] = createdAt
queryItems["customer[object]"] = object
if let metadata = metadata {
for (key, value) in metadata {
queryItems["customer[metadata][\(key)]"] = value
}
}
return queryItems.filter({ !($0.value is NSNull) })
}
}
|
bcbc326218aa6317631c39891db6df0d
| 27.22807 | 66 | 0.554382 | false | false | false | false |
spacedog-io/spacedog-ios-sdk
|
refs/heads/master
|
SpaceDogSDK/SDContext.swift
|
mit
|
1
|
//
// SDContext.swift
// caremen-robot
//
// Created by philippe.rolland on 13/10/2016.
// Copyright © 2016 in-tact. All rights reserved.
//
import Foundation
public class SDContext : CustomStringConvertible {
static let InstanceId = "InstanceId"
static let AccessToken = "AccessToken"
static let CredentialsId = "CredentialsId"
static let CredentialsEmail = "CredentialsEmail"
static let ExpiresIn = "ExpiresIn"
static let IssuedOn = "IssuedOn"
static let DeviceId = "DeviceId"
static let InstallationId = "InstallationId"
let instanceId: String
let appId: String
var deviceId: String?
var installationId: String?
var credentials: SDCredentials?
public init(instanceId: String, appId: String) {
self.instanceId = instanceId
self.appId = appId
}
public func setLogged(with credentials: SDCredentials) -> Void {
self.credentials = credentials
}
public func isLogged() -> Bool {
return self.credentials != nil
}
public func setLoggedOut() -> Void {
self.credentials = nil
}
public var description: String {
return "{instanceId: \(instanceId), credentials: \(credentials?.description ?? "nil"), installationId: \(installationId ?? "nil"), deviceId: \(deviceId ?? "nil")}"
}
}
|
9beac20ef5c87676f34d605e90281237
| 27.208333 | 171 | 0.653619 | false | false | false | false |
dongdongSwift/guoke
|
refs/heads/master
|
gouke/果壳/launchViewController.swift
|
mit
|
1
|
//
// launchViewController.swift
// 果壳
//
// Created by qianfeng on 2016/11/8.
// Copyright © 2016年 张冬. All rights reserved.
//
import UIKit
class launchViewController: UIViewController,NavigationProtocol {
@IBAction func btnClick(btn: UIButton) {
if btn.tag==300{
print("微信登录")
}else if btn.tag==301{
print("微博登录")
}else if btn.tag==302{
print("QQ登录")
}else if btn.tag==303{
print("豆瓣登录")
}else if btn.tag==304{
print("登录")
}else if btn.tag==305{
print("查看用户协议")
}else if btn.tag==306{
print("刷新验证码")
}else if btn.tag==307{
navigationController?.pushViewController(forgetController(), animated: true)
}
}
@IBAction func back(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBOutlet weak var accountTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var verificationCodeTextField: UITextField!
@IBOutlet weak var verificationImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
addTitle("登录")
}
func keyBoardDidReturn(){
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
accountTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
verificationCodeTextField.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
2aa75bfa4880a7dfb4a08d08a9233d3b
| 26.552632 | 106 | 0.622254 | false | false | false | false |
u10int/Kinetic
|
refs/heads/master
|
Pod/Classes/Event.swift
|
mit
|
1
|
//
// Event.swift
// Kinetic
//
// Created by Nicholas Shipes on 11/19/17.
//
import Foundation
public enum EventState<T> {
case active
case closed(T)
}
public final class Event<T> {
public typealias Observer = (T) -> Void
private(set) internal var state = EventState<T>.active
internal var closed: Bool {
if case .active = state {
return false
} else {
return true
}
}
private var observers = [Observer]()
private var keyedObservers = [String: Observer]()
internal func trigger(_ payload: T) {
guard closed == false else { return }
deliver(payload)
}
internal func observe(_ observer: @escaping Observer) {
guard closed == false else {
// observer(T)
return
}
observers.append(observer)
}
internal func observe(_ observer: @escaping Observer, key: String) {
guard closed == false else {
// observer(T)
return
}
keyedObservers[key] = observer
}
internal func unobserve(key: String) {
keyedObservers.removeValue(forKey: key)
}
internal func close(_ payload: T) {
guard closed == false else { return }
state = .closed(payload)
deliver(payload)
}
private func deliver(_ payload: T) {
observers.forEach { (observer) in
observer(payload)
}
keyedObservers.forEach { (key, observer) in
observer(payload)
}
}
}
|
0e74b2f6f8f2497996015a635ba5356d
| 17.671429 | 69 | 0.665647 | false | false | false | false |
centrifugal/centrifuge-ios
|
refs/heads/develop
|
Example/CentrifugeiOS/ViewController.swift
|
mit
|
2
|
//
// ViewController.swift
// CentrifugeiOS
//
// Created by German Saprykin on 04/18/2016.
// Copyright (c) 2016 German Saprykin. All rights reserved.
//
import UIKit
import CentrifugeiOS
typealias MessagesCallback = (CentrifugeServerMessage) -> Void
class ViewController: UIViewController, CentrifugeChannelDelegate, CentrifugeClientDelegate {
@IBOutlet weak var nickTextField: UITextField!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
let datasource = TableViewDataSource()
var nickName: String {
get {
if let nick = self.nickTextField.text, nick.count > 0 {
return nick
}else {
return "anonymous"
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = datasource
let timestamp = "\(Int(Date().timeIntervalSince1970))"
let token = Centrifuge.createToken(string: "\(user)\(timestamp)", key: secret)
let creds = CentrifugeCredentials(token: token, user: user, timestamp: timestamp)
let url = "wss://centrifugo.herokuapp.com/connection/websocket"
client = Centrifuge.client(url: url, creds: creds, delegate: self)
}
//MARK:- Interactions with server
var client: CentrifugeClient!
let channel = "jsfiddle-chat"
let user = "ios-swift"
let secret = "secret"
func publish(_ text: String) {
client.publish(toChannel: channel, data: ["nick" : nickName, "input" : text]) { message, error in
print("publish message: \(String(describing: message))")
}
}
//MARK: CentrifugeClientDelegate
func client(_ client: CentrifugeClient, didDisconnectWithError error: Error) {
showError(error)
}
func client(_ client: CentrifugeClient, didReceiveRefreshMessage message: CentrifugeServerMessage) {
print("didReceiveRefresh message: \(message)")
}
//MARK: CentrifugeChannelDelegate
func client(_ client: CentrifugeClient, didReceiveMessageInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let input = data["input"] as? String, let nick = data["nick"] as? String {
addItem(nick, subtitle: input)
}
}
func client(_ client: CentrifugeClient, didReceiveJoinInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let user = data["user"] as? String {
addItem(message.method.rawValue, subtitle: user)
}
}
func client(_ client: CentrifugeClient, didReceiveLeaveInChannel channel: String, message: CentrifugeServerMessage) {
if let data = message.body?["data"] as? [String : AnyObject], let user = data["user"] as? String {
addItem(message.method.rawValue, subtitle: user)
}
}
func client(_ client: CentrifugeClient, didReceiveUnsubscribeInChannel channel: String, message: CentrifugeServerMessage) {
print("didReceiveUnsubscribeInChannel \(message)" )
}
//MARK: Presentation
func addItem(_ title: String, subtitle: String) {
self.datasource.addItem(TableViewItem(title: title, subtitle: subtitle))
self.tableView.reloadData()
}
func showAlert(_ title: String, message: String) {
let vc = UIAlertController(title: title, message: message, preferredStyle: .alert)
let close = UIAlertAction(title: "Close", style: .cancel) { _ in
vc.dismiss(animated: true, completion: nil)
}
vc.addAction(close)
show(vc, sender: self)
}
func showError(_ error: Any) {
showAlert("Error", message: "\(error)")
}
func showMessage(_ message: CentrifugeServerMessage) {
showAlert("Message", message: "\(message)")
}
func showResponse(_ message: CentrifugeServerMessage?, error: Error?) {
if let msg = message {
showMessage(msg)
} else if let err = error {
showError(err)
}
}
//MARK:- Interactions with user
@IBAction func sendButtonDidPress(_ sender: AnyObject) {
if let text = messageTextField.text, text.count > 0 {
messageTextField.text = ""
publish(text)
}
}
@IBAction func actionButtonDidPress() {
let alert = UIAlertController(title: "Choose command", message: nil, preferredStyle: .actionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .cancel) { _ in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(cancel)
let connect = UIAlertAction(title: "Connect", style: .default) { _ in
self.client.connect(withCompletion: self.showResponse)
}
alert.addAction(connect)
let disconnect = UIAlertAction(title: "Disconnect", style: .default) { _ in
self.client.disconnect()
}
alert.addAction(disconnect)
let ping = UIAlertAction(title: "Ping", style: .default) { _ in
self.client.ping(withCompletion: self.showResponse)
}
alert.addAction(ping)
let subscribe = UIAlertAction(title: "Subscribe to \(channel)", style: .default) { _ in
self.client.subscribe(toChannel: self.channel, delegate: self, completion: self.showResponse)
}
alert.addAction(subscribe)
let unsubscribe = UIAlertAction(title: "Unsubscribe from \(channel)", style: .default) { _ in
self.client.unsubscribe(fromChannel: self.channel, completion: self.showResponse)
}
alert.addAction(unsubscribe)
let history = UIAlertAction(title: "History \(channel)", style: .default) { _ in
self.client.history(ofChannel: self.channel, completion: self.showResponse)
}
alert.addAction(history)
let presence = UIAlertAction(title: "Presence \(channel)", style: .default) { _ in
self.client.presence(inChannel: self.channel, completion:self.showResponse)
}
alert.addAction(presence)
present(alert, animated: true, completion: nil)
}
}
|
59baeabbfc1f23ffbffb26efc7ebd2a2
| 34.788889 | 144 | 0.62108 | false | false | false | false |
SanctionCo/pilot-ios
|
refs/heads/master
|
Pods/Gallery/Sources/Utils/VideoEditor/AdvancedVideoEditor.swift
|
mit
|
1
|
import Foundation
import AVFoundation
import Photos
public class AdvancedVideoEditor: VideoEditing {
var writer: AVAssetWriter!
var videoInput: AVAssetWriterInput?
var audioInput: AVAssetWriterInput?
var reader: AVAssetReader!
var videoOutput: AVAssetReaderVideoCompositionOutput?
var audioOutput: AVAssetReaderAudioMixOutput?
var audioCompleted: Bool = false
var videoCompleted: Bool = false
let requestQueue = DispatchQueue(label: "no.hyper.Gallery.AdvancedVideoEditor.RequestQueue", qos: .background)
let finishQueue = DispatchQueue(label: "no.hyper.Gallery.AdvancedVideoEditor.FinishQueue", qos: .background)
// MARK: - Initialization
public init() {
}
// MARK: - Edit
public func edit(video: Video, completion: @escaping (_ video: Video?, _ tempPath: URL?) -> Void) {
process(video: video, completion: completion)
}
public func crop(avAsset: AVAsset, completion: @escaping (URL?) -> Void) {
guard let outputURL = EditInfo.outputURL else {
completion(nil)
return
}
guard let writer = try? AVAssetWriter(outputURL: outputURL as URL, fileType: EditInfo.file.type),
let reader = try? AVAssetReader(asset: avAsset)
else {
completion(nil)
return
}
// Config
writer.shouldOptimizeForNetworkUse = true
self.writer = writer
self.reader = reader
wire(avAsset)
// Start
writer.startWriting()
reader.startReading()
writer.startSession(atSourceTime: kCMTimeZero)
// Video
if let videoOutput = videoOutput, let videoInput = videoInput {
videoInput.requestMediaDataWhenReady(on: requestQueue) {
if !self.stream(from: videoOutput, to: videoInput) {
self.finishQueue.async {
self.videoCompleted = true
if self.audioCompleted {
self.finish(outputURL: outputURL, completion: completion)
}
}
}
}
}
// Audio
if let audioOutput = audioOutput, let audioInput = audioInput {
audioInput.requestMediaDataWhenReady(on: requestQueue) {
if !self.stream(from: audioOutput, to: audioInput) {
self.finishQueue.async {
self.audioCompleted = true
if self.videoCompleted {
self.finish(outputURL: outputURL, completion: completion)
}
}
}
}
}
}
// MARK: - Finish
fileprivate func finish(outputURL: URL, completion: @escaping (URL?) -> Void) {
if reader.status == .failed {
writer.cancelWriting()
}
guard reader.status != .cancelled
&& reader.status != .failed
&& writer.status != .cancelled
&& writer.status != .failed
else {
completion(nil)
return
}
writer.finishWriting {
switch self.writer.status {
case .completed:
completion(outputURL)
default:
completion(nil)
}
}
}
// MARK: - Helper
fileprivate func wire(_ avAsset: AVAsset) {
wireVideo(avAsset)
wireAudio(avAsset)
}
fileprivate func wireVideo(_ avAsset: AVAsset) {
let videoTracks = avAsset.tracks(withMediaType: AVMediaType.video)
if !videoTracks.isEmpty {
// Output
let videoOutput = AVAssetReaderVideoCompositionOutput(videoTracks: videoTracks, videoSettings: nil)
videoOutput.videoComposition = EditInfo.composition(avAsset)
if reader.canAdd(videoOutput) {
reader.add(videoOutput)
}
// Input
let videoInput = AVAssetWriterInput(mediaType: AVMediaType.video,
outputSettings: EditInfo.videoSettings,
sourceFormatHint: avAsset.g_videoDescription)
if writer.canAdd(videoInput) {
writer.add(videoInput)
}
self.videoInput = videoInput
self.videoOutput = videoOutput
}
}
fileprivate func wireAudio(_ avAsset: AVAsset) {
let audioTracks = avAsset.tracks(withMediaType: AVMediaType.audio)
if !audioTracks.isEmpty {
// Output
let audioOutput = AVAssetReaderAudioMixOutput(audioTracks: audioTracks, audioSettings: nil)
audioOutput.alwaysCopiesSampleData = true
if reader.canAdd(audioOutput) {
reader.add(audioOutput)
}
// Input
let audioInput = AVAssetWriterInput(mediaType: AVMediaType.audio,
outputSettings: EditInfo.audioSettings,
sourceFormatHint: avAsset.g_audioDescription)
if writer.canAdd(audioInput) {
writer.add(audioInput)
}
self.audioOutput = audioOutput
self.audioInput = audioInput
}
}
fileprivate func stream(from output: AVAssetReaderOutput, to input: AVAssetWriterInput) -> Bool {
while input.isReadyForMoreMediaData {
guard reader.status == .reading && writer.status == .writing,
let buffer = output.copyNextSampleBuffer()
else {
input.markAsFinished()
return false
}
return input.append(buffer)
}
return true
}
}
|
2976aa7b5deacfae6284b2d15722e680
| 27.088398 | 112 | 0.641031 | false | false | false | false |
grandiere/box
|
refs/heads/master
|
box/View/GridVisor/VGridVisorMenuButton.swift
|
mit
|
1
|
import UIKit
class VGridVisorMenuButton:UIButton
{
private let kAlphaNotSelected:CGFloat = 1
private let kAlphaSelected:CGFloat = 0.3
private let kAnimationDuration:TimeInterval = 0.5
init(image:UIImage)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
translatesAutoresizingMaskIntoConstraints = false
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.normal)
setImage(
image.withRenderingMode(UIImageRenderingMode.alwaysOriginal),
for:UIControlState.highlighted)
imageView!.clipsToBounds = true
imageView!.contentMode = UIViewContentMode.center
alpha = 0
}
required init?(coder:NSCoder)
{
return nil
}
override var isSelected:Bool
{
didSet
{
hover()
}
}
override var isHighlighted:Bool
{
didSet
{
hover()
}
}
//MARK: private
private func hover()
{
if isSelected || isHighlighted
{
alpha = kAlphaSelected
}
else
{
alpha = kAlphaNotSelected
}
}
//MARK: public
func animate(show:Bool)
{
let alpha:CGFloat
if show
{
alpha = 1
isUserInteractionEnabled = true
}
else
{
alpha = 0
isUserInteractionEnabled = false
}
UIView.animate(withDuration:kAnimationDuration)
{ [weak self] in
self?.alpha = alpha
}
}
}
|
b938bcac37709c060fe7c100a5b8d575
| 19.650602 | 73 | 0.528588 | false | false | false | false |
tutao/tutanota
|
refs/heads/master
|
app-ios/tutanota/Sources/Remote/IosCommonSystemFacade.swift
|
gpl-3.0
|
1
|
import Foundation
import Combine
enum InitState {
case waitingForInit
case initReceived
}
class IosCommonSystemFacade: CommonSystemFacade {
private let viewController: ViewController
private var initialized = CurrentValueSubject<InitState, Never>(.waitingForInit)
init(viewController: ViewController) {
self.viewController = viewController
}
func initializeRemoteBridge() async throws {
self.initialized.send(.initReceived)
}
func reload(_ query: [String : String]) async throws {
self.initialized = CurrentValueSubject(.waitingForInit)
await self.viewController.loadMainPage(params: query)
}
func getLog() async throws -> String {
let entries = TUTLogger.sharedInstance().entries()
return entries.joined(separator: "\n")
}
func awaitForInit() async {
/// awaiting for the first and hopefully only void object in this publisher
/// could be simpler but .values is iOS > 15
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
// first will end the subscription after the first match so we don't need to cancel manually
// (it is anyway hard to do as .sink() is called sync right away before we get subscription)
let _ = self.initialized
.first(where: { $0 == .initReceived })
.sink { v in
continuation.resume()
}
}
}
}
|
a1b3e977b2fea2fba2fd782aba48a22f
| 29.866667 | 98 | 0.701224 | false | false | false | false |
KennethTsang/GrowingTextView
|
refs/heads/master
|
Example/GrowingTextView/Example2.swift
|
mit
|
1
|
//
// Example2.swift
// GrowingTextView
//
// Created by Tsang Kenneth on 16/3/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import GrowingTextView
class Example2: UIViewController {
@IBOutlet weak var inputToolbar: UIView!
@IBOutlet weak var textView: GrowingTextView!
@IBOutlet weak var textViewBottomConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// *** Customize GrowingTextView ***
textView.layer.cornerRadius = 4.0
// *** Listen to keyboard show / hide ***
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
// *** Hide keyboard when tapping outside ***
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler))
view.addGestureRecognizer(tapGesture)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
if let endFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
var keyboardHeight = UIScreen.main.bounds.height - endFrame.origin.y
if #available(iOS 11, *) {
if keyboardHeight > 0 {
keyboardHeight = keyboardHeight - view.safeAreaInsets.bottom
}
}
textViewBottomConstraint.constant = keyboardHeight + 8
view.layoutIfNeeded()
}
}
@objc func tapGestureHandler() {
view.endEditing(true)
}
}
extension Example2: GrowingTextViewDelegate {
// *** Call layoutIfNeeded on superview for animation when changing height ***
func textViewDidChangeHeight(_ textView: GrowingTextView, height: CGFloat) {
UIView.animate(withDuration: 0.3, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: [.curveLinear], animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: nil)
}
}
|
be3974f3429217154b0baa03459eceff
| 33.460317 | 166 | 0.663749 | false | false | false | false |
youngsoft/TangramKit
|
refs/heads/master
|
TangramKitDemo/IntegratedDemo/AllTestModel&View/AllTest1TableViewCell.swift
|
mit
|
1
|
//
// AllTest1TableViewCell.swift
// TangramKit
//
// Created by apple on 16/8/23.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
protocol AllTest1Cell {
var rootLayout:TGBaseLayout!{get}
func setModel(model: AllTest1DataModel, isImageMessageHidden: Bool)
}
class AllTest1TableViewCell: UITableViewCell,AllTest1Cell {
//对于需要动态评估高度的UITableViewCell来说可以把布局视图暴露出来。用于高度评估和边界线处理。以及事件处理的设置。
fileprivate(set) var rootLayout:TGBaseLayout!
weak var headImageView:UIImageView!
weak var nickNameLabel:UILabel!
weak var textMessageLabel:UILabel!
weak var imageMessageImageView:UIImageView!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
/**
* 您可以尝试用不同的布局来实现相同的功能。
*/
self.createLinearRootLayout()
// self.createRelativeRootLayout()
// self.createFloatRootLayout()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
//iOS8以后您可以重载这个方法来动态的评估cell的高度,Autolayout内部是通过这个方法来评估高度的,因此如果用TangramKit实现的话就不需要调用基类的方法,而是调用根布局视图的sizeThatFits来评估获取动态的高度。
override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize
{
/*
通过布局视图的sizeThatFits方法能够评估出UITableViewCell的动态高度。sizeThatFits并不会进行布局而只是评估布局的尺寸。
因为cell的高度是自适应的,因此这里通过调用高度为wrap的布局视图的sizeThatFits来获取真实的高度。
*/
if #available(iOS 11.0, *) {
//如果你的界面要支持横屏的话,因为iPhoneX的横屏左右有44的安全区域,所以这里要减去左右的安全区域的值,来作为布局宽度尺寸的评估值。
//如果您的界面不需要支持横屏,或者延伸到安全区域外则不需要做这个特殊处理,而直接使用else部分的代码即可。
return self.rootLayout.sizeThatFits(CGSize(width:targetSize.width - self.safeAreaInsets.left - self.safeAreaInsets.right, height:targetSize.height))
} else {
// Fallback on earlier versions
return self.rootLayout.sizeThatFits(targetSize) //如果使用系统自带的分割线,请记得将返回的高度height+1
}
}
func setModel(model: AllTest1DataModel, isImageMessageHidden: Bool)
{
self.headImageView.image = UIImage(named: model.headImage)
self.headImageView.sizeToFit()
self.nickNameLabel.text = model.nickName
self.nickNameLabel.sizeToFit()
self.textMessageLabel.text = model.textMessage
if model.imageMessage.isEmpty
{
self.imageMessageImageView.tg_visibility = .gone
}
else
{
self.imageMessageImageView.image = UIImage(named: model.imageMessage)
self.imageMessageImageView.sizeToFit()
if isImageMessageHidden
{
self.imageMessageImageView.tg_visibility = .gone
}
else
{
self.imageMessageImageView.tg_visibility = .visible
}
}
}
}
//MARK: Layout Construction
extension AllTest1TableViewCell
{
//用线性布局来实现UI界面
func createLinearRootLayout()
{
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGLinearLayout(.horz)
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
//如果您将布局视图作为子视图添加到UITableViewCell本身,并且同时设置了布局视图的宽度等于父布局的情况下,那么有可能最终展示的宽度会不正确。经过试验是因为对UITableViewCell本身的KVO监控所得到的新老尺寸的问题导致的这应该是iOS的一个BUG。所以这里建议最好是把布局视图添加到UITableViewCell的子视图contentView里面去。
/*
用线性布局实现时,整体用一个水平线性布局:左边是头像,右边是一个垂直的线性布局。垂直线性布局依次加入昵称、文本消息、图片消息。
*/
let headImageView = UIImageView()
self.rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let messageLayout = TGLinearLayout(.vert)
messageLayout.tg_width.equal(.fill) //等价于tg_width.equal(100%)
messageLayout.tg_height.equal(.wrap)
messageLayout.tg_leading.equal(5)
messageLayout.tg_vspace = 5 //前面4行代码描述的是垂直布局占用除头像外的所有宽度,并和头像保持5个点的间距。
self.rootLayout.addSubview(messageLayout)
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
messageLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_width.equal(.fill)
textMessageLabel.tg_height.equal(.wrap) //高度为包裹,也就是动态高度。
messageLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_centerX.equal(0) //图片视图在父布局视图中水平居中。
messageLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
//用相对布局来实现UI界面
func createRelativeRootLayout() {
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGRelativeLayout()
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
/*
用相对布局实现时,左边是头像视图,昵称文本在头像视图的右边,文本消息在昵称文本的下面,图片消息在文本消息的下面。
*/
let headImageView = UIImageView()
rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
nickNameLabel.tg_leading.equal(self.headImageView.tg_trailing, offset:5) //昵称文本的左边在头像视图的右边并偏移5个点。
rootLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
//昵称文本的左边在头像视图的右边并偏移5个点。
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_leading.equal(self.headImageView.tg_trailing, offset:5) //文本消息的左边在头像视图的右边并偏移5个点。
textMessageLabel.tg_trailing.equal(rootLayout.tg_trailing) //文本消息的右边和父布局的右边对齐。上面2行代码也同时确定了文本消息的宽度。
textMessageLabel.tg_top.equal(self.nickNameLabel.tg_bottom,offset:5) //文本消息的顶部在昵称文本的底部并偏移5个点
textMessageLabel.tg_height.equal(.wrap)
rootLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_centerX.equal(5) //图片消息的水平中心点等于父布局的水平中心点并偏移5个点的位置,这里要偏移5的原因是头像和消息之间需要5个点的间距。
imageMessageImageView.tg_top.equal(self.textMessageLabel.tg_bottom, offset:5) //图片消息的顶部在文本消息的底部并偏移5个点。
rootLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
//用浮动布局来实现UI界面
func createFloatRootLayout()
{
/*
在UITableViewCell中使用TGLayout中的布局时请将布局视图作为contentView的子视图。如果我们的UITableViewCell的高度是动态的,请务必在将布局视图添加到contentView之前进行如下设置:
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
*/
self.rootLayout = TGFloatLayout(.vert)
self.rootLayout.tg_topPadding = 5
self.rootLayout.tg_bottomPadding = 5
self.rootLayout.tg_width.equal(.fill)
self.rootLayout.tg_height.equal(.wrap)
self.rootLayout.tg_cacheEstimatedRect = true //这个属性只局限于在UITableViewCell中使用,用来优化tableviewcell的高度自适应的性能,其他地方请不要使用!!!
self.contentView.addSubview(self.rootLayout)
/*
用浮动布局实现时,头像视图浮动到最左边,昵称文本跟在头像视图后面并占用剩余宽度,文本消息也跟在头像视图后面并占用剩余宽度,图片消息不浮动占据所有宽度。
要想了解浮动布局的原理,请参考文章:http://www.jianshu.com/p/0c075f2fdab2 中的介绍。
*/
let headImageView = UIImageView()
headImageView.tg_trailing.equal(5) //右边保留出5个点的视图间距。
rootLayout.addSubview(headImageView)
self.headImageView = headImageView
let nickNameLabel = UILabel()
nickNameLabel.textColor = CFTool.color(3)
nickNameLabel.font = CFTool.font(17)
nickNameLabel.tg_bottom.equal(5) //下边保留出5个点的视图间距。
nickNameLabel.tg_width.equal(.fill) //占用剩余宽度。
rootLayout.addSubview(nickNameLabel)
self.nickNameLabel = nickNameLabel
let textMessageLabel = UILabel()
textMessageLabel.font = CFTool.font(15)
textMessageLabel.textColor = CFTool.color(4)
textMessageLabel.tg_width.equal(.fill) //占用剩余宽度。
textMessageLabel.tg_height.equal(.wrap) //高度包裹
rootLayout.addSubview(textMessageLabel)
self.textMessageLabel = textMessageLabel
let imageMessageImageView = UIImageView()
imageMessageImageView.tg_top.equal(5)
imageMessageImageView.tg_reverseFloat = true //反向浮动
imageMessageImageView.tg_width.equal(.fill) //占用剩余空间
imageMessageImageView.contentMode = .center
rootLayout.addSubview(imageMessageImageView)
self.imageMessageImageView = imageMessageImageView
}
}
|
50e373b2e7ab6a721d584a48cccddba6
| 37.59176 | 195 | 0.683424 | false | false | false | false |
linhaosunny/smallGifts
|
refs/heads/master
|
小礼品/小礼品/Classes/Module/Me/Chat/ChatBar/KeyBoard/Emoji/EmojiGroupControlCell.swift
|
mit
|
1
|
//
// EmojiGroupControlCell.swift
// 小礼品
//
// Created by 李莎鑫 on 2017/5/12.
// Copyright © 2017年 李莎鑫. All rights reserved.
//
import UIKit
import SnapKit
class EmojiGroupControlCell: UICollectionViewCell {
//MARK: 属性
var viewModel:EmojiGroupControlCellViewModel? {
didSet{
backView.image = viewModel?.backViewImage
imageView.image = viewModel?.imageViewImage
isbackViewHide = viewModel!.backViewHide
leftLine.backgroundColor = viewModel?.lineColor
rightLine.backgroundColor = viewModel?.lineColor
backView.isHidden = isbackViewHide
}
}
var isbackViewHide:Bool = false {
didSet{
backView.isHidden = isbackViewHide
}
}
//MARK: 懒加载
var backView:UIImageView = { () -> UIImageView in
let view = UIImageView()
view.contentMode = .scaleAspectFill
return view
}()
var imageView:UIImageView = { () -> UIImageView in
let view = UIImageView()
return view
}()
var leftLine:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.lightGray
return view
}()
var rightLine:UIView = { () -> UIView in
let view = UIView()
view.backgroundColor = UIColor.lightGray
return view
}()
//MARK: 构造方法
override init(frame: CGRect) {
super.init(frame: frame)
setupEmojiGroupControlCell()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
setupEmojiGroupControlCellSubView()
}
//MARK: 私有方法
private func setupEmojiGroupControlCell() {
addSubview(backView)
addSubview(imageView)
addSubview(leftLine)
addSubview(rightLine)
}
private func setupEmojiGroupControlCellSubView() {
backView.snp.makeConstraints { (make) in
make.top.bottom.equalToSuperview()
make.left.equalTo(leftLine.snp.right)
make.right.equalTo(rightLine.snp.left)
}
leftLine.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.width.equalTo(margin*0.1)
make.top.equalToSuperview().offset(margin*0.3)
make.bottom.equalToSuperview().offset(-margin*0.3)
}
imageView.snp.makeConstraints { (make) in
make.left.equalTo(leftLine.snp.right)
make.top.bottom.equalTo(leftLine)
make.right.equalTo(rightLine.snp.left)
}
rightLine.snp.makeConstraints { (make) in
make.top.bottom.width.equalTo(leftLine)
make.right.equalToSuperview()
}
}
}
|
f47927ae507e624c15a527e0eadd603d
| 26.708738 | 62 | 0.597758 | false | false | false | false |
WalterCreazyBear/Swifter30
|
refs/heads/master
|
ArtList/ArtList/WorksViewController.swift
|
mit
|
1
|
//
// WorksViewController.swift
// ArtList
//
// Created by Bear on 2017/6/26.
// Copyright © 2017年 Bear. All rights reserved.
//
import UIKit
class WorksViewController: UIViewController {
var model:Artist!
let cellID = "CELLID"
lazy var table:UITableView = {
let table = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height))
table.backgroundColor = UIColor.white
table.delegate = self
table.dataSource = self
table.register(WorkDetailTableViewCell.self, forCellReuseIdentifier: self.cellID)
return table
}()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(model:Artist) {
self.model = model
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
title = model.name
view.backgroundColor = UIColor.white
self.view.addSubview(self.table)
}
}
extension WorksViewController:UITableViewDelegate,UITableViewDataSource
{
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.model.works.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath)
let work = model.works[indexPath.row]
cell.selectionStyle = .none
if cell.isKind(of: WorkDetailTableViewCell.self)
{
(cell as! WorkDetailTableViewCell).bindData(model: work)
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let work = model.works[indexPath.row]
if work.isExpanded
{
return 380
}
else{
return 250
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var work = model.works[indexPath.row]
work.isExpanded = !work.isExpanded
model.works[indexPath.row] = work
(tableView.cellForRow(at: indexPath) as! WorkDetailTableViewCell).bindData(model: work)
tableView.beginUpdates()
tableView.endUpdates()
// tableView.reloadData()
tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}
}
|
116ee8e36f9d317b2c87179031f71674
| 28.181818 | 140 | 0.636682 | false | false | false | false |
daniel-barros/TV-Calendar
|
refs/heads/master
|
TV Calendar/TrackingLimitGuard.swift
|
gpl-3.0
|
1
|
//
// TrackingLimitGuard.swift
// TV Calendar
//
// Created by Daniel Barros López on 3/14/17.
// Copyright © 2017 Daniel Barros. All rights reserved.
//
import ExtendedFoundation
import RealmSwift
fileprivate let userTrackingLimitKey = "userTrackingLimitKey"
/// Knows about limits on the number of shows the user can track and how to remove them via in-app purchases.
/// There's a common limit and a user-specific limit which will be used instead for users who exceeded the limit before it was applied on previous app versions.
struct TrackingLimitGuard {
init(trackedShows: Results<Show>, iapManager: InAppPurchaseManager = .shared) {
self.trackedShows = trackedShows
self.iapManager = iapManager
setUserTrackingLimit()
}
fileprivate let trackedShows: Results<Show>
fileprivate let iapManager: InAppPurchaseManager
/// True unless the corresponding in-app purchase has being acquired.
var hasTrackingLimit: Bool {
return !iapManager.isProductPurchased(InAppPurchaseManager.ProductIdentifiers.unlockUnlimitedTracking)
}
/// The maximum number of shows a user is allowed to track if the tracking limit applies.
static var trackingLimit: Int {
return userTrackingLimit ?? commonTrackingLimit
}
/// `true` if user has a tracking limit and it has being reached.
var hasReachedTrackingLimit: Bool {
return hasTrackingLimit && trackedShows.count >= TrackingLimitGuard.trackingLimit
}
func buyTrackingLimitRemoval(firstTry: Bool = true, completion: @escaping (BooleanResult<InAppPurchaseManager.IAPError>) -> ()) {
// Get iap product
guard let product = iapManager.unlockUnlimitedTrackingProduct else {
if firstTry {
// Retrieve products and try again
iapManager.findProducts(completion: { result in
self.buyTrackingLimitRemoval(firstTry: false, completion: completion)
})
} else {
completion(.failure(.productUnavailable))
}
return
}
// Purchase it
iapManager.purchase(product, completion: completion)
}
func restoreTrackingLimitRemoval(completion: @escaping (BooleanResult<InAppPurchaseManager.IAPError>) -> ()) {
iapManager.restorePurchases(completion: completion)
}
static var priceForRemovingTrackingLimit: (Double, Locale)? {
if let product = InAppPurchaseManager.shared.unlockUnlimitedTrackingProduct {
return (product.price.doubleValue, product.priceLocale)
}
return nil
}
static fileprivate let commonTrackingLimit = 6
static fileprivate(set) var userTrackingLimit: Int? {
get { return nil }
set { }
// get { return UserDefaults.standard.value(forKey: userTrackingLimitKey) as? Int }
// set { return UserDefaults.standard.set(newValue, forKey: userTrackingLimitKey) }
}
}
// MARK: Helpers
fileprivate extension TrackingLimitGuard {
/// Sets the current number of tracked shows as a user-specific tracking limit for early adopters.
mutating func setUserTrackingLimit() {
if trackedShows.count > TrackingLimitGuard.commonTrackingLimit && TrackingLimitGuard.userTrackingLimit == nil {
TrackingLimitGuard.userTrackingLimit = trackedShows.count
}
}
}
|
ac9c9ea8b85cae04c0c47ef82482349b
| 37.588889 | 160 | 0.68068 | false | false | false | false |
tavultesoft/keymanweb
|
refs/heads/master
|
ios/tools/KeyboardCalibrator/KeyboardCalibrator/DummyInputViewController.swift
|
apache-2.0
|
1
|
//
// DummyInputViewController.swift
// DefaultKeyboardHost
//
// Created by Joshua Horton on 1/13/20.
// Copyright © 2020 SIL International. All rights reserved.
//
import Foundation
import UIKit
private class CustomInputView: UIInputView {
var height: CGFloat
var inset: CGFloat
var innerView: UIView!
var insetView: UIView!
var heightLabel: UILabel!
var insetHeightLabel: UILabel!
init(height: CGFloat, inset: CGFloat) {
self.height = height
self.inset = inset
super.init(frame: CGRect.zero, inputViewStyle: .keyboard)
}
override var intrinsicContentSize: CGSize {
get {
return CGSize(width: UIScreen.main.bounds.width, height: height > 0 ? height + inset : 100)
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setConstraints() {
var guide: UILayoutGuide
if #available(iOS 11.0, *) {
guide = self.safeAreaLayoutGuide
} else {
guide = self.layoutMarginsGuide
}
if height != 0 {
innerView.heightAnchor.constraint(equalToConstant: height).isActive = true
} else {
innerView.heightAnchor.constraint(equalTo: guide.heightAnchor).isActive = true
}
if #available(iOS 11.0, *) {
innerView.widthAnchor.constraint(equalTo: guide.widthAnchor).isActive = true
innerView.leftAnchor.constraint(equalTo: guide.leftAnchor).isActive = true
insetView.widthAnchor.constraint(equalTo: guide.widthAnchor).isActive = true
} else {
innerView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
innerView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
insetView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
}
innerView.bottomAnchor.constraint(equalTo: insetView.topAnchor).isActive = true
insetView.heightAnchor.constraint(equalToConstant: inset).isActive = true
insetView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
}
func load() {
innerView = UIView()
innerView.backgroundColor = .red
innerView.translatesAutoresizingMaskIntoConstraints = false
heightLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
heightLabel.text = "Hello World"
innerView.addSubview(heightLabel)
self.addSubview(innerView)
insetView = UIView()
insetView.backgroundColor = .green
insetView.translatesAutoresizingMaskIntoConstraints = false
insetHeightLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 21))
insetHeightLabel.text = "(0.0, \(inset))"
insetView.addSubview(insetHeightLabel)
self.addSubview(insetView)
}
override func layoutSubviews() {
super.layoutSubviews()
if innerView.bounds.size != CGSize.zero {
heightLabel.text = "\(innerView.bounds.size)"
} else {
heightLabel.text = "\(intrinsicContentSize)"
}
}
}
class DummyInputViewController: UIInputViewController {
var kbdHeight: CGFloat
var insetHeight: CGFloat
// The app group used to access common UserDefaults settings.
static let appGroup = "group.horton.kmtesting"
static var keyboardHeightDefault: CGFloat {
get {
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
return (userDefaults.object(forKey: "height") as? CGFloat) ?? 0
}
set(value) {
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
userDefaults.set(value, forKey: "height")
}
}
@IBOutlet var nextKeyboardButton: UIButton!
var asSystemKeyboard: Bool = false
// This is the one used to initialize the keyboard as the app extension, marking "system keyboard" mode.
convenience init() {
// Retrieve kbd height from app group!
let userDefaults = UserDefaults(suiteName: DummyInputViewController.appGroup)!
let height = userDefaults.float(forKey: "height")
self.init(height: CGFloat(height))
asSystemKeyboard = true
}
init(height: CGFloat, inset: CGFloat = 0) {
kbdHeight = height
insetHeight = inset
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func loadView() {
let baseView = CustomInputView(height: kbdHeight, inset: insetHeight)
baseView.backgroundColor = .blue
baseView.translatesAutoresizingMaskIntoConstraints = false
self.inputView = baseView
}
open override func viewDidLoad() {
let baseView = self.inputView as! CustomInputView
// Perform custom UI setup here
baseView.load()
baseView.setConstraints()
// Adds a very basic "Next keyboard" button to ensure we can always swap keyboards, even on iPhone SE.
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
var guide: UILayoutGuide
if #available(iOS 11.0, *) {
guide = self.view.safeAreaLayoutGuide
self.nextKeyboardButton.isHidden = !self.needsInputModeSwitchKey || !asSystemKeyboard
} else {
guide = self.view.layoutMarginsGuide
self.nextKeyboardButton.isHidden = false // Seems buggy to vary, and it matters greatly on older devices.
}
self.nextKeyboardButton.leftAnchor.constraint(equalTo: guide.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
}
|
ca3dbdf6a1b72cbae4fddfa6a37f92b9
| 29.936842 | 126 | 0.718612 | false | false | false | false |
ontouchstart/swift3-playground
|
refs/heads/playgroundbook
|
Learn to Code 2.playgroundbook/Contents/Chapters/Document9.playgroundchapter/Pages/Exercise1.playgroundpage/Contents.swift
|
mit
|
1
|
//#-hidden-code
//
// Contents.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
//#-end-hidden-code
/*:
**Goal:** Create a [variable](glossary://variable) to track the number of gems collected.
For this puzzle, you’ll need to keep track of how many gems Byte collects. This value should be 0 in the beginning; after Byte picks up the first gem, the value should change to 1.
To [declare](glossary://declaration) (create) a variable, use `var` and give your variable a name. Then use the [assignment operator](glossary://assignment%20operator) (`=`) to set an initial value for the variable.
var myAge = 15
Once a variable has been declared, you may [assign](glossary://assignment) it a new value at any time:
myAge = 16
1. steps: Set the initial value of `gemCounter` to `0`.
2. Move to the gem and pick it up.
3. Set the value of `gemCounter` to `1`.
*/
//#-hidden-code
playgroundPrologue()
//#-end-hidden-code
//#-code-completion(everything, hide)
//#-code-completion(currentmodule, show)
//#-code-completion(identifier, show, isOnOpenSwitch, moveForward(), turnLeft(), turnRight(), collectGem(), toggleSwitch(), isOnGem, isOnClosedSwitch, var, =, isBlocked, true, false, isBlockedLeft, &&, ||, !, isBlockedRight, if, func, for, while)
var gemCounter = /*#-editable-code yourFuncName*/<#T##Set the initial value##Int#>/*#-end-editable-code*/
//#-editable-code Tap to enter code
//#-end-editable-code
//#-hidden-code
finalGemCount = gemCounter
playgroundEpilogue()
//#-end-hidden-code
|
55c8793e5b99fb57eb918d6081cdc26c
| 38.25641 | 246 | 0.708034 | false | false | false | false |
miletliyusuf/VisionDetect
|
refs/heads/master
|
VisionDetect/VisionDetect.swift
|
mit
|
1
|
//
// VisionDetect.swift
// VisionDetect
//
// Created by Yusuf Miletli on 8/21/17.
// Copyright © 2017 Miletli. All rights reserved.
//
import Foundation
import UIKit
import CoreImage
import AVFoundation
import ImageIO
public protocol VisionDetectDelegate: AnyObject {
func didNoFaceDetected()
func didFaceDetected()
func didSmile()
func didNotSmile()
func didBlinked()
func didNotBlinked()
func didWinked()
func didNotWinked()
func didLeftEyeClosed()
func didLeftEyeOpened()
func didRightEyeClosed()
func didRightEyeOpened()
}
///Makes every method is optional
public extension VisionDetectDelegate {
func didNoFaceDetected() { }
func didFaceDetected() { }
func didSmile() { }
func didNotSmile() { }
func didBlinked() { }
func didNotBlinked() { }
func didWinked() { }
func didNotWinked() { }
func didLeftEyeClosed() { }
func didLeftEyeOpened() { }
func didRightEyeClosed() { }
func didRightEyeOpened() { }
}
public enum VisionDetectGestures {
case face
case noFace
case smile
case noSmile
case blink
case noBlink
case wink
case noWink
case leftEyeClosed
case noLeftEyeClosed
case rightEyeClosed
case noRightEyeClosed
}
open class VisionDetect: NSObject {
public weak var delegate: VisionDetectDelegate? = nil
public enum DetectorAccuracy {
case BatterySaving
case HigherPerformance
}
public enum CameraDevice {
case ISightCamera
case FaceTimeCamera
}
public typealias TakenImageStateHandler = ((UIImage) -> Void)
public var onlyFireNotificatonOnStatusChange : Bool = true
public var visageCameraView : UIView = UIView()
//Private properties of the detected face that can be accessed (read-only) by other classes.
private(set) var faceDetected : Bool?
private(set) var faceBounds : CGRect?
private(set) var faceAngle : CGFloat?
private(set) var faceAngleDifference : CGFloat?
private(set) var leftEyePosition : CGPoint?
private(set) var rightEyePosition : CGPoint?
private(set) var mouthPosition : CGPoint?
private(set) var hasSmile : Bool?
private(set) var isBlinking : Bool?
private(set) var isWinking : Bool?
private(set) var leftEyeClosed : Bool?
private(set) var rightEyeClosed : Bool?
//Private variables that cannot be accessed by other classes in any way.
private var faceDetector : CIDetector?
private var videoDataOutput : AVCaptureVideoDataOutput?
private var videoDataOutputQueue : DispatchQueue?
private var cameraPreviewLayer : AVCaptureVideoPreviewLayer?
private var captureSession : AVCaptureSession = AVCaptureSession()
private let notificationCenter : NotificationCenter = NotificationCenter.default
private var currentOrientation : Int?
private let stillImageOutput = AVCapturePhotoOutput()
private var detectedGestures:[VisionDetectGestures] = []
private var takenImageHandler: TakenImageStateHandler?
private var takenImage: UIImage? {
didSet {
if let image = self.takenImage {
takenImageHandler?(image)
}
}
}
public init(cameraPosition: CameraDevice, optimizeFor: DetectorAccuracy) {
super.init()
currentOrientation = convertOrientation(deviceOrientation: UIDevice.current.orientation)
switch cameraPosition {
case .FaceTimeCamera : self.captureSetup(position: AVCaptureDevice.Position.front)
case .ISightCamera : self.captureSetup(position: AVCaptureDevice.Position.back)
}
var faceDetectorOptions : [String : AnyObject]?
switch optimizeFor {
case .BatterySaving : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyLow as AnyObject]
case .HigherPerformance : faceDetectorOptions = [CIDetectorAccuracy : CIDetectorAccuracyHigh as AnyObject]
}
self.faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: faceDetectorOptions)
}
public func addTakenImageChangeHandler(handler: TakenImageStateHandler?) {
self.takenImageHandler = handler
}
//MARK: SETUP OF VIDEOCAPTURE
public func beginFaceDetection() {
self.captureSession.startRunning()
setupSaveToCameraRoll()
}
public func endFaceDetection() {
self.captureSession.stopRunning()
}
private func setupSaveToCameraRoll() {
if captureSession.canAddOutput(stillImageOutput) {
captureSession.addOutput(stillImageOutput)
}
}
public func saveTakenImageToPhotos() {
if let image = self.takenImage {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
public func takeAPicture() {
if self.stillImageOutput.connection(with: .video) != nil {
let settings = AVCapturePhotoSettings()
let previewPixelType = settings.availablePreviewPhotoPixelFormatTypes.first ?? nil
let previewFormat = [String(kCVPixelBufferPixelFormatTypeKey): previewPixelType,
String(kCVPixelBufferWidthKey): 160,
String(kCVPixelBufferHeightKey): 160]
settings.previewPhotoFormat = previewFormat as [String : Any]
self.stillImageOutput.capturePhoto(with: settings, delegate: self)
}
}
private func captureSetup(position: AVCaptureDevice.Position) {
var captureError: NSError?
var captureDevice: AVCaptureDevice?
let devices = AVCaptureDevice.DiscoverySession(
deviceTypes: [.builtInWideAngleCamera],
mediaType: .video,
position: position
).devices
for testedDevice in devices {
if ((testedDevice as AnyObject).position == position) {
captureDevice = testedDevice
}
}
if (captureDevice == nil) {
captureDevice = AVCaptureDevice.default(for: .video)
}
var deviceInput : AVCaptureDeviceInput?
do {
if let device = captureDevice {
deviceInput = try AVCaptureDeviceInput(device: device)
}
} catch let error as NSError {
captureError = error
deviceInput = nil
}
captureSession.sessionPreset = .high
if (captureError == nil) {
if let input = deviceInput,
captureSession.canAddInput(input) {
captureSession.addInput(input)
}
self.videoDataOutput = AVCaptureVideoDataOutput()
self.videoDataOutput?.videoSettings = [
String(kCVPixelBufferPixelFormatTypeKey): Int(kCVPixelFormatType_32BGRA)
]
self.videoDataOutput?.alwaysDiscardsLateVideoFrames = true
self.videoDataOutputQueue = DispatchQueue(label: "VideoDataOutputQueue")
self.videoDataOutput?.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue)
if let output = self.videoDataOutput,
captureSession.canAddOutput(output) {
captureSession.addOutput(output)
}
}
visageCameraView.frame = UIScreen.main.bounds
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer.frame = UIScreen.main.bounds
previewLayer.videoGravity = .resizeAspectFill
visageCameraView.layer.addSublayer(previewLayer)
}
private func addItemToGestureArray(item:VisionDetectGestures) {
if !self.detectedGestures.contains(item) {
self.detectedGestures.append(item)
}
}
var options : [String : AnyObject]?
//TODO: 🚧 HELPER TO CONVERT BETWEEN UIDEVICEORIENTATION AND CIDETECTORORIENTATION 🚧
private func convertOrientation(deviceOrientation: UIDeviceOrientation) -> Int {
var orientation: Int = 0
switch deviceOrientation {
case .portrait:
orientation = 6
case .portraitUpsideDown:
orientation = 2
case .landscapeLeft:
orientation = 3
case .landscapeRight:
orientation = 4
default : orientation = 1
}
return orientation
}
}
// MARK: - AVCapturePhotoCaptureDelegate
extension VisionDetect: AVCapturePhotoCaptureDelegate {
public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation(),
let image = UIImage(data: imageData) {
self.takenImage = image
}
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension VisionDetect: AVCaptureVideoDataOutputSampleBufferDelegate {
public func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
var sourceImage = CIImage()
if takenImage == nil {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
let opaqueBuffer = Unmanaged<CVImageBuffer>.passUnretained(imageBuffer!).toOpaque()
let pixelBuffer = Unmanaged<CVPixelBuffer>.fromOpaque(opaqueBuffer).takeUnretainedValue()
sourceImage = CIImage(cvPixelBuffer: pixelBuffer, options: nil)
}
else {
if let ciImage = takenImage?.ciImage {
sourceImage = ciImage
}
}
options = [
CIDetectorSmile: true as AnyObject,
CIDetectorEyeBlink: true as AnyObject,
CIDetectorImageOrientation: 6 as AnyObject
]
let features = self.faceDetector!.features(in: sourceImage, options: options)
if (features.count != 0) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == false) {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
} else {
self.delegate?.didFaceDetected()
self.addItemToGestureArray(item: .face)
}
self.faceDetected = true
for feature in features as! [CIFaceFeature] {
faceBounds = feature.bounds
if (feature.hasFaceAngle) {
if (faceAngle != nil) {
faceAngleDifference = CGFloat(feature.faceAngle) - faceAngle!
} else {
faceAngleDifference = CGFloat(feature.faceAngle)
}
faceAngle = CGFloat(feature.faceAngle)
}
if (feature.hasLeftEyePosition) {
leftEyePosition = feature.leftEyePosition
}
if (feature.hasRightEyePosition) {
rightEyePosition = feature.rightEyePosition
}
if (feature.hasMouthPosition) {
mouthPosition = feature.mouthPosition
}
if (feature.hasSmile) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == false) {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
} else {
self.delegate?.didSmile()
self.addItemToGestureArray(item: .smile)
}
hasSmile = feature.hasSmile
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.hasSmile == true) {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
} else {
self.delegate?.didNotSmile()
self.addItemToGestureArray(item: .noSmile)
}
hasSmile = feature.hasSmile
}
if (feature.leftEyeClosed || feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isWinking == false) {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
} else {
self.delegate?.didWinked()
self.addItemToGestureArray(item: .wink)
}
isWinking = true
if (feature.leftEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.leftEyeClosed == false) {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
} else {
self.delegate?.didLeftEyeClosed()
self.addItemToGestureArray(item: .leftEyeClosed)
}
leftEyeClosed = feature.leftEyeClosed
}
if (feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.rightEyeClosed == false) {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
} else {
self.delegate?.didRightEyeClosed()
self.addItemToGestureArray(item: .rightEyeClosed)
}
rightEyeClosed = feature.rightEyeClosed
}
if (feature.leftEyeClosed && feature.rightEyeClosed) {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == false) {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
} else {
self.delegate?.didBlinked()
self.addItemToGestureArray(item: .blink)
}
isBlinking = true
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.isBlinking == true) {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
}
if (self.isWinking == true) {
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
}
if (self.leftEyeClosed == true) {
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
}
if (self.rightEyeClosed == true) {
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
} else {
self.delegate?.didNotBlinked()
self.addItemToGestureArray(item: .noBlink)
self.delegate?.didNotWinked()
self.addItemToGestureArray(item: .noWink)
self.delegate?.didLeftEyeOpened()
self.addItemToGestureArray(item: .noLeftEyeClosed)
self.delegate?.didRightEyeOpened()
self.addItemToGestureArray(item: .noRightEyeClosed)
}
isBlinking = false
isWinking = false
leftEyeClosed = feature.leftEyeClosed
rightEyeClosed = feature.rightEyeClosed
}
}
} else {
if (onlyFireNotificatonOnStatusChange == true) {
if (self.faceDetected == true) {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
} else {
self.delegate?.didNoFaceDetected()
self.addItemToGestureArray(item: .noFace)
}
self.faceDetected = false
}
}
}
|
b80bfdfebb94868b8ecd10bcd0581505
| 34.704641 | 124 | 0.564287 | false | false | false | false |
VoIPGRID/vialer-ios
|
refs/heads/master
|
Vialer/Calling/Dialer/Controllers/DialerViewController.swift
|
gpl-3.0
|
1
|
//
// DialerViewController.swift
// Copyright © 2017 VoIPGRID. All rights reserved.
//
import UIKit
import AVFoundation
class DialerViewController: UIViewController, SegueHandler {
enum SegueIdentifier: String {
case sipCalling = "SIPCallingSegue"
case twoStepCalling = "TwoStepCallingSegue"
case reachabilityBar = "ReachabilityBarSegue"
}
fileprivate struct Config {
struct ReachabilityBar {
static let animationDuration = 0.3
static let height: CGFloat = 30.0
}
}
// MARK: - Properties
var numberText: String? {
didSet {
if let number = numberText {
numberText = PhoneNumberUtils.cleanPhoneNumber(number)
}
numberLabel.text = numberText
setupButtons()
}
}
var sounds = [String: AVAudioPlayer]()
var lastCalledNumber: String? {
didSet {
setupButtons()
}
}
var user = SystemUser.current()!
fileprivate let reachability = ReachabilityHelper.instance.reachability!
fileprivate var notificationCenter = NotificationCenter.default
fileprivate var reachabilityChanged: NotificationToken?
fileprivate var sipDisabled: NotificationToken?
fileprivate var sipChanged: NotificationToken?
fileprivate var encryptionUsageChanged: NotificationToken?
// MARK: - Outlets
@IBOutlet weak var leftDrawerButton: UIBarButtonItem!
@IBOutlet weak var numberLabel: PasteableUILabel! {
didSet {
numberLabel.delegate = self
}
}
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var reachabilityBarHeigthConstraint: NSLayoutConstraint!
@IBOutlet weak var reachabilityBar: UIView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
}
// MARK: - Lifecycle
extension DialerViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupLayout()
setupSounds()
reachabilityChanged = notificationCenter.addObserver(descriptor: Reachability.changed) { [weak self] _ in
self?.updateReachabilityBar()
}
sipDisabled = notificationCenter.addObserver(descriptor: SystemUser.sipDisabledNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
sipChanged = notificationCenter.addObserver(descriptor: SystemUser.sipChangedNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
encryptionUsageChanged = notificationCenter.addObserver(descriptor:SystemUser.encryptionUsageNotification) { [weak self] _ in
self?.updateReachabilityBar()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateReachabilityBar()
VialerGAITracker.trackScreenForController(name: controllerName)
try! AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: AVAudioSession.Category.ambient.rawValue))
setupButtons()
}
}
// MARK: - Actions
extension DialerViewController {
@IBAction func leftDrawerButtonPressed(_ sender: UIBarButtonItem) {
mm_drawerController.toggle(.left, animated: true, completion: nil)
}
@IBAction func deleteButtonPressed(_ sender: UIButton) {
if let number = numberText {
numberText = String(number.dropLast())
setupButtons()
}
}
@IBAction func deleteButtonLongPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
numberText = nil
}
}
@IBAction func callButtonPressed(_ sender: UIButton) {
guard numberText != nil else {
numberText = lastCalledNumber
return
}
lastCalledNumber = numberText
if ReachabilityHelper.instance.connectionFastEnoughForVoIP() {
VialerGAITracker.setupOutgoingSIPCallEvent()
DispatchQueue.main.async {
self.performSegue(segueIdentifier: .sipCalling)
}
} else {
VialerGAITracker.setupOutgoingConnectABCallEvent()
DispatchQueue.main.async {
self.performSegue(segueIdentifier: .twoStepCalling)
}
}
}
@IBAction func numberPressed(_ sender: NumberPadButton) {
numberPadPressed(character: sender.number)
playSound(character: sender.number)
}
@IBAction func zeroButtonLongPress(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
playSound(character: "0")
numberPadPressed(character: "+")
}
}
}
// MARK: - Segues
extension DialerViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segueIdentifier(segue: segue) {
case .sipCalling:
let sipCallingVC = segue.destination as! SIPCallingViewController
if (UIApplication.shared.delegate as! AppDelegate).isScreenshotRun {
sipCallingVC.handleOutgoingCallForScreenshot(phoneNumber: numberText!)
} else {
sipCallingVC.handleOutgoingCall(phoneNumber: numberText!, contact: nil)
}
numberText = nil
case .twoStepCalling:
let twoStepCallingVC = segue.destination as! TwoStepCallingViewController
twoStepCallingVC.handlePhoneNumber(numberText!)
numberText = nil
case .reachabilityBar:
break
}
}
}
// MARK: - PasteableUILabelDelegate
extension DialerViewController : PasteableUILabelDelegate {
func pasteableUILabel(_ label: UILabel!, didReceivePastedText text: String!) {
numberText = text
}
}
// MARK: - Helper functions layout
extension DialerViewController {
fileprivate func setupUI() {
title = NSLocalizedString("Keypad", comment: "Keypad")
tabBarItem.image = UIImage(asset: .tabKeypad)
tabBarItem.selectedImage = UIImage(asset: .tabKeypadActive)
}
fileprivate func setupLayout() {
navigationItem.titleView = UIImageView(image: UIImage(asset: .logo))
updateReachabilityBar()
}
fileprivate func setupSounds() {
DispatchQueue.global(qos: .userInteractive).async {
var sounds = [String: AVAudioPlayer]()
for soundNumber in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "#", "*"] {
let soundFileName = "dtmf-\(soundNumber)"
let soundURL = Bundle.main.url(forResource: soundFileName, withExtension: "aif")
assert(soundURL != nil, "No sound available")
do {
let player = try AVAudioPlayer(contentsOf: soundURL!)
player.prepareToPlay()
sounds[soundNumber] = player
} catch let error {
VialerLogError("Couldn't load sound: \(error)")
}
}
self.sounds = sounds
}
}
fileprivate func setupButtons() {
// Enable callbutton if:
// - status isn't offline or
// - there is a number in memory or
// - there is a number to be called
if reachability.status == .notReachable || (lastCalledNumber == nil && numberText == nil) {
callButton.isEnabled = false
} else {
callButton.isEnabled = true
}
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.callButton.alpha = self.callButton.isEnabled ? 1.0 : 0.5
}, completion: nil)
deleteButton.isEnabled = numberText != nil
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.deleteButton.alpha = self.deleteButton.isEnabled ? 1.0 : 0.0
}, completion: nil)
}
fileprivate func numberPadPressed(character: String) {
if character == "+" {
if numberText == "0" || numberText == nil {
numberText = "+"
}
} else if numberText != nil {
numberText = "\(numberText!)\(character)"
} else {
numberText = character
}
}
fileprivate func playSound(character: String) {
if let player = sounds[character] {
player.currentTime = 0
player.play()
}
}
fileprivate func updateReachabilityBar() {
DispatchQueue.main.async {
self.setupButtons()
if (!self.user.sipEnabled) {
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else if (!self.reachability.hasHighSpeed) {
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else if (!self.user.sipUseEncryption){
self.reachabilityBarHeigthConstraint.constant = Config.ReachabilityBar.height
} else {
self.reachabilityBarHeigthConstraint.constant = 0
}
UIView.animate(withDuration: Config.ReachabilityBar.animationDuration) {
self.reachabilityBar.setNeedsUpdateConstraints()
self.view.layoutIfNeeded()
}
}
}
}
|
c75e0c043899b9f2e82699b2f0aa8729
| 34.146067 | 133 | 0.622762 | false | false | false | false |
Stitch7/mclient
|
refs/heads/master
|
mclient/PrivateMessages/_MessageKit/Views/MessageLabel.swift
|
mit
|
1
|
/*
MIT License
Copyright (c) 2017-2018 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 UIKit
open class MessageLabel: UILabel {
// MARK: - Private Properties
private lazy var layoutManager: NSLayoutManager = {
let layoutManager = NSLayoutManager()
layoutManager.addTextContainer(self.textContainer)
return layoutManager
}()
private lazy var textContainer: NSTextContainer = {
let textContainer = NSTextContainer()
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = self.numberOfLines
textContainer.lineBreakMode = self.lineBreakMode
textContainer.size = self.bounds.size
return textContainer
}()
private lazy var textStorage: NSTextStorage = {
let textStorage = NSTextStorage()
textStorage.addLayoutManager(self.layoutManager)
return textStorage
}()
private lazy var rangesForDetectors: [DetectorType: [(NSRange, MessageTextCheckingType)]] = [:]
private var isConfiguring: Bool = false
// MARK: - Public Properties
open weak var delegate: MessageLabelDelegate?
open var enabledDetectors: [DetectorType] = [] {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var attributedText: NSAttributedString? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var text: String? {
didSet {
setTextStorage(attributedText, shouldParse: true)
}
}
open override var font: UIFont! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var textColor: UIColor! {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open override var lineBreakMode: NSLineBreakMode {
didSet {
textContainer.lineBreakMode = lineBreakMode
if !isConfiguring { setNeedsDisplay() }
}
}
open override var numberOfLines: Int {
didSet {
textContainer.maximumNumberOfLines = numberOfLines
if !isConfiguring { setNeedsDisplay() }
}
}
open override var textAlignment: NSTextAlignment {
didSet {
setTextStorage(attributedText, shouldParse: false)
}
}
open var textInsets: UIEdgeInsets = .zero {
didSet {
if !isConfiguring { setNeedsDisplay() }
}
}
open override var intrinsicContentSize: CGSize {
var size = super.intrinsicContentSize
size.width += textInsets.horizontal
size.height += textInsets.vertical
return size
}
internal var messageLabelFont: UIFont?
private var attributesNeedUpdate = false
public static var defaultAttributes: [NSAttributedString.Key: Any] = {
return [
NSAttributedString.Key.foregroundColor: UIColor.darkText,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.underlineColor: UIColor.darkText
]
}()
open internal(set) var addressAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var dateAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var phoneNumberAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var urlAttributes: [NSAttributedString.Key: Any] = defaultAttributes
open internal(set) var transitInformationAttributes: [NSAttributedString.Key: Any] = defaultAttributes
public func setAttributes(_ attributes: [NSAttributedString.Key: Any], detector: DetectorType) {
switch detector {
case .phoneNumber:
phoneNumberAttributes = attributes
case .address:
addressAttributes = attributes
case .date:
dateAttributes = attributes
case .url:
urlAttributes = attributes
case .transitInformation:
transitInformationAttributes = attributes
}
if isConfiguring {
attributesNeedUpdate = true
} else {
updateAttributes(for: [detector])
}
}
// MARK: - Initializers
public override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
// MARK: - Open Methods
open override func drawText(in rect: CGRect) {
let insetRect = rect.inset(by: textInsets)
textContainer.size = CGSize(width: insetRect.width, height: rect.height)
let origin = insetRect.origin
let range = layoutManager.glyphRange(for: textContainer)
layoutManager.drawBackground(forGlyphRange: range, at: origin)
layoutManager.drawGlyphs(forGlyphRange: range, at: origin)
}
// MARK: - Public Methods
public func configure(block: () -> Void) {
isConfiguring = true
block()
if attributesNeedUpdate {
updateAttributes(for: enabledDetectors)
}
attributesNeedUpdate = false
isConfiguring = false
setNeedsDisplay()
}
// MARK: - Private Methods
private func setTextStorage(_ newText: NSAttributedString?, shouldParse: Bool) {
guard let newText = newText, newText.length > 0 else {
textStorage.setAttributedString(NSAttributedString())
setNeedsDisplay()
return
}
let style = paragraphStyle(for: newText)
let range = NSRange(location: 0, length: newText.length)
let mutableText = NSMutableAttributedString(attributedString: newText)
mutableText.addAttribute(.paragraphStyle, value: style, range: range)
if shouldParse {
rangesForDetectors.removeAll()
let results = parse(text: mutableText)
setRangesForDetectors(in: results)
}
for (detector, rangeTuples) in rangesForDetectors {
if enabledDetectors.contains(detector) {
let attributes = detectorAttributes(for: detector)
rangeTuples.forEach { (range, _) in
mutableText.addAttributes(attributes, range: range)
}
}
}
let modifiedText = NSAttributedString(attributedString: mutableText)
textStorage.setAttributedString(modifiedText)
if !isConfiguring { setNeedsDisplay() }
}
private func paragraphStyle(for text: NSAttributedString) -> NSParagraphStyle {
guard text.length > 0 else { return NSParagraphStyle() }
var range = NSRange(location: 0, length: text.length)
let existingStyle = text.attribute(.paragraphStyle, at: 0, effectiveRange: &range) as? NSMutableParagraphStyle
let style = existingStyle ?? NSMutableParagraphStyle()
style.lineBreakMode = lineBreakMode
style.alignment = textAlignment
return style
}
private func updateAttributes(for detectors: [DetectorType]) {
guard let attributedText = attributedText, attributedText.length > 0 else { return }
let mutableAttributedString = NSMutableAttributedString(attributedString: attributedText)
for detector in detectors {
guard let rangeTuples = rangesForDetectors[detector] else { continue }
for (range, _) in rangeTuples {
let attributes = detectorAttributes(for: detector)
mutableAttributedString.addAttributes(attributes, range: range)
}
let updatedString = NSAttributedString(attributedString: mutableAttributedString)
textStorage.setAttributedString(updatedString)
}
}
private func detectorAttributes(for detectorType: DetectorType) -> [NSAttributedString.Key: Any] {
switch detectorType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .url:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
}
}
private func detectorAttributes(for checkingResultType: NSTextCheckingResult.CheckingType) -> [NSAttributedString.Key: Any] {
switch checkingResultType {
case .address:
return addressAttributes
case .date:
return dateAttributes
case .phoneNumber:
return phoneNumberAttributes
case .link:
return urlAttributes
case .transitInformation:
return transitInformationAttributes
default:
fatalError(MessageKitError.unrecognizedCheckingResult)
}
}
private func setupView() {
numberOfLines = 0
lineBreakMode = .byWordWrapping
}
// MARK: - Parsing Text
private func parse(text: NSAttributedString) -> [NSTextCheckingResult] {
guard enabledDetectors.isEmpty == false else { return [] }
let checkingTypes = enabledDetectors.reduce(0) { $0 | $1.textCheckingType.rawValue }
let detector = try? NSDataDetector(types: checkingTypes)
let range = NSRange(location: 0, length: text.length)
let matches = detector?.matches(in: text.string, options: [], range: range) ?? []
guard enabledDetectors.contains(.url) else {
return matches
}
// Enumerate NSAttributedString NSLinks and append ranges
var results: [NSTextCheckingResult] = matches
text.enumerateAttribute(NSAttributedString.Key.link, in: range, options: []) { value, range, _ in
guard let url = value as? URL else { return }
let result = NSTextCheckingResult.linkCheckingResult(range: range, url: url)
results.append(result)
}
return results
}
private func setRangesForDetectors(in checkingResults: [NSTextCheckingResult]) {
guard checkingResults.isEmpty == false else { return }
for result in checkingResults {
switch result.resultType {
case .address:
var ranges = rangesForDetectors[.address] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .addressComponents(result.addressComponents))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .address)
case .date:
var ranges = rangesForDetectors[.date] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .date(result.date))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .date)
case .phoneNumber:
var ranges = rangesForDetectors[.phoneNumber] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .phoneNumber(result.phoneNumber))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .phoneNumber)
case .link:
var ranges = rangesForDetectors[.url] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .link(result.url))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .url)
case .transitInformation:
var ranges = rangesForDetectors[.transitInformation] ?? []
let tuple: (NSRange, MessageTextCheckingType) = (result.range, .transitInfoComponents(result.components))
ranges.append(tuple)
rangesForDetectors.updateValue(ranges, forKey: .transitInformation)
default:
fatalError("Received an unrecognized NSTextCheckingResult.CheckingType")
}
}
}
// MARK: - Gesture Handling
private func stringIndex(at location: CGPoint) -> Int? {
guard textStorage.length > 0 else { return nil }
var location = location
location.x -= textInsets.left
location.y -= textInsets.top
let index = layoutManager.glyphIndex(for: location, in: textContainer)
let lineRect = layoutManager.lineFragmentUsedRect(forGlyphAt: index, effectiveRange: nil)
var characterIndex: Int?
if lineRect.contains(location) {
characterIndex = layoutManager.characterIndexForGlyph(at: index)
}
return characterIndex
}
open func handleGesture(_ touchLocation: CGPoint) -> Bool {
guard let index = stringIndex(at: touchLocation) else { return false }
for (detectorType, ranges) in rangesForDetectors {
for (range, value) in ranges {
if range.contains(index) {
handleGesture(for: detectorType, value: value)
return true
}
}
}
return false
}
private func handleGesture(for detectorType: DetectorType, value: MessageTextCheckingType) {
switch value {
case let .addressComponents(addressComponents):
var transformedAddressComponents = [String: String]()
guard let addressComponents = addressComponents else { return }
addressComponents.forEach { (key, value) in
transformedAddressComponents[key.rawValue] = value
}
handleAddress(transformedAddressComponents)
case let .phoneNumber(phoneNumber):
guard let phoneNumber = phoneNumber else { return }
handlePhoneNumber(phoneNumber)
case let .date(date):
guard let date = date else { return }
handleDate(date)
case let .link(url):
guard let url = url else { return }
handleURL(url)
case let .transitInfoComponents(transitInformation):
var transformedTransitInformation = [String: String]()
guard let transitInformation = transitInformation else { return }
transitInformation.forEach { (key, value) in
transformedTransitInformation[key.rawValue] = value
}
handleTransitInformation(transformedTransitInformation)
}
}
private func handleAddress(_ addressComponents: [String: String]) {
delegate?.didSelectAddress(addressComponents)
}
private func handleDate(_ date: Date) {
delegate?.didSelectDate(date)
}
private func handleURL(_ url: URL) {
delegate?.didSelectURL(url)
}
private func handlePhoneNumber(_ phoneNumber: String) {
delegate?.didSelectPhoneNumber(phoneNumber)
}
private func handleTransitInformation(_ components: [String: String]) {
delegate?.didSelectTransitInformation(components)
}
}
private enum MessageTextCheckingType {
case addressComponents([NSTextCheckingKey: String]?)
case date(Date?)
case phoneNumber(String?)
case link(URL?)
case transitInfoComponents([NSTextCheckingKey: String]?)
}
|
a354b0e30bef19c3ddb9e507fb1dcfed
| 33.550633 | 129 | 0.640777 | false | false | false | false |
JGiola/swift
|
refs/heads/main
|
validation-test/Sema/type_checker_perf/fast/fast-operator-typechecking.swift
|
apache-2.0
|
9
|
// RUN: %target-typecheck-verify-swift -swift-version 5 -solver-expression-time-threshold=1
// rdar://problem/32998180
func checksum(value: UInt16) -> UInt16 {
var checksum = (((value >> 2) ^ (value >> 8) ^ (value >> 12) ^ (value >> 14)) & 0x01) << 1
checksum |= (((value) ^ (value >> UInt16(4)) ^ (value >> UInt16(6)) ^ (value >> UInt16(10))) & 0x01)
checksum ^= 0x02
return checksum
}
// rdar://problem/42672829
func f(tail: UInt64, byteCount: UInt64) {
if tail & ~(1 << ((byteCount & 7) << 3) - 1) == 0 { }
}
// rdar://problem/32547805
func size(count: Int) {
// Size of the buffer we need to allocate
let _ = count * MemoryLayout<Float>.size * (4 + 3 + 3 + 2 + 4)
}
|
122531ba1271fc4c8c919808e62e4370
| 33.35 | 102 | 0.598253 | false | false | false | false |
zhouxj6112/ARKit
|
refs/heads/master
|
ARKitInteraction/ARKitInteraction/ViewController+ObjectSelection.swift
|
apache-2.0
|
1
|
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
Methods on the main view controller for handling virtual object loading and movement
*/
import UIKit
import SceneKit
extension ViewController: VirtualObjectSelectionViewControllerDelegate {
/**
Adds the specified virtual object to the scene, placed using
the focus square's estimate of the world-space position
currently corresponding to the center of the screen.
- Tag: PlaceVirtualObject
*/
func placeVirtualObject(_ virtualObject: VirtualObject) {
guard let cameraTransform = session.currentFrame?.camera.transform,
let focusSquarePosition = focusSquare.lastPosition else {
statusViewController.showMessage("CANNOT PLACE OBJECT\nTry moving left or right.")
return
}
virtualObjectInteraction.selectedObject = virtualObject
// 控制位置
virtualObject.setPosition(focusSquarePosition, relativeTo: cameraTransform, smoothMovement: false)
// 缩放比例
virtualObject.setScale();
// 控制方向
virtualObject.setDirection();
updateQueue.async {
if self.sceneView.scene.rootNode.childNodes.count > 3 {
let preObj = self.sceneView.scene.rootNode.childNodes[3];
let max = preObj.boundingBox.max;
let min = preObj.boundingBox.min;
virtualObject.simdPosition = simd_float3(0, (max.y-min.y), 0);
preObj.addChildNode(virtualObject);
self.virtualObjectInteraction.selectedObject = preObj as? VirtualObject;
} else {
self.sceneView.scene.rootNode.addChildNode(virtualObject)
}
}
}
// MARK: - VirtualObjectSelectionViewControllerDelegate
func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didSelectObject object: VirtualObject) {
virtualObjectLoader.loadVirtualObject(object, loadedHandler: { [unowned self] loadedObject in
DispatchQueue.main.async {
self.hideObjectLoadingUI()
self.placeVirtualObject(loadedObject)
}
})
displayObjectLoadingUI()
}
func virtualObjectSelectionViewController(_: VirtualObjectSelectionViewController, didDeselectObject object: VirtualObject) {
guard let objectIndex = virtualObjectLoader.loadedObjects.index(of: object) else {
fatalError("Programmer error: Failed to lookup virtual object in scene.")
}
virtualObjectLoader.removeVirtualObject(at: objectIndex)
}
// MARK: Object Loading UI
func displayObjectLoadingUI() {
// Show progress indicator.
spinner.startAnimating()
addObjectButton.setImage(#imageLiteral(resourceName: "buttonring"), for: [])
addObjectButton.isEnabled = false
isRestartAvailable = false
}
func hideObjectLoadingUI() {
// Hide progress indicator.
spinner.stopAnimating()
addObjectButton.setImage(#imageLiteral(resourceName: "add"), for: [])
addObjectButton.setImage(#imageLiteral(resourceName: "addPressed"), for: [.highlighted])
addObjectButton.isEnabled = true
isRestartAvailable = true
}
}
|
70f7d0722a77611f7ea385b22a1be568
| 36.022222 | 129 | 0.668067 | false | false | false | false |
bhold6160/GITList
|
refs/heads/master
|
GITList/GITList/Cloudkit.swift
|
mit
|
1
|
//
// Cloudkit.swift
// GITList
//
// Created by Louis W. Haywood on 8/23/17.
// Copyright © 2017 Brandon Holderman. All rights reserved.
//
import Foundation
import CloudKit
typealias ListCompletion = (Bool)->()
typealias GetListCompletion = ([List]?)->()
class CloudKit {
static let shared = CloudKit()
let container = CKContainer.default()
var database : CKDatabase {
return container.privateCloudDatabase
}
private init (){}
func save(list: List, completion: @escaping ListCompletion) {
do {
if let record = try list.record() {
self.database.save(record, completionHandler: { (record, error) in
if error != nil {
print(error!)
completion(false)
}
if let record = record {
print(record)
completion(true)
}
})
}
} catch {
print(error)
}
}
func getList(completion: @escaping GetListCompletion) {
let query = CKQuery(recordType: "List", predicate: NSPredicate(value: true))
query.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
self.database.perform(query, inZoneWith: nil) { (records, error) in
if error != nil {
print(error!.localizedDescription)
completion(nil)
}
if let records = records {
var allLists = [List]()
for record in records {
guard let recordValue = record["items"] as? [String] else { continue }
guard let createdAt = record["creationDate"] as? Date else { continue }
let newList = List()
newList.items = recordValue
newList.createdAtDate = createdAt
allLists.append(newList)
}
OperationQueue.main.addOperation {
completion(allLists)
}
completion(nil)
}
}
}
}
|
d69f21f6a790402e27b19b77a68fa05e
| 28.876712 | 91 | 0.508482 | false | false | false | false |
ajaybeniwal/SwiftTransportApp
|
refs/heads/master
|
TransitFare/TopMostViewController.swift
|
mit
|
1
|
//
// TopMostViewController.swift
// TransitFare
//
// Created by ajaybeniwal203 on 24/2/16.
// Copyright © 2016 ajaybeniwal203. All rights reserved.
//
import UIKit
extension UIViewController{
class func topMostViewController() -> UIViewController?{
let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
return self.topMostViewControllerOfViewController(rootViewController)
}
class func topMostViewControllerOfViewController(viewController: UIViewController?) -> UIViewController? {
// UITabBarController
if let tabBarController = viewController as? UITabBarController,
let selectedViewController = tabBarController.selectedViewController {
return self.topMostViewControllerOfViewController(selectedViewController)
}
// UINavigationController
if let navigationController = viewController as? UINavigationController,
let visibleViewController = navigationController.visibleViewController {
return self.topMostViewControllerOfViewController(visibleViewController)
}
// presented view controller
if let presentedViewController = viewController?.presentedViewController {
return self.topMostViewControllerOfViewController(presentedViewController)
}
return viewController
}
}
|
b6204048561e5eb148d259407fd1f37b
| 35.564103 | 110 | 0.721599 | false | false | false | false |
gossipgeek/gossipgeek
|
refs/heads/develop
|
GossipGeek/GossipGeek/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// GossipGeek
//
// Created by Toureek on 10/05/2017.
// Copyright © 2017 application. All rights reserved.
//
import UIKit
let kApplicationID = "B4wHEEb4qLnekUEb6uiiwo4w-gzGzoHsz"
let kApplicationKey = "bvkHfVjS1pmOA14SFujzxxGE"
let kStoryBoardName = "Main"
let kAppTabBarStoryBoardId = "tabbarviewcontroller"
let kAppLoginStoryBoardId = "loginviewcontroller"
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
connectToAVOSCloudSDKService(launchOptions: launchOptions)
if isUserLogin() {
showMainPage()
} else {
showLoginPage()
}
return true
}
func connectToAVOSCloudSDKService(launchOptions: [UIApplicationLaunchOptionsKey: Any]?) {
initLCObject()
AVOSCloud.setApplicationId(kApplicationID, clientKey: kApplicationKey)
AVOSCloud.setAllLogsEnabled(true)
}
func initLCObject() {
Magazine.registerSubclass()
}
// TODO: - It will be removed after register-feature finished
func isUserLogin() -> Bool {
return true
}
func showMainPage() {
let storyboard = UIStoryboard.init(name: kStoryBoardName, bundle: nil)
let mainTabPage = storyboard.instantiateViewController(withIdentifier: kAppTabBarStoryBoardId)
self.window?.rootViewController = mainTabPage
}
func showLoginPage() {
let storyboard = UIStoryboard.init(name: kStoryBoardName, bundle: nil)
let loginView = storyboard.instantiateViewController(withIdentifier: kAppLoginStoryBoardId)
let navigator = UINavigationController.init(rootViewController: loginView)
self.window?.rootViewController = navigator
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
6c0be789981773a36c40f5c0ede55675
| 38.402174 | 285 | 0.726897 | false | false | false | false |
arsonik/AKTrakt
|
refs/heads/master
|
Source/shared/Requests/Movie.swift
|
mit
|
1
|
//
// Movie.swift
// Pods
//
// Created by Florian Morello on 26/05/16.
//
//
import Foundation
import Alamofire
public class TraktRequestMovie: TraktRequest {
public init(id: AnyObject, extended: TraktRequestExtendedOptions? = nil) {
super.init(path: "/movies/\(id)", params: extended?.value())
}
public func request(trakt: Trakt, completion: (TraktMovie?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
completion(TraktMovie(data: response.result.value as? JSONHash), response.result.error)
}
}
}
public class TraktRequestMovieReleases: TraktRequest {
public init(id: AnyObject, country: String? = nil, extended: TraktRequestExtendedOptions? = nil) {
super.init(path: "/movies/\(id)/releases" + (country != nil ? "/\(country!)" : ""), params: extended?.value())
}
public func request(trakt: Trakt, completion: ([TraktRelease]?, NSError?) -> Void) -> Request? {
return trakt.request(self) { response in
guard let data = response.result.value as? [JSONHash] else {
return completion(nil, response.result.error)
}
completion(data.flatMap { TraktRelease(data: $0) }, response.result.error)
}
}
}
|
e0960401c0ba93a9215d765f35ffa5ea
| 32.526316 | 118 | 0.636578 | false | false | false | false |
overtake/TelegramSwift
|
refs/heads/master
|
Telegram-Mac/InlineAuthOptionRowItem.swift
|
gpl-2.0
|
1
|
//
// InlineAuthOptionRowItem.swift
// Telegram
//
// Created by Mikhail Filimonov on 22/05/2019.
// Copyright © 2019 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
class InlineAuthOptionRowItem: GeneralRowItem {
fileprivate let selected: Bool
fileprivate let textLayout: TextViewLayout
init(_ initialSize: NSSize, stableId: AnyHashable, attributedString: NSAttributedString, selected: Bool, action: @escaping()->Void) {
self.selected = selected
self.textLayout = TextViewLayout(attributedString, maximumNumberOfLines: 3, alwaysStaticItems: true)
super.init(initialSize, stableId: stableId, action: action, inset: NSEdgeInsetsMake(10, 30, 10, 30))
}
override func makeSize(_ width: CGFloat, oldWidth: CGFloat) -> Bool {
textLayout.measure(width: width - inset.left - inset.right - 50)
return super.makeSize(width, oldWidth: oldWidth)
}
override func viewClass() -> AnyClass {
return InlineAuthOptionRowView.self
}
override var height: CGFloat {
return max(textLayout.layoutSize.height + inset.top + inset.bottom, 30)
}
}
private final class InlineAuthOptionRowView : TableRowView {
private let textView = TextView()
private let selectView: SelectingControl = SelectingControl(unselectedImage: theme.icons.chatGroupToggleUnselected, selectedImage: theme.icons.chatGroupToggleSelected)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
addSubview(selectView)
selectView.userInteractionEnabled = false
textView.userInteractionEnabled = false
textView.isSelectable = false
}
override func mouseUp(with event: NSEvent) {
guard let item = item as? InlineAuthOptionRowItem else {
return
}
item.action()
}
override func set(item: TableRowItem, animated: Bool) {
super.set(item: item, animated: animated)
guard let item = item as? InlineAuthOptionRowItem else {
return
}
selectView.set(selected: item.selected, animated: animated)
}
override func layout() {
super.layout()
guard let item = item as? InlineAuthOptionRowItem else {
return
}
textView.update(item.textLayout)
if item.textLayout.layoutSize.height < selectView.frame.height {
selectView.centerY(x: item.inset.left)
textView.centerY(x: selectView.frame.maxX + 10)
} else {
selectView.setFrameOrigin(NSMakePoint(item.inset.left, item.inset.top))
textView.setFrameOrigin(NSMakePoint(selectView.frame.maxX + 10, selectView.frame.minY))
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
9093967567cd2c1e0fbddc37534cafa6
| 31.32967 | 171 | 0.653977 | false | false | false | false |
HenningBrandt/SwiftPromise
|
refs/heads/master
|
Source/SwiftPromise.swift
|
mit
|
1
|
//
// SwiftPromise.swift
//
// Copyright (c) 2015 Henning Brandt (http://thepurecoder.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Bind-Operator.
Operator for Promises flatMap.
*/
public func >>=<T,R>(p: Promise<T>, f: (T) -> Promise<R>) -> Promise<R> {
return p.flatMap(f: f)
}
public class Promise<T> {
/**
Type for the final result of the promise.
It consists of a fulfilled or failed result represented by an Either and
all callbacks scheduled for the advent of the result.
*/
private typealias PromiseValue = (Either<T>?, [DeliverBlock])
/**
A GCD queue.
The future block or any method dealing with the promise result is executed in an execution enviroment.
This enviroment or context is a dispatch queue on which the corresponding computations are performed
*/
public typealias ExecutionContext = DispatchQueue
/**
A block of work that can be performed in the background.
The return value of the block becomes the value of the fulfilled promise.
If the block throws an error, the promise fails with this error.
*/
public typealias BackgroundTask = (() throws -> T)
/**
A unit of work. It consists of the execution context on which it should be performed and
the task itself doing the work with the result of the fulfilled promise.
*/
private typealias DeliverBlock = (ExecutionContext, (Either<T>) -> ())
/**
The internal result holding the promises value and any callbacks.
Any code interested in the result must schedule one of the different callbacks or access it via
- `value`
- `error`
- `result`
fulfillment can be tested via
- `isFulfilled`
*/
private var internalValue: PromiseValue = (nil, [])
/**
A sempahore to synchronize the critial path concerning fulfillment of the promises result.
Setting the value can occur from many different threads. The promise must, on a thread safe level, ensure that:
- a promises value can only be set once and after that can never change.
- any callback scheduled before or after setting the promises value is guaranteed to be invoked with the result
*/
private let fulfillSemaphore = DispatchSemaphore(value: 1)
/**
The default execution context used for the background task the promise was initialized with and
any scheduled callback not specifying its own context when scheduled.
- important:
Exceptions are the three result callbacks:
- `onComplete()`
- `onSuccess()`
- `onFailure()`
These three normally mark endpoints in the value processing and will presumably
used for interacting with UIKit for updating UI elements etc. So for convenience
they are performed on the main queue by default.
*/
private let defaultExecutionContext: ExecutionContext
/**
Initializer for creating a Promise whose value comes from a block.
Use this if you want the promise to manage asynchronous execution and
fulfill itself with the computed value. This mimics more or less the concept of
a _Future_ combined with a _Promise_.
- parameter executionContext: The default execution context. The given task will be performed on this queue among others.
Default is a global queue with the default quality of service.
- parameter task: A block that gets executed immediately on the given execution context.
The value returned by this block will fulfill the promise.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.DefaultContext, task: BackgroundTask) {
self.defaultExecutionContext = executionContext
self.defaultExecutionContext.async {
do {
let result = try task()
self.fulfill(.result(result))
} catch let error {
self.fulfill(.failure(error))
}
}
}
/**
Initializer for creating a _Promise_ with an already computed value.
The _Promise_ will fulfill itself immediately with a given value.
You can use this when you have code returning a _Promise_ with a future value, but once you have it you return a cached result
or some function wants a _Promise_ but you just want to pass an inexpensive value that don't need background computation etc.
- parameter executionContext: The default execution context.
Default is the main queue.
- parameter value: The value to fulfill the _Promise_ with.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.MainContext, value: T) {
self.defaultExecutionContext = executionContext
self.fulfill(.result(value))
}
/**
Initialier for creating an empty _Promise_.
Use this if your background computation is more complicated and doesn't fit in a block.
For example when you use libraries requiring own callback blocks or delegate callbacks.
You can than create an empty _Promise_ return it immediately, performing your work
and fulfill it manually later via `fulfill()`.
- parameter executionContext: The default execution context.
Default is a global queue with the default quality of service.
*/
public init(_ executionContext: ExecutionContext = ExecutionContextConstant.DefaultContext) {
self.defaultExecutionContext = executionContext
}
/**
Method for providing the promise with a value.
Use this to fulfill the _Promise_ with either a result or an error.
All callbacks already queued up will be called with the given value.
`fulfill()` is thread safe and can safely be called from any thread.
- important:
A _Promise_ can only be fulfilled once and will have this value over its whole lifetime.
You can have multiple threads compute a value and call fulfill on the same _Promise_ but only
the first value will be excepted and set on the _Promise_. All later calls to fulfill are ignored
and its value will be droped.
- parameter value: The value to set on the _Promise_. This can either be a result or a failure.
See `Either` for this.
*/
public func fulfill(_ value: Either<T>) {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, blocks) = self.internalValue
guard internalResult == nil else { return }
self.internalValue = (value, blocks)
self.executeDeliverBlocks(value)
}
/**
Gives back if the promise is fulfilled with either a value or an error.
- returns: true if promise is fulfilled otherwise false
*/
public func isFulfilled() -> Bool {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
return internalResult != nil
}
/**
Returns the value the promise was fulfilled with.
A Promise can either be fulfilled with a result or an error,
so value returns an Either.
- returns: An Either with the Promises result/error or nil if the Promise is not fulfilled yet
*/
public func value() -> Either<T>? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
return internalResult
}
/**
Returns the Promises result if there is one.
- returns: The Promises result if there is one or nil if the Promise is not fulfilled yet
or is fulfilled with an error.
*/
public func result() -> T? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
guard let result = internalResult else {
return nil
}
switch result {
case .result(let r):
return r
case .failure:
return nil
}
}
/**
Returns the Promises error if there is one.
- returns: The Promises error if there is one or nil if the Promise is not fulfilled yet
or is fulfilled with a result.
*/
public func error() -> ErrorProtocol? {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let (internalResult, _) = self.internalValue
guard let result = internalResult else {
return nil
}
switch result {
case .result:
return nil
case .failure(let error):
return error
}
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in general fulfillment of the Promise with eiter a result or an error.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument.
*/
@discardableResult
public func onComplete(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (Either<T>) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({ f($0) }, context)
return self
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in fulfillment of the Promise with a result.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the result of the Promise as argument.
*/
@discardableResult
public func onSuccess(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (T) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({
switch $0 {
case .result(let result):
f(result)
case .failure:
break
}
}, context)
return self
}
/**
Callback triggered at fulfillment of the Promise.
Registers a callback interested in fulfillment of the Promise with an error.
- parameter context: dispatch_queue on which to perform the block. Default is the main queue.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument.
Can throw an error wich will be carried up the Promise chain.
*/
@discardableResult
public func onFailure(_ context: ExecutionContext = ExecutionContextConstant.MainContext, f: (ErrorProtocol) -> ()) -> Promise<T> {
self.enqueueDeliverBlock({
switch $0 {
case .result:
break
case .failure(let error):
f(error)
}
}, context)
return self
}
/**
Map a Promise of type A to a Promise of type B.
Registers a callback on fulfillment, which will map the Promise to a Promise of another type.
- parameter context: dispatch queue on which to perform the block.
Default is the default queue the Promise was initialized with.
- parameter f: The block scheduled for fulfillment. Takes the result of the Promise as an argument and returning another result.
Can throw an error wich will be carried up the Promise chain.
- returns: A Promise wrapping the value produced by f
*/
public func map<R>(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> R) -> Promise<R> {
let promise = Promise<R>(self.validContext(context))
self.enqueueDeliverBlock({
switch $0 {
case .failure(let error):
promise.fulfill(.failure(error))
case .result(let result):
do {
let mappedResult = try f(result)
promise.fulfill(.result(mappedResult))
} catch let error {
promise.fulfill(.failure(error))
}
}
}, context)
return promise
}
/**
Returning a second Promise produced with the value of self by a given function f.
Monadic bind-function. Can among others be used to sequence Promises.
Because f, returning the second Promise, is called with the result of the first Promise,
the execution of f is delayed until the first Promise is fulfilled.
Has also an operator: >>=
- parameter context: dispatch queue on which to perform the block.
Default is the default queue the Promise was initialized with.
- parameter f: The block scheduled for fulfillment. Takes the value of the Promise as argument and returning a second Promise.
Can throw an error wich will be carried up the Promise chain.
- returns: The Promise produced by f
*/
public func flatMap<R>(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> Promise<R>) -> Promise<R> {
let ctx = self.validContext(context)
let placeholder = Promise<R>(ctx)
self.enqueueDeliverBlock({
switch $0 {
case .failure(let error):
placeholder.fulfill(.failure(error))
case .result(let result):
do {
// The f function can't produce a Promise until the current promise is fulfilled
// but it is required to return a promise immediately for this reason we introduce
// a placeholder which completes simultaneously with the promise produced by f.
let promise = try f(result)
promise.onComplete(ctx) { placeholder.fulfill($0) }
} catch let error {
placeholder.fulfill(.failure(error))
}
}
}, context)
return placeholder
}
public func filter(_ context: ExecutionContext = ExecutionContextConstant.PlaceHolderContext, f: (T) throws -> Bool) -> Promise<T> {
let promise = Promise<T>(self.validContext(context))
self.enqueueDeliverBlock({
switch $0 {
case .failure:
promise.fulfill($0)
case .result(let result):
do {
let passedFilter = try f(result)
if passedFilter {
promise.fulfill($0)
} else {
promise.fulfill(.failure(Error.filterNotPassed))
}
} catch let error {
promise.fulfill(.failure(error))
}
}
}, context)
return promise
}
public class func collect<R>(_ promises: [Promise<R>]) -> Promise<[R]> {
func comb(_ acc: Promise<[R]>, elem: Promise<R>) -> Promise<[R]> {
return elem >>= { x in
acc >>= { xs in
var _xs = xs
_xs.append(x)
return Promise<[R]>(value: _xs)
}
}
}
return promises.reduce(Promise<[R]>(value: []), combine: comb)
}
public class func select<R>(_ promises: [Promise<R>], context: ExecutionContext = ExecutionContextConstant.DefaultContext)
-> Promise<(Promise<R>, [Promise<R>])>
{
let promise = Promise<(Promise<R>, [Promise<R>])>(context)
for p in promises {
p.onComplete { _ in
let result = (p, promises.filter { $0 !== p } )
promise.fulfill(.result(result))
}
}
return promise
}
}
extension Promise {
private func enqueueDeliverBlock(_ block: (Either<T>) -> (), _ executionContext: ExecutionContext?) {
self.fulfillSemaphore.wait()
defer { self.fulfillSemaphore.signal() }
let ctx = executionContext != nil ? executionContext! : self.defaultExecutionContext
var (result, deliverBlocks) = self.internalValue
deliverBlocks.append((ctx, block))
self.internalValue = (result, deliverBlocks)
if let _result = result {
self.executeDeliverBlocks(_result)
}
}
private func executeDeliverBlocks(_ value: Either<T>) {
var (_, deliverBlocks) = self.internalValue
for deliverBlock in deliverBlocks {
let (executionContext, block) = deliverBlock
executionContext.async {
block(value)
}
}
deliverBlocks.removeAll()
}
private func validContext(_ context: ExecutionContext) -> ExecutionContext {
guard context.isEqual(ExecutionContextConstant.PlaceHolderContext) else {
return self.defaultExecutionContext
}
return context
}
}
private struct ExecutionContextConstant {
static let MainContext = DispatchQueue.main
static let DefaultContext = DispatchQueue.global(attributes: DispatchQueue.GlobalAttributes(rawValue: UInt64(Int(DispatchQueueAttributes.qosDefault.rawValue))))
static let PlaceHolderContext = DispatchQueue(label: "com.promise.placeHolder", attributes: DispatchQueueAttributes.concurrent)
}
|
f31fa281f6629e918ad6abb7d4e04356
| 36.381148 | 161 | 0.644831 | false | false | false | false |
wireapp/wire-ios-sync-engine
|
refs/heads/develop
|
Source/Synchronization/Strategies/TeamRolesDownloadRequestStrategy.swift
|
gpl-3.0
|
1
|
//
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
fileprivate extension Team {
static var predicateForTeamRolesNeedingToBeUpdated: NSPredicate = {
NSPredicate(format: "%K == YES AND %K != NULL", #keyPath(Team.needsToDownloadRoles), Team.remoteIdentifierDataKey()!)
}()
func updateRoles(with payload: [String: Any]) {
guard let rolesPayload = payload["conversation_roles"] as? [[String: Any]] else { return }
let existingRoles = self.roles
// Update or insert new roles
let newRoles = rolesPayload.compactMap {
Role.createOrUpdate(with: $0, teamOrConversation: .team(self), context: managedObjectContext!)
}
// Delete removed roles
let rolesToDelete = existingRoles.subtracting(newRoles)
rolesToDelete.forEach {
managedObjectContext?.delete($0)
}
}
}
public final class TeamRolesDownloadRequestStrategy: AbstractRequestStrategy, ZMContextChangeTrackerSource, ZMRequestGeneratorSource, ZMRequestGenerator, ZMDownstreamTranscoder {
private (set) var downstreamSync: ZMDownstreamObjectSync!
fileprivate unowned var syncStatus: SyncStatus
public init(withManagedObjectContext managedObjectContext: NSManagedObjectContext, applicationStatus: ApplicationStatus, syncStatus: SyncStatus) {
self.syncStatus = syncStatus
super.init(withManagedObjectContext: managedObjectContext, applicationStatus: applicationStatus)
downstreamSync = ZMDownstreamObjectSync(
transcoder: self,
entityName: Team.entityName(),
predicateForObjectsToDownload: Team.predicateForTeamRolesNeedingToBeUpdated,
filter: nil,
managedObjectContext: managedObjectContext
)
}
public override func nextRequest(for apiVersion: APIVersion) -> ZMTransportRequest? {
let request = downstreamSync.nextRequest(for: apiVersion)
if request == nil {
completeSyncPhaseIfNoTeam()
}
return request
}
public var contextChangeTrackers: [ZMContextChangeTracker] {
return [downstreamSync]
}
public var requestGenerators: [ZMRequestGenerator] {
return [self]
}
fileprivate let expectedSyncPhase = SyncPhase.fetchingTeamRoles
fileprivate var isSyncing: Bool {
return syncStatus.currentSyncPhase == self.expectedSyncPhase
}
private func completeSyncPhaseIfNoTeam() {
if self.syncStatus.currentSyncPhase == self.expectedSyncPhase && !self.downstreamSync.hasOutstandingItems {
self.syncStatus.finishCurrentSyncPhase(phase: self.expectedSyncPhase)
}
}
// MARK: - ZMDownstreamTranscoder
public func request(forFetching object: ZMManagedObject!, downstreamSync: ZMObjectSync!, apiVersion: APIVersion) -> ZMTransportRequest! {
guard downstreamSync as? ZMDownstreamObjectSync == self.downstreamSync, let team = object as? Team else { fatal("Wrong sync or object for: \(object.safeForLoggingDescription)") }
return TeamDownloadRequestFactory.requestToDownloadRoles(for: team.remoteIdentifier!, apiVersion: apiVersion)
}
public func update(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
guard downstreamSync as? ZMDownstreamObjectSync == self.downstreamSync,
let team = object as? Team,
let payload = response.payload?.asDictionary() as? [String: Any] else { return }
team.needsToDownloadRoles = false
team.updateRoles(with: payload)
if self.isSyncing {
self.syncStatus.finishCurrentSyncPhase(phase: self.expectedSyncPhase)
}
}
public func delete(_ object: ZMManagedObject!, with response: ZMTransportResponse!, downstreamSync: ZMObjectSync!) {
// pass
}
}
|
b715d7000f0eb3ee2fcb45b59a5c6925
| 39.513514 | 186 | 0.71203 | false | false | false | false |
brunophilipe/Noto
|
refs/heads/master
|
Noto/Misc/MetricsTextStorage.swift
|
gpl-3.0
|
1
|
//
// MetricsTextStorage.swift
// Noto
//
// Created by Bruno Philipe on 5/8/17.
// Copyright © 2017 Bruno Philipe. All rights reserved.
//
import Foundation
class MetricsTextStorage: ConcreteTextStorage
{
private var textMetrics = StringMetrics()
private var _isUpdatingMetrics = false
var observer: TextStorageObserver? = nil
var metrics: StringMetrics
{
return textMetrics
}
var isUpdatingMetrics: Bool
{
return _isUpdatingMetrics
}
override func replaceCharacters(in range: NSRange, with str: String)
{
let stringLength = (string as NSString).length
let delta = (str as NSString).length - range.length
let testRange = range.expanding(byEncapsulating: 1, maxLength: stringLength)
_isUpdatingMetrics = true
let oldMetrics = textMetrics
if let observer = self.observer
{
observer.textStorageWillUpdateMetrics(self)
}
let stringBeforeChange = attributedSubstring(from: testRange).string
super.replaceCharacters(in: range, with: str)
let rangeAfterChange = testRange.expanding(by: delta).meaningfulRange
let stringAfterChange = (stringLength + delta) > 0 ? attributedSubstring(from: rangeAfterChange).string : ""
DispatchQueue.global(qos: .utility).async
{
let metricsBeforeChange = stringBeforeChange.metrics
let metricsAfterChange = stringAfterChange.metrics
self.textMetrics = self.textMetrics - metricsBeforeChange + metricsAfterChange
self._isUpdatingMetrics = false
if let observer = self.observer
{
DispatchQueue.main.async
{
observer.textStorage(self, didUpdateMetrics: self.metrics, fromOldMetrics: oldMetrics)
}
}
}
}
}
protocol TextStorageObserver
{
func textStorageWillUpdateMetrics(_ textStorage: MetricsTextStorage)
func textStorage(_ textStorage: MetricsTextStorage, didUpdateMetrics: StringMetrics, fromOldMetrics: StringMetrics)
}
|
401544284cc89625c97b0926767f99a3
| 23.986667 | 116 | 0.751868 | false | false | false | false |
KyoheiG3/SpringIndicator
|
refs/heads/master
|
SpringIndicator/CAPropertyAnimation+Key.swift
|
mit
|
1
|
//
// CAPropertyAnimation+Key.swift
// SpringIndicator
//
// Created by Kyohei Ito on 2017/09/25.
// Copyright © 2017年 kyohei_ito. All rights reserved.
//
import UIKit
extension CAPropertyAnimation {
enum Key: String {
case strokeStart = "strokeStart"
case strokeEnd = "strokeEnd"
case strokeColor = "strokeColor"
case rotationZ = "transform.rotation.z"
case scale = "transform.scale"
}
convenience init(key: Key) {
self.init(keyPath: key.rawValue)
}
}
|
e536ea8f141902681d51e22c4f780ec3
| 21.782609 | 54 | 0.64313 | false | false | false | false |
quangvu1994/Exchange
|
refs/heads/master
|
Exchange/Extension /CollapsibleTableViewHeader.swift
|
mit
|
1
|
//
// CollapsibleTableViewHeader.swift
// Exchange
//
// Created by Quang Vu on 7/27/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
protocol CollapsibleTableViewHeaderDelegate {
func toggleSection(header: CollapsibleTableViewHeader, section: Int)
}
class CollapsibleTableViewHeader: UITableViewHeaderFooterView {
var delegate: CollapsibleTableViewHeaderDelegate?
var section: Int = 0
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(CollapsibleTableViewHeader.selectHeaderAction(gestureRecognizer:))))
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func selectHeaderAction(gestureRecognizer: UITapGestureRecognizer){
let cell = gestureRecognizer.view as! CollapsibleTableViewHeader
delegate?.toggleSection(header: self, section: cell.section)
}
func customInit(title: String ,section: Int, delegate: CollapsibleTableViewHeaderDelegate) {
self.textLabel?.text = title
self.section = section
self.delegate = delegate
}
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel?.textColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
self.contentView.backgroundColor = UIColor(red: 234/255, green: 234/255, blue: 234/255, alpha: 1.0)
}
}
|
16620b6f06f0ae247325350e7365deef
| 32.369565 | 157 | 0.708795 | false | false | false | false |
brunomorgado/ScrollableAnimation
|
refs/heads/master
|
ScrollableAnimation/Tests/ScrollableAnimationTests.swift
|
mit
|
1
|
//
// ScrollableAnimationTests.swift
// ScrollableAnimationExample
//
// Created by Bruno Morgado on 30/12/14.
// Copyright (c) 2014 kocomputer. All rights reserved.
//
import UIKit
import XCTest
import ScrollableAnimationExample
class ScrollableAnimationTests: XCTestCase {
let animationController: ScrollableAnimationController = ScrollableAnimationController()
override func setUp() {
super.setUp()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testAddScrollableAnimation() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = toValue
let completionExpectation = expectationWithDescription("finished")
let translation = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation, forKey: nil, withController: self.animationController)
self.animationController.updateAnimatablesForOffset(animationDistance) {
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
completionExpectation.fulfill()
}
waitForExpectationsWithTimeout(2, { error in
XCTAssertNil(error, "Error")
})
}
func testRemoveAllScrollableAnimations() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let translation1 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
let translation2 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeAllScrollableAnimationsWithController(animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: nil, withController: self.animationController)
mockAnimatable.layer.addScrollableAnimation(translation2, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeAllScrollableAnimationsWithController(animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
}
func testRemoveScrollableAnimationForKey() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let animationKey = "animationKey"
let completionExpectation = expectationWithDescription("finished")
let translation1 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
let translation2 = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: animationKey, withController: self.animationController)
mockAnimatable.layer.removeScrollableAnimationForKey(animationKey, withController: animationController)
self.animationController.updateAnimatablesForOffset(animationDistance, nil)
XCTAssertEqual(mockAnimatable.layer.position, animatableExpectedPosition)
mockAnimatable.layer.addScrollableAnimation(translation1, forKey: animationKey, withController: self.animationController)
mockAnimatable.layer.addScrollableAnimation(translation2, forKey: nil, withController: self.animationController)
mockAnimatable.layer.removeScrollableAnimationForKey(animationKey, withController: animationController)
self.animationController.updateAnimatablesForOffset(animationDistance) {
XCTAssertEqual(mockAnimatable.layer.position, toValue)
completionExpectation.fulfill()
}
waitForExpectationsWithTimeout(2, { error in
XCTAssertNil(error, "Error")
})
}
func testScrollableAnimationForKey() {
var mockAnimatable = UIView(frame: CGRectMake(0, 0, 100, 100))
let animationDistance = Float(300)
let fromValue = mockAnimatable.layer.position
let toValue = CGPointMake(mockAnimatable.layer.position.x, mockAnimatable.layer.position.y + CGFloat(animationDistance))
let animatableExpectedPosition = fromValue
let animationKey = "animationKey"
let translation = self.getMockTranslationFromValue(fromValue, toValue: toValue, withDistance: animationDistance)
}
// MARK: - Helper methods
private func getMockTranslationFromValue(fromValue: CGPoint, toValue: CGPoint, withDistance distance: Float) -> ScrollableBasicAnimation {
let translation = ScrollableBasicAnimation(keyPath: "position")
translation.beginOffset = 0
translation.distance = distance
translation.fromValue = NSValue(CGPoint: fromValue)
translation.toValue = NSValue(CGPoint: toValue)
return translation
}
}
|
e03ab96a03e6a482fd5a7f01ec932d0a
| 49.463415 | 142 | 0.736266 | false | true | false | false |
joeytat/JWStarRating
|
refs/heads/master
|
Classes/JWStarRatingView.swift
|
mit
|
1
|
//
// JWStarRatingView.swift
// WapaKit
//
// Created by Joey on 1/21/15.
// Copyright (c) 2015 Joeytat. All rights reserved.
//
import UIKit
@IBDesignable class JWStarRatingView: UIView {
@IBInspectable var starColor: UIColor = UIColor(red: 200.0/255.0, green: 200.0/255.0, blue: 200.0/255.0, alpha: 1)
@IBInspectable var starHighlightColor: UIColor = UIColor(red: 88.0/255.0, green: 88.0/255.0, blue: 88.0/255.0, alpha: 1)
@IBInspectable var starCount:Int = 5
@IBInspectable var spaceBetweenStar:CGFloat = 10.0
#if TARGET_INTERFACE_BUILDER
override func willMoveToSuperview(newSuperview: UIView?) {
let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar)
addSubview(starRating)
}
#else
override func awakeFromNib() {
super.awakeFromNib()
let starRating = JWStarRating(frame: self.bounds, starCount: self.starCount, starColor: self.starColor, starHighlightColor: self.starHighlightColor, spaceBetweenStar: self.spaceBetweenStar)
starRating.addTarget(self, action: #selector(JWStarRatingView.valueChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)
addSubview(starRating)
}
#endif
func valueChanged(starRating:JWStarRating){
// Do something with the value...
print("Value changed \(starRating.ratedStarIndex)")
}
}
|
b8575ecaee10c7bc98f54d45634cf95a
| 38.051282 | 197 | 0.701248 | false | false | false | false |
objecthub/swift-lispkit
|
refs/heads/master
|
Sources/LispKit/Primitives/ControlFlowLibrary.swift
|
apache-2.0
|
1
|
//
// ControlFlowLibrary.swift
// LispKit
//
// Created by Matthias Zenger on 22/01/2016.
// Copyright © 2016 ObjectHub. 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.
//
public final class ControlFlowLibrary: NativeLibrary {
/// Name of the library.
public override class var name: [String] {
return ["lispkit", "control"]
}
/// Declarations of the library.
public override func declarations() {
self.define(SpecialForm("begin", self.compileBegin))
self.define(SpecialForm("let", self.compileLet))
self.define(SpecialForm("let*", self.compileLetStar))
self.define(SpecialForm("letrec", self.compileLetRec))
self.define(SpecialForm("letrec*", self.compileLetRecStar))
self.define(SpecialForm("let-values", self.compileLetValues))
self.define(SpecialForm("let*-values", self.compileLetStarValues))
self.define(SpecialForm("letrec-values", self.compileLetRecValues))
self.define(SpecialForm("let-optionals", self.compileLetOptionals))
self.define(SpecialForm("let*-optionals", self.compileLetStarOptionals))
self.define(SpecialForm("let-keywords", self.compileLetKeywords))
self.define(SpecialForm("let*-keywords", self.compileLetStarKeywords))
self.define(SpecialForm("let-syntax", self.compileLetSyntax))
self.define(SpecialForm("letrec-syntax", self.compileLetRecSyntax))
self.define(SpecialForm("do", self.compileDo))
self.define(SpecialForm("if", self.compileIf))
self.define(SpecialForm("when", self.compileWhen))
self.define(SpecialForm("unless", self.compileUnless))
self.define(SpecialForm("cond", self.compileCond))
self.define(SpecialForm("case", self.compileCase))
}
private func splitBindings(_ bindingList: Expr) throws -> (Expr, Expr) {
var symbols = Exprs()
var exprs = Exprs()
var bindings = bindingList
while case .pair(let binding, let rest) = bindings {
guard case .pair(.symbol(let sym), .pair(let expr, .null)) = binding else {
throw RuntimeError.eval(.malformedBinding, binding, bindingList)
}
symbols.append(.symbol(sym))
exprs.append(expr)
bindings = rest
}
guard bindings.isNull else {
throw RuntimeError.eval(.malformedBindings, bindingList)
}
return (Expr.makeList(symbols), Expr.makeList(exprs))
}
private func compileBegin(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, let exprs) = expr else {
preconditionFailure("malformed begin")
}
return try compiler.compileSeq(exprs,
in: env,
inTailPos: tail,
localDefine: false)
}
private func compileLet(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "let", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
var res = false
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileBindings(first,
in: env,
atomic: true,
predef: false)
res = try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
group.finalize()
case .symbol(let sym):
guard case .pair(let bindings, let rest) = body else {
throw RuntimeError.argumentCount(of: "let", min: 2, expr: expr)
}
let (params, exprs) = try splitBindings(bindings)
let group = BindingGroup(owner: compiler, parent: env)
let index = group.allocBindingFor(sym).index
compiler.emit(.pushUndef)
compiler.emit(.makeLocalVariable(index))
let nameIdx = compiler.registerConstant(first)
try compiler.compileLambda(nameIdx,
params,
rest,
Env(group))
compiler.emit(.setLocalValue(index))
// res = try compiler.compile(.pair(first, exprs),
// in: Env(group),
// inTailPos: tail)
// Make frame for closure invocation
let pushFrameIp = compiler.emit(.makeFrame)
compiler.emit(.pushLocalValue(index))
// Push arguments and call function
if compiler.call(try compiler.compileExprs(exprs, in: env), inTailPos: tail) {
// Remove make_frame if this was a tail call
compiler.patch(.noOp, at: pushFrameIp)
res = true
} else {
res = false
}
default:
throw RuntimeError.type(first, expected: [.listType, .symbolType])
}
if !res && compiler.numLocals > initialLocals {
compiler.emit(.reset(initialLocals, compiler.numLocals - initialLocals))
}
compiler.numLocals = initialLocals
return res
}
private func compileLetStar(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "let*", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileBindings(first, in: env, atomic: false, predef: false)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetRec(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "letrec", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileBindings(first,
in: env,
atomic: true,
predef: true,
postset: true)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetRecStar(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "letrec*", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileBindings(first, in: env, atomic: true, predef: true)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetValues(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "let-values", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileMultiBindings(first, in: env, atomic: true)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetStarValues(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "let*-values", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileMultiBindings(first, in: env, atomic: false, predef: false)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetRecValues(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "letrec-values", min: 1, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(body, in: env, inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileMultiBindings(first, in: env, atomic: false, predef: true)
let res = try compiler.compileSeq(body, in: Env(group), inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetOptionals(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else {
throw RuntimeError.argumentCount(of: "let-optionals", min: 2, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(.pair(optlist, body),
in: env,
inTailPos: tail)
case .pair(_, _):
try compiler.compile(optlist, in: env, inTailPos: false)
let group = try compiler.compileOptionalBindings(first, in: env, optenv: env)
let res = try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetStarOptionals(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else {
throw RuntimeError.argumentCount(of: "let*-optionals", min: 2, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(.pair(optlist, body),
in: env,
inTailPos: tail)
case .pair(_, _):
try compiler.compile(optlist, in: env, inTailPos: false)
let group = try compiler.compileOptionalBindings(first, in: env, optenv: nil)
let res = try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetKeywords(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else {
throw RuntimeError.argumentCount(of: "let-keywords", min: 2, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(.pair(optlist, body),
in: env,
inTailPos: tail)
case .pair(_, _):
try compiler.compile(optlist, in: env, inTailPos: false)
let group = try self.compileKeywordBindings(compiler, first, in: env, atomic: true)
compiler.emit(.pop)
let res = try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetStarKeywords(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let optlist, .pair(let first, let body))) = expr else {
throw RuntimeError.argumentCount(of: "let*-keywords", min: 2, expr: expr)
}
let initialLocals = compiler.numLocals
switch first {
case .null:
return try compiler.compileSeq(.pair(optlist, body),
in: env,
inTailPos: tail)
case .pair(_, _):
try compiler.compile(optlist, in: env, inTailPos: false)
let group = try self.compileKeywordBindings(compiler, first, in: env, atomic: false)
compiler.emit(.pop)
let res = try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
return compiler.finalizeBindings(group, exit: res, initialLocals: initialLocals)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileKeywordBindings(_ compiler: Compiler,
_ bindingList: Expr,
in lenv: Env,
atomic: Bool) throws -> BindingGroup {
let group = BindingGroup(owner: compiler, parent: lenv)
let env = atomic ? lenv : .local(group)
var bindings = bindingList
var prevIndex = -1
let initialIp = compiler.emitPlaceholder()
let backfillIp = compiler.offsetToNext(0)
var keywords = [Symbol : Symbol]()
// Backfill keyword bindings with defaults
while case .pair(let binding, let rest) = bindings {
let sym: Symbol
let expr: Expr
switch binding {
case .pair(.symbol(let s), .pair(let def, .null)):
sym = s
expr = def
case .pair(.symbol(let s), .pair(.symbol(let key), .pair(let def, .null))):
keywords[s] = key
sym = s
expr = def
default:
throw RuntimeError.eval(.malformedBinding, binding, bindingList)
}
compiler.emit(.pushUndef)
let pushValueIp = compiler.emitPlaceholder()
compiler.emit(.eq)
let alreadySetIp = compiler.emitPlaceholder()
try compiler.compile(expr, in: env, inTailPos: false)
let binding = group.allocBindingFor(sym)
guard binding.index > prevIndex else {
throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList)
}
compiler.emit(binding.isValue ? .setLocal(binding.index) : .setLocalValue(binding.index))
compiler.patch(binding.isValue ? .pushLocal(binding.index) : .pushLocalValue(binding.index),
at: pushValueIp)
compiler.patch(.branchIfNot(compiler.offsetToNext(alreadySetIp)), at: alreadySetIp)
prevIndex = binding.index
bindings = rest
}
guard bindings.isNull else {
throw RuntimeError.eval(.malformedBindings, bindingList)
}
let finalIp = compiler.emitPlaceholder()
compiler.patch(.branch(compiler.offsetToNext(initialIp)), at: initialIp)
// Allocate space for all the bindings
bindings = bindingList
while case .pair(.pair(.symbol(let sym), _), let rest) = bindings {
let binding = group.allocBindingFor(sym)
compiler.emit(.pushUndef)
compiler.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index))
bindings = rest
}
// Process keyword list
bindings = bindingList
let loopIp = compiler.emit(.dup)
compiler.emit(.isNull)
let listEmptyIp = compiler.emitPlaceholder()
compiler.emit(.deconsKeyword)
while case .pair(.pair(.symbol(let sym), _), let rest) = bindings {
let binding = group.allocBindingFor(sym)
compiler.emit(.dup)
if let key = keywords[sym] {
compiler.pushConstant(.symbol(key))
} else {
compiler.pushConstant(.symbol(compiler.context.symbols.intern(sym.identifier + ":")))
}
compiler.emit(.eq)
let keywordCompIp = compiler.emitPlaceholder()
compiler.emit(.pop)
compiler.emit(binding.isValue ? .setLocal(binding.index) : .makeLocalVariable(binding.index))
compiler.emit(.branch(-compiler.offsetToNext(loopIp)))
compiler.patch(.branchIfNot(compiler.offsetToNext(keywordCompIp)), at: keywordCompIp)
bindings = rest
}
compiler.emit(.raiseError(EvalError.unknownKeyword.rawValue, 2))
compiler.patch(.branchIf(compiler.offsetToNext(listEmptyIp)), at: listEmptyIp)
// Jumop to the default backfill
compiler.emit(.branch(-compiler.offsetToNext(backfillIp)))
// Patch instructions jumping to the end
compiler.patch(.branch(compiler.offsetToNext(finalIp)), at: finalIp)
return group
}
private func compileLetSyntax(_ compiler: Compiler,
expr: Expr,
env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "let-syntax", min: 1, expr: expr)
}
switch first {
case .null:
return try compiler.compileSeq(body,
in: env,
inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileMacros(first,
in: env,
recursive: false)
return try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileLetRecSyntax(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let first, let body)) = expr else {
throw RuntimeError.argumentCount(of: "letrec-syntax", min: 1, expr: expr)
}
switch first {
case .null:
return try compiler.compileSeq(body,
in: env,
inTailPos: tail)
case .pair(_, _):
let group = try compiler.compileMacros(first,
in: env,
recursive: true)
return try compiler.compileSeq(body,
in: Env(group),
inTailPos: tail)
default:
throw RuntimeError.type(first, expected: [.listType])
}
}
private func compileDo(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
// Decompose expression into bindings, exit, and body
guard case .pair(_, .pair(let bindingList, .pair(let exit, let body))) = expr else {
throw RuntimeError.argumentCount(of: "do", min: 2, expr: expr)
}
// Extract test and terminal expressions
guard case .pair(let test, let terminal) = exit else {
throw RuntimeError.eval(.malformedTest, exit)
}
let initialLocals = compiler.numLocals
// Setup bindings
let group = BindingGroup(owner: compiler, parent: env)
var bindings = bindingList
var prevIndex = -1
var doBindings = [Int]()
var stepExprs = Exprs()
// Compile initial bindings
while case .pair(let binding, let rest) = bindings {
guard case .pair(.symbol(let sym), .pair(let start, let optStep)) = binding else {
throw RuntimeError.eval(.malformedBinding, binding, bindingList)
}
try compiler.compile(start, in: env, inTailPos: false)
let index = group.allocBindingFor(sym).index
guard index > prevIndex else {
throw RuntimeError.eval(.duplicateBinding, .symbol(sym), bindingList)
}
compiler.emit(.makeLocalVariable(index))
switch optStep {
case .pair(let step, .null):
doBindings.append(index)
stepExprs.append(step)
case .null:
break;
default:
throw RuntimeError.eval(.malformedBinding, binding, bindingList)
}
prevIndex = index
bindings = rest
}
guard bindings.isNull else {
throw RuntimeError.eval(.malformedBindings, bindingList)
}
// Compile test expression
let testIp = compiler.offsetToNext(0)
try compiler.compile(test, in: Env(group), inTailPos: false)
let exitJumpIp = compiler.emitPlaceholder()
// Compile body
try compiler.compileSeq(body, in: Env(group), inTailPos: false)
compiler.emit(.pop)
// Compile step expressions and update bindings
for step in stepExprs {
try compiler.compile(step, in: Env(group), inTailPos: false)
}
for index in doBindings.reversed() {
compiler.emit(.setLocalValue(index))
}
// Loop
compiler.emit(.branch(-compiler.offsetToNext(testIp)))
// Exit if the test expression evaluates to true
compiler.patch(.branchIf(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp)
// Compile terminal expressions
let res = try compiler.compileSeq(terminal,
in: Env(group),
inTailPos: tail)
// Remove bindings from stack
if !res && compiler.numLocals > initialLocals {
compiler.emit(.reset(initialLocals, compiler.numLocals - initialLocals))
}
compiler.numLocals = initialLocals
return res
}
private func compileIf(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let cond, .pair(let thenp, let alternative))) = expr else {
throw RuntimeError.argumentCount(of: "if", min: 2, expr: expr)
}
var elsep = Expr.void
if case .pair(let ep, .null) = alternative {
elsep = ep
}
try compiler.compile(cond, in: env, inTailPos: false)
let elseJumpIp = compiler.emitPlaceholder()
// Compile if in tail position
if try compiler.compile(elsep, in: env, inTailPos: tail) {
compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp)
return try compiler.compile(thenp, in: env, inTailPos: true)
}
// Compile if in non-tail position
let exitJumpIp = compiler.emitPlaceholder()
compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp)
if try compiler.compile(thenp, in: env, inTailPos: tail) {
compiler.patch(.return, at: exitJumpIp)
return true
}
compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp)
return false
}
private func compileWhen(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let cond, let exprs)) = expr else {
throw RuntimeError.argumentCount(of: "when", min: 1, expr: expr)
}
try compiler.compile(cond, in: env, inTailPos: false)
let elseJumpIp = compiler.emitPlaceholder()
compiler.emit(.pushVoid)
let exitJumpIp = compiler.emitPlaceholder()
compiler.patch(.branchIf(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp)
if try compiler.compileSeq(exprs, in: env, inTailPos: tail) {
compiler.patch(.return, at: exitJumpIp)
return true
}
compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp)
return false
}
private func compileUnless(_ compiler: Compiler,
expr: Expr,
env: Env,
tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let cond, let exprs)) = expr else {
throw RuntimeError.argumentCount(of: "unless", min: 1, expr: expr)
}
try compiler.compile(cond, in: env, inTailPos: false)
let elseJumpIp = compiler.emitPlaceholder()
compiler.emit(.pushVoid)
let exitJumpIp = compiler.emitPlaceholder()
compiler.patch(.branchIfNot(compiler.offsetToNext(elseJumpIp)), at: elseJumpIp)
if try compiler.compileSeq(exprs, in: env, inTailPos: tail) {
compiler.patch(.return, at: exitJumpIp)
return true
}
compiler.patch(.branch(compiler.offsetToNext(exitJumpIp)), at: exitJumpIp)
return false
}
private func compileCond(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
// Extract case list
guard case .pair(_, let caseList) = expr else {
preconditionFailure()
}
// Keep track of jumps for successful cases
var exitJumps = [Int]()
var exitOrJumps = [Int]()
var cases = caseList
// Track if there was an else case and whether there was a tail call in the else case
var elseCaseTailCall: Bool? = nil
// Iterate through all cases
while case .pair(let cas, let rest) = cases {
switch cas {
case .pair(.symbol(let s), let exprs) where s.root == compiler.context.symbols.else:
guard rest == .null else {
throw RuntimeError.eval(.malformedCondClause, cases)
}
elseCaseTailCall = try compiler.compileSeq(exprs,
in: env,
inTailPos: tail)
case .pair(let test, .null):
try compiler.compile(test, in: env, inTailPos: false)
exitOrJumps.append(compiler.emitPlaceholder())
case .pair(let test, .pair(.symbol(let s), .pair(let proc, .null)))
where s.root == compiler.context.symbols.doubleArrow:
// Compile condition
try compiler.compile(test, in: env, inTailPos: false)
// Jump if it's false or inject stack frame
let escapeIp = compiler.emitPlaceholder()
// Inject stack frame
let pushFrameIp = compiler.emit(.injectFrame)
// Compile procedure
try compiler.compile(proc, in: env, inTailPos: false)
// Swap procedure with argument (= condition)
compiler.emit(.swap)
// Call procedure
if compiler.call(1, inTailPos: tail) {
// Remove InjectFrame if this was a tail call
compiler.patch(.noOp, at: pushFrameIp)
} else {
exitJumps.append(compiler.emitPlaceholder())
}
compiler.patch(.keepOrBranchIfNot(compiler.offsetToNext(escapeIp)), at: escapeIp)
case .pair(let test, let exprs):
try compiler.compile(test, in: env, inTailPos: false)
let escapeIp = compiler.emitPlaceholder()
if !(try compiler.compileSeq(exprs,
in: env,
inTailPos: tail)) {
exitJumps.append(compiler.emitPlaceholder())
}
compiler.patch(.branchIfNot(compiler.offsetToNext(escapeIp)), at: escapeIp)
default:
throw RuntimeError.eval(.malformedCondClause, cas)
}
cases = rest
}
// Was there an else case?
if let wasTailCall = elseCaseTailCall {
// Did the else case and all other cases have tail calls?
if wasTailCall && exitJumps.count == 0 && exitOrJumps.count == 0 {
return true
}
} else {
// There was no else case: return false
compiler.emit(.pushFalse)
}
// Resolve jumps to current instruction
for ip in exitJumps {
compiler.patch(.branch(compiler.offsetToNext(ip)), at: ip)
}
for ip in exitOrJumps {
compiler.patch(.or(compiler.offsetToNext(ip)), at: ip)
}
return false
}
private func compileCase(_ compiler: Compiler, expr: Expr, env: Env, tail: Bool) throws -> Bool {
guard case .pair(_, .pair(let key, let caseList)) = expr else {
throw RuntimeError.argumentCount(of: "case", min: 3, expr: expr)
}
// Keep track of jumps for successful cases
var exitJumps = [Int]()
var cases = caseList
// Track if there was an else case and whether there was a tail call in the else case
var elseCaseTailCall: Bool? = nil
// Compile key
try compiler.compile(key, in: env, inTailPos: false)
// Compile cases
while case .pair(let cas, let rest) = cases {
switch cas {
case .pair(.symbol(let s), .pair(.symbol(let t), .pair(let proc, .null)))
where s.root == compiler.context.symbols.else &&
t.root == compiler.context.symbols.doubleArrow:
guard rest == .null else {
throw RuntimeError.eval(.malformedCaseClause, cases)
}
// Inject stack frame
let pushFrameIp = compiler.emit(.injectFrame)
// Compile procedure
try compiler.compile(proc, in: env, inTailPos: false)
// Swap procedure with argument (= condition)
compiler.emit(.swap)
// Call procedure
if compiler.call(1, inTailPos: tail) {
// Remove InjectFrame if this was a tail call
compiler.patch(.noOp, at: pushFrameIp)
elseCaseTailCall = true
} else {
elseCaseTailCall = false
}
case .pair(.symbol(let s), let exprs) where s.root == compiler.context.symbols.else:
guard rest == .null else {
throw RuntimeError.eval(.malformedCaseClause, cases)
}
compiler.emit(.pop)
elseCaseTailCall = try compiler.compileSeq(exprs,
in: env,
inTailPos: tail)
case .pair(var keys, .pair(.symbol(let s), .pair(let proc, .null)))
where s.root == compiler.context.symbols.doubleArrow:
// Check keys
var positiveJumps = [Int]()
while case .pair(let value, let next) = keys {
compiler.emit(.dup)
try compiler.pushValue(value)
compiler.emit(.eqv)
positiveJumps.append(compiler.emitPlaceholder())
keys = next
}
guard keys.isNull else {
throw RuntimeError.eval(.malformedCaseClause, cas)
}
let jumpToNextCase = compiler.emitPlaceholder()
for ip in positiveJumps {
compiler.patch(.branchIf(compiler.offsetToNext(ip)), at: ip)
}
// Inject stack frame
let pushFrameIp = compiler.emit(.injectFrame)
// Compile procedure
try compiler.compile(proc, in: env, inTailPos: false)
// Swap procedure with argument (= condition)
compiler.emit(.swap)
// Call procedure
if compiler.call(1, inTailPos: tail) {
// Remove InjectFrame if this was a tail call
compiler.patch(.noOp, at: pushFrameIp)
} else {
exitJumps.append(compiler.emitPlaceholder())
}
compiler.patch(.branch(compiler.offsetToNext(jumpToNextCase)), at: jumpToNextCase)
case .pair(var keys, let exprs):
var positiveJumps = [Int]()
while case .pair(let value, let next) = keys {
compiler.emit(.dup)
try compiler.pushValue(value)
compiler.emit(.eqv)
positiveJumps.append(compiler.emitPlaceholder())
keys = next
}
guard keys.isNull else {
throw RuntimeError.eval(.malformedCaseClause, cas)
}
let jumpToNextCase = compiler.emitPlaceholder()
for ip in positiveJumps {
compiler.patch(.branchIf(compiler.offsetToNext(ip)), at: ip)
}
compiler.emit(.pop)
if !(try compiler.compileSeq(exprs,
in: env,
inTailPos: tail)) {
exitJumps.append(compiler.emitPlaceholder())
}
compiler.patch(.branch(compiler.offsetToNext(jumpToNextCase)), at: jumpToNextCase)
default:
throw RuntimeError.eval(.malformedCaseClause, cas)
}
cases = rest
}
// Was there an else case?
if let wasTailCall = elseCaseTailCall {
// Did the else case and all other cases have tail calls?
if wasTailCall && exitJumps.count == 0 {
return true
}
} else {
// There was no else case: drop key and return false
compiler.emit(.pop)
compiler.emit(.pushFalse)
}
// Resolve jumps to current instruction
for ip in exitJumps {
compiler.patch(.branch(compiler.offsetToNext(ip)), at: ip)
}
return false
}
}
|
373d44cbd621b54dad020fa5469c142b
| 41.594692 | 100 | 0.583416 | false | false | false | false |
brentsimmons/Evergreen
|
refs/heads/ios-candidate
|
Shared/Images/ImageDownloader.swift
|
mit
|
1
|
//
// ImageDownloader.swift
// NetNewsWire
//
// Created by Brent Simmons on 11/25/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import os.log
import RSCore
import RSWeb
extension Notification.Name {
static let ImageDidBecomeAvailable = Notification.Name("ImageDidBecomeAvailableNotification") // UserInfoKey.url
}
final class ImageDownloader {
private var log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: "ImageDownloader")
private let folder: String
private var diskCache: BinaryDiskCache
private let queue: DispatchQueue
private var imageCache = [String: Data]() // url: image
private var urlsInProgress = Set<String>()
private var badURLs = Set<String>() // That return a 404 or whatever. Just skip them in the future.
init(folder: String) {
self.folder = folder
self.diskCache = BinaryDiskCache(folder: folder)
self.queue = DispatchQueue(label: "ImageDownloader serial queue - \(folder)")
}
@discardableResult
func image(for url: String) -> Data? {
if let data = imageCache[url] {
return data
}
findImage(url)
return nil
}
}
private extension ImageDownloader {
func cacheImage(_ url: String, _ image: Data) {
imageCache[url] = image
postImageDidBecomeAvailableNotification(url)
}
func findImage(_ url: String) {
guard !urlsInProgress.contains(url) && !badURLs.contains(url) else {
return
}
urlsInProgress.insert(url)
readFromDisk(url) { (image) in
if let image = image {
self.cacheImage(url, image)
self.urlsInProgress.remove(url)
return
}
self.downloadImage(url) { (image) in
if let image = image {
self.cacheImage(url, image)
}
self.urlsInProgress.remove(url)
}
}
}
func readFromDisk(_ url: String, _ completion: @escaping (Data?) -> Void) {
queue.async {
if let data = self.diskCache[self.diskKey(url)], !data.isEmpty {
DispatchQueue.main.async {
completion(data)
}
return
}
DispatchQueue.main.async {
completion(nil)
}
}
}
func downloadImage(_ url: String, _ completion: @escaping (Data?) -> Void) {
guard let imageURL = URL(string: url) else {
completion(nil)
return
}
downloadUsingCache(imageURL) { (data, response, error) in
if let data = data, !data.isEmpty, let response = response, response.statusIsOK, error == nil {
self.saveToDisk(url, data)
completion(data)
return
}
if let response = response as? HTTPURLResponse, response.statusCode >= HTTPResponseCode.badRequest && response.statusCode <= HTTPResponseCode.notAcceptable {
self.badURLs.insert(url)
}
if let error = error {
os_log(.info, log: self.log, "Error downloading image at %@: %@.", url, error.localizedDescription)
}
completion(nil)
}
}
func saveToDisk(_ url: String, _ data: Data) {
queue.async {
self.diskCache[self.diskKey(url)] = data
}
}
func diskKey(_ url: String) -> String {
return url.md5String
}
func postImageDidBecomeAvailableNotification(_ url: String) {
DispatchQueue.main.async {
NotificationCenter.default.post(name: .ImageDidBecomeAvailable, object: self, userInfo: [UserInfoKey.url: url])
}
}
}
|
a479912f557c1c284c6a4dee5f0e27e2
| 21.34965 | 160 | 0.692428 | false | false | false | false |
gizmosachin/VolumeBar
|
refs/heads/master
|
Sources/Internal/SystemVolumeManager.swift
|
mit
|
1
|
//
// SystemVolumeManager.swift
//
// Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
import AVFoundation
@objc internal protocol SystemVolumeObserver {
func volumeChanged(to volume: Float)
}
internal final class SystemVolumeManager: NSObject {
fileprivate let observers: NSHashTable<SystemVolumeObserver>
fileprivate var isObservingSystemVolumeChanges: Bool = false
internal override init() {
observers = NSHashTable<SystemVolumeObserver>.weakObjects()
super.init()
startObservingSystemVolumeChanges()
startObservingApplicationStateChanges()
}
deinit {
observers.removeAllObjects()
stopObservingSystemVolumeChanges()
stopObservingApplicationStateChanges()
}
public func volumeChanged(to volume: Float) {
for case let observer as SystemVolumeObserver in observers.objectEnumerator() {
observer.volumeChanged(to: volume)
}
}
}
// System Volume Changes
internal extension SystemVolumeManager {
func startObservingSystemVolumeChanges() {
try? AVAudioSession.sharedInstance().setActive(true)
if !isObservingSystemVolumeChanges {
// Observe system volume changes
AVAudioSession.sharedInstance().addObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume), options: [.old, .new], context: nil)
// We need to manually set this to avoid adding ourselves as an observer twice.
// This can happen if VolumeBar is started and the app has just launched.
// Without this, KVO retains us and we crash when system volume changes after stop() is called. :(
isObservingSystemVolumeChanges = true
}
}
func stopObservingSystemVolumeChanges() {
// Stop observing system volume changes
if isObservingSystemVolumeChanges {
AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume))
isObservingSystemVolumeChanges = false
}
}
/// Observe changes in volume.
///
/// This method is called when the user presses either of the volume buttons.
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
let volume = AVAudioSession.sharedInstance().outputVolume
volumeChanged(to: volume)
}
}
// Application State Changes
internal extension SystemVolumeManager {
func startObservingApplicationStateChanges() {
// Add application state observers
NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil)
}
func stopObservingApplicationStateChanges() {
// Remove application state observers
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
/// Observe when the application background state changes.
@objc func applicationWillResignActive(notification: Notification) {
// Stop observing volume while in the background
stopObservingSystemVolumeChanges()
}
@objc func applicationDidBecomeActive(notification: Notification) {
// Restart session after becoming active
startObservingSystemVolumeChanges()
}
}
// Volume Manager Observers
internal extension SystemVolumeManager {
func addObserver(_ observer: SystemVolumeObserver) {
observers.add(observer)
}
func removeObserver(_ observer: SystemVolumeObserver) {
observers.remove(observer)
}
}
|
324667827273704d88c880c8ebe72517
| 37.062992 | 194 | 0.779892 | false | false | false | false |
Camvergence/AssetFlow
|
refs/heads/master
|
PhotosPlus/PhotosPlus/UIImageView_PHAsset.swift
|
mit
|
3
|
//
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
#if os(iOS) || os(tvOS)
import Foundation
import UIKit
import Photos
extension UIImageView {
public func loadAsset(_ asset: PHAsset?,
version: PHImageRequestOptionsVersion = .current,
options: PHImageRequestOptions,
imageManager: PHImageManager? = nil,
completion: @escaping () -> Void) -> PHImageRequestID {
guard let asset = asset
else {
return PHInvalidImageRequestID
}
let manager = imageManager ?? PHImageManager.default()
return manager.requestImage(for: asset,
targetSize: bounds.size.screenScaled(),
contentMode: .aspectFit,
options: options) { [weak self] (image, _) in
self?.image = image
completion()
}
}
}
#endif
|
0eb9b44633197c3245a9a0d9f0b51852
| 28.054054 | 82 | 0.546047 | false | false | false | false |
rustedivan/tapmap
|
refs/heads/master
|
tapmap/Rendering/BorderRenderer.swift
|
mit
|
1
|
//
// BorderRenderer.swift
// tapmap
//
// Created by Ivan Milles on 2020-04-13.
// Copyright © 2019 Wildbrain. All rights reserved.
//
import Metal
import simd
fileprivate struct FrameUniforms {
let mvpMatrix: simd_float4x4
let width: simd_float1
var color: simd_float4
}
struct BorderContour {
let contours: [VertexRing]
}
class BorderRenderer<RegionType> {
typealias LoddedBorderHash = Int
let rendererLabel: String
let device: MTLDevice
let pipeline: MTLRenderPipelineState
let maxVisibleLineSegments: Int
var lineSegmentsHighwaterMark: Int = 0
var borderContours: [LoddedBorderHash : BorderContour]
var frameSelectSemaphore = DispatchSemaphore(value: 1)
let lineSegmentPrimitive: LineSegmentPrimitive
let instanceUniforms: [MTLBuffer]
var frameLineSegmentCount: [Int] = []
var borderScale: Float
var width: Float = 1.0
var color: simd_float4 = simd_float4(0.0, 0.0, 0.0, 1.0)
var actualBorderLod: Int = 10
var wantedBorderLod: Int
init(withDevice device: MTLDevice, pixelFormat: MTLPixelFormat, bufferCount: Int, maxSegments: Int, label: String) {
borderScale = 0.0
let shaderLib = device.makeDefaultLibrary()!
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.sampleCount = 4
pipelineDescriptor.vertexFunction = shaderLib.makeFunction(name: "lineVertex")
pipelineDescriptor.fragmentFunction = shaderLib.makeFunction(name: "lineFragment")
pipelineDescriptor.colorAttachments[0].pixelFormat = pixelFormat;
pipelineDescriptor.vertexBuffers[0].mutability = .immutable
do {
try pipeline = device.makeRenderPipelineState(descriptor: pipelineDescriptor)
self.rendererLabel = label
self.device = device
self.frameLineSegmentCount = Array(repeating: 0, count: bufferCount)
self.maxVisibleLineSegments = maxSegments // Determined experimentally and rounded up a lot
self.instanceUniforms = (0..<bufferCount).map { bufferIndex in
device.makeBuffer(length: maxSegments * MemoryLayout<LineInstanceUniforms>.stride, options: .storageModeShared)!
}
self.lineSegmentPrimitive = makeLineSegmentPrimitive(in: device, inside: -0.05, outside: 0.95)
} catch let error {
fatalError(error.localizedDescription)
}
borderContours = [:]
wantedBorderLod = GeometryStreamer.shared.wantedLodLevel
}
func setStyle(innerWidth: Float, outerWidth: Float, color: simd_float4) {
self.width = innerWidth
self.color = color
}
func prepareFrame(borderedRegions: [Int : RegionType], zoom: Float, zoomRate: Float, inside renderBox: Aabb, bufferIndex: Int) {
let streamer = GeometryStreamer.shared
let lodLevel = streamer.wantedLodLevel
var borderLodMiss = false
// Stream in any missing geometries at the wanted LOD level
for borderHash in borderedRegions.keys {
let loddedBorderHash = borderHashLodKey(borderHash, atLod: lodLevel)
if borderContours[loddedBorderHash] == nil {
borderLodMiss = true
if let tessellation = streamer.tessellation(for: borderHash, atLod: lodLevel, streamIfMissing: true) {
borderContours[loddedBorderHash] = BorderContour(contours: tessellation.contours)
}
}
}
// Update the LOD level if we have all its geometries
if !borderLodMiss && actualBorderLod != streamer.wantedLodLevel {
actualBorderLod = streamer.wantedLodLevel
}
// Collect the vertex rings for the visible set of borders
let frameRenderList: [BorderContour] = borderedRegions.compactMap {
let loddedKey = borderHashLodKey($0.key, atLod: actualBorderLod)
return borderContours[loddedKey]
}
// Generate all the vertices in all the outlines
let regionContours = frameRenderList.flatMap { $0.contours }
var borderBuffer = generateContourLineGeometry(contours: regionContours, inside: renderBox)
guard borderBuffer.count < maxVisibleLineSegments else {
assert(false, "line segment buffer blew out at \(borderBuffer.count) vertices (max \(maxVisibleLineSegments))")
borderBuffer = Array(borderBuffer[0..<maxVisibleLineSegments])
}
let borderZoom = zoom / (1.0 - zoomRate + zoomRate * Stylesheet.shared.borderZoomBias.value) // Borders become wider at closer zoom levels
frameSelectSemaphore.wait()
self.borderScale = 1.0 / borderZoom
self.frameLineSegmentCount[bufferIndex] = borderBuffer.count
self.instanceUniforms[bufferIndex].contents().copyMemory(from: borderBuffer, byteCount: MemoryLayout<LineInstanceUniforms>.stride * borderBuffer.count)
if borderBuffer.count > lineSegmentsHighwaterMark {
lineSegmentsHighwaterMark = borderBuffer.count
print("\(rendererLabel) used a max of \(lineSegmentsHighwaterMark) line segments.")
}
frameSelectSemaphore.signal()
}
func renderBorders(inProjection projection: simd_float4x4, inEncoder encoder: MTLRenderCommandEncoder, bufferIndex: Int) {
encoder.pushDebugGroup("Render \(rendererLabel)'s borders")
defer {
encoder.popDebugGroup()
}
frameSelectSemaphore.wait()
var uniforms = FrameUniforms(mvpMatrix: projection,
width: width * borderScale,
color: color)
let instances = instanceUniforms[bufferIndex]
let count = frameLineSegmentCount[bufferIndex]
frameSelectSemaphore.signal()
if count == 0 {
return
}
encoder.setRenderPipelineState(pipeline)
encoder.setVertexBytes(&uniforms, length: MemoryLayout.stride(ofValue: uniforms), index: 1)
encoder.setVertexBuffer(instances, offset: 0, index: 2)
renderInstanced(primitive: lineSegmentPrimitive, count: count, into: encoder)
}
func borderHashLodKey(_ regionHash: RegionHash, atLod lod: Int) -> LoddedBorderHash {
return "\(regionHash)-\(lod)".hashValue
}
}
|
b0cd0ed59901fbe096c287386b7bbdf9
| 34.886076 | 154 | 0.755908 | false | false | false | false |
seivan/SpriteKitComposition
|
refs/heads/develop
|
TestsAndSample/Tests/SampleComponent.swift
|
mit
|
1
|
//
// SampleComponent.swift
// TestsAndSample
//
// Created by Seivan Heidari on 26/11/14.
// Copyright (c) 2014 Seivan Heidari. All rights reserved.
//
import UIKit
import SpriteKit
class SampleComponent: Component {
var assertionDidAddToNode:SKNode! = nil
var assertionDidAddNodeToScene:SKScene! = nil
var assertionDidRemoveFromNode:SKNode! = nil
var assertionDidRemoveNodeFromScene:SKScene! = nil
var assertionDidChangeSceneSizedFrom:CGSize! = nil
var assertionDidMoveToView:SKView! = nil
var assertionWillMoveFromView:SKView! = nil
var assertionDidUpdate:NSTimeInterval! = nil
var assertionDidEvaluateActions = false
var assertionDidSimulatePhysics = false
var assertionDidApplyConstraints = false
var assertionDidFinishUpdate = false
var assertionDidContactSceneStarted:(contact:SKPhysicsContact, state:ComponentState)! = nil
var assertionDidContactSceneCompleted:(contact:SKPhysicsContact, state:ComponentState)! = nil
var assertionDidContactNodeStarted:(node:SKNode, contact:SKPhysicsContact, state:ComponentState)! = nil
var assertionDidContactNodeCompleted:(node:SKNode, contact:SKPhysicsContact, state:ComponentState)! = nil
var assertionDidTouchSceneStarted:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchSceneChanged:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchSceneCompleted:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchSceneCancelled:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchNodeStarted:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchNodeChanged:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchNodeCompleted:(touches:[UITouch], state:ComponentState)! = nil
var assertionDidTouchNodeCancelled:(touches:[UITouch], state:ComponentState)! = nil
// var assertionDidBeginContactWithNode:(node:SKNode, contact:SKPhysicsContact)! = nil
// var assertionDidEndContactWithNode:(node:SKNode, contact:SKPhysicsContact)! = nil
// var assertionDidBeginContact:SKPhysicsContact! = nil
// var assertionDidEndContact:SKPhysicsContact! = nil
//
// var assertionDidBeginNodeTouches:[UITouch]! = nil
// var assertionDidMoveNodeTouches:[UITouch]! = nil
// var assertionDidEndNodeTouches:[UITouch]! = nil
// var assertionDidCancelNodeTouches:[UITouch]! = nil
// var assertionDidBeginSceneTouches:[UITouch]! = nil
// var assertionDidMoveSceneTouches:[UITouch]! = nil
// var assertionDidEndSceneTouches:[UITouch]! = nil
// var assertionDidCancelSceneTouches:[UITouch]! = nil
func didAddToNode(node:SKNode) {
self.assertionDidAddToNode = node
}
func didAddNodeToScene(scene:SKScene) {
self.assertionDidAddNodeToScene = scene
}
func didRemoveFromNode(node:SKNode) {
self.assertionDidRemoveFromNode = node
}
func didRemoveNodeFromScene(scene:SKScene) {
self.assertionDidRemoveNodeFromScene = scene
}
func didChangeSceneSizedFrom(previousSize:CGSize) {
self.assertionDidChangeSceneSizedFrom = previousSize
}
func didMoveToView(view: SKView) {
self.assertionDidMoveToView = view
}
func willMoveFromView(view: SKView) {
self.assertionWillMoveFromView = view
}
func didUpdate(time:NSTimeInterval) {
self.assertionDidUpdate = time
}
func didEvaluateActions() {
self.assertionDidEvaluateActions = true
}
func didSimulatePhysics() {
self.assertionDidSimulatePhysics = true
}
func didApplyConstraints() {
self.assertionDidApplyConstraints = true
}
func didFinishUpdate() {
self.assertionDidFinishUpdate = true
}
func didContactScene(contact:SKPhysicsContact, state:ComponentState) {
switch state.value {
case ComponentState.Started.value:
self.assertionDidContactSceneStarted = (contact:contact, state:state)
case ComponentState.Completed.value:
self.assertionDidContactSceneCompleted = (contact:contact, state:state)
default:
self.assertionDidContactSceneCompleted = nil
self.assertionDidContactSceneStarted = nil
}
}
func didContactNode(node:SKNode, contact:SKPhysicsContact, state:ComponentState) {
switch state.value {
case ComponentState.Started.value:
self.assertionDidContactNodeStarted = (node:node, contact:contact, state:state)
case ComponentState.Completed.value:
self.assertionDidContactNodeCompleted = (node:node, contact:contact, state:state)
default:
self.assertionDidContactNodeStarted = (node:node, contact:contact, state:state)
self.assertionDidContactNodeCompleted = (node:node, contact:contact, state:state)
}
}
func didTouchScene(touches:[UITouch], state:ComponentState) {
switch state.value {
case ComponentState.Started.value:
self.assertionDidTouchSceneStarted = (touches:touches, state:state)
case ComponentState.Changed.value:
self.assertionDidTouchSceneChanged = (touches:touches, state:state)
case ComponentState.Completed.value:
self.assertionDidTouchSceneCompleted = (touches:touches, state:state)
case ComponentState.Cancelled.value:
self.assertionDidTouchSceneCancelled = (touches:touches, state:state)
default:
self.assertionDidTouchSceneStarted = nil
self.assertionDidTouchSceneChanged = nil
self.assertionDidTouchSceneCompleted = nil
self.assertionDidTouchSceneCancelled = nil
}
}
func didTouchNode(touches:[UITouch], state:ComponentState) {
switch state.value {
case ComponentState.Started.value:
self.assertionDidTouchNodeStarted = (touches:touches, state:state)
case ComponentState.Changed.value:
self.assertionDidTouchNodeChanged = (touches:touches, state:state)
case ComponentState.Completed.value:
self.assertionDidTouchNodeCompleted = (touches:touches, state:state)
case ComponentState.Cancelled.value:
self.assertionDidTouchNodeCancelled = (touches:touches, state:state)
default:
self.assertionDidTouchNodeStarted = nil
self.assertionDidTouchNodeChanged = nil
self.assertionDidTouchNodeCompleted = nil
self.assertionDidTouchNodeCancelled = nil
}
}
}
|
5cd511d01d072994be273e4ac01ba096
| 37.918239 | 107 | 0.763413 | false | false | false | false |
noppoMan/Prorsum
|
refs/heads/master
|
Sources/Prorsum/Go/Channel.swift
|
mit
|
1
|
//
// Channel.swift
// Prorsum
//
// Created by Yuki Takei on 2016/11/23.
//
//
import Foundation
#if os(Linux)
import func CoreFoundation._CFIsMainThread
// avoid unimplemented error
private extension Thread {
static var isMainThread: Bool {
return _CFIsMainThread()
}
}
#endif
class IDGenerator {
static let shared = IDGenerator()
private var _currentId = 0
private let mutex = Mutex()
init(){}
func currentId() -> Int {
mutex.lock()
_currentId+=1
mutex.unlock()
return _currentId
}
}
public enum ChannelError: Error {
case receivedOnClosedChannel
case sendOnClosedChannel
case bufferSizeLimitExceeded(Int)
}
public class Channel<T> {
let id : Int
var messageQ = Queue<T>()
public private(set) var capacity: Int
let cond = Cond()
public fileprivate(set) var isClosed = false
// have to use Channel<T>.make() to initialize the Channel
init(capacity: Int){
self.capacity = capacity
self.id = IDGenerator.shared.currentId()
}
public func count() -> Int {
if capacity == 0 {
return 0
}
return messageQ.count
}
public func send(_ message: T) throws {
cond.mutex.lock()
defer {
cond.mutex.unlock()
}
if isClosed {
throw ChannelError.sendOnClosedChannel
}
messageQ.push(message)
cond.broadcast()
if Thread.isMainThread, messageQ.count > capacity {
throw ChannelError.bufferSizeLimitExceeded(capacity)
}
}
public func nonBlockingReceive() throws -> T? {
cond.mutex.lock()
defer {
cond.mutex.unlock()
}
if let f = messageQ.front {
messageQ.pop()
cond.broadcast()
return f.value
}
if isClosed {
throw ChannelError.receivedOnClosedChannel
}
return nil
}
public func receive() throws -> T {
cond.mutex.lock()
defer {
cond.mutex.unlock()
}
while true {
if let f = messageQ.front {
messageQ.pop()
cond.broadcast()
return f.value
}
if isClosed {
throw ChannelError.receivedOnClosedChannel
}
cond.wait()
}
}
public func close(){
cond.mutex.lock()
cond.broadcast()
isClosed = true
cond.mutex.unlock()
}
}
extension Channel {
public static func make(capacity: Int = 0) -> Channel<T> {
return Channel<T>(capacity: capacity)
}
}
|
adc9de2bdd659f05ed64c157c4339771
| 19.435714 | 64 | 0.520098 | false | false | false | false |
barbosa/clappr-ios
|
refs/heads/master
|
Pod/Classes/Enum/ContainerEvent.swift
|
bsd-3-clause
|
1
|
public enum ContainerEvent: String {
case PlaybackStateChanged = "clappr:container:playback_state_changed"
case PlaybackDVRStateChanged = "clappr:container:playback_dvr_state_changed"
case BitRate = "clappr:container:bit_rate"
case Destroyed = "clappr:container:destroyed"
case Ready = "clappr:container:ready"
case Error = "clappr:container:error"
case LoadedMetadata = "clappr:container:loaded_metadata"
case TimeUpdated = "clappr:container:time_update"
case Progress = "clappr:container:progress"
case Play = "clappr:container:play"
case Stop = "clappr:container:stop"
case Pause = "clappr:container:pause"
case Ended = "clappr:container:ended"
case Tap = "clappr:container:tap"
case Seek = "clappr:container:seek"
case Volume = "clappr:container:volume"
case Buffering = "clappr:container:buffering"
case BufferFull = "clappr:container:buffer_full"
case SettingsUpdated = "clappr:container:settings_updated"
case HighDefinitionUpdated = "clappr:container:hd_updated"
case MediaControlDisabled = "clappr:container:media_control_disabled"
case MediaControlEnabled = "clappr:container:media_control_enabled"
case AudioSourcesUpdated = "clappr:container:audio_sources_updated"
case SubtitleSourcesUpdated = "clappr:container:subtitle_sources_updated"
case SourceChanged = "clappr:container:source_changed"
}
|
dafc7f13b9a02695fbb53360ea81e5a3
| 51.148148 | 80 | 0.749112 | false | false | false | false |
ArnavChawla/InteliChat
|
refs/heads/master
|
Carthage/Checkouts/swift-sdk/Source/VisualRecognitionV3/Models/ClassifiedImage.swift
|
mit
|
1
|
/**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** Results for one image. */
public struct ClassifiedImage: Decodable {
/// Source of the image before any redirects. Not returned when the image is uploaded.
public var sourceUrl: String?
/// Fully resolved URL of the image after redirects are followed. Not returned when the image is uploaded.
public var resolvedUrl: String?
/// Relative path of the image file if uploaded directly. Not returned when the image is passed by URL.
public var image: String?
public var error: ErrorInfo?
/// The classifiers.
public var classifiers: [ClassifierResult]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case sourceUrl = "source_url"
case resolvedUrl = "resolved_url"
case image = "image"
case error = "error"
case classifiers = "classifiers"
}
}
|
f1deb7086839c631df777e51c59c8734
| 33.022222 | 110 | 0.70934 | false | false | false | false |
6ag/BaoKanIOS
|
refs/heads/master
|
BaoKanIOS/Classes/Module/Profile/View/Info/JFInfoHeaderView.swift
|
apache-2.0
|
1
|
//
// JFInfoHeaderView.swift
// BaoKanIOS
//
// Created by zhoujianfeng on 16/5/26.
// Copyright © 2016年 六阿哥. All rights reserved.
//
import UIKit
import YYWebImage
import SnapKit
class JFInfoHeaderView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
准备UI
*/
fileprivate func prepareUI() {
backgroundColor = UIColor.white
addSubview(avatarImageView)
addSubview(usernameLabel)
addSubview(levelLabel)
addSubview(pointsLabel)
avatarImageView.snp.makeConstraints { (make) in
make.left.equalTo(MARGIN)
make.centerY.equalTo(self)
make.size.equalTo(CGSize(width: 50, height: 50))
}
usernameLabel.snp.makeConstraints { (make) in
make.left.equalTo(avatarImageView.snp.right).offset(20)
make.top.equalTo(avatarImageView).offset(2)
}
levelLabel.snp.makeConstraints { (make) in
make.left.equalTo(usernameLabel)
make.bottom.equalTo(avatarImageView).offset(-2)
}
pointsLabel.snp.makeConstraints { (make) in
make.top.equalTo(avatarImageView)
make.right.equalTo(-MARGIN)
}
avatarImageView.yy_setImage(with: URL(string: JFAccountModel.shareAccount()!.avatarUrl!), options: YYWebImageOptions.allowBackgroundTask)
usernameLabel.text = JFAccountModel.shareAccount()!.username!
levelLabel.text = "等级:\(JFAccountModel.shareAccount()!.groupName!)"
pointsLabel.text = "\(JFAccountModel.shareAccount()!.points!)积分"
}
// MARK: - 懒加载
fileprivate lazy var avatarImageView: UIImageView = {
let avatarImageView = UIImageView()
avatarImageView.layer.cornerRadius = 25
avatarImageView.layer.masksToBounds = true
return avatarImageView
}()
fileprivate lazy var usernameLabel: UILabel = {
let usernameLabel = UILabel()
return usernameLabel
}()
fileprivate lazy var levelLabel: UILabel = {
let levelLabel = UILabel()
levelLabel.font = UIFont.systemFont(ofSize: 13)
levelLabel.textColor = UIColor.gray
return levelLabel
}()
fileprivate lazy var pointsLabel: UILabel = {
let pointsLabel = UILabel()
pointsLabel.font = UIFont.systemFont(ofSize: 13)
pointsLabel.textColor = UIColor.gray
return pointsLabel
}()
}
|
72eead3b158f94bd81ac38a8d6df9b5a
| 28.876404 | 145 | 0.621286 | false | false | false | false |
WhosPablo/PicShare
|
refs/heads/master
|
PicShare/SignUpViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// PicShare
//
// Created by Pablo Arango on 10/14/15.
// Copyright © 2015 Pablo Arango. All rights reserved.
//
import Parse
import UIKit
class SignUpViewController: UIViewController {
@IBOutlet weak var signUpUsername: UITextField!
@IBOutlet weak var signUpEmail: UITextField!
@IBOutlet weak var signUpPassword: UITextField!
@IBOutlet weak var signUpPasswordVerification: UITextField!
@IBOutlet weak var signUpAlert: UILabel!
var actInd: UIActivityIndicatorView = UIActivityIndicatorView( frame: CGRectMake(0, 0, 150, 150)) as UIActivityIndicatorView
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.actInd.center = self.view.center
self.actInd.hidesWhenStopped = true
self.actInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
view.addSubview(self.actInd)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signUpAction(sender: AnyObject) {
self.actInd.startAnimating()
let username = self.signUpUsername.text
let password = self.signUpPassword.text
let passwordVerification = self.signUpPasswordVerification.text
let email = self.signUpEmail.text
if(username?.utf16.count<1){
self.signUpAlert.text = "Username field is empty"
self.signUpAlert.hidden = false
self.actInd.stopAnimating()
return
}
if(email?.utf16.count<5){
self.signUpAlert.text = "Email field is empty or invalid"
self.signUpAlert.hidden = false
self.actInd.stopAnimating()
return
}
if(password?.utf16.count<6){
self.signUpAlert.text = "Password field is empty or too short"
self.signUpAlert.hidden = false
self.actInd.stopAnimating()
return
} else if (password != passwordVerification){
self.signUpAlert.text = "Passwords do not match"
self.signUpAlert.hidden = false
self.actInd.stopAnimating()
return
}
if (username?.utf16.count>=1 && password?.utf16.count>=1 && email?.utf16.count>=1 && password == passwordVerification){
self.actInd.startAnimating()
let newUser = PFUser()
newUser.username = username;
newUser.password = password;
newUser.email = email;
newUser.signUpInBackgroundWithBlock({(success: Bool, error: NSError?) ->
Void in
self.actInd.stopAnimating()
if(error == nil){
self.signUpAlert.hidden = true
self.performSegueWithIdentifier("signUpDone", sender: self);
} else {
var errorString = error!.localizedDescription
errorString.replaceRange(errorString.startIndex...errorString.startIndex, with: String(errorString[errorString.startIndex]).uppercaseString)
self.signUpAlert.text = errorString
self.signUpAlert.hidden = false
}
})
}
}
@IBAction func cancelAction(sender: AnyObject) {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
|
b484dd777d5471c06df696e8376a6872
| 31.760684 | 160 | 0.576311 | false | false | false | false |
bykoianko/omim
|
refs/heads/master
|
iphone/Maps/Bookmarks/Categories/Sharing/BookmarksSharingViewController.swift
|
apache-2.0
|
1
|
import SafariServices
@objc
protocol BookmarksSharingViewControllerDelegate: AnyObject {
func didShareCategory()
}
final class BookmarksSharingViewController: MWMTableViewController {
typealias ViewModel = MWMAuthorizationViewModel
@objc var categoryId = MWMFrameworkHelper.invalidCategoryId()
var categoryUrl: URL?
@objc weak var delegate: BookmarksSharingViewControllerDelegate?
private var sharingTags: [MWMTag]?
private var sharingUserStatus: MWMCategoryAuthorType?
private var manager: MWMBookmarksManager {
return MWMBookmarksManager.shared()
}
private var categoryAccessStatus: MWMCategoryAccessStatus? {
guard categoryId != MWMFrameworkHelper.invalidCategoryId() else {
assert(false)
return nil
}
return manager.getCategoryAccessStatus(categoryId)
}
private let kPropertiesSegueIdentifier = "chooseProperties"
private let kTagsControllerIdentifier = "tags"
private let kEditOnWebSegueIdentifier = "editOnWeb"
private let publicSectionIndex = 0
private let privateSectionIndex = 1
private let editOnWebCellIndex = 3
private let rowsInPrivateSection = 2
private var rowsInPublicSection: Int {
return categoryAccessStatus == .public ? 4 : 3
}
@IBOutlet private weak var uploadAndPublishCell: UploadActionCell!
@IBOutlet private weak var getDirectLinkCell: UploadActionCell!
@IBOutlet private weak var editOnWebCell: UITableViewCell!
@IBOutlet private weak var licenseAgreementTextView: UITextView! {
didSet {
let htmlString = String(coreFormat: L("ugc_routes_user_agreement"), arguments: [ViewModel.termsOfUseLink()])
let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: UIFont.regular14(),
NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText()]
licenseAgreementTextView.attributedText = NSAttributedString.string(withHtml: htmlString,
defaultAttributes: attributes)
licenseAgreementTextView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = L("sharing_options")
configureActionCells()
assert(categoryId != MWMFrameworkHelper.invalidCategoryId(), "We can't share nothing")
guard let categoryAccessStatus = categoryAccessStatus else { return }
switch categoryAccessStatus {
case .local:
break
case .public:
categoryUrl = manager.sharingUrl(forCategoryId: categoryId)
uploadAndPublishCell.cellState = .completed
case .private:
categoryUrl = manager.sharingUrl(forCategoryId: categoryId)
getDirectLinkCell.cellState = .completed
case .other:
break
}
}
func configureActionCells() {
uploadAndPublishCell.config(titles: [ .normal : L("upload_and_publish"),
.inProgress : L("upload_and_publish_progress_text"),
.completed : L("upload_and_publish_success") ],
image: UIImage(named: "ic24PxGlobe"),
delegate: self)
getDirectLinkCell.config(titles: [ .normal : L("upload_and_get_direct_link"),
.inProgress : L("direct_link_progress_text"),
.completed : L("direct_link_success") ],
image: UIImage(named: "ic24PxLink"),
delegate: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSections(in _: UITableView) -> Int {
return categoryAccessStatus == .public ? 1 : 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case publicSectionIndex:
return rowsInPublicSection
case privateSectionIndex:
return rowsInPrivateSection
default:
return 0
}
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return section == 0 ? L("public_access") : L("limited_access")
}
override func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell == getDirectLinkCell && getDirectLinkCell.cellState != .normal
|| cell == uploadAndPublishCell && uploadAndPublishCell.cellState != .normal {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell == uploadAndPublishCell {
startUploadAndPublishFlow()
} else if cell == getDirectLinkCell {
uploadAndGetDirectLink()
}
}
func startUploadAndPublishFlow() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPublic])
performAfterValidation(anchor: uploadAndPublishCell) { [weak self] in
if let self = self {
self.performSegue(withIdentifier: self.kPropertiesSegueIdentifier, sender: self)
}
}
}
func uploadAndPublish() {
guard categoryId != MWMFrameworkHelper.invalidCategoryId(),
let tags = sharingTags,
let userStatus = sharingUserStatus else {
assert(false, "not enough data for public sharing")
return
}
manager.setCategory(categoryId, authorType: userStatus)
manager.setCategory(categoryId, tags: tags)
manager.uploadAndPublishCategory(withId: categoryId, progress: { (progress) in
self.uploadAndPublishCell.cellState = .inProgress
}) { (url, error) in
if let error = error as NSError? {
self.uploadAndPublishCell.cellState = .normal
self.showErrorAlert(error)
} else {
self.uploadAndPublishCell.cellState = .completed
self.categoryUrl = url
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : self.manager.getCategoryTracksCount(self.categoryId),
kStatPoints : self.manager.getCategoryMarksCount(self.categoryId)])
self.tableView.beginUpdates()
self.tableView.deleteSections(IndexSet(arrayLiteral: self.privateSectionIndex), with: .fade)
self.tableView.insertRows(at: [IndexPath(item: self.editOnWebCellIndex,
section: self.publicSectionIndex)],
with: .automatic)
self.tableView.endUpdates()
}
}
}
func uploadAndGetDirectLink() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPrivate])
performAfterValidation(anchor: getDirectLinkCell) { [weak self] in
guard let s = self, s.categoryId != MWMFrameworkHelper.invalidCategoryId() else {
assert(false, "categoryId must be valid")
return
}
s.manager.uploadAndGetDirectLinkCategory(withId: s.categoryId, progress: { (progress) in
if progress == .uploadStarted {
s.getDirectLinkCell.cellState = .inProgress
}
}, completion: { (url, error) in
if let error = error as NSError? {
s.getDirectLinkCell.cellState = .normal
s.showErrorAlert(error)
} else {
s.getDirectLinkCell.cellState = .completed
s.categoryUrl = url
s.delegate?.didShareCategory()
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : s.manager.getCategoryTracksCount(s.categoryId),
kStatPoints : s.manager.getCategoryMarksCount(s.categoryId)])
}
})
}
}
func performAfterValidation(anchor: UIView, action: @escaping MWMVoidBlock) {
if MWMFrameworkHelper.isNetworkConnected() {
signup(anchor: anchor, onComplete: { success in
if success {
action()
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 1])
}
})
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 0])
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("common_check_internet_connection_dialog_title"),
message: L("common_check_internet_connection_dialog"),
rightButtonTitle: L("downloader_retry"),
leftButtonTitle: L("cancel")) {
self.performAfterValidation(anchor: anchor,
action: action)
}
}
}
func showErrorAlert(_ error: NSError) {
guard error.code == kCategoryUploadFailedCode,
let statusCode = error.userInfo[kCategoryUploadStatusKey] as? Int,
let status = MWMCategoryUploadStatus(rawValue: statusCode) else {
assert(false)
return
}
switch (status) {
case .networkError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 1])
self.showUploadError()
case .serverError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 2])
self.showUploadError()
case .authError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 3])
self.showUploadError()
case .malformedData:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 4])
self.showMalformedDataError()
case .accessError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 5])
self.showAccessError()
case .invalidCall:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 6])
assert(false, "sharing is not available for paid bookmarks")
}
}
private func showUploadError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("upload_error_toast"))
}
private func showMalformedDataError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("unable_upload_error_subtitle_broken"))
}
private func showAccessError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("unable_upload_error_subtitle_edited"))
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == kPropertiesSegueIdentifier {
if let vc = segue.destination as? SharingPropertiesViewController {
vc.delegate = self
}
} else if segue.identifier == kEditOnWebSegueIdentifier {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatEditOnWeb])
if let vc = segue.destination as? EditOnWebViewController {
vc.delegate = self
vc.guideUrl = categoryUrl
}
}
}
}
extension BookmarksSharingViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let safari = SFSafariViewController(url: URL)
present(safari, animated: true, completion: nil)
return false
}
}
extension BookmarksSharingViewController: UploadActionCellDelegate {
func cellDidPressShareButton(_ cell: UploadActionCell, senderView: UIView) {
guard let url = categoryUrl else {
assert(false, "must provide guide url")
return
}
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatCopyLink])
let message = String(coreFormat: L("share_bookmarks_email_body_link"), arguments: [url.absoluteString])
let shareController = MWMActivityViewController.share(for: nil, message: message) {
_, success, _, _ in
if success {
Statistics.logEvent(kStatSharingLinkSuccess, withParameters: [kStatFrom : kStatSharingOptions])
}
}
shareController?.present(inParentViewController: self, anchorView: senderView)
}
}
extension BookmarksSharingViewController: SharingTagsViewControllerDelegate {
func sharingTagsViewController(_ viewController: SharingTagsViewController, didSelect tags: [MWMTag]) {
navigationController?.popViewController(animated: true)
sharingTags = tags
uploadAndPublish()
}
func sharingTagsViewControllerDidCancel(_ viewController: SharingTagsViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: SharingPropertiesViewControllerDelegate {
func sharingPropertiesViewController(_ viewController: SharingPropertiesViewController,
didSelect userStatus: MWMCategoryAuthorType) {
sharingUserStatus = userStatus
let storyboard = UIStoryboard.instance(.sharing)
let tagsController = storyboard.instantiateViewController(withIdentifier: kTagsControllerIdentifier)
as! SharingTagsViewController
tagsController.delegate = self
guard var viewControllers = navigationController?.viewControllers else {
assert(false)
return
}
viewControllers.removeLast()
viewControllers.append(tagsController)
navigationController?.setViewControllers(viewControllers, animated: true)
}
}
extension BookmarksSharingViewController: EditOnWebViewControllerDelegate {
func editOnWebViewControllerDidFinish(_ viewController: EditOnWebViewController) {
dismiss(animated: true)
}
}
|
2f2eee871b62cd2f0836b7c461a79c5e
| 38.661064 | 125 | 0.666714 | false | false | false | false |
ello/ello-ios
|
refs/heads/master
|
Specs/Networking/AuthenticationManagerSpec.swift
|
mit
|
1
|
////
/// AuthenticationManagerSpec.swift
//
@testable import Ello
import Quick
import Nimble
class AuthenticationManagerSpec: QuickSpec {
override func spec() {
describe("AuthenticationManager") {
describe("canMakeRequest(ElloAPI)") {
let noTokenReqd: [ElloAPI] = [
.auth(email: "", password: ""), .reAuth(token: ""), .anonymousCredentials
]
let anonymous: [ElloAPI] = [
.availability(content: [:]),
.join(email: "", username: "", password: "", invitationCode: nil), .categories
]
let authdOnly: [ElloAPI] = [
.amazonCredentials, .currentUserProfile, .pushSubscriptions(token: Data())
]
let expectations: [(AuthState, supported: [ElloAPI], unsupported: [ElloAPI])] = [
(.noToken, supported: noTokenReqd, unsupported: authdOnly),
(.anonymous, supported: noTokenReqd + anonymous, unsupported: authdOnly),
(.authenticated, supported: authdOnly, unsupported: []),
(.initial, supported: noTokenReqd, unsupported: anonymous + authdOnly),
(.userCredsSent, supported: noTokenReqd, unsupported: anonymous + authdOnly),
(
.shouldTryUserCreds, supported: noTokenReqd,
unsupported: anonymous + authdOnly
),
(.refreshTokenSent, supported: noTokenReqd, unsupported: anonymous + authdOnly),
(
.shouldTryRefreshToken, supported: noTokenReqd,
unsupported: anonymous + authdOnly
),
(
.anonymousCredsSent, supported: noTokenReqd,
unsupported: anonymous + authdOnly
),
(
.shouldTryAnonymousCreds, supported: noTokenReqd,
unsupported: anonymous + authdOnly
),
]
for (state, supported, unsupported) in expectations {
for supportedEndpoint in supported {
it("\(state) should support \(supportedEndpoint)") {
let manager = AuthenticationManager.shared
manager.specs(setAuthState: state)
expect(manager.canMakeRequest(supportedEndpoint)) == true
}
}
for unsupportedEndpoint in unsupported {
it("\(state) should not support \(unsupportedEndpoint)") {
let manager = AuthenticationManager.shared
manager.specs(setAuthState: state)
expect(manager.canMakeRequest(unsupportedEndpoint)) == false
}
}
}
}
}
}
}
|
ae907067e0a68f2bc924666cd90e64df
| 44.397059 | 100 | 0.487528 | false | false | false | false |
LearningSwift2/LearningApps
|
refs/heads/master
|
SimpleVideoPlayer/SimpleVideoPlayer/ViewController.swift
|
apache-2.0
|
1
|
//
// ViewController.swift
// SimpleVideoPlayer
//
// Created by Phil Wright on 12/1/15.
// Copyright © 2015 Touchopia, LLC. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func prepareForSegue(segue: UIStoryboardSegue,
sender: AnyObject?) {
if segue.identifier == "MoviePlayer" {
let destination = segue.destinationViewController as! AVPlayerViewController
if let path = NSBundle.mainBundle().pathForResource("GITGirlsProgram", ofType:"mp4") {
let url = NSURL(fileURLWithPath: path)
destination.player = AVPlayer(URL: url)
}
}
}
}
|
5eaf94b34bf5e746a132e5a892a4d2ad
| 26.648649 | 102 | 0.609971 | false | false | false | false |
alickbass/ViewComponents
|
refs/heads/master
|
ViewComponents/UIControlStyle.swift
|
mit
|
1
|
//
// UIControlStyle.swift
// ViewComponents
//
// Created by Oleksii on 01/05/2017.
// Copyright © 2017 WeAreReasonablePeople. All rights reserved.
//
import UIKit
private enum UIControlStyleKey: Int, StyleKey {
case isEnabled = 150, isSelected, isHighlighted
case contentVerticalAlignment, contentHorizontalAlignment
}
public extension AnyStyle where T: UIControl {
private typealias ViewStyle<Item> = Style<T, Item, UIControlStyleKey>
public static func isEnabled(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isEnabled, sideEffect: { $0.isEnabled = $1 }).toAnyStyle
}
public static func isSelected(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isSelected, sideEffect: { $0.isSelected = $1 }).toAnyStyle
}
public static func isHighlighted(_ value: Bool) -> AnyStyle<T> {
return ViewStyle(value, key: .isHighlighted, sideEffect: { $0.isHighlighted = $1 }).toAnyStyle
}
public static func contentVerticalAlignment(_ value: UIControlContentVerticalAlignment) -> AnyStyle<T> {
return ViewStyle(value, key: .contentVerticalAlignment, sideEffect: { $0.contentVerticalAlignment = $1 }).toAnyStyle
}
public static func contentHorizontalAlignment(_ value: UIControlContentHorizontalAlignment) -> AnyStyle<T> {
return ViewStyle(value, key: .contentHorizontalAlignment, sideEffect: { $0.contentHorizontalAlignment = $1 }).toAnyStyle
}
}
|
2997acf10e0d824c648834258d308a54
| 38.078947 | 128 | 0.705724 | false | false | false | false |
chashmeetsingh/Youtube-iOS
|
refs/heads/master
|
YouTube Demo/AppDelegate.swift
|
mit
|
1
|
//
// AppDelegate.swift
// YouTube Demo
//
// Created by Chashmeet Singh on 06/01/17.
// Copyright © 2017 Chashmeet Singh. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let layout = UICollectionViewFlowLayout()
window?.rootViewController = UINavigationController(rootViewController: HomeController(collectionViewLayout: layout))
UINavigationBar.appearance().barTintColor = UIColor.rgb(red: 230, green: 32, blue: 31)
// Remove black shadow
UINavigationBar.appearance().shadowImage = UIImage()
UINavigationBar.appearance().setBackgroundImage(UIImage(), for: .default)
application.statusBarStyle = .lightContent
let statusBarBackgroundView = UIView()
statusBarBackgroundView.backgroundColor = UIColor.rgb(red: 194, green: 31, blue: 31)
window?.addSubview(statusBarBackgroundView)
window?.addConstraintsWithFormat(format: "H:|[v0]|", view: statusBarBackgroundView)
window?.addConstraintsWithFormat(format: "V:|[v0(20)]", view: statusBarBackgroundView)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
d9b060e45006ed984cc62740b23180fc
| 46.621212 | 285 | 0.727967 | false | false | false | false |
Hbaoxian/HBXXMPPFrameWorkDemo
|
refs/heads/master
|
Demo/Pods/KissXML/KissXML/DDXML.swift
|
apache-2.0
|
7
|
//
// DDXML.swift
// KissXML
//
// Created by David Chiles on 1/29/16.
//
//
import Foundation
#if os(iOS) || os(watchOS) || os(tvOS)
public typealias XMLNode = DDXMLNode
public typealias XMLElement = DDXMLElement
public typealias XMLDocument = DDXMLDocument
public let XMLInvalidKind = DDXMLInvalidKind
public let XMLDocumentKind = DDXMLDocumentKind
public let XMLElementKind = DDXMLElementKind
public let XMLAttributeKind = DDXMLAttributeKind
public let XMLNamespaceKind = DDXMLNamespaceKind
public let XMLProcessingInstructionKind = DDXMLProcessingInstructionKind
public let XMLCommentKind = DDXMLCommentKind
public let XMLTextKind = DDXMLTextKind
public let XMLDTDKind = DDXMLDTDKind
public let XMLEntityDeclarationKind = DDXMLEntityDeclarationKind
public let XMLAttributeDeclarationKind = DDXMLAttributeDeclarationKind
public let XMLElementDeclarationKind = DDXMLElementDeclarationKind
public let XMLNotationDeclarationKind = DDXMLNotationDeclarationKind
public let XMLNodeOptionsNone = DDXMLNodeOptionsNone
public let XMLNodeExpandEmptyElement = DDXMLNodeExpandEmptyElement
public let XMLNodeCompactEmptyElement = DDXMLNodeCompactEmptyElement
public let XMLNodePrettyPrint = DDXMLNodePrettyPrint
#endif
|
bdc50d7b17725ade867857d500bc6b38
| 40.0625 | 77 | 0.787671 | false | false | false | false |
AlesTsurko/DNMKit
|
refs/heads/master
|
DNM_iOS/DNM_iOS/DurationalExtension.swift
|
gpl-2.0
|
1
|
//
// DurationalExtension.swift
// denm_view
//
// Created by James Bean on 8/23/15.
// Copyright © 2015 James Bean. All rights reserved.
//
import UIKit
public class DurationalExtension: LigatureHorizontal {
public var width: CGFloat = 0
public init(y: CGFloat, left: CGFloat, right: CGFloat, width: CGFloat) {
super.init(y: y, left: left, right: right)
self.width = width
build()
}
public override init() { super.init() }
public override init(layer: AnyObject) { super.init(layer: layer) }
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
public override func setVisualAttributes() {
lineWidth = width
strokeColor = UIColor.grayscaleColorWithDepthOfField(.Middleground).CGColor
opacity = 0.666
}
}
|
f5e446fcf0b07fa63911c40e9547e661
| 26.866667 | 83 | 0.651914 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo
|
refs/heads/master
|
Demo24-UIToolbar/Demo24-UIToolbar/ViewController.swift
|
mit
|
1
|
//
// ViewController.swift
// Demo24-UIToolbar
//
// Created by Prashant on 10/10/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// maintain state that toolbar is hiden or not.
var toolbarHidden: Bool = false
// outlet - toolbar
@IBOutlet var toolbar: UIToolbar!
// Action - toggle button
@IBAction func toggleButtonAction(_ sender: UIButton) {
// We are moving tool bar out of screen using animation.
// i.e. we are changing the frame postion for the toolbar and change it's alpha.
UIView.animate(withDuration: 1.0, animations: {
() -> Void in
// show/hide toolbar
if self.toolbarHidden {
self.toolbarHidden = false
let frameRect = CGRect(x: self.toolbar.frame.origin.x, y: self.toolbar.frame.origin.y - self.toolbar.frame.height , width: self.toolbar.frame.width , height: self.toolbar.frame.height)
self.toolbar.frame = frameRect
self.toolbar.alpha = 1.0
}else {
self.toolbarHidden = true
let frameRect = CGRect(x: self.toolbar.frame.origin.x , y: self.toolbar.frame.origin.y + self.toolbar.frame.height, width: self.toolbar.frame.width , height: self.toolbar.frame.height)
self.toolbar.frame = frameRect
self.toolbar.alpha = 0
}
})
}
// outlet - debug label
@IBOutlet var debugLabel: UILabel!
// action - rewind button
@IBAction func rewindButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Rewind - Action"
}
// action - play button
@IBAction func playButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Play - Action"
}
// action - pause button
@IBAction func pauseButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Pause - Action"
}
// action - forward button
@IBAction func forwardButtonAction(_ sender: UIBarButtonItem) {
self.debugLabel.text = "Forward - Action"
}
// MARK: - View functions
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
e9223a67cca05d1bde0124ebd2c0203b
| 29.022222 | 206 | 0.57883 | false | false | false | false |
thiagolioy/marvelapp
|
refs/heads/master
|
Marvel/Network/MarvelAPIManager.swift
|
mit
|
1
|
//
// MarvelAPIManager.swift
// Marvel
//
// Created by Thiago Lioy on 14/11/16.
// Copyright © 2016 Thiago Lioy. All rights reserved.
//
import Foundation
import Moya
import RxSwift
import ObjectMapper
import Moya_ObjectMapper
extension Response {
func removeAPIWrappers() -> Response {
guard let json = try? self.mapJSON() as? Dictionary<String, AnyObject>,
let results = json?["data"]?["results"] ?? [],
let newData = try? JSONSerialization.data(withJSONObject: results, options: .prettyPrinted) else {
return self
}
let newResponse = Response(statusCode: self.statusCode,
data: newData,
response: self.response)
return newResponse
}
}
struct MarvelAPIManager {
let provider: RxMoyaProvider<MarvelAPI>
let disposeBag = DisposeBag()
init() {
provider = RxMoyaProvider<MarvelAPI>()
}
}
extension MarvelAPIManager {
typealias AdditionalStepsAction = (() -> ())
fileprivate func requestObject<T: Mappable>(_ token: MarvelAPI, type: T.Type,
completion: @escaping (T?) -> Void,
additionalSteps: AdditionalStepsAction? = nil) {
provider.request(token)
.debug()
.mapObject(T.self)
.subscribe { event -> Void in
switch event {
case .next(let parsedObject):
completion(parsedObject)
additionalSteps?()
case .error(let error):
print(error)
completion(nil)
default:
break
}
}.addDisposableTo(disposeBag)
}
fileprivate func requestArray<T: Mappable>(_ token: MarvelAPI, type: T.Type,
completion: @escaping ([T]?) -> Void,
additionalSteps: AdditionalStepsAction? = nil) {
provider.request(token)
.debug()
.map { response -> Response in
return response.removeAPIWrappers()
}
.mapArray(T.self)
.subscribe { event -> Void in
switch event {
case .next(let parsedArray):
completion(parsedArray)
additionalSteps?()
case .error(let error):
print(error)
completion(nil)
default:
break
}
}.addDisposableTo(disposeBag)
}
}
protocol MarvelAPICalls {
func characters(query: String?, completion: @escaping ([Character]?) -> Void)
}
extension MarvelAPIManager: MarvelAPICalls {
func characters(query: String? = nil, completion: @escaping ([Character]?) -> Void) {
requestArray(.characters(query),
type: Character.self,
completion: completion)
}
}
|
eb7f9d732a7bcb89584d9f5df7b00a03
| 29.323529 | 110 | 0.515681 | false | false | false | false |
maikotrindade/ios-basics
|
refs/heads/master
|
playground3.playground/Contents.swift
|
gpl-3.0
|
1
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
func firstfunction() {
print("Hello!")
}
firstfunction()
func secondFunction() -> Int {
return 12345
}
secondFunction()
func thirdFunc (firstValue : Int, secondValue: Int) -> Int {
return firstValue + secondValue
}
thirdFunc(100, 900)
//thirdFunc(100, secondValue: 123)
func forthFunction(firstValue : Int, secondValue: Int) -> (doubled : Int, qradrupled : Int) {
return (firstValue * 2, secondValue * 4)
}
forthFunction(2, 2)
forthFunction(2, 2).0
forthFunction(2, 2).qradrupled
//array of numbers
func addNumbers(numbers: Int...) -> Int {
var total = 0
for number in numbers {
total += number
}
return total
}
addNumbers(1,2,3,4,5,6,7,8,9,10)
//params
func swapValues(inout firstValue: Int, inout secondValue: Int) {
let tempValue = firstValue
firstValue = secondValue
secondValue = tempValue
}
var swap1 = 10
var swap2 = 20
swapValues(&swap1, &swap2)
print("\(swap1), \(swap2)")
//variable as Func
var numbersFunc: (Int...) -> Int
numbersFunc = addNumbers
numbersFunc(2,3,4,5,6,7)
//func as param
func timesThree(number: Int) -> Int{
return number*3
}
//func doSomethingToNumber (aNumber: Int, thingToDo: (Int)->Int)->Int {
// return thingsToDo(aNumber)
//}
//doSomethingToNumber(4, thingToDo: timesThree)
func createAdder(numberToAdd: Int) -> (Int) -> Int {
func adder(number:Int) -> Int{
return number + numberToAdd
}
return adder
}
var addTwo = createAdder(2)
addTwo(2)
func createInc(incrementAmount : Int) -> () -> Int {
var amount = 0
func incrementor () -> Int {
amount += incrementAmount
return amount
}
return incrementor
}
var incrementByTen = createInc(10)
incrementByTen()
incrementByTen()
class Vehicle {
var color : String?
var maxSpeed = 80
func description() -> String {
return "A \(self.color) vehicle"
}
func travel() {
print("Traveling ar \(maxSpeed) kph")
}
}
var redVehicle = Vehicle()
redVehicle.color = "Red"
redVehicle.maxSpeed = 95
|
e210c38b87982d33e9fd265bfbc062cd
| 9.549296 | 93 | 0.624833 | false | false | false | false |
MateuszKarwat/Napi
|
refs/heads/master
|
Napi/Controllers/Preferences/Tabs/MatchPreferencesViewController.swift
|
mit
|
1
|
//
// Created by Mateusz Karwat on 09/04/2017.
// Copyright © 2017 Mateusz Karwat. All rights reserved.
//
import AppKit
final class MatchPreferencesViewController: NSViewController {
@IBOutlet private weak var cancelRadioButton: NSButton!
@IBOutlet private weak var overrideRadioButton: NSButton!
@IBOutlet private weak var backupNewSubtitlesRadioButton: NSButton!
@IBOutlet private weak var backupExistingSubtitlesRadioButton: NSButton!
var radioButtonsBinding: [NameMatcher.NameConflictAction: NSButton] {
return [.cancel: cancelRadioButton,
.override: overrideRadioButton,
.backupSourceItem: backupNewSubtitlesRadioButton,
.backupDestinationItem: backupExistingSubtitlesRadioButton]
}
override func viewDidLoad() {
super.viewDidLoad()
setupRadioButtons()
}
private func setupRadioButtons() {
if let enabledRadioButton = radioButtonsBinding[Preferences[.nameConflictAction]] {
enabledRadioButton.state = .on
}
}
@IBAction func nameConflictActionRadioButtonDidChange(_ sender: NSButton) {
radioButtonsBinding.forEach { nameConflictAction, radioButton in
if radioButton === sender {
Preferences[.nameConflictAction] = nameConflictAction
return
}
}
}
}
|
ad52c780641f07649976600bec401ba6
| 32.707317 | 91 | 0.68741 | false | false | false | false |
huangboju/Moots
|
refs/heads/master
|
Examples/Lumia/Lumia/Component/DynamicsCatalog/Controllers/ItemPropertiesVC.swift
|
mit
|
1
|
//
// ItemPropertiesVC.swift
// Lumia
//
// Created by 黄伯驹 on 2020/1/1.
// Copyright © 2020 黄伯驹. All rights reserved.
//
import UIKit
class ItemPropertiesVC: UIViewController {
private lazy var square: UIImageView = {
let square = UIImageView(image: UIImage(named: "Box1")?.withRenderingMode(.alwaysTemplate))
square.frame = CGRect(origin: CGPoint(x: 110, y: 279), size: CGSize(width: 100, height: 100))
square.tintColor = .darkGray
square.isUserInteractionEnabled = true
return square
}()
private lazy var square1: UIImageView = {
let square = UIImageView(image: UIImage(named: "Box1")?.withRenderingMode(.alwaysTemplate))
square.frame = CGRect(origin: CGPoint(x: 250, y: 279), size: CGSize(width: 100, height: 100))
square.tintColor = .darkGray
square.isUserInteractionEnabled = true
return square
}()
private lazy var square2PropertiesBehavior: UIDynamicItemBehavior = {
let square2PropertiesBehavior = UIDynamicItemBehavior(items: [square1])
square2PropertiesBehavior.elasticity = 0.5
return square2PropertiesBehavior
}()
private lazy var square1PropertiesBehavior: UIDynamicItemBehavior = {
let square1PropertiesBehavior = UIDynamicItemBehavior(items: [square])
return square1PropertiesBehavior
}()
var animator: UIDynamicAnimator?
override func loadView() {
view = DecorationView()
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(square)
view.addSubview(square1)
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Replay", style: .plain, target: self, action: #selector(replayAction))
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let animator = UIDynamicAnimator(referenceView: view)
// We want to show collisions between views and boundaries with different
// elasticities, we thus associate the two views to gravity and collision
// behaviors. We will only change the restitution parameter for one of these
// views.
let gravityBeahvior = UIGravityBehavior(items: [square, square1])
let collisionBehavior = UICollisionBehavior(items: [square, square1])
collisionBehavior.translatesReferenceBoundsIntoBoundary = true
// A dynamic item behavior gives access to low-level properties of an item
// in Dynamics, here we change restitution on collisions only for square2,
// and keep square1 with its default value.
// A dynamic item behavior is created for square1 so it's velocity can be
// manipulated in the -resetAction: method.
animator.addBehavior(square1PropertiesBehavior)
animator.addBehavior(square2PropertiesBehavior)
animator.addBehavior(gravityBeahvior)
animator.addBehavior(collisionBehavior)
self.animator = animator
}
@objc func replayAction() {
square1PropertiesBehavior.addLinearVelocity(CGPoint(x: 0, y: -1 * square1PropertiesBehavior.linearVelocity(for: square).y), for: square)
square.center = CGPoint(x: 90, y: 171)
animator?.updateItem(usingCurrentState: square)
square2PropertiesBehavior.addLinearVelocity(CGPoint(x: 0, y: -1 * square2PropertiesBehavior.linearVelocity(for: square1).y), for: square1)
square1.center = CGPoint(x: 230, y: 171)
animator?.updateItem(usingCurrentState: square1)
}
}
|
4a3cf4c967ce07ad366f6e12beb437d6
| 37.284211 | 146 | 0.674457 | false | false | false | false |
LoveZYForever/HXWeiboPhotoPicker
|
refs/heads/master
|
Pods/HXPHPicker/Sources/HXPHPicker/Picker/Controller/PhotoPickerController+FetchAsset.swift
|
mit
|
1
|
//
// PhotoPickerController+FetchAsset.swift
// HXPHPicker
//
// Created by Slience on 2021/8/25.
//
import UIKit
import Photos
// MARK: fetch Asset
extension PhotoPickerController {
func fetchData(status: PHAuthorizationStatus) {
if status.rawValue >= 3 {
PHPhotoLibrary.shared().register(self)
// 有权限
ProgressHUD.showLoading(addedTo: view, afterDelay: 0.15, animated: true)
fetchCameraAssetCollection()
}else if status.rawValue >= 1 {
// 无权限
view.addSubview(deniedView)
}
}
/// 获取相机胶卷资源集合
func fetchCameraAssetCollection() {
if !config.allowLoadPhotoLibrary {
if cameraAssetCollection == nil {
cameraAssetCollection = PhotoAssetCollection(
albumName: config.albumList.emptyAlbumName.localized,
coverImage: config.albumList.emptyCoverImageName.image
)
}
fetchCameraAssetCollectionCompletion?(cameraAssetCollection)
return
}
if config.creationDate {
options.sortDescriptors = [NSSortDescriptor.init(key: "creationDate", ascending: config.creationDate)]
}
PhotoManager.shared.fetchCameraAssetCollection(
for: selectOptions,
options: options
) { [weak self] (assetCollection) in
guard let self = self else { return }
if assetCollection.count == 0 {
self.cameraAssetCollection = PhotoAssetCollection(
albumName: self.config.albumList.emptyAlbumName.localized,
coverImage: self.config.albumList.emptyCoverImageName.image
)
}else {
// 获取封面
self.cameraAssetCollection = assetCollection
}
if self.config.albumShowMode == .popup {
self.fetchAssetCollections()
}
self.fetchCameraAssetCollectionCompletion?(self.cameraAssetCollection)
}
}
/// 获取相册集合
func fetchAssetCollections() {
cancelAssetCollectionsQueue()
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation] in
if self.config.creationDate {
self.options.sortDescriptors = [
NSSortDescriptor(
key: "creationDate",
ascending: self.config.creationDate
)
]
}
self.assetCollectionsArray = []
var localCount = self.localAssetArray.count + self.localCameraAssetArray.count
var coverImage = self.localCameraAssetArray.first?.originalImage
if coverImage == nil {
coverImage = self.localAssetArray.first?.originalImage
}
var firstSetImage = true
for phAsset in self.selectedAssetArray where
phAsset.phAsset == nil {
let inLocal = self.localAssetArray.contains(
where: {
$0.isEqual(phAsset)
})
let inLocalCamera = self.localCameraAssetArray.contains(
where: {
$0.isEqual(phAsset)
}
)
if !inLocal && !inLocalCamera {
if firstSetImage {
coverImage = phAsset.originalImage
firstSetImage = false
}
localCount += 1
}
}
if operation.isCancelled {
return
}
if !self.config.allowLoadPhotoLibrary {
DispatchQueue.main.async {
self.cameraAssetCollection?.realCoverImage = coverImage
self.cameraAssetCollection?.count += localCount
self.assetCollectionsArray.append(self.cameraAssetCollection!)
self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray)
}
return
}
PhotoManager.shared.fetchAssetCollections(
for: self.options,
showEmptyCollection: false
) { [weak self] (assetCollection, isCameraRoll, stop) in
guard let self = self else {
stop.pointee = true
return
}
if operation.isCancelled {
stop.pointee = true
return
}
if let assetCollection = assetCollection {
if let collection = assetCollection.collection,
let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssetCollections: collection) {
if !canAdd {
return
}
}
assetCollection.count += localCount
if isCameraRoll {
self.assetCollectionsArray.insert(assetCollection, at: 0)
}else {
self.assetCollectionsArray.append(assetCollection)
}
}else {
if let cameraAssetCollection = self.cameraAssetCollection {
self.cameraAssetCollection?.count += localCount
if coverImage != nil {
self.cameraAssetCollection?.realCoverImage = coverImage
}
if !self.assetCollectionsArray.isEmpty {
self.assetCollectionsArray[0] = cameraAssetCollection
}else {
self.assetCollectionsArray.append(cameraAssetCollection)
}
}
DispatchQueue.main.async {
self.fetchAssetCollectionsCompletion?(self.assetCollectionsArray)
}
}
}
}
assetCollectionsQueue.addOperation(operation)
}
func cancelAssetCollectionsQueue() {
assetCollectionsQueue.cancelAllOperations()
}
private func getSelectAsset() -> ([PHAsset], [PhotoAsset]) {
var selectedAssets = [PHAsset]()
var selectedPhotoAssets: [PhotoAsset] = []
var localIndex = -1
for (index, photoAsset) in selectedAssetArray.enumerated() {
if config.selectMode == .single {
break
}
photoAsset.selectIndex = index
photoAsset.isSelected = true
if let phAsset = photoAsset.phAsset {
selectedAssets.append(phAsset)
selectedPhotoAssets.append(photoAsset)
}else {
let inLocal = localAssetArray
.contains {
if $0.isEqual(photoAsset) {
localAssetArray[localAssetArray.firstIndex(of: $0)!] = photoAsset
return true
}
return false
}
let inLocalCamera = localCameraAssetArray
.contains(where: {
if $0.isEqual(photoAsset) {
localCameraAssetArray[
localCameraAssetArray.firstIndex(of: $0)!
] = photoAsset
return true
}
return false
})
if !inLocal && !inLocalCamera {
if photoAsset.localIndex > localIndex {
localIndex = photoAsset.localIndex
localAssetArray.insert(photoAsset, at: 0)
}else {
if localIndex == -1 {
localIndex = photoAsset.localIndex
localAssetArray.insert(photoAsset, at: 0)
}else {
localAssetArray.insert(photoAsset, at: 1)
}
}
}
}
}
return (selectedAssets, selectedPhotoAssets)
}
/// 获取相册里的资源
/// - Parameters:
/// - assetCollection: 相册
/// - completion: 完成回调
func fetchPhotoAssets(
assetCollection: PhotoAssetCollection?,
completion: (([PhotoAsset], PhotoAsset?, Int, Int) -> Void)?
) {
cancelFetchAssetsQueue()
let operation = BlockOperation()
operation.addExecutionBlock { [unowned operation] in
var photoCount = 0
var videoCount = 0
self.localAssetArray.forEach { $0.isSelected = false }
self.localCameraAssetArray.forEach { $0.isSelected = false }
let result = self.getSelectAsset()
let selectedAssets = result.0
let selectedPhotoAssets = result.1
var localAssets: [PhotoAsset] = []
if operation.isCancelled {
return
}
localAssets.append(contentsOf: self.localCameraAssetArray.reversed())
localAssets.append(contentsOf: self.localAssetArray)
var photoAssets = [PhotoAsset]()
photoAssets.reserveCapacity(assetCollection?.count ?? 10)
var lastAsset: PhotoAsset?
assetCollection?.enumerateAssets( usingBlock: { [weak self] (photoAsset, index, stop) in
guard let self = self,
let phAsset = photoAsset.phAsset
else {
stop.pointee = true
return
}
if operation.isCancelled {
stop.pointee = true
return
}
if let canAdd = self.pickerDelegate?.pickerController(self, didFetchAssets: phAsset) {
if !canAdd {
return
}
}
if self.selectOptions.contains(.gifPhoto) {
if phAsset.isImageAnimated {
photoAsset.mediaSubType = .imageAnimated
}
}
if self.config.selectOptions.contains(.livePhoto) {
if phAsset.isLivePhoto {
photoAsset.mediaSubType = .livePhoto
}
}
switch photoAsset.mediaType {
case .photo:
if !self.selectOptions.isPhoto {
return
}
photoCount += 1
case .video:
if !self.selectOptions.isVideo {
return
}
videoCount += 1
}
var asset = photoAsset
if let index = selectedAssets.firstIndex(of: phAsset) {
let selectPhotoAsset = selectedPhotoAssets[index]
asset = selectPhotoAsset
lastAsset = selectPhotoAsset
}
photoAssets.append(asset)
})
if self.config.photoList.showAssetNumber {
localAssets.forEach {
if $0.mediaType == .photo {
photoCount += 1
}else {
videoCount += 1
}
}
}
photoAssets.append(contentsOf: localAssets.reversed())
if self.config.photoList.sort == .desc {
photoAssets.reverse()
}
if operation.isCancelled {
return
}
DispatchQueue.main.async {
completion?(photoAssets, lastAsset, photoCount, videoCount)
}
}
assetsQueue.addOperation(operation)
}
func cancelFetchAssetsQueue() {
assetsQueue.cancelAllOperations()
}
}
|
fc0553934e2ac436422e4487c3f80602
| 38.229032 | 119 | 0.491983 | false | false | false | false |
LeafPlayer/Leaf
|
refs/heads/master
|
Leaf/UIComponents/NSBackgourndChangableButton.swift
|
gpl-3.0
|
1
|
//
// NSBackgourndChangableButton.swift
// Leaf
//
// Created by lincolnlaw on 2017/11/2.
// Copyright © 2017年 lincolnlaw. All rights reserved.
//
import Cocoa
final class NSBackgourndChangableButton: NSView {
typealias Action = (NSBackgourndChangableButton) -> Void
private let normalBackground = CGColor(gray: 0, alpha: 0)
private let hoverBackground = CGColor(gray: 0, alpha: 0.25)
private let pressedBackground = CGColor(gray: 0, alpha: 0.35)
public private(set) var action: Action = { _ in }
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
}
convenience init(action: @escaping Action) {
self.init(frame: .zero)
self.action = action
wantsLayer = true
layer?.cornerRadius = 4
}
override var frame: NSRect {
get { return super.frame }
set {
for area in trackingAreas { removeTrackingArea(area) }
super.frame = newValue
addTrackingArea(NSTrackingArea(rect: bounds, options: [.activeInKeyWindow, .mouseEnteredAndExited], owner: self, userInfo: nil))
}
}
override func mouseEntered(with event: NSEvent) {
layer?.backgroundColor = hoverBackground
}
override func mouseExited(with event: NSEvent) {
layer?.backgroundColor = normalBackground
}
override func mouseDown(with event: NSEvent) {
layer?.backgroundColor = pressedBackground
action(self)
}
override func mouseUp(with event: NSEvent) {
layer?.backgroundColor = hoverBackground
}
}
|
2b18a06df536821ee84fd52be1ffc35a
| 27.583333 | 140 | 0.638484 | false | false | false | false |
clwi/CWPack
|
refs/heads/master
|
goodies/swift/CWPack.swift
|
mit
|
1
|
//
// CWPack.swift
// CWPack
//
// Created by Claes Wihlborg on 2022-01-17.
//
/*
The MIT License (MIT)
Copyright (c) 2021 Claes Wihlborg
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 AppKit
enum CWPackError: Error {
case fileError(_ errNo:Int)
case contextError(_ err:Int32)
case packerError(_ err:String)
case unpackerError(_ err:String)
}
// MARK: ------------------------------ MessagePack Objects
struct CWNil {
}
struct ArrayHeader {
let count:Int
init (_ count:Int) {self.count = count}
init () {count = 0}
}
struct DictionaryHeader {
let count:UInt32
init (_ count:UInt32) {self.count = count}
init () {count = 0}
}
struct MsgPackExt {
let type: Int8
let data: Data
init (_ type:Int8, _ data: Data) {
self.type = type
self.data = data
}
}
// MARK: ------------------------------ MessagePacker
class CWPacker {
let p: UnsafeMutablePointer<cw_pack_context>
var optimizeReal: Bool = true
var OK: Bool {p.pointee.return_code == CWP_RC_OK}
init(_ p:UnsafeMutablePointer<cw_pack_context>) {
self.p = p
}
}
class CWDataPacker: CWPacker {
private var context = dynamic_memory_pack_context()
var data: Data {
let c:Int = context.pc.current - context.pc.start
return Data(bytes:context.pc.start, count:c)}
init() {
super.init(&context.pc)
init_dynamic_memory_pack_context(&context, 1024)
}
}
class CWFilePacker: CWPacker {
private var context = file_pack_context()
private let ownsChannel: Bool
let fh: FileHandle?
func flush() {cw_pack_flush(&context.pc)}
init(to descriptor:Int32) {
ownsChannel = false
fh = nil
super.init(&context.pc)
init_file_pack_context(&context, 1024, descriptor)
}
init(to url:URL) throws {
fh = try FileHandle(forWritingTo: url)
ownsChannel = true
super.init(&context.pc)
init_file_pack_context(&context, 1024, fh!.fileDescriptor)
}
deinit {
terminate_file_pack_context(&context)
// if ownsChannel {close(context.fileDescriptor)}
}
}
// MARK: ------------------------------ MessageUnpacker
class CWUnpacker {
let p: UnsafeMutablePointer<cw_unpack_context>
var OK: Bool {p.pointee.return_code == CWP_RC_OK}
init(_ p:UnsafeMutablePointer<cw_unpack_context>) {
self.p = p
}
}
class CWDataUnpacker: CWUnpacker {
private var context = cw_unpack_context()
private var buffer: [UInt8]
init(from data: Data) {
buffer = Array(repeating: UInt8(0), count: data.count)
super.init(&context)
data.copyBytes(to: &buffer, count: data.count)
cw_unpack_context_init(&context, buffer, UInt(data.count), nil)
}
}
class CWFileUnpacker: CWUnpacker {
private var context = file_unpack_context()
private let ownsChannel: Bool
let fh: FileHandle?
init(from descriptor:Int32) {
ownsChannel = false
fh = nil
super.init(&context.uc)
init_file_unpack_context(&context, 1024, descriptor)
}
init(from url:URL) throws {
fh = try FileHandle(forReadingFrom: url)
ownsChannel = true
super.init(&context.uc)
init_file_unpack_context(&context, 1024, fh!.fileDescriptor)
}
deinit {
terminate_file_unpack_context(&context)
// if ownsChannel {close(context.fileDescriptor)}
}
}
|
0a01a1de89bef9d3d27bb3484d899c50
| 25.081395 | 95 | 0.653143 | false | false | false | false |
Diuit/DUMessagingUIKit-iOS
|
refs/heads/develop
|
DUMessagingUIKit/DUMessageCellTextView.swift
|
mit
|
1
|
//
// DUMessageCellTextView.swift
// DUMessagingUIKit
//
// Created by Pofat Diuit on 2016/6/5.
// Copyright © 2016年 duolC. All rights reserved.
//
import UIKit
open class DUMessageCellTextView: UITextView {
override open func awakeFromNib() {
super.awakeFromNib()
isEditable = false
isSelectable = true
isUserInteractionEnabled = true
dataDetectorTypes = UIDataDetectorTypes()
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
isScrollEnabled = false
backgroundColor = UIColor.clear
textContainerInset = UIEdgeInsets.zero
textContainer.lineFragmentPadding = 0
contentInset = UIEdgeInsets.zero
scrollIndicatorInsets = UIEdgeInsets.zero
contentOffset = CGPoint.zero
let underline = NSUnderlineStyle.styleSingle.rawValue | NSUnderlineStyle.patternSolid.rawValue
linkTextAttributes = [ NSForegroundColorAttributeName : GlobalUISettings.tintColor,
NSUnderlineStyleAttributeName: underline]
}
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
// ignore double tap to prevent unrelevatn menu showing
if let gr = gestureRecognizer as? UITapGestureRecognizer {
if gr.numberOfTapsRequired == 2 { return false }
}
return true
}
}
|
da9ed516bd1b060f13685251737b602a
| 32.204545 | 103 | 0.673511 | false | false | false | false |
yanif/circator
|
refs/heads/master
|
MetabolicCompass/View Controller/Analysis/AnalysisViewController.swift
|
apache-2.0
|
1
|
//
// AnalysisViewController.swift
// MetabolicCompass
//
// Created by Artem Usachov on 8/10/16.
// Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import UIKit
// Enums
enum AnalysisType : Int {
case Correlate = 0
case Fasting
case OurStudy
}
class AnalysisViewController: UIViewController {
var currentViewController: UIViewController?
@IBOutlet weak var containerView: UIView!
override func viewDidLoad() {
let correlateController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as! CorrelationChartsViewController
self.addChildViewController(correlateController)
correlateController.view.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(correlateController.view, toView: self.containerView)
self.currentViewController = correlateController;
super.viewDidLoad()
}
func switchToScatterPlotViewController() {
let newViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("correlatePlaceholder") as! CorrelationChartsViewController
newViewController.view.translatesAutoresizingMaskIntoConstraints = false
cycleFromViewController(self.currentViewController!, toViewController: newViewController)
self.currentViewController = newViewController;
}
func switchToFastingViewController() {
let fastingViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("fastingController");
fastingViewController.view.translatesAutoresizingMaskIntoConstraints = false
cycleFromViewController(self.currentViewController!, toViewController: fastingViewController);
self.currentViewController = fastingViewController;
}
func switchToOurStudyViewController() {
let ourStudyViewController = UIStoryboard(name: "TabScreens", bundle: nil).instantiateViewControllerWithIdentifier("ourStudyController");
ourStudyViewController.view.translatesAutoresizingMaskIntoConstraints = false
cycleFromViewController(self.currentViewController!, toViewController: ourStudyViewController);
self.currentViewController = ourStudyViewController;
}
@IBAction func segmentSelectedAction(segment: UISegmentedControl) {
switch segment.selectedSegmentIndex {
case AnalysisType.Correlate.rawValue:
switchToScatterPlotViewController()
case AnalysisType.OurStudy.rawValue:
switchToOurStudyViewController()
default://by default show fastings
switchToFastingViewController()
}
}
func cycleFromViewController(oldViewController: UIViewController, toViewController newViewController: UIViewController) {
oldViewController.willMoveToParentViewController(nil)
oldViewController.view.removeFromSuperview()
oldViewController.removeFromParentViewController()
self.addChildViewController(newViewController)
self.addSubview(newViewController.view, toView:self.containerView!)
newViewController.view.layoutIfNeeded()
newViewController.didMoveToParentViewController(self)
}
func addSubview(subView:UIView, toView parentView:UIView) {
parentView.addSubview(subView)
var viewBindingsDict = [String: AnyObject]()
viewBindingsDict["subView"] = subView
parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[subView]|",
options: [], metrics: nil, views: viewBindingsDict))
parentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[subView]|",
options: [], metrics: nil, views: viewBindingsDict))
}
}
|
a0451abd314258ab12578b61ce9c7d2e
| 44.571429 | 179 | 0.750261 | false | false | false | false |
wvteijlingen/Spine
|
refs/heads/master
|
Spine/Serializing.swift
|
mit
|
1
|
//
// Serializing.swift
// Spine
//
// Created by Ward van Teijlingen on 23-08-14.
// Copyright (c) 2014 Ward van Teijlingen. All rights reserved.
//
import Foundation
/// Serializer (de)serializes according to the JSON:API specification.
public class Serializer {
/// The resource factory used for dispensing resources.
fileprivate var resourceFactory = ResourceFactory()
/// The transformers used for transforming to and from the serialized representation.
fileprivate var valueFormatters = ValueFormatterRegistry.defaultRegistry()
/// The key formatter used for formatting field names to keys.
public var keyFormatter: KeyFormatter = AsIsKeyFormatter()
public init() {}
/// Deserializes the given data into a JSONAPIDocument.
///
/// - parameter data: The data to deserialize.
/// - parameter mappingTargets: Optional resources onto which data will be deserialized.
///
/// - throws: SerializerError that can occur in the deserialization.
///
/// - returns: A JSONAPIDocument
public func deserializeData(_ data: Data, mappingTargets: [Resource]? = nil) throws -> JSONAPIDocument {
let deserializeOperation = DeserializeOperation(data: data, resourceFactory: resourceFactory, valueFormatters: valueFormatters, keyFormatter: keyFormatter)
if let mappingTargets = mappingTargets {
deserializeOperation.addMappingTargets(mappingTargets)
}
deserializeOperation.start()
switch deserializeOperation.result! {
case .failure(let error):
throw error
case .success(let document):
return document
}
}
/// Serializes the given JSON:API document into NSData. Only the main data is serialized.
///
/// - parameter document: The JSONAPIDocument to serialize.
/// - parameter options: Serialization options to use.
///
/// - throws: SerializerError that can occur in the serialization.
///
/// - returns: Serialized data
public func serializeDocument(_ document: JSONAPIDocument, options: SerializationOptions = [.IncludeID]) throws -> Data {
let serializeOperation = SerializeOperation(document: document, valueFormatters: valueFormatters, keyFormatter: keyFormatter)
serializeOperation.options = options
serializeOperation.start()
switch serializeOperation.result! {
case .failure(let error):
throw error
case .success(let data):
return data
}
}
/// Serializes the given Resources into NSData.
///
/// - parameter resources: The resources to serialize.
/// - parameter options: The serialization options to use.
///
/// - throws: SerializerError that can occur in the serialization.
///
/// - returns: Serialized data.
public func serializeResources(_ resources: [Resource], options: SerializationOptions = [.IncludeID]) throws -> Data {
let document = JSONAPIDocument(data: resources, included: nil, errors: nil, meta: nil, links: nil, jsonapi: nil)
return try serializeDocument(document, options: options)
}
/// Converts the given resource to link data, and serializes it into NSData.
/// `{"data": { "type": "people", "id": "12" }}`
///
/// If no resource is passed, `null` is used:
/// `{ "data": null }`
///
/// - parameter resource: The resource to serialize link data for.
///
/// - throws: SerializerError that can occur in the serialization.
///
/// - returns: Serialized data.
public func serializeLinkData(_ resource: Resource?) throws -> Data {
let payloadData: Any
if let resource = resource {
assert(resource.id != nil, "Attempt to convert resource without id to linkage. Only resources with ids can be converted to linkage.")
payloadData = ["type": resource.resourceType, "id": resource.id!]
} else {
payloadData = NSNull()
}
do {
return try JSONSerialization.data(withJSONObject: ["data": payloadData], options: JSONSerialization.WritingOptions(rawValue: 0))
} catch let error as NSError {
throw SerializerError.jsonSerializationError(error)
}
}
/// Converts the given resources to link data, and serializes it into NSData.
/// ```json
/// {
/// "data": [
/// { "type": "comments", "id": "12" },
/// { "type": "comments", "id": "13" }
/// ]
/// }
/// ```
///
/// - parameter resources: The resource to serialize link data for.
///
/// - throws: SerializerError that can occur in the serialization.
///
/// - returns: Serialized data.
public func serializeLinkData(_ resources: [Resource]) throws -> Data {
let payloadData: Any
if resources.isEmpty {
payloadData = []
} else {
payloadData = resources.map { resource in
return ["type": resource.resourceType, "id": resource.id!]
}
}
do {
return try JSONSerialization.data(withJSONObject: ["data": payloadData], options: JSONSerialization.WritingOptions(rawValue: 0))
} catch let error as NSError {
throw SerializerError.jsonSerializationError(error)
}
}
/// Registers a resource class.
///
/// - parameter resourceClass: The resource class to register.
public func registerResource(_ resourceClass: Resource.Type) {
resourceFactory.registerResource(resourceClass)
}
/// Registers transformer `transformer`.
///
/// - parameter transformer: The Transformer to register.
public func registerValueFormatter<T: ValueFormatter>(_ formatter: T) {
valueFormatters.registerFormatter(formatter)
}
}
/// A JSONAPIDocument represents a JSON API document containing
/// resources, errors, metadata, links and jsonapi data.
public struct JSONAPIDocument {
/// Primary resources extracted from the response.
public var data: [Resource]?
/// Included resources extracted from the response.
public var included: [Resource]?
/// Errors extracted from the response.
public var errors: [APIError]?
/// Metadata extracted from the reponse.
public var meta: Metadata?
/// Links extracted from the response.
public var links: [String: URL]?
/// JSONAPI information extracted from the response.
public var jsonapi: JSONAPIData?
}
public struct SerializationOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) { self.rawValue = rawValue }
/// Whether to include the resource ID in the serialized representation.
public static let IncludeID = SerializationOptions(rawValue: 1 << 1)
/// Whether to only serialize fields that are dirty.
public static let DirtyFieldsOnly = SerializationOptions(rawValue: 1 << 2)
/// Whether to include to-many linked resources in the serialized representation.
public static let IncludeToMany = SerializationOptions(rawValue: 1 << 3)
/// Whether to include to-one linked resources in the serialized representation.
public static let IncludeToOne = SerializationOptions(rawValue: 1 << 4)
/// If set, then attributes with null values will not be serialized.
public static let OmitNullValues = SerializationOptions(rawValue: 1 << 5)
}
|
08f214ae8231bc82c68175167ef5c461
| 32.816832 | 157 | 0.717904 | false | false | false | false |
rainedAllNight/RNScrollPageView
|
refs/heads/master
|
RNScrollPageView-Example/RNScrollPageView/HKCell.swift
|
mit
|
1
|
//
// HKCell.swift
// TableView
//
// Created by 罗伟 on 2017/5/15.
// Copyright © 2017年 罗伟. All rights reserved.
//
import UIKit
class HKCell: UITableViewCell {
@IBOutlet weak var bgImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func updateBgImageViewFrame() {
let toWindowFrame = self.convert(self.bounds, to: self.window)
let superViewCenter = self.superview!.center
let cellOffSetY = toWindowFrame.midY - superViewCenter.y
let ratio = cellOffSetY/self.superview!.frame.height
let offSetY = -self.frame.height * ratio
let transY = CGAffineTransform(translationX: 0, y: offSetY)
self.bgImageView.transform = transY
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
2bea72b08d1e4040e95baf35d147c9e0
| 25.459459 | 70 | 0.650664 | false | false | false | false |
daniel-beard/2049
|
refs/heads/main
|
2049/Vector.swift
|
mit
|
1
|
//
// Vector.swift
// 2049
//
// Created by Daniel Beard on 12/6/14.
// Copyright (c) 2014 DanielBeard. All rights reserved.
//
import Foundation
final class Vector {
var x = 0
var y = 0
init(x: Int, y: Int) {
self.x = x
self.y = y
}
class func getVector(_ direction: Int) -> Vector {
let map: [Int: Vector] = [
0: Vector(x: 0, y: -1), // Up
1: Vector(x: 1, y: 0), // Right
2: Vector(x: 0, y: 1), // Down
3: Vector(x: -1, y: 0) // Left
]
return map[direction]!
}
}
|
82006a18344dc46f8f6f8b0f7b8cd448
| 19.551724 | 56 | 0.466443 | false | false | false | false |
shhuangtwn/ProjectLynla
|
refs/heads/master
|
DataCollectionTool/RatingControl.swift
|
mit
|
1
|
//
// RatingControl.swift
// DataCollectionTool
//
// Created by Bryan Huang on 2016/11/3.
// Copyright © 2016年 freelance. All rights reserved.
//
import UIKit
class RatingControl: UIView {
// MARK: Properties
var rating = 3 {
didSet {
setNeedsLayout()
}
}
var ratingButtons = [UIButton]()
var spacing = 5
var stars = 5
// MARK: Initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let filledStarImage = UIImage(named: "starIcon24")
let emptyStarImage = UIImage(named: "emptyStar")
for _ in 0..<5 {
let button = UIButton()
button.setImage(emptyStarImage, forState: .Normal)
button.setImage(filledStarImage, forState: .Selected)
button.setImage(filledStarImage, forState: [.Highlighted, .Selected])
button.adjustsImageWhenHighlighted = false
button.addTarget(self, action: #selector(RatingControl.ratingButtonTapped(_:)), forControlEvents: .TouchDown)
ratingButtons += [button]
addSubview(button)
}
}
override func layoutSubviews() {
// Set the button's width and height to a square the size of the frame's height.
let buttonSize = Int(frame.size.height)
var buttonFrame = CGRect(x: 0, y: 0, width: buttonSize, height: buttonSize)
// Offset each button's origin by the length of the button plus spacing.
for (index, button) in ratingButtons.enumerate() {
buttonFrame.origin.x = CGFloat(index * (buttonSize + spacing))
button.frame = buttonFrame
}
updateButtonSelectionStates()
}
override func intrinsicContentSize() -> CGSize {
let buttonSize = Int(frame.size.height)
let width = (buttonSize + spacing) * stars
return CGSize(width: width, height: buttonSize)
}
// MARK: Button Action
func ratingButtonTapped(button: UIButton) {
rating = ratingButtons.indexOf(button)! + 1
updateButtonSelectionStates()
}
func updateButtonSelectionStates() {
for (index, button) in ratingButtons.enumerate() {
// If the index of a button is less than the rating, that button should be selected.
button.selected = index < rating
}
}
}
|
d8586005d13462b213eec66c928539e4
| 29.9125 | 121 | 0.596442 | false | false | false | false |
ericmarkmartin/Nightscouter2
|
refs/heads/master
|
Common/Extensions/Double-Extension.swift
|
mit
|
1
|
//
// ApplicationExtensions.swift
// Nightscout
//
// Created by Peter Ina on 5/18/15.
// Copyright (c) 2015 Peter Ina. All rights reserved.
//
import Foundation
public extension Range
{
public var randomInt: Int
{
get
{
var offset = 0
if (startIndex as! Int) < 0 // allow negative ranges
{
offset = abs(startIndex as! Int)
}
let mini = UInt32(startIndex as! Int + offset)
let maxi = UInt32(endIndex as! Int + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
}
public extension MgdlValue {
public var toMmol: Double {
get{
return (self / 18)
}
}
public var toMgdl: Double {
get{
return floor(self * 18)
}
}
internal var mgdlFormatter: NSNumberFormatter {
let numberFormat = NSNumberFormatter()
numberFormat.numberStyle = .NoStyle
return numberFormat
}
public var formattedForMgdl: String {
if let reserved = ReservedValues(mgdl: self) {
return reserved.description
}
return self.mgdlFormatter.stringFromNumber(self)!
}
internal var mmolFormatter: NSNumberFormatter {
let numberFormat = NSNumberFormatter()
numberFormat.numberStyle = .DecimalStyle
numberFormat.minimumFractionDigits = 1
numberFormat.maximumFractionDigits = 1
numberFormat.secondaryGroupingSize = 1
return numberFormat
}
public var formattedForMmol: String {
if let reserved = ReservedValues(mgdl: self) {
return reserved.description
}
return self.mmolFormatter.stringFromNumber(self.toMmol)!
}
}
public extension MgdlValue {
internal var bgDeltaFormatter: NSNumberFormatter {
let numberFormat = NSNumberFormatter()
numberFormat.numberStyle = .DecimalStyle
numberFormat.positivePrefix = numberFormat.plusSign
numberFormat.negativePrefix = numberFormat.minusSign
return numberFormat
}
public func formattedBGDelta(forUnits units: Units, appendString: String? = nil) -> String {
var formattedNumber: String = ""
switch units {
case .Mmol:
let numberFormat = bgDeltaFormatter
numberFormat.minimumFractionDigits = 1
numberFormat.maximumFractionDigits = 1
numberFormat.secondaryGroupingSize = 1
formattedNumber = numberFormat.stringFromNumber(self) ?? "?"
case .Mgdl:
formattedNumber = self.bgDeltaFormatter.stringFromNumber(self) ?? "?"
}
var unitMarker: String = units.description
if let appendString = appendString {
unitMarker = appendString
}
return formattedNumber + " " + unitMarker
}
public var formattedForBGDelta: String {
return self.bgDeltaFormatter.stringFromNumber(self)!
}
}
public extension Double {
var isInteger: Bool {
return rint(self) == self
}
}
public extension Double {
public func millisecondsToSecondsTimeInterval() -> NSTimeInterval {
return round(self/1000)
}
public var inThePast: NSTimeInterval {
return -self
}
public func toDateUsingMilliseconds() -> NSDate {
let date = NSDate(timeIntervalSince1970:millisecondsToSecondsTimeInterval())
return date
}
}
extension NSTimeInterval {
var minuteSecondMS: String {
return String(format:"%d:%02d.%03d", minute , second, millisecond )
}
var minute: Double {
return (self/60.0)%60
}
var second: Double {
return self % 60
}
var millisecond: Double {
return self*1000
}
}
extension Int {
var msToSeconds: Double {
return Double(self) / 1000
}
}
|
db2af920be2fe62471f001e75ee34311
| 24.643312 | 96 | 0.599006 | false | false | false | false |
mikaelbo/MBFacebookImagePicker
|
refs/heads/master
|
MBFacebookImagePicker/Views/MBFacebookPickerEmptyView.swift
|
mit
|
1
|
//
// MBFacebookPickerEmptyView.swift
// FacebookImagePicker
//
// Copyright © 2017 Mikaelbo. All rights reserved.
//
import UIKit
class MBFacebookPickerEmptyView: UIView {
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
configureLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureLabel()
}
fileprivate func configureLabel() {
titleLabel.numberOfLines = 2
let wantedSize = CGSize(width: 205, height: 40)
titleLabel.textAlignment = .center
titleLabel.frame = CGRect(x: (bounds.size.width - wantedSize.width) / 2,
y: (bounds.size.height - wantedSize.height) / 2,
width: wantedSize.width,
height: wantedSize.height)
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textColor = UIColor(red: 85 / 255, green: 85 / 255, blue: 85 / 255, alpha: 0.5)
titleLabel.autoresizingMask = [.flexibleTopMargin,
.flexibleBottomMargin,
.flexibleLeftMargin,
.flexibleRightMargin]
addSubview(titleLabel)
}
}
|
a6e124945f94a3bddabb9e5fcc82bd5a
| 32.025 | 98 | 0.561696 | false | true | false | false |
jeevanRao7/Swift_Playgrounds
|
refs/heads/master
|
Swift Playgrounds/Design Patterns/Interpreter.playground/Contents.swift
|
mit
|
1
|
/*
*********************************************
Interpreter Pattern
Reference: http://www.oodesign.com/interpreter-pattern.html
*********************************************
Problem Statement :
SENTENCE: ((true * k) + h)
GRAMMER :
BooleanExp ::= Constant | Variable | OrExp | AndExp | NotExp
AndExp ::= BooleanExp ’*’ BooleanExp
OrExp ::= BooleanExp ’+’ BooleanExp
NotExp ::= ’~’ BooleanExp
Variable ::= [A-z][A-z]*
Constant ::= ’true’ | ’false’
*********************************************/
//Protocol + Extension = Abstract class.
protocol BooleanExpression {
func interpret(ctx:Context) -> Bool;
}
extension BooleanExpression {
func interpret(ctx:Context) -> Bool {
assertionFailure("Expression must be implemented in Concrete Class")
return false;
}
}
//Context - Concrete Class
public class Context {
var hash:Dictionary<String, Bool> = Dictionary()
public func lookUp(variable:Variable) -> Bool {
return hash[variable.localVariable]!
}
public func assignValue(variable:Variable , value:Bool) {
self.hash.updateValue(value, forKey: variable.localVariable)
}
}
public class Constant : BooleanExpression {
var booleanValue : Bool
//Constructor
init(booleanValue:Bool) {
self.booleanValue = booleanValue;
}
//Concrete method
public func interpret(ctx: Context) -> Bool {
return self.booleanValue;
}
}
public class Variable : BooleanExpression {
var localVariable:String;
//Constructor
init(localVariable : String) {
self.localVariable = localVariable;
}
public func interpret(ctx: Context) -> Bool{
return ctx.lookUp(variable:self);
}
}
public class AndExpression : BooleanExpression {
var leftExp:BooleanExpression;
var rightExp:BooleanExpression;
//constuctor
init(leftExp:BooleanExpression, rightExp:BooleanExpression) {
self.leftExp = leftExp;
self.rightExp = rightExp;
}
public func interpret(ctx: Context) -> Bool {
return (leftExp.interpret(ctx:ctx) && rightExp.interpret(ctx:ctx))
}
}
public class NotExpression : BooleanExpression {
var exp:BooleanExpression;
//constuctor
init(exp:BooleanExpression) {
self.exp = exp;
}
public func interpret(ctx: Context) -> Bool {
return !(exp.interpret(ctx:ctx))
}
}
public class OrExpression : BooleanExpression {
var leftExp:BooleanExpression;
var rightExp:BooleanExpression;
//constuctor
init(leftExp:BooleanExpression, rightExp:BooleanExpression) {
self.leftExp = leftExp;
self.rightExp = rightExp;
}
public func interpret(ctx: Context) -> Bool {
return (leftExp.interpret(ctx:ctx) || rightExp.interpret(ctx:ctx))
}
}
/********** Main **********/
let context = Context();
let exp1 = Constant.init(booleanValue: true);
let exp2 = Variable.init(localVariable: "k");
let exp3 = Variable.init(localVariable: "h");
let exp4 = AndExpression.init(leftExp: exp1, rightExp: exp2);
let finalExp = OrExpression.init(leftExp: exp4, rightExp: exp3);
context.assignValue(variable: exp2 , value: false);
context.assignValue(variable: exp3 , value: true);
print("Final result of Expression : \(finalExp.interpret(ctx: context))")
/* Simplified version
let k = Variable.init(localVariable: "k");
let h = Variable.init(localVariable: "h");
let finalExp = AndExpression(leftExp: Constant.init(booleanValue: true), rightExp: OrExpression.init(leftExp: k, rightExp: h))
context.assignValue(variable: k, value: false)
context.assignValue(variable: h, value: false)
*/
|
b6e12ac6ccfc16207999c22d6d4c8304
| 22.425926 | 127 | 0.627404 | false | false | false | false |
raulriera/Bike-Compass
|
refs/heads/master
|
App/Carthage/Checkouts/Alamofire/Tests/UploadTests.swift
|
mit
|
2
|
//
// UploadTests.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class UploadFileInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndFile() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, urlString, file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndFile() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], file: imageURL)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndData() {
// Given
let urlString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, urlString, data: Data())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndData() {
// Given
let urlString = "https://httpbin.org/"
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], data: Data())
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadStreamInitializationTestCase: BaseTestCase {
func testUploadClassMethodWithMethodURLAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(.POST, urlString, stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
XCTAssertNil(request.response, "response should be nil")
}
func testUploadClassMethodWithMethodURLHeadersAndStream() {
// Given
let urlString = "https://httpbin.org/"
let imageURL = URLForResource("rainbow", withExtension: "jpg")
let imageStream = InputStream(url: imageURL)!
// When
let request = Alamofire.upload(.POST, urlString, headers: ["Authorization": "123456"], stream: imageStream)
// Then
XCTAssertNotNil(request.request, "request should not be nil")
XCTAssertEqual(request.request?.httpMethod ?? "", "POST", "request HTTP method should be POST")
XCTAssertEqual(request.request?.urlString ?? "", urlString, "request URL string should be equal")
let authorizationHeader = request.request?.value(forHTTPHeaderField: "Authorization") ?? ""
XCTAssertEqual(authorizationHeader, "123456", "Authorization header is incorrect")
XCTAssertNil(request.response, "response should be nil")
}
}
// MARK: -
class UploadDataTestCase: BaseTestCase {
func testUploadDataRequest() {
// Given
let urlString = "https://httpbin.org/post"
let data = "Lorem ipsum dolor sit amet".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "Upload request should succeed: \(urlString)")
var request: URLRequest?
var response: HTTPURLResponse?
var error: NSError?
// When
Alamofire.upload(.POST, urlString, data: data)
.response { responseRequest, responseResponse, _, responseError in
request = responseRequest
response = responseResponse
error = responseError
expectation.fulfill()
}
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testUploadDataRequestWithProgress() {
// Given
let urlString = "https://httpbin.org/post"
let data: Data = {
var text = ""
for _ in 1...3_000 {
text += "Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}
return text.data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(withDescription: "Bytes upload progress should be reported: \(urlString)")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var responseRequest: URLRequest?
var responseResponse: HTTPURLResponse?
var responseData: Data?
var responseError: ErrorProtocol?
// When
let upload = Alamofire.upload(.POST, urlString, data: data)
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (bytes: bytesWritten, totalBytes: totalBytesWritten, totalBytesExpected: totalBytesExpectedToWrite)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { request, response, data, error in
responseRequest = request
responseResponse = response
responseData = data
responseError = error
expectation.fulfill()
}
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(responseRequest, "response request should not be nil")
XCTAssertNotNil(responseResponse, "response response should not be nil")
XCTAssertNotNil(responseData, "response data should not be nil")
XCTAssertNil(responseError, "response error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
// MARK: -
class UploadMultipartFormDataTestCase: BaseTestCase {
// MARK: Tests
func testThatUploadingMultipartFormDataSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload_data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataSucceedsWithDefaultParameters() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
func testThatUploadingMultipartFormDataWhileStreamingFromMemoryMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: false)
}
func testThatUploadingMultipartFormDataWhileStreamingFromDiskMonitorsProgress() {
executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: true)
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdStreamsFromMemory() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNil(streamFileURL, "stream file URL should be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
}
func testThatUploadingMultipartFormDataBelowMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertFalse(streamingFromDisk, "streaming from disk should be false")
}
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdStreamsFromDisk() {
// Given
let urlString = "https://httpbin.org/post"
let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var streamingFromDisk: Bool?
var streamFileURL: URL?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: french, name: "french")
multipartFormData.appendBodyPart(data: japanese, name: "japanese")
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, uploadStreamFileURL):
streamingFromDisk = uploadStreamingFromDisk
streamFileURL = uploadStreamFileURL
upload.response { _, _, _, _ in
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
XCTAssertNotNil(streamFileURL, "stream file URL should not be nil")
if let
streamingFromDisk = streamingFromDisk,
streamFilePath = streamFileURL?.path
{
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
XCTAssertTrue(
FileManager.default().fileExists(atPath: streamFilePath),
"stream file path should exist"
)
}
}
func testThatUploadingMultipartFormDataAboveMemoryThresholdSetsContentTypeHeader() {
// Given
let urlString = "https://httpbin.org/post"
let uploadData = "upload data".data(using: String.Encoding.utf8, allowLossyConversion: false)!
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var formData: MultipartFormData?
var request: URLRequest?
var streamingFromDisk: Bool?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: uploadData, name: "upload_data")
formData = multipartFormData
},
encodingMemoryThreshold: 0,
encodingCompletion: { result in
switch result {
case let .success(upload, uploadStreamingFromDisk, _):
streamingFromDisk = uploadStreamingFromDisk
upload.response { responseRequest, _, _, _ in
request = responseRequest
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(streamingFromDisk, "streaming from disk should not be nil")
if let streamingFromDisk = streamingFromDisk {
XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
}
if let
request = request,
multipartFormData = formData,
contentType = request.value(forHTTPHeaderField: "Content-Type")
{
XCTAssertEqual(contentType, multipartFormData.contentType, "Content-Type header value should match")
} else {
XCTFail("Content-Type header value should not be nil")
}
}
// ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1
// func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() {
// // Given
// let manager: Manager = {
// let identifier = "com.alamofire.uploadtests.\(UUID().uuidString)"
// let configuration = URLSessionConfiguration.backgroundSessionConfigurationForAllPlatformsWithIdentifier(identifier)
//
// return Manager(configuration: configuration, serverTrustPolicyManager: nil)
// }()
//
// let urlString = "https://httpbin.org/post"
// let french = "français".data(using: String.Encoding.utf8, allowLossyConversion: false)!
// let japanese = "日本語".data(using: String.Encoding.utf8, allowLossyConversion: false)!
//
// let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
//
// var request: URLRequest?
// var response: HTTPURLResponse?
// var data: Data?
// var error: NSError?
// var streamingFromDisk: Bool?
//
// // When
// manager.upload(
// .POST,
// urlString,
// multipartFormData: { multipartFormData in
// multipartFormData.appendBodyPart(data: french, name: "french")
// multipartFormData.appendBodyPart(data: japanese, name: "japanese")
// },
// encodingCompletion: { result in
// switch result {
// case let .success(upload, uploadStreamingFromDisk, _):
// streamingFromDisk = uploadStreamingFromDisk
//
// upload.response { responseRequest, responseResponse, responseData, responseError in
// request = responseRequest
// response = responseResponse
// data = responseData
// error = responseError
//
// expectation.fulfill()
// }
// case .failure:
// expectation.fulfill()
// }
// }
// )
//
// waitForExpectations(withTimeout: timeout, handler: nil)
//
// // Then
// XCTAssertNotNil(request, "request should not be nil")
// XCTAssertNotNil(response, "response should not be nil")
// XCTAssertNotNil(data, "data should not be nil")
// XCTAssertNil(error, "error should be nil")
//
// if let streamingFromDisk = streamingFromDisk {
// XCTAssertTrue(streamingFromDisk, "streaming from disk should be true")
// } else {
// XCTFail("streaming from disk should not be nil")
// }
// }
// MARK: Combined Test Execution
private func executeMultipartFormDataUploadRequestWithProgress(streamFromDisk: Bool) {
// Given
let urlString = "https://httpbin.org/post"
let loremData1: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
}
return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let loremData2: Data = {
var loremValues: [String] = []
for _ in 1...1_500 {
loremValues.append("Lorem ipsum dolor sit amet, nam no graeco recusabo appellantur.")
}
return loremValues.joined(separator: " ").data(using: String.Encoding.utf8, allowLossyConversion: false)!
}()
let expectation = self.expectation(withDescription: "multipart form data upload should succeed")
var byteValues: [(bytes: Int64, totalBytes: Int64, totalBytesExpected: Int64)] = []
var progressValues: [(completedUnitCount: Int64, totalUnitCount: Int64)] = []
var request: URLRequest?
var response: HTTPURLResponse?
var data: Data?
var error: NSError?
// When
Alamofire.upload(
.POST,
urlString,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: loremData1, name: "lorem1")
multipartFormData.appendBodyPart(data: loremData2, name: "lorem2")
},
encodingMemoryThreshold: streamFromDisk ? 0 : 100_000_000,
encodingCompletion: { result in
switch result {
case .success(let upload, _, _):
upload.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
let bytes = (
bytes: bytesWritten,
totalBytes: totalBytesWritten,
totalBytesExpected: totalBytesExpectedToWrite
)
byteValues.append(bytes)
let progress = (
completedUnitCount: upload.progress.completedUnitCount,
totalUnitCount: upload.progress.totalUnitCount
)
progressValues.append(progress)
}
upload.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
case .failure:
expectation.fulfill()
}
}
)
waitForExpectations(withTimeout: timeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
XCTAssertEqual(byteValues.count, progressValues.count, "byteValues count should equal progressValues count")
if byteValues.count == progressValues.count {
for index in 0..<byteValues.count {
let byteValue = byteValues[index]
let progressValue = progressValues[index]
XCTAssertGreaterThan(byteValue.bytes, 0, "reported bytes should always be greater than 0")
XCTAssertEqual(
byteValue.totalBytes,
progressValue.completedUnitCount,
"total bytes should be equal to completed unit count"
)
XCTAssertEqual(
byteValue.totalBytesExpected,
progressValue.totalUnitCount,
"total bytes expected should be equal to total unit count"
)
}
}
if let
lastByteValue = byteValues.last,
lastProgressValue = progressValues.last
{
let byteValueFractionalCompletion = Double(lastByteValue.totalBytes) / Double(lastByteValue.totalBytesExpected)
let progressValueFractionalCompletion = Double(lastProgressValue.0) / Double(lastProgressValue.1)
XCTAssertEqual(byteValueFractionalCompletion, 1.0, "byte value fractional completion should equal 1.0")
XCTAssertEqual(
progressValueFractionalCompletion,
1.0,
"progress value fractional completion should equal 1.0"
)
} else {
XCTFail("last item in bytesValues and progressValues should not be nil")
}
}
}
|
14974fee540a544f739b26b02ade9e80
| 38.957087 | 129 | 0.607772 | false | false | false | false |
iOS-mamu/SS
|
refs/heads/master
|
P/Potatso/Sync/PushLocalChangesOperation.swift
|
mit
|
1
|
//
// PushLocalChangesOperation.swift
// Potatso
//
// Created by LEI on 8/12/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import Foundation
import PSOperations
import CloudKit
class PushLocalChangesOperation: PSOperations.Operation {
let zoneID: CKRecordZoneID
fileprivate let internalQueue = PSOperations.OperationQueue()
var toSaveRecords: [CKRecord] = []
var toDeleteRecordIDs: [CKRecordID] = []
var maxRecordsPerRequest = 400
init(zoneID: CKRecordZoneID) {
self.zoneID = zoneID
super.init()
internalQueue.maxConcurrentOperationCount = 15
}
override func execute() {
DDLogInfo(">>>>>> Start Push Local Changes...")
let toSaveObjects = DBUtils.allObjectsToSyncModified()
let toDeleteObjects = DBUtils.allObjectsToSyncDeleted()
toSaveRecords = toSaveObjects.map {
($0 as! CloudKitRecord).toCloudKitRecord()
}
toDeleteRecordIDs = toDeleteObjects.map {
($0 as! CloudKitRecord).recordId
}
DDLogInfo("toSaveRecords: \(toSaveRecords.count), toDeleteRecordIDs: \(toDeleteRecordIDs.count)")
let finishObserver = BlockObserver { operation, errors in
self.finish(errors)
return
}
let finishOp = PSOperations.BlockOperation {}
finishOp.addObserver(finishObserver)
if toSaveRecords.count > maxRecordsPerRequest {
let total = toSaveRecords.count/maxRecordsPerRequest + 1
for i in 0..<total {
let start = i * maxRecordsPerRequest
let end = min((i + 1) * maxRecordsPerRequest, toSaveRecords.count)
let records = Array(toSaveRecords[start..<end])
let op = addModifiedOperation("Push Local Modified Changes <\(i)/\(total), count: \(records.count)>", records: records)
internalQueue.addOperation(op)
finishOp.addDependency(op)
}
} else {
let op = addModifiedOperation("Push Local Modified Changes<count: \(toSaveRecords.count)>", records: toSaveRecords)
internalQueue.addOperation(op)
finishOp.addDependency(op)
}
if toDeleteRecordIDs.count > maxRecordsPerRequest {
let total = toDeleteRecordIDs.count/maxRecordsPerRequest + 1
for i in 0..<total {
let start = i * maxRecordsPerRequest
let end = min((i + 1) * maxRecordsPerRequest, toDeleteRecordIDs.count)
let recordIDs = Array(toDeleteRecordIDs[start..<end])
let op = addDeletedOperation("Push Local Deleted Changes <\(i)/\(total), count: \(recordIDs.count)>", recordIDs: recordIDs)
internalQueue.addOperation(op)
finishOp.addDependency(op)
}
} else {
let op = addDeletedOperation("Push Local Deleted Changes<count: \(toDeleteRecordIDs.count)>", recordIDs: toDeleteRecordIDs)
internalQueue.addOperation(op)
finishOp.addDependency(op)
}
internalQueue.addOperation(finishOp)
}
func addModifiedOperation(_ name: String, records: [CKRecord]) -> PSOperations.Operation {
let op = PushLocalModifiedChangesOperation(zoneID: potatsoZoneId, name: name, modifiedRecords: records)
return op
}
func addDeletedOperation(_ name: String, recordIDs: [CKRecordID]) -> PSOperations.Operation {
let op = PushLocalDeletedChangesOperation(zoneID: potatsoZoneId, name: name, deletedRecordIDs: recordIDs)
return op
}
}
|
2e76f5120f839fbba2892b679588c0a5
| 40.425287 | 139 | 0.642342 | false | false | false | false |
skylib/SnapImagePicker
|
refs/heads/master
|
SnapImagePicker/Categories/UIImage+square.swift
|
bsd-3-clause
|
1
|
import UIKit
extension UIImage {
func square() -> UIImage?{
let x = self.size.width <= self.size.height ? 0 : (self.size.width - self.size.height) / 2
let y = self.size.height <= self.size.width ? 0 : (self.size.height - self.size.width) / 2
let width = min(self.size.width, self.size.height)
let height = width
let cropRect = CGRect(x: x * self.scale, y: y * self.scale, width: width * self.scale, height: height * self.scale)
if let cgImage = self.cgImage!.cropping(to: cropRect) {
return UIImage(cgImage: cgImage)
}
return nil
}
}
extension UIImage {
func findZoomScaleForLargestFullSquare() -> CGFloat {
return max(size.width, size.height)/min(size.width, size.height)
}
func findCenteredOffsetForImageWithZoomScale(_ zoomScale: CGFloat) -> CGFloat {
return abs(size.height - size.width) * zoomScale / 2
}
}
|
5621b8d659269ca15d66648ea2dac501
| 33.703704 | 123 | 0.6254 | false | false | false | false |
barbrobmich/linkbase
|
refs/heads/master
|
LinkBase/LinkBase/ProfileLanguageCell.swift
|
mit
|
1
|
//
// ProfileLanguageCell.swift
// LinkBase
//
// Created by Barbara Ristau on 4/7/17.
// Copyright © 2017 barbrobmich. All rights reserved.
//
import UIKit
class ProfileLanguageCell: UITableViewCell {
@IBOutlet weak var languageNameLabel: UILabel!
@IBOutlet weak var languageImageView: UIImageView!
@IBOutlet weak var collectionView: UICollectionView!
var retrievedAffiliations: [Affiliation] = []
var retrievedProjects: [Project] = []
var matchedItemsCount: Int!
var projectIndex: Int = 0
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
collectionView.dataSource = self
collectionView.delegate = self
}
}
extension ProfileLanguageCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//return 10
return matchedItemsCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ProfileLangCollectionCell", for: indexPath) as! ProfileLangCollectionCell
if retrievedAffiliations.count != 0 && retrievedProjects.count == 0 {
cell.affiliation = retrievedAffiliations[indexPath.item]
cell.affProjNameLabel.text = retrievedAffiliations[indexPath.item].name
}
else if retrievedProjects.count != 0 && retrievedAffiliations.count == 0 {
cell.project = retrievedProjects[indexPath.item]
cell.affProjNameLabel.text = retrievedProjects[indexPath.item].name
}
else if retrievedAffiliations.count > 0 && retrievedProjects.count > 0 {
if indexPath.item < retrievedAffiliations.count {
cell.affiliation = retrievedAffiliations[indexPath.item]
cell.affProjNameLabel.text = retrievedAffiliations[indexPath.item].name
}
if indexPath.item >= retrievedAffiliations.count && indexPath.item < matchedItemsCount {
cell.project = retrievedProjects[projectIndex]
cell.affProjNameLabel.text = retrievedProjects[projectIndex].name
projectIndex += 1
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
}
|
933f6bdb76121c20385e758fb1ea65b0
| 34.039474 | 149 | 0.673676 | false | false | false | false |
wojteklu/logo
|
refs/heads/master
|
Logo/Playground.playground/Contents.swift
|
mit
|
1
|
//: Playground - noun: a place where people can play
import Logo
let code20 = "" +
"to qcircle :size " +
"repeat 90 [fd(:size) rt(1)] " +
"end " +
//"to petal :size " +
//"qcircle(:size) " +
//"rt(90) " +
//"qcircle(:size) " +
//"rt(90) " +
//"end " +
"qcircle(5) rt(90) qcircle(5)"
let code = "fd(100) rt(90) fd(100)"
//let code2 = "to wojtek fd(100) end wojtek() rt(90) wojtek()"
let code13 = "" +
"to qcircle :size " +
"repeat 90 [fd(:size) rt(1)] " +
"end " +
"to petal :size " +
"qcircle(:size) " +
"rt(90) " +
"qcircle(:size) " +
"rt(90) " +
"end " +
"to flower :size " +
"repeat 10 [petal(:size) rt(360/10)] " +
"end " +
"to plant :size " +
"flower(:size) " +
"bk(135 * :size) " +
"petal(:size) " +
"bk(65 * :size) " +
"end " +
"repeat 1 [ plant(2) ] "
let code3 = "" +
"to tree :size " +
"if (:size < 5) [fd(:size) bk(:size) ] else [" +
"fd(:size/3) " +
"lt(30) tree(:size*2/3) rt(30) " +
"fd(:size/6) " +
"rt(25) tree(:size/2) lt(25) " +
"fd(:size/3) " +
"rt(25) tree(:size/2) lt(25) " +
"fd(:size/6) " +
"bk(:size) ]" +
"end " +
"to qcircle :size " +
"repeat 90 [fd(:size) rt(1)] " +
"end " +
"bk(150) tree(250) "
let code4 = "" +
"to fern :size :sign " +
"if (:size > 1) [" +
"fd(:size) " +
"rt(70 * :sign) fern(:size * 1/2, :sign * 1) lt(70 * :sign) " +
"fd(:size) " +
"lt(70 * :sign) fern(:size * 1/2, :sign) rt(70 * :sign) " +
"rt(7 * :sign) fern(:size - 1, :sign) lt(7 * :sign) " +
"bk(:size * 2) ] " +
"end " +
"fern(30, 1)"
let code10 = "" +
"to line :count :length " +
"if (:count = 1) [fd(:length)] " +
"else [ " +
"line(:count-1, :length) " +
"lt(60) line(:count-1, :length) " +
"rt(120) line(:count-1, :length) " +
"lt(60) line(:count-1, :length) " +
" ] end " +
"to koch :count :length " +
"rt(30) line(:count, :length) " +
"rt(120) line(:count, :length) " +
"rt(120) line(:count, :length) " +
"end " +
"koch(5, 10)"
let code100 = "" +
"repeat 100 [" +
"repeat 8 [" +
"fd(80)" +
"rt(80)" +
"bk(80)" +
"] " +
"rt(45)" +
"]"
let code2 = "to square :length repeat 4 [ forward(:length) right(90) ] end repeat 220 [ square(random(200)) right(10) ]"
let interpreter = Interpreter()
interpreter.run(code: code2)
|
44cd54c04071b41b4bdcbb484b38703b
| 21.358491 | 120 | 0.467932 | false | false | false | false |
mgzf/MGAssociationMenuView
|
refs/heads/master
|
Sources/MGAssociationPeriferal.swift
|
mit
|
1
|
//
//
// _____
// / ___/____ ____ ____ _
// \__ \/ __ \/ __ \/ __ `/
// ___/ / /_/ / / / / /_/ /
// /____/\____/_/ /_/\__, /
// /____/
//
// .-~~~~~~~~~-._ _.-~~~~~~~~~-.
// __.' ~. .~ `.__
// .'// \./ \\`.
// .'// | \\`.
// .'// .-~"""""""~~~~-._ | _,-~~~~"""""""~-. \\`.
// .'//.-" `-. | .-' "-.\\`.
// .'//______.============-.. \ | / ..-============.______\\`.
//.'______________________________\|/______________________________`.
//
//
// BottomLineVisible.swift
// MGAssociationMenuView
//
// Created by song on 2017/8/1.
// Copyright © 2017年 song. All rights reserved.
//
import UIKit
//MARK: - MenuView 高度控制
public enum MGAssociationFrameEnum: Int{
/*!根据高度自动计算出最多显示多少行 */
case autoLayout = 0
/*! 直接显示本身高度 */
case custom
}
//MARK: - view加线 Protocol
public protocol BottomLineVisible : class {
var lineColor: UIColor { get set }
var lineHeight: CGFloat { get set }
func addLineTo(view:UIView, edge:UIEdgeInsets?)
func deleteLineTo(view:UIView)
}
extension BottomLineVisible{
public func addLineTo(view:UIView, edge:UIEdgeInsets?){
let lineEdge = edge ?? UIEdgeInsets.zero
let lineView = UIView()
lineView.tag = 135792
lineView.backgroundColor = lineColor
view.addSubview(lineView)
lineView.snp.makeConstraints { (make) in
make.left.equalTo(view).offset(lineEdge.left)
make.right.equalTo(view).offset(lineEdge.right)
make.bottom.equalTo(view).offset(lineEdge.bottom)
make.height.equalTo(lineHeight)
}
}
public func deleteLineTo(view:UIView){
if let subView = view.viewWithTag(135792) {
subView.removeFromSuperview()
}
}
}
|
695edeb70df118b3f6f96933b127bea6
| 25.6875 | 69 | 0.392037 | false | false | false | false |
eurofurence/ef-app_ios
|
refs/heads/release/4.0.0
|
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Settings/App Icon Picker/View Model/Repository Adapter/RepositoryBackedAppIconsViewModel.swift
|
mit
|
1
|
import Combine
public class RepositoryBackedAppIconsViewModel<IconState>: AppIconsViewModel where IconState: ApplicationIconState {
public init(repository: any AppIconRepository, applicationIconState: IconState) {
let repositoryIcons = repository.loadAvailableIcons()
icons = repositoryIcons.map({ IconViewModel(icon: $0, applicationIconState: applicationIconState) })
}
public typealias Icon = IconViewModel
public private(set) var icons: [IconViewModel]
public class IconViewModel: AppIconViewModel {
private let icon: AppIcon
private let applicationIconState: IconState
private var subscriptions = Set<AnyCancellable>()
init(icon: AppIcon, applicationIconState: IconState) {
self.icon = icon
self.applicationIconState = applicationIconState
applicationIconState
.alternateIconNamePublisher
.map({ [icon] (alternateIconName) in icon.alternateIconName == alternateIconName })
.sink { [weak self] in self?.isCurrentAppIcon = $0 }
.store(in: &subscriptions)
}
public var imageName: String {
icon.imageFileName
}
public var displayName: String {
icon.displayName
}
@Published public private(set) var isCurrentAppIcon: Bool = false
public func selectAsAppIcon() {
applicationIconState.updateApplicationIcon(alternateIconName: icon.alternateIconName)
}
}
}
|
bf140376efae97311729ebbd0c5e7840
| 33.617021 | 116 | 0.630608 | false | false | false | false |
antitypical/Manifold
|
refs/heads/master
|
Manifold/Module+Prelude.swift
|
mit
|
1
|
// Copyright © 2015 Rob Rix. All rights reserved.
extension Module {
public static var prelude: Module {
let identity = Declaration("identity",
type: nil => { A in A --> A },
value: nil => { A in A => id })
let constant = Declaration("constant",
type: (nil, nil) => { A, B in A --> B --> A },
value: (nil, nil) => { A, B in A => { B => const($0) } })
let flip = Declaration("flip",
type: (nil, nil, nil) => { A, B, C in (A --> B --> C) --> (B --> A --> C) },
value: (nil, nil, nil) => { A, B, C in (A --> B --> C) => { f in (nil, nil) => { b, a in f[a, b] } } })
return Module("Prelude", [ identity, constant, flip ])
}
}
import Prelude
|
d7015b6111f72809ac8278badd339a1b
| 29.545455 | 106 | 0.50744 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity
|
refs/heads/master
|
EnjoyUniversity/EnjoyUniversity/Classes/Tools/SwiftyControl/SwiftySpinner.swift
|
mit
|
1
|
//
// SwiftySpinner.swift
// EnjoyUniversity
//
// Created by lip on 17/4/15.
// Copyright © 2017年 lip. All rights reserved.
//
import UIKit
protocol SwiftySpinnerDelegate {
/// 选中
func swiftySpinnerDidSelectRowAt(cell:SwiftySpinnerCell,row:Int)
/// 显示状态变化
func swiftySpinnerDidChangeStatus(isOnView:Bool)
}
class SwiftySpinner: UIView {
/// 下拉选择列表
lazy var spinnertableview = UITableView()
/// 下拉选择数组
var datalist = [String]()
/// 是否显示
var isOnView: Bool = false{
didSet{
delegate?.swiftySpinnerDidChangeStatus(isOnView: isOnView)
}
}
/// 代理
var delegate:SwiftySpinnerDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.6)
spinnertableview.layer.masksToBounds = true
spinnertableview.layer.cornerRadius = 10
spinnertableview.separatorStyle = .none
spinnertableview.delegate = self
spinnertableview.dataSource = self
spinnertableview.backgroundColor = UIColor.white
addSubview(spinnertableview)
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(removeSpinner))
tapgesture.delegate = self
addGestureRecognizer(tapgesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reloadData(){
let tbheight:CGFloat = CGFloat(datalist.count > 3 ? 4 : datalist.count)*44.0
spinnertableview.frame = CGRect(x: 10, y: -tbheight , width: UIScreen.main.bounds.width - 20, height: tbheight)
spinnertableview.reloadData()
}
}
// MARK: - 动画方法
extension SwiftySpinner{
func showSpinner(){
isOnView = true
self.alpha = 1
UIView.animate(withDuration: 0.5) {
self.spinnertableview.frame.origin = CGPoint(x: 10, y: 64 + 10)
}
}
func removeSpinner(){
isOnView = false
UIView.animate(withDuration: 0.5, animations: {
self.alpha = 0
self.spinnertableview.frame.origin = CGPoint(x: 5, y: -self.spinnertableview.frame.height)
}) { (_) in
self.removeFromSuperview()
}
}
}
// MARK: - 代理方法
extension SwiftySpinner:UIGestureRecognizerDelegate,UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return datalist.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = SwiftySpinnerCell(title: datalist[indexPath.row], font: 15, textcolor: UIColor.darkText)
if indexPath.row == 0{
cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1)
cell.indicatorview.isHidden = false
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
for cell in tableView.visibleCells{
let cell = cell as? SwiftySpinnerCell
cell?.textlabel.textColor = UIColor.darkText
cell?.indicatorview.isHidden = true
}
guard let cell = tableView.cellForRow(at: indexPath) as? SwiftySpinnerCell else{
return
}
cell.textlabel.textColor = UIColor.init(red: 18/255, green: 150/255, blue: 219/255, alpha: 1)
cell.indicatorview.isHidden = false
removeSpinner()
delegate?.swiftySpinnerDidSelectRowAt(cell: cell, row: indexPath.row)
}
// 解决手势和 tableview 响应冲突
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
if NSStringFromClass((touch.view?.classForCoder)!) == "UITableViewCellContentView"{
return false
}
return true
}
}
/// 自定义 Cell
class SwiftySpinnerCell:UITableViewCell{
let textlabel = UILabel()
let indicatorview = UIImageView(image: UIImage(named: "community_select"))
init(title:String,font:CGFloat = 15,textcolor:UIColor = UIColor.darkText) {
super.init(style: .default, reuseIdentifier: nil)
selectionStyle = .none
textlabel.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width - 20, height: self.frame.height)
textlabel.text = title
textlabel.textAlignment = .center
textlabel.font = UIFont.boldSystemFont(ofSize: font)
textlabel.textColor = textcolor
textlabel.backgroundColor = UIColor.clear
addSubview(textlabel)
indicatorview.frame = CGRect(x: 5, y: 5, width: 5, height: frame.height - 10)
indicatorview.isHidden = true
addSubview(indicatorview)
self.backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
3f4dc5a57d298230d5cab695474ca5f0
| 28.384181 | 119 | 0.620265 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.