repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tianbinbin/DouYuShow
|
DouYuShow/DouYuShow/Classes/Main/Model/AnchorModel.swift
|
1
|
952
|
//
// AnchorModel.swift
// DouYuShow
//
// Created by 田彬彬 on 2017/6/5.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
var room_id :Int = 0 //房间号
var vertical_src :String = "" //房间对应的urlstring
var isVertical :Int = 0 //0 表示电脑直播 1 手机直播
var room_name :String = "" //房间名称
var nickname :String = "" //主播名称
var online:Int = 0 //在线人数
var anchor_city :String = "" //所在城市
init(dict:[String:Any]) {
super.init()
setValuesForKeys(dict)
}
// 因为字典 dict 可能由很多的key 我们需要的只需要这么多 所以要重写这个方法 不然会crash
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
|
mit
|
11f3f1e132797d1e74e048801b41001c
| 23.333333 | 72 | 0.520548 | 3.82381 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/LinkedList/61_RotateList.swift
|
1
|
998
|
//
// 61_RotateList.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-06.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:61 Rotate List
URL: https://leetcode.com/problems/rotate-list/
Space: O(1)
Time: O(N)
*/
class RotateList_Solution {
func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
guard let validHead = head else {
return nil
}
var totalCount = 1
var currentNode = validHead
while let nextNode = currentNode.next {
totalCount += 1
currentNode = nextNode
}
var needRotate = k % totalCount
var prevNode: ListNode? = validHead
var postNode: ListNode? = validHead
while needRotate > 0 {
postNode = postNode?.next
needRotate -= 1
}
while postNode?.next != nil {
postNode = postNode?.next
prevNode = prevNode?.next
}
postNode?.next = head
postNode = prevNode?.next
prevNode?.next = nil
return postNode
}
}
|
mit
|
d27509a368becdbf18fa18e0cc68c9a6
| 19.346939 | 62 | 0.627884 | 3.70632 | false | false | false | false |
AlphaJian/PaperCalculator
|
PaperCalculator/PaperCalculator/Class/MainViewController.swift
|
1
|
2059
|
//
// MainViewController.swift
// PaperCalculator
//
// Created by appledev018 on 9/28/16.
// Copyright © 2016 apple. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
@IBOutlet weak var btn1: UIButton!
@IBOutlet weak var btn2: UIButton!
@IBOutlet weak var btn3: UIButton!
@IBOutlet weak var btn4: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
btn1.layer.cornerRadius = 10
btn2.layer.cornerRadius = 10
btn3.layer.cornerRadius = 10
btn4.layer.cornerRadius = 10
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pi(_ sender: AnyObject) {
let vc = ReviewPaperViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func setting(_ sender: AnyObject) {
let vc = SettingPaperViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func checkReport(_ sender: AnyObject) {
let vc = ReportViewController()
DataManager.shareManager.getRank()
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func checkCharts(_ sender: AnyObject) {
let vc = ChartsViewController()
DataManager.shareManager.getStatistics()
self.navigationController?.pushViewController(vc, animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
fbbcd3d4c6484e410c8a31b6521fd165
| 25.050633 | 106 | 0.641885 | 5.081481 | false | false | false | false |
crspybits/SMSyncServer
|
iOS/iOSTests/Pods/SMSyncServer/SMSyncServer/Classes/Internal/CoreData/SMUploadFile.swift
|
3
|
3805
|
//
// SMUploadFile.swift
//
//
// Created by Christopher Prince on 1/18/16.
//
//
import Foundation
import CoreData
import SMCoreLib
/* Core Data model notes:
1) filePathBaseURLType is the raw value of the SMRelativeLocalURL BaseURLType (nil if file change indicates a deletion).
2) filePath is the relative path of the URL in the case of a local relative url or the path for other urls (nil if file change indicates a deletion).
*/
@objc(SMUploadFile)
class SMUploadFile: SMUploadFileOperation, CoreDataModel {
// To deal with conflict resolution. Leave this as nil if you don't want undeletion. Set it to true if you do want undeletion.
var undeleteServerFile:Bool? {
set {
self.internalUndeleteServerFile = newValue
CoreData.sessionNamed(SMCoreData.name).saveContext()
}
get {
if self.internalUndeleteServerFile == nil {
return nil
}
else {
return self.internalUndeleteServerFile!.boolValue
}
}
}
class func entityName() -> String {
return "SMUploadFile"
}
class func newObject() -> NSManagedObject {
let fileChange = CoreData.sessionNamed(SMCoreData.name).newObjectWithEntityName(self.entityName()) as! SMUploadFile
fileChange.operationStage = .ServerUpload
CoreData.sessionNamed(SMCoreData.name).saveContext()
return fileChange
}
// Returns nil if the file change indicates a deletion. Don't use self.internalRelativeLocalURL directly.
var fileURL: SMRelativeLocalURL? {
get {
return CoreData.getSMRelativeLocalURL(fromCoreDataProperty: self.internalRelativeLocalURL)
}
set {
CoreData.setSMRelativeLocalURL(newValue, toCoreDataProperty: &self.internalRelativeLocalURL, coreDataSessionName: SMCoreData.name)
}
}
// If the block doesn't indicate deletion, creates upload blocks.
func addUploadBlocks() {
let uploadBlocks = NSMutableOrderedSet()
var fileSizeRemaining = FileStorage.fileSize(self.fileURL!.path)
var currBlockStartOffset:UInt = 0
while fileSizeRemaining > 0 {
var currBlockSize:UInt
if fileSizeRemaining >= SMSyncServer.BLOCK_SIZE_BYTES {
currBlockSize = SMSyncServer.BLOCK_SIZE_BYTES
}
else {
currBlockSize = fileSizeRemaining
}
let uploadBlock = SMUploadBlock.newObject() as! SMUploadBlock
uploadBlock.numberBytes = currBlockSize
uploadBlock.startByteOffset = currBlockStartOffset
uploadBlocks.addObject(uploadBlock)
fileSizeRemaining -= currBlockSize
currBlockStartOffset += currBlockSize
}
self.blocks = uploadBlocks
CoreData.sessionNamed(SMCoreData.name).saveContext()
}
override func removeObject() {
// We can't iterate over self.blocks! and delete the blocks within there because the deletion itself changes the contents of self.blocks and causes this to fail.
let blocksToDelete = NSOrderedSet(orderedSet: self.blocks!)
for elem in blocksToDelete {
let block = elem as? SMUploadBlock
Assert.If(nil == block, thenPrintThisString: "Didn't have an SMUploadBlock object")
block!.removeObject()
}
super.removeObject()
}
override func convertToServerFile() -> SMServerFile {
let serverFile = super.convertToServerFile()
serverFile.undeleteServerFile = self.undeleteServerFile
return serverFile
}
}
|
gpl-3.0
|
22171a7dbd1370b1b04983c93d76a069
| 33.279279 | 169 | 0.638108 | 5.121131 | false | false | false | false |
devlucky/Kakapo
|
Tests/RouteMatcherTests.swift
|
1
|
11690
|
//
// RouteMatcherTests.swift
// Kakapo
//
// Created by Hector Zarco on 31/03/16.
// Copyright © 2016 devlucky. All rights reserved.
//
import Quick
import Nimble
@testable import Kakapo
class RouteMatcherTests: QuickSpec {
override func spec() {
func match(_ path: String, requestURL: String) -> URLInfo? {
return matchRoute("http://test.com/",
path: path,
requestURL: URL(string: "http://test.com/"+requestURL)!)
}
describe("Route matching") {
context("when the path is not representing the requetsURL") {
it("should not match if the base is different") {
let result = matchRoute("http://test.com/",
path: "/users/:id",
requestURL: URL(string: "http://foo.com/users/1")!)
expect(result).to(beNil())
}
it("should not match if the path is different") {
expect(match("/users/:id", requestURL: "/comments/1")).to(beNil())
}
it("should not match if the wildcard is missing") {
expect(match("/users/:id", requestURL: "/users/")).to(beNil())
}
it("should not match if a component is missing") {
expect(match("/users/:id/comments", requestURL: "/users/1")).to(beNil())
}
it("should not match if a component doesn't match") {
expect(match("/users/:user_id/comments/:comment_id", requestURL: "/users/1/whatever/2")).to(beNil())
}
it("should not match if the request has extra components") {
expect(match("/users/:id/comments", requestURL: "/users/1/comments/2")).to(beNil())
}
}
context("when the path is representing the requestURL") {
it("should match even if the base url is empty") {
expect(matchRoute("", path: "/users", requestURL: URL(string: "/users")!)?.components) == [:]
}
it("should match a path without wilcard and equal components") {
expect(match("/users", requestURL: "/users")?.components) == [:]
}
it("should match a path containing a wildcard") {
expect(match("/users/:id", requestURL: "/users/1")?.components) == ["id": "1"]
}
it("should match a path with equal components except for wildcard") {
expect(match("/users/:id/comments", requestURL: "/users/1/comments")?.components) == ["id": "1"]
}
it("should match a path with multiple wildcards") {
expect(match("/users/:user_id/comments/:comment_id", requestURL: "/users/1/comments/2")?.components) == ["user_id": "1", "comment_id": "2"]
}
it("should match a path with only wildcards") {
expect(match("/:user_id/:comment_id", requestURL: "/1/2/")?.components) == ["user_id": "1", "comment_id": "2"]
}
context("when the request contains query parameters") {
it("should match a path") {
expect(match("/users/:id/comments", requestURL: "/users/1/comments?page=2")?.components) == ["id": "1"]
}
it("should match a path when there are not actual parameters") {
let info = match("/users/:id", requestURL: "/users/1?")
expect(info?.components) == ["id": "1"]
expect(info?.queryParameters) == []
}
it("should match a path when there is a trailing question mark") {
let info = match("/users", requestURL: "/users?")
expect(info?.components) == [:]
expect(info?.queryParameters) == []
}
it("should retreive the query parameter") {
expect(match("/users/:id", requestURL: "/users/1?page=2")?.queryParameters) == [URLQueryItem(name: "page", value: "2")]
}
it("should retreive multiple query parameters") {
let queryParameters = [URLQueryItem(name: "page", value: "2"), URLQueryItem(name: "size", value: "50")]
expect(match("/users/:id", requestURL: "/users/1?page=2&size=50")?.queryParameters) == queryParameters
}
}
}
context("base url") {
it("shoud match if the base url contains the scheme") {
let result = matchRoute("http://test.com/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("shoud not match if the base url contains a different the scheme") {
let result = matchRoute("http://test.com/",
path: "/users/:id",
requestURL: URL(string: "https://test.com/users/1")!)
expect(result).to(beNil())
}
it("shoud match any scheme if the base url doesn't contain the scheme") {
let result = matchRoute("test.com/",
path: "/users/:id",
requestURL: URL(string: "ssh://test.com/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("shoud match if the base url contains components") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("shoud not match if the base url contains wildcard") {
let result = matchRoute("http://test.com/api/:api_version/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result).to(beNil())
}
it("should match any subdomain when the base url doesn't contain a scheme (wildcard baseURL)") {
let result = matchRoute("test.com/",
path: "/users/:id",
requestURL: URL(string: "http://api.test.com/users/1")!)
expect(result?.components) == ["id": "1"]
}
}
context("trailing and leading slashes") {
context("base url and path") {
it("should match when base url contains a trailing slash and the path doesn't contain a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("should match when base url contains a trailing slash and the path contains a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("should match when base url doesn't contain a trailing slash and the path contains a leading slash") {
let result = matchRoute("http://test.com/api/v3",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("should match when base url doesn't contain a trailing slash and the path doesn't contain a leading slash") {
let result = matchRoute("http://test.com/api/v3",
path: "users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
}
context("path and requestURL") {
it("should match when path contains a trailing slash and the requestURL doesn't contain a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id/",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
it("should match when path contains a trailing slash and the requestURL contains a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id/",
requestURL: URL(string: "http://test.com/api/v3/users/1/")!)
expect(result?.components) == ["id": "1"]
}
it("should match when path doesn't contain a trailing slash and the requestURL contains a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1/")!)
expect(result?.components) == ["id": "1"]
}
it("should match when path doesn't contain a trailing slash and the requestURL doesn't contain a leading slash") {
let result = matchRoute("http://test.com/api/v3/",
path: "/users/:id",
requestURL: URL(string: "http://test.com/api/v3/users/1")!)
expect(result?.components) == ["id": "1"]
}
}
}
}
}
}
|
mit
|
5adc1f28d38b1ff6d18ceec24f84ec0f
| 52.374429 | 159 | 0.41877 | 5.431691 | false | true | false | false |
roambotics/swift
|
test/SILGen/resilient_assign_by_wrapper.swift
|
2
|
4776
|
// RUN: %target-swift-emit-silgen %s -emit-verbose-sil -enable-library-evolution | %FileCheck %s
@propertyWrapper
public struct WrapGod<T> {
private var value: T
public init(wrappedValue: T) {
value = wrappedValue
}
public var wrappedValue: T {
get { value }
set { value = newValue }
}
}
public protocol Existential {}
public enum AddressOnlyEnum {
case some
case value(Existential?)
}
public class AddressOnlySetter {
@WrapGod var value: AddressOnlyEnum = .value(nil)
init() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17AddressOnlySetterCACycfc
// CHECK: [[E1:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK: [[W:%.*]] = alloc_stack $WrapGod<AddressOnlyEnum>
// CHECK: [[I:%.*]] = function_ref @$s27resilient_assign_by_wrapper17AddressOnlySetterC5valueAA0eF4EnumOvpfP : $@convention(thin) (@in AddressOnlyEnum) -> @out WrapGod<AddressOnlyEnum>
// CHECK: apply [[I]]([[W]], [[E1]])
// CHECK: [[E2:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK-NEXT: inject_enum_addr [[E2]] : $*AddressOnlyEnum, #AddressOnlyEnum.some!enumelt
// CHECK: [[S:%.*]] = partial_apply [callee_guaranteed] {{%.*}}({{%.*}}) : $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
// CHECK: assign_by_wrapper origin property_wrapper, [[E2]] : $*AddressOnlyEnum
// CHECK-SAME: set [[S]] : $@callee_guaranteed (@in AddressOnlyEnum) -> ()
self.value = .some
}
func testAssignment() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17AddressOnlySetterC14testAssignmentyyF
// CHECK: [[E:%.*]] = alloc_stack $AddressOnlyEnum
// CHECK: inject_enum_addr [[E]] : $*AddressOnlyEnum, #AddressOnlyEnum.some!enumelt
// CHECK: [[S:%.*]] = class_method %0 : $AddressOnlySetter, #AddressOnlySetter.value!setter : (AddressOnlySetter) -> (AddressOnlyEnum) -> (), $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
// CHECK: apply [[S]]([[E]], %0) : $@convention(method) (@in AddressOnlyEnum, @guaranteed AddressOnlySetter) -> ()
self.value = .some
}
}
public struct SubstitutedSetter<T> {
@WrapGod var value: T
}
extension SubstitutedSetter where T == Bool {
init() {
// CHECK-LABEL: hidden [ossa] @$s27resilient_assign_by_wrapper17SubstitutedSetterVAASbRszlEACySbGycfC
// CHECK: [[W:%.*]] = struct_element_addr {{%.*}} : $*SubstitutedSetter<Bool>, #SubstitutedSetter._value
// CHECK: [[B:%.*]] = alloc_stack $Bool
// CHECK: assign_by_wrapper origin property_wrapper, [[B]] : $*Bool to [[W]] : $*WrapGod<Bool>
// CHECK-SAME: init {{%.*}} : $@callee_guaranteed (@in Bool) -> @out WrapGod<Bool>
// CHECK-SAME: set {{%.*}} : $@callee_guaranteed (@in Bool) -> ()
self.value = true
}
}
public struct ReabstractedSetter<T> {
@WrapGod var value: (T) -> ()
}
extension ReabstractedSetter where T == Int {
init() {
// CHECK-LABEL: hidden [ossa] @$s27resilient_assign_by_wrapper18ReabstractedSetterVAASiRszlEACySiGycfC
// CHECK: [[F:%.*]] = function_ref @$s27resilient_assign_by_wrapper18ReabstractedSetterVAASiRszlEACySiGycfcySicfU_ : $@convention(thin) (Int) -> ()
// CHECK: [[TH_F:%.*]] = thin_to_thick_function [[F]] : $@convention(thin) (Int) -> () to $@callee_guaranteed (Int) -> ()
// CHECK: [[THUNK_REF:%.*]] = function_ref @$sSiIegy_SiIegn_TR : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> ()) -> ()
// CHECK: [[CF:%.*]] = partial_apply [callee_guaranteed] [[THUNK_REF]]([[TH_F]]) : $@convention(thin) (@in_guaranteed Int, @guaranteed @callee_guaranteed (Int) -> ()) -> ()
// CHECK: [[CF2:%.*]] = convert_function [[CF]]
// CHECK: assign_by_wrapper origin property_wrapper, [[CF2]]
// CHECK-SAME: to {{%.*}} : $*WrapGod<(Int) -> ()>
self.value = { x in }
}
}
public struct ObjectifiedSetter<T: AnyObject> {
@WrapGod var value: T
}
public class SomeObject {}
extension ObjectifiedSetter where T == SomeObject {
init() {
// CHECK-LABEL: sil hidden [ossa] @$s27resilient_assign_by_wrapper17ObjectifiedSetterV5valuexvs : $@convention(method) <T where T : AnyObject> (@owned T, @inout ObjectifiedSetter<T>) -> () {
// CHECK: [[OBJ:%.*]] = apply {{%.*}}({{%.*}}) : $@convention(method) (@thick SomeObject.Type) -> @owned SomeObject
// CHECK: [[STORAGE:%.*]] = struct_element_addr {{%.*}} : $*ObjectifiedSetter<SomeObject>, #ObjectifiedSetter._value
// CHECK: assign_by_wrapper origin property_wrapper, [[OBJ]] : $SomeObject to [[STORAGE]] : $*WrapGod<SomeObject>
// CHECK-SAME: init {{%.*}} : $@callee_guaranteed (@owned SomeObject) -> @out WrapGod<SomeObject>
// CHECK-SAME: set {{%.*}} : $@callee_guaranteed (@owned SomeObject) -> ()
self.value = SomeObject()
}
}
|
apache-2.0
|
f3385799b5937c63807c5ccb7f292cde
| 45.368932 | 225 | 0.644682 | 3.665388 | false | false | false | false |
EmmaXiYu/SE491
|
DonateParkSpot/DonateParkSpot/LoginViewController.swift
|
1
|
4109
|
//
// LoginViewController.swift
// DonateParkSpot
//
// Created by Apple on 10/23/15.
// Copyright © 2015 Apple. All rights reserved.
//
import UIKit
import Parse
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var userEmailTextField: UITextField!
@IBOutlet weak var userPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
userEmailTextField.delegate = self;
userPasswordTextField.delegate = self;
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == userEmailTextField {
userPasswordTextField.becomeFirstResponder()
return true
}else if textField == userPasswordTextField{
self.view.endEditing(true)
return true;
}
return true;
}
@IBAction func LoginButtonTapped(sender: AnyObject) {
Login()
}
func Login()
{
let user = PFUser()
user.username = userEmailTextField.text!.lowercaseString
user.password = userPasswordTextField.text!
PFUser.logInWithUsernameInBackground(userEmailTextField.text!, password: userPasswordTextField.text!, block: {
(username : PFUser?, Error : NSError?) -> Void in
if Error == nil{
/* let loginUser = PFUser.currentUser()
var ifemailVerified = loginUser?["emailVerified"] as! Bool
if ifemailVerified == true
{*/
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().setObject(user.username, forKey: "username")
NSUserDefaults.standardUserDefaults().synchronize();
self.dismissViewControllerAnimated(true, completion: nil);
DonateSpotUserSession.isLocationManagerIntited = false
let svc : SpotLocationService = SpotLocationService()
svc.IsUserHaveActivePaidBid()
let loginUser = PFUser.currentUser()
var searcgRadium = loginUser?["SearchRadium"] as? String
if searcgRadium == nil{
loginUser!["SearchRadium"] = "1"
loginUser!.saveInBackgroundWithBlock({
(success: Bool, error: NSError?) -> Void in
})}
let installation = PFInstallation.currentInstallation()
installation["user"] = PFUser.currentUser()
installation.saveInBackground()
if installation.badge != 0 {
installation.badge = 0
installation.saveEventually()
}}
// }
/* else
{
self.displayMyAlertMessage("Please verify the link we send to you" );
}}*/
else
{
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isUserLoggedIn")
NSUserDefaults.standardUserDefaults().synchronize();
self.displayMyAlertMessage("Email or password is not valid");
self.dismissViewControllerAnimated(true, completion: nil);
}
})
}
func displayMyAlertMessage(usermessage:String)
{
let myAlert=UIAlertController(title: "Alert", message:usermessage,
preferredStyle: UIAlertControllerStyle.Alert);
let okayAction=UIAlertAction(title: "Okay", style:UIAlertActionStyle.Default, handler:nil)
myAlert.addAction(okayAction);
self.presentViewController(myAlert, animated: true, completion: nil);
}
}
|
apache-2.0
|
9ad1639d65ce4abb523d68ff72cfd24b
| 31.09375 | 119 | 0.543574 | 6.359133 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
OBAKit/UI/DrawerNavigationBar.swift
|
3
|
3386
|
//
// DrawerNavigationBar.swift
// OBAKit
//
// Created by Aaron Brethorst on 8/13/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
import SnapKit
@objc(OBADrawerNavigationBar)
public class DrawerNavigationBar: UIView {
@objc public private(set)
lazy var closeButton: UIButton = {
let button = UIButton(type: .system)
button.setImage(#imageLiteral(resourceName: "close_circle"), for: .normal)
button.accessibilityLabel = OBAStrings.close
return button
}()
private lazy var closeButtonWrapper: UIView = {
let wrapper = closeButton.oba_embedInWrapperView(withConstraints: false)
wrapper.clipsToBounds = true
closeButton.snp.makeConstraints { make in
make.width.height.equalTo(35)
make.leading.top.trailing.equalToSuperview()
}
return wrapper
}()
@objc public private(set)
lazy var titleLabel: UILabel = {
let label = UILabel.oba_autolayoutNew()
label.numberOfLines = 0
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.setContentHuggingPriority(.defaultHigh, for: .vertical)
label.font = OBATheme.headlineFont
return label
}()
@objc public private(set)
lazy var subtitleLabel: UILabel = {
let label = UILabel.oba_autolayoutNew()
label.numberOfLines = 0
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.setContentHuggingPriority(.defaultHigh, for: .vertical)
label.font = OBATheme.subheadFont
return label
}()
private lazy var grabHandle: GrabHandle = {
let handle = GrabHandle.oba_autolayoutNew()
handle.snp.makeConstraints { $0.height.equalTo(4) }
return handle
}()
private let kUseDebugColors = false
public override init(frame: CGRect) {
super.init(frame: frame)
layer.shadowRadius = 1.0
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.3
let labelStack = UIStackView.oba_verticalStack(withArrangedSubviews: [titleLabel, subtitleLabel])
let labelStackWrapper = labelStack.oba_embedInWrapper()
let horizStack = UIStackView.oba_horizontalStack(withArrangedSubviews: [labelStackWrapper, closeButtonWrapper])
let horizWrapper = horizStack.oba_embedInWrapper()
let outerStack = UIStackView.oba_verticalStack(withArrangedSubviews: [grabHandle, horizWrapper])
outerStack.spacing = OBATheme.compactPadding
addSubview(outerStack)
outerStack.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(OBATheme.defaultEdgeInsets)
}
if kUseDebugColors {
backgroundColor = .yellow
titleLabel.backgroundColor = .magenta
subtitleLabel.backgroundColor = .purple
grabHandle.backgroundColor = .green
}
}
required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
// Drop Shadow
extension DrawerNavigationBar {
@objc public func hideDrawerNavigationBarShadow() {
layer.shadowOpacity = 0.0
}
@objc public func showDrawerNavigationBarShadow() {
layer.shadowOpacity = 0.3
}
}
|
apache-2.0
|
2c1648c3379c47151c15d609cc83e918
| 31.864078 | 119 | 0.675037 | 4.754213 | false | false | false | false |
OneBusAway/onebusaway-iphone
|
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/ViewControllers/CalendarViewController.swift
|
2
|
2582
|
/**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class CalendarViewController: UIViewController, ListAdapterDataSource {
lazy var adapter: ListAdapter = {
return ListAdapter(updater: ListAdapterUpdater(), viewController: self)
}()
let collectionView = UICollectionView(
frame: .zero,
collectionViewLayout: ListCollectionViewLayout(stickyHeaders: false, topContentInset: 0, stretchToEdge: false)
)
var months = [Month]()
override func viewDidLoad() {
super.viewDidLoad()
let date = Date()
let currentMonth = Calendar.current.component(.month, from: date)
let month = Month(
name: DateFormatter().monthSymbols[currentMonth - 1],
days: 30,
appointments: [
2: ["Hair"],
4: ["Nails"],
7: ["Doctor appt", "Pick up groceries"],
12: ["Call back the cable company", "Find a babysitter"],
13: ["Dinner at The Smith"],
17: ["Buy running shoes", "Buy a fitbit", "Start running"],
20: ["Call mom"],
21: ["Contribute to IGListKit"],
25: ["Interview"],
26: ["Quit running", "Buy ice cream"]
]
)
months.append(month)
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: ListAdapterDataSource
func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
return months
}
func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
return MonthSectionController()
}
func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil }
}
|
apache-2.0
|
f4db4896d01e189f8717d1a7e5626a07
| 32.973684 | 118 | 0.644074 | 5.143426 | false | false | false | false |
leeaken/LTMap
|
LTMap/LTLocationMap/LocationPick/Extension/LTLocationSearchResultVCExtension.swift
|
1
|
1762
|
//
// LTLocationSearchResultVCExtension.swift
// LTMap
//
// 导航界面-搜索结果拓展
// Created by aken on 2017/6/4.
// Copyright © 2017年 LTMap. All rights reserved.
//
import UIKit
private let cellForSearchIdentifier = "cellForSearchIdentifier"
extension LTLocationSearchResultVC : UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: cellForSearchIdentifier) as? LTLocationCell
if cell == nil {
cell = LTLocationCell(style:.subtitle,reuseIdentifier: cellForSearchIdentifier)
}
let model = dataSource[indexPath.row]
cell?.searchKeyword = searchParam.keyword
cell?.enabledFoundCharacter = true
cell?.model = model
return cell!
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let model = dataSource[indexPath.row]
if let del = self.delegate {
del.tableViewDidSelectAt(selectedIndex: indexPath.row, model: model)
}
print(model.subtitle as Any)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if let tmpSearchBar = searchBar {
if dataSource.count > 0 {
tmpSearchBar.resignFirstResponder()
}
}
}
}
|
mit
|
b538760a96ba1c03fd8f52bef8badf17
| 24.573529 | 108 | 0.59632 | 5.573718 | false | false | false | false |
DrGo/LearningSwift
|
PLAYGROUNDS/LSB_008_Closures.playground/section-2.swift
|
2
|
1884
|
import UIKit
/*--------------------------/
// Closures
/--------------------------*/
// "close over"
var x = 10
let add: () -> Int = {
x = x + 2
return x
}
x
add()
x
x = 15
add()
// "close over" with private var
var y = 1000
func createAdder() -> () -> Int {
var y = 10
return {
y = y + 2
return y
}
}
let addAgain = createAdder()
y
addAgain()
addAgain()
addAgain()
y
y = 0
addAgain()
y
// With a parameter
let addOne = { (x: Int) -> Int in
return x + 1
}
addOne(10)
// With two parameters
let addTwoNumbers = { (x: Int, y: Int) -> Int in
return x + y
}
addTwoNumbers(10, 12)
/*--------------------------/
// Sorting
/--------------------------*/
let movies = ["ET", "alien", "ID", "Howard the Duck"]
sorted(movies)
// with explicit sort order
sorted(movies, { (mov1: String, mov2: String) -> Bool in
return mov1 < mov2
})
// with assumed input types
sorted(movies, { (mov1, mov2) -> Bool in
return mov1 < mov2
})
// with trailing closure
sorted(movies) { (mov1, mov2) -> Bool in
return mov1 < mov2
}
// with default argument names
sorted(movies) {
$0 < $1
}
// "named closures"
typealias SortStrings = (String, String) -> Bool
let byAlpha: SortStrings = {
$0 < $1
}
sorted(movies, byAlpha)
let byUncasedAlpha: SortStrings = {
$0.lowercaseString < $1.lowercaseString
}
sorted(movies, byUncasedAlpha)
let byLength: SortStrings = {
count($0) < count($1)
}
sorted(movies, byLength)
/*--------------------------/
// Capturing Values
/--------------------------*/
func makeGreeting(greeting: String) -> (Int) -> String {
var count = 0
return { (customerNumber: Int) -> String in
count++
return "\(count)) \(greeting), customer #\(customerNumber)!"
}
}
let englishGreeting = makeGreeting("Hello")
let frenchGreeting = makeGreeting("Bonjour")
englishGreeting(123)
englishGreeting(222)
frenchGreeting(333)
|
gpl-3.0
|
bb996491b48f1041786f09aedabe5135
| 14.193548 | 64 | 0.578025 | 3.19322 | false | false | false | false |
Hidebush/McBlog
|
McBlog/McBlog/AppDelegate.swift
|
1
|
3797
|
//
// AppDelegate.swift
// McBlog
//
// Created by Theshy on 16/4/14.
// Copyright © 2016年 郭月辉. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(switchRootViewController), name: YHRootViewControllerSwitchNotification, object: nil)
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = defaultViewController()
window?.makeKeyAndVisible()
setUpAppearance()
isNewUpdate()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func switchRootViewController(notification: NSNotification) {
print("切换控制器")
window?.rootViewController = (notification.object as! Bool) ? MainViewController() : WelcomeViewController()
}
private func defaultViewController() -> UIViewController {
if !UserAccount.userLogon {
return MainViewController()
}
return isNewUpdate() ? NewFeautureController() : WelcomeViewController()
}
private func isNewUpdate() -> Bool {
let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)
let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey("sandBoxVersionKey")
NSUserDefaults.standardUserDefaults().setDouble(currentVersion!, forKey: "sandBoxVersionKey")
return currentVersion > sandBoxVersion
}
private func setUpAppearance() {
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
UITabBar.appearance().tintColor = UIColor.orangeColor()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
|
mit
|
ccf9161084485e667131f043077d5a7e
| 40.977778 | 285 | 0.717046 | 5.794479 | false | false | false | false |
mihaicris/digi-cloud
|
Digi Cloud/Controller/Views/BaseListCell.swift
|
1
|
4842
|
//
// BaseListCell.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 20/10/16.
// Copyright © 2016 Mihai Cristescu. All rights reserved.
//
import UIKit
class BaseListCell: UITableViewCell {
// MARK: - Properties
var hasButton: Bool = false {
didSet {
setupActionsButton()
}
}
var hasLink: Bool = false
var actionsButton: UIButton = {
let button = UIButton(type: UIButtonType.system)
button.setTitle("⋯", for: .normal)
button.tag = 1
button.titleLabel?.font = UIFont.systemFont(ofSize: 17)
button.contentHorizontalAlignment = .center
button.setTitleColor(UIColor.darkGray, for: .normal)
return button
}()
var iconImageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.contentMode = .scaleAspectFit
return imageView
}()
var nodeNameLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.lineBreakMode = .byTruncatingMiddle
return label
}()
var detailsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.font = UIFont.fontHelveticaNeue(size: 11)
return label
}()
var rightPaddingButtonConstraint: NSLayoutConstraint?
// MARK: - Initializers and Deinitializers
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Overridden Methods and Properties
override func setEditing(_ editing: Bool, animated: Bool) {
actionsButton.alpha = editing ? 0 : 1
super.setEditing(editing, animated: animated)
}
override func setHighlighted(_ highlighted: Bool, animated: Bool) {
super.setHighlighted(highlighted, animated: animated)
if self.isEditing { return }
if self.hasButton {
if highlighted {
contentView.backgroundColor = UIColor(red: 37 / 255, green: 116 / 255, blue: 255 / 255, alpha: 1.0)
nodeNameLabel.textColor = .white
detailsLabel.textColor = UIColor.init(white: 0.8, alpha: 1)
actionsButton.setTitleColor(.white, for: .normal)
} else {
contentView.backgroundColor = nil
nodeNameLabel.textColor = .black
detailsLabel.textColor = .darkGray
actionsButton.setTitleColor(.darkGray, for: .normal)
}
}
}
// MARK: - Helper Functions
func setupViews() {
self.clipsToBounds = true
separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
contentView.addSubview(iconImageView)
contentView.addSubview(nodeNameLabel)
contentView.addSubview(detailsLabel)
NSLayoutConstraint.activate([
// Dimentional constraints
iconImageView.widthAnchor.constraint(equalToConstant: 26),
iconImageView.heightAnchor.constraint(equalToConstant: 26),
// Horizontal constraints
iconImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 15),
nodeNameLabel.leftAnchor.constraint(equalTo: iconImageView.rightAnchor, constant: 10),
detailsLabel.leftAnchor.constraint(equalTo: nodeNameLabel.leftAnchor),
// Vertical constraints
iconImageView.centerYAnchor.constraint(equalTo: contentView.centerYAnchor, constant: -1),
nodeNameLabel.topAnchor.constraint(equalTo: iconImageView.topAnchor, constant: -3),
detailsLabel.topAnchor.constraint(equalTo: nodeNameLabel.bottomAnchor, constant: 2)
])
rightPaddingButtonConstraint = nodeNameLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor)
rightPaddingButtonConstraint?.isActive = true
}
func setupActionsButton() {
if hasButton {
contentView.addSubview(actionsButton)
contentView.addConstraints(with: "H:[v0(64)]-(-4)-|", views: actionsButton)
actionsButton.heightAnchor.constraint(equalToConstant: AppSettings.tableViewRowHeight * 0.95).isActive = true
actionsButton.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true
rightPaddingButtonConstraint?.constant = -70
} else {
actionsButton.removeFromSuperview()
rightPaddingButtonConstraint?.constant = -20
}
layoutSubviews()
}
}
|
mit
|
a1a2a0db9a300a92a156df766a9ebb62
| 34.065217 | 121 | 0.647241 | 5.34106 | false | false | false | false |
danghoa/GGModules
|
GGModules/Views/SignIn/GGMSignInVC.swift
|
1
|
11246
|
//
// GGMSignInVC.swift
// GGModuleLogin
//
// Created by Đăng Hoà on 1/11/17.
// Copyright © 2017 Green Global. All rights reserved.
//
import UIKit
public class GGMSignInVC: UIViewController {
// MARK: - Enum
public enum Social {
case facebook
case google
case both
case none
}
public enum Response {
case successfully
case failed
case forgot
case signUp
case none
}
public typealias successReturn = (_ result: Response, _ detail: String, _ value: Any?)-> Void
// MARK: - Outlets
@IBOutlet private weak var tableView: UITableView!
@IBOutlet private var viewMain: UIView!
@IBOutlet private weak var imvBG: UIImageView!
@IBOutlet private weak var lblNameProject: UILabel!
@IBOutlet private weak var lblLoginWithAccount: UILabel!
@IBOutlet private weak var btnFacebook: UIButton!
@IBOutlet private weak var btnGoogle: UIButton!
@IBOutlet private weak var lblLoginWithYourAccount: UILabel!
@IBOutlet private weak var viewEmail: UIView!
@IBOutlet private weak var tfEmail: UITextField!
@IBOutlet private weak var viewPassword: UIView!
@IBOutlet private weak var tfPassword: UITextField!
@IBOutlet private weak var viewLogin: UIView!
@IBOutlet private weak var btnLogin: UIButton!
@IBOutlet private weak var btnForgotPassword: UIButton!
@IBOutlet private weak var lblDontHaveAccount: UILabel!
@IBOutlet private weak var btnSignUp: UIButton!
// MARK: - Constant
@IBOutlet weak var consAlignCenterBtnFB: NSLayoutConstraint!
@IBOutlet weak var consHeightBtnFB: NSLayoutConstraint!
@IBOutlet weak var consWidthBtnFB: NSLayoutConstraint!
@IBOutlet weak var consAlignCenterBtnGG: NSLayoutConstraint!
@IBOutlet weak var consHeightBtnGG: NSLayoutConstraint!
@IBOutlet weak var consWidthBtnGG: NSLayoutConstraint!
@IBOutlet weak var consTopLblLoginYourAccount: NSLayoutConstraint!
// MARK: - Variables
private var typeSocial: Social = Social.none
private var typeMaincolor: UIColor = UIColor(red: 22 / 255.0, green: 122 / 255.0, blue: 255 / 255.0, alpha: 1.0)
private var typeName = ""
private var typeBackgroundColor: UIColor? = nil
private var typeBackgroundImage: UIImage? = nil
private var typeImageFacebook: UIImage? = nil
private var typeImageGoogle: UIImage? = nil
private var isSetting: Bool = false
private var typePath: String = ""
private var keyboardHeight: CGFloat = 0.0
private var response: successReturn?
// MARK: - Life Circles
override private init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: "GGMSignInVC", bundle: nibBundleOrNil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
convenience public init(social: Social, mainColor: UIColor, name: String) {
let bundle = Bundle(for: GGMSignInVC.self)
self.init(nibName: "GGMSignInVC", bundle: bundle)
typeSocial = social
typeMaincolor = mainColor
typeName = name
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
GGMIndicator.hide()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
viewMain.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight > 667 ? screenHeight : 667)
tableView.tableHeaderView = viewMain
}
override public func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
configureViewBegin()
configureWithSetting()
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Publics
public func setting(backgroundColor: UIColor?, backgroundImage: UIImage?, imageFacebook: UIImage?, imageGoogle: UIImage?) {
isSetting = true
typeBackgroundColor = backgroundColor
typeBackgroundImage = backgroundImage
typeImageFacebook = imageFacebook
typeImageGoogle = imageGoogle
}
public func settingAPI(path: String) {
typePath = path
}
public func response(res: @escaping successReturn) {
response = res
}
// MARK: - Configures
private func configureViewBegin() {
viewLogin.layer.cornerRadius = 3.0
viewLogin.layer.shadowColor = typeMaincolor.withAlphaComponent(0.57).cgColor
viewLogin.layer.shadowOpacity = 1
viewLogin.layer.shadowOffset = CGSize.zero
viewLogin.layer.shadowRadius = 10
viewEmail.layer.borderColor = UIColor(red: 235 / 255.0, green: 235 / 255.0, blue: 235 / 255.0, alpha: 1).cgColor
viewEmail.layer.borderWidth = 1.0
viewPassword.layer.borderColor = UIColor(red: 235 / 255.0, green: 235 / 255.0, blue: 235 / 255.0, alpha: 1).cgColor
viewPassword.layer.borderWidth = 1.0
tfEmail.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName: UIColor(red: 74 / 255.0, green: 74 / 255.0, blue: 74 / 255.0, alpha: 1), NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16)])
tfPassword.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor(red: 74 / 255.0, green: 74 / 255.0, blue: 74 / 255.0, alpha: 1), NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16)])
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardChanged(_:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}
private func configureWithSetting() {
lblNameProject.textColor = typeMaincolor
lblNameProject.text = typeName
viewLogin.backgroundColor = typeMaincolor
btnForgotPassword.setTitleColor(typeMaincolor.withAlphaComponent(0.78), for: UIControlState.normal)
lblDontHaveAccount.textColor = typeMaincolor
btnSignUp.setTitleColor(typeMaincolor, for: UIControlState.normal)
settingStyle()
settingSocial(social: typeSocial)
}
private func settingStyle() {
if isSetting == true {
if typeBackgroundColor != nil {
view.backgroundColor = typeBackgroundColor
viewMain.backgroundColor = typeBackgroundColor
imvBG.image = nil
} else {
if typeBackgroundImage != nil {
imvBG.image = typeBackgroundImage
}
}
if typeImageFacebook != nil {
btnFacebook.setImage(typeImageFacebook, for: UIControlState.normal)
}
if typeImageGoogle != nil {
btnGoogle.setImage(typeImageGoogle, for: UIControlState.normal)
}
}
}
private func settingSocial(social: Social) {
if social == Social.facebook {
btnGoogle.alpha = 0.0
consAlignCenterBtnFB.constant = 0
consHeightBtnFB.constant = 55
consWidthBtnFB.constant = screenWidth - 40*2
let image = UIImage(named: "ic_fb_large", in: getBundle(), compatibleWith: nil)
btnFacebook.setImage(image, for: UIControlState.normal)
} else if social == Social.google {
btnFacebook.alpha = 0.0
consAlignCenterBtnGG.constant = 0
consHeightBtnGG.constant = 55
consWidthBtnGG.constant = screenWidth - 40*2
let image = UIImage(named: "ic_gg_large", in: getBundle(), compatibleWith: nil)
btnGoogle.setImage(image, for: UIControlState.normal)
} else if social == Social.both {
btnGoogle.alpha = 1.0
consAlignCenterBtnFB.constant = -76.5
consHeightBtnFB.constant = 48
consWidthBtnFB.constant = 142
btnFacebook.alpha = 1.0
consAlignCenterBtnGG.constant = 77.5
consHeightBtnGG.constant = 48
consWidthBtnGG.constant = 142
} else {
lblLoginWithAccount.alpha = 0.0
btnGoogle.alpha = 0.0
btnFacebook.alpha = 0.0
consTopLblLoginYourAccount.constant = -75
}
}
private func validate() -> Bool {
if Common.trimWhiteSpaceInsets(tfEmail.text!) == "" {
showAlert(mess: "Please enter your email", title: typeName, vc: self)
return false
} else if !Common.isValidEmail(tfEmail.text!) {
showAlert(mess: "Email address is invalid", title: typeName, vc: self)
return false
} else if Common.trimWhiteSpaceInsets(tfPassword.text!) == "" {
showAlert(mess: "Please enter your password", title: typeName, vc: self)
return false
} else if Common.trimWhiteSpaceInsets(tfPassword.text!).characters.count < 6 {
showAlert(mess: "Password must be 6 characters or more", title: typeName, vc: self)
return false
} else if Common.trimWhiteSpaceInsets(typePath).characters.count < 6 {
showAlert(mess: "Please setting your API path", title: typeName, vc: self)
return false
} else {
return true
}
}
private func getBundle() -> Bundle {
let bundle = Bundle(for: GGMSignInVC.self)
return bundle
}
// MARK: - Keyboard
func keyboardWasShown(_ notification: Notification) {
if (((notification as NSNotification).userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
let contentInsets = UIEdgeInsets(top: 0, left: 0.0, bottom: keyboardHeight, right: 0.0)
tableView.contentInset = contentInsets
}
}
func keyboardWasHide(_ notification: Notification) {
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
tableView.contentInset = contentInsets
}
func keyboardChanged(_ notification: Notification) {
let sizeKeyboard = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size
keyboardHeight = (sizeKeyboard.height > sizeKeyboard.width ? sizeKeyboard.width : sizeKeyboard.height)
}
// MARK: - Actions
@IBAction private func tapToHideKeyboard(_ sender: Any) {
view.endEditing(true)
}
@IBAction private func tapToLogin(_ sender: Any) {
if validate() {
view.endEditing(true)
let params = [
"email": Common.trimWhiteSpaceInsets(tfEmail.text!),
"password": Common.trimWhiteSpaceInsets(tfPassword.text!),
]
GGMIndicator.show(onView: view)
GGWSIncredible.requestPOSTwithPath(path: typePath, params: params, completed: {[weak self] (object, error) in
GGMIndicator.hide()
if object != nil && error == nil {
self?.response?(Response.successfully, "Login successfully", object)
} else {
self?.response?(Response.failed, "", nil)
}
})
}
}
@IBAction private func tapToForgot(_ sender: Any) {
view.endEditing(true)
response?(Response.forgot, "Tap To Forgot", nil)
}
@IBAction private func tapToSignUp(_ sender: Any) {
view.endEditing(true)
response?(Response.signUp, "Tap To Sign Up", nil)
}
}
|
mit
|
5e950ae199d6fbcc8ce9a88ad27befe1
| 33.066667 | 252 | 0.692137 | 4.369219 | false | false | false | false |
russbishop/swift
|
test/IDE/print_clang_decls.swift
|
1
|
7227
|
// RUN: rm -rf %t
// RUN: mkdir -p %t
// XFAIL: linux
// This file deliberately does not use %clang-importer-sdk for most RUN lines.
// Instead, it generates custom overlay modules itself, and uses -I %t when it
// wants to use them.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: FileCheck %s -check-prefix=TAG_DECLS_AND_TYPEDEFS -strict-whitespace < %t.printed.txt
// RUN: FileCheck %s -check-prefix=NEGATIVE -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: FileCheck %s -check-prefix=FOUNDATION -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ctypes.bits -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: FileCheck %s -check-prefix=CTYPESBITS -strict-whitespace < %t.printed.txt
// RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=nullability -function-definitions=false -prefer-type-repr=true > %t.printed.txt
// RUN: FileCheck %s -check-prefix=CHECK-NULLABILITY -strict-whitespace < %t.printed.txt
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct1 {{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: /*!
// TAG_DECLS_AND_TYPEDEFS-NEXT: @keyword Foo2
// TAG_DECLS_AND_TYPEDEFS-NEXT: */
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStruct2 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}typealias FooStructTypedef1 = FooStruct2{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}struct FooStructTypedef2 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct3 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct4 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct5 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// TAG_DECLS_AND_TYPEDEFS: {{^}}struct FooStruct6 {{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var x: Int32{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} var y: Double{{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}} init(x: Int32, y: Double){{$}}
// TAG_DECLS_AND_TYPEDEFS-NEXT: {{^}}}{{$}}
// Skip through unavailable typedefs when importing types.
// TAG_DECLS_AND_TYPEDEFS: @available(*, unavailable, message: "use double")
// TAG_DECLS_AND_TYPEDEFS-NEXT: typealias real_t = Double
// TAG_DECLS_AND_TYPEDEFS-NEXT: func realSin(_ value: Double) -> Double
// NEGATIVE-NOT: typealias FooStructTypedef2
// FOUNDATION-LABEL: {{^}}/// Aaa. NSArray. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}class NSArray : NSObject {{{$}}
// FOUNDATION-NEXT: subscript(idx: Int) -> AnyObject { get }
// FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingMode. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}enum RuncingMode : UInt {{{$}}
// FOUNDATION-NEXT: {{^}} init?(rawValue: UInt){{$}}
// FOUNDATION-NEXT: {{^}} var rawValue: UInt { get }{{$}}
// FOUNDATION-NEXT: {{^}} case mince{{$}}
// FOUNDATION-NEXT: {{^}} case quince{{$}}
// FOUNDATION-NEXT: {{^}}}{{$}}
// FOUNDATION-LABEL: {{^}}/// Aaa. NSRuncingOptions. Bbb.{{$}}
// FOUNDATION-NEXT: {{^}}struct RuncingOptions : OptionSet {{{$}}
// FOUNDATION-NEXT: {{^}} init(rawValue: UInt){{$}}
// FOUNDATION-NEXT: {{^}} let rawValue: UInt{{$}}
// FOUNDATION-NEXT: {{^}} @available(*, unavailable, message: "use [] to construct an empty option set"){{$}}
// FOUNDATION-NEXT: {{^}} static var none: RuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} static var enableMince: RuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}} static var enableQuince: RuncingOptions { get }{{$}}
// FOUNDATION-NEXT: {{^}}}{{$}}
// FOUNDATION-LABEL: {{^}}/// Unavailable Global Functions{{$}}
// FOUNDATION-NEXT: @available(*, unavailable, message: "Zone-based memory management is unavailable")
// FOUNDATION-NEXT: NSSetZoneName(_ zone: NSZone, _ name: String)
// CTYPESBITS-NOT: FooStruct1
// CTYPESBITS: {{^}}typealias DWORD = Int32{{$}}
// CTYPESBITS-NEXT: {{^}}var MY_INT: Int32 { get }{{$}}
// CTYPESBITS-NOT: FooStruct1
// CHECK-NULLABILITY: func getId1() -> AnyObject?
// CHECK-NULLABILITY: var global_id: AnyObject?
// CHECK-NULLABILITY: class SomeClass {
// CHECK-NULLABILITY: class func methodA(_ obj: SomeClass?) -> AnyObject{{$}}
// CHECK-NULLABILITY: func methodA(_ obj: SomeClass?) -> AnyObject{{$}}
// CHECK-NULLABILITY: class func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> AnyObject{{$}}
// CHECK-NULLABILITY: func methodB(_ block: ((Int32, Int32) -> Int32)? = nil) -> AnyObject{{$}}
// CHECK-NULLABILITY: func methodC() -> AnyObject?
// CHECK-NULLABILITY: var property: AnyObject?
// CHECK-NULLABILITY: func stringMethod() -> String{{$}}
// CHECK-NULLABILITY: func optArrayMethod() -> [AnyObject]?
// CHECK-NULLABILITY: }
// CHECK-NULLABILITY: func compare_classes(_ sc1: SomeClass, _ sc2: SomeClass, _ sc3: SomeClass!)
|
apache-2.0
|
bb0709289c84d958720cbd78c4008b4f
| 54.592308 | 215 | 0.64093 | 3.20062 | false | false | false | false |
benkraus/Operations
|
Operations/iCloudContainerCapability.swift
|
1
|
4469
|
/*
The MIT License (MIT)
Original work Copyright (c) 2015 pluralsight
Modified work Copyright 2016 Ben Kraus
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#if !os(watchOS)
import Foundation
import CloudKit
public struct iCloudContainer: CapabilityType {
public static let name = "iCloudContainer"
private let container: CKContainer
private let permissions: CKApplicationPermissions
public init(container: CKContainer, permissions: CKApplicationPermissions = []) {
self.container = container
self.permissions = permissions
}
public func requestStatus(completion: CapabilityStatus -> Void) {
verifyAccountStatus(container, permission: permissions, shouldRequest: false, completion: completion)
}
public func authorize(completion: CapabilityStatus -> Void) {
verifyAccountStatus(container, permission: permissions, shouldRequest: true, completion: completion)
}
}
private func verifyAccountStatus(container: CKContainer, permission: CKApplicationPermissions, shouldRequest: Bool, completion: CapabilityStatus -> Void) {
container.accountStatusWithCompletionHandler { accountStatus, accountError in
switch accountStatus {
case .NoAccount: completion(.NotAvailable)
case .Restricted: completion(.NotAvailable)
case .CouldNotDetermine:
let error = accountError ?? NSError(domain: CKErrorDomain, code: CKErrorCode.NotAuthenticated.rawValue, userInfo: nil)
completion(.Error(error))
case .Available:
if permission != [] {
verifyPermission(container, permission: permission, shouldRequest: shouldRequest, completion: completion)
} else {
completion(.Authorized)
}
}
}
}
private func verifyPermission(container: CKContainer, permission: CKApplicationPermissions, shouldRequest: Bool, completion: CapabilityStatus -> Void) {
container.statusForApplicationPermission(permission) { permissionStatus, permissionError in
switch permissionStatus {
case .InitialState:
if shouldRequest {
requestPermission(container, permission: permission, completion: completion)
} else {
completion(.NotDetermined)
}
case .Denied: completion(.Denied)
case .Granted: completion(.Authorized)
case .CouldNotComplete:
let error = permissionError ?? NSError(domain: CKErrorDomain, code: CKErrorCode.PermissionFailure.rawValue, userInfo: nil)
completion(.Error(error))
}
}
}
private func requestPermission(container: CKContainer, permission: CKApplicationPermissions, completion: CapabilityStatus -> Void) {
dispatch_async(dispatch_get_main_queue()) {
container.requestApplicationPermission(permission) { requestStatus, requestError in
switch requestStatus {
case .InitialState: completion(.NotDetermined)
case .Denied: completion(.Denied)
case .Granted: completion(.Authorized)
case .CouldNotComplete:
let error = requestError ?? NSError(domain: CKErrorDomain, code: CKErrorCode.PermissionFailure.rawValue, userInfo: nil)
completion(.Error(error))
}
}
}
}
#endif
|
mit
|
2538b0fcffb1c3001eab356f4e499062
| 41.971154 | 155 | 0.690982 | 5.41697 | false | false | false | false |
ReactKit/SwiftTask
|
SwiftTaskTests/SwiftTaskTests.swift
|
1
|
46775
|
//
// SwiftTaskTests.swift
// SwiftTaskTests
//
// Created by Yasuhiro Inami on 2014/08/21.
// Copyright (c) 2014年 Yasuhiro Inami. All rights reserved.
//
import SwiftTask
import Async
import XCTest
/// Safe background flag checking delay to not conflict with main-dispatch_after.
/// (0.3 may be still short for certain environment)
let SAFE_BG_FLAG_CHECK_DELAY = 0.5
class AsyncSwiftTaskTests: SwiftTaskTests
{
override var isAsync: Bool { return true }
}
class SwiftTaskTests: _TestCase
{
//--------------------------------------------------
// MARK: - Init
//--------------------------------------------------
func testInit_value()
{
// NOTE: this is non-async test
if self.isAsync { return }
Task<Float, String, ErrorString>(value: "OK").success { value -> Void in
XCTAssertEqual(value, "OK")
}
}
func testInit_error()
{
// NOTE: this is non-async test
if self.isAsync { return }
Task<Float, String, ErrorString>(error: "ERROR").failure { error, isCancelled -> String in
XCTAssertEqual(error!, "ERROR")
return "RECOVERY"
}
}
// fulfill/reject handlers only, like JavaScript Promise
func testInit_fulfill_reject()
{
// NOTE: this is non-async test
if self.isAsync { return }
Task<Any, String, ErrorString> { fulfill, reject in
fulfill("OK")
return
}.success { value -> Void in
XCTAssertEqual(value, "OK")
}
}
//--------------------------------------------------
// MARK: - Fulfill
//--------------------------------------------------
func testFulfill_success()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}
self.wait()
}
func testFulfill_success_failure()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}.failure { error, isCancelled -> Void in
XCTFail("Should never reach here.")
}
self.wait()
}
func testFulfill_failure_success()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.failure { error, isCancelled -> String in
XCTFail("Should never reach here.")
return "RECOVERY"
}.success { value -> Void in
XCTAssertEqual(value, "OK", "value should be derived from 1st task, passing through 2nd failure task.")
expect.fulfill()
}
self.wait()
}
func testFulfill_success_innerTask_fulfill()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.success { value -> Task<Float, String, ErrorString> in
XCTAssertEqual(value, "OK")
return Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK2")
}
}
}.success { value -> Void in
XCTAssertEqual(value, "OK2")
expect.fulfill()
}
self.wait()
}
func testFulfill_success_innerTask_reject()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.success { value -> Task<Float, String, ErrorString> in
XCTAssertEqual(value, "OK")
return Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}
}.success { value -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
expect.fulfill()
}
self.wait()
}
func testFulfill_then()
{
typealias Task = SwiftTask.Task<Float, String, ErrorString>
let expect = self.expectation(description: #function)
Task { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.then { value, errorInfo -> String in
// thenClosure can handle both fulfilled & rejected
XCTAssertEqual(value!, "OK")
XCTAssertTrue(errorInfo == nil)
return "OK2"
}.then { value, errorInfo -> Void in
XCTAssertEqual(value!, "OK2")
XCTAssertTrue(errorInfo == nil)
expect.fulfill()
}
self.wait()
}
//--------------------------------------------------
// MARK: - Reject
//--------------------------------------------------
func testReject_failure()
{
let expect = self.expectation(description: #function)
Task<Float, Void, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
expect.fulfill()
}
self.wait()
}
func testReject_success_failure()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.success { value -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
expect.fulfill()
}
self.wait()
}
func testReject_failure_success()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.failure { error, isCancelled -> String in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
return "RECOVERY"
}.success { value -> Void in
XCTAssertEqual(value, "RECOVERY", "value should be derived from 2nd failure task.")
expect.fulfill()
}
self.wait()
}
func testReject_failure_innerTask_fulfill()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.failure { error, isCancelled -> Task<Float, String, ErrorString> in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
return Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("RECOVERY")
}
}
}.success { value -> Void in
XCTAssertEqual(value, "RECOVERY")
expect.fulfill()
}
self.wait()
}
func testReject_failure_innerTask_reject()
{
let expect = self.expectation(description: #function)
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.failure { error, isCancelled -> Task<Float, String, ErrorString> in
XCTAssertEqual(error!, "ERROR")
XCTAssertFalse(isCancelled)
return Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("ERROR2")
}
}
}.success { value -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "ERROR2")
XCTAssertFalse(isCancelled)
expect.fulfill()
}
self.wait()
}
func testReject_then()
{
typealias Task = SwiftTask.Task<Float, String, ErrorString>
let expect = self.expectation(description: #function)
Task { progress, fulfill, reject, configure in
self.perform {
reject("ERROR")
}
}.then { value, errorInfo -> String in
// thenClosure can handle both fulfilled & rejected
XCTAssertTrue(value == nil)
XCTAssertEqual(errorInfo!.error!, "ERROR")
XCTAssertFalse(errorInfo!.isCancelled)
return "OK"
}.then { value, errorInfo -> Void in
XCTAssertEqual(value!, "OK")
XCTAssertTrue(errorInfo == nil)
expect.fulfill()
}
self.wait()
}
//--------------------------------------------------
// MARK: - On
//--------------------------------------------------
func testOn_success()
{
let expect = self.expectation(description: #function)
Task<(), String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
fulfill("OK")
}
}.on(success: { value in
XCTAssertEqual(value, "OK")
expect.fulfill()
}).on(failure: { error, isCancelled in
XCTFail("Should never reach here.")
})
self.wait()
}
func testOn_failure()
{
let expect = self.expectation(description: #function)
Task<(), String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
reject("NG")
}
}.on(success: { value in
XCTFail("Should never reach here.")
}).on(failure: { error, isCancelled in
XCTAssertEqual(error!, "NG")
XCTAssertFalse(isCancelled)
expect.fulfill()
})
self.wait()
}
//--------------------------------------------------
// MARK: - Progress
//--------------------------------------------------
func testProgress()
{
let expect = self.expectation(description: #function)
var progressCount = 0
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
progress(0.5)
progress(1.0)
fulfill("OK")
}
}.progress { oldProgress, newProgress in
progressCount += 1
if self.isAsync {
// 0.0 <= progress <= 1.0
XCTAssertTrue(newProgress >= 0)
XCTAssertTrue(newProgress <= 1)
// 1 <= progressCount <= 2
XCTAssertGreaterThanOrEqual(progressCount, 1)
XCTAssertLessThanOrEqual(progressCount, 2)
}
else {
XCTFail("When isAsync=false, 1st task closure is already performed before registering this progress closure, so this closure should not be reached.")
}
}.success { (value: String) -> Void in
XCTAssertEqual(value, "OK")
if self.isAsync {
XCTAssertEqual(progressCount, 2)
}
else {
XCTAssertLessThanOrEqual(progressCount, 0, "progressCount should be 0 because progress closure should not be invoked when isAsync=false")
}
expect.fulfill()
}
self.wait()
}
func testProgress_innerTask_then()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
var progressCount = 0
let task = _interruptableTask(progressCount: 5) // 1st async task (5 progresses)
// chain async-task with then
let task3 = task.then { _,_ -> _InterruptableTask in
let task2 = _interruptableTask(progressCount: 7) // 2st async task (7 progresses)
return task2
}
task3.progress { progressValues in
progressCount += 1
print(progressValues)
return
}.success { value -> Void in
XCTAssertEqual(value, "OK")
XCTAssertEqual(progressCount, 7, "`task3` should receive progress only from `task2` but not from `task`.")
expect.fulfill()
}
self.wait()
}
func testProgress_innerTask_success()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
var progressCount = 0
let task = _interruptableTask(progressCount: 5) // 1st async task (5 progresses)
// chain async-task with success
let task3 = task.success { _ -> _InterruptableTask in
let task2 = _interruptableTask(progressCount: 7) // 2st async task (7 progresses)
return task2
}
task3.progress { progressValues in
progressCount += 1
print(progressValues)
return
}.success { value -> Void in
XCTAssertEqual(value, "OK")
XCTAssertEqual(progressCount, 7, "`task3` should receive progress only from `task2` but not from `task`.")
expect.fulfill()
}
self.wait()
}
func testProgress_innerTask_failure()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
var progressCount = 0
let task = _interruptableTask(progressCount: 5, finalState: .Rejected) // 1st async task (5 progresses -> rejected)
// chain async-task with failure
let task3 = task.failure { _ -> _InterruptableTask in
let task2 = _interruptableTask(progressCount: 7) // 2st async task (7 progresses)
return task2
}
task3.progress { progressValues in
progressCount += 1
print(progressValues)
return
}.success { value -> Void in
XCTAssertEqual(value, "OK")
XCTAssertEqual(progressCount, 7, "`task3` should receive progress only from `task2` but not from `task`.")
expect.fulfill()
}
self.wait()
}
//--------------------------------------------------
// MARK: - Cancel
//--------------------------------------------------
func testCancel()
{
let expect = self.expectation(description: #function)
var progressCount = 0
let task = _interruptableTask(progressCount: 5)
task.progress { oldProgress, newProgress in
progressCount += 1
// 1 <= progressCount <= 3 (not 5)
XCTAssertGreaterThanOrEqual(progressCount, 1)
XCTAssertLessThanOrEqual(progressCount, 3, "progressCount should be stopped to 3 instead of 5 because of cancellation.")
}.success { value -> Void in
XCTFail("Should never reach here because of cancellation.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "I get bored.")
XCTAssertTrue(isCancelled)
XCTAssertEqual(progressCount, 2, "progressCount should be stopped to 2 instead of 5 because of cancellation.")
expect.fulfill()
}
// cancel at time between 1st & 2nd delay (t=0.3)
Async.main(after: 0.3) {
task.cancel(error: "I get bored.")
XCTAssertEqual(task.state, TaskState.Cancelled)
}
self.wait()
}
func testCancel_then_innerTask()
{
let expect = self.expectation(description: #function)
let task1 = _interruptableTask(progressCount: 5)
var task2: _InterruptableTask? = nil
let task3 = task1.then { value, errorInfo -> _InterruptableTask in
task2 = _interruptableTask(progressCount: 5)
return task2!
}
task3.failure { error, isCancelled -> String in
XCTAssertEqual(error!, "I get bored.")
XCTAssertTrue(isCancelled)
expect.fulfill()
return "DUMMY"
}
// cancel task3 at time between task1 fulfilled & before task2 completed (t=0.6)
Async.main(after: 0.6) {
task3.cancel(error: "I get bored.")
XCTAssertEqual(task3.state, TaskState.Cancelled)
XCTAssertTrue(task2 != nil, "task2 should be created.")
XCTAssertEqual(task2!.state, TaskState.Cancelled, "task2 should be cancelled because task2 is created and then task3 (wrapper) is cancelled.")
}
self.wait()
}
//--------------------------------------------------
// MARK: - Pause & Resume
//--------------------------------------------------
func testPauseResume()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
var progressCount = 0
let task = _interruptableTask(progressCount: 5)
task.progress { _ in
progressCount += 1
return
}.success { value -> Void in
XCTAssertEqual(value, "OK")
XCTAssertEqual(progressCount, 5)
expect.fulfill()
}
// pause at t=0.3 (between _interruptableTask's 1st & 2nd delay before pause-check)
Async.main(after: 0.3) {
task.pause()
XCTAssertEqual(task.state, TaskState.Paused)
XCTAssertTrue(task.progress! == 2, "`task` should be progressed halfway.")
// resume at t=0.6
Async.main(after: 0.3) {
XCTAssertEqual(task.state, TaskState.Paused)
XCTAssertTrue(task.progress! == 2, "`task` should pause progressing.")
task.resume()
XCTAssertEqual(task.state, TaskState.Running, "`task` should start running again.")
}
}
self.wait()
}
func testPauseResume_innerTask()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let task = _interruptableTask(progressCount: 5)
weak var innerTask: _InterruptableTask?
// chain async-task with `then`
let task2 = task.then { _,_ -> _InterruptableTask in
innerTask = _interruptableTask(progressCount: 5)
return innerTask!
}
task2.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}
// pause at t=0.3 (between _interruptableTask's 1st & 2nd delay before pause-check)
Async.main(after: 0.3) {
// NOTE: task2 will be paused,
task2.pause()
XCTAssertEqual(task2.state, TaskState.Paused)
XCTAssertNil(task2.progress, "`task2.progress` should be nil because `innerTask.progress()` has not been invoked yet.")
XCTAssertNil(innerTask, "`innerTask` should NOT be created yet.")
XCTAssertEqual(task.state, TaskState.Running, "`task` should NOT be paused.")
XCTAssertTrue(task.progress! == 2, "`task` should be halfway progressed.")
XCTAssertNil(task.value, "`task` should NOT be fulfilled yet.")
// resume at t=0.6
Async.main(after: 0.3) {
XCTAssertEqual(task2.state, TaskState.Paused)
XCTAssertNil(task2.progress, "`task2.progress` should still be nil.")
XCTAssertNotNil(innerTask, "`innerTask` should be created at this point.")
XCTAssertEqual(innerTask!.state, task2.state, "`innerTask!.state` should be same as `task2.state`.")
XCTAssertEqual(task.state, TaskState.Fulfilled, "`task` should NOT be paused, and it should be fulfilled at this point.")
XCTAssertEqual(task.value!, "OK", "`task` should be fulfilled.")
task2.resume()
XCTAssertEqual(task2.state, TaskState.Running, "`task2` should be resumed.")
// check tasks's states at t=0.7
Async.main(after: 0.1) {
XCTAssertEqual(task2.state, TaskState.Running)
XCTAssertEqual(innerTask!.state, task2.state, "`innerTask!.state` should be same as `task2.state`.")
XCTAssertEqual(task.state, TaskState.Fulfilled)
}
}
}
self.wait()
}
//--------------------------------------------------
// MARK: - Try
//--------------------------------------------------
func testRetry_success()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 3
let fulfilledTryCount = 2
var actualTryCount = 0
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
actualTryCount += 1
if actualTryCount != fulfilledTryCount {
reject("ERROR \(actualTryCount)")
}
else {
fulfill("OK")
}
}
}.retry(maxTryCount-1).failure { errorInfo -> String in
XCTFail("Should never reach here because `task.retry(\(maxTryCount-1))` will be fulfilled at `fulfilledTryCount` try even though previous retries will be rejected.")
return "DUMMY"
}.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}
self.wait()
XCTAssertEqual(actualTryCount, fulfilledTryCount, "`actualTryCount` should be stopped at `fulfilledTryCount`, not `maxTryCount`.")
}
func testRetry_failure()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 3
var actualTryCount = 0
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
actualTryCount += 1
reject("ERROR \(actualTryCount)")
}
}.retry(maxTryCount-1).failure { error, isCancelled -> String in
XCTAssertEqual(error!, "ERROR \(actualTryCount)")
XCTAssertFalse(isCancelled)
expect.fulfill()
return "DUMMY"
}
self.wait()
XCTAssertEqual(actualTryCount, maxTryCount, "`actualTryCount` should reach `maxTryCount` because task keeps rejected and never fulfilled.")
}
func testRetry_condition()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 4
var actualTryCount = 0
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
actualTryCount += 1
reject("ERROR \(actualTryCount)")
}
}.retry(maxTryCount-1) { error, isCancelled -> Bool in
XCTAssertNotEqual(error!, "ERROR 0", "Should not evaluate retry condition on first try. It is not retry.")
return actualTryCount < 3
}.failure { error, isCancelled -> String in
XCTAssertEqual(error!, "ERROR 3")
XCTAssertFalse(isCancelled)
expect.fulfill()
return "DUMMY"
}
self.wait()
XCTAssertEqual(actualTryCount, 3)
}
func testRetry_progress()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 3
var actualTryCount = 0
var progressCount = 0
Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
self.perform {
progress(1.0)
actualTryCount += 1
if actualTryCount < maxTryCount {
reject("ERROR \(actualTryCount)")
}
else {
fulfill("OK")
}
}
}.retry(maxTryCount-1).progress { _ in
progressCount += 1
// 1 <= progressCount <= maxTryCount
XCTAssertGreaterThanOrEqual(progressCount, 1)
XCTAssertLessThanOrEqual(progressCount, maxTryCount)
}.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}
self.wait()
XCTAssertEqual(progressCount, maxTryCount)
}
func testRetry_pauseResume()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 5
var actualTryCount = 0
let retryableTask = Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
actualTryCount += 1
print("trying \(actualTryCount)")
var isPaused = false
Async.background(after: 0.1) {
while isPaused {
print("pausing...")
Thread.sleep(forTimeInterval: 0.1)
}
Async.main(after: 0.2) {
if actualTryCount < maxTryCount {
reject("ERROR \(actualTryCount)")
}
else {
fulfill("OK")
}
}
}
configure.pause = {
isPaused = true
return
}
configure.resume = {
isPaused = false
return
}
}.retry(maxTryCount-1)
retryableTask.success { value -> Void in
XCTAssertEqual(value, "OK")
expect.fulfill()
}
// pause `retryableTask` at some point before all tries completes
Async.main(after: 0.5) {
retryableTask.pause()
return
}
Async.main(after: 1.5) {
retryableTask.resume()
return
}
self.wait(5) // wait a little longer
XCTAssertEqual(actualTryCount, maxTryCount)
}
func testRetry_cancel()
{
// NOTE: this is async test
if !self.isAsync { return }
let expect = self.expectation(description: #function)
let maxTryCount = 3
var actualTryCount = 0
let task = Task<Float, String, ErrorString> { progress, fulfill, reject, configure in
Async.main(after: 0.3) {
actualTryCount += 1
if actualTryCount < maxTryCount {
reject("ERROR \(actualTryCount)")
}
else {
fulfill("OK")
}
}
return
}
let retryableTask = task.retry(maxTryCount-1)
retryableTask.success { value -> Void in
XCTFail("Should never reach here because `retryableTask` is cancelled.")
}.failure { errorInfo -> Void in
XCTAssertTrue(errorInfo.isCancelled)
// expect.fulfill()
}
task.success { value -> Void in
XCTFail("Should never reach here because `retryableTask` is cancelled so original-`task` should also be cancelled.")
}.failure { errorInfo -> Void in
XCTAssertTrue(errorInfo.isCancelled)
expect.fulfill()
}
// cancel `retryableTask` at some point before all tries completes
Async.main(after: 0.2) {
retryableTask.cancel()
return
}
self.wait()
XCTAssertTrue(actualTryCount < maxTryCount, "`actualTryCount` should not reach `maxTryCount` because of cancellation.")
}
//--------------------------------------------------
// MARK: - All
//--------------------------------------------------
/// all fulfilled test
func testAll_success()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
Async.background(after: 0.1) {
Async.main { progress(0.1) }
return
}
Async.background(after: 0.2) {
progress(1.0)
Async.main { fulfill("OK \(i)") }
}
}
//
// NOTE:
// For tracking each task's progress, you simply call `task.progress`
// instead of `Task.all(tasks).progress`.
//
task.progress { oldProgress, newProgress in
print("each progress = \(newProgress)")
return
}
tasks.append(task)
}
Task.all(tasks).progress { (oldProgress: Task.BulkProgress?, newProgress: Task.BulkProgress) in
print("all progress = \(newProgress.completedCount) / \(newProgress.totalCount)")
}.success { values -> Void in
for i in 0..<values.count {
XCTAssertEqual(values[i], "OK \(i)")
}
expect.fulfill()
}
self.wait()
}
/// any rejected test
func testAll_failure()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<5 {
// define fulfilling task
let task = Task { progress, fulfill, reject, configure in
Async.background(after: 0.1) {
Async.main { fulfill("OK \(i)") }
return
}
return
}
tasks.append(task)
}
for _ in 0..<5 {
// define rejecting task
let task = Task { progress, fulfill, reject, configure in
Async.background(after: 0.1) {
Async.main { reject("ERROR") }
return
}
return
}
tasks.append(task)
}
Task.all(tasks).success { values -> Void in
XCTFail("Should never reach here because of Task.all failure.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "ERROR", "Task.all non-cancelled error returns 1st-errored object (spec).")
expect.fulfill()
}
self.wait()
}
func testAll_cancel()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
var isCancelled = false
Async.background(after: 0.1) {
if isCancelled {
return
}
Async.main { fulfill("OK \(i)") }
}
configure.cancel = {
isCancelled = true
return
}
}
tasks.append(task)
}
let groupedTask = Task.all(tasks)
groupedTask.success { values -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "Cancel")
XCTAssertTrue(isCancelled)
expect.fulfill()
}
// cancel before fulfilled
Async.main(after: 0.01) {
groupedTask.cancel(error: "Cancel")
return
}
self.wait()
}
func testAll_pauseResume()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
var isPaused = false
Async.background(after: SAFE_BG_FLAG_CHECK_DELAY) {
while isPaused {
Thread.sleep(forTimeInterval: 0.1)
}
Async.main { fulfill("OK \(i)") }
}
configure.pause = {
isPaused = true
return
}
configure.resume = {
isPaused = false
return
}
}
tasks.append(task)
}
let groupedTask = Task.all(tasks)
groupedTask.success { values -> Void in
for i in 0..<values.count {
XCTAssertEqual(values[i], "OK \(i)")
}
expect.fulfill()
}
// pause & resume
self.perform {
groupedTask.pause()
XCTAssertEqual(groupedTask.state, TaskState.Paused)
Async.main(after: 1.0) {
groupedTask.resume()
XCTAssertEqual(groupedTask.state, TaskState.Running)
}
}
self.wait()
}
//--------------------------------------------------
// MARK: - Any
//--------------------------------------------------
/// any fulfilled test
func testAny_success()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
Async.background(after: 0.1) {
Async.main {
if i == 5 {
fulfill("OK \(i)")
}
else {
reject("Failed \(i)")
}
}
return
}
return
}
tasks.append(task)
}
Task.any(tasks).success { value -> Void in
XCTAssertEqual(value, "OK 5")
expect.fulfill()
}
self.wait()
}
/// all rejected test
func testAny_failure()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
Async.background(after: 0.1) {
Async.main { reject("Failed \(i)") }
return
}
return
}
tasks.append(task)
}
Task.any(tasks).success { value -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertTrue(error == nil, "Task.any non-cancelled error returns nil (spec).")
XCTAssertFalse(isCancelled)
expect.fulfill()
}
self.wait()
}
func testAny_cancel()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
var isCancelled = false
Async.background(after: SAFE_BG_FLAG_CHECK_DELAY) {
if isCancelled {
return
}
Async.main { fulfill("OK \(i)") }
}
configure.cancel = {
isCancelled = true
return
}
}
tasks.append(task)
}
let groupedTask = Task.any(tasks)
groupedTask.success { value -> Void in
XCTFail("Should never reach here.")
}.failure { error, isCancelled -> Void in
XCTAssertEqual(error!, "Cancel")
XCTAssertTrue(isCancelled)
expect.fulfill()
}
// cancel before fulfilled
self.perform {
groupedTask.cancel(error: "Cancel")
return
}
self.wait()
}
func testAny_pauseResume()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
var isPaused = false
Async.background(after: SAFE_BG_FLAG_CHECK_DELAY) {
while isPaused {
Thread.sleep(forTimeInterval: 0.1)
}
Async.main { fulfill("OK \(i)") }
}
configure.pause = {
isPaused = true
return
}
configure.resume = {
isPaused = false
return
}
}
tasks.append(task)
}
let groupedTask = Task.any(tasks)
groupedTask.success { value -> Void in
XCTAssertTrue(value.hasPrefix("OK"))
expect.fulfill()
}
// pause & resume
self.perform {
groupedTask.pause()
XCTAssertEqual(groupedTask.state, TaskState.Paused)
Async.main(after: SAFE_BG_FLAG_CHECK_DELAY+0.2) {
groupedTask.resume()
XCTAssertEqual(groupedTask.state, TaskState.Running)
}
}
self.wait()
}
//--------------------------------------------------
// MARK: - Some
//--------------------------------------------------
/// some fulfilled test
func testSome_success()
{
// NOTE: this is async test
if !self.isAsync { return }
typealias Task = SwiftTask.Task<Any, String, ErrorString>
let expect = self.expectation(description: #function)
var tasks: [Task] = Array()
for i in 0..<10 {
// define task
let task = Task { progress, fulfill, reject, configure in
Async.main(after: 0.1) {
if i == 3 || i == 5 {
fulfill("OK \(i)")
}
else {
reject("Failed \(i)")
}
}
return
}
tasks.append(task)
}
Task.some(tasks).success { values -> Void in
XCTAssertEqual(values.count, 2)
XCTAssertEqual(values[0], "OK 3")
XCTAssertEqual(values[1], "OK 5")
expect.fulfill()
}.failure { error, isCancelled -> Void in
XCTFail("Should never reach here because Task.some() will never reject internally.")
}
self.wait()
}
}
|
mit
|
e4268b1366560cd37e662001fb4dfeca
| 28.178415 | 177 | 0.447138 | 5.697771 | false | false | false | false |
aonawale/SwiftDataStore
|
Sources/SwiftDataStore/Adapter.swift
|
1
|
9185
|
//
// Adapter.swift
// SwiftDataStore
//
// Created by Ahmed Onawale on 2/4/17.
// Copyright © 2017 Ahmed Onawale. All rights reserved.
//
import Pluralize
public protocol Cacheable {
init()
}
public enum Request {
case findAll
case find(ID)
case query(Query)
case queryRecord(Query)
case create
case update(ID)
case delete(ID)
}
extension Request {
/// The method type of this request
var method: HTTPMethod {
switch self {
case .create:
return .post
case .update:
return .put
case .delete:
return .delete
default:
return .get
}
}
}
public protocol Adapter: Cacheable {
var host: Host { get }
var namespace: Namespace { get }
var headers: Headers { get }
var cachePolicy: URLRequest.CachePolicy { get }
var timeoutInterval: TimeInterval { get }
var client: NetworkProtocol { get }
func isSuccess(response: HTTPURLResponse, data: Data) -> Bool
func isInvalid(response: HTTPURLResponse, data: Data) -> Bool
func method(for request: Request) -> HTTPMethod
func headers(for request: Request) -> Headers
func path<T: Record>(for Type: T.Type) -> String
func data<T: Record>(for request: Request, store: Store, type: T.Type, snapshot: Snapshot) throws -> Data?
func handle(response: URLResponse?, data: Data?, error: Error?) throws -> Data
func urlFor<T: Record>(findAll type: T.Type, snapshot: Snapshot) throws -> URL
func urlFor<T: Record>(find type: T.Type, id: ID) throws -> URL
func urlFor<T: Record>(create type: T.Type, snapshot: Snapshot) throws -> URL
func requestFor<T: Record>(create type: T.Type, store: Store, snapshot: Snapshot) throws -> URLRequest
func requestFor<T: Record>(findAll type: T.Type, store: Store, snapshot: Snapshot) throws -> URLRequest
func find<T: Record>(type: T.Type, id: ID, store: Store, snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask?
func find<T: Record>(all type: T.Type, store: Store, snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask?
func create<T: Record>(type: T.Type, store: Store, snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask?
}
public extension Adapter {
var scheme: Scheme {
return .https
}
var namespace: Namespace {
return ""
}
var cachePolicy: URLRequest.CachePolicy {
return .useProtocolCachePolicy
}
var timeoutInterval: TimeInterval {
return 60.0
}
var headers: Headers {
return [
"Accept": "application/json",
"Content-Type": "application/json"
]
}
func path<T: Record>(for type: T.Type) -> String {
return String(describing: type).lowercased().pluralize()
}
func method(for request: Request) -> HTTPMethod {
return request.method
}
func headers(for request: Request) -> Headers {
return headers
}
func data<T: Record>(for request: Request, store: Store, type: T.Type, snapshot: Snapshot) throws -> Data? {
var hash = JSON()
let serializer = store.serializer(for: type)
switch request {
case .create:
serializer.serialize(into: &hash, snapshot: snapshot, options: [])
return try serializer.serialize(json: hash)
case .update(_):
serializer.serialize(into: &hash, snapshot: snapshot, options: [.includeId])
return try serializer.serialize(json: hash)
default:
return nil
}
}
func buildUrl<T: Record>(for request: Request, store: Store, type: T.Type, snapshot: Snapshot) throws -> URL {
switch request {
case .create:
return try urlFor(create: type, snapshot: snapshot)
case .find(let id):
return try urlFor(find: type, id: id)
default:
return try url(for: request, type: type)
}
}
private func url<T: Record>(for request: Request, type: T.Type) throws -> URL {
var paths = [namespace, path(for: type)]
var components = URLComponents()
components.scheme = scheme.description
components.host = host
switch request {
case .query(let query), .queryRecord(let query):
components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) }
case .update(let id), .delete(let id), .find(let id):
paths.append(id.value)
default:
break
}
components.path = paths.joined(separator: "/")
guard let url = components.url else { throw AdapterError.url }
return url
}
private func request<T: Record>(for type: T.Type, request: Request, store: Store, snapshot: Snapshot) throws -> URLRequest {
let url = try buildUrl(for: request, store: store, type: type, snapshot: snapshot)
var urlRequest = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeoutInterval)
urlRequest.allHTTPHeaderFields = headers(for: request)
urlRequest.httpMethod = method(for: request).name
urlRequest.httpBody = try data(for: request, store: store, type: type, snapshot: snapshot)
return urlRequest
}
func handle(response: URLResponse?, data: Data?, error: Error?) throws -> Data {
guard let response = response as? HTTPURLResponse,
let data = data else {
throw AdapterError.badResponse
}
if isSuccess(response: response, data: data) {
return data
} else if isInvalid(response: response, data: data) {
throw AdapterError.invalid
}
throw AdapterError(response.statusCode)
}
func isSuccess(response: HTTPURLResponse, data: Data) -> Bool {
return 200..<300 ~= response.statusCode || response.statusCode == 304
}
func isInvalid(response: HTTPURLResponse, data: Data) -> Bool {
return response.statusCode == 422
}
// MARK: URLRequests
func requestFor<T: Record>(findAll type: T.Type, store: Store, snapshot: Snapshot) throws -> URLRequest {
return try request(for: type, request: .findAll, store: store, snapshot: snapshot)
}
func requestFor<T: Record>(find type: T.Type, id: ID, store: Store, snapshot: Snapshot) throws -> URLRequest {
return try request(for: type, request: .find(id), store: store, snapshot: snapshot)
}
func requestFor<T: Record>(create type: T.Type, store: Store, snapshot: Snapshot) throws -> URLRequest {
return try request(for: type, request: .create, store: store, snapshot: snapshot)
}
// MARK: URLs
func urlFor<T: Record>(findAll type: T.Type, snapshot: Snapshot) throws -> URL {
return try url(for: .findAll, type: type)
}
func urlFor<T: Record>(find type: T.Type, id: ID) throws -> URL {
return try url(for: .find(id), type: type)
}
func urlFor<T: Record>(create type: T.Type, snapshot: Snapshot) throws -> URL {
return try url(for: .create, type: type)
}
func perform(request: URLRequest, completion: @escaping DataCompletion) -> URLSessionDataTask? {
return client.load(request: request) {
do {
let data = try self.handle(response: $1, data: $0, error: $2)
completion(data, nil)
} catch {
completion(nil, error)
}
}
}
// MARK: Adapter methods
@discardableResult func find<T: Record>(type: T.Type, id: ID, store: Store,
snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask? {
do {
let request = try requestFor(find: type, id: id, store: store, snapshot: snapshot)
return perform(request: request, completion: completion)
} catch {
completion(nil, error)
}
return nil
}
@discardableResult func find<T: Record>(all type: T.Type, store: Store,
snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask? {
do {
let request = try requestFor(findAll: type, store: store, snapshot: snapshot)
return perform(request: request, completion: completion)
} catch {
completion(nil, error)
}
return nil
}
@discardableResult func create<T: Record>(type: T.Type, store: Store,
snapshot: Snapshot, completion: @escaping DataCompletion) -> URLSessionDataTask? {
do {
let request = try requestFor(create: type, store: store, snapshot: snapshot)
return perform(request: request, completion: completion)
} catch {
completion(nil, error)
}
return nil
}
}
public class RESTAdapter: Adapter {
public var host: Host
public var client: NetworkProtocol
public required init() {
client = Ajax()
host = ""
}
}
|
bsd-2-clause
|
f7166aee023c28339de4555b1085eddb
| 34.053435 | 141 | 0.611934 | 4.394258 | false | false | false | false |
MaxHasADHD/MLOfflineManager
|
Source/OfflineManager.swift
|
1
|
6949
|
//
// OfflineManager.swift
// OfflineManager
//
// Created by Maximilian Litteral on 4/15/16.
// Copyright © 2016 Maximilian Litteral. All rights reserved.
//
import Foundation
enum OperationResult {
case Success
case Retry(interval: NSTimeInterval)
case Failed
}
class OfflineManager: NSObject {
// Type aliases
typealias SuccessCompletionClosure = ((result: OperationResult) -> Void)
// Static
static let defaultManager = OfflineManager()
static var handleOfflineOperation: ((operation: OfflineOperation, fromManager: OfflineManager, completion: SuccessCompletionClosure) -> Void)?
// Public
private(set) var reachability: Reachability?
private(set) var name: String
/// Maximum number of operations that can run at the same time. Default is set to 0, which means there is no limit.
var maxConcurrentOperations: Int = 0
/// Wait time between operations. This does not effect when new operations start if maxConcurrentOperations is 0, or if the maximimum has not been reached yet. Default is 0.
var waitTimeBetweenOperations: NSTimeInterval = 0
// Private
private var operations: [OfflineOperation] = []
private var numberOfRunningOperations: Int = 0
// MARK: - Lifecycle
convenience init?(name: String) {
guard name != "DefaultOfflineManager" else { return nil }
self.init()
self.name = name
}
override init() {
self.name = "DefaultOfflineManager"
super.init()
self.loadOperations()
do {
reachability = try Reachability.reachabilityForInternetConnection()
reachability!.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
if reachability.isReachableViaWiFi() {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability!.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
dispatch_async(dispatch_get_main_queue()) {
print("Not reachable")
}
}
}
catch let error as NSError {
print("Unable to create Reachability: \(error)")
}
}
deinit {
self.reachability?.stopNotifier()
// Save operations?
}
// MARK: - Actions
func startHandlingOperations() {
self.checkForNextOperation()
}
// MARK: Save and Load
func saveOperations() {
print("Saving \(self.operations.count) operations")
let archivedData = NSKeyedArchiver.archivedDataWithRootObject(self.operations)
NSUserDefaults.standardUserDefaults().setObject(archivedData, forKey: self.name)
NSUserDefaults.standardUserDefaults().synchronize()
}
func loadOperations() {
if let data = NSUserDefaults.standardUserDefaults().objectForKey(self.name) as? NSData,
operations = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [OfflineOperation] {
self.operations = operations
print("Loaded \(self.operations.count) operations")
}
else {
print("Nothing in defaults")
}
}
// MARK: Add / Remove operations
func append(operation: OfflineOperation) {
self.operations.append(operation)
if self.maxConcurrentOperations == 0 ||
self.numberOfRunningOperations != self.maxConcurrentOperations {
self.tryOperation(operation)
}
}
func tryOperation(operation: OfflineOperation) {
guard reachability?.currentReachabilityStatus != .NotReachable else { return }
self.numberOfRunningOperations += 1 // Increase number of running operations
operation.state == .Running
OfflineManager.handleOfflineOperation?(operation: operation, fromManager: self, completion: { [weak self] (response) in
guard let wSelf = self else { return }
wSelf.numberOfRunningOperations -= 1 // Decerment number of running operations
switch response {
case .Success:
print("Woohoo! Success")
wSelf.removeOperation(operation)
wSelf.checkForNextOperation()
case .Retry(let interval):
operation.state == .Preparing
print("Will retry in \(interval) seconds")
wSelf.wait(seconds: interval, block: {
wSelf.tryOperation(operation)
})
case .Failed:
operation.state == .Failed
print("Will retry at a later time")
wSelf.checkForNextOperation()
}
})
}
func removeOperation(operation: OfflineOperation) {
if let last = self.operations.last where last == operation {
self.operations.removeLast()
}
else {
guard let index = self.operations.indexOf(operation) else { return }
self.operations.removeAtIndex(index)
}
}
// MARK: - Private
private func wait(seconds seconds: Double, block: (() -> Void)) {
let delay = seconds * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
dispatch_after(time, dispatch_get_main_queue(), { () -> Void in
block()
})
}
private func checkForNextOperation() {
let operationsCount = self.operations.count
guard operationsCount > 0 else { return print("All finished!") }
for i in (0..<operationsCount).reverse() {
guard self.maxConcurrentOperations == 0 ||
self.numberOfRunningOperations != self.maxConcurrentOperations else { return } // Maximum number of operation are running
let operation = self.operations[i]
guard operation.state == .Ready else { continue } // Find operation that is not running
if self.waitTimeBetweenOperations > 0 {
operation.state == .Preparing
self.wait(seconds: self.waitTimeBetweenOperations, block: { [weak self] in
guard let wSelf = self else { return }
wSelf.tryOperation(operation)
})
return // Wait before running
}
else {
self.tryOperation(operation)
}
}
}
}
|
mit
|
f09bab4a17d5c6981b679f7a211d2778
| 34.090909 | 177 | 0.583909 | 5.369397 | false | false | false | false |
Trxy/TRX
|
TRXTests/specs/tween/TweenSpec.swift
|
1
|
3708
|
@testable import TRX
import Quick
import Nimble
class TweenSpec: QuickSpec {
override func spec() {
var subject: Tween<Double>!
var currentValue: Double!
beforeEach {
subject = Tween(from: 1,
to: 4,
time: 2,
ease: Ease.linear) { currentValue = $0 }
}
describe("tweenable") {
itBehavesLike(TweenableExamples.key) {
[
TweenableExamples.durationKey: 2.5,
TweenableExamples.factoryKey: TweenFactory(closure: {
return Tween(from: 1,
to: 4,
time: 2.5) { _ in }
})
]
}
}
describe("seek") {
it("should return correct value on start") {
subject.seek(offset: 0)
expect(currentValue) == 1
}
it("should return correct value in between") {
subject.seek(offset: 1)
expect(currentValue) == 2.5
}
it("should return correct value on completion") {
subject.seek(offset: 2)
expect(currentValue) == 4.0
}
}
describe("delay") {
beforeEach {
subject = Tween(from: 1,
to: 4,
time: 2,
delay: 0.5,
ease: Ease.linear) { currentValue = $0 }
}
context("duration") {
it("should have correct duration") {
expect(subject.duration) == 2.5
}
}
context("seek") {
it("should return correct value on start") {
subject.seek(offset: 0)
expect(currentValue) == 1
}
it("should return correct value after delay") {
subject.seek(offset: 0.5)
expect(currentValue) == 1
}
it("should return correct value in between") {
subject.seek(offset: 1.5)
expect(currentValue) == 2.5
}
it("should return correct value on complition") {
subject.seek(offset: 2.5)
expect(currentValue) == 4.0
}
}
}
describe("reversed") {
beforeEach() {
subject = Tween(from: 1,
to: 4,
time: 2,
ease: Ease.linear
) { currentValue = $0 }.reversed()
}
context("seek") {
it("should return correct value on start") {
subject.seek(offset: 0)
expect(currentValue) == 4
}
it("should return correct value in between") {
subject.seek(offset: 1)
expect(currentValue) == 2.5
}
it("should return correct value on completion") {
subject.seek(offset: 2)
expect(currentValue) == 1
}
}
}
describe("time stretch") {
beforeEach() {
subject = Tween(from: 1,
to: 4,
time: 2,
delay: 1.0,
ease: Ease.linear) { currentValue = $0 }
subject.duration = 6.0
}
context("seek") {
it("should return correct value on start") {
subject.seek(offset: 0)
expect(currentValue) == 1
}
it("should return correct value after delay") {
subject.seek(offset: 2)
expect(currentValue) == 1
}
it("should return correct value in between") {
subject.seek(offset: 4)
expect(currentValue) == 2.5
}
it("should return correct value on completion") {
subject.seek(offset: 6)
expect(currentValue) == 4.0
}
}
}
}
}
|
mit
|
c4de56502bb662307e9d8e20e01e6724
| 21.337349 | 63 | 0.470065 | 4.577778 | false | false | false | false |
stetro/domradio-ios
|
domradio-ios/Controller/NewsDetailViewController.swift
|
1
|
2120
|
//
// NewsDetailViewController.swift
// domradio-ios
//
// Created by Steffen Tröster on 24/06/15.
// Copyright (c) 2015 Steffen Tröster. All rights reserved.
//
import UIKit
import NJKWebViewProgress
import MWFeedParser
import RKDropdownAlert
class NewsDetailViewController: UIViewController, UIWebViewDelegate, NJKWebViewProgressDelegate {
@IBOutlet var webview:UIWebView?
@IBOutlet var progressView:UIProgressView?
var item:MWFeedItem?
var progressProxy:NJKWebViewProgress?
override func viewDidLoad() {
super.viewDidLoad()
if let item = self.item{
self.title = item.title
let url = NSURL (string: item.link!)
let requestObj = NSURLRequest(URL: url!)
self.progressProxy = NJKWebViewProgress()
self.webview!.loadRequest(requestObj)
self.webview!.delegate = progressProxy
self.progressProxy?.webViewProxyDelegate = self
self.progressProxy?.progressDelegate = self
}else{
RKDropdownAlert.title("Netzwerkfehler", message: "Artikel konnte nicht geladen werden!" );
}
}
@IBAction func share(){
var sharingItems = [AnyObject]()
if let text = item?.title {
sharingItems.append(text)
}
if let url = item?.link {
sharingItems.append(url)
}
let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
RKDropdownAlert.title("Netzwerkfehler", message: "Artikel konnte nicht geladen werden!" );
}
func webViewProgress(webViewProgress: NJKWebViewProgress!, updateProgress progress: Float) {
progressView!.setProgress(progress, animated: true)
}
}
|
mit
|
c2ff2163770ecec337313f35ff633b30
| 30.147059 | 118 | 0.651558 | 5.007092 | false | false | false | false |
yonaskolb/XcodeGen
|
Sources/ProjectSpec/TestTargeReference.swift
|
1
|
3474
|
import Foundation
import JSONUtilities
public struct TestableTargetReference: Hashable {
public var name: String
public var location: Location
public var targetReference: TargetReference {
switch location {
case .local:
return TargetReference(name: name, location: .local)
case .project(let projectName):
return TargetReference(name: name, location: .project(projectName))
case .package:
fatalError("Package target is only available for testable")
}
}
public enum Location: Hashable {
case local
case project(String)
case package(String)
}
public init(name: String, location: Location) {
self.name = name
self.location = location
}
}
extension TestableTargetReference {
public init(_ string: String) throws {
let paths = string.split(separator: "/")
switch paths.count {
case 2:
location = .project(String(paths[0]))
name = String(paths[1])
case 1:
location = .local
name = String(paths[0])
default:
throw SpecParsingError.invalidTargetReference(string)
}
}
public static func local(_ name: String) -> TestableTargetReference {
TestableTargetReference(name: name, location: .local)
}
public static func project(_ name: String) -> TestableTargetReference {
let paths = name.split(separator: "/")
return TestableTargetReference(name: String(paths[1]), location: .project(String(paths[0])))
}
public static func package(_ name: String) -> TestableTargetReference {
let paths = name.split(separator: "/")
return TestableTargetReference(name: String(paths[1]), location: .package(String(paths[0])))
}
}
extension TestableTargetReference: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
try! self.init(value)
}
}
extension TestableTargetReference: CustomStringConvertible {
public var reference: String {
switch location {
case .local: return name
case .project(let root), .package(let root):
return "\(root)/\(name)"
}
}
public var description: String {
reference
}
}
extension TestableTargetReference: JSONObjectConvertible {
public init(jsonDictionary: JSONDictionary) throws {
if let project: String = jsonDictionary.json(atKeyPath: "project") {
let paths = project.split(separator: "/")
name = String(paths[1])
location = .project(String(paths[0]))
} else if let project: String = jsonDictionary.json(atKeyPath: "package") {
let paths = project.split(separator: "/")
name = String(paths[1])
location = .package(String(paths[0]))
} else {
name = try jsonDictionary.json(atKeyPath: "local")
location = .local
}
}
}
extension TestableTargetReference: JSONEncodable {
public func toJSONValue() -> Any {
var dictionary: JSONDictionary = [:]
switch self.location {
case .package(let packageName):
dictionary["package"] = "\(packageName)/\(name)"
case .project(let projectName):
dictionary["project"] = "\(projectName)/\(name)"
case .local:
dictionary["local"] = name
}
return dictionary
}
}
|
mit
|
27ec96ca4cf99c9f7ac980e0caa6023d
| 30.017857 | 100 | 0.612838 | 4.778542 | false | true | false | false |
yangchaogit/actor-platform
|
actor-apps/app-ios/ActorSwift/FastCache.swift
|
24
|
2936
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
struct HashMap<T> {
var table = Array<SinglyLinkedList<T>?>()
init() {
for i in 0...99 {
table.append(SinglyLinkedList<T>())
}
}
mutating func setKey(key: Int64, withValue val: T) {
let hashedString = Int(abs(key) % 10)
if let collisionList = table[hashedString] {
collisionList.upsertNodeWithKey(key, AndValue: val)
} else {
table[hashedString] = SinglyLinkedList<T>()
table[hashedString]!.upsertNodeWithKey(key, AndValue: val)
}
}
func getValueAtKey(key: Int64) -> T? {
let hashedString = Int(abs(key) % 10)
if let collisionList = table[hashedString] {
return collisionList.findNodeWithKey(key)?.value
} else {
return nil
}
}
}
struct SinglyLinkedList<T> {
var head = CCHeadNode<CCSinglyNode<T>>()
func findNodeWithKey(key: Int64) -> CCSinglyNode<T>? {
if var currentNode = head.next {
while currentNode.key != key {
if let nextNode = currentNode.next {
currentNode = nextNode
} else {
return nil
}
}
return currentNode
} else {
return nil
}
}
func upsertNodeWithKey(key: Int64, AndValue val: T) -> CCSinglyNode<T> {
if var currentNode = head.next {
while let nextNode = currentNode.next {
if currentNode.key == key {
break
} else {
currentNode = nextNode
}
}
if currentNode.key == key {
currentNode.value = val
return currentNode
} else {
currentNode.next = CCSinglyNode<T>(key: key, value: val, nextNode: nil)
return currentNode.next!
}
} else {
head.next = CCSinglyNode<T>(key: key, value: val, nextNode: nil)
return head.next!
}
}
func displayNodes() {
println("Printing Nodes")
if var currentNode = head.next {
println("First Node's Value is \(currentNode.value!)")
while let nextNode = currentNode.next {
currentNode = nextNode
println("Next Node's Value is \(currentNode.value!)")
}
} else {
println("List is empty")
}
}
}
class CCNode<T> {
var value: T?
init(value: T?) {
self.value = value
}
}
class CCHeadNode<T> {
var next: T?
}
class CCSinglyNode<T>: CCNode<T> {
var key: Int64
var next: CCSinglyNode<T>?
init(key: Int64, value: T, nextNode: CCSinglyNode<T>?) {
self.next = nextNode
self.key = key
super.init(value: value)
}
}
|
mit
|
1c880af30b3fb6dba678b3799b298a23
| 27.784314 | 87 | 0.515327 | 4.206304 | false | false | false | false |
devpunk/cartesian
|
cartesian/View/DrawProject/Menu/VDrawProjectMenuEditBarCell.swift
|
1
|
2751
|
import UIKit
class VDrawProjectMenuEditBarCell:UICollectionViewCell
{
private weak var imageView:UIImageView!
private weak var labelTitle:UILabel!
private let kTitleHeight:CGFloat = 15
private let kTitleBottom:CGFloat = -18
private let kImageTop:CGFloat = 5
private let kImageBottom:CGFloat = 20
private let kAlphaSelected:CGFloat = 0.15
private let kAlphaNotSelected:CGFloat = 1
override init(frame:CGRect)
{
super.init(frame:frame)
clipsToBounds = true
backgroundColor = UIColor.clear
let imageView:UIImageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.clipsToBounds = true
imageView.contentMode = UIViewContentMode.center
imageView.isUserInteractionEnabled = false
self.imageView = imageView
let labelTitle:UILabel = UILabel()
labelTitle.translatesAutoresizingMaskIntoConstraints = false
labelTitle.backgroundColor = UIColor.clear
labelTitle.isUserInteractionEnabled = false
labelTitle.textAlignment = NSTextAlignment.center
labelTitle.font = UIFont.regular(size:12)
labelTitle.textColor = UIColor.black
self.labelTitle = labelTitle
addSubview(imageView)
addSubview(labelTitle)
NSLayoutConstraint.topToTop(
view:imageView,
toView:self,
constant:kImageTop)
NSLayoutConstraint.bottomToTop(
view:imageView,
toView:labelTitle,
constant:kImageBottom)
NSLayoutConstraint.equalsHorizontal(
view:imageView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:labelTitle,
toView:self,
constant:kTitleBottom)
NSLayoutConstraint.height(
view:labelTitle,
constant:kTitleHeight)
NSLayoutConstraint.equalsHorizontal(
view:labelTitle,
toView:self)
}
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 config(model:MDrawProjectMenuEditBarItem)
{
imageView.image = model.image
labelTitle.text = model.title
hover()
}
}
|
mit
|
63162c2b5577f2c8888069fbc8a1474c
| 24.95283 | 68 | 0.601236 | 5.743215 | false | false | false | false |
karstengresch/trhs-ios
|
InteractiveStory/InteractiveStory/Page.swift
|
1
|
2066
|
//
// Page.swift
// InteractiveStory
//
// Created by Karsten Gresch on 13.03.17.
// Copyright © 2017 Closure One. All rights reserved.
//
import Foundation
enum AdventureError: Error {
case nameNotProvided
}
class Page {
let story: Story
typealias Choice = (title: String, page: Page)
var firstChoice: Choice?
var secondChoice: Choice?
init(xStory: Story) {
story = xStory
}
}
extension Page {
func addChoiceWith(title: String, story: Story) -> Page {
let page = Page(xStory: story)
return addChoiceWith(title: title, page: page)
}
func addChoiceWith(title: String, page: Page) -> Page {
switch(firstChoice, secondChoice) {
case(.some, .some): return page
case(.none, .none), (.none, .some): firstChoice = (title, page)
case(.some, .none): secondChoice = (title, page)
}
return page
}
}
struct Adventure {
static func story(withName: String) -> Page {
let returnTrip = Page(xStory: .returnTrip(name: withName))
let touchdown = returnTrip.addChoiceWith(title: "Stop and Investigate", story: .touchDown)
let homeward = returnTrip.addChoiceWith(title: "Continue home to Earth", story: .homeward)
let rover = touchdown.addChoiceWith(title: "Explore the Rover", story: .rover(name: withName))
let crate = touchdown.addChoiceWith(title: "Open the crate", story: .crate)
homeward.addChoiceWith(title: "Head back to Mars", page: touchdown)
let home = homeward.addChoiceWith(title: "Continue Home to Earth", story: .home)
let cave = rover.addChoiceWith(title: "Explore the Coordinates", story: .cave)
rover.addChoiceWith(title: "Return to Earth", page: home)
cave.addChoiceWith(title: "Continue towards faint light", story: .droid(name: withName))
cave.addChoiceWith(title: "Refill the ship and explore the rover", page: rover)
crate.addChoiceWith(title: "Explore the Rover", page: rover)
crate.addChoiceWith(title: "Use the key", story: .monster)
return returnTrip
}
}
|
unlicense
|
c447efa1740d97ff12b2391feba9b538
| 25.818182 | 98 | 0.670702 | 3.554217 | false | false | false | false |
KiiPlatform/thing-if-iOSSample
|
SampleProject/Views/StatusBoolTypeTableViewCell.swift
|
1
|
815
|
//
// StatusBoolTypeTableViewCell.swift
// SampleProject
//
// Created by Yongping on 8/29/15.
// Copyright © 2015 Kii Corporation. All rights reserved.
//
import UIKit
class StatusBoolTypeTableViewCell: UITableViewCell {
var delegate: StatusTableViewCellDelegate?
var value: Bool? {
didSet {
if value != nil {
if value != boolSwitch.on {
boolSwitch.on = value!
}
}
}
}
@IBOutlet weak var boolSwitch: UISwitch!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var statusNameLabel: UILabel!
@IBAction func changeSwitch(sender: AnyObject) {
let boolSwitch = sender as! UISwitch
value = boolSwitch.on
delegate?.setStatus(self, value: boolSwitch.on)
}
}
|
mit
|
86cf1d507cca6f61782b09fdbbc4cb3a
| 22.941176 | 58 | 0.611794 | 4.472527 | false | false | false | false |
Yurssoft/QuickFile
|
QuickFile/Coordinators/YSSettingsCoordinator.swift
|
1
|
1201
|
//
// YSSettingsCoordinator.swift
// YSGGP
//
// Created by Yurii Boiko on 10/17/16.
// Copyright © 2016 Yurii Boiko. All rights reserved.
//
import UIKit
class YSSettingsCoordinator: YSCoordinatorProtocol {
func start(settingsViewController: YSSettingsTableViewController) {
let viewModel = YSSettingsViewModel()
settingsViewController.viewModel = viewModel
viewModel.model = YSSettingsModel()
viewModel.coordinatorDelegate = self
}
}
extension YSSettingsCoordinator: YSSettingsCoordinatorDelegate {
func viewModelSuccessfullyLoggedIn(viewModel: YSSettingsViewModel) {
if let tababarController = YSAppDelegate.appDelegate().window!.rootViewController as? UITabBarController {
tababarController.selectedIndex = 0 // go to drive tab
YSAppDelegate.appDelegate().driveTopCoordinator?.getFilesAfterSuccessLogin()
}
}
func viewModelDidDeleteAllLocalFiles(viewModel: YSSettingsViewModel) {
YSAppDelegate.appDelegate().playerDelegate?.filesDidChange()
YSAppDelegate.appDelegate().playlistDelegate?.filesDidChange()
YSAppDelegate.appDelegate().driveDelegate?.filesDidChange()
}
}
|
mit
|
6dd83bbebb68a26b6a8f2c8dabea7f4e
| 35.363636 | 114 | 0.740833 | 5.172414 | false | false | false | false |
franciscocgoncalves/ToDoList
|
ToDoListApp/ToDoListTableViewController.swift
|
1
|
4721
|
//
// ToDoListTableViewController.swift
// ToDoListApp
//
// Created by Francisco Gonçalves on 10/11/14.
// Copyright (c) 2014 SINFO. All rights reserved.
//
import UIKit
class ToDoListTableViewController: UITableViewController {
var toDoItems: [ToDoItem] = []
func loadInitialData() {
let item1 = ToDoItem()
item1.itemName = "Learn Swift"
toDoItems.append(item1)
let item2 = ToDoItem()
item2.itemName = "Like SINFO on Facebook"
toDoItems.append(item2)
let item3 = ToDoItem()
item3.itemName = "Like IA on Facebook"
toDoItems.append(item3)
}
override func viewDidLoad() {
super.viewDidLoad()
loadInitialData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return toDoItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ToDoCell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
let item = toDoItems[indexPath.row]
cell.textLabel.text = item.itemName
if(item.completed) {
cell.accessoryType = .Checkmark
}
else {
cell.accessoryType = .None
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var tappedItem = toDoItems[indexPath.row]
tappedItem.completed = !tappedItem.completed
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@IBAction func unwindToList(segue: UIStoryboardSegue) {
let source = segue.sourceViewController as AddToDoViewController
var toDoItem: ToDoItem? = source.toDoItem
if let item = toDoItem {
self.toDoItems.append(item)
self.tableView.reloadData()
}
}
}
|
mit
|
74fdf247a6c75cdd27a4825ff2b199ff
| 32.006993 | 157 | 0.652331 | 5.437788 | false | false | false | false |
vlfm/swapi-swift
|
Source/Parsers/RootParser.swift
|
1
|
858
|
import Foundation
final class RootParser {
static func make() -> Parser<Root> {
return { json in
return try Extract.from(jsonDictionary: json) { input in
let films = try input.url(at: "films")
let people = try input.url(at: "people")
let planets = try input.url(at: "planets")
let species = try input.url(at: "species")
let starships = try input.url(at: "starships")
let vehicles = try input.url(at: "vehicles")
return Root(films: films,
people: people,
planets: planets,
species: species,
starships: starships,
vehicles: vehicles)
}
}
}
}
|
apache-2.0
|
2bd5c8a25bf14601811408df0352d16e
| 36.304348 | 68 | 0.455711 | 4.959538 | false | false | false | false |
jwfriese/FrequentFlyer
|
FrequentFlyer/Builds/BuildsDataDeserializer.swift
|
1
|
823
|
import Foundation
import SwiftyJSON
import Result
class BuildsDataDeserializer {
var buildDataDeserializer = BuildDataDeserializer()
func deserialize(_ buildsData: Data) -> Result<[Build], DeserializationError> {
let buildsJSONObject = JSON(data: buildsData)
if buildsJSONObject.type == SwiftyJSON.Type.null {
return Result.failure(DeserializationError(details: "Could not interpret data as JSON dictionary", type: .invalidInputFormat))
}
let builds = buildsJSONObject.arrayValue.flatMap { nextBuildJSON -> Build? in
guard let nextBuildJSONData = try? nextBuildJSON.rawData(options: .prettyPrinted) else { return nil }
return buildDataDeserializer.deserialize(nextBuildJSONData).value
}
return Result.success(builds)
}
}
|
apache-2.0
|
baab342f4a3e89af6e75c1896fb4858c
| 34.782609 | 138 | 0.712029 | 5.208861 | false | false | false | false |
KordianKL/SongGenius
|
Song Genius/Song.swift
|
1
|
1111
|
//
// Song.swift
// Song Genius
//
// Created by Kordian Ledzion on 14.06.2017.
// Copyright © 2017 KordianLedzion. All rights reserved.
//
import RealmSwift
class Song: Object {
dynamic var name: String = ""
dynamic var artist: String = ""
dynamic var releaseYear: String = ""
dynamic var primaryKey: String = ""
dynamic var url: String = ""
convenience init(name: String, artist: String, releaseYear: String, url: String = "") {
self.init()
self.name = name
self.artist = artist
self.releaseYear = releaseYear
self.primaryKey = "\(self.name) by \(self.artist)"
self.url = url
}
convenience init(songEntity: SongEntity) {
self.init()
self.name = songEntity.name
self.artist = songEntity.artist
self.releaseYear = songEntity.releaseYear
self.primaryKey = songEntity.primaryKey
self.url = songEntity.url
}
var entity: SongEntity {
return SongEntity(artist: self.artist, name: self.name, releaseYear: self.releaseYear, url: self.url)
}
}
|
mit
|
6906f99d9e03c011560f7b92ffc45dfe
| 26.75 | 109 | 0.621622 | 4.036364 | false | false | false | false |
hacktoolkit/hacktoolkit-ios_lib
|
Hacktoolkit/lib/Twitter/models/Tweet.swift
|
1
|
14936
|
//
// Tweet.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
class Tweet: NSObject {
var tweetDictionary: NSDictionary!
// Tweet attributes
var id: Int?
var text: String?
var createdAtString: String?
var createdAt: NSDate?
var favoriteCount: Int?
var favorited: Bool?
var retweetCount: Int?
var retweeted: Bool?
// Tweet relations
var user: TwitterUser?
var retweetSource: Tweet?
var retweet: Tweet?
// Meta
var didReply = false
init(tweetDictionary: NSDictionary) {
self.tweetDictionary = tweetDictionary
self.id = tweetDictionary["id"] as? Int
self.text = tweetDictionary["text"] as? String
self.createdAtString = tweetDictionary["created_at"] as? String
var formatter = NSDateFormatter()
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
self.createdAt = formatter.dateFromString(createdAtString!)
self.favoriteCount = tweetDictionary["favorite_count"] as? Int ?? 0
self.favorited = (tweetDictionary["favorited"] as? Int)! == 1
self.retweetCount = tweetDictionary["retweet_count"] as? Int ?? 0
self.retweeted = (tweetDictionary["retweeted"] as? Int)! == 1
var userDictionary = tweetDictionary["user"] as NSDictionary
user = TwitterUser(userDictionary: userDictionary)
var retweetedStatus = tweetDictionary["retweeted_status"] as? NSDictionary
if retweetedStatus != nil {
self.retweetSource = Tweet(tweetDictionary: retweetedStatus!)
}
// TODO: figure out how to set didReply from the tweetDictionary
}
class func tweetsWithArray(tweetDictionaries: [NSDictionary]) -> [Tweet] {
var tweets = tweetDictionaries.map {
(tweetDictionary: NSDictionary) -> Tweet in
Tweet(tweetDictionary: tweetDictionary)
}
return tweets
}
class func create(status: String, asReplyTo replyTweet: Tweet?, withCompletion completion: (tweet: Tweet?, error: NSError?) -> Void) {
// https://dev.twitter.com/rest/reference/post/statuses/update
var params: [String:AnyObject] = [
"status": status,
]
if replyTweet != nil {
params["in_reply_to_status_id"] = replyTweet!.id!
}
TwitterClient.sharedInstance.POST(
TWITTER_API_STATUSES_UPDATE_RESOURCE,
parameters: params,
success: {
(request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
var tweet = Tweet(tweetDictionary: response as NSDictionary)
completion(tweet: tweet, error: nil)
if replyTweet != nil {
replyTweet!.didReply = true
}
},
failure: {
(request: AFHTTPRequestOperation!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
completion(tweet: nil, error: error)
}
)
}
func destroy(callback: (response: AnyObject!, error: NSError!) -> Void) {
TwitterClient.sharedInstance.POST(
"\(TWITTER_API_STATUSES_DESTROY_RESOURCE_PREFIX)\(self.id!)\(TWITTER_API_RESOURCE_SUFFIX)",
parameters: nil,
success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
NSLog("Successfully destroyed tweet")
callback(response: response, error: nil)
},
failure: {
(request: AFHTTPRequestOperation!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
NSLog("Failed to destroy tweet")
callback(response: nil, error: error)
}
)
}
func wasRetweeted() -> Bool {
var value = self.retweetSource != nil
return value
}
func getSource() -> Tweet {
var sourceTweet: Tweet
if self.wasRetweeted() {
sourceTweet = self.retweetSource!
} else {
sourceTweet = self
}
return sourceTweet
}
func toggleRetweet(callback: () -> Void) {
self.retweeted! = !self.retweeted!
if self.retweeted! == true {
self.getSource().retweetCount! += 1
self.retweet(callback)
} else {
self.unretweet(callback)
self.getSource().retweetCount! -= 1
}
}
func retweet(callback: () -> Void) {
TwitterClient.sharedInstance.POST(
"\(TWITTER_API_STATUSES_RETWEET_RESOURCE_PREFIX)\(self.id!)\(TWITTER_API_RESOURCE_SUFFIX)",
parameters: nil,
success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
NSLog("Successfully retweeted")
callback()
var retweet = Tweet(tweetDictionary: response as NSDictionary)
self.retweet = retweet
},
failure: {
(request: AFHTTPRequestOperation!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
NSLog("Failed to retweet")
callback()
// revert the optimistic API call
self.getSource().retweetCount! -= 1
}
)
}
func unretweet(callback: () -> Void) {
self.retweet?.destroy({
(response: AnyObject!, error: NSError!) -> Void in
callback()
if response != nil {
NSLog("Successfully unretweeted")
} else if error != nil {
NSLog("Failed to unretweet")
// revert the optimistic API call
self.getSource().retweetCount! += 1
}
})
}
func toggleFavorite(callback: () -> Void) {
self.favorited! = !self.favorited!
if self.favorited! == true {
self.getSource().favoriteCount! += 1
self.favorite(callback)
} else {
self.unfavorite(callback)
self.getSource().favoriteCount! -= 1
}
}
func favorite(callback: () -> Void) {
var params: [String:AnyObject] = [
"id" : self.id!,
]
TwitterClient.sharedInstance.POST(
TWITTER_API_FAVORITES_CREATE_RESOURCE,
parameters: params,
success: {
(request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
NSLog("Successfully favorited")
callback()
},
failure: {
(request: AFHTTPRequestOperation!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
NSLog("Failed to favorite")
callback()
// revert the optimistic API call
self.getSource().favoriteCount! -= 1
}
)
}
func unfavorite(callback: () -> Void) {
var params: [String:AnyObject] = ["id" : self.id!]
TwitterClient.sharedInstance.POST(
TWITTER_API_FAVORITES_DESTROY_RESOURCE,
parameters: params,
success: { (request: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
NSLog("Successfully unfavorited")
callback()
},
failure: {
(request: AFHTTPRequestOperation!, error: NSError!) -> Void in
HTKNotificationUtils.displayNetworkErrorMessage()
NSLog("Failed to favorite")
callback()
// revert the optimistic API call
self.getSource().favoriteCount! += 1
}
)
}
}
//{
// contributors = "<null>";
// coordinates = "<null>";
// "created_at" = "Tue Sep 30 19:57:18 +0000 2014";
// entities = {
// hashtags = (
// );
// media = (
// {
// "display_url" = "pic.twitter.com/hATh2M5jDW";
// "expanded_url" = "http://twitter.com/crunchbase/status/517040509525565440/photo/1";
// id = 517040508623785984;
// "id_str" = 517040508623785984;
// indices = (
// 122,
// 144
// );
// "media_url" = "http://pbs.twimg.com/media/ByzlmmsCEAAhzHz.png";
// "media_url_https" = "https://pbs.twimg.com/media/ByzlmmsCEAAhzHz.png";
// sizes = {
// large = {
// h = 348;
// resize = fit;
// w = 408;
// };
// medium = {
// h = 348;
// resize = fit;
// w = 408;
// };
// small = {
// h = 290;
// resize = fit;
// w = 340;
// };
// thumb = {
// h = 150;
// resize = crop;
// w = 150;
// };
// };
// type = photo;
// url = "http://t.co/hATh2M5jDW";
// }
// );
// symbols = (
// );
// urls = (
// {
// "display_url" = "bit.ly/1rDF5kV";
// "expanded_url" = "http://bit.ly/1rDF5kV";
// indices = (
// 99,
// 121
// );
// url = "http://t.co/R68NqOUfwK";
// }
// );
// "user_mentions" = (
// );
// };
// "extended_entities" = {
// media = (
// {
// "display_url" = "pic.twitter.com/hATh2M5jDW";
// "expanded_url" = "http://twitter.com/crunchbase/status/517040509525565440/photo/1";
// id = 517040508623785984;
// "id_str" = 517040508623785984;
// indices = (
// 122,
// 144
// );
// "media_url" = "http://pbs.twimg.com/media/ByzlmmsCEAAhzHz.png";
// "media_url_https" = "https://pbs.twimg.com/media/ByzlmmsCEAAhzHz.png";
// sizes = {
// large = {
// h = 348;
// resize = fit;
// w = 408;
// };
// medium = {
// h = 348;
// resize = fit;
// w = 408;
// };
// small = {
// h = 290;
// resize = fit;
// w = 340;
// };
// thumb = {
// h = 150;
// resize = crop;
// w = 150;
// };
// };
// type = photo;
// url = "http://t.co/hATh2M5jDW";
// }
// );
// };
// "favorite_count" = 1;
// favorited = 0;
// geo = "<null>";
// id = 517040509525565440;
// "id_str" = 517040509525565440;
// "in_reply_to_screen_name" = "<null>";
// "in_reply_to_status_id" = "<null>";
// "in_reply_to_status_id_str" = "<null>";
// "in_reply_to_user_id" = "<null>";
// "in_reply_to_user_id_str" = "<null>";
// lang = en;
// place = "<null>";
// "possibly_sensitive" = 0;
// "retweet_count" = 6;
// retweeted = 0;
// source = "<a href=\"http://twitter.com\" rel=\"nofollow\">Twitter Web Client</a>";
// text = "Recent investments & new startups indicate growing interest towards Google Glass in healthcare http://t.co/R68NqOUfwK http://t.co/hATh2M5jDW";
// truncated = 0;
// user = {
// "contributors_enabled" = 0;
// "created_at" = "Wed Apr 02 01:07:12 +0000 2008";
// "default_profile" = 0;
// "default_profile_image" = 0;
// description = "CrunchBase is the world\U2019s most comprehensive dataset of startup activity and it\U2019s accessible to everyone.";
// entities = {
// description = {
// urls = (
// );
// };
// url = {
// urls = (
// {
// "display_url" = "crunchbase.com";
// "expanded_url" = "http://www.crunchbase.com";
// indices = (
// 0,
// 22
// );
// url = "http://t.co/2sOf3bjuA7";
// }
// );
// };
// };
// "favourites_count" = 159;
// "follow_request_sent" = 0;
// "followers_count" = 31183;
// following = 1;
// "friends_count" = 22424;
// "geo_enabled" = 1;
// id = 14279577;
// "id_str" = 14279577;
// "is_translation_enabled" = 0;
// "is_translator" = 0;
// lang = en;
// "listed_count" = 1083;
// location = "San Francisco";
// name = CrunchBase;
// notifications = 0;
// "profile_background_color" = C0DEED;
// "profile_background_image_url" = "http://abs.twimg.com/images/themes/theme1/bg.png";
// "profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme1/bg.png";
// "profile_background_tile" = 0;
// "profile_banner_url" = "https://pbs.twimg.com/profile_banners/14279577/1398278857";
// "profile_image_url" = "http://pbs.twimg.com/profile_images/458740928761446401/O2mWKocb_normal.png";
// "profile_image_url_https" = "https://pbs.twimg.com/profile_images/458740928761446401/O2mWKocb_normal.png";
// "profile_link_color" = 2992A7;
// "profile_sidebar_border_color" = C0DEED;
// "profile_sidebar_fill_color" = DDEEF6;
// "profile_text_color" = 333333;
// "profile_use_background_image" = 1;
// protected = 0;
// "screen_name" = crunchbase;
// "statuses_count" = 2171;
// "time_zone" = "Pacific Time (US & Canada)";
// url = "http://t.co/2sOf3bjuA7";
// "utc_offset" = "-25200";
// verified = 0;
// };
//}
|
mit
|
b0efebda5ee6cdd73e2f51a1a814de19
| 35.788177 | 160 | 0.468666 | 4.152349 | false | false | false | false |
Drusy/auvergne-webcams-ios
|
Carthage/Checkouts/realm-cocoa/examples/ios/swift/Encryption/AppDelegate.swift
|
1
|
1303
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import UIKit
#if !swift(>=4.2)
extension UIApplication {
typealias LaunchOptionsKey = UIApplicationLaunchOptionsKey
}
#endif
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
return true
}
}
|
apache-2.0
|
c41e1c7d948f8250f923d3560b436c4f
| 33.289474 | 151 | 0.650806 | 5.212 | false | false | false | false |
harenbrs/swix
|
swixUseCases/swix-OSX/swix/ndarray/helper-functions.swift
|
2
|
2410
|
//
// helper-functions.swift
// swix
//
// Created by Scott Sievert on 8/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
func println(x: ndarray, prefix:String="array([", postfix:String="])", newline:String="\n", format:String="%.3f", seperator:String=", ", printWholeMatrix:Bool=false){
print(prefix)
var suffix = seperator
var printed = false
for i in 0..<x.n{
if i==x.n-1 { suffix = "" }
if printWholeMatrix || (x.n)<16 || i<3 || i>(x.n-4){
print(NSString(format: format+suffix, x[i]))
}else if printed == false{
printed = true
print("..., ")
}
}
print(postfix)
print(newline)
}
func print(x: ndarray, prefix:String="ndarray([", postfix:String="])", format:String="%.3f", printWholeMatrix:Bool=false){
println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printWholeMatrix:printWholeMatrix)
}
func concat(x:ndarray, y:ndarray)->ndarray{
var z = zeros(x.n + y.n)
z[0..<x.n] = x
z[x.n..<y.n+x.n] = y
return z
}
func argwhere(idx: ndarray) -> ndarray{
// counts non-zero elements, return array of doubles (which can be indexed!).
var i = arange(idx.n)
var args = zeros(sum(idx).int)
vDSP_vcmprsD(!i, 1.cint, !idx, 1.cint, !args, 1.cint, vDSP_Length(idx.n))
return args
}
func reverse(x:ndarray) -> ndarray{
var y = x.copy()
vDSP_vrvrsD(!y, 1.cint, vDSP_Length(y.n.cint))
return y
}
func sort(x:ndarray)->ndarray{
var y = x.copy()
y.sort()
return y
}
func delete(x:ndarray, idx:ndarray) -> ndarray{
var i = ones(x.n)
i[idx] *= 0
return x[argwhere(i)]
}
func repeat(x: ndarray, N:Int, axis:Int=0) -> ndarray{
var y = zeros((N, x.n))
// wrapping using OpenCV
CVWrapper.repeat(!x, to:!y, n_x:x.n.cint, n_repeat:N.cint)
if axis==0{}
else if axis==1 { y = y.T}
return y.flat
}
func write_csv(x:ndarray, #filename:String, prefix:String=S2_PREFIX){
var seperator=","
var str = ""
for i in 0..<x.n{
seperator = i == x.n-1 ? "," : ","
str += String(format: "\(x[i])"+seperator)
}
str += "\n"
var error:NSError?
str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding, error: &error)
if let error=error{
println("File probably wasn't recognized \n\(error)")
}
}
|
mit
|
084add830ce630597e6da1e1f6399bfc
| 28.390244 | 166 | 0.590871 | 3.113695 | false | false | false | false |
zhou9734/ZCJImagePicker
|
ZCJImagePicker/ImagePicker/Preview/PreviewViewController.swift
|
1
|
7743
|
//
// PreviewViewController.swift
// 图片选择器
//
// Created by zhoucj on 16/8/25.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
let PreviewReuseIdentifier = "PreviewReuseIdentifier"
class PreviewViewController: UIViewController {
var alassetModels = [ALAssentModel]()
var countPhoto = 0
var _currentImageIndex: Int = -1
var indexPath: NSIndexPath?
init(alassetModels: [ALAssentModel], countPhoto: Int, indexPath: NSIndexPath){
self.alassetModels = alassetModels
self.countPhoto = countPhoto
self.indexPath = indexPath
if let alassetModel = self.alassetModels.first where alassetModel.isFirst {
self.alassetModels.removeFirst()
}
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI(){
view.addSubview(collectionView)
view.addSubview(naviBar)
collectionView.frame = self.view.frame
//转到点击到的图片
if let tempIndex = indexPath {
countLbl.text = "\(tempIndex.item + 1)" + "/" + "\(alassetModels.count)"
collectionView.scrollToItemAtIndexPath(tempIndex, atScrollPosition: .Left, animated: true)
}
naviBar.translatesAutoresizingMaskIntoConstraints = false
let dict = ["naviBar": naviBar]
var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[naviBar]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[naviBar(64)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict)
view.addConstraints(cons)
dealCountPhoto()
}
//导航栏
private lazy var naviBar: UINavigationBar = {
let nvBar = UINavigationBar()
nvBar.barStyle = .Default
let nvBarItem = UINavigationItem()
nvBarItem.leftBarButtonItem = UIBarButtonItem(customView: self.leftButton)
nvBarItem.rightBarButtonItem = UIBarButtonItem(customView: self.rightButton)
nvBarItem.titleView = self.countLbl
nvBar.items = [nvBarItem]
return nvBar
}()
//图片浏览
lazy var collectionView: UICollectionView = {
let clv = UICollectionView(frame: CGRectZero, collectionViewLayout: PreviewFlowLayout())
clv.registerClass(PreviewCollectionCell.self, forCellWithReuseIdentifier: PreviewReuseIdentifier)
clv.dataSource = self
clv.delegate = self
clv.backgroundColor = UIColor.whiteColor()
return clv
}()
//标签
private lazy var countLbl: UILabel = {
let lbl = UILabel()
lbl.text = "0/0"
lbl.textAlignment = .Center
lbl.font = UIFont.systemFontOfSize(20)
lbl.bounds = CGRectMake(0, 0, 100, 40)
return lbl
}()
//返回按钮
private lazy var leftButton: UIButton = {
let btn = UIButton()
btn.setTitle("返回", forState: .Normal)
btn.setTitleColor(UIColor.grayColor(), forState: .Normal)
btn.titleLabel?.font = UIFont.systemFontOfSize(16)
btn.addTarget(self, action: Selector("backBtnClick"), forControlEvents: .TouchUpInside)
btn.frame.size = CGSize(width: 50, height: 35)
return btn
}()
//下一步按钮
private lazy var rightButton: UIButton = {
let btn = UIButton()
btn.setTitle("下一步", forState: .Normal)
btn.addTarget(self, action: Selector("nextStepClick"), forControlEvents: .TouchUpInside)
btn.setBackgroundImage(UIImage(named: "tabbar_compose_below_button"), forState: .Normal)
btn.setBackgroundImage(UIImage(named: "common_button_big_orange"), forState: .Selected)
btn.setTitleColor(UIColor.grayColor(), forState: .Normal)
btn.setTitleColor(UIColor.whiteColor(), forState: .Selected)
btn.frame.size = CGSize(width: 70, height: 28)
btn.titleLabel?.font = UIFont.systemFontOfSize(15)
return btn
}()
@objc private func backBtnClick(){
NSNotificationCenter.defaultCenter().postNotificationName(RreviewPhotoDone, object: self, userInfo: ["alassetModels": alassetModels])
dismissViewControllerAnimated(true, completion: nil)
}
@objc private func nextStepClick(){
NSNotificationCenter.defaultCenter().postNotificationName(NextSetp, object: self, userInfo: ["alassetModels": alassetModels])
dismissViewControllerAnimated(true, completion: nil)
}
}
//MARK: - UICollectionViewDataSource代理
extension PreviewViewController: UICollectionViewDataSource{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return alassetModels.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PreviewReuseIdentifier, forIndexPath: indexPath) as! PreviewCollectionCell
cell.delegate = self
cell.assentModel = alassetModels[indexPath.item]
cell.index = indexPath.item
return cell
}
}
//MARK: - UICollectionViewDelegate代理
extension PreviewViewController: UICollectionViewDelegate{
func scrollViewDidScroll(scrollView: UIScrollView) {
let temIndex = Int((scrollView.contentOffset.x + scrollView.bounds.size.width) / scrollView.bounds.size.width)
countLbl.text = "\(temIndex)" + "/" + "\(alassetModels.count)"
_currentImageIndex = alassetModels[temIndex - 1].orginIndex
}
}
//MARK: - PhotoLibraryCellDelegate代理
extension PreviewViewController: PhotoLibraryCellDelegate{
func countCanSelected() -> Bool {
return countPhoto < 9 ? true : false
}
func doSelectedPhoto(index: Int, checked: Bool) {
if checked{
countPhoto = countPhoto + 1
alassetModels[index].isChecked = true
}else{
countPhoto = countPhoto - 1
alassetModels[index].isChecked = false
}
dealCountPhoto()
}
func dealCountPhoto(){
if countPhoto > 0{
rightButton.setTitle("下一步(\(countPhoto))", forState: .Normal)
rightButton.frame.size = CGSize(width: 90, height: 28)
rightButton.selected = true
rightButton.enabled = true
}else{
rightButton.frame.size = CGSize(width: 70, height: 28)
rightButton.setTitle("下一步", forState: .Normal)
rightButton.selected = false
rightButton.enabled = false
}
}
}
//MARK: - 自定义布局
class PreviewFlowLayout: UICollectionViewFlowLayout{
override func prepareLayout() {
//设置每个cell尺寸
let screenSize = UIScreen.mainScreen().bounds.size
// itemSize = CGSizeMake(screenSize.width, screenSize.height - 64)
itemSize = screenSize
// 最小的行距
minimumLineSpacing = 0
// 最小的列距
minimumInteritemSpacing = 0
// collectionView的滚动方向
scrollDirection = .Horizontal // default .Vertical
//设置分页
collectionView?.pagingEnabled = true
//禁用回弹
collectionView?.bounces = false
//去除滚动条
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.showsVerticalScrollIndicator = false
}
}
|
mit
|
55c3f5c6d2da2cee2cec70c620458d80
| 39.682796 | 160 | 0.669046 | 4.84379 | false | false | false | false |
carlosgrossi/ExtensionKit
|
ExtensionKit/ExtensionKit/UIKit/UILabel.swift
|
1
|
511
|
//
// UILabel.swift
// ExtensionKit
//
// Created by Carlos Grossi on 22/06/17.
// Copyright © 2017 Carlos Grossi. All rights reserved.
//
import Foundation
public extension UILabel {
convenience init(text: String, numberOfLines: Int = 0, textAlignment: NSTextAlignment = .center, font: UIFont?) {
self.init(frame: CGRect.zero)
self.text = text
self.numberOfLines = numberOfLines
self.textAlignment = textAlignment
self.font = font ?? UIFont.systemFont(ofSize: 20)
self.sizeToFit()
}
}
|
mit
|
069022e4f8f18adc86cdf82a84799187
| 22.181818 | 114 | 0.711765 | 3.541667 | false | false | false | false |
alessandrostone/MusicTheory
|
MusicTheory/Note.swift
|
1
|
2397
|
//
// Note.swift
// MusicTheory
//
// Created by Daniel Breves Ribeiro on 2/04/2015.
// Copyright (c) 2015 Daniel Breves. All rights reserved.
//
import Foundation
public class Note {
public let name: String
public let value: Int8
public let octave: Int8
lazy var letter: String = {
return String(first(self.name)!)
}()
lazy var letterIndex: Int = {
let letter = String(first(self.name)!)
return find(Music.Alphabet, letter)!
}()
public init(name: String, octave: Int8 = 4) {
self.name = name
self.octave = octave
let keyLetter = String(first(name)!)
var oct = octave
var noteValue = Music.Notes[keyLetter]!
if countElements(name) > 1 {
let accident = name[name.endIndex.predecessor()]
if accident == "#" {
noteValue++
} else if accident == "b" {
noteValue--
}
}
noteValue += (octave + 1) * 12
self.value = noteValue
}
private init(name: String, value: Int8, octave: Int8) {
self.name = name
self.value = value
self.octave = octave
}
public func scale(type: String) -> RootWithIntervals {
return RootWithIntervals(root: self, intervals: Music.Scales[type]!)
}
public func chord(quality: String) -> RootWithIntervals {
return RootWithIntervals(root: self, intervals: Music.Chords[quality]!)
}
public func add(intervalSymbol: String) -> Note {
let interval = Music.Intervals[intervalSymbol]!
let noteLetterValue = Music.Notes[self.letter]!
let resultantLetterIndex = (self.letterIndex + Int(interval.degree)) % Music.Alphabet.count
var resultantNoteName = Music.Alphabet[resultantLetterIndex]
var resultantLetterValue = Music.Notes[resultantNoteName]!
let resultantNoteValue = self.value + interval.steps
var octave = self.octave
if resultantLetterValue < noteLetterValue {
octave++
}
resultantLetterValue += (octave + 1) * 12
let accidentals = distance(resultantLetterValue, resultantNoteValue)
if accidentals != 0 {
let accidentalSymbol = accidentals > 0 ? "#" : "b"
let numberOfAccidentals = abs(accidentals)
for _ in 0..<numberOfAccidentals {
resultantNoteName += accidentalSymbol
}
}
return Note(name: resultantNoteName, value: resultantNoteValue, octave: octave)
}
}
|
mit
|
fe15e74156ec8cf650e45b03bdb87b92
| 25.351648 | 95 | 0.64539 | 4.015075 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/Managers/Launcher/AnalyticsCoordinator.swift
|
1
|
1458
|
//
// AnalyticsCoordinator.swift
// Rocket.Chat
//
// Created by Rafael Machado on 11/12/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import Foundation
import Fabric
import Crashlytics
import Firebase
let kCrashReportingDisabledKey = "kCrashReportingDisabledKey"
private var isFirebaseInitialized = false
struct AnalyticsCoordinator: LauncherProtocol {
static var isUsageDataLoggingDisabled: Bool {
return UserDefaults.standard.bool(forKey: kCrashReportingDisabledKey)
}
static func toggleCrashReporting(disabled: Bool) {
UserDefaults.standard.set(disabled, forKey: kCrashReportingDisabledKey)
if !disabled {
AnalyticsCoordinator().prepareToLaunch(with: nil)
}
}
func prepareToLaunch(with options: [UIApplication.LaunchOptionsKey: Any]?) {
if AnalyticsCoordinator.isUsageDataLoggingDisabled {
return
}
launchFabric()
launchFirebase()
}
private func launchFirebase() {
#if RELEASE || BETA
guard
!isFirebaseInitialized,
let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
NSDictionary(contentsOfFile: path) != nil
else {
return
}
isFirebaseInitialized = true
FirebaseApp.configure()
#endif
}
private func launchFabric() {
Fabric.with([Crashlytics.self])
}
}
|
mit
|
452cdb0a19700ce61baa4d1d04972ba5
| 23.694915 | 92 | 0.660261 | 4.684887 | false | false | false | false |
MaxHasADHD/TraktKit
|
Common/Wrapper/Resources/UserResource.swift
|
1
|
1528
|
//
// UserResource.swift
//
//
// Created by Maximilian Litteral on 9/9/22.
//
import Foundation
extension TraktManager {
/// Resource for authenticated user
public struct CurrentUserResource {
public let traktManager: TraktManager
init(traktManager: TraktManager = .sharedManager) {
self.traktManager = traktManager
}
// MARK: - Methods
public func settings() async throws -> Route<AccountSettings> {
try await traktManager.get("users/settings", authorized: true)
}
}
/// Resource for /Users/id
public struct UsersResource {
public let username: String
public let traktManager: TraktManager
init(username: String, traktManager: TraktManager = .sharedManager) {
self.username = username
self.traktManager = traktManager
}
// MARK: - Methods
public func lists() async throws -> Route<[TraktList]> {
try await traktManager.get("users/\(username)/lists")
}
public func itemsOnList(_ listId: String, type: ListItemType? = nil) async throws -> Route<[TraktListItem]> {
if let type = type {
return try await traktManager.get("users/\(username)/lists/\(listId)/items/\(type.rawValue)")
} else {
return try await traktManager.get("users/\(username)/lists/\(listId)/items")
}
}
}
}
|
mit
|
c1da27304d95c7ba5a271ef97927a747
| 28.960784 | 117 | 0.574607 | 5.110368 | false | false | false | false |
instacrate/tapcrate-api
|
Sources/api/Stripe/Models/Account/Account.swift
|
1
|
11006
|
//
// Account.swift
// Stripe
//
// Created by Hakon Hanesand on 1/2/17.
//
//
import Node
import Vapor
import Foundation
public final class DeclineChargeRules: NodeConvertible {
public let avs_failure: Bool
public let cvc_failure: Bool
public required init(node: Node) throws {
avs_failure = try node.extract("avs_failure")
cvc_failure = try node.extract("cvc_failure")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"avs_failure" : .bool(avs_failure),
"cvc_failure" : .bool(cvc_failure)
] as [String : Node])
}
}
public final class Document: NodeConvertible {
public let id: String
public let created: Date
public let size: Int
public required init(node: Node) throws {
id = try node.extract("id")
created = try node.extract("created")
size = try node.extract("size")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"id" : .string(id),
"created" : try created.makeNode(in: context),
"size" : .number(.int(size))
] as [String : Node])
}
}
public final class DateOfBirth: NodeConvertible {
public let day: Int?
public let month: Int?
public let year: Int?
public required init(node: Node) throws {
day = try? node.extract("day")
month = try? node.extract("month")
year = try? node.extract("year")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node.object([:]).add(objects: [
"day" : day,
"month" : month,
"year" : year
])
}
}
public final class TermsOfServiceAgreement: NodeConvertible {
public let date: Date?
public let ip: String?
public let user_agent: String?
public required init(node: Node) throws {
date = try? node.extract("date")
ip = try? node.extract("ip")
user_agent = try? node.extract("user_agent")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node.object([:]).add(objects: [
"date" : date,
"ip" : ip,
"user_agent" : user_agent
])
}
}
public final class TransferSchedule: NodeConvertible {
public let delay_days: Int
public let interval: Interval
public required init(node: Node) throws {
delay_days = try node.extract("delay_days")
interval = try node.extract("interval")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"delay_days" : .number(.int(delay_days)),
"interval" : try interval.makeNode(in: context)
] as [String : Node])
}
}
public final class Keys: NodeConvertible {
public let secret: String
public let publishable: String
public required init(node: Node) throws {
secret = try node.extract("secret")
publishable = try node.extract("publishable")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"secret" : .string(secret),
"publishable" : .string(publishable)
] as [String : Node])
}
}
extension Sequence where Iterator.Element == (key: String, value: Node) {
func group(with separator: String = ".") throws -> Node {
guard let dictionary = self as? [String : Node] else {
throw Abort.custom(status: .internalServerError, message: "Unable to cast to [String: Node].")
}
var result = Node.object([:])
dictionary.forEach { (arg: (key: String, value: Node)) -> () in
let (key, value) = arg
result[key.components(separatedBy: separator)] = value
}
return result
}
}
public final class StripeAccount: NodeConvertible {
static let type = "account"
public let id: String
public let business_logo: String?
public let business_name: String?
public let business_url: String?
public let charges_enabled: Bool
public let country: CountryType
public let debit_negative_balances: Bool
public let decline_charge_on: DeclineChargeRules
public let default_currency: Currency
public let details_submitted: Bool
public let display_name: String?
public let email: String
public let external_accounts: [ExternalAccount]
public let legal_entity: LegalEntity
public let managed: Bool
public let product_description: String?
public let statement_descriptor: String?
public let support_email: String?
public let support_phone: String?
public let timezone: String
public let tos_acceptance: TermsOfServiceAgreement
public let transfer_schedule: TransferSchedule
public let transfer_statement_descriptor: String?
public let transfers_enabled: Bool
public let verification: IdentityVerification
public let keys: Keys?
public let metadata: Node
public required init(node: Node) throws {
guard try node.extract("object") == StripeAccount.type else {
throw NodeError.unableToConvert(input: node, expectation: StripeAccount.type, path: ["object"])
}
id = try node.extract("id")
business_logo = try? node.extract("business_logo")
business_name = try? node.extract("business_name")
business_url = try? node.extract("business_url")
charges_enabled = try node.extract("charges_enabled")
country = try node.extract("country")
debit_negative_balances = try node.extract("debit_negative_balances")
decline_charge_on = try node.extract("decline_charge_on")
default_currency = try node.extract("default_currency")
details_submitted = try node.extract("details_submitted")
display_name = try? node.extract("display_name")
email = try node.extract("email")
external_accounts = try node.extractList("external_accounts")
legal_entity = try node.extract("legal_entity")
managed = try node.extract("managed")
product_description = try? node.extract("product_description")
statement_descriptor = try? node.extract("statement_descriptor")
support_email = try? node.extract("support_email")
support_phone = try? node.extract("support_phone")
timezone = try node.extract("timezone")
tos_acceptance = try node.extract("tos_acceptance")
transfer_schedule = try node.extract("transfer_schedule")
transfer_statement_descriptor = try? node.extract("transfer_statement_descriptor")
transfers_enabled = try node.extract("transfers_enabled")
verification = try node.extract("verification")
keys = try? node.extract("keys")
metadata = try node.extract("metadata")
}
public func makeNode(in context: Context?) throws -> Node {
return try Node(node: [
"id" : .string(id),
"charges_enabled" : .bool(charges_enabled),
"country" : try country.makeNode(in: context),
"debit_negative_balances" : .bool(debit_negative_balances),
"decline_charge_on" : try decline_charge_on.makeNode(in: context),
"default_currency" : try default_currency.makeNode(in: context),
"details_submitted" : .bool(details_submitted),
"email" : .string(email),
"external_accounts" : try .array(external_accounts.map { try $0.makeNode(in: context) }),
"legal_entity" : try legal_entity.makeNode(in: context),
"managed" : .bool(managed),
"timezone" : .string(timezone),
"tos_acceptance" : try tos_acceptance.makeNode(in: context),
"transfer_schedule" : try transfer_schedule.makeNode(in: context),
"transfers_enabled" : .bool(transfers_enabled),
"verification" : try verification.makeNode(in: context),
"metadata" : metadata
] as [String : Node]).add(objects: [
"business_logo" : business_logo,
"business_name" : business_name,
"business_url" : business_url,
"product_description" : product_description,
"statement_descriptor" : statement_descriptor,
"support_email" : support_email,
"support_phone" : support_phone,
"transfer_statement_descriptor" : transfer_statement_descriptor,
"display_name" : display_name,
"keys" : keys
])
}
public func filteredNeededFieldsWithCombinedDateOfBirth(filtering prefix: String = "tos_acceptance") -> [String] {
var fieldsNeeded = verification.fields_needed.filter { !$0.hasPrefix(prefix) }
if fieldsNeeded.contains(where: { $0.contains("dob") }) {
let keysToRemove = ["legal_entity.dob.day", "legal_entity.dob.month", "legal_entity.dob.year"]
fieldsNeeded = fieldsNeeded.filter { !keysToRemove.contains($0) }
fieldsNeeded.append("legal_entity.dob")
}
if let index = fieldsNeeded.index(of: "external_account") {
fieldsNeeded.remove(at: index)
let accountFields = ["external_account.routing_number", "external_account.account_number", "external_account.country", "external_account.currency"]
fieldsNeeded.append(contentsOf: accountFields)
}
return fieldsNeeded
}
public func descriptionsForNeededFields() throws -> Node {
var descriptions: [Node] = []
try filteredNeededFieldsWithCombinedDateOfBirth().forEach {
descriptions.append(contentsOf: try description(for: $0))
}
return .array(descriptions)
}
private func description(for field: String) throws -> [Node] {
switch field {
case let field where field.hasPrefix("external_account"):
return [.object(ExternalAccount.descriptionsForNeededFields(in: country, for: field))]
case let field where field.hasPrefix("legal_entity"):
return [.object(LegalEntity.descriptionForNeededFields(in: country, for: field))]
case "tos_acceptance.date": fallthrough
case "tos_acceptance.ip": fallthrough
default:
return [.string(field)]
}
}
var requiresIdentityVerification: Bool {
let triggers = ["legal_entity.verification.document",
"legal_entity.additional_owners.0.verification.document",
"legal_entity.additional_owners.1.verification.document",
"legal_entity.additional_owners.2.verification.document",
"legal_entity.additional_owners.3.verification.document"]
return triggers.map { verification.fields_needed.contains($0) }.reduce(false) { $0 || $1 }
}
}
|
mit
|
06d6df80361549c4f260a004cd20900a
| 35.564784 | 159 | 0.619208 | 4.309319 | false | false | false | false |
daniel-barros/Comedores-UGR
|
Comedores UGR/DayMenu.swift
|
1
|
4230
|
//
// DayMenu.swift
// Comedores UGR
//
// Created by Daniel Barros López on 3/25/16.
/*
MIT License
Copyright (c) 2016 Daniel Barros
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
struct DayMenu: Equatable {
let date: String
let dishes: [String]
let processedDate: Date?
let allergens: String? // TODO: Do allergens for individual dishes
init(date: String, dishes: [String], allergens: String?) {
let fixedDate = date.lowercased().capitalized
self.date = fixedDate
self.dishes = dishes
self.processedDate = DayMenu.date(fromRawString: fixedDate)
self.allergens = allergens
}
var month: String? {
return date.components(separatedBy: " ").fourth
}
var dayNumber: String? {
return date.components(separatedBy: " ").second
}
var dayName: String? {
if let day = date.components(separatedBy: " ").first {
return day.substring(to: day.characters.index(before: day.endIndex))
}
return nil
}
var allDishes: String {
return DayMenu.dishesString(from: dishes)
}
var isTodayMenu: Bool {
if let date = processedDate, Calendar.current.isDateInToday(date) {
return true
} else {
return false
}
}
/// `true` if dishes text contains a message like "CERRADO".
var isClosedMenu: Bool {
return dishes.count == 1 && dishes.first == "CERRADO"
}
}
// MARK: Helpers
extension DayMenu {
static func dishesString(from dishesArray: [String]) -> String {
let string = dishesArray.reduce("", { (total: String, dish: String) -> String in
total + dish + "\n"
})
if string.characters.count > 1 {
return string.substring(to: string.characters.index(string.endIndex, offsetBy: -1))
}
return string
}
/// Date from a string like "LUNES, 9 DE ENERO DE 2017".
static func date(fromRawString dateString: String) -> Date? {
let capitalizedDate = dateString.lowercased().capitalized
let components = capitalizedDate.components(separatedBy: " ")
guard components.count == 6 else {
return nil
}
if let month = monthsDict[components[3]],
let day = Int(components[1]) {
let calendar = Calendar.current
let year = calendar.component(.year, from: Date())
return calendar.date(from: DateComponents(year: year, month: month, day: day))
}
return nil
}
}
func ==(lhs: DayMenu, rhs: DayMenu) -> Bool {
return lhs.date == rhs.date && lhs.dishes == rhs.dishes
}
// MARK: DayMenu collections
extension Collection where Iterator.Element == DayMenu {
var todayMenu: DayMenu? {
for menu in self {
if menu.isTodayMenu {
return menu
}
}
return nil
}
}
private let monthsDict = ["Enero": 1, "Febrero": 2, "Marzo": 3, "Abril": 4, "Mayo": 5, "Junio": 6,
"Julio": 7, "Agosto": 8, "Septiembre": 9, "Octubre": 10, "Noviembre": 11, "Diciembre": 12]
|
mit
|
c47796f019f0e3fee2888cbbfa978fdb
| 27.768707 | 98 | 0.631118 | 4.170611 | false | false | false | false |
lhwsygdtc900723/firefox-ios
|
UITests/HistoryTests.swift
|
3
|
4432
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
class HistoryTests: KIFTestCase {
private var webRoot: String!
override func setUp() {
webRoot = SimplePageServer.start()
}
func addHistoryItemPage(pageNo: Int) -> String {
// Load a page
tester().tapViewWithAccessibilityIdentifier("url")
let url = "\(webRoot)/numberedPage.html?page=\(pageNo)"
tester().clearTextFromAndThenEnterTextIntoCurrentFirstResponder("\(url)\n")
tester().waitForWebViewElementWithAccessibilityLabel("Page \(pageNo)")
return "Page \(pageNo), \(url)"
}
func addHistoryItems(noOfItemsToAdd: Int) -> [String] {
var urls = [String]()
for index in 1...noOfItemsToAdd {
urls.append(addHistoryItemPage(index))
}
return urls
}
/**
* Tests for listed history visits
*/
func testAddHistoryUI() {
let urls = addHistoryItems(2)
// Check that both appear in the history home panel
tester().tapViewWithAccessibilityIdentifier("url")
tester().tapViewWithAccessibilityLabel("History")
let firstHistoryRow = tester().waitForCellAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), inTableViewWithAccessibilityIdentifier: "History List")
XCTAssertNotNil(firstHistoryRow.imageView?.image)
XCTAssertEqual(firstHistoryRow.textLabel!.text!, "Page 2")
XCTAssertEqual(firstHistoryRow.detailTextLabel!.text!, "\(webRoot)/numberedPage.html?page=2")
let secondHistoryRow = tester().waitForCellAtIndexPath(NSIndexPath(forRow: 1, inSection: 0), inTableViewWithAccessibilityIdentifier: "History List")
XCTAssertNotNil(secondHistoryRow.imageView?.image)
XCTAssertEqual(secondHistoryRow.textLabel!.text!, "Page 1")
XCTAssertEqual(secondHistoryRow.detailTextLabel!.text!, "\(webRoot)/numberedPage.html?page=1")
tester().tapViewWithAccessibilityLabel("Cancel")
}
func testDeleteHistoryItemFromListWith2Items() {
// add 2 history items
// delete all history items
let urls = addHistoryItems(2)
// Check that both appear in the history home panel
tester().tapViewWithAccessibilityIdentifier("url")
tester().tapViewWithAccessibilityLabel("History")
tester().swipeViewWithAccessibilityLabel(urls[0], inDirection: KIFSwipeDirection.Left)
tester().tapViewWithAccessibilityLabel("Remove")
let secondHistoryRow = tester().waitForCellAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), inTableViewWithAccessibilityIdentifier: "History List")
XCTAssertNotNil(secondHistoryRow.imageView?.image)
if let keyWindow = UIApplication.sharedApplication().keyWindow {
XCTAssertNil(keyWindow.accessibilityElementWithLabel(urls[0]), "page 1 should have been deleted")
}
tester().tapViewWithAccessibilityLabel("Cancel")
}
func testDeleteHistoryItemFromListWithMoreThan100Items() {
if tester().tryFindingTappableViewWithAccessibilityLabel("Top sites", error: nil) {
tester().tapViewWithAccessibilityLabel("Top sites")
}
for pageNo in 1...102 {
BrowserUtils.addHistoryEntry("Page \(pageNo)", url: NSURL(string: "\(webRoot)/numberedPage.html?page=\(pageNo)")!)
}
let urlToDelete = "Page \(102), \(webRoot)/numberedPage.html?page=\(102)"
let secondToLastUrl = "Page \(101), \(webRoot)/numberedPage.html?page=\(101)"
tester().tapViewWithAccessibilityLabel("History")
tester().swipeViewWithAccessibilityLabel(urlToDelete, inDirection: KIFSwipeDirection.Left)
tester().tapViewWithAccessibilityLabel("Remove")
let secondHistoryRow = tester().waitForCellAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), inTableViewWithAccessibilityIdentifier: "History List")
XCTAssertNotNil(secondHistoryRow.imageView?.image)
if let keyWindow = UIApplication.sharedApplication().keyWindow {
XCTAssertNil(keyWindow.accessibilityElementWithLabel(urlToDelete), "page 102 should have been deleted")
}
}
override func tearDown() {
BrowserUtils.clearHistoryItems(tester(), numberOfTests: 2)
}
}
|
mpl-2.0
|
8e040cc850446a018005306dca465664
| 40.811321 | 156 | 0.695171 | 5.326923 | false | true | false | false |
jcfausto/transit-app
|
TransitApp/TransitApp/NSDate+Extension.swift
|
1
|
1269
|
//
// NSDate+Extension.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 24/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Foundation
//Add a custom initialization method to NSDate to support initialization from a datetime string RFC 3339 compliant
//Example of string: "2015-04-17T13:38:00+02:00"
extension NSDate {
convenience init(datetimeString:String) {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let nDate = formatter.dateFromString(datetimeString)!
self.init(timeInterval:0, sinceDate:nDate)
}
/**
This representation returns the time portion of the date only
whith the hour and minute (HH:MM)
*/
var stringValueWithHourAndMinute: String {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:MM"
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: self)
let hour = comp.hour
let minute = comp.minute
return "\(hour):\(minute)"
}
}
|
mit
|
6e3bfc8deb65caba7f4726bc38acb7ec
| 31.512821 | 114 | 0.669558 | 4.283784 | false | false | false | false |
auth0/Lock.iOS-OSX
|
Lock/AuthStyle.swift
|
1
|
21611
|
// AuthStyle.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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
/// Style for AuthButton
public struct AuthStyle {
/// Name that will be used for titles. e.g. 'Login with Auth0'
let name: String
let image: LazyImage
let foregroundColor: UIColor
let normalColor: UIColor
let highlightedColor: UIColor
let borderColor: UIColor?
var localizedLoginTitle: String {
let format = "Sign in with %1$@".i18n(key: "com.auth0.lock.strategy.login.title", comment: "Sign in with %@{strategy}")
return String(format: format, self.name)
}
var localizedSignUpTitle: String {
let format = "Sign up with %1$@".i18n(key: "com.auth0.lock.strategy.signup.title", comment: "Sign up with %@{strategy}")
return String(format: format, self.name)
}
/**
Create a new AuthStyle using a brand color
- parameter name: name to be used as the name of the Auth provider for the titles
- parameter color: brand color that will be used for the button. Default is Auth0 color
- parameter foregroundColor: text color of the button. Default is white
- parameter image: icon used in the button. By default is Auth0's
- returns: a new style
*/
public init(name: String, color: UIColor = UIColor.a0_orange, foregroundColor: UIColor = .white, withImage image: LazyImage = LazyImage(name: "ic_auth_auth0", bundle: bundleForLock())) {
self.init(name: name, normalColor: color, highlightedColor: color.a0_darker(0.3), foregroundColor: foregroundColor, withImage: image)
}
/**
Create a new AuthStyle specifying all colors instead of a brand color
- parameter name: name to be used as the name of the Auth provider for the titles
- parameter normalColor: color used as the normal state color
- parameter highlightedColor: color used as the highlighted state color
- parameter foregroundColor: text color of the button
- parameter image: icon used in the button
- returns: a new style
*/
public init(name: String, normalColor: UIColor, highlightedColor: UIColor, foregroundColor: UIColor, withImage image: LazyImage) {
self.name = name
self.normalColor = normalColor
self.highlightedColor = highlightedColor
self.foregroundColor = foregroundColor
self.borderColor = nil
self.image = image
}
// TODO: In the next major, integrate border color in the other initializers and remove this one
/**
Create a new AuthStyle using a brand color and a border color
- parameter name: name to be used as the name of the Auth provider for the titles
- parameter color: brand color that will be used for the button. Default is Auth0 color
- parameter foregroundColor: text color of the button. Default is white
- parameter borderColor: fill color of the border. Default is Auth0 color
- parameter image: icon used in the button. By default is Auth0's
- returns: a new style
*/
public init(name: String,
color: UIColor = UIColor.a0_orange,
foregroundColor: UIColor = .white,
borderColor: UIColor = UIColor.a0_orange, // This should be optional in the next major, defaulting to nil
withImage image: LazyImage = LazyImage(name: "ic_auth_auth0", bundle: bundleForLock())) {
self.name = name
self.normalColor = color
self.foregroundColor = foregroundColor
self.highlightedColor = color.a0_darker(0.3)
self.borderColor = borderColor
self.image = image
}
static func custom(_ name: String) -> AuthStyle {
return AuthStyle(name: name)
}
}
// MARK: - First class social connection styles
public extension AuthStyle {
/// Amazon style for AuthButton
static var Amazon: AuthStyle {
return AuthStyle(
name: "Amazon".i18n(key: "com.auth0.lock.strategy.localized.amazon", comment: "Amazon"),
color: .a0_fromRGB("#ff9900"),
withImage: LazyImage(name: "ic_auth_amazon", bundle: bundleForLock())
)
}
/// Aol style for AuthButton
static var Aol: AuthStyle {
return AuthStyle(
name: "AOL".i18n(key: "com.auth0.lock.strategy.localized.aol", comment: "AOL"),
color: .a0_fromRGB("#ff0b00"),
withImage: LazyImage(name: "ic_auth_aol", bundle: bundleForLock())
)
}
/// Apple style for AuthButton
static var Apple: AuthStyle {
let normalColor = UIColor.a0_fromRGB("#000000")
return AuthStyle(
name: "Apple".i18n(key: "com.auth0.lock.strategy.localized.apple", comment: "Apple"),
normalColor: normalColor,
highlightedColor: normalColor.a0_lighter(0.3),
foregroundColor: .white,
withImage: LazyImage(name: "ic_auth_apple", bundle: bundleForLock())
)
}
/// Baidu style for AuthButton
static var Baidu: AuthStyle {
return AuthStyle(
name: "百度".i18n(key: "com.auth0.lock.strategy.localized.baidu", comment: "Baidu"),
color: .a0_fromRGB("#2529d8"),
withImage: LazyImage(name: "ic_auth_baidu", bundle: bundleForLock())
)
}
/// Bitbucket style for AuthButton
static var Bitbucket: AuthStyle {
return AuthStyle(
name: "Bitbucket".i18n(key: "com.auth0.lock.strategy.localized.bitbucket", comment: "Bitbucket"),
color: .a0_fromRGB("#205081"),
withImage: LazyImage(name: "ic_auth_bitbucket", bundle: bundleForLock())
)
}
/// Dropbox style for AuthButton
static var Dropbox: AuthStyle {
return AuthStyle(
name: "Dropbox".i18n(key: "com.auth0.lock.strategy.localized.dropbox", comment: "Dropbox"),
color: .a0_fromRGB("#0064d2"),
withImage: LazyImage(name: "ic_auth_dropbox", bundle: bundleForLock())
)
}
/// Dwolla style for AuthButton
static var Dwolla: AuthStyle {
return AuthStyle(
name: "Dwolla".i18n(key: "com.auth0.lock.strategy.localized.dwolla", comment: "Dwolla"),
color: .a0_fromRGB("#F5891F"),
withImage: LazyImage(name: "ic_auth_dwolla", bundle: bundleForLock())
)
}
/// Ebay style for AuthButton
static var Ebay: AuthStyle {
return AuthStyle(
name: "Ebay".i18n(key: "com.auth0.lock.strategy.localized.ebay", comment: "Ebay"),
color: .a0_fromRGB("#007ee5"),
withImage: LazyImage(name: "ic_auth_ebay", bundle: bundleForLock())
)
}
/// Evernote style for AuthButton
static var Evernote: AuthStyle {
return AuthStyle(
name: "Evernote".i18n(key: "com.auth0.lock.strategy.localized.evernote", comment: "Evernote"),
color: .a0_fromRGB("#2dbe60"),
withImage: LazyImage(name: "ic_auth_evernote", bundle: bundleForLock())
)
}
/// Evernote Sandbox style for AuthButton
static var EvernoteSandbox: AuthStyle {
return AuthStyle(
name: "Evernote (sandbox)".i18n(key: "com.auth0.lock.strategy.localized.evernote_sandbox", comment: "EvernoteSandbox"),
color: .a0_fromRGB("#2dbe60"),
withImage: LazyImage(name: "ic_auth_evernote", bundle: bundleForLock())
)
}
/// Exact style for AuthButton
static var Exact: AuthStyle {
return AuthStyle(
name: "Exact".i18n(key: "com.auth0.lock.strategy.localized.exact", comment: "Exact"),
color: .a0_fromRGB("#ED1C24"),
withImage: LazyImage(name: "ic_auth_exact", bundle: bundleForLock())
)
}
/// Facebook style for AuthButton
static var Facebook: AuthStyle {
return AuthStyle(
name: "Facebook".i18n(key: "com.auth0.lock.strategy.localized.facebook", comment: "Facebook"),
color: .a0_fromRGB("#3b5998"),
withImage: LazyImage(name: "ic_auth_facebook", bundle: bundleForLock())
)
}
/// Fitbit style for AuthButton
static var Fitbit: AuthStyle {
return AuthStyle(
name: "Fitbit".i18n(key: "com.auth0.lock.strategy.localized.fitbit", comment: "Fitbit"),
color: .a0_fromRGB("#4cc2c4"),
withImage: LazyImage(name: "ic_auth_fitbit", bundle: bundleForLock())
)
}
/// Github style for AuthButton
static var Github: AuthStyle {
return AuthStyle(
name: "GitHub".i18n(key: "com.auth0.lock.strategy.localized.github", comment: "GitHub"),
color: .a0_fromRGB("#333333"),
withImage: LazyImage(name: "ic_auth_github", bundle: bundleForLock())
)
}
/// Google style for AuthButton
static var Google: AuthStyle {
return AuthStyle(
name: "Google".i18n(key: "com.auth0.lock.strategy.localized.google", comment: "Google"),
color: .a0_fromRGB("#ffffff"),
foregroundColor: .a0_fromRGB("#333333"),
borderColor: .a0_fromRGB("#dee0e2"),
withImage: LazyImage(name: "ic_auth_google", bundle: bundleForLock())
)
}
/// Instagram style for AuthButton
static var Instagram: AuthStyle {
return AuthStyle(
name: "Instagram".i18n(key: "com.auth0.lock.strategy.localized.instagram", comment: "Instagram"),
color: .a0_fromRGB("#3f729b"),
withImage: LazyImage(name: "ic_auth_instagram", bundle: bundleForLock())
)
}
/// Linkedin style for AuthButton
static var Linkedin: AuthStyle {
return AuthStyle(
name: "LinkedIn".i18n(key: "com.auth0.lock.strategy.localized.linkedin", comment: "LinkedIn"),
color: .a0_fromRGB("#0077b5"),
withImage: LazyImage(name: "ic_auth_linkedin", bundle: bundleForLock())
)
}
/// Miicard style for AuthButton
static var Miicard: AuthStyle {
return AuthStyle(
name: "miiCard".i18n(key: "com.auth0.lock.strategy.localized.miicard", comment: "miiCard"),
color: .a0_fromRGB("#35A6FE"),
withImage: LazyImage(name: "ic_auth_miicard", bundle: bundleForLock())
)
}
/// Paypal style for AuthButton
static var Paypal: AuthStyle {
return AuthStyle(
name: "PayPal".i18n(key: "com.auth0.lock.strategy.localized.paypal", comment: "PayPal"),
color: .a0_fromRGB("#009cde"),
withImage: LazyImage(name: "ic_auth_paypal", bundle: bundleForLock())
)
}
/// Paypal style for AuthButton
static var PaypalSandbox: AuthStyle {
return AuthStyle(
name: "PayPal (sandbox)".i18n(key: "com.auth0.lock.strategy.localized.paypal_sandbox", comment: "PaypalSandbox"),
color: .a0_fromRGB("#009cde"),
withImage: LazyImage(name: "ic_auth_paypal", bundle: bundleForLock())
)
}
/// Planning Center style for AuthButton
static var PlanningCenter: AuthStyle {
return AuthStyle(
name: "Planning Center".i18n(key: "com.auth0.lock.strategy.localized.planning_center", comment: "PlanningCenter"),
color: .a0_fromRGB("#4e4e4e"),
withImage: LazyImage(name: "ic_auth_planningcenter", bundle: bundleForLock())
)
}
/// RenRen style for AuthButton
static var RenRen: AuthStyle {
return AuthStyle(
name: "人人".i18n(key: "com.auth0.lock.strategy.localized.renren", comment: "RenRen"),
color: .a0_fromRGB("#0056B5"),
withImage: LazyImage(name: "ic_auth_renren", bundle: bundleForLock())
)
}
/// Salesforce style for AuthButton
static var Salesforce: AuthStyle {
return AuthStyle(
name: "Salesforce".i18n(key: "com.auth0.lock.strategy.localized.salesforce", comment: "Salesforce"),
color: .a0_fromRGB("#1798c1"),
withImage: LazyImage(name: "ic_auth_salesforce", bundle: bundleForLock())
)
}
/// Salesforce Community style for AuthButton
static var SalesforceCommunity: AuthStyle {
return AuthStyle(
name: "Salesforce Community".i18n(key: "com.auth0.lock.strategy.localized.salesforce_community", comment: "SalesforceCommunity"),
color: .a0_fromRGB("#1798c1"),
withImage: LazyImage(name: "ic_auth_salesforce", bundle: bundleForLock())
)
}
/// Salesforce Sandbox style for AuthButton
static var SalesforceSandbox: AuthStyle {
return AuthStyle(
name: "Salesforce (sandbox)".i18n(key: "com.auth0.lock.strategy.localized.salesforce_sandbox", comment: "SalesforceSandbox"),
color: .a0_fromRGB("#1798c1"),
withImage: LazyImage(name: "ic_auth_salesforce", bundle: bundleForLock())
)
}
/// Shopify style for AuthButton
static var Shopify: AuthStyle {
return AuthStyle(
name: "Shopify".i18n(key: "com.auth0.lock.strategy.localized.shopify", comment: "Shopify"),
color: .a0_fromRGB("#96bf48"),
withImage: LazyImage(name: "ic_auth_shopify", bundle: bundleForLock())
)
}
/// Soundcloud style for AuthButton
static var Soundcloud: AuthStyle {
return AuthStyle(
name: "SoundCloud".i18n(key: "com.auth0.lock.strategy.localized.soundcloud", comment: "SoundCloud"),
color: .a0_fromRGB("#ff8800"),
withImage: LazyImage(name: "ic_auth_soundcloud", bundle: bundleForLock())
)
}
/// The City style for AuthButton
static var TheCity: AuthStyle {
return AuthStyle(
name: "The City".i18n(key: "com.auth0.lock.strategy.localized.the_city", comment: "TheCity"),
color: .a0_fromRGB("#767571"),
withImage: LazyImage(name: "ic_auth_thecity", bundle: bundleForLock())
)
}
/// The City Sandbox style for AuthButton
static var TheCitySandbox: AuthStyle {
return AuthStyle(
name: "The City (sandbox)".i18n(key: "com.auth0.lock.strategy.localized.the_city_sandbox", comment: "TheCitySandbox"),
color: .a0_fromRGB("#767571"),
withImage: LazyImage(name: "ic_auth_thecity", bundle: bundleForLock())
)
}
/// 37 Signals style for AuthButton
static var ThirtySevenSignals: AuthStyle {
return AuthStyle(
name: "Basecamp".i18n(key: "com.auth0.lock.strategy.localized.thirty_seven_signals", comment: "Basecamp"),
color: .a0_fromRGB("#6AC071"),
withImage: LazyImage(name: "ic_auth_thirtysevensignals", bundle: bundleForLock())
)
}
/// Twitter style for AuthButton
static var Twitter: AuthStyle {
return AuthStyle(
name: "Twitter".i18n(key: "com.auth0.lock.strategy.localized.twitter", comment: "Twitter"),
color: .a0_fromRGB("#55acee"),
withImage: LazyImage(name: "ic_auth_twitter", bundle: bundleForLock())
)
}
/// Vkontakte style for AuthButton
static var Vkontakte: AuthStyle {
return AuthStyle(
name: "VKontakte".i18n(key: "com.auth0.lock.strategy.localized.vkontakte", comment: "VKontakte"),
color: .a0_fromRGB("#45668e"),
withImage: LazyImage(name: "ic_auth_vk", bundle: bundleForLock())
)
}
/// Microsoft style for AuthButton
static var Microsoft: AuthStyle {
return AuthStyle(
name: "Microsoft Account".i18n(key: "com.auth0.lock.strategy.localized.microsoft", comment: "Microsoft"),
color: .a0_fromRGB("#00a1f1"),
withImage: LazyImage(name: "ic_auth_microsoft", bundle: bundleForLock())
)
}
/// Wordpress style for AuthButton
static var Wordpress: AuthStyle {
return AuthStyle(
name: "WordPress".i18n(key: "com.auth0.lock.strategy.localized.wordpress", comment: "WordPress"),
color: .a0_fromRGB("#21759b"),
withImage: LazyImage(name: "ic_auth_wordpress", bundle: bundleForLock())
)
}
/// Yahoo style for AuthButton
static var Yahoo: AuthStyle {
return AuthStyle(
name: "Yahoo!".i18n(key: "com.auth0.lock.strategy.localized.yahoo", comment: "Yahoo"),
color: .a0_fromRGB("#410093"),
withImage: LazyImage(name: "ic_auth_yahoo", bundle: bundleForLock())
)
}
/// Yammer style for AuthButton
static var Yammer: AuthStyle {
return AuthStyle(
name: "Yammer".i18n(key: "com.auth0.lock.strategy.localized.yammer", comment: "Yammer"),
color: .a0_fromRGB("#0072c6"),
withImage: LazyImage(name: "ic_auth_yammer", bundle: bundleForLock())
)
}
/// Yandex style for AuthButton
static var Yandex: AuthStyle {
return AuthStyle(
name: "Yandex".i18n(key: "com.auth0.lock.strategy.localized.yandex", comment: "Yandex"),
color: .a0_fromRGB("#ffcc00"),
withImage: LazyImage(name: "ic_auth_yandex", bundle: bundleForLock())
)
}
/// Weibo style for AuthButton
static var Weibo: AuthStyle {
return AuthStyle(
name: "新浪微博".i18n(key: "com.auth0.lock.strategy.localized.weibo", comment: "Weibo"),
color: .a0_fromRGB("#DD4B39"),
withImage: LazyImage(name: "ic_auth_weibo", bundle: bundleForLock())
)
}
}
// MARK: - AuthStyle from Strategy & Connection
extension AuthStyle {
static func style(forStrategy strategy: String, connectionName: String) -> AuthStyle {
switch strategy.lowercased() {
case "ad", "adfs":
return .Microsoft
case "amazon":
return .Amazon
case "aol":
return .Aol
case "apple":
return .Apple
case "baidu":
return .Baidu
case "bitbucket":
return .Bitbucket
case "dropbox":
return .Dropbox
case "dwolla":
return .Dwolla
case "ebay":
return .Ebay
case "evernote":
return .Evernote
case "evernote-sandbox":
return .EvernoteSandbox
case "exact":
return .Exact
case "facebook":
return .Facebook
case "fitbit":
return .Fitbit
case "github":
return .Github
case "google-oauth2":
return .Google
case "instagram":
return .Instagram
case "linkedin":
return .Linkedin
case "miicard":
return .Miicard
case "paypal":
return .Paypal
case "paypal-sandbox":
return .PaypalSandbox
case "planningcenter":
return .PlanningCenter
case "renren":
return .RenRen
case "salesforce":
return .Salesforce
case "salesforce-community":
return .SalesforceCommunity
case "salesforce-sandbox":
return .SalesforceSandbox
case "shopify":
return .Shopify
case "soundcloud":
return .Soundcloud
case "thecity":
return .TheCity
case "thecity-sandbox":
return .TheCitySandbox
case "thirtysevensignals":
return .ThirtySevenSignals
case "twitter":
return .Twitter
case "vkontakte":
return .Vkontakte
case "windowslive":
return .Microsoft
case "wordpress":
return .Wordpress
case "yahoo":
return .Yahoo
case "yammer":
return .Yammer
case "yandex":
return .Yandex
case "waad":
return .Google
case "weibo":
return .Weibo
default:
return AuthStyle(name: connectionName)
}
}
}
|
mit
|
9ea884ae8447e5306625db85a5d8041d
| 38.050633 | 190 | 0.598426 | 4.264415 | false | false | false | false |
levieggert/Seek
|
Source/Seek.swift
|
1
|
2777
|
//
// Created by Levi Eggert.
// Copyright © 2020 Levi Eggert. All rights reserved.
//
import UIKit
public class Seek {
public private(set) weak var view: UIView?
public private(set) weak var constraintLayoutView: UIView?
public private(set) weak var constraint: NSLayoutConstraint?
public private(set) var seekProperties: [SeekPropertyType]
public let seekPosition: SeekPosition = SeekPosition()
public init(view: UIView, seekProperties: [SeekPropertyType]) {
self.view = view
self.seekProperties = seekProperties
}
public init(view: UIView, constraint: NSLayoutConstraint, constraintLayoutView: UIView, seekProperties: [SeekPropertyType]) {
self.view = view
self.constraint = constraint
self.constraintLayoutView = constraintLayoutView
self.seekProperties = seekProperties
}
public func setSeekProperties(seekProperties: [SeekPropertyType]) {
self.seekProperties = seekProperties
self.position = seekPosition.value
}
public func animateTo(position: CGFloat, duration: TimeInterval, delay: TimeInterval, animationOptions: UIView.AnimationOptions, complete:((_ finished: Bool) -> Void)?) {
if duration > 0 || delay > 0 {
UIView.animate(withDuration: duration, delay: delay, options: animationOptions, animations: {
self.position = position
}) { (finished: Bool) in
complete?(finished)
}
}
else {
self.position = position
complete?(true)
}
}
public func forceStop() {
view?.layer.removeAllAnimations()
position = 0
}
public func forceComplete(complete:((_ finished: Bool) -> Void)? = nil) {
position = 1
complete?(true)
}
public var position: CGFloat = 0 {
didSet {
seekPosition.value = position
for property in seekProperties {
switch property {
case .alpha(let seekFloat):
view?.alpha = seekFloat.valueForPosition(position: seekPosition.value)
case .constraints(let seekFloat):
constraint?.constant = seekFloat.valueForPosition(position: seekPosition.value)
case .transform(let seekTransform):
view?.transform = seekTransform.valueForPosition(position: seekPosition.value)
}
}
constraintLayoutView?.layoutIfNeeded()
}
}
}
|
mit
|
139cf9982503a41e9b9542d1eb25f840
| 29.844444 | 174 | 0.569524 | 5.540918 | false | false | false | false |
XWebView/XWebView
|
XWebViewTests/ConstructorPlugin.swift
|
1
|
3164
|
/*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import XCTest
import XWebView
class ConstructorPlugin : XWVTestCase {
class Plugin0 : NSObject, XWVScripting {
@objc init(expectation: Any?) {
if let e = expectation as? XWVScriptObject {
e.callMethod("fulfill", with: nil, completionHandler: nil)
}
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin0.init(expectation:)) ? "" : nil
}
}
class Plugin1 : NSObject, XWVScripting {
@objc dynamic var property: Int
@objc init(value: Int) {
property = value
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin1.init(value:)) ? "" : nil
}
}
class Plugin2 : NSObject, XWVScripting {
private let expectation: XWVScriptObject?
@objc init(expectation: Any?) {
self.expectation = expectation as? XWVScriptObject
}
func finalizeForScript() {
expectation?.callMethod("fulfill", with: nil, completionHandler: nil)
}
class func scriptName(for selector: Selector) -> String? {
return selector == #selector(Plugin2.init(expectation:)) ? "" : nil
}
}
let namespace = "xwvtest"
func testConstructor() {
let desc = "constructor"
let script = "if (\(namespace) instanceof Function) fulfill('\(desc)')"
_ = expectation(description: desc)
loadPlugin(Plugin0(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
func testConstruction() {
let desc = "construction"
let script = "new \(namespace)(expectation('\(desc)'))"
_ = expectation(description: desc)
loadPlugin(Plugin0(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
func testSyncProperties() {
let desc = "syncProperties"
let script = "(new \(namespace)(456)).then(function(o){if (o.property==456) fulfill('\(desc)');})"
_ = expectation(description: desc)
loadPlugin(Plugin1(value: 123), namespace: namespace, script: script)
waitForExpectations()
}
func testFinalizeForScript() {
let desc = "finalizeForScript"
let script = "(new \(namespace)(expectation('\(desc)'))).then(function(o){o.dispose();})"
_ = expectation(description: desc)
loadPlugin(Plugin2(expectation: nil), namespace: namespace, script: script)
waitForExpectations()
}
}
|
apache-2.0
|
412e69836ab1efa4f62294365441ac6b
| 36.666667 | 106 | 0.637168 | 4.666667 | false | true | false | false |
tkremenek/swift
|
benchmark/single-source/PointerArithmetics.swift
|
22
|
1056
|
//===--- PointerArithmetics.swift -----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
public let PointerArithmetics = [
BenchmarkInfo(name: "PointerArithmetics",
runFunction: run_PointerArithmetics,
tags: [.validation, .api],
legacyFactor: 100),
]
@inline(never)
public func run_PointerArithmetics(_ N: Int) {
var numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
var c = 0
withUnsafePointer(to: &numbers) {
$0.withMemoryRebound(to: Int.self, capacity: 10) { ptr in
for _ in 1...N*100_000 {
c += (ptr + getInt(10) - getInt(5)).pointee
}
}
}
CheckResults(c != 0)
}
|
apache-2.0
|
9920921dde26b13a676c200cbfd13c05
| 29.171429 | 80 | 0.589962 | 3.940299 | false | false | false | false |
srn214/Floral
|
Floral/Pods/WCDB.swift/swift/source/core/interface/Insert.swift
|
1
|
4467
|
/*
* Tencent is pleased to support the open source community by making
* WCDB available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company.
* All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of
* the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// Chain call for inserting
public final class Insert {
private let core: Core
private var properties: [PropertyConvertible]?
private let name: String
private let isReplace: Bool
init(with core: Core,
named name: String,
on propertyConvertibleList: [PropertyConvertible]?,
isReplace: Bool = false) throws {
guard name.count > 0 else {
throw Error.reportInterface(tag: core.tag,
path: core.path,
operation: .insert,
code: .misuse,
message: "Empty table name")
}
self.name = name
self.properties = propertyConvertibleList
self.isReplace = isReplace
self.core = core
}
private var conflict: Conflict? {
return isReplace ? Conflict.replace : nil
}
private lazy var statement: StatementInsert = StatementInsert()
.insert(intoTable: name,
with: properties!,
onConflict: self.conflict)
.values(Array(repeating: Expression.bindParameter, count: properties!.count))
/// Execute the insert chain call with objects.
///
/// Note that it will run embedded transaction while objects.count>1.
/// The embedded transaction means that it will run a transaction if it's not in other transaction,
/// otherwise it will be executed within the existing transaction.
///
/// - Parameter objects: Object to be inserted
/// - Throws: Error
public func execute<Object: TableEncodable>(with objects: Object...) throws {
try execute(with: objects)
}
/// Execute the insert chain call with objects.
///
/// Note that it will run embedded transaction while objects.count>1.
/// The embedded transaction means that it will run a transaction if it's not in other transaction,
/// otherwise it will be executed within the existing transaction.
///
/// - Parameter objects: Object to be inserted
/// - Throws: Error
public func execute<Object: TableEncodable>(with objects: [Object]) throws {
guard objects.count > 0 else {
Error.warning("Inserting with an empty/nil object")
return
}
let orm = Object.CodingKeys.objectRelationalMapping
func doInsertObject() throws {
properties = properties ?? Object.Properties.all
let recyclableHandleStatement: RecyclableHandleStatement = try core.prepare(statement)
let handleStatement = recyclableHandleStatement.raw
let encoder = TableEncoder(properties!.asCodingTableKeys(), on: recyclableHandleStatement)
if !isReplace {
encoder.primaryKeyHash = orm.getPrimaryKey()?.stringValue.hashValue
}
for var object in objects {
let isAutoIncrement = object.isAutoIncrement
encoder.isPrimaryKeyEncoded = !isAutoIncrement
try object.encode(to: encoder)
try handleStatement.step()
if !isReplace && isAutoIncrement {
object.lastInsertedRowID = handleStatement.lastInsertedRowID
}
try handleStatement.reset()
}
}
return objects.count == 1 ? try doInsertObject() : try core.run(embeddedTransaction: doInsertObject )
}
}
extension Insert: CoreRepresentable {
/// The tag of the related database.
public var tag: Tag? {
return core.tag
}
/// The path of the related database.
public var path: String {
return core.path
}
}
|
mit
|
b511e34d5ae2c9875c2af6b3a98e5f22
| 37.179487 | 109 | 0.630401 | 4.968854 | false | false | false | false |
ArtSabintsev/Freedom
|
FreedomExample/ViewController.swift
|
1
|
950
|
//
// ViewController.swift
// Freedom
//
// Created by Sabintsev, Arthur on 7/1/17.
// Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved.
//
import Freedom
import UIKit
class ViewController: UIViewController {
@IBAction func openURL(_ sender: UIButton) {
// A Sample URL that just happens to be my personal website.
let url = URL(string: "http://www.sabintsev.com")!
// Enable Debug Logs (disabled by default)
Freedom.debugEnabled = true
// Fetch activities for Safari and all third-party browsers supported by Freedom.
let activities = Freedom.browsers()
// Alternatively, one could select a specific browser (or browsers).
// let activities = Freedom.browsers([.chrome])
let viewController = UIActivityViewController(activityItems: [url], applicationActivities: activities)
present(viewController, animated: true, completion: nil)
}
}
|
mit
|
737cef6e48e135016fcc7427bffe943e
| 27.757576 | 110 | 0.682824 | 4.69802 | false | false | false | false |
jindulys/Leetcode_Solutions_Swift
|
Sources/Stack/94_BinaryTreeInorderTraversal.swift
|
1
|
842
|
//
// 94_BinaryTreeInorderTraversal.swift
// LeetcodeSwift
//
// Created by yansong li on 2016-11-08.
// Copyright © 2016 YANSONG LI. All rights reserved.
//
import Foundation
/**
Title:94 Binary Tree Ignorer Traversal
URL: https://leetcode.com/problems/binary-tree-inorder-traversal/
Space: O(N)
Time: O(N)
*/
class BinaryTreeInorderTraversal_Solution {
func inorderTraversal(_ root: TreeNode?) -> [Int] {
var nodeStack: List<TreeNode> = .end
var currentNode = root
var result: [Int] = []
while currentNode != nil || !nodeStack.isEmpty() {
while let validNode = currentNode {
nodeStack.push(validNode)
currentNode = validNode.left
}
let leftMostNode = nodeStack.pop()
result.append(leftMostNode!.val)
currentNode = leftMostNode?.right
}
return result
}
}
|
mit
|
cde22cc72d3df2dc7c2bf5194703baa9
| 24.484848 | 66 | 0.668252 | 3.518828 | false | false | false | false |
TalkingBibles/Talking-Bible-iOS
|
TalkingBible/Utility.swift
|
1
|
3884
|
//
// Copyright 2015 Talking Bibles International
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import AVFoundation
import UIKit
import TMReachability
struct Utility {
static func deviceInformation() -> String {
let deviceModel = UIDevice.currentDevice().model as NSString
let osVersion = UIDevice.currentDevice().systemVersion as NSString
let bundleName = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleIdentifier") as! NSString
let bundleVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! NSString
let attachedDevices = Utility.attachedDevices().joinWithSeparator(", ")
let networkConnections = Utility.networkConnections().joinWithSeparator(",")
let country = NSLocale.currentLocale().localeIdentifier
let languages = (NSLocale.preferredLanguages() ).joinWithSeparator(",")
let defaultUser = DefaultUser.sharedManager
let bookmark = Bookmark(languageId: defaultUser.languageId, bookId: defaultUser.bookId, chapterId: defaultUser.chapterId)
return "\n\n-------------------\nDevice Information\n-------------------\nModel: \(deviceModel) (iOS \(osVersion))\nAttached Devices: \(attachedDevices)\nNetwork Connection: \(networkConnections)\nPreferred Languages: \(languages)\nCountry: \(country)\n\n-------------------\nApp Information\n-------------------\nBundle Name: \(bundleName)\nBundle Version: \(bundleVersion)\nBookmark: \(bookmark.description)"
}
static func attachedDevices() -> [String] {
var devices: [String] = []
let route = AVAudioSession.sharedInstance().currentRoute
for desc in route.outputs {
switch desc.portType {
case AVAudioSessionPortHeadphones:
devices.append("Headphones")
case AVAudioSessionPortAirPlay:
devices.append("AirPlay")
case AVAudioSessionPortCarAudio:
devices.append("Car Audio")
case AVAudioSessionPortUSBAudio:
devices.append("USB Audio")
case AVAudioSessionPortBluetoothHFP:
devices.append("Bluetooth Hands-free")
case AVAudioSessionPortBluetoothA2DP:
devices.append("Bluetooth A2DP")
case AVAudioSessionPortBluetoothLE:
devices.append("Bluetooth LE")
case AVAudioSessionPortHDMI:
devices.append("HDMI")
case AVAudioSessionPortLineOut:
devices.append("Line Out")
case AVAudioSessionPortBuiltInSpeaker:
devices.append("Built-in Speaker")
default:
break
}
}
if devices.count == 0 {
devices.append("None detected")
}
return devices
}
static func networkConnections() -> [String] {
var connections: [String] = []
let reach = TMReachability.reachabilityForInternetConnection()
if reach.isReachableViaWWAN() {
connections.append("WWAN")
}
if reach.isReachableViaWiFi() {
connections.append("WiFi")
}
if connections.count == 0 {
connections.append("None detected")
}
return connections
}
static func safelySetUserDefaultValue(value: AnyObject?, forKey key: String) {
if let value: AnyObject = value {
NSUserDefaults.standardUserDefaults().setValue(value, forKey: key)
} else {
NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}
}
}
|
apache-2.0
|
0d14e99f67126b7d82632697792a4421
| 35.308411 | 414 | 0.691813 | 4.941476 | false | false | false | false |
devandsev/theTVDB-iOS
|
tvShows/Source/Screens/Main/MainVC.swift
|
1
|
1754
|
//
// MainVC.swift
// perfectReads
//
// Created by Andrey Sevrikov on 10/07/2017.
// Copyright © 2017 devandsev. All rights reserved.
//
import UIKit
class MainVC: UIViewController, HasDependencies {
typealias Dependencies = HasConfigService & HasAPI & HasSessionService
var di: Dependencies!
@IBOutlet weak var button: UIButton!
// let authenticationAPI = AuthenticationAPI()
// let config = ConfigService.shared
// let sessionService = SessionService.shared
override func viewDidLoad() {
super.viewDidLoad()
self.di.sessionService.restore(success: {
let vc = SearchWF(with: self.navigationController!).module()
self.navigationController!.pushViewController(vc, animated: true)
// self.navigationController!.present(vc, animated: true) {}
// let week: TimeInterval = 7 * 24 * 60 * 60
// let weekAgo = Date().addingTimeInterval(-week)
//
// self.di.api.updates.updatedSince(date: weekAgo, success: { (s) in
//
// }, failure: { (e) in
//
// })
// self.di.api.series.actors(seriesId: 79636, success: { series in
// print(series)
// }, failure: { _ in
//
// })
}) { error in
print(error)
}
// self.seriesAPI.series(id: 79636, success: { series in
// print(series)
// }, failure: { _ in
//
// })
// self.searchAPI.search(name: "game", success: { series in
// print(series)
// }, failure: { error in
// })
}
}
|
mit
|
fce0086a2bb148aae9ee6963a5e3d123
| 26.390625 | 79 | 0.520251 | 4.183771 | false | false | false | false |
pooi/SubwayAlerter
|
SubwayAlerter/RecentViewController.swift
|
1
|
4735
|
import UIKit
class RecentViewController : UITableViewController {
var fvo = FavoriteVO()//사용자 함수를 위해
var list : Array<String> = []
override func viewDidLoad() {
for parent in self.navigationController!.navigationBar.subviews{
for childView in parent.subviews{
if(childView is UIImageView){
childView.removeFromSuperview()
}
}
}
//네비게이션바 색상변경
let navBarColor = navigationController!.navigationBar
navBarColor.barTintColor = UIColor(red: 230/255.0, green: 70.0/255.0, blue: 70.0/255.0, alpha: 0.0)
navBarColor.tintColor = UIColor.whiteColor()
navBarColor.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
//let list : Array<String> = self.fvo.config.objectForKey("RecentArray") as! Array<String>
self.list = self.fvo.config.objectForKey("RecentArray") as! Array<String>
let temp = list
self.list.removeAll()
for i in 0..<temp.count{
list.append(temp[temp.count-1-i])
}
}
override func viewDidAppear(animated: Bool) {
self.tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
// self.tabBarController?.tabBar.hidden = false
}
@IBAction func closeBtn(sender: AnyObject) {
self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
}
// 전체삭제 버튼
@IBAction func deleteBtn(sender: AnyObject) {
let alert = UIAlertController(title: "확인", message: "최근 경로를 전부 삭제하시겠습니까?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "취소", style: .Default, handler: nil))
alert.addAction(UIAlertAction(title: "확인", style: .Default, handler: { (action) -> Void in
//fvo.config.removeObjectForKey("RecentArray")
let list2 : Array<String> = []
self.fvo.config.setObject(list2, forKey: "RecentArray")
self.list = self.fvo.config.objectForKey("RecentArray") as! Array<String>
self.tableView.reloadData()
}))
self.presentViewController(alert, animated: true, completion: nil)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// 1
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//let list : Array<String> = self.fvo.config.objectForKey("RecentArray") as! Array<String>
return self.list.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
//let list : Array<String> = self.fvo.config.objectForKey("RecentArray") as! Array<String>
cell.textLabel?.text = convertTitle(Title: self.list[indexPath.row])
cell.textLabel?.setFontSize(settingFontSize(0))
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return settingFontSize(9)
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
//tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "moveToSet") {
let path = self.tableView.indexPathForCell(sender as! UITableViewCell)
//let list : Array<String> = self.fvo.config.objectForKey("favoriteArray") as! Array<String>
let (start,finish) = removeComma(Name: self.list[path!.row])
// let bottomBar = segue.destinationViewController as! SetStartTMViewController
// bottomBar.hidesBottomBarWhenPushed = true
(segue.destinationViewController as? SetStartTMViewController)?.start = start
(segue.destinationViewController as? SetStartTMViewController)?.finish = finish
}
}
}
|
bsd-3-clause
|
6da9a92f99a2eccc628460f676899764
| 31.48951 | 118 | 0.596986 | 4.978564 | false | true | false | false |
soxjke/Redux-ReactiveSwift
|
Example/Simple-Weather-App/Simple-Weather-App/Models/Weather.swift
|
1
|
3355
|
//
// Weather.swift
// Simple-Weather-App
//
// Created by Petro Korienev on 10/26/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import Foundation
import ObjectMapper
enum WeatherValue<Value> {
case single(value: Value)
case minmax(min: Value, max: Value)
}
struct WeatherFeature<T> {
let unit: String
let value: WeatherValue<T>
}
struct DayNightWeather {
let windSpeed: WeatherFeature<Double>
let windDirection: String
let precipitationProbability: Int
let phrase: String
let icon: Int
}
// Since Swift 3.1 there's a neat feature called "Type nesting with generics" is
// around, however implementation is buggy and leads to runtime error
// https://bugs.swift.org/browse/SR-4383
// As a workaround, WeatherValue, WeatherFeature, DayNightWeather are standalone types
struct Weather {
let effectiveDate: Date
let temperature: WeatherFeature<Double>
let realFeel: WeatherFeature<Double>
let day: DayNightWeather
let night: DayNightWeather
}
extension Weather: ImmutableMappable {
init(map: Map) throws {
effectiveDate = try map.value("EpochDate", using: DateTransform())
temperature = try map.value("Temperature")
realFeel = try map.value("RealFeelTemperature")
day = try map.value("Day")
night = try map.value("Night")
}
func mapping(map: Map) {
}
}
extension WeatherFeature: ImmutableMappable {
init(map: Map) throws {
if let minimum: T = try? map.value("Minimum.Value"),
let maximum: T = try? map.value("Maximum.Value") { // Min/max
unit = try map.value("Minimum.Unit")
value = .minmax(min: minimum, max: maximum)
}
else { // Single value
unit = try map.value("Unit")
value = .single(value: try map.value("Value"))
}
}
func mapping(map: Map) {
}
}
extension DayNightWeather: ImmutableMappable {
init(map: Map) throws {
windSpeed = try map.value("Wind.Speed")
windDirection = (try? map.value("Wind.Direction.Localized")) ?? ((try? map.value("Wind.Direction.English")) ?? "")
precipitationProbability = try map.value("PrecipitationProbability")
phrase = try map.value("LongPhrase")
icon = try map.value("Icon")
}
func mapping(map: Map) {
}
}
struct CurrentWeather {
let effectiveDate: Date
let phrase: String
let icon: Int
let temperature: WeatherFeature<Double>
let realFeel: WeatherFeature<Double>
let windSpeed: WeatherFeature<Double>
let windDirection: String
}
extension CurrentWeather: ImmutableMappable {
private static let UnitSystem = Locale.current.usesMetricSystem ? "Metric" : "Imperial"
init(map: Map) throws {
effectiveDate = try map.value("EpochTime", using: DateTransform())
temperature = try map.value("Temperature.\(CurrentWeather.UnitSystem)")
realFeel = try map.value("RealFeelTemperature.\(CurrentWeather.UnitSystem)")
windSpeed = try map.value("Wind.Speed.\(CurrentWeather.UnitSystem)")
windDirection = (try? map.value("Wind.Direction.Localized")) ?? ((try? map.value("Wind.Direction.English")) ?? "")
phrase = try map.value("WeatherText")
icon = try map.value("WeatherIcon")
}
func mapping(map: Map) {
}
}
|
mit
|
e90c81e060ec427e16760451030330c0
| 30.641509 | 122 | 0.658915 | 4.03125 | false | false | false | false |
radif/MSSticker-Images
|
Example/Example/MessagesExtension/ExampleCollectionViewCell.swift
|
1
|
3342
|
//
// ExampleCollectionViewCell.swift
// Example
//
// Created by Radif Sharafullin on 8/24/16.
// Copyright © 2016 Radif Sharafullin. All rights reserved.
//
import UIKit
import Messages
class ExampleCollectionViewCell: UICollectionViewCell {
static let kReuseIdentifier = "ExampleCollectionViewCell"
@IBOutlet weak var _spinner: UIActivityIndicatorView!
@IBOutlet weak var _stickerHolderView: UIView!
var _stickerView: MSStickerView? = nil
private var _stickerData : StickerData?=nil
var stickerData : StickerData? {get {return _stickerData}}
override func prepareForReuse() {
if let v = _stickerView {
v.stopAnimating()
v.sticker=nil
v.removeFromSuperview()
}
_stickerView = nil
_stickerData = nil
hideSpinner()
}
func render(stickerData: StickerData){
_stickerData=stickerData
loadCurrentStickerAsync()
}
func loadCurrentStickerAsync(){
if let stickerData = _stickerData {
showSpinner()
let images = stickerData.images
let localizedDescription = stickerData.name
let frameDelay = CGFloat(stickerData.frameDelay)
//async...
DispatchQueue.main.async() { [weak self] in
var imgs = [UIImage]()
for imageName in images{
let img = UIImage(named: imageName)
if let i = img{ imgs.append(i) }
}
let urlForImageName = { (_ name:String)->URL in
var url = Bundle.main.resourceURL!
url.appendPathComponent(name + ".png")
return url
}
let sticker :MSSticker
do {
try sticker=MSSticker(images: imgs, format: .apng, frameDelay: frameDelay, numberOfLoops: 0, localizedDescription: localizedDescription)
}catch MSStickerAnimationInputError.InvalidDimensions {
try! sticker=MSSticker(contentsOfFileURL: urlForImageName("invalid_image_size"), localizedDescription: "invalid dimensions")
}catch MSStickerAnimationInputError.InvalidStickerFileSize {
try! sticker=MSSticker(contentsOfFileURL: urlForImageName("invalid_file_size"), localizedDescription: "invalid file size")
} catch {
fatalError("other error:\(error)")
}
if let s=self{
if localizedDescription == s._stickerData?.name{
let sv = MSStickerView(frame: s._stickerHolderView.bounds, sticker: sticker)
s._stickerHolderView.addSubview(sv)
sv.startAnimating()
s._stickerView = sv
s.hideSpinner()
}
}
}
}
}
func showSpinner(){
_spinner.isHidden = false
_spinner.startAnimating()
}
func hideSpinner(){
_spinner.stopAnimating()
_spinner.isHidden = true
}
}
|
mit
|
5b95d6032f24a5e87bb5125545373869
| 33.091837 | 156 | 0.535468 | 5.681973 | false | false | false | false |
mparrish91/gifRecipes
|
framework/Model/User.swift
|
3
|
1143
|
//
// User.swift
// reddift
//
// Created by sonson on 2015/11/12.
// Copyright © 2015年 sonson. All rights reserved.
//
import Foundation
/**
*/
public enum UserModPermission: String {
case all
case wiki
case posts
case mail
case flair
case unknown
public init(_ value: String) {
switch value {
case "all":
self = .all
case "wiki":
self = .wiki
case "posts":
self = .posts
case "mail":
self = .mail
case "flair":
self = .flair
default:
self = .unknown
}
}
}
/**
User object
*/
public struct User {
let date: TimeInterval
let modPermissions: [UserModPermission]
let name: String
let id: String
public init(date: Double, permissions: [String]?, name: String, id: String) {
self.date = date
if let permissions = permissions {
self.modPermissions = permissions.map({UserModPermission($0)})
} else {
self.modPermissions = []
}
self.name = name
self.id = id
}
}
|
mit
|
224721ca3172741b3ff78b57aed5a9c1
| 18.655172 | 81 | 0.526316 | 4.175824 | false | false | false | false |
khoren93/SwiftHub
|
SwiftHub/Modules/Issues/IssuesViewModel.swift
|
1
|
3918
|
//
// IssuesViewModel.swift
// SwiftHub
//
// Created by Sygnoos9 on 11/20/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import RxDataSources
class IssuesViewModel: ViewModel, ViewModelType {
struct Input {
let headerRefresh: Observable<Void>
let footerRefresh: Observable<Void>
let segmentSelection: Observable<IssueSegments>
let selection: Driver<IssueCellViewModel>
}
struct Output {
let navigationTitle: Driver<String>
let imageUrl: Driver<URL?>
let items: BehaviorRelay<[IssueCellViewModel]>
let userSelected: Driver<UserViewModel>
let issueSelected: Driver<IssueViewModel>
}
let repository: BehaviorRelay<Repository>
let segment = BehaviorRelay<IssueSegments>(value: .open)
let userSelected = PublishSubject<User>()
init(repository: Repository, provider: SwiftHubAPI) {
self.repository = BehaviorRelay(value: repository)
super.init(provider: provider)
if let fullname = repository.fullname {
analytics.log(.issues(fullname: fullname))
}
}
func transform(input: Input) -> Output {
let elements = BehaviorRelay<[IssueCellViewModel]>(value: [])
input.segmentSelection.bind(to: segment).disposed(by: rx.disposeBag)
input.headerRefresh.flatMapLatest({ [weak self] () -> Observable<[IssueCellViewModel]> in
guard let self = self else { return Observable.just([]) }
self.page = 1
return self.request()
.trackActivity(self.headerLoading)
})
.subscribe(onNext: { (items) in
elements.accept(items)
}).disposed(by: rx.disposeBag)
input.footerRefresh.flatMapLatest({ [weak self] () -> Observable<[IssueCellViewModel]> in
guard let self = self else { return Observable.just([]) }
self.page += 1
return self.request()
.trackActivity(self.footerLoading)
})
.subscribe(onNext: { (items) in
elements.accept(elements.value + items)
}).disposed(by: rx.disposeBag)
let userDetails = userSelected.asDriver(onErrorJustReturn: User())
.map({ (user) -> UserViewModel in
let viewModel = UserViewModel(user: user, provider: self.provider)
return viewModel
})
let navigationTitle = repository.map({ (mode) -> String in
return R.string.localizable.eventsNavigationTitle.key.localized()
}).asDriver(onErrorJustReturn: "")
let imageUrl = repository.map({ (repository) -> URL? in
repository.owner?.avatarUrl?.url
}).asDriver(onErrorJustReturn: nil)
let issueSelected = input.selection.map { (cellViewModel) -> IssueViewModel in
let viewModel = IssueViewModel(repository: self.repository.value, issue: cellViewModel.issue, provider: self.provider)
return viewModel
}
return Output(navigationTitle: navigationTitle,
imageUrl: imageUrl,
items: elements,
userSelected: userDetails,
issueSelected: issueSelected)
}
func request() -> Observable<[IssueCellViewModel]> {
let fullname = repository.value.fullname ?? ""
let state = segment.value.state.rawValue
return provider.issues(fullname: fullname, state: state, page: page)
.trackActivity(loading)
.trackError(error)
.map { $0.map({ (issue) -> IssueCellViewModel in
let viewModel = IssueCellViewModel(with: issue)
viewModel.userSelected.bind(to: self.userSelected).disposed(by: self.rx.disposeBag)
return viewModel
})
}
}
}
|
mit
|
a961f75ad6f2c1c39449be04901ac0c6
| 35.607477 | 130 | 0.61782 | 4.964512 | false | false | false | false |
drinkapoint/DrinkPoint-iOS
|
DrinkPoint/Pods/FacebookShare/Sources/Share/Internal/SDKSharingDelegateBridge.swift
|
1
|
2519
|
// Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright 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 FBSDKShareKit
@testable import FacebookCore
private struct BridgingFailedError<Content: ContentProtocol>: ErrorType {
let nativeResults: [NSObject: AnyObject]?
}
internal class SDKSharingDelegateBridge<Content: ContentProtocol>: NSObject, FBSDKSharingDelegate {
internal var completion: (ContentSharerResult<Content> -> Void)? = nil
func setupAsDelegateFor(sharer: FBSDKSharing) {
// We need for the connection to retain us,
// so we can stick around and keep calling into handlers,
// as long as the connection is alive/sending messages.
objc_setAssociatedObject(sharer, unsafeAddressOf(self), self, .OBJC_ASSOCIATION_RETAIN)
sharer.delegate = self
}
func sharer(sharer: FBSDKSharing, didCompleteWithResults results: [NSObject : AnyObject]?) {
let dictionary = results.map {
$0.keyValueFlatMap { key, value in
(key as? String, value as? String)
}
}
let sharingResult = dictionary.map(Content.Result.init)
let result: ContentSharerResult<Content> = sharingResult.map(ContentSharerResult.Success) ??
.Failed(BridgingFailedError<Content>(nativeResults: results))
completion?(result)
}
func sharer(sharer: FBSDKSharing, didFailWithError error: NSError) {
let error: ErrorType = ShareError(error: error) ?? error
completion?(.Failed(error))
}
func sharerDidCancel(sharer: FBSDKSharing) {
completion?(.Cancelled)
}
}
|
mit
|
fa371fac304e49c6cc4d8f2b0c3db1f1
| 41.694915 | 99 | 0.749107 | 4.482206 | false | false | false | false |
liuxuan30/ios-charts
|
Source/Charts/Utils/Platform+Accessibility.swift
|
3
|
5951
|
//
// Platform+Accessibility.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
#if os(iOS) || os(tvOS)
#if canImport(UIKit)
import UIKit
#endif
internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil)
{
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: element)
}
internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil)
{
UIAccessibility.post(notification: UIAccessibility.Notification.screenChanged, argument: element)
}
/// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement.
open class NSUIAccessibilityElement: UIAccessibilityElement
{
private weak var containerView: UIView?
final var isHeader: Bool = false
{
didSet
{
accessibilityTraits = isHeader ? UIAccessibilityTraits.header : UIAccessibilityTraits.none
}
}
final var isSelected: Bool = false
{
didSet
{
accessibilityTraits = isSelected ? UIAccessibilityTraits.selected : UIAccessibilityTraits.none
}
}
override public init(accessibilityContainer container: Any)
{
// We can force unwrap since all chart views are subclasses of UIView
containerView = (container as! UIView)
super.init(accessibilityContainer: container)
}
override open var accessibilityFrame: CGRect
{
get
{
return super.accessibilityFrame
}
set
{
guard let containerView = containerView else { return }
super.accessibilityFrame = containerView.convert(newValue, to: UIScreen.main.coordinateSpace)
}
}
}
extension NSUIView
{
/// An array of accessibilityElements that is used to implement UIAccessibilityContainer internally.
/// Subclasses **MUST** override this with an array of such elements.
@objc open func accessibilityChildren() -> [Any]?
{
return nil
}
public final override var isAccessibilityElement: Bool
{
get { return false } // Return false here, so we can make individual elements accessible
set { }
}
open override func accessibilityElementCount() -> Int
{
return accessibilityChildren()?.count ?? 0
}
open override func accessibilityElement(at index: Int) -> Any?
{
return accessibilityChildren()?[index]
}
open override func index(ofAccessibilityElement element: Any) -> Int
{
guard let axElement = element as? NSUIAccessibilityElement else { return NSNotFound }
return (accessibilityChildren() as? [NSUIAccessibilityElement])?
.firstIndex(of: axElement) ?? NSNotFound
}
}
#endif
#if os(OSX)
#if canImport(AppKit)
import AppKit
#endif
internal func accessibilityPostLayoutChangedNotification(withElement element: Any? = nil)
{
guard let validElement = element else { return }
NSAccessibility.post(element: validElement, notification: .layoutChanged)
}
internal func accessibilityPostScreenChangedNotification(withElement element: Any? = nil)
{
// Placeholder
}
/// A simple abstraction over UIAccessibilityElement and NSAccessibilityElement.
open class NSUIAccessibilityElement: NSAccessibilityElement
{
private weak var containerView: NSView?
final var isHeader: Bool = false
{
didSet
{
setAccessibilityRole(isHeader ? .staticText : .none)
}
}
final var isSelected: Bool = false
{
didSet
{
setAccessibilitySelected(isSelected)
}
}
open var accessibilityLabel: String
{
get
{
return accessibilityLabel() ?? ""
}
set
{
setAccessibilityLabel(newValue)
}
}
open var accessibilityFrame: NSRect
{
get
{
return accessibilityFrame()
}
set
{
guard let containerView = containerView else { return }
let bounds = NSAccessibility.screenRect(fromView: containerView, rect: newValue)
// This works, but won't auto update if the window is resized or moved.
// setAccessibilityFrame(bounds)
// using FrameInParentSpace allows for automatic updating of frame when windows are moved and resized.
// However, there seems to be a bug right now where using it causes an offset in the frame.
// This is a slightly hacky workaround that calculates the offset and removes it from frame calculation.
setAccessibilityFrameInParentSpace(bounds)
let axFrame = accessibilityFrame()
let widthOffset = abs(axFrame.origin.x - bounds.origin.x)
let heightOffset = abs(axFrame.origin.y - bounds.origin.y)
let rect = NSRect(x: bounds.origin.x - widthOffset,
y: bounds.origin.y - heightOffset,
width: bounds.width,
height: bounds.height)
setAccessibilityFrameInParentSpace(rect)
}
}
public init(accessibilityContainer container: Any)
{
// We can force unwrap since all chart views are subclasses of NSView
containerView = (container as! NSView)
super.init()
setAccessibilityParent(containerView)
setAccessibilityRole(.row)
}
}
/// - Note: setAccessibilityRole(.list) is called at init. See Platform.swift.
extension NSUIView: NSAccessibilityGroup
{
open override func accessibilityLabel() -> String?
{
return "Chart View"
}
open override func accessibilityRows() -> [Any]?
{
return accessibilityChildren()
}
}
#endif
|
apache-2.0
|
099477d8e8451f07628ee8f9bdf2ab3c
| 26.67907 | 116 | 0.653672 | 5.121343 | false | false | false | false |
MikotoZero/MMCache
|
Source/MD5/MD5.swift
|
1
|
6755
|
//
// MD5.swift
// MMCache
//
// Created by 丁帅 on 2017/6/1.
// Copyright © 2017年 MikotoZero. All rights reserved.
//
import Foundation
// MARK: - Utilities
private typealias Byte = UInt8
private typealias Word = UInt32
private struct Digest {
let digest: [Byte]
init(_ digest: [Byte]) {
assert(digest.count == 16)
self.digest = digest
}
var checksum: String {
return encodeMD5(digest: digest)
}
}
private func F(_ b: Word, _ c: Word, _ d: Word) -> Word {
return (b & c) | ((~b) & d)
}
private func G(_ b: Word, _ c: Word, _ d: Word) -> Word {
return (b & d) | (c & (~d))
}
private func H(_ b: Word, _ c: Word, _ d: Word) -> Word {
return b ^ c ^ d
}
private func I(_ b: Word, _ c: Word, _ d: Word) -> Word {
return c ^ (b | (~d))
}
private func rotateLeft(_ x: Word, by: Word) -> Word {
return ((x << by) & 0xFFFFFFFF) | (x >> (32 - by))
}
// MARK: - Calculating a MD5 digest of bytes from bytes
private func md5(_ bytes: [Byte]) -> Digest {
// Initialization
let s: [Word] = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21
]
let K: [Word] = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391
]
var a0: Word = 0x67452301 // A
var b0: Word = 0xefcdab89 // B
var c0: Word = 0x98badcfe // C
var d0: Word = 0x10325476 // D
// Pad message with a single bit "1"
var message = bytes
let originalLength = bytes.count
let bitLength = UInt64(originalLength * 8)
message.append(0x80)
// Pad message with bit "0" until message length is 64 bits fewer than 512
repeat {
message.append(0x0)
} while (message.count * 8) % 512 != 448
message.append(Byte((bitLength >> 0) & 0xFF))
message.append(Byte((bitLength >> 8) & 0xFF))
message.append(Byte((bitLength >> 16) & 0xFF))
message.append(Byte((bitLength >> 24) & 0xFF))
message.append(Byte((bitLength >> 32) & 0xFF))
message.append(Byte((bitLength >> 40) & 0xFF))
message.append(Byte((bitLength >> 48) & 0xFF))
message.append(Byte((bitLength >> 56) & 0xFF))
let newBitLength = message.count * 8
assert(newBitLength % 512 == 0)
// Transform
let chunkLength = 512 // 512-bit
let chunkLengthInBytes = chunkLength / 8 // 64-bytes
let totalChunks = newBitLength / chunkLength
assert(totalChunks >= 1)
for chunk in 0..<totalChunks {
let index = chunk*chunkLengthInBytes
var chunk: [Byte] = Array(message[index..<index+chunkLengthInBytes]) // 512-bit/64-byte chunk
// break chunk into sixteen 32-bit words
var M: [Word] = []
for j in 0..<16 {
let m0 = Word(chunk[4*j+0]) << 0
let m1 = Word(chunk[4*j+1]) << 8
let m2 = Word(chunk[4*j+2]) << 16
let m3 = Word(chunk[4*j+3]) << 24
let m = Word(m0 | m1 | m2 | m3)
M.append(m)
}
assert(M.count == 16)
var A: Word = a0
var B: Word = b0
var C: Word = c0
var D: Word = d0
for i in 0..<64 {
var f: Word = 0
var g: Int = 0
if i < 16 {
f = F(B, C, D)
g = i
} else if i >= 16 && i <= 31 {
f = G(B, C, D)
g = ((5*i + 1) % 16)
} else if i >= 32 && i <= 47 {
f = H(B, C, D)
g = ((3*i + 5) % 16)
} else if i >= 48 && i <= 63 {
f = I(B, C, D)
g = ((7*i) % 16)
}
let dTemp = D
D = C
C = B
let x = A &+ f &+ K[i] &+ M[g]
let by = s[i]
B = B &+ rotateLeft(x, by: by)
A = dTemp
}
a0 = a0 &+ A
b0 = b0 &+ B
c0 = c0 &+ C
d0 = d0 &+ D
}
assert(a0 >= 0)
assert(b0 >= 0)
assert(c0 >= 0)
assert(d0 >= 0)
let digest0: Byte = Byte((a0 >> 0) & 0xFF)
let digest1: Byte = Byte((a0 >> 8) & 0xFF)
let digest2: Byte = Byte((a0 >> 16) & 0xFF)
let digest3: Byte = Byte((a0 >> 24) & 0xFF)
let digest4: Byte = Byte((b0 >> 0) & 0xFF)
let digest5: Byte = Byte((b0 >> 8) & 0xFF)
let digest6: Byte = Byte((b0 >> 16) & 0xFF)
let digest7: Byte = Byte((b0 >> 24) & 0xFF)
let digest8: Byte = Byte((c0 >> 0) & 0xFF)
let digest9: Byte = Byte((c0 >> 8) & 0xFF)
let digest10: Byte = Byte((c0 >> 16) & 0xFF)
let digest11: Byte = Byte((c0 >> 24) & 0xFF)
let digest12: Byte = Byte((d0 >> 0) & 0xFF)
let digest13: Byte = Byte((d0 >> 8) & 0xFF)
let digest14: Byte = Byte((d0 >> 16) & 0xFF)
let digest15: Byte = Byte((d0 >> 24) & 0xFF)
let digest = [
digest0, digest1, digest2, digest3, digest4, digest5, digest6, digest7,
digest8, digest9, digest10, digest11, digest12, digest13, digest14, digest15
]
assert(digest.count == 16)
return Digest(digest)
}
// MARK: - Encoding a MD5 digest of bytes to a string
private func encodeMD5(digest: [Byte]) -> String {
assert(digest.count == 16)
let str = digest.reduce("") { str, byte in
let radix = 16
let s = String(byte, radix: radix)
// Ensure byte values less than 16 are padding with a leading 0
let sum = str + (byte < Byte(radix) ? "0" : "") + s
return sum
}
return str
}
// MARK: - String extension
internal extension String {
var md5: String {
return encodeMD5(digest: md5Digest)
}
private var md5Digest: [Byte] {
let bytes = [Byte](self.utf8)
let digest = MMCache.md5(bytes)
return digest.digest
}
}
|
mit
|
abafbe75290f6d0bdfe95de29845fb0b
| 27.472574 | 101 | 0.534825 | 2.855692 | false | false | false | false |
bigxodus/candlelight
|
candlelight/screen/main/controller/BookmarkController.swift
|
1
|
2676
|
import UIKit
class BookmarkController: UIViewController {
static let collectionReuseIdentifier = "collectionCell"
let bottomMenuController: BottomMenuController?
var collectionSource: BookmarkViewDelegate?
required init?(coder aDecoder: NSCoder) {
self.bottomMenuController = nil
super.init(coder: aDecoder)
}
init(bottomMenuController: BottomMenuController) {
self.bottomMenuController = bottomMenuController
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
let root = UIView()
let mainRect = UIScreen.main.bounds
root.frame = CGRect(x: 0, y: 0, width: mainRect.width, height: mainRect.height)
setupCollectionView(parent: root)
bottomMenuController?.setupBottomButtons(parent: root, type: .like)
self.view = root
}
func setupCollectionView(parent: UIView) {
let parentFrame = parent.frame
let statusBarHeight = UIApplication.shared.statusBarFrame.size.height
let frame = CGRect(
x: parentFrame.origin.x,
y: parentFrame.origin.y + statusBarHeight,
width: parentFrame.size.width,
height: parentFrame.size.height - BottomMenuController.bottomMenuHeight - statusBarHeight
)
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: frame.size.width, height: 50)
layout.sectionInset = UIEdgeInsets.zero
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 1
let source = BookmarkViewDelegate(self)
let collectionView = UICollectionView(frame: frame, collectionViewLayout: layout)
collectionView.register(BookmarkViewCell.self, forCellWithReuseIdentifier: BookmarkController.collectionReuseIdentifier)
collectionView.backgroundColor = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0)
collectionView.dataSource = source
collectionView.delegate = source
collectionView.contentInset = UIEdgeInsetsMake(-statusBarHeight, 0, 0, 0)
source.collectionView = collectionView
parent.addSubview(collectionView)
collectionSource = source
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidAppear(_ animated: Bool) {
collectionSource?.reloadCollectionView()
}
}
|
apache-2.0
|
1718b8b0e81ab5580b021d7f8a19f025
| 31.634146 | 128 | 0.686099 | 5.362725 | false | false | false | false |
notohiro/NowCastMapView
|
NowCastMapView/TileCache.swift
|
1
|
4358
|
//
// TileCache.swift
// NowCastMapView
//
// Created by Hiroshi Noto on 2017/05/07.
// Copyright © 2017 Hiroshi Noto. All rights reserved.
//
import Foundation
/**
A `TileCacheProvider` protocol defines a way to request a `Tile`.
*/
public protocol TileCacheProvider {
var baseTime: BaseTime { get }
/**
Returns tiles within given MapRect. The `Tile.image` object will be nil if it's not downloaded.
Call `resume()` method to obtain image file from internet.
- Parameter request: The request you need to get tiles.
- Returns: The tiles within given request.
*/
func tiles(with request: TileModel.Request) throws -> [Tile]
}
open class TileCache {
public let baseTime: BaseTime
public var cache = Set<Tile>()
public var cacheByURL = [URL: Tile]()
open private(set) lazy var model: TileModel = TileModel(baseTime: self.baseTime, delegate: self)
open private(set) weak var delegate: TileModelDelegate?
private let semaphore = DispatchSemaphore(value: 1)
deinit {
model.cancelAll()
}
internal init(baseTime: BaseTime, delegate: TileModelDelegate?) {
self.baseTime = baseTime
self.delegate = delegate
}
}
extension TileCache: TileCacheProvider {
open func tiles(with request: TileModel.Request) throws -> [Tile] {
var ret = [Tile]()
var needsRequest = false
guard let newCoordinates = request.coordinates.intersecting(TileModel.serviceAreaCoordinates) else {
throw NCError.outOfService
}
let newRequest = TileModel.Request(range: request.range,
scale: request.scale,
coordinates: newCoordinates,
withoutProcessing: request.withoutProcessing)
let zoomLevel = ZoomLevel(zoomScale: request.scale)
guard let originModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.origin) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.origin)
throw NCError.tileFailed(reason: reason)
}
guard let terminalModifiers = Tile.Modifiers(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.terminal) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedCoordinate(zoomLevel: zoomLevel, coordinate: newRequest.coordinates.terminal)
throw NCError.tileFailed(reason: reason)
}
for index in request.range {
for latMod in originModifiers.latitude ... terminalModifiers.latitude {
for lonMod in originModifiers.longitude ... terminalModifiers.longitude {
guard let mods = Tile.Modifiers(zoomLevel: zoomLevel, latitude: latMod, longitude: lonMod) else {
let reason = NCError.TileFailedReason.modifiersInitializationFailedMods(zoomLevel: zoomLevel, latitiude: latMod, longitude: lonMod)
throw NCError.tileFailed(reason: reason)
}
guard let url = URL(baseTime: baseTime, index: index, modifiers: mods) else {
throw NCError.tileFailed(reason: .urlInitializationFailed)
}
if let cachedTile = cacheByURL[url] {
ret.append(cachedTile)
} else {
needsRequest = true
}
}
}
}
if needsRequest {
let newRequest = TileModel.Request(range: request.range,
scale: request.scale,
coordinates: request.coordinates,
withoutProcessing: true)
let task = try model.tiles(with: newRequest, completionHandler: nil)
task.resume()
}
return ret
}
}
extension TileCache: TileModelDelegate {
public func tileModel(_ model: TileModel, task: TileModel.Task, added tile: Tile) {
semaphore.wait()
cache.insert(tile)
cacheByURL[tile.url] = tile
semaphore.signal()
delegate?.tileModel(model, task: task, added: tile)
}
public func tileModel(_ model: TileModel, task: TileModel.Task, failed url: URL, error: Error) {
delegate?.tileModel(model, task: task, failed: url, error: error)
}
}
|
mit
|
c1ff375723de46abed50fd522eaa3b8e
| 33.856 | 153 | 0.643333 | 4.473306 | false | false | false | false |
joeldom/PageMenu
|
Demos/Demo 2/PageMenuDemoNoStoryboard/PageMenuDemoNoStoryboard/TestViewController.swift
|
26
|
3108
|
//
// TestViewController.swift
// PageMenuDemoNoStoryboard
//
// Created by Niklas Fahl on 12/19/14.
// Copyright (c) 2014 CAPS. All rights reserved.
//
import UIKit
class TestViewController: UIViewController {
var pageMenu : CAPSPageMenu?
var pageMenu1 : CAPSPageMenu?
override func viewDidLoad() {
super.viewDidLoad()
// Initialize view controllers to display and place in array
var controllerArray : [UIViewController] = []
var controller1 : UIViewController = UIViewController()
controller1.view.backgroundColor = UIColor.purpleColor()
controller1.title = "PURPLE"
controllerArray.append(controller1)
var controller2 : UIViewController = UIViewController()
controller2.view.backgroundColor = UIColor.orangeColor()
controller2.title = "ORANGE"
controllerArray.append(controller2)
var controller3 : UIViewController = UIViewController()
controller3.view.backgroundColor = UIColor.grayColor()
controller3.title = "GRAY"
controllerArray.append(controller3)
var controller4 : UIViewController = UIViewController()
controller4.view.backgroundColor = UIColor.brownColor()
controller4.title = "BROWN"
controllerArray.append(controller4)
// Initialize scroll menu
pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRectMake(0.0, 50.0, self.view.frame.width, 100), pageMenuOptions: nil)
println(self.view.frame.height)
self.view.addSubview(pageMenu!.view)
// Initialize view controllers to display and place in array
var controllerArray_1 : [UIViewController] = []
var controller1_1 : UIViewController = UIViewController()
controller1_1.view.backgroundColor = UIColor.brownColor()
controller1_1.title = "BROWN"
controllerArray_1.append(controller1_1)
var controller2_1 : UIViewController = UIViewController()
controller2_1.view.backgroundColor = UIColor.grayColor()
controller2_1.title = "GRAY"
controllerArray_1.append(controller2_1)
var controller3_1 : UIViewController = UIViewController()
controller3_1.view.backgroundColor = UIColor.orangeColor()
controller3_1.title = "ORANGE"
controllerArray_1.append(controller3_1)
var controller4_1 : UIViewController = UIViewController()
controller4_1.view.backgroundColor = UIColor.purpleColor()
controller4_1.title = "PURPLE"
controllerArray_1.append(controller4_1)
// Initialize scroll menu
pageMenu1 = CAPSPageMenu(viewControllers: controllerArray_1, frame: CGRectMake(0.0, 400.0, self.view.frame.width, 100.0), pageMenuOptions: nil)
self.view.addSubview(pageMenu1!.view)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
bsd-3-clause
|
f3ac1a9b66ffde49d09f38ff1bfff8ff
| 36.902439 | 151 | 0.661197 | 4.988764 | false | false | false | false |
karloscarweber/SwiftFoundations-Examples
|
Playgrounds/Chapter2-VariablesAndConstants.playground/Contents.swift
|
1
|
2104
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Karl", day: "Weber")
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics([2,4,6,8,10])
print(statistics.min)
print(statistics.1)
print(statistics.sum)
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(5,6,7,8)
/*
## OOOH! NESTED FUNCTIONS:
Nested functions are the new hotness in Swift, I believe.
*/
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
add()
add()
add()
return y
}
returnFifteen()
func makeIncrement() -> (Int->Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrement()
increment(12)
func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [10, 19, 7, 12]
hasAnyMatches(numbers, condition: lessThanTen)
/*
# Closures
You can write a closure without a name by surrrounding code with braces ({})
in seperates the arguments and return types from the actual body.
It
*/
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
let mappedNumbers = numbers.map({number in 3 * number})
print(mappedNumbers)
// so the sort method on numbers takes a comparison as it's only argument
let sortedNumbers = numbers.sort({ $1 > $2 })
print(sortedNumbers)
|
mit
|
97fc108f0f532847803b6ad074bdb4c8
| 15.4375 | 80 | 0.59173 | 3.518395 | false | false | false | false |
djflsdl08/BasicIOS
|
Image/Image/NasaViewController.swift
|
1
|
2041
|
//
// NasaViewController.swift
// Image
//
// Created by 김예진 on 2017. 10. 13..
// Copyright © 2017년 Kim,Yejin. All rights reserved.
//
import UIKit
class NasaViewController: UIViewController, UISplitViewControllerDelegate {
private struct Storyboard {
static let ShowImageSegue = "Show Image"
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == Storyboard.ShowImageSegue {
if let ivc = (segue.destination.contentViewController as? ImageViewController) {
let imageName = (sender as? UIButton)?.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
splitViewController?.delegate = self
}
@IBAction func showImage(_ sender: UIButton) {
if let ivc = splitViewController?.viewControllers.last?.contentViewController as? ImageViewController {
let imageName = sender.currentTitle
ivc.imageURL = DemoURL.NASAImageNamed(imageName: imageName)
ivc.title = imageName
} else {
performSegue(withIdentifier: Storyboard.ShowImageSegue, sender: sender)
}
}
func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController: UIViewController, onto primaryViewController: UIViewController) -> Bool {
if primaryViewController.contentViewController == self {
if let ivc = secondaryViewController.contentViewController as? ImageViewController, ivc.imageURL == nil {
return true
}
}
return false
}
}
extension UIViewController {
var contentViewController : UIViewController {
if let navcon = self as? UINavigationController {
return navcon.visibleViewController ?? self
} else {
return self
}
}
}
|
mit
|
2a5dbd07cf330083d7ac538354738b50
| 32.311475 | 191 | 0.650098 | 5.628809 | false | false | false | false |
marty-suzuki/QiitaApiClient
|
QiitaApiClient/Model/QiitaProject.swift
|
1
|
1283
|
//
// QiitaProject.swift
// QiitaApiClient
//
// Created by Taiki Suzuki on 2016/08/21.
//
//
import Foundation
public class QiitaProject: QiitaModel {
public let renderedBody: String
public let archived: Bool
public let body: String
public let createdAt: NSDate
public let id: Int
public let name: String
public let updatedAt: NSDate
public required init?(dictionary: [String : NSObject]) {
guard
let renderedBody = dictionary["rendered_body"] as? String,
let archived = dictionary["archived"] as? Bool,
let body = dictionary["body"] as? String,
let rawCreatedAt = dictionary["created_at"] as? String,
let createdAt = NSDate.dateFromISO8601String(rawCreatedAt),
let id = dictionary["id"] as? Int,
let name = dictionary["name"] as? String,
let rawUpdatedAt = dictionary["updated_at"] as? String,
let updatedAt = NSDate.dateFromISO8601String(rawUpdatedAt)
else {
return nil
}
self.renderedBody = renderedBody
self.archived = archived
self.body = body
self.createdAt = createdAt
self.id = id
self.name = name
self.updatedAt = updatedAt
}
}
|
mit
|
f3ae9c0acd938136d0f8cd142bba2457
| 29.571429 | 71 | 0.614186 | 4.549645 | false | false | false | false |
spxrogers/Moya-Gloss
|
Example and Tests/Tests/SignalProducerTests.swift
|
1
|
8657
|
@testable import Demo
import Quick
import Nimble
import Moya
import ReactiveSwift
import Moya_Gloss
class SignalProducerGlossSpec: QuickSpec {
override func spec() {
let getObject = ExampleAPI.getObject
let getArray = ExampleAPI.getArray
let getNestedObject = ExampleAPI.getNestedObject
let getNestedArray = ExampleAPI.getNestedArray
let getBadObject = ExampleAPI.getBadObject
let getBadFormat = ExampleAPI.getBadFormat
let steven = Person(json: ["name": "steven rogers", "age": 23])!
let john = Person(json: ["name": "john doe"])!
let people = [steven, john]
var provider: Reactive<MoyaProvider<ExampleAPI>>!
beforeEach {
provider = MoyaProvider<ExampleAPI>(stubClosure: MoyaProvider.immediatelyStub).reactive
}
// standard
it("handles a core object request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getObject)
.mapObject(type: Person.self)
.start { (event) in
switch event {
case .value(let person):
equal = steven == person
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
it("handles a core array request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getArray)
.mapArray(type: Person.self)
.start { (event) in
switch event {
case .value(let resultPeople):
equal = people == resultPeople
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
// nested object
it("handles a core nested-object request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getNestedObject)
.mapObject(type: Person.self, forKeyPath: "person")
.start { (event) in
switch event {
case .value(let person):
equal = steven == person
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
it("handles a core multi-level nested-object request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getNestedObject)
.mapObject(type: Person.self, forKeyPath: "multi.nested.person")
.start { (event) in
switch event {
case .value(let person):
equal = steven == person
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
// nested array
it("handles a core nested-array request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getNestedArray)
.mapArray(type: Person.self, forKeyPath: "people")
.start { (event) in
switch event {
case .value(let resultPeople):
equal = people == resultPeople
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
it("handles a core multi-level nested-array request") {
var equal = false
waitUntil(timeout: 5) { done in
provider.request(getNestedArray)
.mapArray(type: Person.self, forKeyPath: "multi.nested.people")
.start { (event) in
switch event {
case .value(let resultPeople):
equal = people == resultPeople
case .failed(_):
equal = false
case .completed:
done()
default:
break
}
}
}
expect(equal).to(beTruthy())
}
// bad requests
it("handles a core object missing required gloss fields") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getBadObject)
.mapObject(type: Person.self)
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
default:
done()
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core object invalid format") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getBadFormat)
.mapObject(type: Person.self)
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
default:
done()
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core array invalid format") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getBadFormat)
.mapArray(type: Person.self)
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
default:
done()
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core nested-object request with invalid keyPath") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getNestedObject)
.mapObject(type: Person.self, forKeyPath: "doesnotexist")
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
case .completed:
done()
default:
break
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core multi-level nested-object request with invalid keyPath") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getNestedObject)
.mapObject(type: Person.self, forKeyPath: "multi.whoops")
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
case .completed:
done()
default:
break
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core nested-array request with invalid keyPath") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getNestedArray)
.mapArray(type: Person.self, forKeyPath: "doesnotexist")
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
case .completed:
done()
default:
break
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
it("handles a core multi-level nested-array request with invalid keyPath") {
var failedWhenExpected = false
waitUntil(timeout: 5) { done in
provider.request(getNestedArray)
.mapArray(type: Person.self, forKeyPath: "multi.whoops")
.start { (event) in
switch event {
case .value(_):
failedWhenExpected = false
case .failed(_):
failedWhenExpected = true
done()
case .completed:
done()
default:
break
}
}
}
expect(failedWhenExpected).to(beTruthy())
}
}
}
|
mit
|
79b80628b456358f7ae6ae4632fadbaa
| 26.137931 | 93 | 0.504101 | 4.98388 | false | false | false | false |
sschiau/swift
|
stdlib/public/core/StringGuts.swift
|
6
|
9234
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
//
// StringGuts is a parameterization over String's representations. It provides
// functionality and guidance for efficiently working with Strings.
//
@frozen
public // SPI(corelibs-foundation)
struct _StringGuts {
@usableFromInline
internal var _object: _StringObject
@inlinable @inline(__always)
internal init(_ object: _StringObject) {
self._object = object
_invariantCheck()
}
// Empty string
@inlinable @inline(__always)
init() {
self.init(_StringObject(empty: ()))
}
}
// Raw
extension _StringGuts {
@inlinable @inline(__always)
internal var rawBits: _StringObject.RawBitPattern {
return _object.rawBits
}
}
// Creation
extension _StringGuts {
@inlinable @inline(__always)
internal init(_ smol: _SmallString) {
self.init(_StringObject(smol))
}
@inlinable @inline(__always)
internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) {
self.init(_StringObject(immortal: bufPtr, isASCII: isASCII))
}
@inline(__always)
internal init(_ storage: __StringStorage) {
self.init(_StringObject(storage))
}
internal init(_ storage: __SharedStringStorage) {
self.init(_StringObject(storage))
}
internal init(
cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int
) {
self.init(_StringObject(
cocoa: cocoa,
providesFastUTF8: providesFastUTF8,
isASCII: isASCII,
length: length))
}
}
// Queries
extension _StringGuts {
// The number of code units
@inlinable @inline(__always)
internal var count: Int { return _object.count }
@inlinable @inline(__always)
internal var isEmpty: Bool { return count == 0 }
@inlinable @inline(__always)
internal var isSmall: Bool { return _object.isSmall }
@inline(__always)
internal var isSmallASCII: Bool {
return _object.isSmall && _object.smallIsASCII
}
@inlinable @inline(__always)
internal var asSmall: _SmallString {
return _SmallString(_object)
}
@inlinable @inline(__always)
internal var isASCII: Bool {
return _object.isASCII
}
@inlinable @inline(__always)
internal var isFastASCII: Bool {
return isFastUTF8 && _object.isASCII
}
@inline(__always)
internal var isNFC: Bool { return _object.isNFC }
@inline(__always)
internal var isNFCFastUTF8: Bool {
// TODO(String micro-performance): Consider a dedicated bit for this
return _object.isNFC && isFastUTF8
}
internal var hasNativeStorage: Bool { return _object.hasNativeStorage }
internal var hasSharedStorage: Bool { return _object.hasSharedStorage }
internal var hasBreadcrumbs: Bool {
return hasNativeStorage || hasSharedStorage
}
}
//
extension _StringGuts {
// Whether we can provide fast access to contiguous UTF-8 code units
@_transparent
@inlinable
internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) }
// A String which does not provide fast access to contiguous UTF-8 code units
@inlinable @inline(__always)
internal var isForeign: Bool {
return _slowPath(_object.isForeign)
}
@inlinable @inline(__always)
internal func withFastUTF8<R>(
_ f: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R {
_internalInvariant(isFastUTF8)
if self.isSmall { return try _SmallString(_object).withUTF8(f) }
defer { _fixLifetime(self) }
return try f(_object.fastUTF8)
}
@inlinable @inline(__always)
internal func withFastUTF8<R>(
range: Range<Int>,
_ f: (UnsafeBufferPointer<UInt8>) throws -> R
) rethrows -> R {
return try self.withFastUTF8 { wholeUTF8 in
return try f(UnsafeBufferPointer(rebasing: wholeUTF8[range]))
}
}
@inlinable @inline(__always)
internal func withFastCChar<R>(
_ f: (UnsafeBufferPointer<CChar>) throws -> R
) rethrows -> R {
return try self.withFastUTF8 { utf8 in
let ptr = utf8.baseAddress._unsafelyUnwrappedUnchecked._asCChar
return try f(UnsafeBufferPointer(start: ptr, count: utf8.count))
}
}
}
// Internal invariants
extension _StringGuts {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
#if arch(i386) || arch(arm)
_internalInvariant(MemoryLayout<String>.size == 12, """
the runtime is depending on this, update Reflection.mm and \
this if you change it
""")
#else
_internalInvariant(MemoryLayout<String>.size == 16, """
the runtime is depending on this, update Reflection.mm and \
this if you change it
""")
#endif
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _dump() { _object._dump() }
}
// C String interop
extension _StringGuts {
@inlinable @inline(__always) // fast-path: already C-string compatible
internal func withCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
if _slowPath(!_object.isFastZeroTerminated) {
return try _slowWithCString(body)
}
return try self.withFastCChar {
return try body($0.baseAddress._unsafelyUnwrappedUnchecked)
}
}
@inline(never) // slow-path
@usableFromInline
internal func _slowWithCString<Result>(
_ body: (UnsafePointer<Int8>) throws -> Result
) rethrows -> Result {
_internalInvariant(!_object.isFastZeroTerminated)
return try String(self).utf8CString.withUnsafeBufferPointer {
let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked
return try body(ptr)
}
}
}
extension _StringGuts {
// Copy UTF-8 contents. Returns number written or nil if not enough space.
// Contents of the buffer are unspecified if nil is returned.
@inlinable
internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? {
let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked
if _fastPath(self.isFastUTF8) {
return self.withFastUTF8 { utf8 in
guard utf8.count <= mbp.count else { return nil }
let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked
ptr.initialize(from: utf8Start, count: utf8.count)
return utf8.count
}
}
return _foreignCopyUTF8(into: mbp)
}
@_effects(releasenone)
@usableFromInline @inline(never) // slow-path
internal func _foreignCopyUTF8(
into mbp: UnsafeMutableBufferPointer<UInt8>
) -> Int? {
#if _runtime(_ObjC)
// Currently, foreign means NSString
if let res = _cocoaStringCopyUTF8(_object.cocoaObject, into: mbp) {
return res
}
// If the NSString contains invalid UTF8 (e.g. unpaired surrogates), we
// can get nil from cocoaStringCopyUTF8 in situations where a character by
// character loop would get something more useful like repaired contents
var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked
var numWritten = 0
for cu in String(self).utf8 {
guard numWritten < mbp.count else { return nil }
ptr.initialize(to: cu)
ptr += 1
numWritten += 1
}
return numWritten
#else
fatalError("No foreign strings on Linux in this version of Swift")
#endif
}
@inline(__always)
internal var utf8Count: Int {
if _fastPath(self.isFastUTF8) { return count }
return String(self).utf8.count
}
}
// Index
extension _StringGuts {
@usableFromInline
internal typealias Index = String.Index
@inlinable @inline(__always)
internal var startIndex: String.Index {
return Index(_encodedOffset: 0)._scalarAligned
}
@inlinable @inline(__always)
internal var endIndex: String.Index {
return Index(_encodedOffset: self.count)._scalarAligned
}
}
// Old SPI(corelibs-foundation)
extension _StringGuts {
@available(*, deprecated)
public // SPI(corelibs-foundation)
var _isContiguousASCII: Bool {
return !isSmall && isFastUTF8 && isASCII
}
@available(*, deprecated)
public // SPI(corelibs-foundation)
var _isContiguousUTF16: Bool {
return false
}
// FIXME: Remove. Still used by swift-corelibs-foundation
@available(*, deprecated)
public var startASCII: UnsafeMutablePointer<UInt8> {
return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!)
}
// FIXME: Remove. Still used by swift-corelibs-foundation
@available(*, deprecated)
public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> {
fatalError("Not contiguous UTF-16")
}
}
@available(*, deprecated)
public // SPI(corelibs-foundation)
func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {
guard let s = p else { return nil }
let count = Int(_swift_stdlib_strlen(s))
var result = [CChar](repeating: 0, count: count + 1)
for i in 0..<count {
result[i] = s[i]
}
return result
}
|
apache-2.0
|
e1439489a47cb1dfde172f9b0b73da42
| 26.72973 | 80 | 0.677496 | 4.191557 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxSwift/RxSwift/Subjects/ReplaySubject.swift
|
1
|
6833
|
//
// ReplaySubject.swift
// RxSwift
//
// Created by Krunoslav Zaher on 4/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents an object that is both an observable sequence as well as an observer.
///
/// Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
public class ReplaySubject<Element>
: Observable<Element>
, SubjectType
, ObserverType
, Disposable {
public typealias SubjectObserverType = ReplaySubject<Element>
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
/// Indicates whether the subject has any observers
public var hasObservers: Bool {
_lock.lock()
let value = _observers.count > 0
_lock.unlock()
return value
}
fileprivate let _lock = RecursiveLock()
// state
fileprivate var _isDisposed = false
fileprivate var _isStopped = false
fileprivate var _stoppedEvent = nil as Event<Element>? {
didSet {
_isStopped = _stoppedEvent != nil
}
}
fileprivate var _observers = Observers()
func unsubscribe(_: DisposeKey) {
rxAbstractMethod()
}
final var isStopped: Bool {
return _isStopped
}
/// Notifies all subscribed observers about next event.
///
/// - parameter event: Event to send to the observers.
public func on(_: Event<E>) {
rxAbstractMethod()
}
/// Returns observer interface for subject.
public func asObserver() -> SubjectObserverType {
return self
}
/// Unsubscribe all observers and release resources.
public func dispose() {
}
/// Creates new instance of `ReplaySubject` that replays at most `bufferSize` last elements of sequence.
///
/// - parameter bufferSize: Maximal number of elements to replay to observer after subscription.
/// - returns: New instance of replay subject.
public static func create(bufferSize: Int) -> ReplaySubject<Element> {
if bufferSize == 1 {
return ReplayOne()
} else {
return ReplayMany(bufferSize: bufferSize)
}
}
/// Creates a new instance of `ReplaySubject` that buffers all the elements of a sequence.
/// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable'
/// number of elements.
public static func createUnbounded() -> ReplaySubject<Element> {
return ReplayAll()
}
#if TRACE_RESOURCES
override init() {
_ = Resources.incrementTotal()
}
deinit {
_ = Resources.decrementTotal()
}
#endif
}
fileprivate class ReplayBufferBase<Element>
: ReplaySubject<Element>
, SynchronizedUnsubscribeType {
func trim() {
rxAbstractMethod()
}
func addValueToBuffer(_: Element) {
rxAbstractMethod()
}
func replayBuffer<O: ObserverType>(_: O) where O.E == Element {
rxAbstractMethod()
}
override func on(_ event: Event<Element>) {
dispatch(_synchronized_on(event), event)
}
func _synchronized_on(_ event: Event<E>) -> Observers {
_lock.lock(); defer { _lock.unlock() }
if _isDisposed {
return Observers()
}
if _isStopped {
return Observers()
}
switch event {
case let .next(element):
addValueToBuffer(element)
trim()
return _observers
case .error, .completed:
_stoppedEvent = event
trim()
let observers = _observers
_observers.removeAll()
return observers
}
}
override func subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == Element {
_lock.lock()
let subscription = _synchronized_subscribe(observer)
_lock.unlock()
return subscription
}
func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E {
if _isDisposed {
observer.on(.error(RxError.disposed(object: self)))
return Disposables.create()
}
let anyObserver = observer.asObserver()
replayBuffer(anyObserver)
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return Disposables.create()
} else {
let key = _observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: key)
}
}
func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
_lock.lock()
_synchronized_unsubscribe(disposeKey)
_lock.unlock()
}
func _synchronized_unsubscribe(_ disposeKey: DisposeKey) {
if _isDisposed {
return
}
_ = _observers.removeKey(disposeKey)
}
override func dispose() {
super.dispose()
synchronizedDispose()
}
func synchronizedDispose() {
_lock.lock()
_synchronized_dispose()
_lock.unlock()
}
func _synchronized_dispose() {
_isDisposed = true
_observers.removeAll()
}
}
final class ReplayOne<Element>: ReplayBufferBase<Element> {
private var _value: Element?
override init() {
super.init()
}
override func trim() {
}
override func addValueToBuffer(_ value: Element) {
_value = value
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
if let value = _value {
observer.on(.next(value))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_value = nil
}
}
class ReplayManyBase<Element>: ReplayBufferBase<Element> {
fileprivate var _queue: Queue<Element>
init(queueSize: Int) {
_queue = Queue(capacity: queueSize + 1)
}
override func addValueToBuffer(_ value: Element) {
_queue.enqueue(value)
}
override func replayBuffer<O: ObserverType>(_ observer: O) where O.E == Element {
for item in _queue {
observer.on(.next(item))
}
}
override func _synchronized_dispose() {
super._synchronized_dispose()
_queue = Queue(capacity: 0)
}
}
final class ReplayMany<Element>: ReplayManyBase<Element> {
private let _bufferSize: Int
init(bufferSize: Int) {
_bufferSize = bufferSize
super.init(queueSize: bufferSize)
}
override func trim() {
while _queue.count > _bufferSize {
_ = _queue.dequeue()
}
}
}
final class ReplayAll<Element>: ReplayManyBase<Element> {
init() {
super.init(queueSize: 0)
}
override func trim() {
}
}
|
mit
|
95598e19cfd03bc427d9e47c9b54979b
| 24.303704 | 118 | 0.599824 | 4.818054 | false | false | false | false |
apple/swift-driver
|
Sources/SwiftDriver/IncrementalCompilation/FirstWaveComputer.swift
|
1
|
15289
|
//===--------------- FirstWaveComputer.swift - Incremental --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import protocol TSCBasic.FileSystem
import class Dispatch.DispatchQueue
extension IncrementalCompilationState {
struct FirstWaveComputer {
let moduleDependencyGraph: ModuleDependencyGraph
let jobsInPhases: JobsInPhases
let inputsInvalidatedByExternals: TransitivelyInvalidatedSwiftSourceFileSet
let inputFiles: [TypedVirtualPath]
let sourceFiles: SourceFiles
let buildRecordInfo: BuildRecordInfo
let maybeBuildRecord: BuildRecord?
let fileSystem: FileSystem
let showJobLifecycle: Bool
let alwaysRebuildDependents: Bool
/// If non-null outputs information for `-driver-show-incremental` for input path
private let reporter: Reporter?
@_spi(Testing) public init(
initialState: IncrementalCompilationState.InitialStateForPlanning,
jobsInPhases: JobsInPhases,
driver: Driver,
reporter: Reporter?
) {
self.moduleDependencyGraph = initialState.graph
self.jobsInPhases = jobsInPhases
self.inputsInvalidatedByExternals = initialState.inputsInvalidatedByExternals
self.inputFiles = driver.inputFiles
self.sourceFiles = SourceFiles(
inputFiles: inputFiles,
buildRecord: initialState.maybeBuildRecord)
self.buildRecordInfo = initialState.buildRecordInfo
self.maybeBuildRecord = initialState.maybeBuildRecord
self.fileSystem = driver.fileSystem
self.showJobLifecycle = driver.showJobLifecycle
self.alwaysRebuildDependents = initialState.incrementalOptions.contains(
.alwaysRebuildDependents)
self.reporter = reporter
}
public func compute(batchJobFormer: inout Driver) throws -> FirstWave {
return try blockingConcurrentAccessOrMutation {
let (initiallySkippedCompileGroups, mandatoryJobsInOrder) =
try computeInputsAndGroups(batchJobFormer: &batchJobFormer)
return FirstWave(
initiallySkippedCompileGroups: initiallySkippedCompileGroups,
mandatoryJobsInOrder: mandatoryJobsInOrder)
}
}
}
}
extension IncrementalCompilationState.FirstWaveComputer: IncrementalCompilationSynchronizer {
var incrementalCompilationQueue: DispatchQueue {
moduleDependencyGraph.incrementalCompilationQueue
}
}
// MARK: - Preparing the first wave
extension IncrementalCompilationState.FirstWaveComputer {
/// At this stage the graph will have all external dependencies found in the swiftDeps or in the priors
/// listed in fingerprintExternalDependencies.
private func computeInputsAndGroups(batchJobFormer: inout Driver)
throws -> (initiallySkippedCompileGroups: [TypedVirtualPath: CompileJobGroup],
mandatoryJobsInOrder: [Job])
{
precondition(sourceFiles.disappeared.isEmpty, "unimplemented")
let compileGroups =
Dictionary(uniqueKeysWithValues:
jobsInPhases.compileGroups.map { ($0.primaryInput, $0) })
guard let buildRecord = maybeBuildRecord else {
func everythingIsMandatory()
throws -> (initiallySkippedCompileGroups: [TypedVirtualPath: CompileJobGroup],
mandatoryJobsInOrder: [Job])
{
let mandatoryCompileGroupsInOrder = sourceFiles.currentInOrder.compactMap {
input -> CompileJobGroup? in
compileGroups[input.typedFile]
}
let mandatoryJobsInOrder = try
jobsInPhases.beforeCompiles +
batchJobFormer.formBatchedJobs(
mandatoryCompileGroupsInOrder.flatMap {$0.allJobs()},
showJobLifecycle: showJobLifecycle)
moduleDependencyGraph.setPhase(to: .buildingAfterEachCompilation)
return (initiallySkippedCompileGroups: [:],
mandatoryJobsInOrder: mandatoryJobsInOrder)
}
return try everythingIsMandatory()
}
moduleDependencyGraph.setPhase(to: .updatingAfterCompilation)
let initiallySkippedInputs = computeInitiallySkippedCompilationInputs(
inputsInvalidatedByExternals: inputsInvalidatedByExternals,
moduleDependencyGraph,
buildRecord)
let initiallySkippedCompileGroups = compileGroups.filter { initiallySkippedInputs.contains($0.key) }
let mandatoryCompileGroupsInOrder = inputFiles.compactMap {
input -> CompileJobGroup? in
initiallySkippedInputs.contains(input)
? nil
: compileGroups[input]
}
let batchedCompilationJobs = try batchJobFormer.formBatchedJobs(
mandatoryCompileGroupsInOrder.flatMap {$0.allJobs()},
showJobLifecycle: showJobLifecycle)
// In the case where there are no compilation jobs to run on this build (no source-files were changed),
// we can skip running `beforeCompiles` jobs if we also ensure that none of the `afterCompiles` jobs
// have any dependencies on them.
let skipAllJobs = batchedCompilationJobs.isEmpty ? !nonVerifyAfterCompileJobsDependOnBeforeCompileJobs() : false
let mandatoryJobsInOrder = skipAllJobs ? [] : jobsInPhases.beforeCompiles + batchedCompilationJobs
return (initiallySkippedCompileGroups: initiallySkippedCompileGroups,
mandatoryJobsInOrder: mandatoryJobsInOrder)
}
/// Determine if any of the jobs in the `afterCompiles` group depend on outputs produced by jobs in
/// `beforeCompiles` group, which are not also verification jobs.
private func nonVerifyAfterCompileJobsDependOnBeforeCompileJobs() -> Bool {
let beforeCompileJobOutputs = jobsInPhases.beforeCompiles.reduce(into: Set<TypedVirtualPath>(),
{ (pathSet, job) in pathSet.formUnion(job.outputs) })
let afterCompilesDependnigJobs = jobsInPhases.afterCompiles.filter {postCompileJob in postCompileJob.inputs.contains(where: beforeCompileJobOutputs.contains)}
if afterCompilesDependnigJobs.isEmpty || afterCompilesDependnigJobs.allSatisfy({ $0.kind == .verifyModuleInterface }) {
return false
} else {
return true
}
}
/// Figure out which compilation inputs are *not* mandatory at the start
private func computeInitiallySkippedCompilationInputs(
inputsInvalidatedByExternals: TransitivelyInvalidatedSwiftSourceFileSet,
_ moduleDependencyGraph: ModuleDependencyGraph,
_ buildRecord: BuildRecord
) -> Set<TypedVirtualPath> {
let allGroups = jobsInPhases.compileGroups
// Input == source file
let changedInputs = computeChangedInputs(moduleDependencyGraph, buildRecord)
if let reporter = reporter {
for input in inputsInvalidatedByExternals {
reporter.report("Invalidated externally; will queue", input)
}
}
let inputsMissingFromGraph = sourceFiles.currentInOrder.filter { sourceFile in
!moduleDependencyGraph.containsNodes(forSourceFile: sourceFile)
}
if let reporter = reporter,
moduleDependencyGraph.phase == .buildingFromSwiftDeps {
for input in inputsMissingFromGraph {
reporter.report("Has malformed dependency source; will queue", input)
}
}
let inputsMissingOutputs = allGroups.compactMap {
$0.outputs.contains { (try? !fileSystem.exists($0.file)) ?? true }
? $0.primaryInput
: nil
}
if let reporter = reporter {
for input in inputsMissingOutputs {
reporter.report("Missing an output; will queue", input)
}
}
// Combine to obtain the inputs that definitely must be recompiled.
var definitelyRequiredInputs = Set(changedInputs.lazy.map {$0.typedFile})
definitelyRequiredInputs.formUnion(inputsInvalidatedByExternals.lazy.map {$0.typedFile})
definitelyRequiredInputs.formUnion(inputsMissingFromGraph.lazy.map {$0.typedFile})
definitelyRequiredInputs.formUnion(inputsMissingOutputs)
if let reporter = reporter {
for scheduledInput in sortByCommandLineOrder(definitelyRequiredInputs) {
reporter.report("Queuing (initial):", scheduledInput)
}
}
// Sometimes, inputs run in the first wave that depend on the changed inputs for the
// first wave, even though they may not require compilation.
// Any such inputs missed, will be found by the rereading of swiftDeps
// as each first wave job finished.
let speculativeInputs = collectInputsToBeSpeculativelyRecompiled(
changedInputs: changedInputs,
externalDependents: inputsInvalidatedByExternals,
inputsMissingOutputs: Set(inputsMissingOutputs),
moduleDependencyGraph)
.subtracting(definitelyRequiredInputs.swiftSourceFiles)
if let reporter = reporter {
for dependent in sortByCommandLineOrder(speculativeInputs) {
reporter.report("Queuing because of the initial set:", dependent)
}
}
let immediatelyCompiledInputs = definitelyRequiredInputs.union(speculativeInputs.lazy.map {$0.typedFile})
let initiallySkippedInputs = Set(buildRecordInfo.compilationInputModificationDates.keys)
.subtracting(immediatelyCompiledInputs)
if let reporter = reporter {
for skippedInput in sortByCommandLineOrder(initiallySkippedInputs) {
reporter.report("Skipping input:", skippedInput)
}
}
return initiallySkippedInputs
}
private func sortByCommandLineOrder(
_ inputs: Set<TypedVirtualPath>
) -> LazyFilterSequence<[TypedVirtualPath]> {
inputFiles.lazy.filter(inputs.contains)
}
private func sortByCommandLineOrder(
_ inputs: Set<SwiftSourceFile>
) -> LazyFilterSequence<[TypedVirtualPath]> {
inputFiles.lazy.filter {inputs.contains(SwiftSourceFile($0))}
}
/// Encapsulates information about an input the driver has determined has
/// changed in a way that requires an incremental rebuild.
struct ChangedInput {
/// The path to the input file.
let typedFile: TypedVirtualPath
/// The status of the input file.
let status: InputInfo.Status
/// If `true`, the modification time of this input matches the modification
/// time recorded from the prior build in the build record.
let datesMatch: Bool
}
// Find the inputs that have changed since last compilation, or were marked as needed a build
private func computeChangedInputs(
_ moduleDependencyGraph: ModuleDependencyGraph,
_ outOfDateBuildRecord: BuildRecord
) -> [ChangedInput] {
jobsInPhases.compileGroups.compactMap { group in
let input = group.primaryInput
let modDate = buildRecordInfo.compilationInputModificationDates[input] ?? .distantFuture
let inputInfo = outOfDateBuildRecord.inputInfos[input.file]
let previousCompilationStatus = inputInfo?.status ?? .newlyAdded
let previousModTime = inputInfo?.previousModTime
switch previousCompilationStatus {
case .upToDate where modDate == previousModTime:
reporter?.report("May skip current input:", input)
return nil
case .upToDate:
reporter?.report("Scheduling changed input", input)
case .newlyAdded:
reporter?.report("Scheduling new", input)
case .needsCascadingBuild:
reporter?.report("Scheduling cascading build", input)
case .needsNonCascadingBuild:
reporter?.report("Scheduling noncascading build", input)
}
return ChangedInput(typedFile: input,
status: previousCompilationStatus,
datesMatch: modDate == previousModTime)
}
}
// Returns the cascaded files to compile in the first wave, even though it may not be need.
// The needs[Non}CascadingBuild stuff was cargo-culted from the legacy driver.
// TODO: something better, e.g. return nothing here, but process changed dependencySource
// before the whole frontend job finished.
private func collectInputsToBeSpeculativelyRecompiled(
changedInputs: [ChangedInput],
externalDependents: TransitivelyInvalidatedSwiftSourceFileSet,
inputsMissingOutputs: Set<TypedVirtualPath>,
_ moduleDependencyGraph: ModuleDependencyGraph
) -> Set<SwiftSourceFile> {
let cascadingChangedInputs = computeCascadingChangedInputs(
from: changedInputs,
inputsMissingOutputs: inputsMissingOutputs)
var inputsToBeCertainlyRecompiled = Set(cascadingChangedInputs)
if alwaysRebuildDependents {
inputsToBeCertainlyRecompiled.formUnion(externalDependents.lazy.map {$0.typedFile})
}
return inputsToBeCertainlyRecompiled.reduce(into: Set()) {
speculativelyRecompiledInputs, certainlyRecompiledInput in
guard let certainlyRecompiledSwiftSourceFile = SwiftSourceFile(ifSource: certainlyRecompiledInput)
else {
return
}
let speculativeDependents = moduleDependencyGraph.collectInputsInvalidatedBy(changedInput: certainlyRecompiledSwiftSourceFile)
for speculativeDependent in speculativeDependents
where !inputsToBeCertainlyRecompiled.contains(speculativeDependent.typedFile) {
if speculativelyRecompiledInputs.insert(speculativeDependent).inserted {
reporter?.report(
"Immediately scheduling dependent on \(certainlyRecompiledInput.file.basename)",
speculativeDependent)
}
}
}
}
//Collect the files that will be compiled whose dependents should be schedule
private func computeCascadingChangedInputs(
from changedInputs: [ChangedInput],
inputsMissingOutputs: Set<TypedVirtualPath>
) -> [TypedVirtualPath] {
changedInputs.compactMap { changedInput in
let inputIsUpToDate =
changedInput.datesMatch && !inputsMissingOutputs.contains(changedInput.typedFile)
let basename = changedInput.typedFile.file.basename
// If we're asked to always rebuild dependents, all we need to do is
// return inputs whose modification times have changed.
guard !alwaysRebuildDependents else {
if inputIsUpToDate {
reporter?.report(
"not scheduling dependents of \(basename) despite -driver-always-rebuild-dependents because is up to date")
return nil
} else {
reporter?.report(
"scheduling dependents of \(basename); -driver-always-rebuild-dependents")
return changedInput.typedFile
}
}
switch changedInput.status {
case .needsCascadingBuild:
reporter?.report(
"scheduling dependents of \(basename); needed cascading build")
return changedInput.typedFile
case .upToDate:
reporter?.report(
"not scheduling dependents of \(basename); unknown changes")
return nil
case .newlyAdded:
reporter?.report(
"not scheduling dependents of \(basename): no entry in build record or dependency graph")
return nil
case .needsNonCascadingBuild:
reporter?.report(
"not scheduling dependents of \(basename): does not need cascading build")
return nil
}
}
}
}
|
apache-2.0
|
54cfbe9b80c7f89de1d759954f79e2a1
| 40.659401 | 162 | 0.721957 | 4.946296 | false | false | false | false |
jopamer/swift
|
test/SILGen/multi_file.swift
|
1
|
3080
|
// RUN: %target-swift-emit-silgen -module-name multi_file -enable-sil-ownership -primary-file %s %S/Inputs/multi_file_helper.swift | %FileCheck %s
func markUsed<T>(_ t: T) {}
// CHECK-LABEL: sil hidden @$S10multi_file12rdar16016713{{[_0-9a-zA-Z]*}}F
func rdar16016713(_ r: Range) {
// CHECK: [[LIMIT:%[0-9]+]] = function_ref @$S10multi_file5RangeV5limitSivg : $@convention(method) (Range) -> Int
// CHECK: {{%[0-9]+}} = apply [[LIMIT]]({{%[0-9]+}}) : $@convention(method) (Range) -> Int
markUsed(r.limit)
}
// CHECK-LABEL: sil hidden @$S10multi_file26lazyPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F
func lazyPropertiesAreNotStored(_ container: LazyContainer) {
var container = container
// CHECK: {{%[0-9]+}} = function_ref @$S10multi_file13LazyContainerV7lazyVarSivg : $@convention(method) (@inout LazyContainer) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @$S10multi_file29lazyRefPropertiesAreNotStored{{[_0-9a-zA-Z]*}}F
func lazyRefPropertiesAreNotStored(_ container: LazyContainerClass) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $LazyContainerClass):
// CHECK: {{%[0-9]+}} = class_method [[ARG]] : $LazyContainerClass, #LazyContainerClass.lazyVar!getter.1 : (LazyContainerClass) -> () -> Int, $@convention(method) (@guaranteed LazyContainerClass) -> Int
markUsed(container.lazyVar)
}
// CHECK-LABEL: sil hidden @$S10multi_file25finalVarsAreDevirtualizedyyAA18FinalPropertyClassCF
func finalVarsAreDevirtualized(_ obj: FinalPropertyClass) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $FinalPropertyClass):
// CHECK: ref_element_addr [[ARG]] : $FinalPropertyClass, #FinalPropertyClass.foo
markUsed(obj.foo)
// CHECK: class_method [[ARG]] : $FinalPropertyClass, #FinalPropertyClass.bar!getter.1
markUsed(obj.bar)
}
// rdar://18448869
// CHECK-LABEL: sil hidden @$S10multi_file34finalVarsDontNeedMaterializeForSetyyAA27ObservingPropertyFinalClassCF
func finalVarsDontNeedMaterializeForSet(_ obj: ObservingPropertyFinalClass) {
obj.foo += 1
// CHECK: [[T0:%.*]] = ref_element_addr %0 : $ObservingPropertyFinalClass, #ObservingPropertyFinalClass.foo
// CHECK-NEXT: [[T1:%.*]] = begin_access [read] [dynamic] [[T0]] : $*Int
// CHECK-NEXT: load [trivial] [[T1]] : $*Int
// CHECK: function_ref @$S10multi_file27ObservingPropertyFinalClassC3fooSivs
}
// rdar://18503960
// Ensure that we type-check the materializeForSet accessor from the protocol.
class HasComputedProperty: ProtocolWithProperty {
var foo: Int {
get { return 1 }
set {}
}
}
// CHECK-LABEL: sil hidden [transparent] @$S10multi_file19HasComputedPropertyC3fooSivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK-LABEL: sil private [transparent] [thunk] @$S10multi_file19HasComputedPropertyCAA012ProtocolWithE0A2aDP3fooSivmTW : $@convention(witness_method: ProtocolWithProperty) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasComputedProperty) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
|
apache-2.0
|
a0bb90d7ac5c0ed8b5f12ef90d6c9426
| 55 | 313 | 0.730844 | 3.507973 | false | false | false | false |
Authman2/Pix
|
Pix/FeedSectionController.swift
|
1
|
2267
|
//
// FeedSectionController.swift
// Pix
//
// Created by Adeola Uthman on 1/7/17.
// Copyright © 2017 Adeola Uthman. All rights reserved.
//
import UIKit
import IGListKit
import Hero
class FeedSectionController: IGListSectionController, IGListSectionType {
// The post object to display.
var post: Post?;
// A reference to the view controller.
var vc: UIViewController?;
init(vc: UIViewController) {
self.vc = vc;
}
func numberOfItems() -> Int {
return 1;
}
func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: (collectionContext?.containerSize.width)! - 20, height: 380);
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext!.dequeueReusableCell(of: FeedCell.self, for: self, at: index) as! FeedCell;
cell.post = post;
cell.vc = self.vc;
cell.imageView.image = cell.post.photo;
cell.captionLabel.text = "\(cell.post.caption!)";
cell.likesLabel.text = "Likes: \(cell.post.likes)";
cell.uploaderLabel.text = "\(cell.post.uploader.firstName) \(cell.post.uploader.lastName)";
return cell
}
func didUpdate(to object: Any) {
self.post = object as? Post;
}
func didSelectItem(at index: Int) {
let detail = PostDetailPage();
detail.post = self.post!;
detail.isHeroEnabled = true;
self.vc?.navigationItem.title = "";
if(navContr.open == true) { navContr.togglePulldownMenu(); }
UIView.animate(withDuration: 0.4, delay: 0, options: [], animations: {
self.vc?.navigationController?.navigationBar.alpha = 0;
self.vc?.navigationItem.titleView?.alpha = 0;
}, completion: { (finished: Bool) in
self.vc?.navigationController?.navigationBar.isHidden = true;
self.vc?.navigationItem.titleView?.isHidden = true;
})
Hero.shared.setDefaultAnimationForNextTransition(animations[0]);
Hero.shared.setContainerColorForNextTransition(detail.view.backgroundColor);
vc?.hero_replaceViewController(with: detail);
}
}
|
gpl-3.0
|
ce1948756fb2443468d3be99a18f653a
| 27.683544 | 112 | 0.608561 | 4.443137 | false | false | false | false |
PekanMmd/Pokemon-XD-Code
|
Objects/processes/Dolphin/ColoXD/Colosseum/context/CMBreakPoints.swift
|
1
|
25729
|
//
// CMBreakPoints.swift
// GoD Tool
//
// Created by Stars Momodu on 10/11/2021.
//
import Foundation
extension XDBreakPointTypes {
var addresses: [Int]? {
switch self {
case .onFrameAdvance:
switch region {
case .US: return [0x801bfd10]
default: return nil
}
case .onWillRenderFrame:
switch region {
case .US: return [0x801c0130]
default: return nil
}
case .onDidRNGRoll:
switch region {
case .US: return [0x801add08]
default: return nil
}
case .onWillGetFlag:
switch region {
case .US: return nil
default: return nil
}
case .onWillSetFlag:
switch region {
case .US: return nil
default: return nil
}
case .onStepCount:
switch region {
case .US: return [0x8012ef58]
default: return nil
}
case .onDidReadOrWriteSave:
switch region {
case .US: return [0x801d0a2c]
default: return nil
}
case .onWillWriteSave:
switch region {
case .US: return [0x801d0110, 0x801d0118]
default: return nil
}
case .onWillChangeMap:
switch region {
case .US: return [0x800ff730, 0x800ff58c]
default: return nil
}
case .onDidChangeMap:
switch region {
case .US: return [0x800ff63c]
default: return nil
}
case .onDidChangeMenuMap:
switch region {
case .US: return [0x800ff76c]
default: return nil
}
case .onDidConfirmMoveSelection:
switch region {
case .US: return [0x80204f6c]
default: return nil
}
case .onDidConfirmTurnSelection:
switch region {
case .US: return [0x8020505c]
default: return nil
}
case .onWillUseMove:
switch region {
case .US: return [0x80212974]
default: return nil
}
case .onMoveEnd:
switch region {
case .US: return [0x80212d68]
default: return nil
}
case .onWillCallPokemon:
switch region {
case .US: return [0x80212db0]
default: return nil
}
case .onPokemonWillSwitchIntoBattle:
switch region {
case .US: return nil
default: return nil
}
case .onShadowPokemonEncountered:
switch region {
case .US: return nil
default: return nil
}
case .onShadowPokemonFled:
switch region {
case .US: return nil
default: return nil
}
case .onShadowPokemonDidEnterReverseMode:
switch region {
case .US: return nil
default: return nil
}
case .onWillUseItem:
switch region {
case .US: return nil
default: return nil
}
case .onWillUseCologne:
switch region {
case .US: return nil
default: return nil
}
case .onWillUseTM:
switch region {
case .US: return nil
default: return nil
}
case .onDidUseTM:
switch region {
case .US: return nil
default: return nil
}
case .onWillGainExp:
switch region {
case .US: return nil
default: return nil
}
case .onLevelUp:
#warning("TODO: find a good way to break on level up")
return nil
case .onWillEvolve:
switch region {
case .US: return nil
default: return nil
}
case .onDidEvolve:
switch region {
case .US: return nil
default: return nil
}
case .onDidPurification:
switch region {
case .US: return nil
default: return nil
}
case .onWillStartBattle:
switch region {
case .US: return nil
default: return nil
}
case .onDidEndBattle:
switch region {
case .US: return nil
default: return nil
}
case .onBattleWhiteout:
switch region {
case .US: return nil
default: return nil
}
case .onBattleTurnStart:
switch region {
case .US: return nil
default: return nil
}
case .onBattleTurnEnd:
switch region {
case .US: return nil
default: return nil
}
case .onPokemonTurnStart:
switch region {
case .US: return nil
default: return nil
}
case .onPokemonTurnEnd:
switch region {
case .US: return nil
default: return nil
}
case .onBattleDamageOrHealing:
switch region {
case .US: return nil
default: return nil
}
case .onPokemonDidFaint:
switch region {
case .US: return nil
default: return nil
}
case .onWillAttemptPokemonCapture:
switch region {
case .US: return nil
default: return nil
}
case .onDidSucceedPokemonCapture:
switch region {
case .US: return nil
default: return nil
}
case .onDidFailPokemonCapture:
switch region {
case .US: return nil
default: return nil
}
case .onMirorRadarActiveAtColosseum:
switch region {
case .US: return nil
default: return nil
}
case .onMirorRadarActiveAtPokespot:
switch region {
case .US: return nil
default: return nil
}
case .onMirorRadarLostSignal:
switch region {
case .US: return nil
default: return nil
}
case .onSpotMonitorActivated:
switch region {
case .US: return nil
default: return nil
}
case .onWildBattleGenerated:
switch region {
case .US: return nil
default: return nil
}
case .onReceivedGiftPokemon:
switch region {
case .US: return nil
default: return nil
}
case .onReceivedItem:
#warning("TODO: research this")
return nil
case .onHealTeam:
#warning("TODO: research this")
return nil
case .onNewGameStart:
#warning("TODO: research this")
return nil
case .onDidPromptReleasePokemon:
switch region {
case .US: return [0x800557f0]
default: return nil
}
case .onDidReleasePokemon:
switch region {
case .US: return [0x80055800]
default: return nil
}
case .onPrint:
switch region {
case .US: return nil
default: return nil
}
case .onSoftReset:
switch region {
case .US: return nil
default: return nil
}
case .onInconsistentState:
return nil
case .yield:
return nil
case .forcedReturn:
return nil
case .clear:
return nil
}
}
var standardReturnOffset: Int? {
switch self {
default:
return nil
}
}
var forcedReturnValueAddress: Int? {
switch self {
case .onWillGetFlag:
switch region {
case .US: return nil
default: return nil
}
default:
return nil
}
}
}
class BreakPointContext: Codable {
fileprivate var forcedReturnValue: Int?
init() {}
init(process: XDProcess, registers: [Int: Int]) {}
func getRegisters() -> [Int: Int] { return [:] }
}
class RenderFrameBufferContext: BreakPointContext {
override init(process: XDProcess, registers: [Int: Int]) {
super.init()
}
override func getRegisters() -> [Int: Int] {
return [:]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class RNGRollContext: BreakPointContext {
var roll: UInt16 = 0
override init(process: XDProcess, registers: [Int: Int]) {
self.roll = UInt16(registers[3] ?? 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [3: Int(roll)]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
//class GetFlagContext: BreakPointContext {
// var flagID: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// flagID = registers[3] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: flagID]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//
// func setReturnValue(_ to: Int) {
// forcedReturnValue = to
// }
//
// func getForcedReturnValue() -> Int? {
// return forcedReturnValue
// }
//}
//
//class SetFlagContext: BreakPointContext {
// var flagID: Int
// var value: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// flagID = registers[3] ?? 0
// value = registers[4] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: flagID, 4: value]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
class StepCounterContext: BreakPointContext {
override init(process: XDProcess, registers: [Int: Int]) {
super.init()
}
override func getRegisters() -> [Int: Int] {
return [:]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class SaveReadOrWriteContext: BreakPointContext {
enum Status: Int, Codable {
case cancelled = -1, previouslyLoadedCleanSave = 1, readSuccessfully = 3, wroteSuccessfully = 4, firstLoadNoSaveData = 5, unknown = -2
}
var status: Status
override init(process: XDProcess, registers: [Int: Int]) {
status = Status(rawValue: registers[3] ?? 0) ?? .unknown
super.init()
}
override func getRegisters() -> [Int: Int] {
return [3: status.rawValue]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class MapOrMenuDidChangeContext: BreakPointContext {
var newRoom: XGRoom
private let isMenu: Bool
init(process: XDProcess, registers: [Int: Int], isMenu: Bool) {
newRoom = XGRoom.roomWithID(registers[isMenu ? 31: 28] ?? 0) ?? XGRoom(index: 0)
self.isMenu = isMenu
super.init()
}
override func getRegisters() -> [Int: Int] {
let index = isMenu ? 31: 28
return [index: newRoom.roomID]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class MapWillChangeContext: BreakPointContext {
var nextRoom: XGRoom
override init(process: XDProcess, registers: [Int: Int]) {
nextRoom = XGRoom.roomWithID(registers[3] ?? 0) ?? XGRoom(index: 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [3: nextRoom.roomID]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class BattleMoveSelectionContext: BreakPointContext {
enum Targets: Int, Codable {
case none = 0x0
case topFoe = 0x1
case topAlly = 0xC
case bottomAlly = 0xD
case bottomFoe = 0x10
}
let moveRoutinePointer: Int
var move: XGMoves
var targets: Targets
var selectedMoveIndex: Int
var pokemon: XDBattlePokemon
override init(process: XDProcess, registers: [Int: Int]) {
pokemon = XDBattlePokemon(file: process, offset: registers[3] ?? 0)
moveRoutinePointer = registers[7] ?? 0
move = .index( registers[8] ?? 0)
targets = Targets(rawValue: registers[9] ?? 0) ?? .none
if targets == .none {
printg("Undocumented move targets case \(registers[9] ?? 0) for move \(move.name.string)")
}
selectedMoveIndex = registers[10] ?? 0
super.init()
}
override func getRegisters() -> [Int: Int] {
return [
3: pokemon.battleDataOffset,
8: move.index,
9: targets.rawValue,
10: selectedMoveIndex
]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class BattleTurnSelectionContext: BreakPointContext {
enum Option: Codable {
case fight(move: XGMoves)
case item(item: XGItems)
case switchPokemon(index: Int)
case call
case unknown(id: Int, parameter: Int)
var optionID: Int {
switch self {
case .fight: return 19
case .item: return 18
case .switchPokemon: return 9
case .call: return 10
case .unknown(let id, _): return id
}
}
var parameter: Int {
switch self {
case .fight(let move): return move.index
case .item(let item): return item.index
case .switchPokemon(let index): return index
case .call: return 0
case .unknown(_, let param): return param
}
}
enum CodingKeys: String, CodingKey {
case type, parameter
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let type = try container.decode(Int.self, forKey: .type)
let parameter = try container.decode(Int.self, forKey: .parameter)
switch type {
case 19: self = .fight(move: .index(parameter))
case 18: self = .item(item: .index(parameter))
case 9: self = .switchPokemon(index: parameter)
case 10: self = .call
default: self = .unknown(id: type, parameter: parameter)
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(optionID, forKey: .type)
try container.encode(parameter, forKey: .parameter)
}
}
let moveRoutinePointer: Int
var pokemon: XDBattlePokemon
var option: Option
override init(process: XDProcess, registers: [Int: Int]) {
pokemon = XDBattlePokemon(file: process, offset: registers[3] ?? 0)
moveRoutinePointer = registers[7] ?? 0
let parameter = registers[8] ?? 0
let type = registers[5] ?? 0
switch type {
case 9: option = .switchPokemon(index: parameter)
case 10: option = .call
case 18: option = .item(item: .index(parameter))
case 19: option = .fight(move: .index(parameter))
default: option = .unknown(id: type, parameter: parameter)
}
super.init()
}
override func getRegisters() -> [Int: Int] {
return [
3: pokemon.battleDataOffset,
5: option.optionID,
8: option.parameter
]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class WillUseMoveContext: BreakPointContext {
var move: XGMoves
var attackingPokemon: XDBattlePokemon
override init(process: XDProcess, registers: [Int: Int]) {
move = .index(registers[24] ?? 0)
attackingPokemon = XDBattlePokemon(file: process, offset: registers[28] ?? 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [24: move.index, 28: attackingPokemon.battleDataOffset]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class WillCallPokemonContext: BreakPointContext {
var pokemon: XDBattlePokemon
override init(process: XDProcess, registers: [Int: Int]) {
pokemon = XDBattlePokemon(file: process, offset: registers[3] ?? 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [3: pokemon.battleDataOffset]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
//class PokemonSwitchInContext: BreakPointContext {
// var pokemon: XDBattlePokemon
// var trainer: XDTrainer?
// let trainerPointer: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[30] ?? 0)
// trainerPointer = registers[3] ?? 0
// trainer = XDTrainer(file: process, offset: trainerPointer)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: trainerPointer, 30: pokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class ShadowPokemonEncounterContext: BreakPointContext {
// var pokemon: XDBattlePokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[29] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [29: pokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class ShadowPokemonFledContext: BreakPointContext {
// var pokemon: XDPartyPokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDPartyPokemon(file: process, offset: registers[28] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [28: pokemon.partyDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class ReverseModeContext: BreakPointContext {
// var pokemon: XDBattlePokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[30] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [30: pokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class UseItemContext: BreakPointContext {
// var pokemon: XDBattlePokemon
// var item: XGItems
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[5] ?? 0)
// item = .index(registers[6] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [5: pokemon.battleDataOffset, 6: item.index]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class UseCologneContext: BreakPointContext {
// var partyPokemonIndex: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// partyPokemonIndex = registers[31] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [31: partyPokemonIndex]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class WillUseTMContext: BreakPointContext {
// var tm: XGTMs
// var hmIndex: Int
// var item: XGItems
//
// override init(process: XDProcess, registers: [Int: Int]) {
// item = .index(registers[25] ?? 0)
// tm = .tm(registers[29] ?? 0)
// hmIndex = registers[30] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [25: item.index, 29: tm.index, 30: hmIndex]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class DidUseTMContext: BreakPointContext {
// var tm: XGTMs
// var hmIndex: Int
// var item: XGItems
// var partyPokemonIndex: Int
// var wasSuccessful: Bool
//
// override init(process: XDProcess, registers: [Int: Int]) {
// item = .index(registers[25] ?? 0)
// wasSuccessful = (registers[26] ?? 0) == 1
// partyPokemonIndex = registers[27] ?? 0
// tm = .tm(registers[29] ?? 0)
// hmIndex = registers[30] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [25: item.index, 29: tm.index, 30: hmIndex]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class ExpGainContext: BreakPointContext {
// let pokemon: XDBattlePokemon
// var exp: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[19] ?? 0)
// exp = registers[18] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [18: exp, 19: pokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class WillEvolveContext: BreakPointContext {
// var pokemon: XDPartyPokemon
// let pokemonOffset: Int
// var evolvedForm: XGPokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemonOffset = registers[3] ?? 0
// pokemon = XDPartyPokemon(file: process, offset: pokemonOffset)
// evolvedForm = .index(registers[4] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: pokemonOffset, 4: evolvedForm.index]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class DidEvolveContext: BreakPointContext {
// var pokemon: XDPartyPokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDPartyPokemon(file: process, offset: registers[27] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [27: pokemon.partyDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class DidPurifyContext: BreakPointContext {
// var pokemon: XDPartyPokemon
// let pokemonOffset: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemonOffset = registers[31] ?? 0
// pokemon = XDPartyPokemon(file: process, offset: pokemonOffset)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [31: pokemonOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class BattleStartContext: BreakPointContext {
// var battle: XGBattle?
// let battleID: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// battleID = registers[3] ?? 0
// battle = XGBattle(index: battleID)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: battleID]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class BattleEndContext: BreakPointContext {
// var result: XGBattleResult?
//
// override init(process: XDProcess, registers: [Int: Int]) {
// result = XGBattleResult(rawValue: registers[3] ?? 0) ?? .unknown1
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// var registers: [Int: Int] = [:]
// if let result = result {
// registers[3] = result.rawValue
// }
// return registers
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class TurnStartContext: BreakPointContext {
// var pokemon: XDPartyPokemon
// let pokemonPointer: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemonPointer = registers[3] ?? 0
// pokemon = XDPartyPokemon(file: process, offset: pokemonPointer)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: pokemonPointer]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class BattleDamageHealingContext: BreakPointContext {
// var attackingPokemon: XDBattlePokemon
// var defendingPokemon: XDBattlePokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// attackingPokemon = XDBattlePokemon(file: process, offset: registers[26] ?? 0)
// defendingPokemon = XDBattlePokemon(file: process, offset: registers[29] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [26: attackingPokemon.battleDataOffset, 29: defendingPokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class PokemonFaintedContext: BreakPointContext {
// var attackingPokemon: XDBattlePokemon
// var defendingPokemon: XDBattlePokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// attackingPokemon = XDBattlePokemon(file: process, offset: registers[29] ?? 0)
// defendingPokemon = XDBattlePokemon(file: process, offset: registers[31] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [29: attackingPokemon.battleDataOffset, 31: defendingPokemon.battleDataOffset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class CaptureAttemptContext: BreakPointContext {
// var pokemon: XDPartyPokemon
// let pokemonOffset: Int
// var pokeball: XGItems
// var baseCatchRate: Int
// var shadowID: Int
// let shadowData: XGDeckPokemon
// let foeTrainer: XDTrainer
// var maxHP: Int
// var currentHP: Int
// var level: Int
// var roomType: Int
// var species: XGPokemon
//
// override init(process: XDProcess, registers: [Int: Int]) {
// species = .index(registers[19] ?? 0)
// maxHP = registers[20] ?? 0
// currentHP = registers[21] ?? 0
// level = registers[22] ?? 0
// roomType = registers[23] ?? 0
// pokemonOffset = registers[26] ?? 0
// pokemon = XDPartyPokemon(file: process, offset: pokemonOffset)
// pokeball = .index(registers[24] ?? 0)
// shadowID = registers[25] ?? 0
// shadowData = .ddpk(shadowID)
// baseCatchRate = registers[29] ?? 0
// foeTrainer = XDTrainer(file: process, offset: registers[30] ?? 0)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [
// 19: species.index,
// 20: maxHP,
// 21: currentHP,
// 22: level,
// 23: roomType,
// 24: pokeball.index,
// 25: shadowID,
// 26: pokemonOffset,
// 29: baseCatchRate
// ]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class CaptureAttemptedContext: BreakPointContext {
// var pokemon: XDBattlePokemon
// let numberOfShakes: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// pokemon = XDBattlePokemon(file: process, offset: registers[27] ?? 0)
// numberOfShakes = registers[28] ?? 0
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [27: pokemon.battleDataOffset, 28: numberOfShakes]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//
//class ReceiveGiftPokemonContext: BreakPointContext {
// let pokemon: XGGiftPokemon
// var giftID: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// giftID = registers[3] ?? 0
// pokemon = XGGiftPokemonManager.giftWithID(giftID)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: giftID]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class PrintContext: BreakPointContext {
// var offset: Int
// let string: String
//
// override init(process: XDProcess, registers: [Int: Int]) {
// offset = registers[3] ?? 0
// string = offset > 0x80000000 ? process.readString(atAddress: offset, charLength: .char) : ""
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [3: offset]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
//
//class WildBattleContext: BreakPointContext {
// var trainer: XDTrainer?
// let trainerPointer: Int
//
// override init(process: XDProcess, registers: [Int: Int]) {
// trainerPointer = registers[26] ?? 0
// trainer = XDTrainer(file: process, offset: trainerPointer)
// super.init()
// }
//
// override func getRegisters() -> [Int: Int] {
// return [26: trainerPointer]
// }
//
// required init(from decoder: Decoder) throws { fatalError("-") }
//}
class ConfirmPokemonReleaseContext: BreakPointContext {
var shouldRelease: Bool
var pokemon: XDPartyPokemon
override init(process: XDProcess, registers: [Int: Int]) {
shouldRelease = registers[3]?.boolean ?? false
pokemon = XDPartyPokemon(file: process, offset: registers[31] ?? 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [3: shouldRelease ? 1 : 0, 31: pokemon.partyDataOffset]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
class PokemonReleaseContext: BreakPointContext {
var pokemon: XDPartyPokemon
override init(process: XDProcess, registers: [Int: Int]) {
pokemon = XDPartyPokemon(file: process, offset: registers[31] ?? 0)
super.init()
}
override func getRegisters() -> [Int: Int] {
return [31: pokemon.partyDataOffset]
}
required init(from decoder: Decoder) throws { fatalError("-") }
}
|
gpl-2.0
|
68596fe10cf077b7c91968bbbc96d419
| 23.739423 | 136 | 0.666641 | 3.048099 | false | false | false | false |
vsqweHCL/DouYuZB
|
DouYuZB/DouYuZB/Classs/Home/Controller/HomeViewController.swift
|
1
|
4033
|
//
// HomeViewController.swift
// DouYuZB
//
// Created by HCL黄 on 16/11/3.
// Copyright © 2016年 HCL黄. All rights reserved.
//
import UIKit
private let kTitleViewH: CGFloat = 40
class HomeViewController: UIViewController {
// MARK:- 懒加载PageTitleView
fileprivate lazy var pageTitleView: PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
// MARK:- 懒加载PageContentView
fileprivate lazy var pageContentView: PageContentView = {[weak self] in
// 1.确定内容的frame
let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTabBarH
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
// 2.确定所有的子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
childVcs.append(AmuseViewController())
childVcs.append(FunnyViewController())
// for _ in 0..<1 {
// let vc = UIViewController()
// vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
// childVcs.append(vc)
// }
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
// MARK:- 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
// 设置UI界面
setupUI()
}
}
extension HomeViewController {
fileprivate func setupUI() {
// 0.不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
// 1.设置导航栏
setupNavigationBar()
// 2.添加TitleView
view.addSubview(pageTitleView)
// 3.添加ContentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.purple
}
fileprivate func setupNavigationBar() {
// 1.设置左侧的Item
let btn = UIButton()
btn.setImage(UIImage(named: "logo"), for: UIControlState())
btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
// 2.设置右侧的Item
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem.createItem("image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem.createItem("btn_search", highImageName: "btn_search_clicked", size: size)
// let qrcodeItem = UIBarButtonItem.createItem("Image_scan", highImageName: "Image_scan_click", size: size)
// 构造函数
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem,qrcodeItem]
}
}
// MARK:- 遵守PageTitleViewDelegate,为了给pageContentView传递值
extension HomeViewController: PageTitleViewDelegate {
func pageTitleView(_ titleView: PageTitleView, selectIndex index: Int) {
pageContentView.setCurrentIndex(index)
}
}
// MARK:- 遵守PageContentViewDelegate,为了给pageTitleView传递值
extension HomeViewController: PageContentViewDelegate {
func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgess(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
|
mit
|
00ff309b781023522ecad9f09274a653
| 32.478261 | 158 | 0.651429 | 5.02611 | false | false | false | false |
faimin/ZDOpenSourceDemo
|
ZDOpenSourceSwiftDemo/Pods/Cartography/Cartography/Constrain.swift
|
6
|
14066
|
//
// Constrain.swift
// Cartography
//
// Created by Robert Böhnke on 30/09/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
import Foundation
/// Removes all constraints for a group.
///
/// - parameter clear: The `ConstraintGroup` whose constraints should be removed.
///
public func constrain(clear group: ConstraintGroup) {
group.replaceConstraints([])
}
/// Updates the constraints of a single layout item.
///
/// - parameter item: The item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem>(_ item: A, replace group: ConstraintGroup = .init(), block: (A.ProxyType) -> Void) -> ConstraintGroup {
let proxy = item.asProxy()
block(proxy)
group.replaceConstraints(proxy.context.constraints)
return group
}
/// Updates the constraints of two layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem>(_ item1: A, _ item2: B, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
block(proxy1, proxy2)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of three layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
block(proxy1, proxy2, proxy3)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of four layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of five layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of six layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter item6: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem, F: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, _ item6: F, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType, F.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
let proxy6 = item6.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5, proxy6)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of seven layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter item6: An item to layout.
/// - parameter item7: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem, F: LayoutItem, G: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, _ item6: F, _ item7: G, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType, F.ProxyType, G.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
let proxy6 = item6.asProxy(context: ctx)
let proxy7 = item7.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5, proxy6, proxy7)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of eight layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter item6: An item to layout.
/// - parameter item7: An item to layout.
/// - parameter item8: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem, F: LayoutItem, G: LayoutItem, H: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, _ item6: F, _ item7: G, _ item8: H, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType, F.ProxyType, G.ProxyType, H.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
let proxy6 = item6.asProxy(context: ctx)
let proxy7 = item7.asProxy(context: ctx)
let proxy8 = item8.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5, proxy6, proxy7, proxy8)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of nine layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter item6: An item to layout.
/// - parameter item7: An item to layout.
/// - parameter item8: An item to layout.
/// - parameter item9: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem, F: LayoutItem, G: LayoutItem, H: LayoutItem, I: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, _ item6: F, _ item7: G, _ item8: H, _ item9: I, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType, F.ProxyType, G.ProxyType, H.ProxyType, I.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
let proxy6 = item6.asProxy(context: ctx)
let proxy7 = item7.asProxy(context: ctx)
let proxy8 = item8.asProxy(context: ctx)
let proxy9 = item9.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5, proxy6, proxy7, proxy8, proxy9)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of ten layout items.
///
/// - parameter item1: An item to layout.
/// - parameter item2: An item to layout.
/// - parameter item3: An item to layout.
/// - parameter item4: An item to layout.
/// - parameter item5: An item to layout.
/// - parameter item6: An item to layout.
/// - parameter item7: An item to layout.
/// - parameter item8: An item to layout.
/// - parameter item9: An item to layout.
/// - parameter item10: An item to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `item`.
///
@discardableResult public func constrain<A: LayoutItem, B: LayoutItem, C: LayoutItem, D: LayoutItem, E: LayoutItem, F: LayoutItem, G: LayoutItem, H: LayoutItem, I: LayoutItem, J: LayoutItem>(_ item1: A, _ item2: B, _ item3: C, _ item4: D, _ item5: E, _ item6: F, _ item7: G, _ item8: H, _ item9: I, _ item10: J, replace group: ConstraintGroup = .init(), block: (A.ProxyType, B.ProxyType, C.ProxyType, D.ProxyType, E.ProxyType, F.ProxyType, G.ProxyType, H.ProxyType, I.ProxyType, J.ProxyType) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy1 = item1.asProxy(context: ctx)
let proxy2 = item2.asProxy(context: ctx)
let proxy3 = item3.asProxy(context: ctx)
let proxy4 = item4.asProxy(context: ctx)
let proxy5 = item5.asProxy(context: ctx)
let proxy6 = item6.asProxy(context: ctx)
let proxy7 = item7.asProxy(context: ctx)
let proxy8 = item8.asProxy(context: ctx)
let proxy9 = item9.asProxy(context: ctx)
let proxy10 = item10.asProxy(context: ctx)
block(proxy1, proxy2, proxy3, proxy4, proxy5, proxy6, proxy7, proxy8, proxy9, proxy10)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of an array of layout items.
///
/// - parameter items: The items to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `items`.
///
@discardableResult public func constrain<T: LayoutItem>(_ items: [T], replace group: ConstraintGroup = .init(), block: ([T.ProxyType]) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy = items.map { $0.asProxy(context: ctx) }
block(proxy)
group.replaceConstraints(ctx.constraints)
return group
}
/// Updates the constraints of a dictionary of layout items.
///
/// - parameter items: The items to layout.
/// - parameter replace: The `ConstraintGroup` whose constraints should be
/// replaced.
/// - parameter block: A block that declares the layout for `items`.
///
@discardableResult public func constrain<T, U: LayoutItem>(_ items: [T: U], replace group: ConstraintGroup = .init(), block: ([T: U.ProxyType]) -> Void) -> ConstraintGroup {
let ctx = Context()
let proxy: [T: U.ProxyType] = items.mapValues { $0.asProxy(context: ctx) }
block(proxy)
group.replaceConstraints(ctx.constraints)
return group
}
|
mit
|
a1a1d995a9e6ed6b3d3d54c5f1829af6
| 41.489426 | 521 | 0.658276 | 3.578626 | false | false | false | false |
volodg/iAsync.social
|
Pods/ReactiveKit/ReactiveKit/Observable/Observable.swift
|
1
|
1973
|
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public protocol ObservableType: StreamType {
typealias Value
var value: Value { get set }
}
public final class Observable<Value>: ActiveStream<Value>, ObservableType {
private var _value: Value
public var value: Value {
get {
return _value
}
set {
_value = newValue
super.next(newValue)
}
}
public init(_ value: Value) {
_value = value
super.init()
}
public override func next(event: Value) {
value = event
}
public override func observe(on context: ExecutionContext? = ImmediateOnMainExecutionContext, observer: Observer) -> DisposableType {
let disposable = super.observe(on: context, observer: observer)
observer(value)
return disposable
}
public func silentUpdate(value: Value) {
_value = value
}
}
|
mit
|
fa999817c6336d062476f8661836bdf7
| 30.822581 | 135 | 0.713634 | 4.298475 | false | false | false | false |
boolkybear/ChromaProjectApp
|
ChromaProjectApp/ChromaProjectApp/NSUserDefaults.swift
|
1
|
1501
|
//
// NSUserDefaults.swift
// ChromaProjectApp
//
// Created by Boolky Bear on 25/12/14.
// Copyright (c) 2014 ByBDesigns. All rights reserved.
//
import Foundation
enum SaveSettings: Int
{
case NotConfigured = 0
case SaveLocally = 1
case SaveInCloud = 2
}
let saveSettingsKey = "saveSettingsKey"
let ubiquityTokenKey = "ubiquityTokenKey"
extension NSUserDefaults
{
class func saveSettings() -> SaveSettings
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let currentSettings = userDefaults.integerForKey(saveSettingsKey)
return SaveSettings(rawValue: currentSettings)!
}
class func setSaveSettings(settings: SaveSettings)
{
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setInteger(settings.rawValue, forKey: saveSettingsKey)
}
class func ubiquityToken() -> AnyObject?
{
let userDefaults = NSUserDefaults.standardUserDefaults()
let tokenData = userDefaults.objectForKey(ubiquityTokenKey) as? NSData
let token: AnyObject? = tokenData != nil ? NSKeyedUnarchiver.unarchiveObjectWithData(tokenData!) : nil
return token
}
class func setUbiquityToken(token: protocol<NSCoding, NSCopying, NSObjectProtocol>?)
{
let userDefaults = NSUserDefaults.standardUserDefaults()
if let token = token
{
let tokenData = NSKeyedArchiver.archivedDataWithRootObject(token)
userDefaults.setObject(tokenData, forKey: ubiquityTokenKey)
}
else
{
userDefaults.removeObjectForKey(ubiquityTokenKey)
}
}
}
|
mit
|
d435e4c827a955016593b56084af1b1c
| 22.46875 | 104 | 0.758827 | 4.123626 | false | false | false | false |
SECH-Tag-EEXCESS-Browser/iOSX-App
|
Team UI/Browser/Browser/AdressBar.swift
|
1
|
1532
|
//
// AdressBar.swift
// Browser
//
// Created by Andreas Ziemer on 11.11.15.
// Copyright © 2015 SECH-Tag-EEXCESS-Browser. All rights reserved.
//
import Foundation
class AddressBar{
func checkURL(url : String) -> String{
let checkedURL: String?
if(validateHTTPWWW(url) || validateHTTP(url)){
checkedURL = url
}else if(validateWWW(url)){
checkedURL = "https://" + url
}else{
let searchString = url.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil)
checkedURL = "https://www.google.de/#q=\(searchString)"
}
return checkedURL!
}
func validateHTTP (stringURL : NSString) -> Bool
{
let urlRegEx = "((https|http)://).*"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluateWithObject(stringURL)
}
func validateWWW (stringURL : NSString) -> Bool
{
let urlRegEx = "((\\w|-)+)(([.]|[/])((\\w|-)+)).*"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluateWithObject(stringURL)
}
func validateHTTPWWW (stringURL : NSString) -> Bool
{
let urlRegEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+)).*"
let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[urlRegEx])
return predicate.evaluateWithObject(stringURL)
}
}
|
mit
|
150308bd3114d123cfdc1d3762a0f6c3
| 33.044444 | 152 | 0.597649 | 4.264624 | false | false | false | false |
stripe/stripe-ios
|
StripePaymentSheet/StripePaymentSheet/PaymentSheet/PaymentSheet+SwiftUI.swift
|
1
|
16845
|
//
// PaymentSheet+SwiftUI.swift
// StripePaymentSheet
//
// Created by David Estes on 1/14/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
// This is adapted from a strategy used in BetterSafariView by Dongkyu Kim.
// https://github.com/stleamist/BetterSafariView
//
import SwiftUI
@available(iOS 13.0, *)
@available(iOSApplicationExtension, unavailable)
@available(macCatalystApplicationExtension, unavailable)
extension View {
/// Presents a sheet for a customer to complete their payment.
/// - Parameter isPresented: A binding to whether the sheet is presented.
/// - Parameter paymentSheet: A PaymentSheet to present.
/// - Parameter onCompletion: Called with the result of the payment after the payment sheet is dismissed.
public func paymentSheet(
isPresented: Binding<Bool>,
paymentSheet: PaymentSheet,
onCompletion: @escaping (PaymentSheetResult) -> Void
) -> some View {
self.modifier(
PaymentSheet.PaymentSheetPresentationModifier(
isPresented: isPresented,
paymentSheet: paymentSheet,
onCompletion: onCompletion
)
)
}
/// Presents a sheet for a customer to select a payment option.
/// - Parameter isPresented: A binding to whether the sheet is presented.
/// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present.
/// - Parameter onSheetDismissed: Called after the payment options sheet is dismissed.
public func paymentOptionsSheet(
isPresented: Binding<Bool>,
paymentSheetFlowController: PaymentSheet.FlowController,
onSheetDismissed: (() -> Void)?
) -> some View {
self.modifier(
PaymentSheet.PaymentSheetFlowControllerPresentationModifier(
isPresented: isPresented,
paymentSheetFlowController: paymentSheetFlowController,
action: .presentPaymentOptions,
optionsCompletion: onSheetDismissed,
paymentCompletion: nil
)
)
}
/// Confirm the payment, presenting a sheet for the user to confirm their payment if needed.
/// - Parameter isConfirming: A binding to whether the payment is being confirmed. This will present a sheet if needed. It will be updated to `false` after performing the payment confirmation.
/// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present.
/// - Parameter onCompletion: Called with the result of the payment after the payment confirmation is done and the sheet (if any) is dismissed.
public func paymentConfirmationSheet(
isConfirming: Binding<Bool>,
paymentSheetFlowController: PaymentSheet.FlowController,
onCompletion: @escaping (PaymentSheetResult) -> Void
) -> some View {
self.modifier(
PaymentSheet.PaymentSheetFlowControllerPresentationModifier(
isPresented: isConfirming,
paymentSheetFlowController: paymentSheetFlowController,
action: .confirm,
optionsCompletion: nil,
paymentCompletion: onCompletion
)
)
}
/// :nodoc:
@available(
*, deprecated,
renamed: "paymentConfirmationSheet(isConfirming:paymentSheetFlowController:onCompletion:)"
)
public func paymentConfirmationSheet(
isConfirmingPayment: Binding<Bool>,
paymentSheetFlowController: PaymentSheet.FlowController,
onCompletion: @escaping (PaymentSheetResult) -> Void
) -> some View {
return paymentConfirmationSheet(
isConfirming: isConfirmingPayment,
paymentSheetFlowController: paymentSheetFlowController,
onCompletion: onCompletion
)
}
}
@available(iOS 13.0, *)
@available(iOSApplicationExtension, unavailable)
@available(macCatalystApplicationExtension, unavailable)
extension PaymentSheet {
/// A button which presents a sheet for a customer to complete their payment.
/// This is a convenience wrapper for the .paymentSheet() ViewModifier.
/// - Parameter paymentSheet: A PaymentSheet to present.
/// - Parameter onCompletion: Called with the result of the payment after the payment sheet is dismissed.
/// - Parameter content: The content of the view.
public struct PaymentButton<Content: View>: View {
private let paymentSheet: PaymentSheet
private let onCompletion: (PaymentSheetResult) -> Void
private let content: Content
@State private var showingPaymentSheet = false
/// Initialize a `PaymentButton` with required parameters.
public init(
paymentSheet: PaymentSheet,
onCompletion: @escaping (PaymentSheetResult) -> Void,
@ViewBuilder content: () -> Content
) {
self.paymentSheet = paymentSheet
self.onCompletion = onCompletion
self.content = content()
}
public var body: some View {
Button(action: {
showingPaymentSheet = true
}) {
content
}.paymentSheet(
isPresented: $showingPaymentSheet,
paymentSheet: paymentSheet,
onCompletion: onCompletion)
}
}
}
@available(iOS 13.0, *)
@available(iOSApplicationExtension, unavailable)
@available(macCatalystApplicationExtension, unavailable)
extension PaymentSheet.FlowController {
/// A button which presents a sheet for a customer to select a payment method.
/// This is a convenience wrapper for the .paymentOptionsSheet() ViewModifier.
/// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present.
/// - Parameter onSheetDismissed: Called after the payment method selector is dismissed.
/// - Parameter content: The content of the view.
public struct PaymentOptionsButton<Content: View>: View {
private let paymentSheetFlowController: PaymentSheet.FlowController
private let onSheetDismissed: () -> Void
private let content: Content
@State private var showingPaymentSheet = false
/// Initialize a `PaymentOptionsButton` with required parameters.
public init(
paymentSheetFlowController: PaymentSheet.FlowController,
onSheetDismissed: @escaping () -> Void,
@ViewBuilder content: () -> Content
) {
self.paymentSheetFlowController = paymentSheetFlowController
self.onSheetDismissed = onSheetDismissed
self.content = content()
}
public var body: some View {
Button(action: {
showingPaymentSheet = true
}) {
content
}.paymentOptionsSheet(
isPresented: $showingPaymentSheet,
paymentSheetFlowController: paymentSheetFlowController,
onSheetDismissed: onSheetDismissed)
}
}
/// :nodoc:
@available(*, deprecated, renamed: "ConfirmButton")
public typealias ConfirmPaymentButton = ConfirmButton
/// A button which confirms the payment or setup. Depending on the user's payment method, it may present a confirmation sheet.
/// This is a convenience wrapper for the .paymentConfirmationSheet() ViewModifier.
/// - Parameter paymentSheetFlowController: A PaymentSheet.FlowController to present.
/// - Parameter onCompletion: Called with the result of the payment/setup confirmation, after the PaymentSheet (if any) is dismissed.
/// - Parameter content: The content of the view.
public struct ConfirmButton<Content: View>: View {
private let paymentSheetFlowController: PaymentSheet.FlowController
private let onCompletion: (PaymentSheetResult) -> Void
private let content: Content
@State private var showingPaymentSheet = false
/// Initialize a `ConfirmPaymentButton` with required parameters.
public init(
paymentSheetFlowController: PaymentSheet.FlowController,
onCompletion: @escaping (PaymentSheetResult) -> Void,
@ViewBuilder content: () -> Content
) {
self.paymentSheetFlowController = paymentSheetFlowController
self.onCompletion = onCompletion
self.content = content()
}
public var body: some View {
Button(action: {
showingPaymentSheet = true
}) {
content
}.paymentConfirmationSheet(
isConfirming: $showingPaymentSheet,
paymentSheetFlowController: paymentSheetFlowController,
onCompletion: onCompletion)
}
}
}
@available(iOS 13.0, *)
@available(iOSApplicationExtension, unavailable)
@available(macCatalystApplicationExtension, unavailable)
extension PaymentSheet {
struct PaymentSheetPresenter: UIViewRepresentable {
@Binding var presented: Bool
weak var paymentSheet: PaymentSheet?
let onCompletion: (PaymentSheetResult) -> Void
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
func makeUIView(context: Context) -> UIView {
return context.coordinator.view
}
func updateUIView(_ uiView: UIView, context: Context) {
context.coordinator.parent = self
context.coordinator.presented = presented
}
class Coordinator {
var parent: PaymentSheetPresenter
let view = UIView()
var presented: Bool {
didSet {
switch (oldValue, presented) {
case (false, false):
break
case (false, true):
guard let viewController = findViewController(for: view) else {
parent.presented = false
return
}
presentPaymentSheet(on: viewController)
case (true, false):
guard let viewController = findViewController(for: view) else {
parent.presented = true
return
}
forciblyDismissPaymentSheet(from: viewController)
case (true, true):
break
}
}
}
init(parent: PaymentSheetPresenter) {
self.parent = parent
self.presented = parent.presented
}
func presentPaymentSheet(on controller: UIViewController) {
let presenter = findViewControllerPresenter(from: controller)
parent.paymentSheet?.present(from: presenter) { (result: PaymentSheetResult) in
self.parent.presented = false
self.parent.onCompletion(result)
}
}
func forciblyDismissPaymentSheet(from controller: UIViewController) {
if let bsvc = controller.presentedViewController as? BottomSheetViewController {
bsvc.didTapOrSwipeToDismiss()
}
}
}
}
struct PaymentSheetFlowControllerPresenter: UIViewRepresentable {
@Binding var presented: Bool
weak var paymentSheetFlowController: PaymentSheet.FlowController?
let action: FlowControllerAction
let optionsCompletion: (() -> Void)?
let paymentCompletion: ((PaymentSheetResult) -> Void)?
func makeCoordinator() -> Coordinator {
return Coordinator(parent: self)
}
func makeUIView(context: Context) -> UIView {
return context.coordinator.view
}
func updateUIView(_ uiView: UIView, context: Context) {
context.coordinator.parent = self
context.coordinator.presented = presented
}
class Coordinator {
var parent: PaymentSheetFlowControllerPresenter
let view = UIView()
var presented: Bool {
didSet {
switch (oldValue, presented) {
case (false, false):
break
case (false, true):
guard let viewController = findViewController(for: view) else {
parent.presented = false
return
}
presentPaymentSheet(on: viewController)
case (true, false):
guard let viewController = findViewController(for: view) else {
parent.presented = true
return
}
forciblyDismissPaymentSheet(from: viewController)
case (true, true):
break
}
}
}
init(parent: PaymentSheetFlowControllerPresenter) {
self.parent = parent
self.presented = parent.presented
}
func presentPaymentSheet(on controller: UIViewController) {
let presenter = findViewControllerPresenter(from: controller)
switch parent.action {
case .confirm:
parent.paymentSheetFlowController?.confirm(from: presenter) { (result) in
self.parent.presented = false
self.parent.paymentCompletion?(result)
}
case .presentPaymentOptions:
parent.paymentSheetFlowController?.presentPaymentOptions(from: presenter) {
self.parent.presented = false
self.parent.optionsCompletion?()
}
}
}
func forciblyDismissPaymentSheet(from controller: UIViewController) {
if let bsvc = controller.presentedViewController as? BottomSheetViewController {
bsvc.didTapOrSwipeToDismiss()
}
}
}
}
struct PaymentSheetPresentationModifier: ViewModifier {
@Binding var isPresented: Bool
let paymentSheet: PaymentSheet
let onCompletion: (PaymentSheetResult) -> Void
func body(content: Content) -> some View {
content.background(
PaymentSheetPresenter(
presented: $isPresented,
paymentSheet: paymentSheet,
onCompletion: onCompletion
)
)
}
}
enum FlowControllerAction {
case presentPaymentOptions
case confirm
}
struct PaymentSheetFlowControllerPresentationModifier: ViewModifier {
@Binding var isPresented: Bool
let paymentSheetFlowController: PaymentSheet.FlowController
let action: FlowControllerAction
let optionsCompletion: (() -> Void)?
let paymentCompletion: ((PaymentSheetResult) -> Void)?
func body(content: Content) -> some View {
content.background(
PaymentSheetFlowControllerPresenter(
presented: $isPresented,
paymentSheetFlowController: paymentSheetFlowController,
action: action,
optionsCompletion: optionsCompletion,
paymentCompletion: paymentCompletion
)
)
}
}
}
// MARK: - Helper functions
func findViewControllerPresenter(from uiViewController: UIViewController) -> UIViewController {
// Note: creating a UIViewController inside here results in a nil window
// This is a bit of a hack: We traverse the view hierarchy looking for the most reasonable VC to present from.
// A VC hosted within a SwiftUI cell, for example, doesn't have a parent, so we need to find the UIWindow.
var presentingViewController: UIViewController =
uiViewController.view.window?.rootViewController ?? uiViewController
// Find the most-presented UIViewController
while let presented = presentingViewController.presentedViewController {
presentingViewController = presented
}
return presentingViewController
}
func findViewController(for uiView: UIView) -> UIViewController? {
if let nextResponder = uiView.next as? UIViewController {
return nextResponder
} else if let nextResponder = uiView.next as? UIView {
return findViewController(for: nextResponder)
} else {
return nil
}
}
|
mit
|
de783b258f5c72de907411182eb4051a
| 38.172093 | 196 | 0.611137 | 5.94774 | false | false | false | false |
BenziAhamed/Nevergrid
|
NeverGrid/Source/GameHintsNode.swift
|
1
|
5445
|
//
// GameHintsNode.swift
// NeverGrid
//
// Created by Benzi on 15/10/14.
// Copyright (c) 2014 Benzi Ahamed. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
class GameHintsNode: SKNode {
required init?(coder:NSCoder) {
super.init(coder: coder)
}
weak var gameScene:GameScene?
var hintsButton:WobbleButton!
var hintsButtonPosition:CGPoint!
var nextButton:WobbleButton!
var hintsNode:HintNode!
var nextButtonPosition:CGPoint!
var showing:Bool = false
var shouldLoadAtGameStart:Bool = false
var hasContent:Bool = false
init(gameScene:GameScene) {
super.init()
// find out if this level has hints
// if not, we are simply an empty node
let level = gameScene.world.level.info
// does this level have hints?
// if so we need to add a hint node
if GameLevelHints.sharedInstance.hasHints(level) {
self.gameScene = gameScene
self.hasContent = true
let hints = GameLevelHints.sharedInstance.getHints(level)
let gameSettings = GameSettings()
if gameSettings.hintsShown[level.number] == nil {
shouldLoadAtGameStart = true
gameSettings.hintsShown[level.number] = true
gameSettings.save()
}
// since we have hints for this level
// create the buttons
hintsNode = HintNode(hints: hints, frame: gameScene.frame)
hintsNode.alpha = 0.0
self.addChild(hintsNode)
// next button
let next = textSprite("okay")
nextButton = WobbleButton(node: next, action: Callback(self,GameHintsNode.displayNextHint))
nextButtonPosition = CGPointMake(
gameScene.frame.maxX - next.frame.width - 10.0,
next.frame.height
)
nextButton.position = nextButtonPosition.offset(dx: 0.0, dy: -2.0*next.frame.height)
self.addChild(nextButton)
// hints button
let help = textSprite("help_mini")
//let edgeSpace:CGFloat = factor(forPhone: 5.0, forPad: 10.0)
// top right
//hintsButtonPosition = CGPointMake(
// gameScene.frame.maxX - edgeSpace - help.frame.width/2.0,
// gameScene.frame.height - help.frame.height/2.0 - edgeSpace
//)
hintsButtonPosition = CGPointMake(gameScene.frame.maxX - help.frame.width, gameScene.frame.height - help.frame.height)
hintsButton = WobbleButton(node: help, action: Callback(self, GameHintsNode.show))
hintsButton.position = hintsButtonPosition.offset(dx: 0.0, dy: 2.0*hintsButton.containedNode.frame.height)
gameScene.hudNode.addChild(hintsButton)
// add to hud node directly as we move position when hide() and show() is called
self.position = CGPointMake(gameScene.frame.maxX, 0.0)
}
}
func showHintsButton() {
hintsButton.runAction(
SKAction.moveByX(0.0, y: -2.0*hintsButton.containedNode.frame.height, duration: 0.3)
.followedBy(ActionFactory.sharedInstance.bounce)
)
}
func hideHintsButton() {
hintsButton.runAction(
SKAction.moveByX(0.0, y: -0.2*hintsButton.containedNode.frame.height, duration: 0.2).timing(SKActionTimingMode.EaseIn)
.followedBy(SKAction.moveByX(0.0, y: 2.2*hintsButton.containedNode.frame.height, duration: 0.3).timing(SKActionTimingMode.EaseIn))
)
}
func displayNextHint() {
if hintsNode.hasFurtherHints() {
hintsNode.displayHint()
} else {
hintsNode.reset()
hide()
}
}
func show() {
if showing { return }
showing = true
gameScene!.ignoreTouches = true
gameScene!.pauseGameNode.hidePauseButton()
hideHintsButton()
// set our position to normal
self.position = CGPointZero
// show overlay
gameScene!.overlay.runAction(SKAction.fadeAlphaTo(0.5, duration: 0.3))
// show hints
hintsNode.runAction(SKAction.fadeInWithDuration(0.3))
hintsNode.displayHint()
// show next button
nextButton.runAction(
SKAction.waitForDuration(0.3)
.followedBy(SKAction.moveTo(nextButtonPosition, duration: 0.2))
.followedBy(ActionFactory.sharedInstance.bounce)
)
}
func hide() {
if !showing { return }
showing = false
gameScene!.ignoreTouches = false
gameScene!.pauseGameNode.showPauseButton()
// hide overlay
gameScene!.overlay.runAction(SKAction.fadeOutWithDuration(0.3))
// hide hints
hintsNode.runAction(SKAction.fadeOutWithDuration(0.3)) {
// move ourself out of the way
[weak self] in
self!.position = CGPointMake(self!.gameScene!.frame.maxX, 0.0)
}
// hide next button
nextButton.runAction(
SKAction.moveByX(0.0, y: -2.0*nextButton.containedNode.frame.height, duration: 0.2)
)
showHintsButton()
}
}
|
isc
|
edecc5150ce996831684408fcf791ca1
| 32.617284 | 146 | 0.58641 | 4.492574 | false | false | false | false |
argent-os/argent-ios
|
app-ios/Notification.swift
|
1
|
3076
|
//
// History.swift
// argent-ios
//
// Created by Sinan Ulkuatam on 4/22/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import SwiftyJSON
import Alamofire
class NotificationItem {
let id: String
let type: String
let created: String
required init(id: String, type: String, created: String) {
self.id = id
self.type = type
self.created = created
}
class func getNotificationList(limit: String, starting_after: String, completionHandler: ([NotificationItem]?, NSError?) -> Void) {
// request to api to get data as json, put in list and table
// check for token, get profile id based on token and make the request
if(userAccessToken != nil) {
User.getProfile({ (user, error) in
if error != nil {
print(error)
}
let parameters : [String : AnyObject] = [:]
let headers = [
"Authorization": "Bearer " + (userAccessToken as! String),
"Content-Type": "application/x-www-form-urlencoded"
]
let limit = limit
let user_id = (user?.id)
let starting_after = starting_after
var endpoint = API_URL + "/stripe/" + user_id! + "/events"
if starting_after != "" {
endpoint = API_URL + "/stripe/" + user_id! + "/events?limit=" + limit + "&starting_after=" + starting_after
} else {
endpoint = API_URL + "/stripe/" + user_id! + "/events?limit=" + limit
}
Alamofire.request(.GET, endpoint, parameters: parameters, encoding: .URL, headers: headers)
.validate().responseJSON { response in
switch response.result {
case .Success:
if let value = response.result.value {
let data = JSON(value)
var notificationItemsArray = [NotificationItem]()
let events = data["events"]["data"].arrayValue
for event in events {
let id = event["id"].stringValue
let type = event["type"].stringValue
let created = event["created"].stringValue
let item = NotificationItem(id: id, type: type, created: created)
notificationItemsArray.append(item)
}
completionHandler(notificationItemsArray, response.result.error)
}
case .Failure(let error):
print(error)
}
}
})
}
}
}
|
mit
|
e5ceb485fa4b45c4a6c8f6a924140e65
| 38.948052 | 135 | 0.457561 | 5.570652 | false | false | false | false |
ello/ello-ios
|
Specs/Controllers/Stream/StreamViewControllerSpec.swift
|
1
|
1929
|
////
/// StreamViewControllerSpec.swift
//
@testable import Ello
import Quick
import Nimble
import SSPullToRefresh
class StreamViewControllerSpec: QuickSpec {
override func spec() {
var controller: StreamViewController!
beforeEach {
controller = StreamViewController()
showController(controller)
}
describe("StreamViewController") {
describe("hasCellItems(for:)") {
it("returns 'false' if 0 items") {
expect(controller.hasCellItems(for: .streamItems)) == false
}
it("returns 'false' if 1 placeholder item") {
controller.appendStreamCellItems([
StreamCellItem(type: .placeholder, placeholderType: .streamItems)
])
expect(controller.hasCellItems(for: .streamItems)) == false
}
it("returns 'true' if 1 jsonable item") {
controller.appendStreamCellItems([
StreamCellItem(type: .streamLoading, placeholderType: .streamItems)
])
expect(controller.hasCellItems(for: .streamItems)) == true
}
it("returns 'true' if more than 1 jsonable item") {
controller.appendStreamCellItems([
StreamCellItem(type: .streamLoading, placeholderType: .streamItems),
StreamCellItem(type: .streamLoading, placeholderType: .streamItems),
])
expect(controller.hasCellItems(for: .streamItems)) == true
}
}
context("responder chain") {
it("reassigns next responder to PostbarController") {
expect(controller.next) === controller.postbarController
}
}
}
}
}
|
mit
|
4cbe285bae7dfb31d1a1d8acd301923a
| 34.722222 | 92 | 0.5324 | 5.464589 | false | false | false | false |
liuCodeBoy/Ant
|
Ant/Ant/LunTan/Public/ListCell/LunTanListWithAvatarCell.swift
|
1
|
1693
|
//
// HuseNeedRentCell.swift
// Ant
//
// Created by LiuXinQiang on 2017/7/20.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class LunTanListWithAvatarCell: UITableViewCell {
var avatarClick: (() -> Void)?
@IBOutlet weak var title: UILabel!
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var createTime: UILabel!
@IBOutlet weak var lable1: UILabel!
@IBOutlet weak var lable2: UILabel!
@IBOutlet weak var lable3: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
changeBorderLineStyle(target: lable1, borderColor: .lightGray)
changeBorderLineStyle(target: lable2, borderColor: skyblue)
changeBorderLineStyle(target: lable3, borderColor: .red)
let tap = UITapGestureRecognizer(target: self, action: #selector(avatarDidClicked))
avatar.addGestureRecognizer(tap)
}
func avatarDidClicked() {
if avatarClick != nil {
avatarClick!()
}
}
var viewModel: LunTanDetialModel? {
didSet {
if let title = viewModel?.title {
self.title.text = title
}
if let name = viewModel?.contact_name {
self.name.text = name
}
if let time = viewModel?.time {
self.createTime.text = "\(time)"
}
if let lable1 = viewModel?.house_type {
self.lable1.text = lable1
}
if let lable2 = viewModel?.house_source {
self.lable2.text = lable2
}
}
}
}
|
apache-2.0
|
a0a55395fbc5c8cce08062c386ce6eb3
| 25.40625 | 91 | 0.574556 | 4.555256 | false | false | false | false |
Esri/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Layers/Symbolize shapefile/SymbolizeShapefileViewController.swift
|
1
|
2952
|
// Copyright 2017 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import ArcGIS
class SymbolizeShapefileViewController: UIViewController {
@IBOutlet weak var mapView: AGSMapView!
var featureLayer: AGSFeatureLayer?
override func viewDidLoad() {
super.viewDidLoad()
// Instantiate a map using a basemap.
let map = AGSMap(basemapStyle: .arcGISStreets)
// Create a shapefile feature table from a named bundle resource.
let shapefileTable = AGSShapefileFeatureTable(name: "Subdivisions")
// Create a feature layer for the shapefile feature table.
let shapefileLayer = AGSFeatureLayer(featureTable: shapefileTable)
// Add the layer to the map.
map.operationalLayers.add(shapefileLayer)
// Display the map in the map view.
mapView.map = map
// Zoom the map to the Shapefile's extent.
zoom(mapView: mapView, to: shapefileLayer)
// Hold on to the layer to set its symbology later.
featureLayer = shapefileLayer
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["SymbolizeShapefileViewController"]
}
func zoom(mapView: AGSMapView, to featureLayer: AGSFeatureLayer) {
// Ensure the feature layer's metadata is loaded.
featureLayer.load { error in
guard error == nil else {
print("Couldn't load the shapefile \(error!.localizedDescription)")
return
}
// Once the layer's metadata has loaded, we can read its full extent.
if let initialExtent = featureLayer.fullExtent {
mapView.setViewpointGeometry(initialExtent)
}
}
}
@IBAction func setShapefileSymbol(_ sender: Any) {
if let layer = featureLayer {
// Create a new yellow fill symbol with a red outline.
let outlineSymbol = AGSSimpleLineSymbol(style: .solid, color: .red, width: 1)
let fillSymbol = AGSSimpleFillSymbol(style: .solid, color: .yellow, outline: outlineSymbol)
// Create a new renderer using this symbol and set it on the layer.
layer.renderer = AGSSimpleRenderer(symbol: fillSymbol)
}
}
}
|
apache-2.0
|
3c94ed495716311aa48ad81cd55ce9a5
| 38.36 | 125 | 0.646003 | 4.863262 | false | false | false | false |
qasim/CDFLabs
|
CDFLabs/Printers/PrinterViewController.swift
|
1
|
3753
|
//
// PrinterViewController.swift
// CDFLabs
//
// Created by Qasim on 2016-04-01.
// Copyright © 2016 Qasim Iqbal. All rights reserved.
//
import UIKit
import Just
import KLCPopup
class PrinterViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var contentViewController: UIViewController?
var refreshControl: UIRefreshControl?
var refreshButton: UIBarButtonItem?
var printer: Printer?
var row: Int = 0
var printjobData: [PrintJob] = []
var tableView: UITableView?
init(printer: Printer, row: Int) {
super.init(nibName: nil, bundle: nil)
self.printer = printer
self.row = row
self.printjobData = printer.jobs
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func loadView() {
super.loadView()
self.loadContentView()
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.title = printer?.name
self.refreshButton = UIBarButtonItem(barButtonSystemItem: .Refresh, target: self,
action: #selector(self.refresh as Void -> Void))
self.navigationItem.rightBarButtonItem = self.refreshButton!
}
func loadContentView() {
self.loadTableView()
self.view.addSubview(self.tableView!)
let viewsDict: [String: AnyObject] = [
"tableView": self.tableView!
]
let options = NSLayoutFormatOptions(rawValue: 0)
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|[tableView]|", options: options, metrics: nil, views: viewsDict))
self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[tableView]|", options: options, metrics: nil, views: viewsDict))
}
func loadTableView() {
self.tableView = CLTableView()
self.tableView?.estimatedRowHeight = CLTable.printerCellHeight
self.tableView?.rowHeight = UITableViewAutomaticDimension
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(self.refresh(_:)),
forControlEvents: .ValueChanged)
self.tableView?.addSubview(refreshControl!)
self.tableView?.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return printjobData.count
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return PrinterJobViewCell(job: self.printjobData[indexPath.row])
}
func tableView(tableView: UITableView,
heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return CLTable.cellHeight + CLTable.cellPadding + 6
}
func refresh() {
self.tableView?.setContentOffset(
CGPointMake(0,
self.tableView!.contentOffset.y - self.refreshControl!.frame.size.height),
animated: true)
self.refreshControl!.beginRefreshing()
self.refresh(self.refreshControl!)
}
func refresh(refreshControl: UIRefreshControl) {
let printersViewController = self.navigationController as? PrintersViewController
let printjobData = printersViewController!.refresh(self.row)
CATransaction.begin()
CATransaction.setCompletionBlock({
self.printjobData = printjobData
self.tableView?.reloadData()
})
refreshControl.endRefreshing()
CATransaction.commit()
}
}
|
mit
|
277ca6a84ed8557f9697a4cd43487fe4
| 30.529412 | 93 | 0.655917 | 5.232915 | false | false | false | false |
qasim/CDFLabs
|
CDFLabs/Locations/BahenLocationViewCell.swift
|
1
|
8042
|
//
// BahenLocationView.swift
// CDFLabs
//
// Created by Qasim Iqbal on 1/5/16.
// Copyright © 2016 Qasim Iqbal. All rights reserved.
//
import UIKit
class BahenLocationViewCell: UITableViewCell {
init() {
super.init(style: .Default, reuseIdentifier: "Bahen")
self.backgroundColor = UIColor.cdfGreyColor()
let insetView = self.createInsetView()
self.addSubview(insetView)
let viewsDict: [String: AnyObject] = [
"insetView": insetView
]
let metricsDict: [String: AnyObject] = [
"cellPadding": CLTable.cellPadding
]
let options = NSLayoutFormatOptions(rawValue: 0)
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-cellPadding-[insetView]-cellPadding-|", options: options, metrics: metricsDict, views: viewsDict))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[insetView]-cellPadding-|", options: options, metrics: metricsDict, views: viewsDict))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func createInsetView() -> UIView {
let insetView = UIView(frame: UIScreen().bounds)
insetView.translatesAutoresizingMaskIntoConstraints = false
insetView.backgroundColor = UIColor.whiteColor()
insetView.layer.cornerRadius = CLTable.cellCornerRadius
let titleLabel = UILabel()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.textColor = UIColor.blackColor()
titleLabel.font = UIFont.systemFontOfSize(24.0, weight: UIFontWeightLight)
titleLabel.lineBreakMode = .ByWordWrapping
titleLabel.numberOfLines = 0
titleLabel.text = "Bahen Centre for Information Technology"
insetView.addSubview(titleLabel)
let locationPinIcon = UIImageView(image: UIImage(named: "LocationPinIcon"))
locationPinIcon.translatesAutoresizingMaskIntoConstraints = false
insetView.addSubview(locationPinIcon)
let locationLabel = UILabel()
locationLabel.translatesAutoresizingMaskIntoConstraints = false
locationLabel.textColor = UIColor.grayColor()
locationLabel.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightLight)
let tapListener = UITapGestureRecognizer(target: self, action: #selector(self.openMaps))
tapListener.numberOfTapsRequired = 1
locationLabel.addGestureRecognizer(tapListener)
locationLabel.userInteractionEnabled = true
locationLabel.text = "40 St George Street, Toronto, ON M5S 2E4"
insetView.addSubview(locationLabel)
let descriptionLabel = UILabel()
descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
descriptionLabel.textColor = UIColor.blackColor()
descriptionLabel.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightLight)
descriptionLabel.lineBreakMode = .ByWordWrapping
descriptionLabel.numberOfLines = 0
descriptionLabel.text = "The Bahen Centre hosts the majority of the CDF labs, highlighted below."
descriptionLabel.setLineHeight(1.1)
insetView.addSubview(descriptionLabel)
let secondFloorLabel = UILabel()
secondFloorLabel.translatesAutoresizingMaskIntoConstraints = false
secondFloorLabel.textColor = UIColor.grayColor()
secondFloorLabel.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightLight)
secondFloorLabel.text = "Second floor"
insetView.addSubview(secondFloorLabel)
let secondFloorImage = UIImageView(image: UIImage(named: "BahenSecondFloor"))
secondFloorImage.translatesAutoresizingMaskIntoConstraints = false
secondFloorImage.contentMode = .ScaleAspectFit
insetView.addSubview(secondFloorImage)
let thirdFloorLabel = UILabel()
thirdFloorLabel.translatesAutoresizingMaskIntoConstraints = false
thirdFloorLabel.textColor = UIColor.grayColor()
thirdFloorLabel.font = UIFont.systemFontOfSize(16.0, weight: UIFontWeightLight)
thirdFloorLabel.text = "Third floor"
insetView.addSubview(thirdFloorLabel)
let thirdFloorImage = UIImageView(image: UIImage(named: "BahenThirdFloor"))
thirdFloorImage.translatesAutoresizingMaskIntoConstraints = false
thirdFloorImage.contentMode = .ScaleAspectFit
insetView.addSubview(thirdFloorImage)
let viewsDict: [String: AnyObject] = [
"insetView": insetView,
"titleLabel": titleLabel,
"locationPinIcon": locationPinIcon,
"locationLabel": locationLabel,
"descriptionLabel": descriptionLabel,
"secondFloorLabel": secondFloorLabel,
"secondFloorImage": secondFloorImage,
"thirdFloorLabel": thirdFloorLabel,
"thirdFloorImage": thirdFloorImage
]
let metricsDict: [String: AnyObject] = [
"cellPadding": CLTable.cellPadding,
"cellHeight": CLTable.cellHeight,
"secondFloorHeight": secondFloorImage.fittedSize.height + 32,
"thirdFloorHeight": thirdFloorImage.fittedSize.height + 32
]
let options = NSLayoutFormatOptions(rawValue: 0)
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[titleLabel]-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[locationPinIcon]-[locationLabel]", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:[titleLabel]-10-[locationPinIcon]", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[descriptionLabel]-16-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[secondFloorLabel]-16-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[secondFloorImage]-16-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[thirdFloorLabel]-16-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"|-16-[thirdFloorImage]-16-|", options: options, metrics: metricsDict, views: viewsDict))
insetView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-14-[titleLabel]-cellPadding-[locationLabel]-[descriptionLabel]-32-[secondFloorLabel]-[secondFloorImage(secondFloorHeight)]-32-[thirdFloorLabel]-[thirdFloorImage(thirdFloorHeight)]|", options: options, metrics: metricsDict, views: viewsDict))
return insetView
}
func openMaps() {
if UIApplication.sharedApplication().canOpenURL(NSURL(string: "comgooglemaps://")!) {
UIApplication.sharedApplication().openURL(NSURL(string:
"comgooglemaps://?q=Bahen+Centre+for+Information+Technology")!)
} else {
UIApplication.sharedApplication().openURL(NSURL(string:
"http://maps.apple.com/?q=Bahen+Centre+for+Information+Technology")!)
}
}
override func setSelected(selected: Bool, animated: Bool) {
// Do nothing
}
override func setHighlighted(highlighted: Bool, animated: Bool) {
// Do nothing
}
}
|
mit
|
b11c5878733b7ac203be9a5d4b385224
| 45.212644 | 258 | 0.680139 | 5.393025 | false | false | false | false |
SuPair/VPNOn
|
VPNOnData/VPNDataManager+VPN.swift
|
1
|
6526
|
//
// VPNDataManager+VPN.swift
// VPN On
//
// Created by Lex Tang on 12/5/14.
// Copyright (c) 2014 LexTang.com. All rights reserved.
//
import CoreData
import VPNOnKit
extension VPNDataManager
{
func allVPN() -> [VPN]
{
var vpns = [VPN]()
let request = NSFetchRequest(entityName: "VPN")
let sortByTitle = NSSortDescriptor(key: "title", ascending: true)
let sortByServer = NSSortDescriptor(key: "server", ascending: true)
let sortByType = NSSortDescriptor(key: "ikev2", ascending: false)
request.sortDescriptors = [sortByTitle, sortByServer, sortByType]
if let moc = managedObjectContext {
if let results = (try? moc.executeFetchRequest(request)) as! [VPN]? {
for vpn in results {
if vpn.deleted {
continue
}
vpns.append(vpn)
}
}
}
return vpns
}
func createVPN(
title: String,
server: String,
account: String,
password: String,
group: String,
secret: String,
alwaysOn: Bool = true,
ikev2: Bool = false,
certificateURL: String?,
certificate: NSData?
) -> VPN?
{
let entity = NSEntityDescription.entityForName("VPN", inManagedObjectContext: managedObjectContext!)
let vpn = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedObjectContext!) as! VPN
vpn.title = title
vpn.server = server
vpn.account = account
vpn.group = group
vpn.alwaysOn = alwaysOn
vpn.ikev2 = ikev2
vpn.certificateURL = certificateURL
var error: NSError?
do {
try managedObjectContext!.save()
saveContext()
if !vpn.objectID.temporaryID {
VPNKeychainWrapper.setPassword(password, forVPNID: vpn.ID)
VPNKeychainWrapper.setSecret(secret, forVPNID: vpn.ID)
VPNKeychainWrapper.setCertificate(certificate, forVPNID: vpn.ID)
if allVPN().count == 1 {
VPNManager.sharedManager.activatedVPNID = vpn.ID
}
return vpn
}
} catch var error1 as NSError {
error = error1
debugPrint("Could not save VPN \(error), \(error?.userInfo)")
}
return .None
}
func deleteVPN(vpn:VPN)
{
let objectID = vpn.objectID
let ID = "\(vpn.ID)"
VPNKeychainWrapper.destoryKeyForVPNID(ID)
managedObjectContext!.deleteObject(vpn)
var saveError: NSError?
do {
try managedObjectContext!.save()
} catch var error as NSError {
saveError = error
}
saveContext()
if let activatedVPNID = VPNManager.sharedManager.activatedVPNID {
if activatedVPNID == ID {
VPNManager.sharedManager.activatedVPNID = nil
var vpns = allVPN()
if let firstVPN = vpns.first {
VPNManager.sharedManager.activatedVPNID = firstVPN.ID
}
}
}
}
func VPNByID(ID: NSManagedObjectID) -> VPN?
{
var error: NSError?
if ID.temporaryID {
return .None
}
var result: NSManagedObject?
do {
result = try managedObjectContext?.existingObjectWithID(ID)
} catch let error1 as NSError {
error = error1
result = nil
}
if let vpn = result {
if !vpn.deleted {
managedObjectContext?.refreshObject(vpn, mergeChanges: true)
return vpn as? VPN
}
} else {
debugPrint("Fetch error: \(error)")
return .None
}
return .None
}
func VPNByIDString(ID: String) -> VPN?
{
if let URL = NSURL(string: ID) {
if let scheme = URL.scheme {
if scheme.lowercaseString == "x-coredata" {
if let moid = persistentStoreCoordinator!.managedObjectIDForURIRepresentation(URL) {
return VPNByID(moid)
}
}
}
}
return .None
}
func VPNByPredicate(predicate: NSPredicate) -> [VPN]
{
var vpns = [VPN]()
var request = NSFetchRequest(entityName: "VPN")
request.predicate = predicate
var error: NSError?
let fetchResults = managedObjectContext!.executeFetchRequest(request) as! [VPN]?
if let results = fetchResults {
for vpn in results {
if vpn.deleted {
continue
}
vpns.append(vpn)
}
} else {
debugPrint("Failed to fetch VPNs: \(error?.localizedDescription)")
}
return vpns
}
func VPNBeginsWithTitle(title: String) -> [VPN]
{
let titleBeginsWithPredicate = NSPredicate(format: "title beginswith[cd] %@", argumentArray: [title])
return VPNByPredicate(titleBeginsWithPredicate)
}
func VPNHasTitle(title: String) -> [VPN]
{
let titleBeginsWithPredicate = NSPredicate(format: "title == %@", argumentArray: [title])
return VPNByPredicate(titleBeginsWithPredicate)
}
func duplicate(vpn: VPN) -> VPN?
{
let duplicatedVPNs = VPNDataManager.sharedManager.VPNBeginsWithTitle(vpn.title)
if duplicatedVPNs.count > 0 {
let newTitle = "\(vpn.title) \(duplicatedVPNs.count)"
VPNKeychainWrapper.passwordForVPNID(vpn.ID)
return createVPN(
newTitle,
server: vpn.server,
account: vpn.account,
password: VPNKeychainWrapper.passwordStringForVPNID(vpn.ID) ?? "",
group: vpn.group,
secret: VPNKeychainWrapper.secretStringForVPNID(vpn.ID) ?? "",
alwaysOn: vpn.alwaysOn,
ikev2: vpn.ikev2,
certificateURL: vpn.certificateURL,
certificate: VPNKeychainWrapper.certificateForVPNID(vpn.ID)
)
}
return .None
}
}
|
mit
|
f947c71d7d714cb003e4703bdab63b4e
| 29.783019 | 113 | 0.528501 | 5.2083 | false | false | false | false |
gewill/Feeyue
|
Feeyue/Main/Weibo/Views/StatusCell.swift
|
1
|
1493
|
//
// StatusCell.swift
// Feeyue
//
// Created by Will on 1/14/16.
// Copyright © 2016 gewill.org. All rights reserved.
//
import UIKit
@objc protocol StatusCellDelegate {
@objc optional func didClickAvatar(_ cell: StatusCell)
}
class StatusCell: UITableViewCell {
@IBOutlet var avatarImageView: UIImageView!
@IBOutlet var userNameLabel: UILabel!
@IBOutlet var createdAtLabel: UILabel!
@IBOutlet var sourceLabel: UILabel!
@IBOutlet var statusTextLabel: KILabel!
var statusId: Int = 0
var delegate: StatusCellDelegate?
override func awakeFromNib() {
super.awakeFromNib()
self.statusTextLabel.adjustsFontSizeToFitWidth = false
self.avatarImageView.layer.cornerRadius = self.avatarImageView.bounds.width / 2
self.avatarImageView.layer.borderWidth = 0.1
self.avatarImageView.layer.borderColor = .none
self.avatarImageView.clipsToBounds = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(StatusCell.tapping(_:)))
tapGesture.numberOfTapsRequired = 1
self.avatarImageView.addGestureRecognizer(tapGesture)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
// MARK: - StatusCellDelegate
@objc func tapping(_ recognizer: UIGestureRecognizer) {
self.delegate?.didClickAvatar!(self)
}
}
|
mit
|
e9596616bafefc56fdb50f7c3bc2c570
| 27.692308 | 104 | 0.676273 | 4.924092 | false | false | false | false |
Seachaos/HurryPorter_iOS
|
Example/HurryPorter/ViewController.swift
|
2
|
6473
|
//
// ViewController.swift
// HurryPorter
//
// Created by Seachaos on 02/25/2016.
// Copyright (c) 2016 Seachaos. All rights reserved.
//
import UIKit
class HookTestCheckResponse : HurryPorterHookDelegateCheckResponse{
func verifyData(porter: HurryPorter, json: [String : AnyObject]?, raw: String) -> Bool {
NSLog("on hook.verifyData:" + raw)
guard let dict = json else{
return false
}
if let status = dict["status"] as? NSNumber{
let code = status.integerValue
if code == 1000 {
return true
}
}
if let status = dict["status"] as? String{
if status == "1000"{
return true
}
}
return false
}
func errorMessage(porter: HurryPorter, json: [String : AnyObject]?, raw: String) -> String? {
return "Just Error"
}
}
class HookTestPrepare : HurryPorterHookDelegatePrepareData{
func willBeSent(porter: HurryPorter, json: [String : AnyObject]) -> [String : AnyObject] {
var dict = json
dict["status"] = 1000
return dict
}
}
class ViewController: UIViewController {
let checker = HookTestCheckResponse()
let prepare = HookTestPrepare()
let uobjc = UsingInOBJC()
override func viewDidLoad() {
super.viewDidLoad()
HurryPorterHook.global.prepareData = prepare
HurryPorterHook.global.checkResponse = checker
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.view.backgroundColor = UIColor.grayColor()
appendButton("[Test Request]", action:"doRequestTest", y:50)
appendButton("[Test HOOK]", action:"doRequestHookTest", y:120)
appendButton("[HOOK and Prepare]", action:"doRequestHookAndPrepareTest", y:190)
appendButton("[Test Request RM HOOK]", action:"doRequestRemoveHookTest", y:260)
appendButton("[Test Request OBJC]", action:"doRequestTestOBJ", y:330)
}
func appendButton(name:String, action:String, y:CGFloat){
let btn = UIButton()
btn.setTitle(name, forState: UIControlState.Normal)
btn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
btn.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
btn.backgroundColor = UIColor.whiteColor()
btn.frame = CGRectMake(50, y, 200, 50)
if(NSString(string: name).length>20){
btn.titleLabel?.font = UIFont.systemFontOfSize(UIFont.smallSystemFontSize())
}
self.view.addSubview(btn)
}
func doRequestRemoveHookTest(){
let dialog = UIAlertView()
dialog.title = "Busy"
dialog.show()
let porter = HurryPorter()
porter.makeRequest( {
(porter)->[String:AnyObject] in
var dict = [String:AnyObject]()
dict["name"] = "Hurry"
dict["value"] = "Porter"
porter.checkResponse = nil
porter.prepareData = nil
return dict
}, onSuccess: {
(porter, json, raw) in
NSLog("success:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, onFailed: {
(porter, raw, status) in
NSLog("failed:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, href: "http://www.myandroid.tw/test/post.php");
}
func doRequestTest(){
let dialog = UIAlertView()
dialog.title = "Busy"
dialog.show()
let porter = HurryPorter()
porter.prepareData = nil
porter.makeRequest( {
(porter)->[String:AnyObject] in
var dict = [String:AnyObject]()
dict["name"] = "Hurry"
dict["value"] = "Porter"
return dict
}, onSuccess: {
(porter, json, raw) in
NSLog("success:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, onFailed: {
(porter, raw, status) in
NSLog("failed:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, href: "http://www.myandroid.tw/test/post.php");
}
func doRequestHookTest(){
let dialog = UIAlertView()
dialog.title = "Busy"
dialog.show()
let porter = HurryPorter()
porter.checkResponse = self.checker
porter.makeRequest( {
(porter)->[String:AnyObject] in
var dict = [String:AnyObject]()
dict["name"] = "Hurry"
dict["value"] = "Porter"
return dict
}, onSuccess: {
(porter, json, raw) in
NSLog("success:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, onFailed: {
(porter, raw, status) in
NSLog("failed:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, href: "http://www.myandroid.tw/test/post.php");
}
func doRequestHookAndPrepareTest(){
let dialog = UIAlertView()
dialog.title = "Busy"
dialog.show()
let porter = HurryPorter()
porter.makeRequest( {
(porter)->[String:AnyObject] in
porter.prepareData = self.prepare
var dict = [String:AnyObject]()
dict["name"] = "Hurry"
dict["value"] = "Porter"
return dict
}, onSuccess: {
(porter, json, raw) in
NSLog("success:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, onFailed: {
(porter, raw, status) in
NSLog("failed:" + raw)
dialog.dismissWithClickedButtonIndex(0, animated: true)
}, href: "http://www.myandroid.tw/test/post.php");
}
func doRequestTestOBJ(){
uobjc.testHurryPorter()
}
}
|
mit
|
3e866d030bd262e013ffb1deaeb32efc
| 32.890052 | 102 | 0.553685 | 4.485793 | false | true | false | false |
s1Moinuddin/TextFieldWrapper
|
TextFieldWrapper/Classes/Protocols/Shakeable.swift
|
2
|
1516
|
//
// Shakeable.swift
// TextFieldWrapper
//
// Created by Shuvo on 7/29/17.
// Copyright © 2017 Shuvo. All rights reserved.
//
import UIKit
public protocol Shakeable {}
public extension Shakeable where Self:UIView {
public func shake(borderColor color: UIColor = .clear, borderWidth width: CGFloat = 2, completion: @escaping (() -> ())) {
CATransaction.begin()
CATransaction.setCompletionBlock { [weak self] in
self?.layer.borderColor = UIColor.clear.cgColor
self?.layer.borderWidth = 0
self?.layer.cornerRadius = 0
self?.layer.isOpaque = false
completion()
}
shake(borderColor: color, borderWidth: width)
CATransaction.commit()
}
public func shake(borderColor color: UIColor = .clear, borderWidth width: CGFloat = 2) {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 5
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 5.0, y: self.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 5.0, y: self.center.y))
layer.borderColor = color.cgColor
layer.borderWidth = width
layer.cornerRadius = 4.0
//layer.shouldRasterize = true
layer.isOpaque = true
layer.add(animation, forKey: "position")
}
}
|
mit
|
5785e81e8854545188524f5ce1661b3d
| 28.134615 | 126 | 0.605281 | 4.455882 | false | false | false | false |
developerY/Swift2_Playgrounds
|
Swift Standard Library.playground/Pages/Understanding Sequence and Collection Protocols.xcplaygroundpage/Sources/TimelineVisualizations.swift
|
5
|
4613
|
import UIKit
private final class TimelineCollectionCell: UICollectionViewCell {
let photoView = UIImageView()
let dateLabel = UILabel()
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
photoView.contentMode = .ScaleAspectFit
photoView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(photoView)
dateLabel.font = UIFont.systemFontOfSize(12)
dateLabel.textAlignment = .Right
dateLabel.numberOfLines = 1
dateLabel.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(dateLabel)
let hPhotoConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"|[photoView]|",
options: [],
metrics: nil,
views: ["photoView": photoView])
let hDateConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"|[dateLabel]|",
options: [],
metrics: nil,
views: ["dateLabel": dateLabel])
let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:|[dateLabel(<=14)]-3-[photoView(134)]|",
options: [],
metrics: nil,
views: ["photoView": photoView, "dateLabel": dateLabel])
self.contentView.addConstraints(hPhotoConstraints + hDateConstraints + vConstraints)
}
}
private final class TimelineCollectionController: UICollectionViewController {
let timelineCellIdentifier = "TimelineCellIdentifier"
var elements = [(date: String, image: UIImage?)]()
override func viewDidLoad() {
self.collectionView!.backgroundColor = .whiteColor()
collectionView!.registerClass(TimelineCollectionCell.self, forCellWithReuseIdentifier: timelineCellIdentifier)
self.view.frame.size = CGSize(width: 1180, height: 160)
collectionView!.contentInset = UIEdgeInsetsMake(5, 5, 5, 5)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return elements.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(timelineCellIdentifier, forIndexPath: indexPath) as! TimelineCollectionCell
let (date, image) = elements[indexPath.row]
cell.photoView.image = image ?? UIImage(named: "NoImage.jpg")
cell.dateLabel.text = date
return cell
}
}
// UICollectionViewControllers are deallocated before their collection view is rendered unless you store them somewhere.
private var timelines = [TimelineCollectionController]()
private final class BorderView: UIView {
private override func drawRect(rect: CGRect) {
UIColor(white: 0.75, alpha: 1.0).set()
UIRectFill(rect)
}
}
private func showTimelineCollection(elements: [(date: String, image: UIImage?)]) -> UIView {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 7
layout.itemSize = CGSize(width: 134, height: 150)
let timeline = TimelineCollectionController(collectionViewLayout: layout)
timeline.elements = elements
timelines.append(timeline)
let topBorder = BorderView(frame: CGRect(x: 0, y: 0, width: 1180, height: 1))
let bottomBorder = BorderView(frame: CGRect(x: 0, y: 161, width: 1180, height: 1))
let view = UIView(frame: CGRect(x: 0, y: 0, width: 1180, height: 162))
view.addSubview(topBorder)
timeline.view.frame.origin.y = 1
view.addSubview(timeline.view)
view.addSubview(bottomBorder)
return view
}
public let mayFirst = NSDate(timeIntervalSince1970: 1.4305*pow(10, 9))
public let maySeventh = NSDate(timeIntervalSince1970: 1.431*pow(10, 9))
public func visualize<T: CollectionType where T.Index: CustomDebugStringConvertible, T.Generator.Element == UIImage?>(collection: T) -> UIView {
let elements = zip(collection.indices, collection).map { date, image in
return (date: date.debugDescription, image: image)
}
return showTimelineCollection(elements)
}
|
mit
|
518c25b8979bef325506b7fb19d88445
| 38.767241 | 148 | 0.688706 | 5.148438 | false | false | false | false |
mamouneyya/TheSkillsProof
|
SouqTask/Modules/Common/Helpers/BackgroundFetcher.swift
|
1
|
3063
|
//
// BackgroundFetcher.swift
// SouqTask
//
// Created by Ma'moun Diraneyya on 3/6/16.
// Copyright © 2016 Mamouneyya. All rights reserved.
//
import UIKit
class BackgroundFetcher {
// MARK: - Public Vars
/// Singleton's class shared instance
static let sharedInstance = BackgroundFetcher()
typealias FetchResultHandler = (UIBackgroundFetchResult) -> ()
typealias FetchProductHandler = (success: Bool, updated: Bool) -> ()
private init() {}
func updateTrackedPricesForFavoritedProducts(completion: FetchResultHandler) {
FavoritesManager.asyncGetAllProductsInFavorite { (products, error) -> () in
if let products = products where products.count > 0 {
var requestsCount = 0
var succeededRequestsCount = 0
var updatedAtLeastOne = false
for product in products {
self.requestProductWithUpdatingPricesIfNeeded(product.id, completion: { (success, updated) -> () in
requestsCount++
if success {
succeededRequestsCount++
}
if updated {
updatedAtLeastOne = true
}
if requestsCount == products.count {
// be forgiveness with up to two failed requests
if succeededRequestsCount >= products.count - 2 {
if updatedAtLeastOne {
completion(UIBackgroundFetchResult.NewData)
} else {
completion(UIBackgroundFetchResult.NoData)
}
} else {
completion(UIBackgroundFetchResult.Failed)
}
}
})
}
} else if error != nil {
completion(UIBackgroundFetchResult.Failed)
} else {
completion(UIBackgroundFetchResult.NoData)
}
}
}
private func requestProductWithUpdatingPricesIfNeeded(productId: String, completion: FetchProductHandler? = nil) {
Networker.request(Product.Request.getProduct(productId: productId)).responseObject { (response: Response<Product, NSError>) -> Void in
switch response.result {
case .Success(let product):
product.updateTrackedPrices() { (updated) -> () in
//print("Item updated: \(updated)")
completion?(success: true, updated: updated)
}
case .Failure(_):
//print("Item update failed!: \(productId)")
completion?(success: false, updated: false)
}
}
}
}
|
mit
|
290694e93f56e8720b26656fcf4a779c
| 37.275 | 142 | 0.489549 | 6.287474 | false | false | false | false |
lenssss/whereAmI
|
Whereami/Controller/Photo/cell/PublishEditGameViewCell.swift
|
1
|
2263
|
//
// PublishEditGameViewController.swift
// Whereami
//
// Created by A on 16/5/19.
// Copyright © 2016年 WuQifei. All rights reserved.
//
import UIKit
class PublishEditGameViewCell: UITableViewCell {
var itemNameLabel:UILabel? = nil
var selectImageView:UIImageView? = nil
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupUI()
}
func setupUI() {
self.backgroundColor = UIColor(red: 90/255.0, green: 90/255.0, blue: 90/255.0, alpha: 1)
self.itemNameLabel = UILabel()
self.itemNameLabel?.textColor = UIColor.whiteColor()
self.contentView.addSubview(self.itemNameLabel!)
self.selectImageView = UIImageView()
self.selectImageView?.image = UIImage(named: "pub_select")
self.contentView.addSubview(self.selectImageView!)
let line = UIView()
line.backgroundColor = UIColor.lightGrayColor()
self.contentView.addSubview(line)
self.itemNameLabel?.autoAlignAxisToSuperviewAxis(.Horizontal)
self.itemNameLabel?.autoPinEdgeToSuperviewEdge(.Left, withInset: 16)
// self.itemNameLabel?.autoPinEdgeToSuperviewEdge(.Top, withInset: 5)
// self.itemNameLabel?.autoPinEdgeToSuperviewEdge(.Bottom, withInset: 5)
self.itemNameLabel?.autoSetDimensionsToSize(CGSize(width: 100,height: 30))
self.selectImageView?.autoAlignAxisToSuperviewAxis(.Horizontal)
self.selectImageView?.autoPinEdgeToSuperviewEdge(.Right, withInset: 16)
self.selectImageView?.autoSetDimensionsToSize(CGSize(width: 30,height: 30))
line.autoPinEdgeToSuperviewEdge(.Bottom)
line.autoPinEdgeToSuperviewEdge(.Left, withInset: 16.0)
line.autoPinEdgeToSuperviewEdge(.Right, withInset: 16.0)
line.autoSetDimension(.Height, toSize: 0.5)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
499d5db835038fdc18f20218706d1532
| 36.04918 | 96 | 0.677434 | 4.798301 | false | false | false | false |
whiteshadow-gr/HatForIOS
|
HAT/Objects/Tools/HATToolsStatus.swift
|
1
|
1416
|
//
/**
* Copyright (C) 2018 HAT Data Exchange Ltd
*
* SPDX-License-Identifier: MPL2
*
* This file is part of the Hub of All Things project (HAT).
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
// MARK: Struct
public struct HATToolsStatus: HATObject {
// MARK: - Coding Keys
/**
The JSON fields used by the hat
The Fields are the following:
* `isAvailable` in JSON is `available`
* `isEnabled` in JSON is `enabled`
* `lastExecution` in JSON is `lastExecution`
* `executionStarted` in JSON is `executionStarted`
*/
private enum CodingKeys: String, CodingKey {
case isAvailable = "available"
case isEnabled = "enabled"
case lastExecution = "lastExecution"
case executionStarted = "executionStarted"
}
// MARK: - Variables
/// A flag indicating if the tool is available to the end users
public var isAvailable: Bool = false
/// A flag indicating if the tool is enabled by the user
public var isEnabled: Bool = false
/// The last execution date in ISO format. Optional
public var lastExecution: String?
/// The date it last started running in ISO format. Optional
public var executionStarted: String?
}
|
mpl-2.0
|
b3b1c56e6a82dffbba0d698e6ecba8c0
| 29.12766 | 70 | 0.655367 | 4.290909 | false | false | false | false |
lewis-smith/Unobtrusive
|
UnobtrusiveDemo/UnobtrusiveDemo/DetailViewController.swift
|
1
|
1968
|
//
// DetailViewController.swift
// UnobtrusivePrompt
//
// Created by Lewis Smith on 18/01/2017.
// Copyright © 2017 Lewis Makes Apps. All rights reserved.
//
import UIKit
import Unobtrusive
class DetailViewController: UIViewController {
@IBOutlet weak var detailDescriptionLabel: UILabel!
@IBOutlet weak var unobtrusiveView: UnobtrusiveView!
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
if let promptView = self.unobtrusiveView {
if self.view.tag == 1 {
promptView.setLabel(text: "short text")
}
if self.view.tag == 2 {
// do not set label text
}
if self.view.tag == 3 {
promptView.setLabel(text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.")
}
promptView.tapGoCallback = {
print("\(self.view.tag)")
}
promptView.tapDismissCallback = {
print("closed")
}
promptView.button.backgroundColor = UIColor.blue
promptView.button.setTitleColor(UIColor.white, for: .normal)
promptView.backgroundColor = UIColor.gray
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
var detailItem: NSDate? {
didSet {
// Update the view.
self.configureView()
}
}
}
|
mit
|
9472f8fc69bfdb450683f86d016ccc50
| 28.358209 | 292 | 0.578546 | 4.880893 | false | false | false | false |
Yalantis/PixPic
|
PixPic/Classes/Flow/PhotoEditor/PhotoEditorViewController.swift
|
1
|
9238
|
//
// PhotoEditorViewController.swift
// PixPic
//
// Created by Illya on 1/25/16.
// Copyright © 2016 Yalantis. All rights reserved.
//
import UIKit
import Photos
typealias PhotoEditorRouterInterface = AuthorizationRouterInterface
protocol PhotoEditorDelegate: class {
func photoEditor(photoEditor: PhotoEditorViewController, didChooseSticker: UIImage)
func imageForPhotoEditor(photoEditor: PhotoEditorViewController, withStickers: Bool) -> UIImage
func removeAllStickers(photoEditor: PhotoEditorViewController)
}
private let cancelActionTitle = NSLocalizedString("cancel", comment: "")
private let postActionTitle = NSLocalizedString("post_with_delay", comment: "")
private let saveActionTitle = NSLocalizedString("save", comment: "")
private let dontSaveActionTitle = NSLocalizedString("don't_save", comment: "")
private let suggestSaveToCameraRollMessage = NSLocalizedString("save_result_after_internet_appears", comment: "")
final class PhotoEditorViewController: UIViewController, StoryboardInitiable, NavigationControllerAppearanceContext {
static let storyboardName = Constants.Storyboard.photoEditor
weak var delegate: PhotoEditorDelegate?
private var model: PhotoEditorModel!
private var router: PhotoEditorRouterInterface!
private weak var locator: ServiceLocator!
private var imageController: ImageViewController?
private var stickersPickerController: StickersPickerViewController? {
didSet {
stickersPickerController?.delegate = self
}
}
@IBOutlet private weak var stickerPickerContainer: UIView!
@IBOutlet private weak var imageContainer: UIView!
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupNavigavionBar()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
AlertManager.sharedInstance.setAlertDelegate(router)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
PushNotificationQueue.handleNotificationQueue()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
switch segue.identifier! {
case Constants.PhotoEditor.imageViewControllerSegue:
imageController = segue.destinationViewController as? ImageViewController
imageController?.model = ImageViewModel(image: model.originalImage)
imageController?.setLocator(locator)
delegate = imageController
case Constants.PhotoEditor.stickersPickerSegue:
stickersPickerController = segue.destinationViewController as? StickersPickerViewController
stickersPickerController?.setLocator(locator)
default:
super.prepareForSegue(segue, sender: sender)
}
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
layoutImageContainer()
layoutStickersPickerContainer()
view.layoutIfNeeded()
}
func didChooseStickerFromPicket(sticker: UIImage) {
delegate?.photoEditor(self, didChooseSticker: sticker)
}
// MARK: - Setup methods
func setLocator(locator: ServiceLocator) {
self.locator = locator
}
func setRouter(router: PhotoEditorRouterInterface) {
self.router = router
}
func setModel(model: PhotoEditorModel) {
self.model = model
}
}
// MARK: - Private methods
extension PhotoEditorViewController {
private func setupNavigavionBar() {
navigationItem.hidesBackButton = true
let newBackButton = UIBarButtonItem(
image: UIImage.appBackButton,
style: .Plain,
target: self,
action: #selector(performBackNavigation)
)
navigationItem.leftBarButtonItem = newBackButton
let savingButton = UIBarButtonItem(
image: UIImage(named: "ic_save"),
style: .Plain,
target: self,
action: #selector(saveImageToCameraRoll)
)
let removeAllStickersButton = UIBarButtonItem(
image: UIImage(named: "ic_remove"),
style: .Plain,
target: self,
action: #selector(removeAllStickers)
)
removeAllStickersButton.imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -30)
navigationItem.rightBarButtonItems = [savingButton, removeAllStickersButton]
navigationItem.title = "Edit"
}
private func layoutImageContainer() {
var size = imageContainer.frame.size
size.width = view.bounds.width
size.height = size.width
imageContainer.bounds.size = size
}
private func layoutStickersPickerContainer() {
var size = stickerPickerContainer.frame.size
size.width = view.bounds.width
stickerPickerContainer.bounds.size = size
}
@objc private func performBackNavigation() {
let alertController = UIAlertController(
title: "Result wasn't saved",
message: "Do you want to save result to the photo library?",
preferredStyle: .ActionSheet
)
let saveAction = UIAlertAction.appAlertAction(
title: saveActionTitle,
style: .Default, color: UIColor.redColor()
) { [weak self] _ in
guard let this = self else {
return
}
this.saveImageToCameraRoll()
this.navigationController!.popViewControllerAnimated(true)
}
alertController.addAction(saveAction)
let dontSaveAction = UIAlertAction.appAlertAction(
title: dontSaveActionTitle,
style: .Default
) { [weak self] _ in
self?.navigationController!.popViewControllerAnimated(true)
}
alertController.addAction(dontSaveAction)
let cancelAction = UIAlertAction.appAlertAction(
title: cancelActionTitle,
style: .Cancel,
handler: nil)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
@objc private func saveImageToCameraRoll() {
guard let image = delegate?.imageForPhotoEditor(self, withStickers: true) else {
ExceptionHandler.handle(Exception.CantApplyStickers)
return
}
PHPhotoLibrary.requestAuthorization { status in
dispatch_async(dispatch_get_main_queue()) {
switch status {
case .Authorized:
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
AlertManager.sharedInstance.showSimpleAlert("Image was saved to the photo library")
default:
AlertManager.sharedInstance.showSimpleAlert("No access to the photo library")
}
}
}
}
private func postToFeed() {
do {
guard let image = delegate?.imageForPhotoEditor(self, withStickers: true) else {
throw Exception.CantApplyStickers
}
var imageData = UIImageJPEGRepresentation(image, 1.0)
var i = 1.0
while imageData?.length > Constants.FileSize.maxUploadSizeBytes {
i = i - 0.1
imageData = UIImageJPEGRepresentation(image, CGFloat(i))
}
guard let file = PFFile(name: "image", data: imageData!) else {
throw Exception.CantCreateParseFile
}
let postService: PostService = locator.getService()
postService.savePost(file)
navigationController!.popToRootViewControllerAnimated(true)
} catch let exception {
ExceptionHandler.handle(exception as! Exception)
}
}
private func suggestSaveToCameraRoll() {
let alertController = UIAlertController(
title: Exception.NoConnection.rawValue,
message: suggestSaveToCameraRollMessage,
preferredStyle: .ActionSheet
)
let saveAction = UIAlertAction.appAlertAction(
title: saveActionTitle,
style: .Default
) { [weak self] _ in
self?.saveImageToCameraRoll()
}
alertController.addAction(saveAction)
let postAction = UIAlertAction.appAlertAction(
title: postActionTitle,
style: .Default
) { [weak self] _ in
self?.postToFeed()
}
alertController.addAction(postAction)
let cancelAction = UIAlertAction.appAlertAction(
title: cancelActionTitle,
style: .Cancel,
handler: nil)
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
@objc private func removeAllStickers() {
delegate?.removeAllStickers(self)
}
}
// MARK: - IBActions
extension PhotoEditorViewController {
@IBAction private func postEditedImage() {
guard ReachabilityHelper.isReachable() else {
suggestSaveToCameraRoll()
return
}
postToFeed()
}
}
|
mit
|
ec801b46bc89e881bb2bf3ff323ad5a3
| 31.184669 | 117 | 0.650644 | 5.439929 | false | false | false | false |
skonb/YapDatabaseExtensions
|
framework/Pods/PromiseKit/Sources/State.swift
|
5
|
3691
|
import Foundation.NSError
enum Resolution {
case Fulfilled(Any) //TODO make type T when Swift can handle it
case Rejected(NSError)
}
enum Seal {
case Pending(Handlers)
case Resolved(Resolution)
}
protocol State {
func get() -> Resolution?
func get(body: (Seal) -> Void)
}
class UnsealedState: State {
private let barrier = dispatch_queue_create("org.promisekit.barrier", DISPATCH_QUEUE_CONCURRENT)
private var seal: Seal
/**
Quick return, but will not provide the handlers array
because it could be modified while you are using it by
another thread. If you need the handlers, use the second
`get` variant.
*/
func get() -> Resolution? {
var result: Resolution?
dispatch_sync(barrier) {
switch self.seal {
case .Resolved(let resolution):
result = resolution
case .Pending:
break
}
}
return result
}
func get(body: (Seal) -> Void) {
var sealed = false
dispatch_sync(barrier) {
switch self.seal {
case .Resolved:
sealed = true
case .Pending:
sealed = false
}
}
if !sealed {
dispatch_barrier_sync(barrier) {
switch (self.seal) {
case .Pending:
body(self.seal)
case .Resolved:
sealed = true // welcome to race conditions
}
}
}
if sealed {
body(seal)
}
}
init(inout resolver: ((Resolution) -> Void)!) {
seal = .Pending(Handlers())
resolver = { resolution in
var handlers: Handlers?
dispatch_barrier_sync(self.barrier) {
switch self.seal {
case .Pending(let hh):
self.seal = .Resolved(resolution)
handlers = hh
case .Resolved:
break
}
}
if let handlers = handlers {
for handler in handlers {
handler(resolution)
}
}
}
}
}
class SealedState: State {
private let resolution: Resolution
init(resolution: Resolution) {
self.resolution = resolution
}
func get() -> Resolution? {
return resolution
}
func get(body: (Seal) -> Void) {
body(.Resolved(resolution))
}
}
class Handlers: SequenceType {
var bodies: [(Resolution)->()] = []
func append(body: (Resolution)->()) {
bodies.append(body)
}
func generate() -> IndexingGenerator<[(Resolution)->()]> {
return bodies.generate()
}
var count: Int {
return bodies.count
}
}
extension Resolution: DebugPrintable {
var debugDescription: String {
switch self {
case Fulfilled(let value):
return "Fulfilled with value: \(value)"
case Rejected(let error):
return "Rejected with error: \(error)"
}
}
}
extension UnsealedState: DebugPrintable {
var debugDescription: String {
var rv: String?
get { seal in
switch seal {
case .Pending(let handlers):
rv = "Pending with \(handlers.count) handlers"
case .Resolved(let resolution):
rv = "\(resolution)"
}
}
return "UnsealedState: \(rv!)"
}
}
extension SealedState: DebugPrintable {
var debugDescription: String {
return "SealedState: \(resolution)"
}
}
|
mit
|
6afa4e2ae0e41fb5531b496c88bb1ae4
| 23.443709 | 100 | 0.516662 | 4.762581 | false | false | false | false |
adrfer/swift
|
validation-test/compiler_crashers_2_fixed/0027-rdar21514140.swift
|
1
|
13339
|
// RUN: not %target-swift-frontend %s -parse
/// A type that is just a wrapper over some base Sequence
internal protocol _SequenceWrapperType {
typealias Base : SequenceType
typealias Generator : GeneratorType = Base.Generator
var _base: Base {get}
}
extension SequenceType
where Self : _SequenceWrapperType, Self.Generator == Self.Base.Generator {
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> Base.Generator {
return self._base.generate()
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
public func _customContainsEquatableElement(
element: Base.Generator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `CollectionType`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(@noescape preprocess: (Self) -> R) -> R? {
return _base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Generator.Element> {
return _base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _initializeTo(ptr: UnsafeMutablePointer<Base.Generator.Element>) {
return _base._initializeTo(ptr)
}
}
internal protocol _CollectionWrapperType : _SequenceWrapperType {
typealias Base : CollectionType
typealias Index : ForwardIndexType = Base.Index
var _base: Base {get}
}
extension CollectionType
where Self : _CollectionWrapperType, Self.Index == Self.Base.Index {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Generator.Element {
return _base[position]
}
}
//===--- New stuff --------------------------------------------------------===//
public protocol _prext_LazySequenceType : SequenceType {
/// A SequenceType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazySequence` layer.
typealias Elements: SequenceType = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing a `_prext_LazySequence`
/// layer.
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements {get}
/// An Array, created on-demand, containing the elements of this
/// lazy SequenceType.
///
/// Note: this property need not be implemented by conforming types, it has a
/// default implementation in a protocol extension.
var array: [Generator.Element] {get}
}
extension _prext_LazySequenceType {
/// an Array, created on-demand, containing the elements of this
/// lazy SequenceType.
public var array: [Generator.Element] {
return Array(self)
}
}
extension _prext_LazySequenceType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazySequenceType where Self : _SequenceWrapperType {
public var elements: Base { return _base }
}
/// A sequence that forwards its implementation to an underlying
/// sequence instance while exposing lazy computations as methods.
public struct _prext_LazySequence<Base_ : SequenceType> : _SequenceWrapperType {
var _base: Base_
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<S : SequenceType>(s: S) -> _prext_LazySequence<S> {
return _prext_LazySequence(_base: s)
}
public extension SequenceType
where Self.Generator == Self, Self : GeneratorType {
public func generate() -> Self {
return self
}
}
//===--- LazyCollection.swift ---------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol _prext_LazyCollectionType : CollectionType, _prext_LazySequenceType {
/// A CollectionType that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazyCollection` layer.
typealias Elements: CollectionType = Self
}
extension _prext_LazyCollectionType where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazyCollectionType where Self : _CollectionWrapperType {
public var elements: Base { return _base }
}
/// A collection that forwards its implementation to an underlying
/// collection instance while exposing lazy computations as methods.
public struct _prext_LazyCollection<Base_ : CollectionType>
: /*_prext_LazyCollectionType,*/ _CollectionWrapperType {
typealias Base = Base_
typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
public init(_ base: Base_) {
self._base = base
}
public var _base: Base_
// FIXME: Why is this needed?
// public var elements: Base { return _base }
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<Base: CollectionType>(s: Base) -> _prext_LazyCollection<Base> {
return _prext_LazyCollection(s)
}
//===--- New stuff --------------------------------------------------------===//
/// The `GeneratorType` used by `_prext_MapSequence` and `_prext_MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `GeneratorType` through a transform function returning `T`.
public struct _prext_MapGenerator<
Base: GeneratorType, T
> : GeneratorType, SequenceType {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
let x = _base.next()
if x != nil {
return _transform(x!)
}
return nil
}
var _base: Base
var _transform: (Base.Element)->T
}
//===--- Sequences --------------------------------------------------------===//
/// A `SequenceType` whose elements consist of those in a `Base`
/// `SequenceType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapSequence<Base : SequenceType, T>
: _prext_LazySequenceType, _SequenceWrapperType {
typealias Elements = _prext_MapSequence
/// Return a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator,T> {
return _prext_MapGenerator(
_base: _base.generate(), _transform: _transform)
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Collections ------------------------------------------------------===//
/// A `CollectionType` whose elements consist of those in a `Base`
/// `CollectionType` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapCollection<Base : CollectionType, T>
: _prext_LazyCollectionType, _CollectionWrapperType {
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Requires: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> T {
return _transform(_base[position])
}
/// Returns a *generator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func generate() -> _prext_MapGenerator<Base.Generator, T> {
return _prext_MapGenerator(_base: _base.generate(), _transform: _transform)
}
public func underestimateCount() -> Int {
return _base.underestimateCount()
}
var _base: Base
var _transform: (Base.Generator.Element)->T
}
//===--- Support for lazy(s) ----------------------------------------------===//
extension _prext_LazySequenceType {
/// Return a `_prext_MapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapSequence<Self.Elements, U> {
return _prext_MapSequence(_base: self.elements, _transform: transform)
}
}
extension _prext_LazyCollectionType {
/// Return a `_prext_MapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Generator.Element) -> U
) -> _prext_MapCollection<Self.Elements, U> {
return _prext_MapCollection(_base: self.elements, _transform: transform)
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
//===--- New stuff --------------------------------------------------------===//
internal protocol _prext_ReverseIndexType : BidirectionalIndexType {
typealias Base : BidirectionalIndexType
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseIndex` values where one value is reachable from the other.
typealias Distance: _SignedIntegerType = Base.Distance
var _base: Base { get }
init(_ base: Base)
}
/// A wrapper for a `BidirectionalIndexType` that reverses its
/// direction of traversal.
extension BidirectionalIndexType where Self : _prext_ReverseIndexType {
/// Returns the next consecutive value after `self`.
///
/// - Requires: The next value is representable.
public func successor() -> Self {
return Self(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Requires: The previous value is representable.
public func predecessor() -> Self {
return Self(_base.successor())
}
}
public struct _prext_ReverseIndex<Base: BidirectionalIndexType>
: BidirectionalIndexType, _prext_ReverseIndexType {
internal init(_ base: Base) { self._base = base }
internal let _base: Base
}
public func == <I> (lhs: _prext_ReverseIndex<I>, rhs: _prext_ReverseIndex<I>) -> Bool {
return lhs._base == rhs._base
}
public struct _prext_ReverseRandomAccessIndex<Base: RandomAccessIndexType>
: RandomAccessIndexType, _prext_ReverseIndexType {
typealias Distance = Base.Distance
internal init(_ base: Base) { self._base = base }
internal let _base: Base
/// Return the minimum number of applications of `successor` or
/// `predecessor` required to reach `other` from `self`.
///
/// - Complexity: O(1).
public func distanceTo(other: _prext_ReverseRandomAccessIndex) -> Distance {
return other._base.distanceTo(_base)
}
/// Return `self` offset by `n` steps.
///
/// - Returns: If `n > 0`, the result of applying `successor` to
/// `self` `n` times. If `n < 0`, the result of applying
/// `predecessor` to `self` `-n` times. Otherwise, `self`.
///
/// - Complexity: O(1).
public func advancedBy(amount: Distance) -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.advancedBy(-amount))
}
}
internal protocol __prext_ReverseCollectionType
: _prext_LazyCollectionType, _CollectionWrapperType {
typealias Base : CollectionType
var _base : Base {get}
}
extension CollectionType
where Self : __prext_ReverseCollectionType,
Self.Index : _prext_ReverseIndexType,
Self.Index.Base == Self.Base.Index,
Generator.Element == Self.Base.Generator.Element
{
public var startIndex : Index { return Index(_base.endIndex) }
public var endIndex : Index { return Index(_base.startIndex) }
public subscript(position: Index) -> Self.Base.Generator.Element {
return _base[position._base.predecessor()]
}
}
|
apache-2.0
|
e2cc0adcbce096e64408c6b01a020685
| 32.181592 | 87 | 0.670215 | 4.215866 | false | false | false | false |
bfortunato/aj-framework
|
platforms/ios/Libs/socket.io-client-swift/Source/SocketEnginePollable.swift
|
1
|
8036
|
//
// SocketEnginePollable.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 1/15/16.
//
// 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
/// Protocol that is used to implement socket.io polling support
public protocol SocketEnginePollable : SocketEngineSpec {
var invalidated: Bool { get }
/// Holds strings waiting to be sent over polling.
/// You shouldn't need to mess with this.
var postWait: [String] { get set }
var session: URLSession? { get }
/// Because socket.io doesn't let you send two polling request at the same time
/// we have to keep track if there's an outstanding poll
var waitingForPoll: Bool { get set }
/// Because socket.io doesn't let you send two post request at the same time
/// we have to keep track if there's an outstanding post
var waitingForPost: Bool { get set }
func doPoll()
func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data])
func stopPolling()
}
// Default polling methods
extension SocketEnginePollable {
private func addHeaders(for req: URLRequest) -> URLRequest {
var req = req
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
req.allHTTPHeaderFields = headers
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
req.setValue(value, forHTTPHeaderField: headerName)
}
}
return req
}
func createRequestForPostWithPostWait() -> URLRequest {
defer { postWait.removeAll(keepingCapacity: true) }
var postStr = ""
for packet in postWait {
let len = packet.count
postStr += "\(len):\(packet)"
}
DefaultSocketLogger.Logger.log("Created POST string: %@", type: "SocketEnginePolling", args: postStr)
var req = URLRequest(url: urlPollingWithSid)
let postData = postStr.data(using: .utf8, allowLossyConversion: false)!
req = addHeaders(for: req)
req.httpMethod = "POST"
req.setValue("text/plain; charset=UTF-8", forHTTPHeaderField: "Content-Type")
req.httpBody = postData
req.setValue(String(postData.count), forHTTPHeaderField: "Content-Length")
return req as URLRequest
}
public func doPoll() {
if websocket || waitingForPoll || !connected || closed {
return
}
waitingForPoll = true
var req = URLRequest(url: urlPollingWithSid)
req = addHeaders(for: req)
doLongPoll(for: req )
}
func doRequest(for req: URLRequest, callbackWith callback: @escaping (Data?, URLResponse?, Error?) -> Void) {
if !polling || closed || invalidated || fastUpgrade {
return
}
DefaultSocketLogger.Logger.log("Doing polling request", type: "SocketEnginePolling")
session?.dataTask(with: req, completionHandler: callback).resume()
}
func doLongPoll(for req: URLRequest) {
doRequest(for: req) {[weak self] data, res, err in
guard let this = self, this.polling else { return }
if err != nil || data == nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(reason: err?.localizedDescription ?? "Error")
}
return
}
DefaultSocketLogger.Logger.log("Got polling response", type: "SocketEnginePolling")
if let str = String(data: data!, encoding: String.Encoding.utf8) {
this.parseQueue.async {
this.parsePollingMessage(str)
}
}
this.waitingForPoll = false
if this.fastUpgrade {
this.doFastUpgrade()
} else if !this.closed && this.polling {
this.doPoll()
}
}
}
private func flushWaitingForPost() {
if postWait.count == 0 || !connected {
return
} else if websocket {
flushWaitingForPostToWebSocket()
return
}
let req = createRequestForPostWithPostWait()
waitingForPost = true
DefaultSocketLogger.Logger.log("POSTing", type: "SocketEnginePolling")
doRequest(for: req) {[weak self] data, res, err in
guard let this = self else { return }
if err != nil {
DefaultSocketLogger.Logger.error(err?.localizedDescription ?? "Error", type: "SocketEnginePolling")
if this.polling {
this.didError(reason: err?.localizedDescription ?? "Error")
}
return
}
this.waitingForPost = false
this.emitQueue.async {
if !this.fastUpgrade {
this.flushWaitingForPost()
this.doPoll()
}
}
}
}
func parsePollingMessage(_ str: String) {
guard str.count != 1 else { return }
var reader = SocketStringReader(message: str)
while reader.hasNext {
if let n = Int(reader.readUntilOccurence(of: ":")) {
let str = reader.read(count: n)
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
} else {
handleQueue.async { self.parseEngineMessage(str, fromPolling: true) }
break
}
}
}
/// Send polling message.
/// Only call on emitQueue
public func sendPollMessage(_ message: String, withType type: SocketEnginePacketType, withData datas: [Data]) {
DefaultSocketLogger.Logger.log("Sending poll: %@ as type: %@", type: "SocketEnginePolling", args: message, type.rawValue)
let fixedMessage: String
if doubleEncodeUTF8 {
fixedMessage = doubleEncodeUTF8(message)
} else {
fixedMessage = message
}
postWait.append(String(type.rawValue) + fixedMessage)
for data in datas {
if case let .right(bin) = createBinaryDataForSend(using: data) {
postWait.append(bin)
}
}
if !waitingForPost {
flushWaitingForPost()
}
}
public func stopPolling() {
waitingForPoll = false
waitingForPost = false
session?.finishTasksAndInvalidate()
}
}
|
apache-2.0
|
d8718ca874f560bb33a44dad4dfe5108
| 33.637931 | 129 | 0.576033 | 5.231771 | false | false | false | false |
insidegui/WWDC
|
WWDC/SearchCoordinator.swift
|
1
|
12991
|
//
// SearchCoordinator.swift
// WWDC
//
// Created by Guilherme Rambo on 25/05/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ConfCore
import RealmSwift
import os.log
enum FilterIdentifier: String {
case text
case event
case focus
case track
case isFavorite
case isDownloaded
case isUnwatched
case hasBookmarks
}
final class SearchCoordinator {
let storage: Storage
let scheduleController: SessionsTableViewController
let videosController: SessionsTableViewController
private let log = OSLog(subsystem: "WWDC", category: "SearchCoordinator")
/// The desired state of the filters upon configuration
private let restorationFiltersState: WWDCFiltersState?
fileprivate var scheduleSearchController: SearchFiltersViewController {
return scheduleController.searchController
}
fileprivate var videosSearchController: SearchFiltersViewController {
return videosController.searchController
}
init(_ storage: Storage,
sessionsController: SessionsTableViewController,
videosController: SessionsTableViewController,
restorationFiltersState: String? = nil) {
self.storage = storage
scheduleController = sessionsController
self.videosController = videosController
self.restorationFiltersState = restorationFiltersState
.flatMap { $0.data(using: .utf8) }
.flatMap { try? JSONDecoder().decode(WWDCFiltersState.self, from: $0) }
NotificationCenter.default.addObserver(self,
selector: #selector(activateSearchField),
name: .MainWindowWantsToSelectSearchField,
object: nil)
}
func configureFilters() {
// Schedule Filters Configuration
var scheduleTextualFilter = TextualFilter(identifier: FilterIdentifier.text, value: nil)
let sessionOption = FilterOption(title: "Sessions", value: "Session")
let labOption = sessionOption.negated(with: "Labs and Others")
let eventOptions = [sessionOption, labOption]
var scheduleEventFilter = MultipleChoiceFilter(identifier: FilterIdentifier.event,
isSubquery: true,
collectionKey: "instances",
modelKey: "rawSessionType",
options: eventOptions,
selectedOptions: [],
emptyTitle: "All Events")
let focusOptions = storage.allFocuses.map { FilterOption(title: $0.name, value: $0.name) }
var scheduleFocusFilter = MultipleChoiceFilter(identifier: FilterIdentifier.focus,
isSubquery: true,
collectionKey: "focuses",
modelKey: "name",
options: focusOptions,
selectedOptions: [],
emptyTitle: "All Platforms")
let trackOptions = storage.allTracks.map { FilterOption(title: $0.name, value: $0.name) }
var scheduleTrackFilter = MultipleChoiceFilter(identifier: FilterIdentifier.track,
isSubquery: false,
collectionKey: "",
modelKey: "trackName",
options: trackOptions,
selectedOptions: [],
emptyTitle: "All Tracks")
let favoritePredicate = NSPredicate(format: "SUBQUERY(favorites, $favorite, $favorite.isDeleted == false).@count > 0")
var scheduleFavoriteFilter = ToggleFilter(identifier: FilterIdentifier.isFavorite,
isOn: false,
defaultValue: false,
customPredicate: favoritePredicate)
let downloadedPredicate = NSPredicate(format: "isDownloaded == true")
var scheduleDownloadedFilter = ToggleFilter(identifier: FilterIdentifier.isDownloaded,
isOn: false,
defaultValue: false,
customPredicate: downloadedPredicate)
let smallPositionPred = NSPredicate(format: "SUBQUERY(progresses, $progress, $progress.relativePosition < \(Constants.watchedVideoRelativePosition)).@count > 0")
let noPositionPred = NSPredicate(format: "progresses.@count == 0")
let unwatchedPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [smallPositionPred, noPositionPred])
var scheduleUnwatchedFilter = ToggleFilter(identifier: FilterIdentifier.isUnwatched,
isOn: false,
defaultValue: false,
customPredicate: unwatchedPredicate)
let bookmarksPredicate = NSPredicate(format: "SUBQUERY(bookmarks, $bookmark, $bookmark.isDeleted == false).@count > 0")
var scheduleBookmarksFilter = ToggleFilter(identifier: FilterIdentifier.hasBookmarks,
isOn: false,
defaultValue: false,
customPredicate: bookmarksPredicate)
// Schedule Filtering State Restoration
let savedScheduleFiltersState = restorationFiltersState?.scheduleTab
scheduleTextualFilter.value = savedScheduleFiltersState?.text?.value
scheduleEventFilter.selectedOptions = savedScheduleFiltersState?.event?.selectedOptions ?? []
scheduleFocusFilter.selectedOptions = savedScheduleFiltersState?.focus?.selectedOptions ?? []
scheduleTrackFilter.selectedOptions = savedScheduleFiltersState?.track?.selectedOptions ?? []
scheduleFavoriteFilter.isOn = savedScheduleFiltersState?.isFavorite?.isOn ?? false
scheduleDownloadedFilter.isOn = savedScheduleFiltersState?.isDownloaded?.isOn ?? false
scheduleUnwatchedFilter.isOn = savedScheduleFiltersState?.isUnwatched?.isOn ?? false
scheduleBookmarksFilter.isOn = savedScheduleFiltersState?.hasBookmarks?.isOn ?? false
let scheduleSearchFilters: [FilterType] = [scheduleTextualFilter,
scheduleEventFilter,
scheduleFocusFilter,
scheduleTrackFilter,
scheduleFavoriteFilter,
scheduleDownloadedFilter,
scheduleUnwatchedFilter,
scheduleBookmarksFilter]
if !scheduleSearchController.filters.isIdentical(to: scheduleSearchFilters) {
scheduleSearchController.filters = scheduleSearchFilters
}
// Videos Filter Configuration
let savedVideosFiltersState = restorationFiltersState?.videosTab
var videosTextualFilter = scheduleTextualFilter
let videosEventOptions = storage.allEvents.map { FilterOption(title: $0.name, value: $0.identifier) }
var videosEventFilter = MultipleChoiceFilter(identifier: FilterIdentifier.event,
isSubquery: false,
collectionKey: "",
modelKey: "eventIdentifier",
options: videosEventOptions,
selectedOptions: [],
emptyTitle: "All Events")
var videosFocusFilter = scheduleFocusFilter
var videosTrackFilter = scheduleTrackFilter
var videosFavoriteFilter = scheduleFavoriteFilter
var videosDownloadedFilter = scheduleDownloadedFilter
var videosUnwatchedFilter = scheduleUnwatchedFilter
var videosBookmarksFilter = scheduleBookmarksFilter
// Videos Filtering State Restoration
videosTextualFilter.value = savedVideosFiltersState?.text?.value
videosEventFilter.selectedOptions = savedVideosFiltersState?.event?.selectedOptions ?? []
videosFocusFilter.selectedOptions = savedVideosFiltersState?.focus?.selectedOptions ?? []
videosTrackFilter.selectedOptions = savedVideosFiltersState?.track?.selectedOptions ?? []
videosFavoriteFilter.isOn = savedVideosFiltersState?.isFavorite?.isOn ?? false
videosDownloadedFilter.isOn = savedVideosFiltersState?.isDownloaded?.isOn ?? false
videosUnwatchedFilter.isOn = savedVideosFiltersState?.isUnwatched?.isOn ?? false
videosBookmarksFilter.isOn = savedVideosFiltersState?.hasBookmarks?.isOn ?? false
let videosSearchFilters: [FilterType] = [videosTextualFilter,
videosEventFilter,
videosFocusFilter,
videosTrackFilter,
videosFavoriteFilter,
videosDownloadedFilter,
videosUnwatchedFilter,
videosBookmarksFilter]
if !videosSearchController.filters.isIdentical(to: videosSearchFilters) {
videosSearchController.filters = videosSearchFilters
}
// set delegates
scheduleSearchController.delegate = self
videosSearchController.delegate = self
updateSearchResults(for: scheduleController, with: scheduleSearchController.filters)
updateSearchResults(for: videosController, with: videosSearchController.filters)
}
func newFilterResults(for controller: SessionsTableViewController, filters: [FilterType]) -> FilterResults {
guard filters.contains(where: { !$0.isEmpty }) else {
return FilterResults(storage: storage, query: nil)
}
var subpredicates = filters.compactMap { $0.predicate }
if controller == scheduleController {
subpredicates.append(NSPredicate(format: "ANY event.isCurrent == true"))
subpredicates.append(NSPredicate(format: "instances.@count > 0"))
} else if controller == videosController {
subpredicates.append(Session.videoPredicate)
}
let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: subpredicates)
os_log("%{public}@", log: log, type: .debug, String(describing: predicate))
return FilterResults(storage: storage, query: predicate)
}
fileprivate func updateSearchResults(for controller: SessionsTableViewController, with filters: [FilterType]) {
controller.setFilterResults(newFilterResults(for: controller, filters: filters), animated: true, selecting: nil)
}
@objc fileprivate func activateSearchField() {
if let window = scheduleSearchController.view.window {
window.makeFirstResponder(scheduleSearchController.searchField)
}
if let window = videosSearchController.view.window {
window.makeFirstResponder(videosSearchController.searchField)
}
}
func currentFiltersState() -> String? {
let state = WWDCFiltersState(
scheduleTab: WWDCFiltersState.Tab(filters: scheduleSearchController.filters),
videosTab: WWDCFiltersState.Tab(filters: videosSearchController.filters)
)
return (try? JSONEncoder().encode(state))
.flatMap { String(bytes: $0, encoding: .utf8) }
}
}
extension SearchCoordinator: SearchFiltersViewControllerDelegate {
func searchFiltersViewController(_ controller: SearchFiltersViewController, didChangeFilters filters: [FilterType]) {
if controller == scheduleSearchController {
updateSearchResults(for: scheduleController, with: filters)
} else {
updateSearchResults(for: videosController, with: filters)
}
}
}
|
bsd-2-clause
|
da36b1c219852d03efc8e135d257a08e
| 48.204545 | 169 | 0.581524 | 6.281431 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.