repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
lduraes/SwiftSampleTodo
SwiftTodo/NewTaskViewController.swift
1
2170
// // NewTaskViewController.swift // SwiftTodo // // Created by lduraes on 6/20/14. // Copyright (c) 2014 Mob4U IT Solutions. All rights reserved. // import UIKit /* * Private methods */ extension NewTaskViewController { func selectorTaskAdded(sender: UIButton!) { if !newTaskText.text.isEmpty { let listViewController = self.navigationController.viewControllers[0] as ListViewController listViewController.tasksArray.append(Task(taskName: newTaskText.text)) listViewController.tableView.reloadData() self.navigationController.popToRootViewControllerAnimated(true) } else { var alertController = UIAlertController(title: kTitleAlert, message: kMessageAlert, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: kButtonOkAlert, style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } } func doneButton() { let doneButton = UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: "selectorTaskAdded:") self.navigationItem.rightBarButtonItem = doneButton } } /* * Textfield methods */ extension NewTaskViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField!) -> Bool { selectorTaskAdded(nil) return true } } class NewTaskViewController: UIViewController { @IBOutlet var newTaskText : UITextField let kTitle: String = "New Task" let kTitleAlert: String = "Ups!" let kMessageAlert: String = "Field is empty!" let kButtonOkAlert: String = "Ok" init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { self.newTaskText.resignFirstResponder() } override func viewDidLoad() { super.viewDidLoad() self.title = kTitle doneButton() self.newTaskText.becomeFirstResponder() } }
gpl-3.0
5ea6c2bdcb85bb21dd66a554d2dac5cb
29.56338
141
0.689862
4.943052
false
false
false
false
anreitersimon/SwiftSortDescriptor
Sources/AnyComparable.swift
1
1392
// // AnyComparable.swift // Pods // // Created by Simon Anreiter on 04/12/2016. // // import Foundation /// type erased wrapper for objects conforming to Comparable struct AnyComparable: Comparable { private let compareClosure: (AnyComparable)->ComparisonResult let base: Any? init<T: Comparable>(_ value: T?) { self.base = value self.compareClosure = { other in let o = other.base as? T switch (value, o) { case (.none, .none): return .orderedSame case (.some(let lhs), .some(let rhs)): if lhs == rhs { return .orderedSame } return lhs < rhs ? .orderedAscending : .orderedDescending case (.none, .some(_)): return .orderedAscending case (.some(_), .none): return .orderedDescending } } } /// compares wrapped values with rule: /// /// `.none < .some()` func compare(_ val: AnyComparable) -> ComparisonResult { return self.compareClosure(val) } public static func <(lhs: AnyComparable, rhs: AnyComparable) -> Bool { return lhs.compare(rhs) == .orderedAscending } public static func ==(lhs: AnyComparable, rhs: AnyComparable) -> Bool { return lhs.compare(rhs) == .orderedSame } }
mit
28d97dcffbf00530ac5b78d059e8377e
25.264151
75
0.550287
4.594059
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/News/Widgets/MVVM/MVVMWidget.swift
1
759
import RouterCore public struct MVVMWidget< ViewModelFactory: NewsWidgetViewModelFactory, ViewFactory: NewsWidgetViewFactory >: NewsWidget where ViewModelFactory.ViewModel == ViewFactory.ViewModel { private let viewModelFactory: ViewModelFactory private let viewFactory: ViewFactory public init(viewModelFactory: ViewModelFactory, viewFactory: ViewFactory) { self.viewModelFactory = viewModelFactory self.viewFactory = viewFactory } public func register(in environment: NewsWidgetEnvironment) { let viewModel = viewModelFactory.makeViewModel(router: environment.router) let view = viewFactory.makeView(viewModel: viewModel) environment.install(dataSource: view) } }
mit
31eb11c9c060ca6d5fa2ef0918710fb7
33.5
82
0.743083
5.5
false
false
false
false
NqiOS/DYTV-swift
DYTV/DYTV/Classes/Home/Controller/NQGameViewController.swift
1
5025
// // NQGameViewController.swift // DYTV // // Created by djk on 17/3/9. // Copyright © 2017年 NQ. All rights reserved. // import UIKit private let kEdgeMargin : CGFloat = 10 private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3 private let kItemH : CGFloat = kItemW * 5 / 5 private let kHeaderViewH : CGFloat = 40 private let kGameViewH : CGFloat = 90 private let kGameCellID = "kGameCellID" private let kHeaderViewID = "kHeaderViewID" class NQGameViewController: NQBaseViewController { // MARK:- 懒加载属性 fileprivate lazy var gameVM : NQGameViewModel = NQGameViewModel() fileprivate lazy var topHeaderView : NQCollectionHeaderView = { let headerView = NQCollectionHeaderView.collectionHeaderView() headerView.frame = CGRect(x: 0, y: -(kHeaderViewH+kGameViewH), width: kScreenW, height: kHeaderViewH) headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.titleLabel.text = "常见" headerView.moreBtn.isHidden = true return headerView }() fileprivate lazy var gameView : NQRecommendGameView = { let gameView = NQRecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() fileprivate lazy var collectionView : UICollectionView = {[unowned self] in //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) //2.创建UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth] collectionView.register(UINib(nibName: "NQCollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID) collectionView.register(UINib(nibName: "NQCollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) collectionView.dataSource = self return collectionView }() // MARK: 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK:- 设置UI界面 extension NQGameViewController{ override func setupUI(){ //0.对ContentView进行赋值 contentView = collectionView //1.添加UICollectionView view.addSubview(collectionView) //2.设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: kHeaderViewH+kGameViewH, left: 0, bottom: 0, right: 0) //3.添加顶部的HeaderView collectionView.addSubview(topHeaderView) //4.将常用游戏的View,添加到collectionView中 collectionView.addSubview(gameView) //5.调用父类方法 super.setupUI() } } // MARK:- 请求数据 extension NQGameViewController{ fileprivate func loadData(){ gameVM.loadAllGameData { //1.展示全部游戏 self.collectionView.reloadData() //2.展示常用游戏 self.gameView.groups = Array(self.gameVM.games[0..<10]) //3.数据请求完成 self.loadDataFinished() } } } // MARK:- 遵守UICollectionView的数据源&代理 extension NQGameViewController : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.games.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.获取cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! NQCollectionGameCell cell.gameModel = gameVM.games[indexPath.item] cell.bottomLine.isHidden = false return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出HeaderView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! NQCollectionHeaderView // 2.给HeaderView设置属性 headerView.titleLabel.text = "全部" headerView.iconImageView.image = UIImage(named: "Img_orange") headerView.moreBtn.isHidden = true return headerView } }
mit
0a7d75c3741c79a58308925a996638dc
35.044776
188
0.676398
5.307692
false
false
false
false
open-telemetry/opentelemetry-swift
Sources/Instrumentation/SDKResourceExtension/DefaultResources.swift
1
860
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import OpenTelemetrySdk public class DefaultResources { // add new resource providers here let application = ApplicationResourceProvider(source: ApplicationDataSource()) let device = DeviceResourceProvider(source: DeviceDataSource()) let os = OSResourceProvider(source: OperatingSystemDataSource()) let telemetry = TelemetryResourceProvider(source: TelemetryDataSource()) public init() {} public func get() -> Resource { var resource = Resource() let mirror = Mirror(reflecting: self) for children in mirror.children { if let provider = children.value as? ResourceProvider { resource.merge(other: provider.create()) } } return resource } }
apache-2.0
dbf59c0231b1ef222602ac85b9d60afa
28.655172
82
0.681395
5.088757
false
false
false
false
manavgabhawala/swift
test/IRGen/objc_subclass.swift
1
19965
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-irgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -new-mangling-for-tests -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize %s // REQUIRES: objc_interop // CHECK: [[SGIZMO:T13objc_subclass10SwiftGizmoC]] = type // CHECK: [[TYPE:%swift.type]] = type // CHECK: [[INT:%TSi]] = type <{ [[LLVM_PTRSIZE_INT:i(32|64)]] }> // CHECK: [[OBJC_CLASS:%objc_class]] = type // CHECK: [[OPAQUE:%swift.opaque]] = type // CHECK: [[GIZMO:%TSo5GizmoC]] = type opaque // CHECK: [[OBJC:%objc_object]] = type opaque // CHECK-32: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i32 12, align [[WORD_SIZE_IN_BYTES:4]] // CHECK-64: @_T013objc_subclass10SwiftGizmoC1xSivWvd = hidden global i64 16, align [[WORD_SIZE_IN_BYTES:8]] // CHECK: @"OBJC_METACLASS_$__TtC13objc_subclass10SwiftGizmo" = hidden global [[OBJC_CLASS]] { [[OBJC_CLASS]]* @"OBJC_METACLASS_$_NSObject", [[OBJC_CLASS]]* @"OBJC_METACLASS_$_Gizmo", [[OPAQUE]]* @_objc_empty_cache, [[OPAQUE]]* null, [[LLVM_PTRSIZE_INT]] ptrtoint ({{.*}} @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo to [[LLVM_PTRSIZE_INT]]) } // CHECK: [[STRING_SWIFTGIZMO:@.*]] = private unnamed_addr constant [32 x i8] c"_TtC13objc_subclass10SwiftGizmo\00" // CHECK-32: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 129, // CHECK-32: i32 20, // CHECK-32: i32 20, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null, // CHECK-32: i8* null // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_METACLASS_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 129, // CHECK-64: i32 40, // CHECK-64: i32 40, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null, // CHECK-64: i8* null // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [7 x i8] c"l8@0:4\00" // CHECK-64: [[METHOD_TYPE_ENCODING1:@.*]] = private unnamed_addr constant [8 x i8] c"q16@0:8\00" // CHECK-32: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4l8\00" // CHECK-64: [[METHOD_TYPE_ENCODING2:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8q16\00" // CHECK-32: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"@8@0:4\00" // CHECK-64: [[GETTER_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"@16@0:8\00" // CHECK-32: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [13 x i8] c"@16@0:4l8@12\00" // CHECK-64: [[INIT_ENCODING:@.*]] = private unnamed_addr constant [14 x i8] c"@32@0:8q16@24\00" // CHECK-32: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [7 x i8] c"v8@0:4\00" // CHECK-64: [[DEALLOC_ENCODING:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00" // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 12, // CHECK-32: i32 11, // CHECK-32: [11 x { i8*, i8*, i8* }] [{ i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[METHOD_TYPE_ENCODING2]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[METHOD_TYPE_ENCODING1]], i32 0, i32 0), // CHECK-32: i8* bitcast (i32 (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%1* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([13 x i8], [13 x i8]* [[INIT_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32, %2*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[DEALLOC_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast ({{(i8|i1)}} (%0*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%0*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*, i32)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-32: }, { i8*, i8*, i8* } { // CHECK-32: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%0*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*) // CHECK-32: }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 11, // CHECK-64: [11 x { i8*, i8*, i8* }] [{ // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* @"\01L_selector_data(x)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC1xSifgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\01L_selector_data(setX:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[METHOD_TYPE_ENCODING2]], i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE3:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoC1xSifsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(getX)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[METHOD_TYPE_ENCODING1]], i64 0, i64 0) // CHECK-64: i8* bitcast (i64 ([[OPAQUE2]]*, i8*)* @_T013objc_subclass10SwiftGizmoC4getXSiyFTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(duplicate)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE1:.*]]* ([[OPAQUE0:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC9duplicateSo0D0CyFTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5:.*]]* ([[OPAQUE6:.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCACycfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(initWithInt:string:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* [[INIT_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE7:%.*]]* ([[OPAQUE8:%.*]]*, i8*, i64, [[OPAQUEONE:.*]]*)* @_T013objc_subclass10SwiftGizmoCACSi3int_SS6stringtcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(dealloc)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[DEALLOC_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE10:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfDTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\01L_selector_data(isEnabled)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ({{(i8|i1)}} ([[OPAQUE11:%.*]]*, i8*)* @_T013objc_subclass10SwiftGizmoC7enabledSbfgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(setIsEnabled:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE12:%.*]]*, i8*, {{(i8|i1)}})* @_T013objc_subclass10SwiftGizmoC7enabledSbfsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE11:%.*]]* ([[OPAQUE12:%.*]]*, i8*, i64)* @_T013objc_subclass10SwiftGizmoCSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([15 x i8], [15 x i8]* @"\01L_selector_data(.cxx_construct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE5]]* ([[OPAQUE6]]*, i8*)* @_T013objc_subclass10SwiftGizmoCfeTo to i8*) // CHECK-64: }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK: [[STRING_X:@.*]] = private unnamed_addr constant [2 x i8] c"x\00" // CHECK: [[STRING_EMPTY:@.*]] = private unnamed_addr constant [1 x i8] zeroinitializer // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-32: i32 20, // CHECK-32: i32 1, // CHECK-32: [1 x { i32*, i8*, i8*, i32, i32 }] [{ i32*, i8*, i8*, i32, i32 } { // CHECK-32: i32* @_T013objc_subclass10SwiftGizmoC1xSivWvd, // CHECK-32: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i32 0, i32 0), // CHECK-32: i32 2, // CHECK-32: i32 4 }] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}] } { // CHECK-64: i32 32, // CHECK-64: i32 1, // CHECK-64: [1 x { i64*, i8*, i8*, i32, i32 }] [{ i64*, i8*, i8*, i32, i32 } { // CHECK-64: i64* @_T013objc_subclass10SwiftGizmoC1xSivWvd, // CHECK-64: i8* getelementptr inbounds ([2 x i8], [2 x i8]* [[STRING_X]], i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([1 x i8], [1 x i8]* [[STRING_EMPTY]], i64 0, i64 0), // CHECK-64: i32 3, // CHECK-64: i32 8 }] // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-32: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-32: i32 132, // CHECK-32: i32 12, // CHECK-32: i32 16, // CHECK-32: i8* null, // CHECK-32: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i32 0, i32 0), // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-32: i8* null, // CHECK-32: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_DATA__TtC13objc_subclass10SwiftGizmo = private constant { {{.*}}* } { // CHECK-64: i32 132, // CHECK-64: i32 16, // CHECK-64: i32 24, // CHECK-64: i32 0, // CHECK-64: i8* null, // CHECK-64: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[STRING_SWIFTGIZMO]], i64 0, i64 0), // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_IVARS__TtC13objc_subclass10SwiftGizmo, // CHECK-64: i8* null, // CHECK-64: @_PROPERTIES__TtC13objc_subclass10SwiftGizmo // CHECK-64: }, section "__DATA, __objc_const", align 8 // CHECK-NOT: @_TMCSo13SwiftGizmo = {{.*NSObject}} // CHECK: @_INSTANCE_METHODS__TtC13objc_subclass12GenericGizmo // CHECK-32: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [10 x i8] c"v12@0:4@8\00" // CHECK-64: [[SETTER_ENCODING:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00" // CHECK-32: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, i32, [5 x { i8*, i8*, i8* }] } { // CHECK-32: i32 12, // CHECK-32: i32 5, // CHECK-32: [5 x { i8*, i8*, i8* }] [ // CHECK-32: { // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%0* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* [[SETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*, %0*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([7 x i8], [7 x i8]* [[GETTER_ENCODING]], i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([10 x i8], [10 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (%3* (%3*, i8*, i32)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-32: }, { // CHECK-32: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i32 0, i32 0), // CHECK-32: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i32 0, i32 0), // CHECK-32: i8* bitcast (void (%3*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*) // CHECK-32: } // CHECK-32: ] // CHECK-32: }, section "__DATA, __objc_const", align 4 // CHECK-64: @_INSTANCE_METHODS__TtC13objc_subclass11SwiftGizmo2 = private constant { i32, {{.*}}] } { // CHECK-64: i32 24, // CHECK-64: i32 5, // CHECK-64: [5 x { i8*, i8*, i8* }] [ // CHECK-64: { // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* @"\01L_selector_data(sg)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE13:%.*]]* ([[OPAQUE14:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfgTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(setSg:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[SETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast (void ([[OPAQUE15:%.*]]*, i8*, [[OPAQUE16:%.*]]*)* @_T013objc_subclass11SwiftGizmo2C2sgAA0C5GizmoCfsTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([5 x i8], [5 x i8]* @"\01L_selector_data(init)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[GETTER_ENCODING]], i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE18:%.*]]* ([[OPAQUE19:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CACycfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"\01L_selector_data(initWithBellsOn:)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([11 x i8], [11 x i8]* {{@[0-9]+}}, i64 0, i64 0), // CHECK-64: i8* bitcast ([[OPAQUE21:%.*]]* ([[OPAQUE22:%.*]]*, i8*, i64)* @_T013objc_subclass11SwiftGizmo2CSQyACGSi7bellsOn_tcfcTo to i8*) // CHECK-64: }, { // CHECK-64: i8* getelementptr inbounds ([14 x i8], [14 x i8]* @"\01L_selector_data(.cxx_destruct)", i64 0, i64 0), // CHECK-64: i8* getelementptr inbounds ([3 x i8], [3 x i8]* {{@[0-9]+}}, i64 0, i64 0) // CHECK-64: i8* bitcast (void ([[OPAQUE20:%.*]]*, i8*)* @_T013objc_subclass11SwiftGizmo2CfETo to i8*) // CHECK-64: } // CHECK-64: ] } // CHECK: @objc_classes = internal global [2 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass10SwiftGizmoCN to i8*), i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_classlist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]] // CHECK: @objc_non_lazy_classes = internal global [1 x i8*] [i8* bitcast (%swift.type* @_T013objc_subclass11SwiftGizmo2CN to i8*)], section "__DATA, __objc_nlclslist, regular, no_dead_strip", align [[WORD_SIZE_IN_BYTES]] import Foundation import gizmo @requires_stored_property_inits class SwiftGizmo : Gizmo { var x = Int() func getX() -> Int { return x } override func duplicate() -> Gizmo { return SwiftGizmo() } override init() { super.init(bellsOn:0) } init(int i: Int, string str : String) { super.init(bellsOn:i) } deinit { var x = 10 } var enabled: Bool { @objc(isEnabled) get { return true } @objc(setIsEnabled:) set { } } } class GenericGizmo<T> : Gizmo { func foo() {} var x : Int { return 0 } var array : [T] = [] } // CHECK: define hidden swiftcc [[LLVM_PTRSIZE_INT]] @_T013objc_subclass12GenericGizmoC1xSifg( var sg = SwiftGizmo() sg.duplicate() @objc_non_lazy_realization class SwiftGizmo2 : Gizmo { var sg : SwiftGizmo override init() { sg = SwiftGizmo() super.init() } deinit { } }
apache-2.0
50c95e44654222350feeb5c29ef11f00
58.068047
347
0.59975
2.762939
false
false
false
false
manavgabhawala/swift
test/IRGen/lazy_globals.swift
1
2253
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -parse-as-library -emit-ir -primary-file %s | %FileCheck %s // REQUIRES: CPU=x86_64 // CHECK: @globalinit_[[T:.*]]_token0 = internal global i64 0, align 8 // CHECK: @_T012lazy_globals1xSiv = hidden global %TSi zeroinitializer, align 8 // CHECK: @_T012lazy_globals1ySiv = hidden global %TSi zeroinitializer, align 8 // CHECK: @_T012lazy_globals1zSiv = hidden global %TSi zeroinitializer, align 8 // CHECK: define internal swiftcc void @globalinit_[[T]]_func0() {{.*}} { // CHECK: entry: // CHECK: store i64 1, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1xSiv, i32 0, i32 0), align 8 // CHECK: store i64 2, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1ySiv, i32 0, i32 0), align 8 // CHECK: store i64 3, i64* getelementptr inbounds (%TSi, %TSi* @_T012lazy_globals1zSiv, i32 0, i32 0), align 8 // CHECK: ret void // CHECK: } // CHECK: define hidden swiftcc i8* @_T012lazy_globals1xSifau() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1xSiv to i8*) // CHECK: } // CHECK: define hidden swiftcc i8* @_T012lazy_globals1ySifau() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1ySiv to i8*) // CHECK: } // CHECK: define hidden swiftcc i8* @_T012lazy_globals1zSifau() {{.*}} { // CHECK: entry: // CHECK: call void @swift_once(i64* @globalinit_[[T]]_token0, i8* bitcast (void ()* @globalinit_[[T]]_func0 to i8*)) // CHECK: ret i8* bitcast (%TSi* @_T012lazy_globals1zSiv to i8*) // CHECK: } var (x, y, z) = (1, 2, 3) // CHECK: define hidden swiftcc i64 @_T012lazy_globals4getXSiyF() {{.*}} { // CHECK: entry: // CHECK: %0 = call swiftcc i8* @_T012lazy_globals1xSifau() // CHECK: %1 = bitcast i8* %0 to %TSi* // CHECK: %._value = getelementptr inbounds %TSi, %TSi* %1, i32 0, i32 0 // CHECK: %2 = load i64, i64* %._value, align 8 // CHECK: ret i64 %2 // CHECK: } func getX() -> Int { return x }
apache-2.0
262a1aaafd93f5712c18ccc49322e736
47.978261
163
0.648913
2.929779
false
false
false
false
oyvind-hauge/OHCubeView
OHCubeView/OHCubeView.swift
1
7713
// // OHCubeView.swift // CubeController // // Created by Øyvind Hauge on 11/08/16. // Copyright © 2016 Oyvind Hauge. All rights reserved. // import UIKit @available(iOS 9.0, *) @objc protocol OHCubeViewDelegate: class { @objc optional func cubeViewDidScroll(_ cubeView: OHCubeView) } @available(iOS 9.0, *) open class OHCubeView: UIScrollView, UIScrollViewDelegate { weak var cubeDelegate: OHCubeViewDelegate? fileprivate let maxAngle: CGFloat = 60.0 fileprivate var childViews = [UIView]() fileprivate lazy var stackView: UIStackView = { let sv = UIStackView() sv.translatesAutoresizingMaskIntoConstraints = false sv.axis = NSLayoutConstraint.Axis.horizontal return sv }() open override func awakeFromNib() { super.awakeFromNib() configureScrollView() } public override init(frame: CGRect) { super.init(frame: frame) configureScrollView() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func layoutSubviews() { super.layoutSubviews() } open func addChildViews(_ views: [UIView]) { for view in views { view.layer.masksToBounds = true stackView.addArrangedSubview(view) addConstraint(NSLayoutConstraint( item: view, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.width, multiplier: 1, constant: 0) ) childViews.append(view) } } open func addChildView(_ view: UIView) { addChildViews([view]) } open func scrollToViewAtIndex(_ index: Int, animated: Bool) { if index > -1 && index < childViews.count { let width = self.frame.size.width let height = self.frame.size.height let frame = CGRect(x: CGFloat(index)*width, y: 0, width: width, height: height) scrollRectToVisible(frame, animated: animated) } } // MARK: Scroll view delegate open func scrollViewDidScroll(_ scrollView: UIScrollView) { transformViewsInScrollView(scrollView) cubeDelegate?.cubeViewDidScroll?(self) } // MARK: Private methods fileprivate func configureScrollView() { // Configure scroll view properties backgroundColor = UIColor.black showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false isPagingEnabled = true bounces = true delegate = self // Add layout constraints addSubview(stackView) addConstraint(NSLayoutConstraint( item: stackView, attribute: NSLayoutConstraint.Attribute.leading, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.leading, multiplier: 1, constant: 0) ) addConstraint(NSLayoutConstraint( item: stackView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0) ) addConstraint(NSLayoutConstraint( item: stackView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.height, multiplier: 1, constant: 0) ) addConstraint(NSLayoutConstraint( item: stackView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0) ) addConstraint(NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: stackView, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: 0) ) addConstraint(NSLayoutConstraint( item: self, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: stackView, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0) ) } fileprivate func transformViewsInScrollView(_ scrollView: UIScrollView) { let xOffset = scrollView.contentOffset.x let svWidth = scrollView.frame.width var deg = maxAngle / bounds.size.width * xOffset for index in 0 ..< childViews.count { let view = childViews[index] deg = index == 0 ? deg : deg - maxAngle let rad = deg * CGFloat(Double.pi / 180) var transform = CATransform3DIdentity transform.m34 = 1 / 500 transform = CATransform3DRotate(transform, rad, 0, 1, 0) view.layer.transform = transform let x = xOffset / svWidth > CGFloat(index) ? 1.0 : 0.0 setAnchorPoint(CGPoint(x: x, y: 0.5), forView: view) applyShadowForView(view, index: index) } } fileprivate func applyShadowForView(_ view: UIView, index: Int) { let w = self.frame.size.width let h = self.frame.size.height let r1 = frameFor(origin: contentOffset, size: self.frame.size) let r2 = frameFor(origin: CGPoint(x: CGFloat(index)*w, y: 0), size: CGSize(width: w, height: h)) // Only show shadow on right-hand side if r1.origin.x <= r2.origin.x { let intersection = r1.intersection(r2) let intArea = intersection.size.width*intersection.size.height let union = r1.union(r2) let unionArea = union.size.width*union.size.height view.layer.opacity = Float(intArea / unionArea) } } fileprivate func setAnchorPoint(_ anchorPoint: CGPoint, forView view: UIView) { var newPoint = CGPoint(x: view.bounds.size.width * anchorPoint.x, y: view.bounds.size.height * anchorPoint.y) var oldPoint = CGPoint(x: view.bounds.size.width * view.layer.anchorPoint.x, y: view.bounds.size.height * view.layer.anchorPoint.y) newPoint = newPoint.applying(view.transform) oldPoint = oldPoint.applying(view.transform) var position = view.layer.position position.x -= oldPoint.x position.x += newPoint.x position.y -= oldPoint.y position.y += newPoint.y view.layer.position = position view.layer.anchorPoint = anchorPoint } fileprivate func frameFor(origin: CGPoint, size: CGSize) -> CGRect { return CGRect(x: origin.x, y: origin.y, width: size.width, height: size.height) } }
mit
8e0155debf446d895f3e822eb1c0a23f
30.73251
139
0.57619
5.185609
false
false
false
false
bradhilton/August
Pods/Convertible/Convertible/Options/ConvertibleOptions.swift
2
3584
// // ConvertibleOptions.swift // Convertibles // // Created by Bradley Hilton on 6/11/15. // Copyright © 2015 Skyvive. All rights reserved. // import Foundation import CoreGraphics public struct ConvertibleOptions { /// Use this option to customize how json keys are decoded public struct JSONKeyDecodingStrategy: _ConvertibleOption { public let strategy: JSONDecoder.KeyDecodingStrategy public static var Default = JSONKeyDecodingStrategy(strategy: .useDefaultKeys) public init(strategy: JSONDecoder.KeyDecodingStrategy) { self.strategy = strategy } } /// Use this option to customize how data is decoded from Base64 public struct JSONKeyEncodingStrategy: _ConvertibleOption { public let strategy: JSONEncoder.KeyEncodingStrategy public static var Default = JSONKeyEncodingStrategy(strategy: .useDefaultKeys) public init(strategy: JSONEncoder.KeyEncodingStrategy) { self.strategy = strategy } } /// Use this option to customize how data is decoded from Base64 public struct Base64DecodingOptions: _ConvertibleOption { public let options: NSData.Base64DecodingOptions public static var Default = Base64DecodingOptions(options: NSData.Base64DecodingOptions()) public init(options: NSData.Base64DecodingOptions) { self.options = options } } /// Use this option to customize how data is encoded to Base64 public struct Base64EncodingOptions: _ConvertibleOption { public let options: NSData.Base64EncodingOptions public static var Default = Base64EncodingOptions(options: NSData.Base64EncodingOptions()) public init(options: NSData.Base64EncodingOptions) { self.options = options } } /// Use this option to include a custom NSDateFormatter /// Default date formatter assumes a ISO 8601 date string public struct DateFormatter: _ConvertibleOption { public let formatter: Foundation.DateFormatter public static var Default: DateFormatter = { let formatter = Foundation.DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return DateFormatter(formatter: formatter) }() public init(formatter: Foundation.DateFormatter) { self.formatter = formatter } } /// Use this option to specify how an image should be encoded public enum ImageEncoding: _ConvertibleOption { case jpeg(quality: CGFloat) case png public static var Default = ImageEncoding.png } /// Use this option to include a custom NSNumberFormatter public struct NumberFormatter: _ConvertibleOption { public let formatter: Foundation.NumberFormatter public static var Default: NumberFormatter = { let formatter = Foundation.NumberFormatter() formatter.numberStyle = Foundation.NumberFormatter.Style.decimal return NumberFormatter(formatter: formatter) }() public init(formatter: Foundation.NumberFormatter) { self.formatter = formatter } } /// Use to specify custom NSStringEncoding; default is NSUTF8StringEncoding public struct StringEncoding: _ConvertibleOption { public let encoding: String.Encoding public static var Default = StringEncoding(encoding: String.Encoding.utf8) public init(encoding: String.Encoding) { self.encoding = encoding } } }
mit
545f9adaf905365f82a5259d3622936e
37.526882
98
0.682668
5.537867
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00175-swift-parser-parseexprlist.swift
1
3749
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g func a<d>() -> [c{ enum b { case c } } class b<i : b> i: g{ func c {} e g { : g { h func i() -> } struct c<d : Sequence> { var b: d } func a<d>() -> [c<d>] { return [] } func j(d: h) -> <k>(() -> k) -> h { return { n n "\(} c i<k : i> { } y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n func ^(a: Boolean, Bool) -> Bool { return !(a) } func b((Any, e))(e: (Any) -> <d>(()-> d) -> f protocol A { func c()l k { func l() -> g { m "" } } class C: k, A { j func l()q c() -> g { m "" } } func e<r where r: A, r: k>(n: r) { n.c() } protocol A { typealias h } c k<r : A> { p f: r p p: r.h } protocol C l.e() } } class o { typealias l = l func h<j>() -> (j, j -> j) -> j { var f: ({ (c: e, f: e -> e) -> return f(c) }(k, i) let o: e = { c, g return f(c) }(l) -> m) -> p>, e> } class n<j : n> struct A<T> { let a: [(T, () -> ())] = [] } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> St} func i<l : d where l.f == c> (n: l) { } i(e()) d> Bool { e !(f) } b protocol f : b { func b ) func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { class func q() } class o: n{ class func q {} func p(e: Int = x) { } let c = p c() func r<o: y, s q n<s> ==(r(t)) protocol p : p { } protocol p { class func c() } class e: p { class func c() { } } (e() u p).v.c() k e.w == l> { } func p(c: Any, m: Any) -> (((Any, Any) -> Any) -> Any) { i) import Foundation class q<k>: c a(b: Int = 0) { } let c = a c() func d<b: Sequence, e where Optional<e> == b.Iterator.Element>(c : b) -> e? { for (mx : e?) in c { struct c<d: Sequence, b where Optional<b> == d.Iterator.Element> enum S<T> { case C(T, () -> ()) } struct A<T> { let a: [(T, () - == g> { } protocol g { typealias f typealias e } struct c<h : g> : g { typealias f = h typealias e = a<c<h>, f> a) func a<b:a protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } func g<h>() -> (h, h -> h) -> h { f f: ((h, h -> h) -> h)! j f } protocol f { class func j() } struct i { f d: f.i func j() { d.j() } } class g { typealias f = f } func g(f: Int = k) { } let i = g struct l<e : Sequence> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k func f<e>() -> (e, e -> e) -> e { e b e.c = { } { e) { f } } protocol f { class func c() } class e: f{ class func c protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } }
apache-2.0
9362c5d6e142ae88acf2cd45e7501c90
15.021368
79
0.452387
2.407836
false
false
false
false
TeamProxima/predictive-fault-tracker
mobile/SieHack/Pods/Charts/Source/Charts/Animation/Animator.swift
53
12831
// // Animator.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 import CoreGraphics #if !os(OSX) import UIKit #endif @objc(ChartAnimatorDelegate) public protocol AnimatorDelegate { /// Called when the Animator has stepped. func animatorUpdated(_ animator: Animator) /// Called when the Animator has stopped. func animatorStopped(_ animator: Animator) } @objc(ChartAnimator) open class Animator: NSObject { open weak var delegate: AnimatorDelegate? open var updateBlock: (() -> Void)? open var stopBlock: (() -> Void)? /// the phase that is animated and influences the drawn values on the x-axis open var phaseX: Double = 1.0 /// the phase that is animated and influences the drawn values on the y-axis open var phaseY: Double = 1.0 fileprivate var _startTimeX: TimeInterval = 0.0 fileprivate var _startTimeY: TimeInterval = 0.0 fileprivate var _displayLink: NSUIDisplayLink? fileprivate var _durationX: TimeInterval = 0.0 fileprivate var _durationY: TimeInterval = 0.0 fileprivate var _endTimeX: TimeInterval = 0.0 fileprivate var _endTimeY: TimeInterval = 0.0 fileprivate var _endTime: TimeInterval = 0.0 fileprivate var _enabledX: Bool = false fileprivate var _enabledY: Bool = false fileprivate var _easingX: ChartEasingFunctionBlock? fileprivate var _easingY: ChartEasingFunctionBlock? public override init() { super.init() } deinit { stop() } open func stop() { if _displayLink != nil { _displayLink?.remove(from: RunLoop.main, forMode: RunLoopMode.commonModes) _displayLink = nil _enabledX = false _enabledY = false // If we stopped an animation in the middle, we do not want to leave it like this if phaseX != 1.0 || phaseY != 1.0 { phaseX = 1.0 phaseY = 1.0 if delegate != nil { delegate!.animatorUpdated(self) } if updateBlock != nil { updateBlock!() } } if delegate != nil { delegate!.animatorStopped(self) } if stopBlock != nil { stopBlock?() } } } fileprivate func updateAnimationPhases(_ currentTime: TimeInterval) { if _enabledX { let elapsedTime: TimeInterval = currentTime - _startTimeX let duration: TimeInterval = _durationX var elapsed: TimeInterval = elapsedTime if elapsed > duration { elapsed = duration } if _easingX != nil { phaseX = _easingX!(elapsed, duration) } else { phaseX = Double(elapsed / duration) } } if _enabledY { let elapsedTime: TimeInterval = currentTime - _startTimeY let duration: TimeInterval = _durationY var elapsed: TimeInterval = elapsedTime if elapsed > duration { elapsed = duration } if _easingY != nil { phaseY = _easingY!(elapsed, duration) } else { phaseY = Double(elapsed / duration) } } } @objc fileprivate func animationLoop() { let currentTime: TimeInterval = CACurrentMediaTime() updateAnimationPhases(currentTime) if delegate != nil { delegate!.animatorUpdated(self) } if updateBlock != nil { updateBlock!() } if currentTime >= _endTime { stop() } } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingX: an easing function for the animation on the x axis /// - parameter easingY: an easing function for the animation on the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { stop() _startTimeX = CACurrentMediaTime() _startTimeY = _startTimeX _durationX = xAxisDuration _durationY = yAxisDuration _endTimeX = _startTimeX + xAxisDuration _endTimeY = _startTimeY + yAxisDuration _endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY _enabledX = xAxisDuration > 0.0 _enabledY = yAxisDuration > 0.0 _easingX = easingX _easingY = easingY // Take care of the first frame if rendering is already scheduled... updateAnimationPhases(_startTimeX) if _enabledX || _enabledY { _displayLink = NSUIDisplayLink(target: self, selector: #selector(animationLoop)) _displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOptionX: the easing function for the animation on the x axis /// - parameter easingOptionY: the easing function for the animation on the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingFunctionFromOption(easingOptionX), easingY: easingFunctionFromOption(easingOptionY)) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easing, easingY: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption)) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval) { animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: .easeInOutSine) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easing: an easing function for the animation open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _startTimeX = CACurrentMediaTime() _durationX = xAxisDuration _endTimeX = _startTimeX + xAxisDuration _endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY _enabledX = xAxisDuration > 0.0 _easingX = easing // Take care of the first frame if rendering is already scheduled... updateAnimationPhases(_startTimeX) if _enabledX || _enabledY { if _displayLink == nil { _displayLink = NSUIDisplayLink(target: self, selector: #selector(animationLoop)) _displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } } } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easingOption: the easing function for the animation open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption) { animate(xAxisDuration: xAxisDuration, easing: easingFunctionFromOption(easingOption)) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis open func animate(xAxisDuration: TimeInterval) { animate(xAxisDuration: xAxisDuration, easingOption: .easeInOutSine) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _startTimeY = CACurrentMediaTime() _durationY = yAxisDuration _endTimeY = _startTimeY + yAxisDuration _endTime = _endTimeX > _endTimeY ? _endTimeX : _endTimeY _enabledY = yAxisDuration > 0.0 _easingY = easing // Take care of the first frame if rendering is already scheduled... updateAnimationPhases(_startTimeY) if _enabledX || _enabledY { if _displayLink == nil { _displayLink = NSUIDisplayLink(target: self, selector: #selector(animationLoop)) _displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.commonModes) } } } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { animate(yAxisDuration: yAxisDuration, easing: easingFunctionFromOption(easingOption)) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis open func animate(yAxisDuration: TimeInterval) { animate(yAxisDuration: yAxisDuration, easingOption: .easeInOutSine) } }
mit
4a533e7e33a54fa1e63706bd2ecdde02
37.881818
175
0.626374
5.366374
false
false
false
false
vlribeiro/loja-desafio-ios
LojaDesafio/LojaDesafio/TransactionProduct.swift
1
1629
// // TransactionProduct.swift // LojaDesafio // // Created by Vinicius Ribeiro on 29/11/15. // Copyright © 2015 Vinicius Ribeiro. All rights reserved. // import Foundation import RealmSwift import Realm class TransactionProduct : Object { dynamic var id : Int dynamic var transactionId : Int dynamic var productId : Int dynamic var quantity : Int init(id : Int, transactionId : Int, productId : Int, quantity : Int) { self.id = id self.transactionId = transactionId self.productId = productId self.quantity = quantity super.init() } required init() { self.id = 0 self.transactionId = 0 self.productId = 0 self.quantity = 0 super.init() } override init(realm: RLMRealm, schema: RLMObjectSchema) { self.id = 0 self.transactionId = 0 self.productId = 0 self.quantity = 0 super.init(realm: realm, schema: schema) } func getDictionaryData() -> Dictionary<String,Any> { var creditCardData = Dictionary<String,Any>() creditCardData["Id"] = self.id creditCardData["TransactionId"] = self.transactionId creditCardData["ProductId"] = self.productId creditCardData["Quantity"] = self.quantity return creditCardData } override static func primaryKey() -> String? { return "id" } override var description : String { return "Produto em Transação -> { quantidade: \(self.quantity), produto: \(self.productId) }" } }
mit
d6143f197e0d1bc2470e9698ed8fa8da
24.421875
101
0.599016
4.554622
false
false
false
false
lynxerzhang/SwiftUtil
ArrayUseCase.playground/Contents.swift
1
2146
//: Playground - noun: a place where people can play //create xcode 7.2.1 and swift 2.1.1 import UIKit //create a new array var programingLanguage = [String]() var appleLanguage = ["swift", "Objective-C"] var webLanguage = ["Javascript", "Actionscript"] //contain "swift", "Objective-C", Javascript, Actionscript programingLanguage = appleLanguage + webLanguage //current study programming language is swift var currentStudy = programingLanguage[0] //swift, Objective-C let apple = programingLanguage[0...1] //swift programingLanguage.first //ActionScript programingLanguage.last //swift programingLanguage.maxElement() //ActionScript programingLanguage.minElement() //4 element programingLanguage.capacity //4 element programingLanguage.count //not empty programingLanguage.isEmpty //iterating for item in programingLanguage { } for (index, item) in programingLanguage.enumerate() { } //array method programingLanguage.contains("Swift") //true programingLanguage.dropFirst(2) //return a new array contains all but the first 2 elements programingLanguage.dropLast(2) //return a new array contains all but the last 2 elements print(programingLanguage) //not alter the orignal array programingLanguage.map { $0.lowercaseString //return a new array, not alter the original array } //@see http://stackoverflow.com/questions/6356043/how-do-i-detect-if-a-character-is-uppercase-or-lowercase //获取数组中所有首字母为大写的对象,不修改原始数组 programingLanguage.filter { return NSCharacterSet.uppercaseLetterCharacterSet().characterIsMember(unichar(($0.unicodeScalars.first?.value)!)) } programingLanguage.prefix(2) programingLanguage.suffix(2) //sort var numAry = [0, 10, 8, 2] //numAry.sortInPlace(<) //直接在原始数组中进行排序 //numAry = numAry.sort(<) //不修改原始数组,将结果作为新书组返回 struct DataObj { let version: Double let dataValue: String } var structAry: [DataObj] = [DataObj(version: 3, dataValue: "as"), DataObj(version: 2, dataValue: "ObjectiveC"), DataObj(version: 2.1, dataValue: "Swift")] structAry.sortInPlace { $0.version < $1.version }
mit
63ff29564939b4f9ed9937da28740ae1
24.797468
154
0.764475
3.489726
false
false
false
false
ktilakraj/MuvizzCode
SlideMenuControllerSwift/HelpMenuController.swift
1
2649
// // NonMenuController.swift // SlideMenuControllerSwift // // Created by Yuji Hato on 1/22/15. // Copyright (c) 2015 Yuji Hato. All rights reserved. // import UIKit class HelpMenuController: UIViewController { @IBOutlet weak var tblHelp: UITableView! weak var delegate: LeftMenuProtocol? let arroptions = ["About Us","Contact Us","Privacy","Terms"] @IBOutlet weak var imageLogo: UIImageView! @IBOutlet weak var btnsearch: UIButton! @IBOutlet weak var btnback: UIButton! override func viewDidLoad() { super.viewDidLoad() tblHelp.separatorStyle = UITableViewCellSeparatorStyle.none } @IBAction func btnsearchclick(_ sender: AnyObject) { } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //self.removeNavigationBarItem() //self.setNavigationBarItem() self.navigationController?.setNavigationBarHidden(true, animated: true) } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil, completion: { (context: UIViewControllerTransitionCoordinatorContext!) -> Void in guard let vc = (self.slideMenuController()?.mainViewController as? UINavigationController)?.topViewController else { return } if vc.isKind(of: HelpMenuController.self) { self.slideMenuController()?.removeLeftGestures() self.slideMenuController()?.removeRightGestures() } }) } @IBAction func didTouchToMain(_ sender: UIButton) { delegate?.changeViewController(LeftMenu.main) } } //MARK:Table view data source extension HelpMenuController: UITableViewDataSource { public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arroptions.count; } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cellHelp", for: indexPath) cell.textLabel?.text = arroptions[indexPath.row] cell.textLabel?.textColor = UIColor.white cell.selectionStyle = UITableViewCellSelectionStyle.none return cell } } extension HelpMenuController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("the selected indexpath \(indexPath.row)") } }
mit
580aab95eb6fa962d9f83f59d189fecc
32.961538
135
0.685919
5.298
false
false
false
false
kingcos/Swift-3-Design-Patterns
11-Observer_Pattern.playground/Contents.swift
1
1512
//: Playground - noun: a place where people can play // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns import UIKit // 协议 protocol Subject { func attach(_ observer: Observer) func detach(_ observer: Observer) func notify() } // 观察者 class Observer: Hashable { var name: String var sub: Subject var hashValue: Int { return "\(name)".hashValue } static func ==(l: Observer, r: Observer) -> Bool { return l.hashValue == r.hashValue } init(_ name: String, _ sub: Subject) { self.name = name self.sub = sub } func update() {} } class Boss: Subject { var observers = Set<Observer>() func attach(_ observer: Observer) { observers.insert(observer) } func detach(_ observer: Observer) { observers.remove(observer) } func notify() { for o in observers { o.update() } } } // 看股票 class StockObserver: Observer { override func update() { print("\(name) 关闭股票,继续工作") } } // 看 NBA class NBAObserver: Observer { override func update() { print("\(name) 关闭 NBA,继续工作") } } let boss = Boss() let colleagueA = StockObserver("A", boss) let colleagueB = NBAObserver("B", boss) // 添加通知者 boss.attach(colleagueA) boss.attach(colleagueB) // 移除通知者 boss.detach(colleagueA) // 发出通知 boss.notify()
apache-2.0
986b11c6fc5b6e024dc481ea97c54004
17.384615
90
0.591353
3.558313
false
false
false
false
lucaslimapoa/NewsAPISwift
Tests/Utilities/Fakes.swift
1
5315
// // Fakes.swift // Tests // // Created by Lucas Lima on 22/06/18. // Copyright © 2018 Lucas Lima. All rights reserved. // import Foundation @testable import NewsAPISwift struct Fakes { struct NewsAPI { static let noApiKeyErrorJsonData = """ { "status": "error", "code": "apiKeyMissing", "message": "Your API key is missing. Append this to the URL with the apiKey param, or use the x-api-key HTTP header." } """.data(using: .utf8)! } } extension Fakes { struct NewsAPITarget { static let allSources = NewsAPISwift.NewsAPITarget.sources(category: .all, language: .all, country: .all) static let allTopHeadlines = NewsAPISwift.NewsAPITarget.topHeadlines(q: nil, sources: nil, category: .all, language: .all, country: .all, pageSize: nil, page: nil) } } extension Fakes { struct Sources { static let successJsonData = """ { "status":"ok", "sources":[ { "id":"source-id", "name":"Source", "description":"Source Description", "url":"http://source.com", "category":"general", "language":"en", "country":"us" } ] } """.data(using: .utf8)! static let invalidJsonData = """ { "status":"ok", "sources":[ { "id":"source-id", "name":"Source", "description":"Source Description", "category":"general", "language":"en", "country":"us" } ] } """.data(using: .utf8)! static let emptyJsonData = """ { "status":"ok", "sources":[] } """.data(using: .utf8)! static let source = NewsSource(id: "source-id", name: "Source", sourceDescription: "Source Description", url: URL(string: "http://source.com")!, category: .general, language: .en, country: .us) } } extension Fakes { struct TopHeadlines { static let successTopHeadlinesJsonData = """ { "status": "ok", "totalResults": 1, "articles": [ { "source": { "id": null, "name": "source 1" }, "author": "Source 1 Author", "title": "Source 1", "description": "Source 1 Description", "url": "https://www.source1.com", "urlToImage": "https://www.source1.com/source01.jpg", "publishedAt": "2018-06-26T12:57:43Z" } ] } """.data(using: .utf8)! static let fractionalSuccessTopHeadlinesJsonData = """ { "status": "ok", "totalResults": 1, "articles": [ { "source": { "id": null, "name": "source 1" }, "author": "Source 1 Author", "title": "Source 1", "description": "Source 1 Description", "url": "https://www.source1.com", "urlToImage": "https://www.source1.com/source01.jpg", "publishedAt": "2018-06-26T19:22:03.7291615Z" } ] } """.data(using: .utf8)! static let topHeadline1 = NewsArticle(source: NewsArticle.NewsSource(id: nil, name: "source 1"), author: "Source 1 Author", title: "Source 1", articleDescription: "Source 1 Description", url: URL(string: "https://www.source1.com")!, urlToImage: URL(string: "https://www.source1.com/source01.jpg"), publishedAt: DateFormatter.iso8601.date(from: "2018-06-26T12:57:43Z")!) static let topHeadlineFractionalDate = NewsArticle(source: NewsArticle.NewsSource(id: nil, name: "source 1"), author: "Source 1 Author", title: "Source 1", articleDescription: "Source 1 Description", url: URL(string: "https://www.source1.com")!, urlToImage: URL(string: "https://www.source1.com/source01.jpg"), publishedAt: DateFormatter.iso8601mm.date(from: "2018-06-26T19:22:03.7291615Z")!) } }
mit
14aceeb5b8601b9653ccd0cd37e258ad
34.426667
171
0.406662
4.943256
false
false
false
false
Foild/PagingMenuController
Example/PagingMenuControllerDemo/UsersViewController.swift
1
2241
// // UsersViewController.swift // PagingMenuControllerDemo // // Created by Yusuke Kita on 5/10/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit class UsersViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var users = [[String: AnyObject]]() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // let url = NSURL(string: "https://api.github.com/users") // let request = NSURLRequest(URL: url!) // let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration()) // // let task = session.dataTaskWithRequest(request) { [unowned self] data, response, error in // let result = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as! [[String: AnyObject]] // self.users = result // // dispatch_async(dispatch_get_main_queue(), { () -> Void in // self.tableView.reloadData() // }) // } // task.resume() } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return users.count } // MARK: - UITableViewDelegate func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) let user = users[indexPath.row] cell.textLabel?.text = user["login"] as? String return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let detailViewController = storyboard?.instantiateViewControllerWithIdentifier("DetailViewController") as! DetailViewController navigationController?.pushViewController(detailViewController, animated: true) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } }
mit
d78c3780e0a2b5b6219c77b639a8d75c
35.754098
135
0.661758
5.297872
false
false
false
false
ldjhust/BeautifulPhotos-Swift2.0
BeautifulPhotos(Swift2.0)/ListPhotos/Controllers/MyCollectionViewController.swift
1
9276
// // ViewController.swift // BeautifulPhotos(Swift2.0) // // Created by ldjhust on 15/9/19. // Copyright © 2015年 example. All rights reserved. // import UIKit import MJRefresh import SDWebImage import ReachabilitySwift import BDKNotifyHUD let cellReuseId: String = "reuseCellId" let headerReuseId: String = "reuseHeaderId" class MyCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { var titleView: MyTitleView! var detailImageView: ShowSingleImageView! var reachbility: Reachability! var isNetworking: Bool = true var isRefreshing: Bool = false var currentPage: Int = 1 var kingImageString: String = "壁纸" { didSet { // 更换显示的壁纸种类 self.currentPage = 1 self.imageDatas = nil self.collectionView?.header.beginRefreshing() } } var imageDatas: [MyImageDataModel]? { didSet { // 获取数据后,刷新collectionView数据 self.collectionView?.reloadData() self.collectionView?.header.endRefreshing() self.collectionView?.footer.endRefreshing() self.isRefreshing = false } } // MARK: - Lifecycle // MARK: - Initializers override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.collectionView?.backgroundColor = UIColor.whiteColor() self.collectionView?.contentInset.top = 46 self.collectionView?.contentInset.left = 2 self.collectionView?.contentInset.right = 2 // 注册可重用的cell self.collectionView?.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: cellReuseId) // 注册可重用header self.collectionView?.registerClass(MyCollectionHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseId) self.titleView = MyTitleView(frame: CGRect(x: 0, y: 0, width: self.collectionView!.frame.width, height: 44)) // MARK: - 监听网络状态 self.reachbility = Reachability.reachabilityForInternetConnection() NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: self.reachbility) self.reachbility.startNotifier() // 启动监听 // MARK: - add subviews self.view?.addSubview(self.titleView) // MARK: - 设置下拉刷新、上拉加载更多 self.collectionView?.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "pullDwonToRefresh") self.collectionView?.footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: "pullUpToRefresh") // MARK: - 程序一开始就要进入下拉刷新获取数据 self.collectionView?.header.beginRefreshing() } override func prefersStatusBarHidden() -> Bool { // 隐藏statusBar return true } // MARK: - Event Responder func pullDwonToRefresh() { if self.reachbility.currentReachabilityStatus == Reachability.NetworkStatus.NotReachable { // 没有网络 self.collectionView?.header.endRefreshing() self.collectionView?.footer.endRefreshing() self.isRefreshing = false let hud = BDKNotifyHUD.notifyHUDWithImage(UIImage(named: "XXX")!, text: "没有网络,请检查!") as! BDKNotifyHUD hud.center = UIApplication.sharedApplication().keyWindow!.center UIApplication.sharedApplication().keyWindow!.addSubview(hud) hud.presentWithDuration(1.0, speed: 0.5, inView: UIApplication.sharedApplication().keyWindow!) { hud.removeFromSuperview() } } else { if !isRefreshing { isRefreshing = true // 设置collectionView正在刷新 // 从百度图片获取图片, 刷新永远从第一页开始取 NetworkPersistent.requestDataWithURL(self, url: self.makeURLString(self.kingImageString, pageNumber: 1), parameters: nil, action: "pullDwon") } } } func pullUpToRefresh() { if self.reachbility.currentReachabilityStatus == Reachability.NetworkStatus.NotReachable { // 没有网络 self.collectionView?.header.endRefreshing() self.collectionView?.footer.endRefreshing() self.isRefreshing = false let hud = BDKNotifyHUD.notifyHUDWithImage(UIImage(named: "XXX")!, text: "没有网络,请检查!") as! BDKNotifyHUD hud.center = UIApplication.sharedApplication().keyWindow!.center UIApplication.sharedApplication().keyWindow!.addSubview(hud) hud.presentWithDuration(1.0, speed: 0.5, inView: UIApplication.sharedApplication().keyWindow!) { hud.removeFromSuperview() } } else { if !isRefreshing { isRefreshing = true // 设置collectionView正在刷新 self.currentPage++ // 获取下一页 self.collectionView?.footer.beginRefreshing() NetworkPersistent.requestDataWithURL(self, url: self.makeURLString(self.kingImageString, pageNumber: self.currentPage), parameters: nil, action: "pullUp") } } } // 监听网络状态 func reachabilityChanged(note: NSNotification) { // 网络发生切换,可以做相应的处理 } // MARK: - private methods func makeURLString(kindImageString: String, pageNumber: Int) -> String { return "http://image.baidu.com/data/imgs?col=\(kindImageString)&tag=全部&pn=\(pageNumber)&p=channel&rn=30&from=1".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! } // MARK: - UICollectionViewDataSource override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if self.imageDatas == nil { return 0 } else { return self.imageDatas!.count - 1 // 第一张图片用来放在Header里面 } } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = self.collectionView?.dequeueReusableCellWithReuseIdentifier(cellReuseId, forIndexPath: indexPath) as? MyCollectionViewCell // Config Cell... cell?.backgroundImageView.sd_setImageWithURL(NSURL(string: self.imageDatas![indexPath.row+1].imageURLString)) return cell! } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { // 因为只有header,所以不需要判断kind是header还是footer let headerView = self.collectionView?.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: headerReuseId, forIndexPath: indexPath) as? MyCollectionHeaderView // Config header... if self.imageDatas != nil { headerView?.backgroundImageView.sd_setImageWithURL(NSURL(string: self.imageDatas![0].imageURLString)) } return headerView! } // MARK: - UICollectionViewDelegate override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell let locationTap = CGPointMake(cell.center.x, cell.center.y - collectionView.contentOffset.y) // 随着滚动cell的垂直坐标一直在增加,所以要获取准确相对于屏幕上方的y值,需减去滚动的距离 self.detailImageView = nil // 清楚之前的值 self.detailImageView = ShowSingleImageView() self.detailImageView.showImageView(cell.backgroundImageView!, startCenter: locationTap) } // MARK: - UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { // Margin return UIEdgeInsets(top: 2, left: 0, bottom: 2, right: 0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { // cell水平最小间距 return 2.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { // cell行最小间距 return 2.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { // cell的尺寸 let width = (self.collectionView!.frame.width - 6) / 2 return CGSize(width: width, height: width * 3 / 4) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { let width = self.collectionView!.frame.width return CGSize(width: width, height: width * 3 / 4) } }
mit
b35ed6d8445906fff85772a22ea01aae
34.407258
213
0.723722
5.023455
false
false
false
false
Perfect-Server-Swift-LearnGuide/Today-News-Admin
Sources/Handler/Index.swift
1
1200
// // Index.swift // Today-News-Admin // // Created by Mac on 17/8/25. // // import PerfectLib import PerfectHTTP import PerfectMustache import Common public struct Index { public static func index() -> RequestHandler { return { req, res in let isParams = req.params().count > 0 var action = req.pathComponents.last ?? "index" action = action == "/" ? "index" : action var handler: MustachePageHandler? switch action { /// 首页 case Server.Route.Index.index.rawValue: handler = IndexHandler() default: print("default") } if !isParams { if let hand = handler { mustacheRequest( request: req, response: res, handler: hand, templatePath: req.documentRoot + "/\(action).mustache" ) } } res.completed() } } }
apache-2.0
18e1255abe3ad97eeed8cae01579414f
22.45098
79
0.417224
5.615023
false
false
false
false
geekaurora/ReactiveListViewKit
ReactiveListViewKit/ReactiveListViewKit/CZListDiff.swift
1
14828
// // CZListDiff.swift // ReactiveListViewKit // // Created by Cheng Zhang on 1/5/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import UIKit public struct MovedIndexPath: Equatable, Hashable { let from: IndexPath let to: IndexPath public static func == (lhs: MovedIndexPath, rhs: MovedIndexPath) -> Bool { return (lhs.from == rhs.from && lhs.to == rhs.to) } public func hash(into hasher: inout Hasher) { hasher.combine(from) hasher.combine(to) } } public struct MovedSection: Equatable, Hashable { let from: Int let to: Int public static func == (lhs: MovedSection, rhs: MovedSection) -> Bool { return (lhs.from == rhs.from && lhs.to == rhs.to) } public var hashValue: Int { return from * 13753 + to } } /** List diff algorithm implementation class - moved - only if pairs exchange, otherwise it will be moved automatically after insert/delete - only changes in ascending order: 0,2 => 2,0 */ public class CZListDiff: NSObject { /// RowDiffResultKey for Rows public enum RowDiffResultKey: Int, CaseCountable { case deleted = 0, unchanged, moved, updated, inserted static var allEnums: [RowDiffResultKey] { var res = [RowDiffResultKey](), i = 0 while let item = RowDiffResultKey(rawValue: i) { res.append(item) i += 1 } return res } } /// RowDiffResultKey for Sections public enum SectionDiffResultKey: Int, CaseCountable { case deletedSections = 0, unchangedSections, movedSections, updatedSections, insertedSections static var allEnums: [SectionDiffResultKey] { var res = [SectionDiffResultKey](), i = 0 while let item = SectionDiffResultKey(rawValue: i) { res.append(item) i += 1 } return res } } /// Compare current/previous SectionModels, output diffing sections/rows public typealias SectionModelsDiffResult = (sections: [SectionDiffResultKey: [CZSectionModel]], rows: [RowDiffResultKey: [CZFeedModel]]) private static func diffSectionModels(current: [CZSectionModel], prev: [CZSectionModel]) -> (sections: [SectionDiffResultKey: [CZSectionModel]], rows: [RowDiffResultKey: [CZFeedModel]]) { let currFeedModels = [CZFeedModel](current.flatMap({$0.feedModels})) let prevFeedModels = [CZFeedModel](prev.flatMap({$0.feedModels})) // Pre-calculate diffing results on FeedModel level let rowsDiff: [RowDiffResultKey: [CZFeedModel]] = self.diffFeedModels(current: currFeedModels, prev: prevFeedModels) var sectionsDiff = [SectionDiffResultKey: [CZSectionModel]]() //================================================================================= // Sections Diffing //================================================================================= // `inserted` - none of FeedModels in current section exists in prev sections let insertedSections = current.filter { currSectionModel in !currSectionModel.feedModels.contains { currFeedModel in prevFeedModels.contains { prevFeedModel in prevFeedModel.isEqual(toDiffableObj: currFeedModel) } } } sectionsDiff[.insertedSections] = insertedSections // `deleted` - none of FeedModels in prev section exists in current sections let deletedSections = prev.filter { prevSectionModel in !prevSectionModel.feedModels.contains{ prevFeedModel in currFeedModels.contains { currFeedModel in currFeedModel.isEqual(toDiffableObj: prevFeedModel) } } } sectionsDiff[.deletedSections] = deletedSections // `unchanged` var unchangedSections = [CZSectionModel]() // `moved` - meet 2 conditions: // 1) prev/curr SectionModel equals // 2) index changes var movedSections = [CZSectionModel]() for (index, currSectionModel) in current.enumerated() { if let oldIndex = prev.index(where: { $0.isEqual(toDiffableObj: currSectionModel)}) { if index == oldIndex { unchangedSections.append(currSectionModel) } else { movedSections.append(currSectionModel) } } } sectionsDiff[.unchangedSections] = unchangedSections sectionsDiff[.movedSections] = movedSections return (sectionsDiff, rowsDiff) } public static func diffFeedModels<FeedModelType: CZFeedModelable>(current currFeedModels: [FeedModelType], prev prevFeedModels: [FeedModelType]) -> [RowDiffResultKey: [FeedModelType]] { var rowsDiff = [RowDiffResultKey: [FeedModelType]]() //================================================================================= // Rows Diffing //================================================================================= // `deleted` - prev FeedModel doesn't exists in current FeedModels let removedModels = prevFeedModels.filter { oldFeedModel in !currFeedModels.contains { $0.viewModel.diffId == oldFeedModel.viewModel.diffId } } rowsDiff[.deleted] = removedModels // `unchanged` - FeedModel with same id in prev/curr FeedModels equals let unchangedModels = currFeedModels.filter { newFeedModel in prevFeedModels.contains { $0.viewModel.diffId == newFeedModel.viewModel.diffId && $0.isEqual(toDiffableObj: newFeedModel) } } rowsDiff[.unchanged] = unchangedModels // `updated` - FeedModel with same id in prev/curr FeedModels doesn't equal let updatedModels = currFeedModels.filter { newFeedModel in prevFeedModels.contains { $0.viewModel.diffId == newFeedModel.viewModel.diffId && !$0.isEqual(toDiffableObj: newFeedModel) } } rowsDiff[.updated] = updatedModels // `inserted` - current FeedModel doesn't exist in prev FeedModels let insertedModels = currFeedModels.filter { newFeedModel in !prevFeedModels.contains { $0.viewModel.diffId == newFeedModel.viewModel.diffId } } rowsDiff[.inserted] = insertedModels return rowsDiff } public static func validatedMovedSections(_ sections: [MovedSection]) -> [MovedSection] { return sections } public static func validatedMovedIndexPathes(_ movedIndexPathes: [MovedIndexPath]) -> [MovedIndexPath] { return movedIndexPathes } // MARK: - Diff function returns IndexPaths/IndexSet public typealias SectionIndexDiffResult = (sections: [SectionDiffResultKey: Any], rows: [RowDiffResultKey: [Any]]) /// Compare prev/current SectionModels, output section/row diffing indexes /// /// - Parameters: /// - current : current SectionModels /// - prev : prev SectionModels /// - Returns : Tuple - (sectionDiffIndexesMap, rowDiffIndexesMap) public static func diffSectionModelIndexes(current: [CZSectionModel], prev: [CZSectionModel]) -> SectionIndexDiffResult { var sectionsDiff: [SectionDiffResultKey: Any] = [:] var rowsDiff: [RowDiffResultKey: [Any]] = [:] let modelsDiffRes: SectionModelsDiffResult = diffSectionModels(current: current, prev: prev) let sectionModelsDiffRes = modelsDiffRes.sections let rowModelsDiffRes = modelsDiffRes.rows /*- Sections Diff -*/ var insertedSections: IndexSet? = nil var deletedSections: IndexSet? = nil // deleted if let deletedSectionModels = sectionModelsDiffRes[.deletedSections] { deletedSections = IndexSet(deletedSectionModels.compactMap {sectionModel in prev.index(where: { $0.isEqual(toDiffableObj: sectionModel) }) }) sectionsDiff[.deletedSections] = deletedSections } // moved if let movedSections = sectionModelsDiffRes[.movedSections] { let res: [MovedSection] = movedSections.compactMap {sectionModel in let oldIndex = prev.index(where: { $0.isEqual(toDiffableObj: sectionModel) })! let newIndex = current.index(where: { $0.isEqual(toDiffableObj: sectionModel) })! return MovedSection(from: oldIndex, to: newIndex) } sectionsDiff[.movedSections] = validatedMovedSections(res) } // inserted if let insertedSectionModels = sectionModelsDiffRes[.insertedSections] { insertedSections = IndexSet(insertedSectionModels.compactMap {sectionModel in current.index(where: { $0.isEqual(toDiffableObj: sectionModel) }) }) sectionsDiff[.insertedSections] = insertedSections } /*- Rows Diff -*/ // deleted rowsDiff[.deleted] = rowModelsDiffRes[.deleted]?.compactMap({ indexPath(forFeedModel: $0, inSectionModels: prev) }).filter({ // exclude "deletedSection" elements guard let deletedSections = deletedSections, let indexPath = $0 as? IndexPath else {return true} return !deletedSections.contains(indexPath.section) }) // unchanged rowsDiff[.unchanged] = rowModelsDiffRes[.unchanged]?.compactMap { // exclude "moved" guard movedIndexPath(forFeedModel: $0, oldSectionModels: prev, newSectionModels: current) == nil else {return nil} return indexPath(forFeedModel: $0, inSectionModels: current) } // moved let unchanged = rowModelsDiffRes[.unchanged] ?? [] let updated = rowModelsDiffRes[.updated] ?? [] let movedRows = [unchanged, updated].joined().compactMap { movedIndexPath(forFeedModel: $0, oldSectionModels: prev, newSectionModels: current) }.filter({ // exclude "inserted" section guard let insertedSections = insertedSections else { return true } return !insertedSections.contains($0.to.section) }) rowsDiff[.moved] = validatedMovedIndexPathes(movedRows) // updated rowsDiff[.updated] = rowModelsDiffRes[.updated]?.compactMap ({ indexPath(forFeedModel: $0, inSectionModels: current) }).filter({ // exclude "moved" rows guard let indexPath = $0 as? IndexPath, let movedItems = rowsDiff[.moved] as? [MovedIndexPath] else {return true} return !movedItems.contains(where: {$0.to == indexPath}) }) // inserted rowsDiff[.inserted] = rowModelsDiffRes[.inserted]?.compactMap ({ indexPath(forFeedModel: $0, inSectionModels: current) }).filter({ // exclude "inserted" section guard let insertedSections = insertedSections, let indexPath = $0 as? IndexPath else {return true} return !insertedSections.contains(indexPath.section) }) let sectionIndexDiffResult = (sectionsDiff, rowsDiff) CZListDiff.prettyPrint(sectionIndexDiffResult: sectionIndexDiffResult) return sectionIndexDiffResult } public static func sectionCount(for sectionDiffValue: Any?) -> Int { if let section = sectionDiffValue as? IndexSet { return section.count } else if let section = sectionDiffValue as? [MovedSection] { return section.count } else { return 0 } } private static func movedIndexPath<FeedModelType: CZFeedModelable> (forFeedModel feedModel: FeedModelType, oldSectionModels: [CZSectionModel], newSectionModels: [CZSectionModel]) -> MovedIndexPath? { if let oldIndexPath = indexPath(forFeedModel: feedModel, inSectionModels: oldSectionModels), let newIndexPath = indexPath(forFeedModel: feedModel, inSectionModels: newSectionModels), oldIndexPath != newIndexPath { return MovedIndexPath(from: oldIndexPath, to: newIndexPath) } return nil } private static func indexPath<FeedModelType: CZFeedModelable> (forFeedModel feedModel: FeedModelType, inSectionModels sectionModels: [CZSectionModel]) -> IndexPath? { for (i, sectionModel) in sectionModels.enumerated() { if let row = sectionModel.feedModels.index(where: { feedModel.isEqual(toDiffableObj: $0) }) { return IndexPath(row: row, section: i) } } return nil } private static func prettyPrint(sectionIndexDiffResult: SectionIndexDiffResult) { let sectionsDiff = sectionIndexDiffResult.sections let rowsDiff = sectionIndexDiffResult.rows // Print count of items dbgPrint("\n******************************\nFeedListFacadeView DiffResult\n******************************") SectionDiffResultKey.allEnums.forEach { dbgPrint("\($0): \(sectionCount(for: sectionsDiff[$0])); ") } dbgPrint("**************************") RowDiffResultKey.allEnums.forEach { dbgPrint("\($0): \(rowsDiff[$0]?.count ?? 0); ") } dbgPrint("**************************") // Print model of items SectionDiffResultKey.allEnums.forEach { dbgPrint("\($0): \(PrettyString(sectionsDiff[$0] ?? [])); ") } dbgPrint("**************************") RowDiffResultKey.allEnums.forEach { dbgPrint("\($0): \(PrettyString(rowsDiff[$0] ?? [])); ") } dbgPrint("**************************") } } /// Protocol for enum providing the count of enumation public protocol CaseCountable { static func countCases() -> Int } // Provide default implementation to count the cases for Int enums assuming starting at 0 and contiguous extension CaseCountable where Self : RawRepresentable, Self.RawValue == Int { // count the number of cases in the enum public static func countCases() -> Int { // starting at zero, verify whether the enum can be instantiated from the Int and increment until it cannot var count = 0 while let _ = Self(rawValue: count) { count += 1 } return count } }
mit
0ccd6d3a9df0f66346f018d35a487a4e
41.729107
164
0.597693
4.968834
false
false
false
false
lorentey/swift
stdlib/public/core/LazyCollection.swift
19
5230
//===--- LazyCollection.swift ---------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// public protocol LazyCollectionProtocol: Collection, LazySequenceProtocol where Elements: Collection { } extension LazyCollectionProtocol { // Lazy things are already lazy @inlinable // protocol-only public var lazy: LazyCollection<Elements> { return elements.lazy } } extension LazyCollectionProtocol where Elements: LazyCollectionProtocol { // Lazy things are already lazy @inlinable // protocol-only public var lazy: Elements { return elements } } /// A collection containing the same elements as a `Base` collection, /// but on which some operations such as `map` and `filter` are /// implemented lazily. /// /// - See also: `LazySequenceProtocol`, `LazyCollection` public typealias LazyCollection<T: Collection> = LazySequence<T> extension LazyCollection: Collection { /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. public typealias Index = Base.Index public typealias Indices = Base.Indices public typealias SubSequence = Slice<LazySequence> /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable public var startIndex: Index { return _base.startIndex } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// `endIndex` is always reachable from `startIndex` by zero or more /// applications of `index(after:)`. @inlinable public var endIndex: Index { return _base.endIndex } @inlinable public var indices: Indices { return _base.indices } // TODO: swift-3-indexing-model - add docs @inlinable public func index(after i: Index) -> Index { return _base.index(after: i) } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable public subscript(position: Index) -> Element { return _base[position] } /// A Boolean value indicating whether the collection is empty. @inlinable public var isEmpty: Bool { return _base.isEmpty } /// Returns the number of elements. /// /// To check whether a collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if `Self` conforms to `RandomAccessCollection`; /// O(*n*) otherwise. @inlinable public var count: Int { return _base.count } // The following requirement enables dispatching for firstIndex(of:) and // lastIndex(of:) when the element type is Equatable. /// Returns `Optional(Optional(index))` if an element was found; /// `Optional(nil)` if the element doesn't exist in the collection; /// `nil` if a search was not performed. /// /// - Complexity: Better than O(*n*) @inlinable public func _customIndexOfEquatableElement( _ element: Element ) -> Index?? { return _base._customIndexOfEquatableElement(element) } /// Returns `Optional(Optional(index))` if an element was found; /// `Optional(nil)` if the element doesn't exist in the collection; /// `nil` if a search was not performed. /// /// - Complexity: Better than O(*n*) @inlinable public func _customLastIndexOfEquatableElement( _ element: Element ) -> Index?? { return _base._customLastIndexOfEquatableElement(element) } // TODO: swift-3-indexing-model - add docs @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _base.index(i, offsetBy: n) } // TODO: swift-3-indexing-model - add docs @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _base.index(i, offsetBy: n, limitedBy: limit) } // TODO: swift-3-indexing-model - add docs @inlinable public func distance(from start: Index, to end: Index) -> Int { return _base.distance(from:start, to: end) } } extension LazyCollection: LazyCollectionProtocol { } extension LazyCollection: BidirectionalCollection where Base: BidirectionalCollection { @inlinable public func index(before i: Index) -> Index { return _base.index(before: i) } } extension LazyCollection: RandomAccessCollection where Base: RandomAccessCollection {} extension Slice: LazySequenceProtocol where Base: LazySequenceProtocol { } extension ReversedCollection: LazySequenceProtocol where Base: LazySequenceProtocol { }
apache-2.0
d656e1112fd25f790453b7e7f2828d48
31.283951
87
0.681262
4.424704
false
false
false
false
narner/AudioKit
AudioKit/Common/MIDI/Packets/MIDIPacketList+SequenceType.swift
1
650
// // MIDIPacketList+SequenceType.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // extension MIDIPacketList: Sequence { public typealias Element = MIDIPacket public func makeIterator() -> AnyIterator<Element> { var p: MIDIPacket = packet var idx: UInt32 = 0 return AnyIterator { guard idx < self.numPackets else { return nil } defer { p = MIDIPacketNext(&p).pointee idx += 1 } return p } } }
mit
67b784dca73dad2841bc79ad28eb3a01
23.037037
62
0.557781
5.070313
false
false
false
false
PhamBaTho/BTNavigationDropdownMenu
Source/Extension/UIViewController+Extension.swift
1
2633
// // UIViewController+Extension.swift // // Copyright (c) 2017 PHAM BA THO ([email protected]). All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit internal extension UIViewController { // Get ViewController in top present level var topPresentedViewController: UIViewController? { var target: UIViewController? = self while (target?.presentedViewController != nil) { target = target?.presentedViewController } return target } // Get top VisibleViewController from ViewController stack in same present level. // It should be visibleViewController if self is a UINavigationController instance // It should be selectedViewController if self is a UITabBarController instance var topVisibleViewController: UIViewController? { if let navigation = self as? UINavigationController { if let visibleViewController = navigation.visibleViewController { return visibleViewController.topVisibleViewController } } if let tab = self as? UITabBarController { if let selectedViewController = tab.selectedViewController { return selectedViewController.topVisibleViewController } } return self } // Combine both topPresentedViewController and topVisibleViewController methods, to get top visible viewcontroller in top present level var topMostViewController: UIViewController? { return self.topPresentedViewController?.topVisibleViewController } }
mit
8d04fc24fdc8f97b00d8ba0da09c909e
45.192982
139
0.725788
5.462656
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/ConversationViewController+ConversationContentViewControllerDelegate.swift
1
7597
// Wire // Copyright (C) 2020 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireSystem import WireDataModel import WireSyncEngine private let zmLog = ZMSLog(tag: "ConversationViewController+ConversationContentViewControllerDelegate") extension ConversationViewController: ConversationContentViewControllerDelegate { func didTap(onUserAvatar user: UserType, view: UIView, frame: CGRect) { let profileViewController = ProfileViewController(user: user, viewer: ZMUser.selfUser(), conversation: conversation, viewControllerDismisser: self) profileViewController.preferredContentSize = CGSize.IPadPopover.preferredContentSize profileViewController.delegate = self endEditing() createAndPresentParticipantsPopoverController(with: frame, from: view, contentViewController: profileViewController.wrapInNavigationController(setBackgroundColor: true)) } func conversationContentViewController(_ contentViewController: ConversationContentViewController, willDisplayActiveMediaPlayerFor message: ZMConversationMessage?) { conversationBarController.dismiss(bar: mediaBarViewController) } func conversationContentViewController(_ contentViewController: ConversationContentViewController, didEndDisplayingActiveMediaPlayerFor message: ZMConversationMessage) { conversationBarController.present(bar: mediaBarViewController) } func conversationContentViewController(_ contentViewController: ConversationContentViewController, didTriggerResending message: ZMConversationMessage) { ZMUserSession.shared()?.enqueue({ message.resend() }) } func conversationContentViewController(_ contentViewController: ConversationContentViewController, didTriggerEditing message: ZMConversationMessage) { guard message.textMessageData?.messageText != nil else { return } inputBarController.editMessage(message) } func conversationContentViewController(_ contentViewController: ConversationContentViewController, didTriggerReplyingTo message: ZMConversationMessage) { let replyComposingView = contentViewController.createReplyComposingView(for: message) inputBarController.reply(to: message, composingView: replyComposingView) } func conversationContentViewController(_ controller: ConversationContentViewController, shouldBecomeFirstResponderWhenShowMenuFromCell cell: UIView) -> Bool { if inputBarController.inputBar.textView.isFirstResponder { inputBarController.inputBar.textView.overrideNextResponder = cell NotificationCenter.default.addObserver(self, selector: #selector(menuDidHide(_:)), name: UIMenuController.didHideMenuNotification, object: nil) return false } return true } func conversationContentViewController(_ contentViewController: ConversationContentViewController, performImageSaveAnimation snapshotView: UIView?, sourceRect: CGRect) { if let snapshotView = snapshotView { view.addSubview(snapshotView) } snapshotView?.frame = view.convert(sourceRect, from: contentViewController.view) let targetView = inputBarController.photoButton let targetCenter = view.convert(targetView.center, from: targetView.superview) UIView.animate(withDuration: 0.33, delay: 0, options: .curveEaseIn, animations: { snapshotView?.center = targetCenter snapshotView?.alpha = 0 snapshotView?.transform = CGAffineTransform(scaleX: 0.01, y: 0.01) }, completion: { _ in snapshotView?.removeFromSuperview() self.inputBarController.bounceCameraIcon() }) } func conversationContentViewControllerWants(toDismiss controller: ConversationContentViewController) { openConversationList() } func conversationContentViewController(_ controller: ConversationContentViewController, presentGuestOptionsFrom sourceView: UIView) { guard conversation.conversationType == .group else { zmLog.error("Illegal Operation: Trying to show guest options for non-group conversation") return } let groupDetailsViewController = GroupDetailsViewController(conversation: conversation) let navigationController = groupDetailsViewController.wrapInNavigationController(setBackgroundColor: true) groupDetailsViewController.presentGuestOptions(animated: false) presentParticipantsViewController(navigationController, from: sourceView) } func conversationContentViewController(_ controller: ConversationContentViewController, presentServicesOptionFrom sourceView: UIView) { guard conversation.conversationType == .group else { zmLog.error("Illegal Operation: Trying to show services options for non-group conversation") return } let groupDetailsViewController = GroupDetailsViewController(conversation: conversation) let navigationController = groupDetailsViewController.wrapInNavigationController() groupDetailsViewController.presentServicesOptions(animated: false) presentParticipantsViewController(navigationController, from: sourceView) } func conversationContentViewController(_ controller: ConversationContentViewController, presentParticipantsDetailsWithSelectedUsers selectedUsers: [UserType], from sourceView: UIView) { if let groupDetailsViewController = (participantsController as? UINavigationController)?.topViewController as? GroupDetailsViewController { groupDetailsViewController.presentParticipantsDetails(with: conversation.sortedOtherParticipants, selectedUsers: selectedUsers, animated: false) } if let participantsController = participantsController { presentParticipantsViewController(participantsController, from: sourceView) } } } extension ConversationViewController { func presentParticipantsViewController(_ viewController: UIViewController, from sourceView: UIView) { ConversationInputBarViewController.endEditingMessage() inputBarController.inputBar.textView.resignFirstResponder() createAndPresentParticipantsPopoverController(with: sourceView.bounds, from: sourceView, contentViewController: viewController) } // MARK: - Application Events & Notifications @objc func menuDidHide(_ notification: Notification?) { inputBarController.inputBar.textView.overrideNextResponder = nil NotificationCenter.default.removeObserver(self, name: UIMenuController.didHideMenuNotification, object: nil) } }
gpl-3.0
95b036ba1629128742d850def3a98d16
48.331169
189
0.738976
6.352007
false
false
false
false
walkingsmarts/ReactiveCocoa
ReactiveCocoa/AppKit/NSControl.swift
1
2913
import ReactiveSwift import enum Result.NoError import AppKit extension NSControl: ActionMessageSending {} extension Reactive where Base: NSControl { /// Sets whether the control is enabled. public var isEnabled: BindingTarget<Bool> { return makeBindingTarget { $0.isEnabled = $1 } } /// Sets the value of the control with an `NSAttributedString`. public var attributedStringValue: BindingTarget<NSAttributedString> { return makeBindingTarget { $0.attributedStringValue = $1 } } /// A signal of values in `NSAttributedString`, emitted by the control. public var attributedStringValues: Signal<NSAttributedString, NoError> { return proxy.invoked.map { $0.attributedStringValue } } /// Sets the value of the control with a `Bool`. public var boolValue: BindingTarget<Bool> { return makeBindingTarget { $0.integerValue = $1 ? NSOnState : NSOffState } } /// A signal of values in `Bool`, emitted by the control. public var boolValues: Signal<Bool, NoError> { return proxy.invoked.map { $0.integerValue != NSOffState } } /// Sets the value of the control with a `Double`. public var doubleValue: BindingTarget<Double> { return makeBindingTarget { $0.doubleValue = $1 } } /// A signal of values in `Double`, emitted by the control. public var doubleValues: Signal<Double, NoError> { return proxy.invoked.map { $0.doubleValue } } /// Sets the value of the control with a `Float`. public var floatValue: BindingTarget<Float> { return makeBindingTarget { $0.floatValue = $1 } } /// A signal of values in `Float`, emitted by the control. public var floatValues: Signal<Float, NoError> { return proxy.invoked.map { $0.floatValue } } /// Sets the value of the control with an `Int32`. public var intValue: BindingTarget<Int32> { return makeBindingTarget { $0.intValue = $1 } } /// A signal of values in `Int32`, emitted by the control. public var intValues: Signal<Int32, NoError> { return proxy.invoked.map { $0.intValue } } /// Sets the value of the control with an `Int`. public var integerValue: BindingTarget<Int> { return makeBindingTarget { $0.integerValue = $1 } } /// A signal of values in `Int`, emitted by the control. public var integerValues: Signal<Int, NoError> { return proxy.invoked.map { $0.integerValue } } /// Sets the value of the control. public var objectValue: BindingTarget<Any?> { return makeBindingTarget { $0.objectValue = $1 } } /// A signal of values in `Any?`, emitted by the control. public var objectValues: Signal<Any?, NoError> { return proxy.invoked.map { $0.objectValue } } /// Sets the value of the control with a `String`. public var stringValue: BindingTarget<String> { return makeBindingTarget { $0.stringValue = $1 } } /// A signal of values in `String`, emitted by the control. public var stringValues: Signal<String, NoError> { return proxy.invoked.map { $0.stringValue } } }
mit
82150bd89215adb85b9a3e00b489f190
29.989362
76
0.715414
3.739409
false
false
false
false
OverSwift/VisualReader
MangaReader/Classes/Presentation/Scenes/Reader/PagesLayout.swift
1
6701
// // PagesLayout.swift // MangaReader // // Created by Sergiy Loza on 01.02.17. // Copyright © 2017 Serhii Loza. All rights reserved. // import UIKit import Utils struct PagesLayoutConfiguration { var sideItemPadding:CGFloat = 8.0 } class PagesLayout: UICollectionViewLayout { fileprivate var cache = [UICollectionViewLayoutAttributes]() private(set) var animator:UIDynamicAnimator! private(set) var spin:UIDynamicItemBehavior! override init() { super.init() creteDynamicAnimator() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) creteDynamicAnimator() } private func creteDynamicAnimator() { self.animator = UIDynamicAnimator(collectionViewLayout: self) // spin = UIDynamicItemBehavior() // spin.allowsRotation = true // animator.addBehavior(spin) } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { guard let collection = collectionView else { return false } if collection.bounds.size == newBounds.size { return false } return true } override func prepare(forCollectionViewUpdates updateItems: [UICollectionViewUpdateItem]) { } override func prepare() { super.prepare() } override func invalidateLayout() { cache.removeAll(keepingCapacity: false) super.invalidateLayout() } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let atts = animator.items(in: rect) as? [UICollectionViewLayoutAttributes] else { var attributes = [UICollectionViewLayoutAttributes]() for attribute in cache { if rect.intersects(attribute.frame) { attributes.append(attribute) } } return attributes } return atts } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return animator.layoutAttributesForCell(at: indexPath) // return cache[indexPath.row] } fileprivate func sectionsCount() -> Int { return collectionView?.numberOfSections ?? 0 } fileprivate func itemsCount(in section:Int) -> Int { return collectionView?.numberOfItems(inSection: section) ?? 0 } } class VerticalPagesLayout: PagesLayout { override var collectionViewContentSize: CGSize { guard let collection = collectionView else { return CGSize.zero } let width = collection.bounds.width let height = CGFloat(itemsCount(in: 0) / 2) * collection.bounds.height / 2 return CGSize(width: width, height: height) } override func prepare() { super.prepare() guard let collection = collectionView else { return } for i in 0..<itemsCount(in: 0) { let indexPath = IndexPath(item: i, section: 0) self.attsFromAnimator(for: indexPath, atts: { (attributes) in let width = collection.bounds.width let height = collection.bounds.height - collection.contentInset.top - collection.contentInset.bottom let itemWidth = width / 2.0 let itemHeight = height / 2.0 attributes.size = CGSize(width: itemWidth - 10 , height: itemHeight - 5) if i % 2 == 0 { let y = (CGFloat(i) * itemHeight / 2.0) + (itemHeight / 2) let x = itemWidth / 2 attributes.center = CGPoint(x: x, y: y) } else { let y = (CGFloat(i - 1) * itemHeight / 2.0) + (itemHeight / 2) let x = (itemWidth / 2) + itemWidth attributes.center = CGPoint(x: x, y: y) } }) } } func configureItem(update: UICollectionViewLayoutAttributes) { } // if animator.behaviors.count == 0 { // let att = UIAttachmentBehavior(item: attributes, attachedToAnchor: attributes.center) // att.length = 0.0 // att.damping = 0.8 // att.frequency = 1.0 // animator.addBehavior(att) // } else { // animator.behaviors.forEach({ (b) in // guard let b = b as? UIAttachmentBehavior else { // return // } // // let contains = b.items.contains(where: { (item) -> Bool in // guard let item = item as? UICollectionViewLayoutAttributes else { return false } // let c = item.indexPath.row == attributes.indexPath.row // print("\(c)") // print("Item index path row \(item.indexPath.row), atts row \(attributes.indexPath.row) | \(c)") // return c // }) // // if !contains { // let att = UIAttachmentBehavior(item: attributes, attachedToAnchor: attributes.center) // att.length = 0.0 // att.damping = 0.8 // att.frequency = 1.0 // animator.addBehavior(att) // } // }) // } // if !animator.behaviors.contains(att) { // animator.addBehavior(att) // } // cache.append(attributes) func attsFromAnimator(for path: IndexPath, atts: (UICollectionViewLayoutAttributes) -> ()) { var attributes: UICollectionViewLayoutAttributes? animator.behaviors.forEach({ (b) in guard let b = b as? UIAttachmentBehavior else { return } let _ = b.items.contains(where: { (item) -> Bool in guard let item = item as? UICollectionViewLayoutAttributes else { return false } let c = item.indexPath == path print("\(c)") print("Item index path row \(item.indexPath.row), atts row \(path.row) | \(c)") if c { attributes = item } return c }) }) if attributes == nil { attributes = UICollectionViewLayoutAttributes(forCellWith: path) atts(attributes!) let snap = UISnapBehavior(item: attributes!, snapTo: attributes!.center) snap.damping = 0.8 let gravity = UIGravityBehavior(items: [attributes!]) // UIAttachmentBehavior.slidingAttachment(with: attributes!, attachmentAnchor: attributes!.center, axisOfTranslation: CGVector.init(dx: 0, dy: 10)) let att = UIAttachmentBehavior.slidingAttachment(with: attributes!, attachmentAnchor: attributes!.center, axisOfTranslation: CGVector.init(dx: 0, dy: 10)) //UIAttachmentBehavior(item: attributes!, attachedToAnchor: attributes!.center) att.length = 0.0 att.damping = 0.8 att.frequency = 1.0 att.frictionTorque = 0.5 att.addChildBehavior(snap) att.addChildBehavior(gravity) animator.addBehavior(att) } else { atts(attributes!) } } } class HorizontalPagesLayout: PagesLayout { override func prepare() { super.prepare() } }
bsd-3-clause
0c6f6a2d94f9f70c889dca881b6c026b
29.454545
160
0.628955
4.393443
false
false
false
false
luismatute/MemeMe
MemeMeApp/MemeEditorViewController.swift
1
7722
// // ViewController.swift // MemeMeApp // // Created by Luis Matute on 4/13/15. // Copyright (c) 2015 Luis Matute. All rights reserved. // import UIKit class MemeEditorViewController: UIViewController { // MARK: - // MARK: Properties var meme: Meme! let inputDelegate = textInputDelegate() let imagePickerViewDelegate = imagePickerDelegate() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let memeTextAttributes = [ NSStrokeColorAttributeName : UIColor.blackColor(), NSForegroundColorAttributeName : UIColor.whiteColor(), NSFontAttributeName : UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName : -1.0 ] // MARK: - // MARK: Outlets @IBOutlet weak var topText: UITextField! @IBOutlet weak var bottomText: UITextField! @IBOutlet weak var imagePickerView: UIImageView! @IBOutlet weak var toolbarCameraButton: UIBarButtonItem! @IBOutlet weak var shareButton: UIBarButtonItem! @IBOutlet weak var topToolbar: UIToolbar! @IBOutlet weak var bottomToolbar: UIToolbar! // MARK: - // MARK: Actions @IBAction func pickImageFromAlbum(sender: AnyObject) { let pickerController = UIImagePickerController() pickerController.delegate = imagePickerViewDelegate pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(pickerController, animated: true, completion: {() in self.shareButton.enabled = true }) } @IBAction func pickImageFromCamera(sender: AnyObject) { let pickerController = UIImagePickerController() pickerController.delegate = imagePickerViewDelegate pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(pickerController, animated: true, completion: {() in self.shareButton.enabled = true }) } @IBAction func shareMeme(sender: AnyObject) { let memedImage = generateMemedImage() let activityVC = UIActivityViewController(activityItems: [memedImage], applicationActivities: nil) activityVC.completionWithItemsHandler = { (activity, success, items, error) in if !success { // Cancelled println("sharing cancelled") return } //Shared Successfully self.save() self.dismissMe() } self.presentViewController(activityVC, animated: true, completion: nil) } @IBAction func dismissModal(sender: AnyObject) { self.dismissMe() } // MARK: - // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() initialSetup() // loads initial setup for view } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) self.subscribeToKeyboardNotification() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) self.unsubscribeToKeyboardNotification() } // MARK: - // MARK: Methods func initialSetup() { // Text Fields Attributes Initialization self.topText.defaultTextAttributes = memeTextAttributes self.bottomText.defaultTextAttributes = memeTextAttributes self.topText.text = "TOP" self.bottomText.text = "BOTTOM" self.topText.delegate = inputDelegate self.bottomText.delegate = inputDelegate self.topText.textAlignment = .Center self.bottomText.textAlignment = .Center // Change border style here so that we can see them in the storyboard self.topText.borderStyle = UITextBorderStyle.None self.bottomText.borderStyle = UITextBorderStyle.None // If editing a meme if let lememe = self.meme { self.imagePickerView.image = lememe.origImage self.topText.text = lememe.topText self.bottomText.text = lememe.bottomText } // Toolbar Buttons self.toolbarCameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) self.shareButton.enabled = self.imagePickerView.image?.size != nil // Setting the self as the viewcontroller for the delegate self.imagePickerViewDelegate.vc = self self.inputDelegate.vc = self } func subscribeToKeyboardNotification() { // Add observers to default notification center NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } func unsubscribeToKeyboardNotification() { // Remove observers from default notification center NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { // Check if bottom text label started the notification if bottomText.isFirstResponder() { self.view.frame.origin.y -= getKeyboardHeight(notification) } } func keyboardWillHide(notification: NSNotification) { self.view.frame.origin.y += getKeyboardHeight(notification) } func getKeyboardHeight(notification: NSNotification) -> CGFloat { let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue // of CGRect // the bottom text field is editing if bottomText.editing { return keyboardSize.CGRectValue().height } else { return 0 } } func generateMemedImage() -> UIImage { // Hide the toolbar and navbar self.topToolbar.hidden = true self.bottomToolbar.hidden = true // Render view to image // Generates Image combining the image with the top and bottom text UIGraphicsBeginImageContext(self.view.frame.size) self.view.drawViewHierarchyInRect(self.view.frame, afterScreenUpdates: true) let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // Show the toolbar and navbar self.topToolbar.hidden = false self.bottomToolbar.hidden = false return memedImage } func save() { // if meme exists, delete it if let lememe = self.meme { self.appDelegate.memes = self.appDelegate.memes.filter {$0._id != lememe._id} self.navigationController?.popViewControllerAnimated(false) } // Creates the meme var meme = Meme(topText: self.topText.text, bottomText: self.bottomText.text, origImage: imagePickerView.image!, memedImage: generateMemedImage()) // Add it to the memes array from the App Delegate appDelegate.memes.append(meme) } func dismissMe() { self.dismissViewControllerAnimated(true, completion: nil) } }
mit
21cd2fdb106b90477372281feacd5c60
40.074468
154
0.65799
5.77994
false
false
false
false
muneikh/xmpp-messenger-ios
Example/XMPP-Messenger-iOS/xmpp-ios-messenger-classes/OneRoster.swift
1
6186
// // OneRoster.swift // OneChat // // Created by Paul on 26/02/2015. // Copyright (c) 2015 ProcessOne. All rights reserved. // import Foundation import XMPPFramework public protocol OneRosterDelegate { func oneRosterContentChanged(controller: NSFetchedResultsController) } public class OneRoster: NSObject, NSFetchedResultsControllerDelegate { public var delegate: OneRosterDelegate? public var fetchedResultsControllerVar: NSFetchedResultsController? // MARK: Singletonsen public class var sharedInstance : OneRoster { struct OneRosterSingleton { static let instance = OneRoster() } return OneRosterSingleton.instance } public class var buddyList: NSFetchedResultsController { get { if sharedInstance.fetchedResultsControllerVar != nil { return sharedInstance.fetchedResultsControllerVar! } return sharedInstance.fetchedResultsController()! } } // MARK: Core Data func managedObjectContext_roster() -> NSManagedObjectContext { return OneChat.sharedInstance.xmppRosterStorage.mainThreadManagedObjectContext } private func managedObjectContext_capabilities() -> NSManagedObjectContext { return OneChat.sharedInstance.xmppRosterStorage.mainThreadManagedObjectContext } public func fetchedResultsController() -> NSFetchedResultsController? { if fetchedResultsControllerVar == nil { let moc = OneRoster.sharedInstance.managedObjectContext_roster() as NSManagedObjectContext? let entity = NSEntityDescription.entityForName("XMPPUserCoreDataStorageObject", inManagedObjectContext: moc!) let sd1 = NSSortDescriptor(key: "sectionNum", ascending: true) let sd2 = NSSortDescriptor(key: "displayName", ascending: true) let sortDescriptors = [sd1, sd2] let fetchRequest = NSFetchRequest() fetchRequest.entity = entity fetchRequest.sortDescriptors = sortDescriptors fetchRequest.fetchBatchSize = 10 fetchedResultsControllerVar = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc!, sectionNameKeyPath: "sectionNum", cacheName: nil) fetchedResultsControllerVar?.delegate = self do { try fetchedResultsControllerVar!.performFetch() } catch let error as NSError { print("Error: \(error.localizedDescription)") abort() } // if fetchedResultsControllerVar?.performFetch() == nil { //Handle fetch error //} } return fetchedResultsControllerVar! } public class func userFromRosterAtIndexPath(indexPath indexPath: NSIndexPath) -> XMPPUserCoreDataStorageObject { return sharedInstance.fetchedResultsController()!.objectAtIndexPath(indexPath) as! XMPPUserCoreDataStorageObject } public class func userFromRosterForJID(jid jid: String) -> XMPPUserCoreDataStorageObject? { let userJID = XMPPJID.jidWithString(jid) if let user = OneChat.sharedInstance.xmppRosterStorage.userForJID(userJID, xmppStream: OneChat.sharedInstance.xmppStream, managedObjectContext: sharedInstance.managedObjectContext_roster()) { return user } else { return nil } } public class func removeUserFromRosterAtIndexPath(indexPath indexPath: NSIndexPath) { let user = userFromRosterAtIndexPath(indexPath: indexPath) sharedInstance.fetchedResultsControllerVar?.managedObjectContext.deleteObject(user) sharedInstance.fetchedResultsControllerVar = nil; sharedInstance.fetchedResultsController() } public func controllerDidChangeContent(controller: NSFetchedResultsController) { delegate?.oneRosterContentChanged(controller) } } extension OneRoster: XMPPRosterDelegate { public func xmppRoster(sender: XMPPRoster, didReceiveBuddyRequest presence:XMPPPresence) { //was let user _ = OneChat.sharedInstance.xmppRosterStorage.userForJID(presence.from(), xmppStream: OneChat.sharedInstance.xmppStream, managedObjectContext: managedObjectContext_roster()) } public func xmppRosterDidEndPopulating(sender: XMPPRoster?) { let jidList = OneChat.sharedInstance.xmppRosterStorage.jidsForXMPPStream(OneChat.sharedInstance.xmppStream) print("List=\(jidList)") } public func sendBuddyRequestTo(username: String) { let presence: DDXMLElement = DDXMLElement.elementWithName("presence") as! DDXMLElement presence.addAttributeWithName("type", stringValue: "subscribe") presence.addAttributeWithName("to", stringValue: username) // presence.addAttributeWithName("from", stringValue: OneChat.sharedInstance.xmppStream?.myJID.bare()) presence.addAttributeWithName("from", stringValue: (OneChat.sharedInstance.xmppStream?.myJID.bare())!) OneChat.sharedInstance.xmppStream?.sendElement(presence) } public func acceptBuddyRequestFrom(username: String) { let presence: DDXMLElement = DDXMLElement.elementWithName("presence") as! DDXMLElement presence.addAttributeWithName("to", stringValue: username) // presence.addAttributeWithName("from", stringValue: OneChat.sharedInstance.xmppStream?.myJID.bare()) presence.addAttributeWithName("from", stringValue: (OneChat.sharedInstance.xmppStream?.myJID.bare())!) presence.addAttributeWithName("type", stringValue: "subscribed") OneChat.sharedInstance.xmppStream?.sendElement(presence) } public func declineBuddyRequestFrom(username: String) { let presence: DDXMLElement = DDXMLElement.elementWithName("presence") as! DDXMLElement presence.addAttributeWithName("to", stringValue: username) // presence.addAttributeWithName("from", stringValue: OneChat.sharedInstance.xmppStream?.myJID.bare()) presence.addAttributeWithName("from", stringValue: (OneChat.sharedInstance.xmppStream?.myJID.bare())!) presence.addAttributeWithName("type", stringValue: "unsubscribed") OneChat.sharedInstance.xmppStream?.sendElement(presence) } } extension OneRoster: XMPPStreamDelegate { public func xmppStream(sender: XMPPStream, didReceiveIQ ip: XMPPIQ) -> Bool { if let msg = ip.attributeForName("from") { // if msg.stringValue() == "conference.process-one.net" { if msg.stringValue == "conference.process-one.net" { } } return false } }
mit
91a8488db46533de77f967f2c07fbbae
37.42236
193
0.761397
4.776834
false
false
false
false
insidegui/WWDC
WWDC/TranscriptTableCellView.swift
1
2246
// // TranscriptTableCellView.swift // WWDC // // Created by Guilherme Rambo on 29/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import ConfCore import PlayerUI class TranscriptTableCellView: NSTableCellView { var annotation: TranscriptAnnotation? { didSet { updateUI() } } override init(frame frameRect: NSRect) { super.init(frame: frameRect) buildUI() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var titleLabel: NSTextField = { let l = NSTextField(labelWithString: "") l.translatesAutoresizingMaskIntoConstraints = false l.font = .systemFont(ofSize: 14, weight: .medium) l.textColor = .primaryText l.cell?.backgroundStyle = .dark l.lineBreakMode = .byTruncatingTail l.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) l.setContentHuggingPriority(.defaultLow, for: .horizontal) return l }() private lazy var subtitleLabel: NSTextField = { let l = NSTextField(labelWithString: "") l.translatesAutoresizingMaskIntoConstraints = false l.font = .systemFont(ofSize: 12) l.textColor = .secondaryText l.cell?.backgroundStyle = .dark l.lineBreakMode = .byTruncatingTail return l }() private func buildUI() { addSubview(titleLabel) addSubview(subtitleLabel) titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true subtitleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true subtitleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12).isActive = true titleLabel.leadingAnchor.constraint(equalTo: subtitleLabel.trailingAnchor, constant: 8).isActive = true titleLabel.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12).isActive = true } private func updateUI() { guard let annotation = annotation else { return } titleLabel.stringValue = annotation.body subtitleLabel.stringValue = String(timestamp: annotation.timecode) ?? "" } }
bsd-2-clause
23e69589c37b2c3ced55abf897a1f512
28.155844
111
0.673497
5.172811
false
false
false
false
coderQuanjun/PigTV
GYJTV/GYJTV/Classes/Live/Model/GiftPackages.swift
1
560
// // GiftPackages.swift // GYJTV // // Created by zcm_iOS on 2017/5/25. // Copyright © 2017年 Quanjun. All rights reserved. // import UIKit class GiftPackages: BaseModel { var t : Int = 0 var title : String = "" var list : [GiftModel] = [GiftModel]() override init(dic : [String : Any]) { super.init() title = dic["title"] as? String ?? "" t = dic["t"] as? Int ?? 0 if let dicArr = dic["list"] as? [[String: Any]] { list = dicArr.map({ GiftModel(dic: $0) }) } } }
mit
4a725e04d963e9fbc20c1e296bd6b081
20.423077
57
0.517056
3.276471
false
false
false
false
eastsss/SwiftyUtilities
Pods/ReactiveCocoa/ReactiveCocoa/UIKit/UIControl.swift
6
2976
import ReactiveSwift import UIKit import enum Result.NoError extension Reactive where Base: UIControl { /// The current associated action of `self`, with its registered event mask /// and its disposable. internal var associatedAction: Atomic<(action: CocoaAction<Base>, controlEvents: UIControlEvents, disposable: Disposable)?> { return associatedValue { _ in Atomic(nil) } } /// Set the associated action of `self` to `action`, and register it for the /// control events specified by `controlEvents`. /// /// - parameters: /// - action: The action to be associated. /// - controlEvents: The control event mask. /// - disposable: An outside disposable that will be bound to the scope of /// the given `action`. internal func setAction(_ action: CocoaAction<Base>?, for controlEvents: UIControlEvents, disposable: Disposable? = nil) { associatedAction.modify { associatedAction in associatedAction?.disposable.dispose() if let action = action { base.addTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) let compositeDisposable = CompositeDisposable() compositeDisposable += isEnabled <~ action.isEnabled compositeDisposable += { [weak base = self.base] in base?.removeTarget(action, action: CocoaAction<Base>.selector, for: controlEvents) } compositeDisposable += disposable associatedAction = (action, controlEvents, ScopedDisposable(compositeDisposable)) } else { associatedAction = nil } } } /// Create a signal which sends a `value` event for each of the specified /// control events. /// /// - parameters: /// - controlEvents: The control event mask. /// /// - returns: A signal that sends the control each time the control event /// occurs. public func controlEvents(_ controlEvents: UIControlEvents) -> Signal<Base, NoError> { return Signal { observer in let receiver = CocoaTarget(observer) { $0 as! Base } base.addTarget(receiver, action: #selector(receiver.sendNext), for: controlEvents) let disposable = lifetime.ended.observeCompleted(observer.sendCompleted) return ActionDisposable { [weak base = self.base] in disposable?.dispose() base?.removeTarget(receiver, action: #selector(receiver.sendNext), for: controlEvents) } } } @available(*, unavailable, renamed: "controlEvents(_:)") public func trigger(for controlEvents: UIControlEvents) -> Signal<(), NoError> { fatalError() } /// Sets whether the control is enabled. public var isEnabled: BindingTarget<Bool> { return makeBindingTarget { $0.isEnabled = $1 } } /// Sets whether the control is selected. public var isSelected: BindingTarget<Bool> { return makeBindingTarget { $0.isSelected = $1 } } /// Sets whether the control is highlighted. public var isHighlighted: BindingTarget<Bool> { return makeBindingTarget { $0.isHighlighted = $1 } } }
mit
a979c31dfce75a45ea42e9657c4f6a83
33.206897
126
0.694892
4.313043
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PassportNewPhoneNumberRowItem.swift
1
15872
// // SecureIdNewPhoneNumberRowItem.swift // Telegram // // Created by Mikhail Filimonov on 21/03/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import KeyboardKey import SwiftSignalKit private let manager = CountryManager() private final class PassportPhoneNumberArguments { let sendCode:(String)->Void init(sendCode:@escaping(String)->Void) { self.sendCode = sendCode } } private final class PassportPhoneTextField : NSTextField { override func resignFirstResponder() -> Bool { (self.delegate as? PassportPhoneContainerView)?.controlTextDidBeginEditing(Notification(name: NSControl.textDidChangeNotification)) return super.resignFirstResponder() } override func becomeFirstResponder() -> Bool { (self.delegate as? PassportPhoneContainerView)?.controlTextDidEndEditing(Notification(name: NSControl.textDidChangeNotification)) return super.becomeFirstResponder() } override func mouseDown(with event: NSEvent) { superview?.mouseDown(with: event) } } private class PassportPhoneContainerView : View, NSTextFieldDelegate { var arguments:PassportPhoneNumberArguments? private let countrySelector:TitleButton = TitleButton() fileprivate let errorLabel:LoginErrorStateView = LoginErrorStateView() let codeText:PassportPhoneTextField = PassportPhoneTextField() let numberText:PassportPhoneTextField = PassportPhoneTextField() fileprivate var selectedItem:CountryItem? private let manager: CountryManager required init(frame frameRect: NSRect, manager: CountryManager) { self.manager = manager super.init(frame: frameRect) countrySelector.style = ControlStyle(font: NSFont.medium(.title), foregroundColor: theme.colors.accent, backgroundColor: theme.colors.background) countrySelector.set(text: "France", for: .Normal) _ = countrySelector.sizeToFit() addSubview(countrySelector) countrySelector.set(handler: { [weak self] _ in self?.showCountrySelector() }, for: .Click) updateLocalizationAndTheme(theme: theme) codeText.stringValue = "+" codeText.textColor = theme.colors.text codeText.font = NSFont.normal(.title) numberText.textColor = theme.colors.text numberText.font = NSFont.normal(.title) numberText.isBordered = false numberText.isBezeled = false numberText.drawsBackground = false numberText.focusRingType = .none codeText.drawsBackground = false codeText.isBordered = false codeText.isBezeled = false codeText.focusRingType = .none codeText.delegate = self codeText.nextResponder = numberText codeText.nextKeyView = numberText numberText.delegate = self numberText.nextResponder = codeText numberText.nextKeyView = codeText addSubview(codeText) addSubview(numberText) errorLabel.layer?.opacity = 0 addSubview(errorLabel) let code = NSLocale.current.regionCode ?? "US" update(selectedItem: manager.item(bySmallCountryName: code), update: true) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) backgroundColor = theme.colors.background numberText.placeholderAttributedString = NSAttributedString.initialize(string: strings().loginPhoneFieldPlaceholder, color: theme.colors.grayText, font: NSFont.normal(.header), coreText: false) codeText.textView?.insertionPointColor = theme.colors.indicatorColor numberText.textView?.insertionPointColor = theme.colors.indicatorColor needsLayout = true } func setPhoneError(_ error: AuthorizationCodeRequestError) { let text:String switch error { case .invalidPhoneNumber: text = strings().phoneNumberInvalid case .limitExceeded: text = strings().loginFloodWait case .generic: text = "undefined error" case .phoneLimitExceeded: text = "undefined error" case .phoneBanned: text = "PHONE BANNED" case .timeout: text = "timeout" } errorLabel.state.set(.error(text)) } func update(countryCode: Int32, number: String) { self.codeText.stringValue = "\(countryCode)" self.numberText.stringValue = formatPhoneNumber(number) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } required init(frame frameRect: NSRect) { fatalError("init(frame:) has not been implemented") } override func layout() { super.layout() codeText.sizeToFit() numberText.sizeToFit() let maxInset: CGFloat = 0 let contentInset = maxInset countrySelector.setFrameOrigin(contentInset - 2, floorToScreenPixels(backingScaleFactor, 25 - countrySelector.frame.height/2)) codeText.setFrameOrigin(contentInset, floorToScreenPixels(backingScaleFactor, 75 - codeText.frame.height/2)) numberText.setFrameOrigin(contentInset + separatorInset, floorToScreenPixels(backingScaleFactor, 75 - codeText.frame.height/2)) errorLabel.centerX(y: 120) } override func draw(_ layer: CALayer, in ctx: CGContext) { super.draw(layer, in: ctx) let maxInset: CGFloat = 0 ctx.setFillColor(theme.colors.border.cgColor) ctx.fill(NSMakeRect(maxInset, 50, frame.width - maxInset, .borderSize)) ctx.fill(NSMakeRect(maxInset, 100, frame.width - maxInset, .borderSize)) // ctx.fill(NSMakeRect(maxInset + separatorInset, 50, .borderSize, 50)) } func showCountrySelector() { var items:[ContextMenuItem] = [] for country in manager.countries { let item = ContextMenuItem(country.fullName, handler: { [weak self] in self?.update(selectedItem: country, update: true) }) items.append(item) } if let currentEvent = NSApp.currentEvent { ContextMenu.show(items: items, view: countrySelector, event: currentEvent, onShow: {(menu) in }, onClose: {}) } } func controlTextDidBeginEditing(_ obj: Notification) { codeText.textView?.backgroundColor = theme.colors.background numberText.textView?.backgroundColor = theme.colors.background codeText.textView?.insertionPointColor = theme.colors.indicatorColor numberText.textView?.insertionPointColor = theme.colors.indicatorColor } func controlTextDidEndEditing(_ obj: Notification) { } func controlTextDidChange(_ obj: Notification) { if let field = obj.object as? NSTextField { field.textView?.backgroundColor = theme.colors.background let code = codeText.stringValue.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() let dec = code.prefix(4) if field == codeText { if code.length > 4 { let list = Array(code).map {String($0)} let reduced = list.reduce([], { current, value -> [String] in var current = current current.append((current.last ?? "") + value) return current }).map({Int($0)}).filter({$0 != nil}).map({$0!}) var found: Bool = false for _code in reduced { if let item = manager.item(byCodeNumber: _code) { codeText.stringValue = "+" + String(_code) update(selectedItem: item, update: true, updateCode: false) let codeString = String(_code) var formated = formatPhoneNumber(codeString + String(code[codeString.endIndex..<code.endIndex]) + numberText.stringValue.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) if formated.hasPrefix("+") { formated = formated.fromSuffix(2) } formated = String(code[codeString.endIndex..<code.endIndex]).prefix(17) numberText.stringValue = formated window?.makeFirstResponder(numberText) numberText.setCursorToEnd() found = true break } } if !found { update(selectedItem: nil, update: true, updateCode: false) } } else { codeText.stringValue = "+" + dec var item:CountryItem? = nil if let code = Int(dec) { item = manager.item(byCodeNumber: code) } update(selectedItem: item, update: true, updateCode:false) } } else if field == numberText { var formated = formatPhoneNumber(dec + numberText.stringValue.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) if formated.hasPrefix("+") { formated = formated.fromSuffix(2) } formated = String(formated[dec.endIndex..<formated.endIndex]).prefix(17) numberText.stringValue = formated } } arguments?.sendCode(number) needsLayout = true setNeedsDisplayLayer() } var number:String { return codeText.stringValue + numberText.stringValue } func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { if commandSelector == #selector(insertNewline(_:)) { if control == codeText { self.window?.makeFirstResponder(self.numberText) self.numberText.selectText(nil) } else if !numberText.stringValue.isEmpty { arguments?.sendCode(number) } //Queue.mainQueue().justDispatch { (control as? NSTextField)?.setCursorToEnd() //} return true } else if commandSelector == #selector(deleteBackward(_:)) { if control == numberText { if numberText.stringValue.isEmpty { Queue.mainQueue().justDispatch { self.window?.makeFirstResponder(self.codeText) self.codeText.setCursorToEnd() } } } return false } return false } func update(selectedItem:CountryItem?, update:Bool, updateCode:Bool = true) -> Void { self.selectedItem = selectedItem if update { countrySelector.set(text: selectedItem?.shortName ?? strings().loginInvalidCountryCode, for: .Normal) _ = countrySelector.sizeToFit() if updateCode { codeText.stringValue = selectedItem != nil ? "+\(selectedItem!.code)" : "+" } needsLayout = true setNeedsDisplayLayer() } } var separatorInset:CGFloat { return codeText.frame.width + 10 } } class PassportNewPhoneNumberRowItem: GeneralRowItem, InputDataRowDataValue { var value: InputDataValue { return _value } fileprivate var _value: InputDataValue = .string("") init(_ initialSize: NSSize, stableId: AnyHashable, action: @escaping()->Void) { super.init(initialSize, height: 110, stableId: stableId, action: action) } override func viewClass() -> AnyClass { return PassportNewPhoneNumberRowView.self } } private final class PassportNewPhoneNumberRowView : TableRowView { fileprivate let container: PassportPhoneContainerView = PassportPhoneContainerView(frame: NSMakeRect(0, 0, 300, 110), manager: manager) required init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(container) } // override var firstResponder: NSResponder? { // if container.numberText._mouseInside() { // return container.numberText // } else if container.codeText._mouseInside() { // return container.codeText // } // return container.numberText // } // override var mouseInsideField: Bool { return container.numberText._mouseInside() || container.codeText._mouseInside() } override func hitTest(_ point: NSPoint) -> NSView? { switch true { case NSPointInRect(point, container.numberText.frame): return container.numberText case NSPointInRect(point, container.codeText.frame): return container.codeText default: return super.hitTest(point) } } override func hasFirstResponder() -> Bool { return true } override var firstResponder: NSResponder? { let isKeyDown = NSApp.currentEvent?.type == NSEvent.EventType.keyDown && NSApp.currentEvent?.keyCode == KeyboardKey.Tab.rawValue switch true { case container.codeText._mouseInside() && !isKeyDown: return container.codeText case container.numberText._mouseInside() && !isKeyDown: return container.numberText default: switch true { case container.codeText.textView == window?.firstResponder: return container.codeText.textView case container.numberText.textView == window?.firstResponder: return container.numberText.textView default: return container.numberText } } } override func nextResponder() -> NSResponder? { if window?.firstResponder == container.codeText.textView { return container.numberText } if window?.firstResponder == container.numberText.textView { return container.codeText } return nil } override func layout() { super.layout() guard let item = item as? GeneralRowItem else { return } container.setFrameSize(frame.width - item.inset.left - item.inset.right, container.frame.height) container.center() } override func set(item: TableRowItem, animated: Bool) { super.set(item: item, animated: animated) container.arguments = PassportPhoneNumberArguments(sendCode: { [weak self] phone in guard let item = self?.item as? PassportNewPhoneNumberRowItem else {return} item._value = .string(phone) }) } override func updateColors() { super.updateColors() container.updateLocalizationAndTheme(theme: theme) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
17c91ff2eaba9f5fac9a7bc42162ef6d
34.112832
219
0.589503
5.474646
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/Window/StemGroupView.swift
1
4040
// // StemGroupView.swift // StemCode // // Created by David Evans on 25/04/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import UIKit import StemProjectKit protocol StemGroupViewDelegate: AnyObject { func groupViewDidRequestToggleExpand(_ group: StemGroupView) } class StemGroupView: UIView, StemItemView { typealias StemItemType = StemGroup weak var delegate: StemItemViewDelegate! @IBOutlet var imageView: UIImageView! @IBOutlet var nameLabel: UILabel! @IBOutlet var childGroupsContainer: UIStackView! @IBOutlet var childFilesContainer: UIStackView! @IBOutlet var selectionView: UIView! @IBOutlet var arrowImageVoew: UIImageView! @IBOutlet private(set) var isCollapsedConstraint: NSLayoutConstraint! var stemItem: StemGroup! var selected=false func setItem(_ item: StemGroup, openFile: StemFile) { stemItem = item if self.stemItem == stemItem.parentProject.rootGroup && item.parentProject.stemFile == openFile { } nameLabel.text = stemItem.name renderChildren(openFile: openFile) item.groupAdded.subscribe(with: self) { [unowned self] (group) in // TODO: Find a workaround, the project StemFile as the open file is a hack let view = group.createView(delegate: self.delegate, openFile: self.stemItem.parentProject.stemFile) view.delegate = self.delegate self.childGroupsContainer.addArrangedSubview(view as UIView) view.imageView.leftAnchor.constraint(equalTo: self.imageView.rightAnchor).isActive = true } item.fileAdded.subscribe(with: self) { [unowned self] (file) in // TODO: Find a workaround, the project StemFile as the open file is a hack let view = file.createView(delegate: self.delegate, openFile: self.stemItem.parentProject.stemFile) view.delegate = self.delegate self.childGroupsContainer.addArrangedSubview(view as UIView) view.imageView.leftAnchor.constraint(equalTo: self.imageView.rightAnchor).isActive = true } } func renderChildren(openFile: StemFile) { renderChildViews(stemItem.childGroups, inView: childGroupsContainer, openFile: openFile) renderChildViews(stemItem.childFiles, inView: childFilesContainer, openFile: openFile) } func renderChildViews<T: Sequence>(_ children: T, inView container: UIStackView, openFile: StemFile) where T.Element: StemItem { for child in children { // TODO: This is horrible, find a way to do a Switch or something if let item = child as? StemFile { let view = item.createView(delegate: self.delegate, openFile: openFile) container.addArrangedSubview(view) view.imageView.leftAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true } else { let item = child as! StemGroup let view = item.createView(delegate: self.delegate, openFile: openFile) container.addArrangedSubview(view) view.imageView.leftAnchor.constraint(equalTo: imageView.rightAnchor).isActive = true } } } @IBAction func toggleExpand() { delegate?.groupViewDidRequestToggleExpand(self) } func expand() { isCollapsedConstraint.isActive = true let rotation: CGFloat = CGFloat.pi / 2 self.arrowImageVoew.transform = CGAffineTransform(rotationAngle: rotation) self.layoutIfNeeded() } func collapse() { isCollapsedConstraint.isActive = false let rotation: CGFloat = 0 self.arrowImageVoew.transform = CGAffineTransform(rotationAngle: rotation) self.layoutIfNeeded() } override func select(_ sender: Any?) { selected = !selected selectionView.backgroundColor = selected ? Theme.Blue : UIColor.clear nameLabel.textColor = selected ? UIColor.white : UIColor.black arrowImageVoew.tintColor = selected ? UIColor.white : Theme.DarkGrey } }
mit
9416f524c10dc8ebf4332c213a2503ce
36.398148
129
0.690765
4.584563
false
false
false
false
pocketworks/FloatLabelFields
FloatLabelFields/FloatLabelTextField.swift
1
9603
// // FloatLabelTextField.swift // FloatLabelFields // // Created by Fahim Farook on 28/11/14. // Copyright (c) 2015 RookSoft Ltd & Myles Ringle. All rights reserved. // // Original Concept by Matt D. Smith // http://dribbble.com/shots/1254439--GIF-Mobile-Form-Interaction?list=users // // Objective-C version by Jared Verdi // https://github.com/jverdi/JVFloatLabeledTextField // // // Updated for Swift 2.0 by Myles Ringle on 15/10/15. // import UIKit @IBDesignable public class FloatLabelTextField: UITextField,UITextFieldDelegate { let animationDuration = 0.3 var title = UILabel() private var hasError: Bool = false private var originalPlaceHolderText: String? private var validators = [String: Any]() // MARK:- Properties override public var accessibilityLabel: String! { get { if text!.isEmpty { return title.text } else { return text } } set { self.accessibilityLabel = newValue } } override public var placeholder: String? { didSet { if title.text == nil { title.text = placeholder title.sizeToFit() } } } override public var attributedPlaceholder: NSAttributedString? { didSet { title.text = attributedPlaceholder?.string title.sizeToFit() } } var titleFont: UIFont = UIFont.systemFontOfSize(12.0) { didSet { title.font = titleFont } } @IBInspectable var hintYPadding: CGFloat = 0.0 @IBInspectable var titleYPadding: CGFloat = 0.0 { didSet { var r = title.frame r.origin.y = titleYPadding title.frame = r } } @IBInspectable var titleTextColour: UIColor = UIColor.grayColor() { didSet { if !isFirstResponder() { title.textColor = titleTextColour } } } @IBInspectable var titleActiveTextColour: UIColor! { didSet { if isFirstResponder() { title.textColor = titleActiveTextColour } } } @IBInspectable var errorTextColor: UIColor = UIColor.redColor() @IBInspectable var errorFontSize: CGFloat = 7.5 @IBInspectable public var isRequired: Bool = false @IBInspectable var isEmail: Bool = false // MARK:- Init required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.delegate = self setup() } override init(frame:CGRect) { super.init(frame:frame) self.delegate = self setup() } // MARK:- Overrides override public func layoutSubviews() { super.layoutSubviews() let isResp = isFirstResponder() setTitlePositionForTextAlignment() if !text!.isEmpty && !hasError { placeholder = originalPlaceHolderText title.textColor = titleTextColour showTitle(isResp) } } override public func textRectForBounds(bounds: CGRect) -> CGRect { var r = super.editingRectForBounds(bounds) var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top, 0.0, 0.0, 0.0)) return CGRectIntegral(r) } override public func editingRectForBounds(bounds: CGRect) -> CGRect { var r = super.editingRectForBounds(bounds) var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = UIEdgeInsetsInsetRect(r, UIEdgeInsetsMake(top, 0.0, 0.0, 0.0)) return CGRectIntegral(r) } override public func clearButtonRectForBounds(bounds: CGRect) -> CGRect { var r = super.clearButtonRectForBounds(bounds) var top = ceil(title.font.lineHeight + hintYPadding) top = min(top, maxTopInset()) r = CGRect(x: r.origin.x, y: r.origin.y + (top * 0.5), width: r.size.width, height: r.size.height) return CGRectIntegral(r) } // MARK:- Public Methods public func textFieldDidBeginEditing(textField: UITextField) { clearError() let isResp = isFirstResponder() showTitle(isResp) if originalPlaceHolderText == nil { if let pHolder = placeholder { originalPlaceHolderText = pHolder } } placeholder = "" } public func textFieldDidEndEditing(textField: UITextField) { placeholder = originalPlaceHolderText hideTitle(false) // validateAllRules() } func addValidator(message:String,regex:NSRegularExpression) { validators[message] = regex } func addValidator(message:String,validator condtion: () -> Bool) { validators[message] = condtion } func validate() -> Bool { validateAllRules() return hasError } // MARK:- Private Methods private func setup() { borderStyle = UITextBorderStyle.None titleActiveTextColour = tintColor // Set up title label title.alpha = 0.0 title.font = titleFont title.textColor = titleTextColour if let str = placeholder { if !str.isEmpty { title.text = str title.sizeToFit() } } self.addSubview(title) } private func maxTopInset() -> CGFloat { return max(0, floor(bounds.size.height - font!.lineHeight - 4.0)) } private func setTitlePositionForTextAlignment() { let r = textRectForBounds(bounds) var x = r.origin.x if textAlignment == NSTextAlignment.Center { x = r.origin.x + (r.size.width * 0.5) - title.frame.size.width } else if textAlignment == NSTextAlignment.Right { x = r.origin.x + r.size.width - title.frame.size.width } title.frame = CGRect(x: x, y: title.frame.origin.y, width: frame.size.width, height: title.frame.size.height) } private func showTitle(animated: Bool) { let dur = animated ? animationDuration : 0 UIView.animateWithDuration(dur, delay: 0, options: [.BeginFromCurrentState, .CurveEaseOut], animations: { // Animation self.title.alpha = 1.0 var r = self.title.frame r.origin.y = self.titleYPadding self.title.frame = r }, completion: nil) } private func hideTitle(animated: Bool) { let dur = animated ? animationDuration : 0 UIView.animateWithDuration(dur, delay: 0, options: [.BeginFromCurrentState, .CurveEaseIn], animations: { // Animation self.title.alpha = 0.0 var r = self.title.frame r.origin.y = self.title.font.lineHeight + self.hintYPadding self.title.frame = r }, completion: nil) } private func validateAllRules() { // Check required field rule if isRequired && text!.isEmpty { setRequiredError() return } // Check if its a email field if isEmail && !text!.isEmail() { setEmailError() return } // check all the custom validators for (message,validator) in validators { // check the predicate if (validator as? (() -> Bool) != nil) { hasError = !(validator as! () -> Bool)() } else { // check the regex let regex = validator as? NSRegularExpression hasError = !(regex?.matchesInString(self.text!, options: NSMatchingOptions.ReportProgress, range: NSMakeRange(0, self.text!.length)) != nil) } if hasError { setCustomError(message) return } } let isResp = isFirstResponder() if hasError { showTitle(isResp) }else { clearError() if text!.isEmpty { hideTitle(isResp) } } } private func setRequiredError () { var fieldName = "" if let pHolder = placeholder { if pHolder != "" { fieldName = pHolder } else if let orgHolder = originalPlaceHolderText { fieldName = orgHolder } } title.text = "\(fieldName) can't be blank" showError() } private func setEmailError() { title.text = "Invalid Email" showError() } private func setCustomError(error: String) { title.text = error showError() } private func showError() { title.font = self.font!.fontWithSize(errorFontSize) title.textColor = errorTextColor hasError = true let isResp = isFirstResponder() showTitle(isResp) } private func clearError() { if let pHolder = placeholder { if pHolder != "" { title.text = pHolder } else if let orgHolder = originalPlaceHolderText { title.text = orgHolder } } title.textColor = titleTextColour title.font = self.font hasError = false } }
mit
e09d8a3923c3a05efe7e4bc55fe47867
27.924699
156
0.557013
4.828054
false
false
false
false
Karumi/BothamNetworking
BothamNetworking/HTTPResponse.swift
1
1891
// // HTTPResponse.swift // BothamNetworking // // Created by Pedro Vicente Gomez on 20/11/15. // Copyright © 2015 GoKarumi S.L. All rights reserved. // import Foundation public struct HTTPResponse { public let statusCode: Int public let headers: CaseInsensitiveDictionary<String>? public let body: Data public init(statusCode: Int, headers: CaseInsensitiveDictionary<String>?, body: Data) { self.statusCode = statusCode self.headers = headers self.body = body } public func withStatusCode(_ statusCode: Int) -> HTTPResponse { return HTTPResponse( statusCode: statusCode, headers: headers, body: body) } public func withHeaders(_ headers: [String: String]?) -> HTTPResponse { return HTTPResponse( statusCode: statusCode, headers: CaseInsensitiveDictionary(dictionary: headers ?? [ : ]), body: body) } public func appendingHeaders(_ headers: [String: String]) -> HTTPResponse { var newHeaders = self.headers for (k, v) in headers { _ = newHeaders?.update(value: v, forKey: k) } return HTTPResponse( statusCode: statusCode, headers: newHeaders, body: body) } public func withBody(_ body: Data) -> HTTPResponse { return HTTPResponse( statusCode: statusCode, headers: headers, body: body) } } extension HTTPResponse: CustomDebugStringConvertible { public var debugDescription: String { let headers = self.headers?.map { (key, value) in "\(key): \(value)\n" }.joined(separator: "\n") ?? "" return "\(statusCode)\n" + "\(headers)\n" + "\(String(data: body, encoding: String.Encoding.utf8)!)\n" } }
apache-2.0
1e2e900b294a0275c57d042673c24a8c
25.619718
79
0.583069
4.78481
false
false
false
false
elegion/ios-Flamingo
Source/StubsManagerFactory.swift
1
5067
// // StubsManagerFactory.swift // Flamingo // // Created by Dmitrii Istratov on 03-10-2017. // Copyright © 2017 ELN. All rights reserved. // import Foundation public enum JSONAny: Codable { case int(Int) case double(Double) case string(String) case bool(Bool) case array([JSONAny]) case dictionary([String: JSONAny]) case null public init(from decoder: Decoder) throws { if let bool = try? Bool(from: decoder) { self = .bool(bool) } else if let integer = try? Int(from: decoder) { self = .int(integer) } else if let double = try? Double(from: decoder) { self = .double(double) } else if let string = try? String(from: decoder) { self = .string(string) } else if let array = try? [JSONAny](from: decoder) { self = .array(array) } else if let dictionary = try? [String: JSONAny](from: decoder) { self = .dictionary(dictionary) } else { self = .null } } public func encode(to encoder: Encoder) throws { switch self { case .int(let value): try value.encode(to: encoder) case .double(let value): try value.encode(to: encoder) case .string(let value): try value.encode(to: encoder) case .bool(let value): try value.encode(to: encoder) case .array(let value): try value.encode(to: encoder) case .dictionary(let value): try value.encode(to: encoder) case .null: //TODO break } } public var value: Any { switch self { case .int(let value): return value case .double(let value): return value case .string(let value): return value case .bool(let value): return value case .array(let value): return value.map({ $0.value }) case .dictionary(let value): return value.mapValues({ $0.value }) case .null: return NSNull() } } } public struct RequestStubMap: Decodable { public let url: URL public let method: HTTPMethod public let params: [String: Any]? public let responseStub: ResponseStub public var requestStub: RequestStub { return RequestStub(url: url, method: method, params: params) } private enum CodingKeys: String, CodingKey { case url case method case params case responseStub = "stub" } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) url = try container.decode(.url) method = try container.decode(.method) if container.contains(.params) { let jsonParams: JSONAny = try container.decode(.params) params = jsonParams.value as? [String: Any] } else { params = nil } responseStub = try container.decode(.responseStub) } public init(url: URL, method: HTTPMethod, params: [String: Any]?, responseStub: ResponseStub) { self.url = url self.method = method self.params = params self.responseStub = responseStub } public init(request: RequestStub, responseStub: ResponseStub) { self.url = request.url self.method = request.method self.params = request.params self.responseStub = responseStub } } public struct StubFile: Decodable { public let version: String? public let stubs: [RequestStubMap] public init(fromFile path: String, decoder: JSONDecoder = JSONDecoder()) throws { let filemanager = FileManager.default if !filemanager.fileExists(atPath: path) { throw StubsError.stubClientFactoryError(.fileNotExists(path)) } if !filemanager.isReadableFile(atPath: path) { throw StubsError.stubClientFactoryError(.cannotAccessToFile(path)) } guard let content = filemanager.contents(atPath: path) else { throw StubsError.stubClientFactoryError(.wrongListFormat) } self = try decoder.decode(type(of: self), from: content) } } public class StubsManagerFactory { public static func manager() -> StubsDefaultManager { return StubsDefaultManager() } public static func manager(_ key: RequestStub, stub: ResponseStub) -> StubsDefaultManager { let session = self.manager() session.add(key, stub: stub) return session } public static func manager(with stubs: [RequestStubMap]) -> StubsDefaultManager { let session = self.manager() session.add(stubsArray: stubs) return session } public static func manager(fromFile path: String, decoder: JSONDecoder = JSONDecoder()) throws -> StubsDefaultManager { let stubFile = try StubFile(fromFile: path, decoder: decoder) return self.manager(with: stubFile.stubs) } }
mit
b93bd846331eba98905ce6b08cb868a7
28.976331
123
0.601066
4.344768
false
false
false
false
Paladinfeng/leetcode
leetcode/Best Time to Buy and Sell Stock II/main.swift
1
618
// // main.swift // Best Time to Buy and Sell Stock II // // Created by xuezhaofeng on 27/02/2018. // Copyright © 2018 paladinfeng. All rights reserved. // import Foundation class Solution { func maxProfit(_ prices: [Int]) -> Int { if prices.count == 0 { return 0 } var maxProfit = 0 for i in 0..<prices.count-1 { if prices[i] < prices[i+1] { maxProfit += (prices[i+1] - prices[i]) } } return maxProfit } } let result = Solution().maxProfit([7, 1, 5, 3, 6, 4]) print(result)
mit
879a60e38f36632397c0c7a072e9f81a
19.566667
54
0.507293
3.525714
false
false
false
false
breadwallet/breadwallet-ios
breadwallet/src/ViewControllers/WalletConnectionSettingsViewController.swift
1
9422
// // WalletConnectionSettingsViewController.swift // breadwallet // // Created by Ehsan Rezaie on 2019-08-28. // Copyright © 2019 Breadwinner AG. All rights reserved. // // See the LICENSE file at the project root for license information. // import UIKit import WalletKit import SafariServices class WalletConnectionSettingsViewController: UIViewController, Trackable { private let walletConnectionSettings: WalletConnectionSettings private var currency: Currency { return Currencies.btc.instance! } private let modeChangeCallback: (WalletConnectionMode) -> Void // views private let animatedBlockSetLogo = AnimatedBlockSetLogo() private let header = UILabel.wrapping(font: Theme.h3Accent, color: Theme.primaryText) private let explanationLabel = UITextView() private let footerLabel = UILabel.wrapping(font: Theme.caption, color: Theme.secondaryText) private let toggleSwitch = UISwitch() private let footerLogo = UIImageView(image: UIImage(named: "BlocksetLogoWhite")) private let mainBackground = UIView(color: Theme.secondaryBackground) private let footerBackground = UIView(color: Theme.secondaryBackground) // MARK: - Lifecycle init(walletConnectionSettings: WalletConnectionSettings, modeChangeCallback: @escaping (WalletConnectionMode) -> Void) { self.walletConnectionSettings = walletConnectionSettings self.modeChangeCallback = modeChangeCallback super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() [mainBackground, footerBackground, animatedBlockSetLogo, header, explanationLabel, toggleSwitch, footerLabel, footerLogo].forEach { view.addSubview($0) } setUpAppearance() addConstraints() bindData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setWhiteStyle() } private func setUpAppearance() { view.backgroundColor = Theme.primaryBackground explanationLabel.textAlignment = .center mainBackground.layer.cornerRadius = 4.0 footerBackground.layer.cornerRadius = 4.0 mainBackground.clipsToBounds = true footerBackground.clipsToBounds = true // Clip the main view so that the block animation doesn't show when back gesture is active view.clipsToBounds = true if E.isIPhone5 { animatedBlockSetLogo.isHidden = true animatedBlockSetLogo.constrain([ animatedBlockSetLogo.heightAnchor.constraint(equalToConstant: 0.0), animatedBlockSetLogo.widthAnchor.constraint(equalToConstant: 0.0)]) } } private func addConstraints() { let screenHeight: CGFloat = UIScreen.main.bounds.height let topMarginPercent: CGFloat = 0.08 let imageTopMargin: CGFloat = E.isIPhone6 ? 8.0 : (screenHeight * topMarginPercent) let containerTopMargin: CGFloat = E.isIPhone6 ? 0.0 : -C.padding[2] let leftRightMargin: CGFloat = 54.0 mainBackground.constrain([ mainBackground.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: C.padding[2]), mainBackground.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -C.padding[2]), mainBackground.topAnchor.constraint(equalTo: animatedBlockSetLogo.topAnchor, constant: containerTopMargin), mainBackground.bottomAnchor.constraint(equalTo: toggleSwitch.bottomAnchor, constant: C.padding[4]) ]) animatedBlockSetLogo.constrain([ animatedBlockSetLogo.centerXAnchor.constraint(equalTo: view.centerXAnchor), animatedBlockSetLogo.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: imageTopMargin) ]) header.constrain([ header.centerXAnchor.constraint(equalTo: view.centerXAnchor), header.topAnchor.constraint(equalTo: animatedBlockSetLogo.bottomAnchor, constant: E.isIPhone5 ? C.padding[2] : C.padding[4])]) explanationLabel.constrain([ explanationLabel.leftAnchor.constraint(equalTo: view.leftAnchor, constant: leftRightMargin), explanationLabel.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -leftRightMargin), explanationLabel.topAnchor.constraint(equalTo: header.bottomAnchor, constant: C.padding[2]) ]) toggleSwitch.constrain([ toggleSwitch.centerXAnchor.constraint(equalTo: view.centerXAnchor), toggleSwitch.topAnchor.constraint(equalTo: explanationLabel.bottomAnchor, constant: C.padding[3]) ]) footerLabel.constrain([ footerLabel.bottomAnchor.constraint(equalTo: footerBackground.topAnchor, constant: -C.padding[1]), footerLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor) ]) footerLogo.constrain([ footerLogo.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -52.0), footerLogo.centerXAnchor.constraint(equalTo: view.centerXAnchor)]) footerBackground.constrain([ footerBackground.topAnchor.constraint(equalTo: footerLogo.topAnchor, constant: -C.padding[2]), footerBackground.leadingAnchor.constraint(equalTo: footerLogo.leadingAnchor, constant: -C.padding[2]), footerBackground.trailingAnchor.constraint(equalTo: footerLogo.trailingAnchor, constant: C.padding[2]), footerBackground.bottomAnchor.constraint(equalTo: footerLogo.bottomAnchor, constant: C.padding[2]) ]) } private func bindData() { title = S.WalletConnectionSettings.viewTitle header.text = S.WalletConnectionSettings.header footerLabel.text = S.WalletConnectionSettings.footerTitle let selectedMode = walletConnectionSettings.mode(for: currency) toggleSwitch.isOn = selectedMode == WalletConnectionMode.api_only //This needs to be done in the next run loop or else the animations don't //start in the right spot DispatchQueue.main.async { [weak self] in guard let `self` = self else { return } self.animatedBlockSetLogo.isOn = self.toggleSwitch.isOn } toggleSwitch.valueChanged = { [weak self] in guard let `self` = self else { return } // Fast sync can only be turned on via the toggle. // It needs to be turned off by the confirmation alert. if self.toggleSwitch.isOn { self.setMode() } else { self.confirmToggle() } } setupLink() } private func setMode() { let newMode = toggleSwitch.isOn ? WalletConnectionMode.api_only : WalletConnectionMode.p2p_only walletConnectionSettings.set(mode: newMode, for: currency) UINotificationFeedbackGenerator().notificationOccurred(.success) animatedBlockSetLogo.isOn.toggle() saveEvent(makeToggleEvent()) self.modeChangeCallback(newMode) } private func confirmToggle() { let alert = UIAlertController(title: "", message: S.WalletConnectionSettings.confirmation, preferredStyle: .alert) alert.addAction(UIAlertAction(title: S.Button.cancel, style: .cancel, handler: { _ in self.toggleSwitch.setOn(true, animated: true) })) alert.addAction(UIAlertAction(title: S.WalletConnectionSettings.turnOff, style: .default, handler: { _ in self.setMode() })) present(alert, animated: true) } private func setupLink() { let string = NSMutableAttributedString(string: S.WalletConnectionSettings.explanatoryText) let linkRange = string.mutableString.range(of: S.WalletConnectionSettings.link) if linkRange.location != NSNotFound { string.addAttribute(.link, value: NSURL(string: "https://www.brd.com/blog/fastsync-explained")!, range: linkRange) } explanationLabel.attributedText = string explanationLabel.delegate = self explanationLabel.isEditable = false explanationLabel.backgroundColor = .clear explanationLabel.font = Theme.body1 explanationLabel.textColor = Theme.secondaryText explanationLabel.textAlignment = .center //TODO:CYRPTO - is there a way to make this false but also // keep the link working? //explanationLabel.isSelectable = false explanationLabel.isScrollEnabled = false } private func makeToggleEvent() -> String { let event = toggleSwitch.isOn ? Event.enable.name : Event.disable.name return makeEventName([EventContext.fastSync.name, currency.code, event]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension WalletConnectionSettingsViewController: UITextViewDelegate { func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { let vc = SFSafariViewController(url: URL) self.present(vc, animated: true, completion: nil) return false } }
mit
2dc32b77ae445c762e95b39078bfbde3
43.230047
161
0.68135
5.078706
false
false
false
false
GreenCom-Networks/ios-charts
ChartsRealm/Classes/Data/RealmBarDataSet.swift
1
8583
// // RealmBarDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import Realm import Realm.Dynamic public class RealmBarDataSet: RealmBarLineScatterCandleBubbleDataSet, IBarChartDataSet { public override func initialize() { self.highlightColor = NSUIColor.blackColor() } public required init() { super.init() } public override init(results: RLMResults?, yValueField: String, xIndexField: String?, label: String?) { super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(results: RLMResults?, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(results: results, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(results: RLMResults?, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: xIndexField, stackValueField: stackValueField, label: "DataSet") } public convenience init(results: RLMResults?, yValueField: String, stackValueField: String, label: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(results: RLMResults?, yValueField: String, stackValueField: String) { self.init(results: results, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public override init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, label: String?) { super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String, label: String?) { _stackValueField = stackValueField super.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: xIndexField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, xIndexField: String?, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String, label: String?) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: label) } public convenience init(realm: RLMRealm?, modelName: String, resultsWhere: String, yValueField: String, stackValueField: String) { self.init(realm: realm, modelName: modelName, resultsWhere: resultsWhere, yValueField: yValueField, xIndexField: nil, stackValueField: stackValueField, label: nil) } public override func notifyDataSetChanged() { _cache.removeAll() ensureCache(start: 0, end: entryCount - 1) self.calcStackSize(_cache as! [BarChartDataEntry]) super.notifyDataSetChanged() } // MARK: - Data functions and accessors internal var _stackValueField: String? /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 internal override func buildEntryFromResultObject(object: RLMObject, atIndex: UInt) -> ChartDataEntry { let value = object[_yValueField!] let entry: BarChartDataEntry if value is RLMArray { var values = [Double]() for val in value as! RLMArray { values.append((val as! RLMObject)[_stackValueField!] as! Double) } entry = BarChartDataEntry(values: values, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } else { entry = BarChartDataEntry(value: value as! Double, xIndex: _xIndexField == nil ? Int(atIndex) : object[_xIndexField!] as! Int) } return entry } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(yVals: [BarChartDataEntry]!) { for i in 0 ..< yVals.count { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } public override func calcMinMax(start start : Int, end: Int) { let yValCount = self.entryCount if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } ensureCache(start: start, end: endValue) if _cache.count == 0 { return } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for i in start ... endValue { if let e = _cache[i - _cacheFirst] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// - returns: the maximum number of bars that can be stacked upon another in this DataSet. public var stackSize: Int { return _stackSize } /// - returns: true if this DataSet is stacked (stacksize > 1) or not. public var isStacked: Bool { return _stackSize > 1 ? true : false } /// array of labels used to describe the different values of the stacked bars public var stackLabels: [String] = ["Stack"] // MARK: - Styling functions and accessors /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) public var barSpace: CGFloat = 0.15 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value public var barShadowColor = NSUIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) public var highlightAlpha = CGFloat(120.0 / 255.0) // MARK: - NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { let copy = super.copyWithZone(zone) as! RealmBarDataSet copy._stackSize = _stackSize copy.stackLabels = stackLabels copy.barSpace = barSpace copy.barShadowColor = barShadowColor copy.highlightAlpha = highlightAlpha return copy } }
apache-2.0
018f57773b47726e3cb6be9f93ac5a2e
32.924901
173
0.580566
5.139521
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Models/Blog+Quota.swift
2
4320
import Foundation /// This extension add methods to make the manipulation of disk quota values for a blog easier extension Blog { /// Returns true if quota values are available for the site @objc var isQuotaAvailable: Bool { return quotaSpaceAllowed != nil && quotaSpaceUsed != nil } /// Returns the percentage value (0 to 1) of the disk space quota being used @objc var quotaPercentageUsed: NSNumber? { guard let quotaSpaceAllowed = quotaSpaceAllowed?.doubleValue, let quotaSpaceUsed = quotaSpaceUsed?.doubleValue else { return nil } let quotaPercentageUsed = quotaSpaceUsed / quotaSpaceAllowed return NSNumber(value: quotaPercentageUsed) } /// Returns the quota space allowed in a string format using human readable units (kb, Mb, Gb). EX: 1.5 Gb @objc var quotaSpaceAllowedDescription: String? { guard let quotaSpaceAllowed = quotaSpaceAllowed?.int64Value else { return nil } return ByteCountFormatter.string(fromByteCount: quotaSpaceAllowed, countStyle: .binary) } /// Returns the disk quota percentage in a human readable format. Ex: 5% @objc var quotaPercentageUsedDescription: String? { let percentageFormatter = NumberFormatter() percentageFormatter.numberStyle = .percent guard let percentage = quotaPercentageUsed, let quotaPercentageUsedDescription = percentageFormatter.string(from: percentage) else { return nil } return quotaPercentageUsedDescription } /// Returns an human readable message indicating the percentage of disk quota space available in regard to the maximum allowed.Ex: 10% of 15 GB used @objc var quotaUsageDescription: String? { guard isQuotaAvailable, let quotaPercentageUsedDescription = self.quotaPercentageUsedDescription, let quotaSpaceAllowedDescription = self.quotaSpaceAllowedDescription else { return nil } let formatString = NSLocalizedString("%@ of %@ used on your site", comment: "Amount of disk quota being used. First argument is the total percentage being used second argument is total quota allowed in GB.Ex: 33% of 14 GB used on your site.") return String(format: formatString, quotaPercentageUsedDescription, quotaSpaceAllowedDescription) } /// Returns the disk space quota still available to use in the site. @objc var quotaSpaceAvailable: NSNumber? { guard let quotaSpaceAllowed = quotaSpaceAllowed?.int64Value, let quotaSpaceUsed = quotaSpaceUsed?.int64Value else { return nil } let quotaSpaceAvailable = quotaSpaceAllowed - quotaSpaceUsed return NSNumber(value: quotaSpaceAvailable) } /// Returns the maximum upload byte size supported for a media file on the site. @objc var maxUploadSize: NSNumber? { guard let maxUploadSize = getOptionValue("max_upload_size") as? NSNumber else { return nil } return maxUploadSize } /// Returns true if the site has disk quota available to for the file size of the URL provided. /// /// If no quota information is available for the site this method returns true. /// - Parameter url: the file URL to check the filesize /// - Returns: true if there is space available @objc func hasSpaceAvailable(for url: URL) -> Bool { guard let fileSize = url.fileSize, let spaceAvailable = quotaSpaceAvailable?.int64Value else { // let's assume the site can handle it if we don't know any of quota or fileSize information. return true } return fileSize < spaceAvailable } /// Returns true if the site is able to support the file size of an upload made with the specified URL. /// /// - Parameter url: the file URL to check the filesize. /// - Returns: true if the site is able to support the URL file size. @objc func isAbleToHandleFileSizeOf(url: URL) -> Bool { guard let fileSize = url.fileSize, let maxUploadSize = maxUploadSize?.int64Value, maxUploadSize > 0 else { // let's assume the site can handle it. return true } return fileSize < maxUploadSize } }
gpl-2.0
8b5e6a0200b2f2c7976c2c02f5bc99cc
44.957447
250
0.680787
4.942792
false
false
false
false
badoo/Chatto
ChattoApp/ChattoApp/Source/Chat View Controllers/MessagesSelectionChatViewController.swift
1
2309
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit class MessagesSelectionChatViewController: DemoChatViewController { override func viewDidLoad() { super.viewDidLoad() self.setupSelectionButton() } // MARK: - Selection private func setupSelectionButton() { let button = UIBarButtonItem( title: "Select", style: .plain, target: self, action: #selector(handleSelectionButtonTap) ) self.navigationItem.rightBarButtonItem = button } @objc private func handleSelectionButtonTap() { self.setupCancellationButton() self.messagesSelector.isActive = true self.refreshContent() } // MARK: - Cancellation private func setupCancellationButton() { let button = UIBarButtonItem( title: "Cancel", style: .plain, target: self, action: #selector(handleCancellationButtonTap) ) self.navigationItem.rightBarButtonItem = button } @objc private func handleCancellationButtonTap() { self.setupSelectionButton() self.messagesSelector.isActive = false self.refreshContent() } }
mit
65faf3d453e4ea308f39ab52973c4718
31.985714
78
0.700736
5.131111
false
false
false
false
gavinpardoe/DEP-Enrolment
DEP-Enrolment/SoruceViewController.swift
1
7453
// // SoruceViewController.swift // DEP-Enrolment // // Created by Gavin on 05/11/2016. // Copyright © 2016 Trams Ltd. All rights reserved. // // Designed for Use with Jamf Pro. // // The MIT License (MIT) // // Copyright (c) 2016 Gavin Pardoe // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import Cocoa class SoruceViewController: NSViewController, NSTextFieldDelegate { // Interface Builder Connections @IBOutlet weak var userName: NSTextField! @IBOutlet weak var assetTag: NSTextField! @IBOutlet weak var departmentPopup: NSPopUpButton! // Create Instance Refrences var department: [String]! let shellTask = Process() // Key Refrences for userDetails.plist let assetTagKey = "AssetTag" let usernameKey = "Username" let departmentKey = "Department" override func viewDidLoad() { super.viewDidLoad() // Popup Menu Settings department = ["Accounts", "Design", "Marketing", "Operations", "Sales", "Service"] // Modify as required departmentPopup.removeAllItems() departmentPopup.addItems(withTitles: department) departmentPopup.selectItem(at: 0) } // Receives Changes to Text Fields from Delegate & Constrains Characters override func controlTextDidChange(_ obj: Notification) { let characterSet: CharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789-_").inverted let alphaCharSet: CharacterSet = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ.").inverted self.assetTag.stringValue = (self.assetTag.stringValue.components(separatedBy: characterSet) as NSArray).componentsJoined(by: "") self.userName.stringValue = (self.userName.stringValue.components(separatedBy: alphaCharSet) as NSArray).componentsJoined(by: "") } // Submits the User Data to the Jamf Server and Creates the .plist func start() { // Get NSTextField Values as Strings let assetTagValue = self.assetTag.stringValue let usernameValue = self.userName.stringValue let departmentValue = self.departmentPopup.title _ = departmentValue // Runs the Below Tasks Asynchronously as a Background Process DispatchQueue.global(qos: .background).async { // Run Jamf Recon with User Submited Values let appleScriptRecon = NSAppleScript(source: "do shell script \"/usr/local/jamf/bin/jamf recon -assetTag \(assetTagValue) -endUsername \(usernameValue) -department \(departmentValue)\" with administrator " + "privileges")!.executeAndReturnError(nil) let result = appleScriptRecon.stringValue if ((result?.contains("<computer_id")) != nil) { //debugPrint("process completed") // Specify Values for .plist if let plist = Plist(name: "userDetails") { let dict = plist.getMutablePlistFile()! dict[self.assetTagKey] = (assetTagValue) dict[self.usernameKey] = (usernameValue) dict[self.departmentKey] = (departmentValue) do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print(plist.getValuesInPlistFile() ?? "missing") } else { print("Unable to get Plist") } } else { print("process failed") // Specify values for .plist if let plist = Plist(name: "userDetails") { let dict = plist.getMutablePlistFile()! dict[self.assetTagKey] = (assetTagValue) dict[self.usernameKey] = (usernameValue) dict[self.departmentKey] = (departmentValue) do { try plist.addValuesToPlistFile(dict) } catch { print(error) } print(plist.getValuesInPlistFile() ?? "missing") } else { print("Unable to get Plist") } DispatchQueue.main.async { //print(result!) } } } } // Checks for Empty Text Fields, If Empty an Error Message Will be Displayed func checkTextfields() { // Get NSTextField Values as Strings let assetTagValue = assetTag.stringValue let usernameValue = userName.stringValue let departmentValue = departmentPopup.title _ = departmentValue // Make Sure Text Fields are not Empty if assetTagValue.isEmpty { //debugPrint("No Asset Tag Entered") missingValuesAlert() } else if usernameValue.isEmpty { //debugPrint("No Username Entered") missingValuesAlert() } else { //debugPrint("Running Command") // Calls the start Function start() // Performs View Segue, with Custom Segue performSegue(withIdentifier: "segue1", sender: self) } } // Display Message if Any Text Fields are Empty func missingValuesAlert(){ let alert = NSAlert() alert.messageText = "Missing Text Field Values" // Edit as Required alert.informativeText = "All Text Fields Must be Populated" // Edit as Required alert.addButton(withTitle: "Ok") alert.beginSheetModal(for: self.view.window!, completionHandler: { (returnCode) -> Void in if returnCode == NSAlertFirstButtonReturn { } }) } // Refrence to Start Button @IBAction func startDEP(_ sender: Any) { // Calls checkTextfields Function checkTextfields() } }
mit
d4eabf49eb520b1da66425cba12e2884
37.020408
261
0.584138
5.483444
false
false
false
false
rubiconmd/rubicon-ios-sdk
RubiconMD-iOS-SDKTests/AutenticationTestCase.swift
1
1276
// // RubiconMD_iOS_SDKTests.swift // RubiconMDiOSSDK // // Created by Vanessa Cantero Gómez on 19/12/14. // Copyright (c) 2014 RubiconMD. All rights reserved. // import UIKit import XCTest import RubiconMDiOSSDK class AutenticationTestCase: XCTestCase { let invalidUser = "user" let invalidPassword = "password" let validUser = "USER" let validPassword = "PASSWORD" func testHTTPAutentication() { RubiconMDiOSSDK.accessToken(invalidUser, invalidPassword) { (accessToken, HTTPStatusCode, serializationError) -> Void in XCTAssert(HTTPStatusCode.statusCode == 401, "HTTPStatusCode.statusCode should be 401") XCTAssertNotNil(HTTPStatusCode.description, "HTTPStatusCode.description should bot be nil") XCTAssertNil(accessToken, "accessToken should be nil") } RubiconMDiOSSDK.accessToken(validUser, validPassword) { (accessToken, HTTPStatusCode, serializationError) -> Void in XCTAssert(HTTPStatusCode.statusCode == 200, "HTTPStatusCode.statusCode should be 200") XCTAssertNotNil(HTTPStatusCode.description, "HTTPStatusCode.description should bot be nil") XCTAssertNotNil(accessToken!, "accessToken should not be nil") } } }
mit
9b02d4a3eae3d07fe129bb5c28282157
35.428571
128
0.705098
4.636364
false
true
false
false
nikrad/ios
FiveCalls/FiveCalls/IssuesViewController.swift
1
8704
// // IssuesViewController.swift // FiveCalls // // Created by Ben Scheirman on 1/30/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit import Crashlytics import DZNEmptyDataSet protocol IssuesViewControllerDelegate : class { func didStartLoadingIssues() func didFinishLoadingIssues() } class IssuesViewController : UITableViewController { weak var issuesDelegate: IssuesViewControllerDelegate? var lastLoadResult: IssuesLoadResult? var isLoading = false // keep track of when calls are made, so we know if we need to reload any cells var needToReloadVisibleRowsOnNextAppearance = false var issuesManager = IssuesManager() var logs: ContactLogs? var iPadShareButton: UIButton? { didSet { self.iPadShareButton?.addTarget(self, action: #selector(share), for: .touchUpInside) }} struct ViewModel { let issues: [Issue] } var viewModel = ViewModel(issues: []) override func viewDidLoad() { super.viewDidLoad() tableView.emptyDataSetDelegate = self tableView.emptyDataSetSource = self self.registerForPreviewing(with: self, sourceView: tableView) Answers.logCustomEvent(withName:"Screen: Issues List") navigationController?.setNavigationBarHidden(true, animated: false) loadIssues() tableView.estimatedRowHeight = 75 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView() NotificationCenter.default.addObserver(forName: .callMade, object: nil, queue: nil) { [weak self] _ in self?.needToReloadVisibleRowsOnNextAppearance = true } NotificationCenter.default.addObserver(self, selector: #selector(madeCall), name: .callMade, object: nil) } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) logs = ContactLogs.load() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // only reload rows if we need to. this fixes a rare tableview inconsistency crash we've seen if needToReloadVisibleRowsOnNextAppearance { tableView.reloadRows(at: tableView.indexPathsForVisibleRows ?? [], with: .none) needToReloadVisibleRowsOnNextAppearance = false } } func share(button: UIButton) { if let nav = self.splitViewController?.viewControllers.last as? UINavigationController, let shareable = nav.viewControllers.last as? IssueShareable { shareable.shareIssue(from: button) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } func loadIssues() { isLoading = true tableView.reloadEmptyDataSet() issuesDelegate?.didStartLoadingIssues() issuesManager.userLocation = UserLocation.current issuesManager.fetchIssues { [weak self] in self?.issuesLoaded(result: $0) } } private func issuesLoaded(result: IssuesLoadResult) { isLoading = false lastLoadResult = result issuesDelegate?.didFinishLoadingIssues() if case .success = result { viewModel = ViewModel(issues: issuesManager.issues) tableView.reloadData() } else { tableView.reloadEmptyDataSet() } } func madeCall() { logs = ContactLogs.load() tableView.reloadRows(at: tableView.indexPathsForVisibleRows ?? [], with: .none) } override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool { if identifier == R.segue.issuesViewController.issueSegue.identifier, let split = self.splitViewController { guard let indexPath = tableView.indexPathForSelectedRow else { return true } let controller = R.storyboard.main.issueDetailViewController()! controller.issuesManager = issuesManager controller.issue = issuesManager.issues[indexPath.row] let nav = UINavigationController(rootViewController: controller) nav.setNavigationBarHidden(true, animated: false) split.showDetailViewController(nav, sender: self) self.iPadShareButton?.isHidden = false return false } return true } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let indexPath = tableView.indexPathForSelectedRow else { return } if let typedInfo = R.segue.issuesViewController.issueSegue(segue: segue) { typedInfo.destination.issuesManager = issuesManager typedInfo.destination.issue = viewModel.issues[indexPath.row] } } // MARK: - UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel.issues.count } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let notAButton = BorderedButton(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 26.0)) notAButton.setTitle(R.string.localizable.whatsImportantTitle(), for: .normal) notAButton.setTitleColor(.fvc_darkBlueText, for: .normal) notAButton.backgroundColor = .fvc_superLightGray notAButton.borderWidth = 1 notAButton.borderColor = .fvc_mediumGray notAButton.topBorder = true notAButton.bottomBorder = true return notAButton } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 26.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.issueCell, for: indexPath)! let issue = viewModel.issues[indexPath.row] cell.titleLabel.text = issue.name if let hasContacted = logs?.hasCompleted(issue: issue.id, allContacts: issue.contacts) { cell.checkboxView.isChecked = hasContacted } return cell } } extension IssuesViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { guard let indexPath = tableView.indexPathForRow(at: location) else { return nil } guard let detailViewController = R.storyboard.main.issueDetailViewController() else { return nil } guard let cell = tableView.cellForRow(at: indexPath) else { return nil } detailViewController.issuesManager = issuesManager detailViewController.issue = issuesManager.issues[indexPath.row] previewingContext.sourceRect = cell.frame return detailViewController } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { self.show(viewControllerToCommit, sender: self) } } extension IssuesViewController : DZNEmptyDataSetSource { private func appropriateErrorMessage(for result: IssuesLoadResult) -> String { switch result { case .offline: return R.string.localizable.issueLoadFailedConnection() case .serverError(_): return R.string.localizable.issueLoadFailedServer() default: return "" } } func description(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? { let message = appropriateErrorMessage(for: lastLoadResult ?? .offline) return NSAttributedString(string: message, attributes: [ NSFontAttributeName: Appearance.instance.bodyFont ]) } func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControlState) -> UIImage? { return #imageLiteral(resourceName: "refresh") } } extension IssuesViewController : DZNEmptyDataSetDelegate { func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool { return !isLoading } func emptyDataSet(_ scrollView: UIScrollView, didTap button: UIButton) { loadIssues() tableView.reloadEmptyDataSet() } }
mit
90961b911436fa93829cf9b1327f2816
35.721519
157
0.673331
5.546845
false
false
false
false
coodly/laughing-adventure
Source/UI/FetchedCollectionView.swift
1
5939
/* * Copyright 2017 Coodly LLC * * 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 UIKit import CoreData open class FetchedCollectionView<Model: NSManagedObject, Cell: UICollectionViewCell>: UICollectionView, UICollectionViewDataSource, NSFetchedResultsControllerDelegate, UICollectionViewDelegate { public var fetchedController: NSFetchedResultsController<Model>? { didSet { registerCell(forType: Cell.self) fetchedController?.delegate = self dataSource = self delegate = self } } private var changeActions = [ChangeAction]() public var cellConfiguration: ((Cell, Model, IndexPath) -> ())? public var contentChangeHandler: ((FetchedCollectionView<Model, Cell>) -> ())? public var selectionHandler: ((Model, IndexPath) -> ())? public func numberOfSections(in collectionView: UICollectionView) -> Int { return fetchedController?.sections?.count ?? 0 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let controller = fetchedController else { return 0 } let sections:[NSFetchedResultsSectionInfo] = controller.sections! as [NSFetchedResultsSectionInfo] return sections[section].numberOfObjects } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath) as Cell let object = fetchedController!.object(at: indexPath) cellConfiguration?(cell, object, indexPath) return cell } public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { Logging.log("controllerWillChangeContent") changeActions.removeAll() } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { changeActions.append(ChangeAction(sectionIndex: sectionIndex, indexPath: nil, newIndexPath: nil, changeType: type)) } public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { changeActions.append(ChangeAction(sectionIndex: nil, indexPath: indexPath, newIndexPath: newIndexPath, changeType: type)) } public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { Logging.log("controllerDidChangeContent: \(changeActions.count) changes") let visible = indexPathsForVisibleItems let updateClosure = { // update sections let sectionActions = self.changeActions.filter({ $0.sectionIndex != nil }) Logging.log("\(sectionActions.count) section actions") let sectionInserts = sectionActions.filter({ $0.changeType == .insert }).map({ $0.sectionIndex! }) self.insertSections(IndexSet(sectionInserts)) let sectionDeletes = sectionActions.filter({ $0.changeType == .insert }).map({ $0.sectionIndex! }) self.deleteSections(IndexSet(sectionDeletes)) assert(sectionActions.filter({ $0.changeType != .insert && $0.changeType != .delete}).count == 0) let cellActions = self.changeActions.filter({ $0.sectionIndex == nil }) Logging.log("\(cellActions.count) cell actions") let cellUpdates = cellActions.filter({ $0.changeType == .update }) self.reloadItems(at: cellUpdates.map({ $0.indexPath! })) let cellInserts = cellActions.filter({ $0.changeType == .insert }).map({ $0.newIndexPath! }) self.insertItems(at: cellInserts) let cellDeletes = cellActions.filter({ $0.changeType == .delete}).map({ $0.indexPath! }) self.deleteItems(at: cellDeletes) let moveActions = cellActions.filter({ $0.changeType == .move}) for action in moveActions { self.moveItem(at: action.indexPath!, to: action.newIndexPath!) } } let completion: (Bool) -> () = { finished in self.contentChangeHandler?(self) } performBatchUpdates(updateClosure, completion: completion) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if decelerate { return } contentChangeHandler?(self) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { contentChangeHandler?(self) } public func object(at indexPath: IndexPath) -> Model { return fetchedController!.object(at: indexPath) } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) let object = fetchedController!.object(at: indexPath) selectionHandler?(object, indexPath) } }
apache-2.0
790e886c73b3a498bdb0389150b92f4b
43.320896
216
0.669136
5.608121
false
false
false
false
kickstarter/ios-oss
Library/TestHelpers/MockApplication.swift
1
504
import Foundation import Library import UIKit final class MockApplication: UIApplicationType { var applicationIconBadgeNumber = 0 var canOpenURL = false var canOpenURLWasCalled = false var openUrlWasCalled = false func canOpenURL(_: URL) -> Bool { self.canOpenURLWasCalled = true return self.canOpenURL } func open( _: URL, options _: [UIApplication.OpenExternalURLOptionsKey: Any], completionHandler _: ((Bool) -> Void)? ) { self.openUrlWasCalled = true } }
apache-2.0
a71df514eb3376db70a76a54d5e6c4ca
20.913043
62
0.708333
4.666667
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/ExtensionMapKit.swift
1
6169
// // ExtensionMapKit.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/23. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation import MapKit import UIKit /// MapKit 用の値に変換するextension extension Style { // TODO:LineStyle // TODO:PolyStyle // TODO:Width } extension Placemark { // MKOverlay var toMKOverlay:MKOverlay? { var shape:MKShape? = nil let polygons = self.select(Polygon) if polygons.count == 1 { let polygon = polygons[0].toMKPolygon shape = polygon shape?.title = self.value.name?.value } return shape as? MKOverlay } // MKOverlayPathRenderer func getMKOverlayPathRenderer() -> MKOverlayPathRenderer? { let polygons = self.select(Polygon) if polygons.count == 1 { let idString = self.value.styleUrl?.value.substringFromIndex(self.value.styleUrl!.value.startIndex.advancedBy(1)) debugPrint("id = \(idString)") let styles = self.root.select("id", attributeValue: idString!) debugPrint("\(styles)") let renderer = polygons[0].getMKOverlayPathRenderer()! if styles.count == 1 { let style = styles[0] as! Style renderer.strokeColor = style.value.lineStyle?.value.color?.toUIColor renderer.fillColor = style.value.polyStyle?.value.color?.toUIColor renderer.lineWidth = CGFloat((style.value.lineStyle?.value.width?.value)!) } return renderer } return nil } // MKAnnotation var toMKAnnotation:MKAnnotation? { let points = self.select(Point) if points.count == 1 { let point = points[0].toMKPointAnnotation point?.title = self.value.name?.value return point } return nil } // MKAnnotationView func getMKAnnotationView() -> MKAnnotationView? { let points = self.select(Point) if points.count == 1 { return points[0].getMKAnnotationView() } return nil } } extension Point { // MKPointAnnotation var toMKPointAnnotation:MKPointAnnotation? { guard let coordinate = (self.value.coordinates?.toLocationCoordinate2Ds[0]) else { return nil } let anotation:MKPointAnnotation = MKPointAnnotation() anotation.coordinate = coordinate return anotation } // func getMKAnnotationView() -> MKAnnotationView? { guard let point = self.toMKPointAnnotation else { return nil } let view = MKPinAnnotationView(annotation: point, reuseIdentifier: nil) view.canShowCallout = true view.animatesDrop = true return view } } extension Polygon { // MKPolygon var toMKPolygon:MKPolygon? { let coords:[CLLocationCoordinate2D] = self.value.outerBoundaryIs!.value.linearRing!.value.coordinates!.toLocationCoordinate2Ds var polygons:[MKPolygon] = [] if var innerBoundaryIsCoord:[CLLocationCoordinate2D] = self.value.innerBoundaryIs?.value.linearRing?.value.coordinates?.toLocationCoordinate2Ds { polygons.append(MKPolygon(coordinates: &innerBoundaryIsCoord, count: innerBoundaryIsCoord.count)) } let ret = MKPolygon(coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>(coords), count: coords.count, interiorPolygons: polygons) debugPrint("\(ret.pointCount) == \(coords.count)") assert(ret.pointCount == coords.count) return ret } // MKOverlayPathRenderer func getMKOverlayPathRenderer() -> MKOverlayPathRenderer? { guard let polygon = self.toMKPolygon else { return nil } let renderer = MKPolygonRenderer(polygon: polygon) return renderer } } extension LineString { // MKShape var toMKPolyLine:MKPolyline? { let coords:[CLLocationCoordinate2D] = self.value.coordinates!.toLocationCoordinate2Ds let ret = MKPolyline(coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>(coords), count: coords.count) return ret } // KMOverlayPathRenderer func getMKOverlayPathRenderer(target: MKPolyline) -> MKOverlayPathRenderer? { let renderer = MKPolylineRenderer(polyline: target) return renderer } } extension Coordinates { var toLocationCoordinate2Ds:[CLLocationCoordinate2D] { var ret:[CLLocationCoordinate2D]=[] ret.reserveCapacity(10) for v in value { let longitude:Double = Double(v.longitude)! let latitude:Double = Double(v.latitude)! let coord = CLLocationCoordinate2DMake(latitude, longitude) if CLLocationCoordinate2DIsValid(coord) { ret.append(coord) } } return ret } } extension BgColor { var toUIColor:UIColor? { return UIColor(hexString: self.value) } } extension Color { var toUIColor:UIColor? { return UIColor(hexString: self.value) } } extension TextColor { var toUIColor:UIColor? { return UIColor(hexString: self.value) } } /// <summary> /// <![CDATA[ /// /// aabbggrr /// /// ffffffff: opaque white /// ff000000: opaque black /// /// ]]> /// </summary> public extension UIColor { public convenience init?(hexString: String){ let r, g, b, a : CGFloat if hexString.characters.count == 8 { let scanner = NSScanner(string: hexString) var hexNumber: UInt64 = 0 if scanner.scanHexLongLong(&hexNumber) { a = CGFloat((hexNumber & 0xff000000) >> 24) / 255 b = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255 g = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255 r = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red:r, green: g, blue: b, alpha: a) return } } return nil } func toHexString() -> String { // TODO: hexString return "" } }
mit
171fc88da1ee8732bbeae7a3177a8248
29.864322
153
0.613481
4.573343
false
false
false
false
jegumhon/URWeatherView
URWeatherView/SpriteAssets/URSnowEmitterNode.swift
1
1848
// // URSnowEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 14.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URSnowEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URSnowEmitterNode.self) let particleImage = UIImage(named: "snow_typeA", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 40.0 // self.particleBirthRateMax? self.particleLifetime = 50.0 self.particleLifetimeRange = 0.0 self.particlePositionRange = CGVector(dx: 363.44, dy: -30.0) self.zPosition = 0.0 self.emissionAngle = CGFloat(269.863 * .pi / 180.0) self.emissionAngleRange = CGFloat(22.918 * .pi / 180.0) self.particleSpeed = 10.0 self.particleSpeedRange = 30.0 self.xAcceleration = -2 self.yAcceleration = -1 self.particleAlpha = 1.0 self.particleAlphaRange = 0.2 self.particleAlphaSpeed = 0.0 self.particleScale = 0.1 self.particleScaleRange = 0.1 self.particleScaleSpeed = 0.0 self.particleRotation = 0.0 self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 1.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
mit
c3c7c44801839595a345098a106c4fc4
36.653061
232
0.647154
3.63189
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Binary Search/35_Search Insert Position.swift
1
1465
// 35_Search Insert Position // https://leetcode.com/problems/search-insert-position/ // // Created by Honghao Zhang on 9/16/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. // //You may assume no duplicates in the array. // //Example 1: // //Input: [1,3,5,6], 5 //Output: 2 //Example 2: // //Input: [1,3,5,6], 2 //Output: 1 //Example 3: // //Input: [1,3,5,6], 7 //Output: 4 //Example 4: // //Input: [1,3,5,6], 0 //Output: 0 // import Foundation class Num35 { /// Binary search, when while loop ends, check where to insert func searchInsert(_ nums: [Int], _ target: Int) -> Int { if nums.count == 0 { return 0 } if nums.count == 1 { if nums[0] == target { return 0 } else if nums[0] > target { return 0 } else { return 1 } } var start = 0 var end = nums.count - 1 while start + 1 < end { let mid = start + (end - start) / 2 if nums[mid] < target { start = mid } else if nums[mid] > target { end = mid } else { return mid } } if target <= nums[start] { return start } else if nums[start] < target, target <= nums[end] { return end } else { return end + 1 } } }
mit
f6f7da82fa7ee86379787777df981012
18.783784
157
0.543716
3.319728
false
false
false
false
lukejmann/FBLA2017
FBLA2017/ResetPasswordPopoverViewController.swift
1
1288
// // EnterPricePopoverViewController.swift // FBLA2017 // // Created by Luke Mann on 4/9/17. // Copyright © 2017 Luke Mann. All rights reserved. // import UIKit import FirebaseAuth //Class to make a popover for making a new group class ResetPasswordPopoverViewController: UIViewController { @IBOutlet weak var textBox: UITextView! override func viewDidLoad() { super.viewDidLoad() textBox.textAlignment = .center textBox.adjustsFontForContentSizeCategory = true textBox.font = UIFont(name: "AvenirNext-Bold", size: 36) textBox.becomeFirstResponder() } override func viewDidAppear(_ animated: Bool) { self.view.layer.cornerRadius = 10 self.view.layer.masksToBounds = true } @IBAction func cancelButtonPressed(_ sender: UIButton) { textBox.endEditing(true) dismiss(animated: true, completion: nil) } @IBAction func okButtonPressed(_ sender: Any) { textBox.endEditing(true) if let text = textBox?.text { if !text.isEmpty { FIRAuth.auth()?.sendPasswordReset(withEmail: self.textBox.text!, completion: nil) } dismiss(animated: true, completion: nil) } } }
mit
d7a862c4f0320d89ff11b0a89bde6d7e
25.8125
97
0.632479
4.766667
false
false
false
false
wfleming/SwiftLint
Source/SwiftLintFramework/Rules/LegacyConstantRule.swift
2
2857
// // LegacyConstantRule.swift // SwiftLint // // Created by Aaron McTavish on 12/01/2016. // Copyright © 2016 Realm. All rights reserved. // import SourceKittenFramework public struct LegacyConstantRule: CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.Warning) public init() {} public static let description = RuleDescription( identifier: "legacy_constant", name: "Legacy Constant", description: "Struct-scoped constants are preferred over legacy global constants.", nonTriggeringExamples: [ "CGRect.infinite", "CGPoint.zero", "CGRect.zero", "CGSize.zero", "CGRect.null" ], triggeringExamples: [ "↓CGRectInfinite", "↓CGPointZero", "↓CGRectZero", "↓CGSizeZero", "↓CGRectNull" ], corrections: [ "CGRectInfinite\n": "CGRect.infinite\n", "CGPointZero\n": "CGPoint.zero\n", "CGRectZero\n": "CGRect.zero\n", "CGSizeZero\n": "CGSize.zero\n", "CGRectNull\n": "CGRect.null\n" ] ) public func validateFile(file: File) -> [StyleViolation] { let constants = ["CGRectInfinite", "CGPointZero", "CGRectZero", "CGSizeZero", "CGRectNull"] let pattern = "\\b(" + constants.joinWithSeparator("|") + ")\\b" return file.matchPattern(pattern, withSyntaxKinds: [.Identifier]).map { StyleViolation(ruleDescription: self.dynamicType.description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } public func correctFile(file: File) -> [Correction] { let patterns = [ "CGRectInfinite": "CGRect.infinite", "CGPointZero": "CGPoint.zero", "CGRectZero": "CGRect.zero", "CGSizeZero": "CGSize.zero", "CGRectNull": "CGRect.null" ] let description = self.dynamicType.description var corrections = [Correction]() var contents = file.contents for (pattern, template) in patterns { let matches = file.matchPattern(pattern, withSyntaxKinds: [.Identifier]) let regularExpression = regex(pattern) for range in matches.reverse() { contents = regularExpression.stringByReplacingMatchesInString(contents, options: [], range: range, withTemplate: template) let location = Location(file: file, characterOffset: range.location) corrections.append(Correction(ruleDescription: description, location: location)) } } file.write(contents) return corrections } }
mit
c244c15002e01aae92983cb99daa567f
32.482353
96
0.588545
4.949565
false
false
false
false
aiqiuqiu/Tuan
Tuan/UserPrefrence/VC/HMDealLocalListViewController.swift
2
5287
// // HMDealLocalListViewController.swift // Tuan // // Created by nero on 15/5/29. // Copyright (c) 2015年 nero. All rights reserved. // 本地记录父类 import UIKit private struct HMTextStatus { static let HMEditText = "编辑" static let HMDoneText = "完成" } class HMDealLocalListViewController:HMDealListViewController { // MARK: - init override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: items lazy var backItem:UIBarButtonItem = { var item = UIBarButtonItem(imageName: "icon_back", highImageName: "icon_back_highlighted", target: self, action: Selector("back")) return item }() lazy var selectAllItem:UIBarButtonItem = { var item = UIBarButtonItem(title: " 全选 ", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("selectAll")) return item }() lazy var unselectAllItem:UIBarButtonItem = { var item = UIBarButtonItem(title: " 全不选 ", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("unselectAll")) return item }() lazy var deleteItem:UIBarButtonItem = { var item = UIBarButtonItem(title: " 删除 ", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("delete")) item.enabled = false return item }() func back(){ dismissViewControllerAnimated(true, completion: nil) } // /** // * 全选 // */ func selectAll(){ for deal in deals { deal.checking = true } self.collectionView?.reloadData() // // 控制删除item的状态和文字 dealCellDidClickCover(HMDealCell()) } // /** // * 全不选 // */ func unselectAll(){ for deal in deals { deal.checking = false } self.collectionView?.reloadData() // // 控制删除item的状态和文字 dealCellDidClickCover(HMDealCell()) } override func viewDidLoad() { super.viewDidLoad() // // 设置左上角的返回按钮 navigationItem.leftBarButtonItems = [self.backItem ] // // 设置右上角的编辑按钮 navigationItem.rightBarButtonItem = UIBarButtonItem(title: HMTextStatus.HMEditText, style: UIBarButtonItemStyle.Done, target: self, action: Selector("edit")) } /** * 编辑 或者完成 */ func edit(){ let title = navigationItem.rightBarButtonItem?.title if title == HMTextStatus.HMEditText { navigationItem.rightBarButtonItem?.title = HMTextStatus.HMDoneText for deal in deals { deal.editing = true } self.collectionView?.reloadData() // // 左边显示4个item self.navigationItem.leftBarButtonItems = [self.backItem, self.selectAllItem, self.unselectAllItem, self.deleteItem] }else{ navigationItem.rightBarButtonItem?.title = HMTextStatus.HMEditText for deal in deals { deal.editing = false deal.checking = false } self.collectionView?.reloadData() dealCellDidClickCover(HMDealCell()) // // 左边显示1个item self.navigationItem.leftBarButtonItems = [self.backItem]; } } /** * 返回即将删除的团购 */ func willDeletedDeals() ->[HMDeal] { var checkingDeals = [HMDeal]() // 取出被打钩的团购 for deal in deals { if deal.checking { checkingDeals.append(deal) // 由于history 和collec 用的是相同的model 所以删除之后状态要清空 deal.checking = false deal.editing = false } } let dealsNS = NSMutableArray(array: deals) dealsNS.removeObjectsInArray(checkingDeals) //waning 这里有错 self.deals = NSArray(array: dealsNS) as! [(HMDeal)] collectionView?.reloadData() // 控制删除item的状态和文字 dealCellDidClickCover(nil ) return checkingDeals; } /** * 删除 */ func delete(){ } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) for deal in deals { deal.editing = false deal.checking = false } } override func dealCellDidClickCover(dealCell: HMDealCell?) { var deleteEnable = false var checkingCount = 0 // // 1.删除item的状态 for deal in deals { if deal.checking { deleteEnable = true checkingCount++ } } deleteItem.enabled = deleteEnable // // 2.删除item的文字 if checkingCount > 0 { deleteItem.title = " 删除\(checkingCount) " }else{ deleteItem.title = " 删除 " } } } //extension HMDealLocalListViewController : HMDealCellDelegate { //}
mit
3ffb0b54de39a4beb083a6f2495c3921
29.096386
165
0.577578
4.483842
false
false
false
false
GarenChen/SunshineAlbum
SunshineAlbum/Classes/View/PhotoPreviewCell.swift
1
2423
// // PhotoPreviewCell.swift // PhotosDemo // // Created by ChenGuangchuan on 2017/8/27. // Copyright © 2017年 CGC. All rights reserved. // import UIKit class PhotoPreviewCell: UICollectionViewCell, PreviewContentType, UIScrollViewDelegate { @IBOutlet private weak var contentScrollView: UIScrollView! @IBOutlet private weak var contentImageView: UIImageView! var tapConentToHideBar: ((Bool) -> Void)? private var hiddenBars: Bool = false var model: AssetModel? { didSet { guard let model = model else { return } contentImageView.image = nil AssetsManager.shared.fetchPreviewImage(asset: model.asset) { [weak self] (image) in guard let `self` = self else { return } self.contentImageView.image = image } } } override func awakeFromNib() { super.awakeFromNib() // Initialization code contentScrollView.delegate = self let singleTap = UITapGestureRecognizer(target: self, action: #selector(singleTapImageView)) addGestureRecognizer(singleTap) let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapImageView(_:))) doubleTap.numberOfTapsRequired = 2 addGestureRecognizer(doubleTap) } func recoverSubview() { contentScrollView.setZoomScale(1, animated: false) } @objc func singleTapImageView() { hiddenBars = !hiddenBars tapConentToHideBar?(hiddenBars) } @objc func doubleTapImageView(_ gesture: UITapGestureRecognizer) { if contentScrollView.zoomScale > 1 { contentScrollView.setZoomScale(1, animated: true) } else { let touchPoint = gesture.location(in: contentImageView) let newScale = contentScrollView.maximumZoomScale let xSize = frame.size.width / newScale let ySize = frame.size.height / newScale contentScrollView.zoom(to: CGRect(x: touchPoint.x - xSize/2, y: touchPoint.y - ySize/2, width: xSize, height: ySize), animated: true) } } // MARK: - UIScroll view delegate func scrollViewDidZoom(_ scrollView: UIScrollView) { } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return contentImageView } }
mit
5db6e4c5a5416e6d87190525b8e12907
30.025641
145
0.628926
5.094737
false
false
false
false
banjun/NorthLayout
Example/NorthLayout-osx/AppDelegate.swift
1
1079
// // AppDelegate.swift // NorthLayout-osx // // Created by BAN Jun on 5/9/15. // Copyright (c) 2015 banjun. All rights reserved. // import Cocoa import NorthLayout @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! func applicationDidFinishLaunching(_ notification: Notification) { // Insert code here to initialize your application let view = window.contentView! let nameLabel = NSTextField() nameLabel.stringValue = "Name" nameLabel.backgroundColor = .gray let textLabel = NSTextField() textLabel.stringValue = "Some text label" textLabel.backgroundColor = .lightGray let autolayout = view.northLayoutFormat(["p": 8], [ "name": nameLabel, "text": textLabel, "L": MinView(), "R": MinView(), ]) autolayout("H:|-p-[name]-p-|") autolayout("H:|-p-[L][text(<=320)][R(==L)]-p-|") autolayout("V:|-p-[name]-p-[text]") } }
mit
049f76e18021eec233c7a7ec6084ea9d
25.317073
70
0.585728
4.495833
false
false
false
false
freesuraj/PGParallaxView
FrameMe/NewsFeeder.swift
1
1702
// // NewsFeeder.swift // FrameMe // // Created by Suraj Pathak on 30/12/15. // Copyright © 2015 Suraj Pathak. All rights reserved. // import Foundation struct EspnNews { var title: String = "" var story: String = "" var imageUrlString: String = "" } struct NewsFeeder { static func loadHeadlines() -> [EspnNews] { guard let newsJsonData = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("espnNews_sample", ofType: "json")!) else { return [] } var newsArray = [EspnNews]() do { let json = try NSJSONSerialization.JSONObjectWithData(newsJsonData, options: .AllowFragments) if let headlines = json["headlines"] as? [[String: AnyObject]] { for headline in headlines { var espnNews = EspnNews() if let title = headline["headline"] as? String { espnNews.title = title } if let story = headline["story"] as? String { espnNews.story = story } if let images = headline["images"] as? [AnyObject] { let firstImage = images[0] if let url = firstImage["url"] as? String { espnNews.imageUrlString = url } } newsArray.append(espnNews) } } } catch { print("error serializing JSON: \(error)") } newsArray.appendContentsOf(newsArray) newsArray.appendContentsOf(newsArray) return newsArray } }
mit
0b01ad7f876e997e3f1d2b77819892f8
32.352941
137
0.508524
4.818697
false
false
false
false
neoneye/SwiftyFORM
Source/Cells/SwitchCell.swift
1
1482
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public struct SwitchCellModel { var title: String = "" var titleFont: UIFont = .preferredFont(forTextStyle: .body) var titleTextColor: UIColor = Colors.text var valueDidChange: (Bool) -> Void = { (value: Bool) in SwiftyFormLog("value \(value)") } } public class SwitchCell: UITableViewCell, AssignAppearance { public let model: SwitchCellModel public let switchView: UISwitch public init(model: SwitchCellModel) { self.model = model self.switchView = UISwitch() super.init(style: .default, reuseIdentifier: nil) selectionStyle = .none textLabel?.text = model.title textLabel?.font = model.titleFont assignDefaultColors() switchView.addTarget(self, action: #selector(SwitchCell.valueChanged), for: .valueChanged) accessoryView = switchView } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc public func valueChanged() { SwiftyFormLog("value did change") model.valueDidChange(switchView.isOn) } public func setValueWithoutSync(_ value: Bool, animated: Bool) { SwiftyFormLog("set value \(value), animated \(animated)") switchView.setOn(value, animated: animated) } public func assignDefaultColors() { textLabel?.textColor = model.titleTextColor } public func assignTintColors() { textLabel?.textColor = tintColor } }
mit
0aa51b09cb21e5488cb894159dd1f0d2
25.945455
92
0.709177
4.139665
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/Feedbin/FeedbinDate.swift
1
466
// // FeedbinDate.swift // Account // // Created by Maurice Parker on 5/12/19. // Copyright © 2019 Ranchero Software, LLC. All rights reserved. // import Foundation struct FeedbinDate { public static var formatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'" formatter.locale = Locale(identifier: "en_US") formatter.timeZone = TimeZone(abbreviation: "GMT") return formatter }() }
mit
5c7791b91e7b759794d6fd983306afbb
21.142857
65
0.703226
3.345324
false
false
false
false
aranasaurus/ratings-app
mobile/LikeLike/Modules/ItemDetails/ItemDetailsView.swift
1
2374
// // ItemDetailsView.swift // LikeLike // // Created by Ryan Arana on 10/26/17. // Copyright © 2017 aranasaurus. All rights reserved. // import UIKit final class ItemDetailsView: UIView { var item: Item? { didSet { if let item = item { configure(for: item) } else { prepareForReuse() } } } private let rating: UILabel = UILabel() private let imageView: UIImageView = UIImageView() private let comments: UITextView = UITextView() // TODO: Tag List private let stackView: UIStackView = UIStackView() init(item: Item?) { self.item = item super.init(frame: .zero) setupSubviews() if let item = item { configure(for: item) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func prepareForReuse() { rating.text = nil imageView.image = nil comments.text = "" } private func setupSubviews() { backgroundColor = Colors.lightBackground stackView.translatesAutoresizingMaskIntoConstraints = false stackView.axis = .vertical stackView.spacing = 16 stackView.isLayoutMarginsRelativeArrangement = true addSubview(stackView) NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 8), stackView.leadingAnchor.constraint(equalTo: readableContentGuide.leadingAnchor), stackView.trailingAnchor.constraint(equalTo: readableContentGuide.trailingAnchor) ]) rating.textColor = Colors.foreground rating.font = UIFont.preferredFont(forTextStyle: .title1, compatibleWith: traitCollection) rating.textAlignment = .right stackView.addArrangedSubview(rating) // TODO: actually configure these stackView.addArrangedSubview(imageView) stackView.addArrangedSubview(comments) // TODO: Tag List } // TODO: update fonts as needed for system preference and trait collection changes private func configure(for item: Item) { rating.text = String(format: "%0.0f stars", item.rating) imageView.image = UIImage(contentsOfFile: item.photoUrl?.absoluteString ?? "") } }
mit
8d8de8dabf7197728dce592bedd1316e
28.296296
98
0.638432
5.092275
false
false
false
false
Fidetro/SwiftFFDB
Sources/Create.swift
1
1456
// // Create.swift // Swift-FFDB // // Created by Fidetro on 2018/6/1. // Copyright © 2018年 Fidetro. All rights reserved. // import Foundation public struct Create :STMT { var stmt: String public init(_ stmt: String) { self.stmt = " " + "create" + " " + stmt } public init(_ table:FFObject.Type) { self.init("table if not exists \(table.tableName()) (\(createTableSQL(table: table)))") } } fileprivate func createTableSQL(table:FFObject.Type) -> String { var sql = String() let primaryKeyColumn = table.primaryKeyColumn() let type = table.columnsType()[primaryKeyColumn] ?? "integer PRIMARY KEY AUTOINCREMENT" if let customAutoColumn = table.customColumns()?[primaryKeyColumn] { sql.append("\(customAutoColumn) \(type)") sql.append(",") }else{ sql.append("\(primaryKeyColumn) \(type)") sql.append(",") } for (index,column) in table.columnsOfSelf().enumerated() { if let name = table.customColumns()?[column] { sql.append(name) }else{ sql.append(column) } sql.append(" ") if let type = table.columnsType()[column]{ sql.append(type) }else{ sql.append("TEXT") } if table.columnsOfSelf().count-1 != index { sql.append(",") } } return sql }
apache-2.0
392e2277ae6d637c904cc485b53ac146
22.819672
96
0.547832
4.024931
false
false
false
false
stevewight/DetectorKit
DetectorKit/Models/Helpers/CoordConverter.swift
1
1594
// // CoordConverter.swift // Sherlock // // Created by Steve on 12/10/16. // Copyright © 2016 Steve Wight. All rights reserved. // import UIKit class CoordConverter: NSObject { var transform:CGAffineTransform! var imageSize:CGSize! var viewSize:CGSize! init(_ inputImageSize:CGSize,_ inputViewSize:CGSize) { super.init() imageSize = inputImageSize viewSize = inputViewSize transform = executeTransform() } public func convert(_ bounds:CGRect)->CGRect { var newBounds = bounds.applying(transform) let scale = calcScale() newBounds = newBounds.applying(scaleTranform(scale)) newBounds.origin.x += calcOffsetX(scale) newBounds.origin.y += calcOffsetY(scale) return newBounds } private func executeTransform()->CGAffineTransform { let newTransform = CGAffineTransform(scaleX: 1, y: -1) return newTransform.translatedBy(x: 0, y: -imageSize.height) } private func calcScale()->CGFloat { return min(viewSize.width / imageSize.width, viewSize.height / imageSize.height) } private func calcOffsetX(_ scale:CGFloat)->CGFloat { return (viewSize.width - imageSize.width * scale) / 2 } private func calcOffsetY(_ scale:CGFloat)->CGFloat { return (viewSize.height - imageSize.height * scale) / 2 } private func scaleTranform(_ scale:CGFloat)->CGAffineTransform { return CGAffineTransform(scaleX: scale, y: scale) } }
mit
ad3ddc87d998f460cd315f1afac027ef
26.465517
68
0.629002
4.657895
false
false
false
false
firebase/quickstart-ios
dynamiclinks/DynamicLinksSwiftUIExample/LinkReceivedView.swift
1
3424
// Copyright 2022 Google LLC // // 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 SwiftUI import FirebaseDynamicLinks struct LinkReceivedView: View { let receivedLinkModel: ReceivedLinkModel var body: some View { Form { Section(header: Text("Received URL")) { if let linkURL = receivedLinkModel.receivedURL { HStack { Label("URL", systemImage: "link") Text(linkURL.absoluteString).font(.system(.body, design: .monospaced)) } } } if let dynamicLink = receivedLinkModel.dynamicLink, let linkURL = dynamicLink.url { Section(header: Text("Dynamic Link")) { LazyVGrid(columns: [ GridItem(.flexible(minimum: 50.0, maximum: .infinity), alignment: .init(horizontal: .trailing, vertical: .center)), GridItem( .flexible(minimum: 50.0, maximum: .infinity), alignment: .init(horizontal: .leading, vertical: .center) ), ]) { Text("URL").multilineTextAlignment(.trailing) Link( destination: linkURL, label: { Label(linkURL.absoluteString, systemImage: "link").labelStyle(.titleOnly) .multilineTextAlignment(.leading) } ) Text("Match Confidence").multilineTextAlignment(.trailing) Text(dynamicLink.matchType.name).multilineTextAlignment(.leading) Text("UTM Parameters").multilineTextAlignment(.trailing) Text(dynamicLink.utmParametersDictionary.description).multilineTextAlignment(.leading) Text("Minimum App Version").multilineTextAlignment(.trailing) Text(dynamicLink.minimumAppVersion ?? "N/A").multilineTextAlignment(.leading) } } } if let error = receivedLinkModel.error { Section(header: Text("Error")) { Text(error.localizedDescription) } } } } } struct LinkReceivedView_Previews: PreviewProvider { static let linkURL = "https://firebase.google.com" static var previews: some View { LinkReceivedView(receivedLinkModel: ReceivedLinkModel( receivedURL: URL(string: "https://firebase.page.link?link=\(linkURL)"), dynamicLink: MutableDynamicLink( url: URL(string: linkURL), matchType: .unique ), error: nil )).previewDisplayName("Received Dynamic Link") LinkReceivedView(receivedLinkModel: ReceivedLinkModel( receivedURL: URL(string: linkURL), dynamicLink: nil, error: DynamicLinkError.previewError )).previewDisplayName("Dynamic Link Error") } } private enum DynamicLinkError: Error { case previewError } extension DynamicLinkError: LocalizedError { var errorDescription: String? { switch self { case .previewError: return "The received URL is not a Dynamic Link." } } }
apache-2.0
b0738915d9aac7ef1689879c6bd3388e
34.298969
98
0.650117
4.74896
false
false
false
false
siejkowski/LetsTry
Tests/LinuxMain.swift
1
1960
import XCTest @testable import LetsTryTests struct FlatMapTests { static var allTestCases = [ testCase(TryFlatMappableTests.allTests), testCase(TryTypedFlatMappableTests.allTests), testCase(TryLazyFlatMappableTests.allTests) ] } struct MapTests { static var allTestCases = [ testCase(TryMappableTests.allTests), testCase(TryTypedMappableTests.allTests), testCase(TryLazyMappableTests.allTests) ] } struct OperatorsTests { static var allTestCases = [ testCase(TryOperatorsTests.allTests), testCase(TryLazyOperatorsTests.allTests), testCase(TryTypedOperatorsTests.allTests) ] } struct PatternMatchingTests { static var allTestCases = [ testCase(TryPatternMatchingTests.allTests), testCase(TryTypedPatternMatchingTests.allTests), testCase(TryLazyPatternMatchingTests.allTests) ] } struct TransformationsTests { static var allTestCases = [ testCase(TryConvertibleTests.allTests), testCase(TryLazyConvertibleTests.allTests), testCase(TryTypedConvertibleTests.allTests), testCase(OptionalConvertibleTests.allTests), testCase(ThrowsConvertibleTests.allTests) ] } struct TypeTests { static var allTestCases = [ testCase(TryLazyCreationTests.allTests), testCase(TryLazyComputableTests.allTests), testCase(TryLazyErrorableTests.allTests), testCase(TryCreationTests.allTests), testCase(TryErrorableTests.allTests), testCase(TryTypedCreationTests.allTests), testCase(TryTypedErrorableTests.allTests) ] } XCTMain( FlatMapTests.allTestCases + MapTests.allTestCases + OperatorsTests.allTestCases + PatternMatchingTests.allTestCases + TransformationsTests.allTestCases + TypeTests.allTestCases )
mit
3fb15e71fd3663a681448d105068ad4c
29.153846
60
0.685714
4.924623
false
true
false
false
southfox/jfwindguru
JFWindguru/Classes/Model/Time.swift
1
1494
// // Time.swift // Pods // // Created by Javier Fuchs on 6/6/16. // // import Foundation public class Time: Object, Mappable { var hour: Int = 0 var minutes: Int = 0 var seconds: Int = 0 required public convenience init?(map: [String:Any]) { self.init("00:00:00") mapping(map: map) } public func mapping(map: [String:Any]) { } required public init?(_ str: String?) { super.init() hour = 0 minutes = 0 seconds = 0 if let str = str { let words = str.components(separatedBy: ":") if words.count == 3 { hour = Int(words[0]) ?? 0 minutes = Int(words[1]) ?? 0 seconds = Int(words[2]) ?? 0 } else if words.count == 2 { hour = Int(words[0]) ?? 0 minutes = Int(words[1]) ?? 0 } else { assert(false) } } } public var description : String { var aux : String = "\(type(of:self)): " aux += String(format: "%02d:%02d:%02d", hour, minutes, seconds) return aux } } extension Time { public func asDate() -> Date? { var interval = Double(hour) interval += Double(minutes * 60) interval += Double(seconds * 60 * 60) let date = Date.init(timeInterval:interval, since: Date.init()) return date } }
mit
9dcf90003e066d1c09af8e9d8d05e6d6
21.298507
71
0.470549
4.005362
false
false
false
false
artists-formally-known-as-flippinclash/ios-blastermind
Blastermind/Blastermind/GameEngine.swift
1
4529
// // GameEngine.swift // Blastermind // // Created by Stephen Christopher on 2015.03.06. // Copyright (c) 2015 Big Nerd Ranch. All rights reserved. // import Foundation // All logic and game moves should go through here. // The engine may use other resources, locally or on a server, to make game // decisions class GameEngine: ClientDelegate { private var engineState = EngineState.Online(Client()) private var serverConn = ServerConnection() private var playerCallback: (Match)->() = {(Match) in } var localPlayer: Player = Player(name:"Bobo", id: 1) var watchedMatch: Match? // aaaaaaahhhh var feedbackForAllRows: [Feedback] = [] var feedbackCallback: ((Feedback)->())? // DEBUG: func makeItAllHappen() { let maybePlayer = SuggestedPlayer(name: "Bobo") requestMatch(maybePlayer, startMatchCallback: mixItUp) } func mixItUp(Match) { println("What is even happening") } func weDidIt() { println("Winning.") } // Real stuff func requestMatch(player: SuggestedPlayer, startMatchCallback:(Match)->()) { switch engineState { case .Online(let theClient): theClient.delegate = self playerCallback = startMatchCallback serverConn.requestNewMatch(player, callback: receiveMatch) case .Offline: // start local match break } } func receiveMatch(data: NSData) { let meDictKey = "you" let dataDictKey = "data" var jsonParsingError = NSErrorPointer() let matchDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: jsonParsingError) as! [String: AnyObject]? if matchDict == nil && jsonParsingError != nil { println("Failed to parse match: <\(jsonParsingError)") } else if let actualMatch = matchDict, let me = actualMatch[meDictKey] as? NSDictionary, let player = Player(json: me), let data = actualMatch[dataDictKey] as? NSDictionary, let match = Match(json: data) { // println("Received player: <\(player)>, match: <\(match)>, name: <\(match.name)>") localPlayer = player switch engineState { case .Online(let client): watchedMatch = match client.watchMatch(match, callback: { (eventData) -> Void in println("engine got data: <\(eventData)>") }) case .Offline: break } } } func receivedEvent(_: PTPusherEvent!) { playerCallback(watchedMatch!) } func easyGuess(guess: Guess, feedCallBack: (Feedback)->() ) { self.feedbackCallback = feedCallBack sendInGuess(localPlayer, match: watchedMatch!, guess: guess) } func sendInGuess(player: Player, match: Match, guess: Guess) { serverConn.actuallySubmitGuess(player, match: match, guess: guess) { (data) -> () in println("got guess data: <\(data)>") self.receiveFeedback(data) } } func receiveFeedback(data: NSData) { let dataDictKey = "data" let feedbackDictKey = "feedback" let typeCountKey = "position_count" let typeAndPositionKey = "peg_count" let outcomeKey = "outcome" // might cheat and grab this let lossKey = "incorrect" let winKey = "correct" var jsonParsingError = NSErrorPointer() let fullFeedbackDict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: jsonParsingError) as! [String: AnyObject]? if fullFeedbackDict == nil && jsonParsingError != nil { println("Failed to parse match: <\(jsonParsingError)") } else if let actualDict = fullFeedbackDict, let dataDict = actualDict[dataDictKey] as? NSDictionary, let feedbackDict = dataDict[feedbackDictKey] as? [String: Int] { println(fullFeedbackDict) println(feedbackDict) let tc = feedbackDict[typeCountKey] ?? 0 let tpc = feedbackDict[typeAndPositionKey] ?? 0 let feedback = Feedback(typeCount: tc, typeAndPositionCount: tpc, row: 0) // FIXME: BROKEN, NEED ROW self.feedbackCallback?(feedback) } } } private enum EngineState { case Online(Client) case Offline }
apache-2.0
0d998f05e27a72d517cb47dbc896efdc
33.06015
165
0.606536
4.579373
false
false
false
false
CosynPa/ViewModelProperty
ViewModelProperty/ViewModelProperty.swift
1
6638
// // ViewModelProperty.swift // ViewModelProperty // // Created by CosynPa on 5/24/16. // import Foundation import ReactiveSwift public enum CurrentOrUpdate<UpdateInfo> { case current case update(UpdateInfo) } public enum CurrentOrUpdateOrAction<UpdateInfo, ActionInfo> { case current case update(UpdateInfo) case action(ActionInfo) } public final class ViewModelProperty<Value, UpdateInfo, ActionInfo> { public let updateSignal: Signal<(Value, UpdateInfo), Never> private let updateObserver: Signal<(Value, UpdateInfo), Never>.Observer public let actionSignal: Signal<(Value, ActionInfo), Never> private let actionObserver: Signal<(Value, ActionInfo), Never>.Observer // MARK: - Derived signals /// Like updateSignal but send current value immediately public private(set) lazy var updateProducer: SignalProducer<(Value, CurrentOrUpdate<UpdateInfo>), Never> = { [unowned self] in return SignalProducer { observer, producerDisposable in observer.send(value: (self._value, .current)) producerDisposable += self.updateSignal.observeValues { (value, updateInfo) in observer.send(value: (value, .update(updateInfo))) } } }() /// Send current value immediately and send both updates and actions public private(set) lazy var allChangeProducer: SignalProducer<(Value, CurrentOrUpdateOrAction<UpdateInfo, ActionInfo>), Never> = { [unowned self] in return SignalProducer { observer, producerDisposable in observer.send(value: (self._value, .current)) producerDisposable += self.updateSignal.observeValues { (value, updateInfo) in observer.send(value: (value, .update(updateInfo))) } producerDisposable += self.actionSignal.observeValues { (value, actionInfo) in observer.send(value: (value, .action(actionInfo))) } } }() public private(set) lazy var noInfoUpdateSignal: Signal<Value, Never> = self.updateSignal.map { (value, _) in value } public private(set) lazy var noInfoActionSignal: Signal<Value, Never> = self.actionSignal.map { (value, _) in value } public private(set) lazy var noInfoUpdateProducer: SignalProducer<Value, Never> = self.updateProducer.map { (value, _) in value } public private(set) lazy var noInfoAllChangeProducer: SignalProducer<Value, Never> = self.allChangeProducer.map { (value, _) in value } // MARK: - private let lock: NSRecursiveLock private var _value: Value public var value: Value { get { return withValue { $0 } } } public init(_ initialValue: Value) { _value = initialValue lock = NSRecursiveLock() lock.name = "org.FU.ViewModelProperty" (updateSignal, updateObserver) = Signal.pipe() (actionSignal, actionObserver) = Signal.pipe() } /// Set the value by program update such as network callback. Returns the old value. @discardableResult public func setValueByUpdate(_ newValue: Value, info: UpdateInfo) -> Value { lock.lock() defer { lock.unlock() } let oldValue = _value _value = newValue updateObserver.send(value: (_value, info)) return oldValue } /// Set the value by user action, e.g. user edit a text field. Returns the old value. @discardableResult public func setValueByAction(_ newValue: Value, info: ActionInfo) -> Value { lock.lock() defer { lock.unlock() } let oldValue = _value _value = newValue actionObserver.send(value: (_value, info)) return oldValue } /// Atomically performs an arbitrary action using the current value of the /// variable. /// /// Returns the result of the action. public func withValue<Result>(action: (Value) throws -> Result) rethrows -> Result { lock.lock() defer { lock.unlock() } return try action(_value) } deinit { updateObserver.sendCompleted() actionObserver.sendCompleted() } } public struct NoInfo { public init() {} } public extension ViewModelProperty where UpdateInfo == NoInfo { func setValueByUpdate(_ newValue: Value) -> Value { return setValueByUpdate(newValue, info: NoInfo()) } } public extension ViewModelProperty where ActionInfo == NoInfo { func setValueByAction(_ newValue: Value) -> Value { return setValueByAction(newValue, info: NoInfo()) } } infix operator <+ : DefaultPrecedence infix operator +> : DefaultPrecedence // These two operators make the direction of data flow clearer. @discardableResult public func <+ <Value, UpdateInfo, ActionInfo>(property: ViewModelProperty<Value, UpdateInfo, ActionInfo>, valueAndInfo: (Value, UpdateInfo)) -> Value { return property.setValueByUpdate(valueAndInfo.0, info: valueAndInfo.1) } @discardableResult public func +> <Value, UpdateInfo, ActionInfo>(valueAndInfo: (Value, ActionInfo), property: ViewModelProperty<Value, UpdateInfo, ActionInfo>) -> Value { return property.setValueByAction(valueAndInfo.0, info: valueAndInfo.1) } @discardableResult public func <+ <Value, ActionInfo>(property: ViewModelProperty<Value, NoInfo, ActionInfo>, value: Value) -> Value { return property.setValueByUpdate(value, info: NoInfo()) } @discardableResult public func +> <Value, UpdateInfo>(value: Value, property: ViewModelProperty<Value, UpdateInfo, NoInfo>) -> Value { return property.setValueByAction(value, info: NoInfo()) } infix operator ?<+ : DefaultPrecedence infix operator +>? : DefaultPrecedence // These two operators are for optional properties @discardableResult public func ?<+ <Value, UpdateInfo, ActionInfo>(property: ViewModelProperty<Value, UpdateInfo, ActionInfo>?, valueAndInfo: (Value, UpdateInfo)) -> Value? { return property?.setValueByUpdate(valueAndInfo.0, info: valueAndInfo.1) } @discardableResult public func +>? <Value, UpdateInfo, ActionInfo>(valueAndInfo: (Value, ActionInfo), property: ViewModelProperty<Value, UpdateInfo, ActionInfo>?) -> Value? { return property?.setValueByAction(valueAndInfo.0, info: valueAndInfo.1) } @discardableResult public func ?<+ <Value, ActionInfo>(property: ViewModelProperty<Value, NoInfo, ActionInfo>?, value: Value) -> Value? { return property?.setValueByUpdate(value, info: NoInfo()) } @discardableResult public func +>? <Value, UpdateInfo>(value: Value, property: ViewModelProperty<Value, UpdateInfo, NoInfo>?) -> Value? { return property?.setValueByAction(value, info: NoInfo()) }
mit
e173045886d415a58d96b20b26c6ada7
34.308511
155
0.689967
4.263327
false
false
false
false
lennet/proNotes
app/proNotes/Model/DocumentLayer/DocumentLayer.swift
1
2199
// // DocumentLayer.swift // proNotes // // Created by Leo Thomas on 13/12/15. // Copyright © 2015 leonardthomas. All rights reserved. // import UIKit enum DocumentLayerType: Int { case pdf = 1 case sketch = 2 case image = 3 case text = 4 } class DocumentLayer: NSObject, NSCoding { private final let indexKey = "index" private final let hiddenKey = "key" private final let nameKey = "name" var index: Int var type: DocumentLayerType var name: String weak var docPage: DocumentPage! var hidden = false init(index: Int, type: DocumentLayerType, docPage: DocumentPage) { self.index = index self.type = type self.docPage = docPage self.name = String(describing: type) } init(fileWrapper: FileWrapper, index: Int, docPage: DocumentPage) { self.index = index self.type = .sketch self.docPage = docPage self.name = String(describing: type) } required init(coder aDecor: NSCoder) { fatalError("init(coder:type:) has not been implemented") } required init(coder aDecoder: NSCoder, type: DocumentLayerType) { self.index = aDecoder.decodeInteger(forKey: indexKey) self.name = (aDecoder.decodeObject(forKey: nameKey) as? String) ?? String(describing: type) self.hidden = aDecoder.decodeBool(forKey: hiddenKey) self.type = type } func encode(with aCoder: NSCoder) { aCoder.encode(index, forKey: indexKey) aCoder.encode(hidden, forKey: hiddenKey) aCoder.encode(name, forKey: nameKey) } func removeFromPage() { self.docPage.removeLayer(self) } func undoAction(_ oldObject: Any?) { // empty Base Implementation } override func isEqual(_ object: Any?) -> Bool { guard let layer = object as? DocumentLayer else { return false } guard layer.type == type else { return false } guard layer.index == index else { return false } guard layer.name == name else { return false } return layer.hidden == hidden } }
mit
717d415a25952eaac0e77f021f9efc3e
23.696629
99
0.60737
4.25969
false
false
false
false
BareFeetWare/BFWControls
BFWControls/Modules/NibReplaceable/View/NibCellView.swift
1
2175
// // NibCellView.swift // // Created by Tom Brodhurst-Hill on 18/03/2016. // Copyright © 2016 BareFeetWare. Free to use and modify, without warranty. // import UIKit open class NibCellView: NibView, TextLabelsGettable { // MARK: - IBOutlets @IBOutlet open weak var textLabel: UILabel? @IBOutlet open weak var detailTextLabel: UILabel? @IBOutlet open weak var iconView: UIView? @IBOutlet open weak var accessoryView: UIView? @IBOutlet open weak var separatorView: UIView? // MARK: - Variables and functions @IBInspectable open var text: String? { get { return textLabel?.text } set { textLabel?.text = newValue } } @IBInspectable open var detailText: String? { get { return detailTextLabel?.text } set { detailTextLabel?.text = newValue } } fileprivate var accessoryConstraints = [NSLayoutConstraint]() @IBInspectable open var showAccessory: Bool { get { return !(accessoryView?.isHidden ?? true) } set { guard let accessoryView = accessoryView else { return } accessoryView.isHidden = !newValue if newValue { NSLayoutConstraint.activate(accessoryConstraints) } else { if let siblingAndSuperviewConstraints = accessoryView.siblingAndSuperviewConstraints, !siblingAndSuperviewConstraints.isEmpty { accessoryConstraints = siblingAndSuperviewConstraints NSLayoutConstraint.deactivate(accessoryConstraints) } } } } // Deprecated. Use table view separators instead. @IBInspectable open var showSeparator: Bool { get { return !(separatorView?.isHidden ?? true) } set { separatorView?.isHidden = !newValue } } // MARK: - NibReplaceable open override var placeholderViews: [UIView] { return [textLabel, detailTextLabel].compactMap { $0 } } }
mit
34afa9af4078fba25d3a5ce2feb58585
26.871795
101
0.583257
5.503797
false
false
false
false
juzooda/photos
PhotoSearch/Photos/PhotosViewController.swift
1
3143
// // PhotoSearchViewController.swift // PhotoSearch // // Created by Rafael Oda on 28/10/2017. // Copyright © 2017 Rafael Oda. All rights reserved. // import UIKit import Kingfisher protocol PhotosViewProtocol: class { func update(dataSource: [PhotoModel]) func updateActivityIndicatorState(active: Bool) } class PhotosViewController: UIViewController, PhotosViewProtocol { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var collectionView: UICollectionView! var viewModel: PhotosViewModelProtocol! var dataSource = [PhotoModel]() //MARK: UIViewController Life Cycle override func viewDidLoad() { super.viewDidLoad() viewModel.fetchPhotos() } //MARK: View Model Updates func update(dataSource: [PhotoModel]) { self.dataSource = dataSource collectionView.reloadData() } func updateActivityIndicatorState(active: Bool) { active ? activityIndicator.startAnimating() : activityIndicator.stopAnimating() } //MARK: Transition Landscape/Portrait override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { collectionView.collectionViewLayout.invalidateLayout() super.viewWillTransition(to: size, with: coordinator) } } //MARK: - UICollectionViewDataSource extension PhotosViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCellId", for: indexPath) as! PhotoCollectionViewCell let model = dataSource[indexPath.row] item.imageView.setPhoto(model: model) return item } } //MARK: - UICollectionViewDelegateFlowLayout - Cell size calculation extension PhotosViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = collectionView.frame.width let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout let spacing = flowLayout?.minimumInteritemSpacing ?? 0 let availableSize = width - (spacing * 2) let verticeSize = availableSize/3.0 return CGSize(width: verticeSize, height: verticeSize) } } //MARK: - UIScrollViewDelegate - Fetch photos on the bottom. extension PhotosViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollViewContentHeight = scrollView.contentSize.height let scrollViewContentPositionY = scrollView.contentOffset.y + collectionView.bounds.size.height if scrollViewContentHeight == scrollViewContentPositionY { viewModel.fetchPhotos() } } }
apache-2.0
82fee9d352621570ec18cd225215e4a4
34.303371
160
0.732973
5.765138
false
false
false
false
ryuichis/swift-ast
Sources/AST/Expression/SequenceExpression.swift
2
3562
/* Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Source /* SequenceExpression stores a list of binary operations in a flat structure. There always be at least two binary operations in this structure. When there is only one operation, we simply return it directly instead of building it into this sequence. The operations in SequenceExpression should be folded into a tree structure after semantic analysis. Therefore, SequenceExpression should only exist in parsing results and/or when the sematic analysis is disabled intentionally. In other words, if a SequenceExpression survives even after an active semantic analysis, there must be an error in the sema process, thus, error needs to be reported. */ public class SequenceExpression : ASTNode, BinaryExpression { public enum Element { case expression(Expression) case assignmentOperator case binaryOperator(Operator) case ternaryConditionalOperator(Expression) case typeCheck(Type) case typeCast(Type) case typeConditionalCast(Type) case typeForcedCast(Type) } public let elements: [Element] override public var sourceRange: SourceRange { var startLocation: SourceLocation? if let firstElement = elements.first, case .expression(let firstExpr) = firstElement { startLocation = firstExpr.sourceRange.start } var endLocation: SourceLocation? if let lastElement = elements.last { switch lastElement { case .expression(let expr): endLocation = expr.sourceRange.end case .typeCheck(let type): endLocation = type.sourceRange.end case .typeCast(let type): endLocation = type.sourceRange.end case .typeConditionalCast(let type): endLocation = type.sourceRange.end case .typeForcedCast(let type): endLocation = type.sourceRange.end default: endLocation = nil } } guard let start = startLocation, let end = endLocation else { return .INVALID } return SourceRange(start: start, end: end) } public init(elements: [Element]) { self.elements = elements } // MARK: - ASTTextRepresentable override public var textDescription: String { return elements.map({ $0.textDescription }).joined(separator: " ") } } extension SequenceExpression.Element : ASTTextRepresentable { public var textDescription: String { switch self { case .expression(let expr): return expr.textDescription case .assignmentOperator: return "=" case .binaryOperator(let op): return op case .ternaryConditionalOperator(let expr): return "? \(expr.textDescription) :" case .typeCheck(let type): return "is \(type.textDescription)" case .typeCast(let type): return "as \(type.textDescription)" case .typeConditionalCast(let type): return "as? \(type.textDescription)" case .typeForcedCast(let type): return "as! \(type.textDescription)" } } }
apache-2.0
ebd016d4ec88270cf210f9ea4405d323
32.603774
90
0.718417
4.807018
false
false
false
false
e-how/kingTrader
kingTrader/Pods/CryptoSwift/CryptoSwift/HMAC.swift
20
2995
// // HMAC.swift // CryptoSwift // // Created by Marcin Krzyzanowski on 13/01/15. // Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved. // import Foundation final public class HMAC { public enum Variant { case sha1, sha256, sha384, sha512, md5 var size:Int { switch (self) { case .sha1: return SHA1(NSData()).size case .sha256: return SHA2.Variant.sha256.size case .sha384: return SHA2.Variant.sha384.size case .sha512: return SHA2.Variant.sha512.size case .md5: return MD5(NSData()).size } } func calculateHash(bytes bytes:[UInt8]) -> [UInt8]? { switch (self) { case .sha1: return NSData.withBytes(bytes).sha1()?.arrayOfBytes() case .sha256: return NSData.withBytes(bytes).sha256()?.arrayOfBytes() case .sha384: return NSData.withBytes(bytes).sha384()?.arrayOfBytes() case .sha512: return NSData.withBytes(bytes).sha512()?.arrayOfBytes() case .md5: return NSData.withBytes(bytes).md5()?.arrayOfBytes(); } } func blockSize() -> Int { switch self { case .md5, .sha1, .sha256: return 64 case .sha384, .sha512: return 128 } } } var key:[UInt8] let variant:Variant class internal func authenticate(key key: [UInt8], message: [UInt8], variant:HMAC.Variant = .md5) -> [UInt8]? { return HMAC(key, variant: variant)?.authenticate(message: message) } // MARK: - Private internal init? (_ key: [UInt8], variant:HMAC.Variant = .md5) { self.variant = variant self.key = key if (key.count > variant.blockSize()) { if let hash = variant.calculateHash(bytes: key) { self.key = hash } } if (key.count < variant.blockSize()) { // keys shorter than blocksize are zero-padded self.key = key + [UInt8](count: variant.blockSize() - key.count, repeatedValue: 0) } } internal func authenticate(message message:[UInt8]) -> [UInt8]? { var opad = [UInt8](count: variant.blockSize(), repeatedValue: 0x5c) for (idx, _) in key.enumerate() { opad[idx] = key[idx] ^ opad[idx] } var ipad = [UInt8](count: variant.blockSize(), repeatedValue: 0x36) for (idx, _) in key.enumerate() { ipad[idx] = key[idx] ^ ipad[idx] } var finalHash:[UInt8]? = nil; if let ipadAndMessageHash = variant.calculateHash(bytes: ipad + message) { finalHash = variant.calculateHash(bytes: opad + ipadAndMessageHash); } return finalHash } }
apache-2.0
8c54e50ceddeaac930302bbaa1e277d4
30.208333
116
0.522871
4.182961
false
false
false
false
MattCheetham/HarvestKit-Swift
HarvestKit-Shared/Company.swift
1
2833
// // Company.swift // HarvestKit // // Created by Matthew Cheetham on 16/01/2016. // Copyright © 2016 Matt Cheetham. All rights reserved. // import Foundation /** A struct representation of a company. Typiclaly returned from the API when querying about the current authenticated user */ public struct Company { /** Determines whether or not this company account is active */ public var active: Bool? /** The plan this buisiness is on. Determines how much their monthly payments are */ public var planType: String? /** Not documented in Harvest Documentation. Presumably the format that timers from this account should be displayed in. */ public var timeFormat: String? /** The URL that users must go to to access this harvest account */ public var baseURL: NSURL? /** The day that this company considers to be the beginning of the working week */ public var weekStartDay: String? /** An dictionary of objects determining what modules this company has enabled. This can determine which controllers you can use as some methods will return 404 where that feature is not enabled in the modules. Admins can configure modules. */ public var modules: [String: Bool]? /** The seperator that should be used for numbers over a thousand if any. Helps to localise figures where appropriate */ public var thousandsSeperator: String? /** The color scheme that the company has applied to their account in the website. You may use this to theme your application if you wish. */ public var colorScheme: String? /** The symbol that should be use to denote a decimal. Varies per company locale. */ public var decimalSymbol: String? /** The name of the company */ public var companyName: String? /** The time format used by the company. 12h or 24h for example. */ public var clockFormat: String? internal init(dictionary: [String: AnyObject]) { active = dictionary["active"] as? Bool planType = dictionary["plan_type"] as? String timeFormat = dictionary["time_format"] as? String if let baseURLString = dictionary["base_uri"] as? String { baseURL = NSURL(string: baseURLString) } weekStartDay = dictionary["week_start_day"] as? String modules = dictionary["modules"] as? [String: Bool] thousandsSeperator = dictionary["thousands_separator"] as? String colorScheme = dictionary["color_scheme"] as? String decimalSymbol = dictionary["decimal_symbol"] as? String companyName = dictionary["name"] as? String clockFormat = dictionary["clock"] as? String } }
mit
c2a9e5719ed585dda52ee50f49462ef0
30.131868
240
0.655367
4.791878
false
false
false
false
vojto/NiceKit
NiceKit/EditableOutlineView.swift
1
1119
// // TasksOutlineView.swift // NiceKit // // Created by Vojtech Rinik on 6/16/17. // Copyright © 2017 Vojtech Rinik. All rights reserved. // import Foundation import AppKit open class EditableOutlineView: NiceOutlineView { open var editedCellView: EditableTableCellView? open var isEditing: Bool { return editedCellView != nil } override open func mouseDown(with event: NSEvent) { let point = convert(event.locationInWindow, from: nil) let rowIndex = row(at: point) let columnIndex = column(at: point) let selectedIndex = selectedRow super.mouseDown(with: event) if isEditing { return } let finalPoint = convert(window!.mouseLocationOutsideOfEventStream, from: nil) // let finalRowIndex = row(at: finalPoint) let deltaX = abs(finalPoint.x - point.x) let deltaY = abs(finalPoint.y - point.y) if deltaX < 2, deltaY < 2, rowIndex == selectedIndex { edit(at: rowIndex, column: columnIndex) } } }
mit
23d4a1b7e0dc17e8d5b561a192d4d6d4
25
86
0.604651
4.544715
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/ViewControllers/DisplayViewController.swift
1
1257
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import IGListKit import UIKit final class DisplayViewController: UIViewController, ListAdapterDataSource { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() 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 [1, 2, 3, 4, 5, 6] as [NSNumber] } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { return DisplaySectionController() } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } }
mit
ea3c61fa6fe0dc80d019ae1912d2e829
28.928571
109
0.701671
5.2375
false
false
false
false
luannguyenkhoa/LNSideMenu
LNSideMenu/Classes/LNCommon.swift
1
5903
// // LNCommon.swift // LNSideMenuEffect // // Created by Luan Nguyen on 6/22/16. // Copyright © 2016 Luan Nguyen. All rights reserved. // import UIKit import ObjectiveC // MARK: Global variables internal let screenHeight = UIScreen.main.bounds.height internal let screenWidth = UIScreen.main.bounds.width internal var kNavBarHeight: CGFloat { return UIApplication.shared.statusBarFrame.size.height + ([.landscapeRight, .landscapeLeft].contains(UIApplication.shared.statusBarOrientation) ? 32 : 44) } internal let kDistanceItemToRight: CGFloat = 18 // MARK: Typealias internal typealias Completion = () -> () // MARK: Enums public enum Position { case right case left } public enum LNSideMenuAnimation { case none case `default` } public enum LNSize { case full case half case twothird case custom(CGFloat) public var width: CGFloat { switch self { case .full: return UIScreen.main.bounds.width case .twothird: return UIScreen.main.bounds.width * 2 / 3 case .half: return UIScreen.main.bounds.width / 2 case .custom(let width): return width } } } public enum LNColor { case highlight case title case bgItem case bgView public var color: UIColor { switch self { case .highlight: return .red case .title: return .black case .bgItem: return .white case .bgView: return .purple } } } // MARK: Protocols public protocol LNSideMenuProtocol { var menu: LNSideMenu?{get} var animationType: LNSideMenuAnimation {get set} func setContentViewController(_ contentViewController: UIViewController) } internal protocol LNSMDelegate: class { func didSelectItemAtIndex(SideMenu: LNSideMenuView, index: Int) } @objc public protocol LNSideMenuDelegate { @objc optional func sideMenuWillOpen() @objc optional func sideMenuWillClose() @objc optional func sideMenuDidOpen() @objc optional func sideMenuDidClose() @objc optional func sideMenuShouldOpenSideMenu () -> Bool func didSelectItemAtIndex(_ index: Int) } public protocol LNSideMenuManager { mutating func instance()-> LNSideMenuProtocol? mutating func toggleSideMenuView() mutating func hideSideMenuView() mutating func showSideMenuView() func fixSideMenuSize() } // MARK: Extensions var sideMenuMg: LNSideMenuManagement = LNSideMenuManagement() public extension UIViewController { // A protocol as a store property public var sideMenuManager: LNSideMenuManager? { get { sideMenuMg.viewController = self return sideMenuMg } set { } } // MARK: Navigation bar translucent style public func navigationBarTranslucentStyle() { navigationBarEffect |> true } public func navigationBarNonTranslecentStyle() { navigationBarEffect |> false } fileprivate func navigationBarEffect(_ translucent: Bool) { navigationController?.navigationBar.isTranslucent = translucent navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .top, barMetrics: .default) navigationController?.navigationBar.shadowImage = UIImage() } } // MARK: Operator overloading infix operator |>: AdditionPrecedence internal func |> <A>(arg: inout A, param: A) { arg = param } internal func |><A, B> (f: (A)->B, arg: A) -> B { return f(arg) } internal func |> <A, B, C> (f: @escaping (A)-> B, g: @escaping (B)->C) -> (A) -> C { return { g(f($0)) } } internal func |><A> (f: (A)->(), arg: A){ f(arg) } internal func |><A, B> (f: (A, B)->(), arg: (A, B)){ f(arg.0, arg.1) } internal func |><A, B, C> (f: (A, B, C)->(), arg: (A, B, C)){ f(arg.0, arg.1, arg.2) } internal func |><A, B, C, D> (f: (A, B, C, D)->(), arg: (A, B, C, D)){ f(arg.0, arg.1, arg.2, arg.3) } internal func |><A, B, C, D, E> (f: (A, B, C, D, E)->(), arg: (A, B, C, D, E)){ f(arg.0, arg.1, arg.2, arg.3, arg.4) } internal func |><A, B, C, D, E, F> (f: (A, B, C, D, E, F)->(), arg: (A, B, C, D, E, F)){ f(arg.0, arg.1, arg.2, arg.3, arg.4, arg.5) } internal func |><A, B, C, D, E, F, G> (f: (A, B, C, D, E, F, G)->(), arg: (A, B, C, D, E, F, G)){ f(arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6) } internal func |><A, B, C, D, E, F, G, H> (f: (A, B, C, D, E, F, G, H)->(), arg: (A, B, C, D, E, F, G, H)){ f(arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6, arg.7) } internal func |><A, B, C, D, E, F, G, H, I> (f: (A, B, C, D, E, F, G, H, I)->(), arg: (A, B, C, D, E, F, G, H, I)){ f(arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6, arg.7, arg.8) } internal func |><A, B, C, D, E, F, G, H, I, J> (f: (A, B, C, D, E, F, G, H, I, J)->(), arg: (A, B, C, D, E, F, G, H, I, J)){ f(arg.0, arg.1, arg.2, arg.3, arg.4, arg.5, arg.6, arg.7, arg.8, arg.9) } // A functional that handling mathematic method internal func inoutMath<A>(_ f: (_ lhs: inout A, _ rhs: A) -> (), _ fParam: inout A, _ sParam: A) { f(&fParam, sParam) } internal func compare<A>(_ f:(_ lhs: A, _ rhs: A) -> Bool, _ fp: inout A, _ sp: A) { fp = f(fp, sp) ? sp : fp } // Getting frame's components extension CGRect { var x: CGFloat { get { return self.origin.x } set { self.origin.x = newValue } } var y: CGFloat { get { return self.origin.y } set { self.origin.y = newValue } } var width: CGFloat { get { return self.size.width } set { self.size.width = newValue } } var height: CGFloat { get { return self.size.height } set { self.size.height = newValue } } } extension UIView { var x: CGFloat { get { return self.frame.x } set { self.frame.x = newValue } } var y: CGFloat { get { return self.frame.y } set { self.frame.y = newValue } } var width: CGFloat { get { return self.frame.width } set { self.frame.width = newValue } } var height: CGFloat { get { return self.frame.height } set { self.frame.height = newValue } } }
mit
bcb82ad5177cf8d6571384d86107dba0
23.089796
158
0.620976
3.07556
false
false
false
false
DerrickQin2853/SinaWeibo-Swift
SinaWeibo/SinaWeibo/Classes/View/Profile/ViewController/DQProfileViewController.swift
1
3016
// // DQProfileViewController.swift // SinaWeibo // // Created by admin on 16/9/22. // Copyright © 2016年 Derrick_Qin. All rights reserved. // import UIKit class DQProfileViewController: DQBaseTableViewController { override func viewDidLoad() { super.viewDidLoad() //设置游客界面信息 visitorLoginView.setPageInfo(tipText: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人", imageName: "visitordiscover_image_profile") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
8a3ff4cd857b3f779d0c5f7b594f5ec5
30.967391
136
0.66576
5.079447
false
false
false
false
BenEmdon/swift-algorithm-club
Graph/Graph/Vertex.swift
1
684
// // Vertex.swift // Graph // // Created by Andrew McKnight on 5/8/16. // import Foundation public struct Vertex<T where T: Equatable, T: Hashable>: Equatable { public var data: T public let index: Int } extension Vertex: CustomStringConvertible { public var description: String { get { return "\(index): \(data)" } } } extension Vertex: Hashable { public var hashValue: Int { get { return "\(data)\(index)".hashValue } } } public func ==<T: Equatable>(lhs: Vertex<T>, rhs: Vertex<T>) -> Bool { guard lhs.index == rhs.index else { return false } guard lhs.data == rhs.data else { return false } return true }
mit
748598008a6bf9885fabade4a5031e30
13.553191
70
0.615497
3.5625
false
false
false
false
jay18001/brickkit-ios
Source/Behaviors/SpotlightLayoutBehavior.swift
1
8334
// // SpotlightLayoutBehavior.swift // BrickKit // // Created by Ruben Cagnie on 6/4/16. // Copyright © 2016 Wayfair LLC. All rights reserved. // public protocol SpotlightLayoutBehaviorDataSource: class { func spotlightLayoutBehavior(_ behavior: SpotlightLayoutBehavior, smallHeightForItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> CGFloat? } open class SpotlightLayoutBehavior: BrickLayoutBehavior { weak var dataSource: SpotlightLayoutBehaviorDataSource? open var scrollLastBrickToTop = true open var lastBrickStretchy = false open var scrollAttributes: [BrickLayoutAttributes] = [] open var indexInSpotlight: Int = 0 open override var needsDownstreamCalculation: Bool { return true } open override func shouldUseForDownstreamCalculation(for indexPath: IndexPath, with identifier: String, for collectionViewLayout: UICollectionViewLayout) -> Bool { return dataSource?.spotlightLayoutBehavior(self, smallHeightForItemAtIndexPath: indexPath, withIdentifier: identifier, inCollectionViewLayout: collectionViewLayout) != nil } public init(dataSource: SpotlightLayoutBehaviorDataSource) { self.dataSource = dataSource } open override func resetRegisteredAttributes(_ collectionViewLayout: UICollectionViewLayout) { scrollAttributes = [] } open override func registerAttributes(_ attributes: BrickLayoutAttributes, for collectionViewLayout: UICollectionViewLayout) { if let _ = dataSource?.spotlightLayoutBehavior(self, smallHeightForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout) { scrollAttributes.append(attributes) } } open override func invalidateInCollectionViewLayout(_ collectionViewLayout: UICollectionViewLayout, contentSize: inout CGSize, attributesDidUpdate: (_ attributes: BrickLayoutAttributes, _ oldFrame: CGRect?) -> Void) { guard let collectionView = collectionViewLayout.collectionView, let firstAttribute = scrollAttributes.first, let dataSource = self.dataSource else { return } let topContentInset: CGFloat = collectionView.contentInset.top let offsetY: CGFloat = collectionView.contentOffset.y + topContentInset //Current scroll offset var previousAttributeWasInSpotlight: Bool = false var currentY: CGFloat = 0 //Current Y var sectionInset: CGFloat = 0 // removes extra space from the bottom collectionView.contentInset.bottom = 0 //Prevents crash, can't have last brick stretchy if only two bricks. if (lastBrickStretchy && scrollAttributes.count < 3) { lastBrickStretchy = false } let firstFrameOriginY: CGFloat = firstAttribute.originalFrame.origin.y for (index, attributes) in scrollAttributes.enumerated() { if let brickCollectionView = collectionView as? BrickCollectionView, let inset = brickCollectionView.layout.dataSource?.brickLayout(brickCollectionView.layout, insetFor: attributes.indexPath.section) { sectionInset = inset } let oldFrame = attributes.frame var originalFrameWithInsets = attributes.originalFrame originalFrameWithInsets?.size.height = attributes.originalFrame.size.height + sectionInset let isAbove = (originalFrameWithInsets?.maxY)! <= offsetY let isBelow = (originalFrameWithInsets?.minY)! > offsetY let firstSpotlightBrickBelowTopOfCollectionView = firstFrameOriginY >= offsetY let isInSpotlight = (!isAbove && !isBelow) || (offsetY < 0 && index == 0) || (firstSpotlightBrickBelowTopOfCollectionView && index == 0) // we can unwrap height safely because only bricks that are given a non nil height will be members of scroll attributes let height = dataSource.spotlightLayoutBehavior(self, smallHeightForItemAtIndexPath: attributes.indexPath, withIdentifier: attributes.identifier, inCollectionViewLayout: collectionViewLayout)! if isInSpotlight { var spotlightHeight = max(height, (originalFrameWithInsets?.maxY)! - offsetY) indexInSpotlight = index attributes.frame.origin.y = (originalFrameWithInsets?.maxY)! - spotlightHeight // Dont stretch if the top brick is not a spotlight brick if firstSpotlightBrickBelowTopOfCollectionView && firstFrameOriginY > 0 { spotlightHeight = (originalFrameWithInsets?.size.height)! attributes.frame.origin.y = (originalFrameWithInsets?.origin.y)! } attributes.frame.size.height = spotlightHeight } else if previousAttributeWasInSpotlight && !firstSpotlightBrickBelowTopOfCollectionView { //Allows for the last brick to stretch. if lastBrickStretchy && indexInSpotlight == (scrollAttributes.count - 2) { let spotlightHeight = (originalFrameWithInsets?.size.height)! - scrollAttributes[index-1].frame.size.height attributes.frame.origin.y = scrollAttributes[index-1].frame.maxY + sectionInset attributes.frame.size.height = (originalFrameWithInsets?.size.height)! + spotlightHeight } else { let ratio = ((originalFrameWithInsets?.minY)! - offsetY) / (originalFrameWithInsets?.size.height)! let leftOver = (originalFrameWithInsets?.size.height)! - height let inset = (sectionInset - (leftOver * (1-ratio))) attributes.frame.origin.y = currentY + (inset > 0 ? inset : 0) attributes.frame.size.height = height + (leftOver * (1-ratio)) } } else if isAbove { attributes.frame.origin.y = (originalFrameWithInsets?.maxY)! - height attributes.frame.size.height = height } else if isBelow { //Last brick now expands in height when second to last brick expands as well. if lastBrickStretchy && indexInSpotlight == (scrollAttributes.count - 3) { var previousOriginalFrameWithInsets = scrollAttributes[index - 1].originalFrame previousOriginalFrameWithInsets?.size.height = scrollAttributes[index - 1].originalFrame.size.height + sectionInset let ratio = ((previousOriginalFrameWithInsets?.minY)! - offsetY) / (originalFrameWithInsets?.size.height)! let leftOver = (originalFrameWithInsets?.size.height)! - height attributes.frame.origin.y = scrollAttributes[index - 1].frame.maxY + sectionInset attributes.frame.size.height = height + (leftOver * (1-ratio)) } else { attributes.frame.origin.y = currentY + sectionInset attributes.frame.size.height = height } } currentY = attributes.frame.maxY previousAttributeWasInSpotlight = isInSpotlight && offsetY >= 0 if attributes.frame != oldFrame { attributesDidUpdate(attributes, oldFrame) } } let lastAttribute = scrollAttributes.last! // We can safely unwrap, because we checked the count in the beginning of the function if let brickCollectionView = collectionView as? BrickCollectionView, let inset = brickCollectionView.layout.dataSource?.brickLayout(brickCollectionView.layout, insetFor: lastAttribute.indexPath.section) { sectionInset = inset } if scrollLastBrickToTop { contentSize.height = lastAttribute.originalFrame.minY + collectionView.frame.height + sectionInset } else if lastBrickStretchy { contentSize.height = lastAttribute.originalFrame.maxY } else { let firstHeight = scrollAttributes.first!.originalFrame.height // We can safely unwrap, because we checked the count in the beginning of the function contentSize.height = lastAttribute.originalFrame.maxY - firstHeight + sectionInset } } }
apache-2.0
414f93fb68f92111455a8d043e205134
54.18543
237
0.681507
5.428664
false
false
false
false
AjayOdedara/CoreKitTest
CoreKit/Pods/SwiftDate/Sources/SwiftDate/ISO8601Parser.swift
1
25986
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// This defines all possible errors you can encounter parsing ISO8601 string /// /// - eof: end of file /// - notDigit: expected digit, value cannot be parsed as int /// - notDouble: expected double digit, value cannot be parsed as double /// - invalid: invalid state reached. Something in the format is not correct public enum ISO8601ParserError: Error { case eof case notDigit case notDouble case invalid } // MARK: - Internal Extension for UnicodeScalar type internal extension UnicodeScalar { /// return `true` if current character is a digit (arabic), `false` otherwise var isDigit: Bool { return "0"..."9" ~= self } /// return `true` if current character is a space var isSpace: Bool { return CharacterSet.whitespaces.contains(self) } } // MARK: - Internal Extension for Int type internal extension Int { /// Return `true` if current year is a leap year, `false` otherwise var isLeapYear: Bool { return ((self % 4) == 0) && (((self % 100) != 0) || ((self % 400) == 0)) } } /// Parser configuration /// This configuration can be used to define custom behaviour of the parser itself. public struct ISO8601Configuration { /// Time separator character. By default is `:`. var time_separator: ISO8601Parser.ISOChar = ":" /// Strict parsing. By default is `false`. var strict: Bool = false /// Calendar used to generate the date. By default is the current system calendar var calendar: Calendar = Calendar.current init(strict: Bool = false, calendar: Calendar? = nil) { self.strict = strict self.calendar = calendar ?? Calendar.current } } /// Internal structure internal enum Weekday: Int { case monday = 0 case tuesday = 1 case wednesday = 2 case thursday = 3 } /// This is the ISO8601 Parser class: it evaluates automatically the format of the ISO8601 date /// and attempt to parse it in a valid `Date` object. /// Resulting date also includes Time Zone settings and a property which allows you to inspect /// single date components. /// /// This work is inspired to the original ISO8601DateFormatter class written in ObjC by /// Peter Hosey (available here https://bitbucket.org/boredzo/iso-8601-parser-unparser). /// I've made a Swift porting and fixed some issues when parsing several ISO8601 date variants. public class ISO8601Parser { /// Some typealias to make the code cleaner public typealias ISOString = String.UnicodeScalarView public typealias ISOIndex = String.UnicodeScalarView.Index public typealias ISOChar = UnicodeScalar public typealias ISOParsedDate = (date: Date?, timezone: TimeZone?) /// This represent the internal parser status representation public struct ParsedDate { /// Type of date parsed /// /// - monthAndDate: month and date style /// - week: date with week number /// - dateOnly: date only public enum DateStyle { case monthAndDate case week case dateOnly } /// Parsed year value var year: Int = 0 /// Parsed month or week number var month_or_week: Int = 0 /// Parsed day value var day: Int = 0 /// Parsed hour value var hour: Int = 0 /// Parsed minutes value var minute: TimeInterval = 0.0 /// Parsed seconds value var seconds: TimeInterval = 0.0 /// Parsed weekday number (1=monday, 7=sunday) /// If `nil` source string has not specs about weekday. var weekday: Int? = nil /// Timezone parsed hour value var tz_hour: Int = 0 /// Timezone parsed minute value var tz_minute: Int = 0 /// Type of parsed date var type: DateStyle = .monthAndDate /// Parsed timezone object var timezone: TimeZone? } /// Source raw parsed values private var date: ParsedDate = ParsedDate() /// Source string represented as unicode scalars private let string: ISOString /// Current position of the parser in source string. /// Initially is equal to `string.startIndex` private var cIdx: ISOIndex /// Just a shortcut to the last index in source string private var eIdx: ISOIndex /// Lenght of the string private var length: Int /// Number of hyphens characters found before any value /// Consequential "-" are used to define implicit values in dates. private var hyphens: Int = 0 /// Private date components used for default values private var now_cmps: DateComponents /// Configuration used for parser private var cfg: ISO8601Configuration /// Date components parsed private(set) var date_components: DateComponents? /// Parsed date private(set) var parsedDate: Date? /// Parsed timezone private(set) var parsedTimeZone: TimeZone? /// Date adjusted at parsed timezone private var dateInTimezone: Date? { get { self.cfg.calendar.timeZone = date.timezone ?? TimeZone(identifier: "UTC")! return self.cfg.calendar.date(from: self.date_components!) } } /// Formatter used to transform a date to a valid ISO8601 string private(set) var formatter: DateFormatter = DateFormatter() /// Initialize a new parser with a source ISO8601 string to parse /// Parsing is done during initialization; any exception is reported /// before allocating. /// /// - Parameters: /// - src: source ISO8601 string /// - config: configuration used for parsing /// - Throws: throw an `ISO8601Error` if parsing operation fails public init?(_ src: String, config: ISO8601Configuration = ISO8601Configuration()) { let src_trimmed = src.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) guard src_trimmed.characters.count > 0 else { return nil } self.string = src_trimmed.unicodeScalars self.length = src_trimmed.characters.count self.cIdx = string.startIndex self.eIdx = string.endIndex self.cfg = config self.now_cmps = cfg.calendar.dateComponents([.year,.month,.day], from: Date()) var idx = self.cIdx while idx < self.eIdx { if string[idx] == "-" { hyphens += 1 } else { break } idx = string.index(after: idx) } do { try self.parse() } catch { return nil } } /// Return a date parsed from a valid ISO8601 string /// /// - Parameter string: source string /// - Returns: a valid `Date` object or `nil` if date cannot be parsed public static func date(from string: String) -> ISOParsedDate? { guard let parser = ISO8601Parser(string) else { return nil } return (parser.parsedDate,parser.parsedTimeZone) } //MARK: - Internal Parser /// Private parsing function /// /// - Throws: throw an `ISO8601Error` if parsing operation fails @discardableResult private func parse() throws -> ISOParsedDate { // PARSE DATE if current() == "T" { // There is no date here, only a time. // Set the date to now; then we'll parse the time. next() guard current().isDigit else { throw ISO8601ParserError.invalid } date.year = now_cmps.year! date.month_or_week = now_cmps.month! date.day = now_cmps.day! } else { moveUntil(is: "-") let is_time_only = (string.contains("T") == false && string.contains(":") && !string.contains("-")) if is_time_only == false { var (num_digits,segment) = try read_int() switch num_digits { case 0: try parse_digits_0(num_digits, &segment) case 8: try parse_digits_8(num_digits, &segment) case 6: try parse_digits_6(num_digits, &segment) case 4: try parse_digits_4(num_digits, &segment) case 1: try parse_digits_1(num_digits, &segment) case 2: try parse_digits_2(num_digits, &segment) case 7: try parse_digits_7(num_digits, &segment) //YYYY DDD (ordinal date) case 3: try parse_digits_3(num_digits, &segment) //--DDD (ordinal date, implicit year) default: throw ISO8601ParserError.invalid } } else { date.year = now_cmps.year! date.month_or_week = now_cmps.month! date.day = now_cmps.day! } } var hasTime = false if current().isSpace || current() == "T" { hasTime = true next() } // PARSE TIME if current().isDigit == true { let time_sep = cfg.time_separator let hasTimeSeparator = string.contains(time_sep) date.hour = try read_int(2).value if hasTimeSeparator == false && hasTime{ date.minute = TimeInterval(try read_int(2).value) } else if current() == time_sep { next() if time_sep == "," || time_sep == "." { //We can't do fractional minutes when '.' is the segment separator. //Only allow whole minutes and whole seconds. date.minute = TimeInterval(try read_int(2).value) if current() == time_sep { next() date.seconds = TimeInterval(try read_int(2).value) } } else { //Allow a fractional minute. //If we don't get a fraction, look for a seconds segment. //Otherwise, the fraction of a minute is the seconds. date.minute = try read_double().value if current() != ":" { var int_part: Double = 0.0 var frac_part: Double = 0.0 frac_part = modf(date.minute, &int_part) date.minute = int_part date.seconds = frac_part if date.seconds > Double.ulpOfOne { // Convert fraction (e.g. .5) into seconds (e.g. 30). date.seconds = date.seconds * 60 } else if current() == time_sep { next() date.seconds = try read_double().value } } else { // fractional minutes next() date.seconds = try read_double().value } } } if cfg.strict == false { if current().isSpace == true { next() } } switch current() { case "Z": date.timezone = TimeZone(abbreviation: "UTC") case "+","-": let is_negative = current() == "-" next() if current().isDigit == true { //Read hour offset. date.tz_hour = try read_int(2).value if is_negative == true { date.tz_hour = -date.tz_hour } // Optional separator if current() == time_sep { next() } if current().isDigit { // Read minute offset date.tz_minute = try read_int(2).value if is_negative == true { date.tz_minute = -date.tz_minute } } let timezone_offset = (date.tz_hour * 3600) + (date.tz_minute * 60) date.timezone = TimeZone(secondsFromGMT: timezone_offset) } default: break } } self.date_components = DateComponents() self.date_components!.year = date.year self.date_components!.day = date.day self.date_components!.hour = date.hour self.date_components!.minute = Int(date.minute) self.date_components!.second = Int(date.seconds) switch date.type { case .monthAndDate: self.date_components!.month = date.month_or_week case .week: //Adapted from <http://personal.ecu.edu/mccartyr/ISOwdALG.txt>. //This works by converting the week date into an ordinal date, then letting the next case handle it. let prevYear = date.year - 1 let YY = prevYear % 100 let C = prevYear - YY let G = YY + YY / 4 let isLeapYear = (((C / 100) % 4) * 5) let Jan1Weekday = ((isLeapYear + G) % 7) var day = ((8 - Jan1Weekday) + (7 * (Jan1Weekday > Weekday.thursday.rawValue ? 1 : 0))) day += (date.day - 1) + (7 * (date.month_or_week - 2)) if let weekday = date.weekday { //self.date_components!.weekday = weekday self.date_components!.day = day + weekday } else { self.date_components!.day = day } case .dateOnly: //An "ordinal date". break } //self.cfg.calendar.timeZone = date.timezone ?? TimeZone(identifier: "UTC")! //self.parsedDate = self.cfg.calendar.date(from: self.date_components!) let tz = date.timezone ?? TimeZone(identifier: "UTC")! self.parsedTimeZone = tz self.cfg.calendar.timeZone = tz self.parsedDate = self.cfg.calendar.date(from: self.date_components!) return (self.parsedDate,self.parsedTimeZone) } private func parse_digits_3(_ num_digits: Int, _ segment: inout Int) throws { //Technically, the standard only allows one hyphen. But it says that two hyphens is the logical implementation, and one was dropped for brevity. So I have chosen to allow the missing hyphen. if hyphens < 1 || (hyphens > 2 && cfg.strict == false) { throw ISO8601ParserError.invalid } date.day = segment date.year = now_cmps.year! date.type = .dateOnly if cfg.strict == true && (date.day > (365 + (date.year.isLeapYear ? 1 : 0))) { throw ISO8601ParserError.invalid } } private func parse_digits_7(_ num_digits: Int, _ segment: inout Int) throws { guard hyphens == 0 else { throw ISO8601ParserError.invalid } date.day = segment % 1000 date.year = segment / 1000 date.type = .dateOnly if cfg.strict == true && (date.day > (365 + (date.year.isLeapYear ? 1 : 0))) { throw ISO8601ParserError.invalid } } private func parse_digits_2(_ num_digits: Int, _ segment: inout Int) throws { func parse_hyphens_3(_ num_digits: Int, _ segment: inout Int) throws { date.year = now_cmps.year! date.month_or_week = now_cmps.month! date.day = segment } func parse_hyphens_2(_ num_digits: Int, _ segment: inout Int) throws { date.year = now_cmps.year! date.month_or_week = segment if current() == "-" { next() date.day = try read_int(2).value } else { date.day = 1 } } func parse_hyphens_1(_ num_digits: Int, _ segment: inout Int) throws { let current_year = now_cmps.year! let current_century = (current_year % 100) date.year = segment + (current_year - current_century) if num_digits == 1 { // implied decade date.year += current_century - (current_year % 10) } if current() == "-" { next() if current() == "W" { next() date.type = .week } date.month_or_week = try read_int(2).value if current() == "-" { next() if date.type == .week { // weekday number let weekday = try read_int().value if weekday > 7 { throw ISO8601ParserError.invalid } date.weekday = weekday } else { date.day = try read_int().value if date.day == 0 { date.day = 1 } if date.month_or_week == 0 { date.month_or_week = 1 } } } else { date.day = 1 } } else { date.month_or_week = 1 date.day = 1 } } func parse_hyphens_0(_ num_digits: Int, _ segment: inout Int) throws { if current() == "-" { // Implicit century date.year = now_cmps.year! date.year -= (date.year % 100) date.year += segment next() if current() == "W" { try parseWeekAndDay() } else if current().isDigit == false { try centuryOnly(&segment) } else { // Get month and/or date. let (v_count,v_seg) = try read_int() switch v_count { case 4: // YY-MMDD date.day = v_seg % 100 date.month_or_week = v_seg / 100 case 1: // YY-M; YY-M-DD (extension) if cfg.strict == true { throw ISO8601ParserError.invalid } case 2: // YY-MM; YY-MM-DD date.month_or_week = v_seg if current() == "-" { next() if current().isDigit == true { date.day = try read_int(2).value } else { date.day = 1 } } else { date.day = 1 } case 3: // Ordinal date date.day = v_seg date.type = .dateOnly default: break } } } else if current() == "W" { date.year = now_cmps.year! date.year -= (date.year % 100) date.year += segment try parseWeekAndDay() } else { try centuryOnly(&segment) } } switch hyphens { case 0: try parse_hyphens_0(num_digits, &segment) case 1: try parse_hyphens_1(num_digits, &segment) //-YY; -YY-MM (implicit century) case 2: try parse_hyphens_2(num_digits, &segment) //--MM; --MM-DD case 3: try parse_hyphens_3(num_digits, &segment) //---DD default: throw ISO8601ParserError.invalid } } private func parse_digits_1(_ num_digits: Int, _ segment: inout Int) throws { if cfg.strict == true { // Two digits only - never just one. guard hyphens == 1 else { throw ISO8601ParserError.invalid } if current() == "-" { next() } next() guard current() == "W" else { throw ISO8601ParserError.invalid } date.year = now_cmps.year! date.year -= (date.year % 10) date.year += segment } else { try parse_digits_2(num_digits, &segment) } } private func parse_digits_4(_ num_digits: Int, _ segment: inout Int) throws { func parse_hyphens_0(_ num_digits: Int, _ segment: inout Int) throws { date.year = segment if current() == "-" { next() } if current().isDigit == false { if current() == "W" { try parseWeekAndDay() } else { date.month_or_week = 1 date.day = 1 } } else { let (v_num,v_seg) = try read_int() switch v_num { case 4: // MMDD date.day = v_seg % 100 date.month_or_week = v_seg / 100 case 2: // MM date.month_or_week = v_seg if current() == "-" { next() } if current().isDigit == false { date.day = 1 } else { date.day = try read_int().value } case 3: // DDD date.day = v_seg % 1000 date.type = .dateOnly if cfg.strict == true && (date.day > 365 + (date.year.isLeapYear ? 1 : 0)) { throw ISO8601ParserError.invalid } default: throw ISO8601ParserError.invalid } } } func parse_hyphens_1(_ num_digits: Int, _ segment: inout Int) throws { date.month_or_week = segment % 100 date.year = segment / 100 if current() == "-" { next() } if current().isDigit == false { date.day = 1 } else { date.day = try read_int().value } } func parse_hyphens_2(_ num_digits: Int, _ segment: inout Int) throws { date.day = segment % 100 date.month_or_week = segment / 100 date.year = now_cmps.year! } switch hyphens { case 0: try parse_hyphens_0(num_digits, &segment) // YYYY case 1: try parse_hyphens_1(num_digits, &segment) // YYMM case 2: try parse_hyphens_2(num_digits, &segment) // MMDD default: throw ISO8601ParserError.invalid } } private func parse_digits_6(_ num_digits: Int, _ segment: inout Int) throws { // YYMMDD (implicit century) guard hyphens == 0 else { throw ISO8601ParserError.invalid } date.day = segment % 100 segment /= 100 date.month_or_week = segment % 100 date.year = now_cmps.year! date.year -= (date.year % 100) date.year += (segment / 100) } private func parse_digits_8(_ num_digits: Int, _ segment: inout Int) throws { // YYYY MM DD guard hyphens == 0 else { throw ISO8601ParserError.invalid } date.day = segment % 100 segment /= 100 date.month_or_week = segment % 100 date.year = segment / 100 } private func parse_digits_0(_ num_digits: Int, _ segment: inout Int) throws { guard current() == "W" else { throw ISO8601ParserError.invalid } if seek(1) == "-" && isDigit(seek(2)) && ((hyphens == 1 || hyphens == 2) && cfg.strict == false) { date.year = now_cmps.year! date.month_or_week = 1 next(2) try parseDayAfterWeek() } else if hyphens == 1 { date.year = now_cmps.year! if current() == "W" { next() date.month_or_week = try read_int(2).value date.type = .week try parseWeekday() } else { try parseDayAfterWeek() } } else { throw ISO8601ParserError.invalid } } private func parseWeekday() throws { if current() == "-" { next() } let weekday = try read_int().value if weekday > 7 { throw ISO8601ParserError.invalid } date.type = .week date.weekday = weekday } private func parseWeekAndDay() throws { next() if current().isDigit == false { //Not really a week-based date; just a year followed by '-W'. guard cfg.strict == false else { throw ISO8601ParserError.invalid } date.month_or_week = 1 date.day = 1 } else { date.month_or_week = try read_int(2).value try parseWeekday() } } private func parseDayAfterWeek() throws { date.day = current().isDigit == true ? try read_int(2).value : 1 date.type = .week } private func centuryOnly(_ segment: inout Int) throws { date.year = segment * 100 + now_cmps.year! % 100 date.month_or_week = 1 date.day = 1 } /// Return `true` if given character is a char /// /// - Parameter char: char to evaluate /// - Returns: `true` if char is a digit, `false` otherwise private func isDigit(_ char: UnicodeScalar?) -> Bool { guard let char = char else { return false } return char.isDigit } /// MARK: - Scanner internal functions /// Get the value at specified offset from current scanner position without /// moving the current scanner's index. /// /// - Parameter offset: offset to move /// - Returns: char at given position, `nil` if not found @discardableResult public func seek(_ offset: Int = 1) -> ISOChar? { let move_idx = string.index(cIdx, offsetBy: offset) guard move_idx < eIdx else { return nil } return string[move_idx] } /// Return the char at the current position of the scanner /// /// - Parameter next: if `true` return the current char and move to the next position /// - Returns: the char sat the current position of the scanner @discardableResult public func current(_ next: Bool = false) -> ISOChar { let current = string[cIdx] if next == true { cIdx = string.index(after: cIdx) } return current } /// Move by `offset` characters the index of the scanner and return the char at the current /// position. If EOF is reached `nil` is returned. /// /// - Parameter offset: offset value (use negative number to move backwards) /// - Returns: character at the current position. @discardableResult private func next(_ offset: Int = 1) -> ISOChar? { let next = string.index(cIdx, offsetBy: offset) guard next < eIdx else { return nil } cIdx = next return string[cIdx] } /// Read from the current scanner index and parse the value as Int. /// /// - Parameter max_count: number of characters to move. If nil scanners continues until a non /// digit value is encountered. /// - Returns: parsed value /// - Throws: throw an exception if parser fails @discardableResult private func read_int(_ max_count: Int? = nil) throws -> (count: Int, value: Int) { var move_idx = cIdx var count = 0 while move_idx < eIdx { if let max = max_count, count >= max { break } if string[move_idx].isDigit == false { break } count += 1 move_idx = string.index(after: move_idx) } let raw_value = String(string[cIdx..<move_idx]) if raw_value == "" { return (count,0) } guard let value = Int(raw_value) else { throw ISO8601ParserError.notDigit } cIdx = move_idx return (count, value) } /// Read from the current scanner index and parse the value as Double. /// If parser fails an exception is throw. /// Unit separator can be `-` or `,`. /// /// - Returns: double value /// - Throws: throw an exception if parser fails @discardableResult private func read_double() throws -> (count: Int, value: Double) { var move_idx = cIdx var count = 0 var fractional_start = false while move_idx < eIdx { let char = string[move_idx] if char == "." || char == "," { if fractional_start == true { throw ISO8601ParserError.notDouble } else { fractional_start = true } } else { if char.isDigit == false { break } } count += 1 move_idx = string.index(after: move_idx) } let raw_value = String(string[cIdx..<move_idx]).replacingOccurrences(of: ",", with: ".") if raw_value == "" { return (count,0.0) } guard let value = Double(raw_value) else { throw ISO8601ParserError.notDouble } cIdx = move_idx return (count,value) } /// Move the current scanner index to the next position until the current char of the scanner /// is the given `char` value. /// /// - Parameter char: char /// - Returns: the number of characters passed @discardableResult private func moveUntil(is char: UnicodeScalar) -> Int { var move_idx = cIdx var count = 0 while move_idx < eIdx { guard string[move_idx] == char else { break } move_idx = string.index(after: move_idx) count += 1 } cIdx = move_idx return count } /// Move the current scanner index to the next position until passed `char` value is /// encountered or `eof` is reached. /// /// - Parameter char: char /// - Returns: the number of characters passed @discardableResult private func moveUntil(isNot char: UnicodeScalar) -> Int { var move_idx = cIdx var count = 0 while move_idx < eIdx { guard string[move_idx] != char else { break } move_idx = string.index(after: move_idx) count += 1 } cIdx = move_idx return count } }
mit
25680939b452356aa00c1ce6c764e24a
27.032362
192
0.640037
3.306107
false
false
false
false
jessegrosjean/BirchOutline
Common/Sources/OutlineType.swift
1
7238
// // OutlineType.swift // Birch // // Created by Jesse Grosjean on 6/14/16. // Copyright © 2016 Jesse Grosjean. All rights reserved. // import Foundation import JavaScriptCore public protocol OutlineType: AnyObject { var jsOutline: JSValue { get } var root: ItemType { get } var items: [ItemType] { get } func itemForID(_ id: String) -> ItemType? func evaluateItemPath(_ path: String) -> [ItemType] func createItem(_ text: String) -> ItemType func cloneItem(_ item: ItemType, deep: Bool) -> ItemType func cloneItems(_ items: [ItemType], deep: Bool) -> [ItemType] func groupUndo(_ callback: @escaping () -> Void) func groupChanges(_ callback: @escaping () -> Void) var changed: Bool { get } func updateChangeCount(_ changeKind: ChangeKind) func onDidUpdateChangeCount(_ callback: @escaping (_ changeKind: ChangeKind) -> Void) -> DisposableType func onDidChange(_ callback: @escaping (_ mutation: MutationType) -> Void) -> DisposableType func onDidEndChanges(_ callback: @escaping (_ mutations: [MutationType]) -> Void) -> DisposableType func undo() func redo() var serializedMetadata: String { get set } func serializeItems(_ items: [ItemType], options: [String : Any]?) -> String func deserializeItems(_ serializedItems: String, options: [String : Any]?) -> [ItemType]? func serialize(_ options: [String: Any]?) -> String func reloadSerialization(_ serialization: String, options: [String: Any]?) var retainCount: Int { get } } public enum ChangeKind { case done case undone case redone case cleared public init?(string: String) { switch string { case "Done": self = .done case "Undone": self = .undone case "Redone": self = .redone case "Cleared": self = .cleared default: return nil } } public func toString() -> String { switch self { case .done: return "Done" case .undone: return "Undone" case .redone: return "Redone" case .cleared: return "Cleared" } } } open class Outline: OutlineType { open var jsOutline: JSValue public init(jsOutline: JSValue) { self.jsOutline = jsOutline } open var root: ItemType { return jsOutline.forProperty("root") } open var items: [ItemType] { return jsOutline.forProperty("items").toItemTypeArray() } open func itemForID(_ id: String) -> ItemType? { return jsOutline.invokeMethod("getItemForID", withArguments: [id]).selfOrNil() } open func evaluateItemPath(_ path: String) -> [ItemType] { return jsOutline.invokeMethod("evaluateItemPath", withArguments: [path]).toItemTypeArray() } open func createItem(_ text: String) -> ItemType { return jsOutline.invokeMethod("createItem", withArguments: [text]) } open func cloneItem(_ item: ItemType, deep: Bool = true) -> ItemType { return jsOutline.invokeMethod("cloneItem", withArguments: [item, deep]) } open func cloneItems(_ items: [ItemType], deep: Bool = true) -> [ItemType] { let jsItems = JSValue.fromItemTypeArray(items, context: jsOutline.context) let jsItemsClone = jsOutline.invokeMethod("cloneItems", withArguments: [jsItems, deep]) return jsItemsClone!.toItemTypeArray() } public func groupUndo(_ callback: @escaping () -> Void) { let callbackWrapper: @convention(block) () -> Void = { callback() } jsOutline.invokeMethod("groupUndo", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } public func groupChanges(_ callback: @escaping () -> Void) { let callbackWrapper: @convention(block) () -> Void = { callback() } jsOutline.invokeMethod("groupChanges", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open var changed: Bool { return jsOutline.forProperty("isChanged").toBool() } open func updateChangeCount(_ changeKind: ChangeKind) { jsOutline.invokeMethod("updateChangeCount", withArguments: [changeKind.toString()]) } open func onDidUpdateChangeCount(_ callback: @escaping (_ changeKind: ChangeKind) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ changeKindString: String) -> Void = { changeKindString in callback(ChangeKind(string: changeKindString)!) } return jsOutline.invokeMethod("onDidUpdateChangeCount", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func onDidChange(_ callback: @escaping (_ mutation: MutationType) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ mutation: JSValue) -> Void = { mutation in callback(Mutation(jsMutation: mutation)) } return jsOutline.invokeMethod("onDidChange", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func onDidEndChanges(_ callback: @escaping (_ mutations: [MutationType]) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ mutation: JSValue) -> Void = { jsMutations in let length = Int((jsMutations.forProperty("length").toInt32())) var mutations = [Mutation]() for i in 0..<length { mutations.append(Mutation(jsMutation: jsMutations.atIndex(i))) } callback(mutations) } return jsOutline.invokeMethod("onDidEndChanges", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func undo() { jsOutline.invokeMethod("undo", withArguments: []) } open func redo() { jsOutline.invokeMethod("redo", withArguments: []) } public var serializedMetadata: String { get { return jsOutline.forProperty("serializedMetadata").toString() } set { jsOutline.setValue(newValue, forProperty: "serializedMetadata") } } open func serializeItems(_ items: [ItemType], options: [String : Any]?) -> String { let mapped: [Any] = items.map { $0 } return jsOutline.invokeMethod("serializeItems", withArguments: [mapped, options ?? [:]]).toString() } open func deserializeItems(_ serializedItems: String, options: [String : Any]?) -> [ItemType]? { return jsOutline.invokeMethod("deserializeItems", withArguments: [serializedItems, options ?? [:]]).toItemTypeArray() } open func serialize(_ options:[String: Any]?) -> String { return jsOutline.invokeMethod("serialize", withArguments: [options ?? [:]]).toString() } open func reloadSerialization(_ serialization: String, options: [String: Any]?) { jsOutline.invokeMethod("reloadSerialization", withArguments: [serialization, options ?? [:]]) } open var retainCount: Int { return Int(jsOutline.forProperty("retainCount").toInt32()) } }
mit
428fff6b8db8900063d17f80d4c8c011
33.626794
132
0.625121
4.571699
false
false
false
false
storehouse/Advance
Samples/SampleApp-iOS/Sources/SpringConfigurationView.swift
1
4333
import Foundation import UIKit protocol SpringConfigurationViewDelegate: class { func springConfigurationViewDidChange(_ view: SpringConfigurationView) } class SpringConfigurationView: UIView { weak var delegate: SpringConfigurationViewDelegate? = nil var tension: CGFloat { get { return CGFloat(tensionSlider.slider.value) } set { tensionSlider.slider.value = Float(newValue) } } var damping: CGFloat { get { return CGFloat(dampingSlider.slider.value) } set { dampingSlider.slider.value = Float(newValue) } } fileprivate let tensionSlider = LabeledSliderView() fileprivate let dampingSlider = LabeledSliderView() override init(frame: CGRect) { super.init(frame: frame) addSubview(tensionSlider) addSubview(dampingSlider) tensionSlider.slider.addTarget(self, action: #selector(changed), for: .valueChanged) dampingSlider.slider.addTarget(self, action: #selector(changed), for: .valueChanged) tensionSlider.slider.minimumValue = 1.0 tensionSlider.slider.maximumValue = 400.0 dampingSlider.slider.minimumValue = 0.1 dampingSlider.slider.maximumValue = 80.0 tensionSlider.slider.value = 120.0 dampingSlider.slider.value = 10.0 tensionSlider.text = "Tension" dampingSlider.text = "Damping" } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func sizeThatFits(_ size: CGSize) -> CGSize { var s = CGSize.zero s.width = size.width s.height += tensionSlider.sizeThatFits(size).height s.height += dampingSlider.sizeThatFits(size).height return s } override func layoutSubviews() { super.layoutSubviews() var tensionSize = tensionSlider.sizeThatFits(bounds.size) tensionSize.width = bounds.width tensionSlider.frame = CGRect(origin: CGPoint.zero, size: tensionSize) var dampingSize = dampingSlider.sizeThatFits(bounds.size) dampingSize.width = bounds.width dampingSlider.frame = CGRect(x: 0.0, y: tensionSlider.frame.maxY, width: bounds.width, height: dampingSize.height) } @objc fileprivate dynamic func changed() { delegate?.springConfigurationViewDidChange(self) } } private class LabeledSliderView: UIView { var labelWidth: CGFloat = 90.0 { didSet { setNeedsLayout() } } var gutterWidth: CGFloat = 20.0 { didSet { setNeedsLayout() } } var sideMargin: CGFloat = 12.0 { didSet { setNeedsLayout() } } var text: String { get { return label.text ?? "" } set { label.text = newValue } } fileprivate let label: UILabel fileprivate let slider: UISlider override init(frame: CGRect) { label = UILabel() slider = UISlider() super.init(frame: frame) slider.minimumTrackTintColor = UIColor(red: 0.0, green: 196.0/255.0, blue: 1.0, alpha: 1.0) label.text = "Untitled" label.textColor = UIColor.darkGray addSubview(label) addSubview(slider) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate override func sizeThatFits(_ size: CGSize) -> CGSize { var s = size s.height = 44.0 return s } fileprivate override func layoutSubviews() { super.layoutSubviews() var labelSize = label.sizeThatFits(bounds.size) labelSize.width = min(labelSize.width, labelWidth) label.bounds = CGRect(origin: CGPoint.zero, size: labelSize) label.center = CGPoint(x: sideMargin + labelSize.width/2.0, y: bounds.midY) var sliderFrame = CGRect.zero sliderFrame.size.height = slider.sizeThatFits(bounds.size).height sliderFrame.size.width = bounds.width - (sideMargin * 2.0) - labelWidth - gutterWidth sliderFrame.origin.x = sideMargin + labelWidth + gutterWidth sliderFrame.origin.y = (bounds.height - sliderFrame.height) / 2.0 slider.frame = sliderFrame } }
bsd-2-clause
3f519db4b302cf64261cbb4df4734f8e
30.398551
122
0.632818
4.580338
false
false
false
false
davehirsch/SwipeViewSwiftly
SwipeViewSwiftly/ViewController.swift
1
3529
/* ViewController.swift SwipeViewSwiftly Version 1.1, December 30, 2014 Adapted for Swift by David Hirsch on 12/27/14 from: SwipeView 1.3.2 ( https://github.com/nicklockwood/SwipeView ) This version Copyright (C) 2014, David Hirsch, licensed under MIT License. */ import UIKit class ViewController: UIViewController, SwipeViewDataSource, SwipeViewDelegate { @IBOutlet weak var swipeView: SwipeView! var items: [Int] required init(coder aDecoder: NSCoder) { items = Array() for i in [1...100] { items += i } super.init(coder: aDecoder) } //MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. swipeView.delegate=self swipeView.dataSource=self swipeView.pagingEnabled=true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - SwipeViewDataSource functions func numberOfItemsInSwipeView(swipeView: SwipeView) -> Int { return items.count } func viewForItemAtIndex(index: Int, swipeView: SwipeView, reusingView: UIView?) -> UIView? { var label : UILabel var returnedView : UIView //create new view if no view is available for recycling if (reusingView == nil) { //don't do anything specific to the index within //this `if (view == nil) {...}` statement because the view will be //recycled and used with other index values later returnedView = UIView(frame: self.swipeView.bounds) returnedView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight let insetRect = CGRectInset(returnedView.bounds, 15, 25) label = UILabel(frame: insetRect) label.layer.cornerRadius = 10 label.layer.masksToBounds = true label.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight label.backgroundColor = UIColor.whiteColor() label.textAlignment = NSTextAlignment.Center label.font = label.font.fontWithSize(35) label.numberOfLines = 0 label.tag = 1 returnedView.addSubview(label) } else { //get a reference to the label in the recycled view returnedView = reusingView! label = returnedView.viewWithTag(1) as UILabel } //set background color srand48(index) // code color semi-randomly to index, so each view retains the same color let red = CGFloat(drand48()) let green = CGFloat(drand48()) let blue = CGFloat(drand48()) returnedView.backgroundColor = UIColor(red: red, green: green, blue: blue, alpha: 1.0) //set item label //remember to always set any properties of your carousel item //views outside of the `if (view == nil) {...}` check otherwise //you'll get weird issues with carousel item content appearing //in the wrong place in the carousel label.text = "This is view #\(self.items[index])." return returnedView; } //MARK: - SwipeViewDelegate functions func swipeViewItemSize(swipeView: SwipeView) -> CGSize { return self.swipeView.bounds.size } }
mit
af2b46f45f647c39087ea5b2bfc42441
34.29
112
0.633607
4.956461
false
false
false
false
AntoineBarroux/Demo-Firebase-iOS
FirebaseDemo/Constants.swift
1
517
// // constants.swift // FirebaseDemo // // Created by antoine on 27/01/2017. // Copyright © 2017 Cobaltians. All rights reserved. // import Foundation // MARK : FCM let gcmMessageIDKey = "gcm.message_id" // MARK : EVENTS let EVENT_GETTOKEN:String = "getToken" let EVENT_SUBSCRIBE:String = "abonnement" let EVENT_UNSUBSCRIBE:String = "desabonnement" let EVENT_GETAPIKEY:String = "getApiKey" // MARK : SECRET KEY TO COMMUNICATE WITH KRISTALBUILDS API let SECRET_KEY:String = "dF6vmQCZGZa99xVhHXXMpZ83BKmLcH"
mit
340c67cbb6a49e59aa924fa33f61e055
22.454545
58
0.74031
2.804348
false
false
false
false
SunshinyNeko/LightSwordX
LightSwordX/ViewController.Servers.swift
2
8060
// // UserServersDataSource.swift // LightSwordX // // Created by Neko on 12/23/15. // Copyright © 2015 Neko. All rights reserved. // import Cocoa import SINQ extension ViewController: NSTableViewDataSource { @objc func numberOfRowsInTableView(tableView: NSTableView) -> Int { return servers.count } @objc func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return servers[row].address } @IBAction func addServer(sender: NSButton) { let server = UserServer() server.id = servers.count if servers.count == 0 { server.address = "public1.lightsword.org" server.port = 443 } servers.append(server) serversTableView.reloadData() selectedRow = servers.count - 1 let indexSet = NSIndexSet(index: selectedRow) serversTableView.selectRowIndexes(indexSet, byExtendingSelection: false) serverDetailsView.hidden = false keepConnectionCheckBox.state = server.keepConnection ? NSOnState : NSOffState serverAddressTextField.stringValue = server.address serverPortTextField.stringValue = String(server.port) cipherAlgorithmComboBox.stringValue = server.cipherAlgorithm proxyModeComboBox.selectItemAtIndex(server.proxyMode.rawValue) passwordTextField.stringValue = server.password listenAddressTextField.stringValue = server.listenAddr listenPortTextField.stringValue = String(server.listenPort) saveServers(true) if (server.keepConnection) { startServer(server) } } @IBAction func removeServer(sender: NSButton) { let selectedRow = serversTableView.selectedRow if (selectedRow == -1) { return } let removed = servers.removeAtIndex(selectedRow) serversTableView.reloadData() if (servers.count == 0) { serverDetailsView.hidden = true } saveServers(true) stopServer(removed) } @IBAction func setAsDefaultServer(sender: NSButton) { let selectedServer = servers[selectedRow] selectedServer.keepConnection = !selectedServer.keepConnection saveServers(true) if selectedServer.keepConnection { startServer(selectedServer) return } stopServer(selectedServer) } @IBAction func testConnectionSpeed(sender: NSButton) { let ip = servers[selectedRow].address let port = servers[selectedRow].port sender.enabled = false dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let start = StatisticsHelper.getUptimeInMilliseconds() let con = TCPClient(addr: ip, port: port) let (success, _) = con.connect(timeout: 10) con.close() let message = success ? "\(NSLocalizedString("Elapsed Time", comment: "")): \(StatisticsHelper.getUptimeInMilliseconds() - start)ms\n\(ip) ✓" : NSLocalizedString("Connection Timeout", comment: "") let notification = NSUserNotification() notification.title = NSLocalizedString("Test Connection Speed", comment: "") notification.informativeText = message NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification) dispatch_async(dispatch_get_main_queue()) { sender.enabled = true } } } } extension ViewController: NSTableViewDelegate { func tableView(tableView: NSTableView, shouldSelectRow row: Int) -> Bool { let info = servers[row] selectedRow = row serverAddressTextField.stringValue = info.address serverPortTextField.stringValue = String(info.port) cipherAlgorithmComboBox.stringValue = info.cipherAlgorithm proxyModeComboBox.selectItemAtIndex(info.proxyMode.rawValue) passwordTextField.stringValue = info.password keepConnectionCheckBox.state = info.keepConnection ? NSOnState : NSOffState listenAddressTextField.stringValue = info.listenAddr listenPortTextField.stringValue = String(info.listenPort) saveServers() return true } } extension ViewController: NSComboBoxDelegate { override func controlTextDidChange(obj: NSNotification) { let textField: NSTextField! = obj.object as? NSTextField if textField == nil { return } var newValue = textField.stringValue let selectedServer = servers[selectedRow] switch textField.identifier! { case "serverAddress": if (newValue.length == 0) { newValue = "127.0.0.1" } selectedServer.address = newValue serversTableView.reloadData() break case "serverPort": let port = Int(newValue) ?? 8900 selectedServer.port = port serverPortTextField.stringValue = String(port) break case "password": if (newValue.length == 0) { newValue = "lightsword.neko" } selectedServer.password = newValue break case "listenAddr": if (newValue.length == 0) { newValue = "127.0.0.1" } else if (newValue == "localhost") { newValue = "127.0.0.1" } if ipv4Regex.test(newValue) && !["127.0.0.1", "0.0.0.0"].contains(newValue) { newValue = "127.0.0.1" } selectedServer.listenAddr = newValue listenAddressTextField.stringValue = newValue break case "listenPort": let port = Int(newValue) ?? 1080 selectedServer.listenPort = port listenPortTextField.stringValue = String(port) break default: return } isDirty = true } override func controlTextDidEndEditing(obj: NSNotification) { saveServers() } func comboBoxSelectionDidChange(notification: NSNotification) { let comboBox = notification.object as! NSComboBox let handlers = [ "cipherAlgorithm": cipherAlgorithmComboBoxChanged, "proxyMode": proxyModeComboBoxChanged ] handlers[comboBox.identifier!]?(comboBox) } private func cipherAlgorithmComboBoxChanged(comboBox: NSComboBox) { let methods = ["aes-256-cfb", "aes-192-cfb", "aes-128-cfb"] let selectedIndex = comboBox.indexOfSelectedItem if (servers[selectedRow].cipherAlgorithm == methods[selectedIndex]) { return } servers[selectedRow].cipherAlgorithm = methods[selectedIndex] isDirty = true } private func proxyModeComboBoxChanged(comboBox: NSComboBox) { let modes = [ ProxyMode.GLOBAL.rawValue: ProxyMode.GLOBAL, ProxyMode.BLACK.rawValue: ProxyMode.BLACK, ProxyMode.WHITE.rawValue: ProxyMode.WHITE ] let selectedIndex = comboBox.indexOfSelectedItem if let selectedMode = modes[selectedIndex] { if (servers[selectedRow].proxyMode == selectedMode) { return } servers[selectedRow].proxyMode = selectedMode if let running = sinq(self.runningServers).firstOrNil({ s in s.tag as? Int == self.servers[self.selectedRow].id }) { running.proxyMode = selectedMode } isDirty = true } } }
gpl-2.0
9d123e5700d5426daf3c691458a88150
32.293388
208
0.593894
5.339298
false
false
false
false
LiulietLee/BilibiliCD
Shared/Network/URLBuilder.swift
1
1301
// // URLBuilder.swift // BCD // // Created by Liuliet.Lee on 20/7/2018. // Copyright © 2018 Liuliet.Lee. All rights reserved. // import Foundation class URLBuilder { private var components: URLComponents init() { self.components = URLComponents() } @discardableResult func set(scheme: String) -> URLBuilder { self.components.scheme = scheme return self } @discardableResult func set(host: String) -> URLBuilder { self.components.host = host return self } @discardableResult func set(port: Int) -> URLBuilder { self.components.port = port return self } @discardableResult func set(path: String) -> URLBuilder { var path = path if !path.hasPrefix("/") { path = "/" + path } self.components.path = path return self } @discardableResult func addQueryItem(name: String, value: String) -> URLBuilder { if self.components.queryItems == nil { self.components.queryItems = [] } self.components.queryItems?.append(URLQueryItem(name: name, value: value)) return self } func build() -> URL? { return self.components.url } }
gpl-3.0
4146a8a3de8eaa3fe428b86a81ead8b3
21.033898
82
0.572308
4.561404
false
false
false
false
rnystrom/GitHawk
Classes/Search/SearchResultSectionController.swift
1
1724
// // SearchResultSectionController.swift // Freetime // // Created by Sherlock, James on 28/07/2017. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import IGListKit protocol SearchResultSectionControllerDelegate: class { func didSelect(sectionController: SearchResultSectionController, repo: RepositoryDetails) } final class SearchResultSectionController: ListGenericSectionController<SearchRepoResult> { private weak var delegate: SearchResultSectionControllerDelegate? private let client: GithubClient init(client: GithubClient, delegate: SearchResultSectionControllerDelegate) { self.client = client self.delegate = delegate super.init() } override func sizeForItem(at index: Int) -> CGSize { return collectionContext.cellSize( with: Styles.Sizes.tableCellHeight + Styles.Sizes.rowSpacing * 2 ) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: SearchRepoResultCell.self, for: self, at: index) as? SearchRepoResultCell, let object = object else { fatalError("Missing context, object, or cell is wrong type") } cell.configure(result: object) return cell } override func didSelectItem(at index: Int) { guard let object = object else { return } let repo = RepositoryDetails( owner: object.owner, name: object.name ) delegate?.didSelect(sectionController: self, repo: repo) viewController?.route_detail(to: RepositoryViewController( client: client, repo: repo )) } }
mit
3ab4dfce1e63d9e23082798b458b4612
29.22807
142
0.675566
5.008721
false
false
false
false
mcxiaoke/learning-ios
cocoa_programming_for_osx/07_TableViews/SimpleToDo/SimpleToDo/MainWindowController.swift
1
2160
// // MainWindowController.swift // SimpleToDo // // Created by mcxiaoke on 16/4/27. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa class MainWindowController: NSWindowController, NSTableViewDelegate, NSTableViewDataSource, NSTextFieldDelegate{ var items:[String] = [] var curIndex = NSNotFound @IBOutlet weak var textField: NSTextField! @IBOutlet weak var tableView: NSTableView! @IBOutlet weak var addButton: NSButton! @IBAction func addItem(sender: AnyObject) { if curIndex != NSNotFound { self.items[curIndex] = self.textField.stringValue }else { self.items.append(self.textField.stringValue) } self.curIndex = NSNotFound self.textField.stringValue = "" updateUI() self.tableView.reloadData() } override func controlTextDidChange(obj: NSNotification) { updateUI() } func updateUI() { self.addButton.enabled = !self.textField.stringValue.isEmpty } func deleteRow(action:NSTableViewRowAction, row:Int) { // } // table view func numberOfRowsInTableView(tableView: NSTableView) -> Int { return items.count } func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? { return items[row] } func tableView(tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableRowActionEdge) -> [NSTableViewRowAction] { let deleteAction = NSTableViewRowAction(style: NSTableViewRowActionStyle.Destructive, title: "Delete", handler: { action, row in print("action = \(action) row = \(row)") }) return [deleteAction] } func tableViewSelectionDidChange(notification: NSNotification) { let row = self.tableView.selectedRow self.curIndex = row self.textField.stringValue = items[row] } override var windowNibName: String? { return "MainWindowController" } override func windowDidLoad() { super.windowDidLoad() self.textField.delegate = self for i in 1...10 { items.append("Simple ToDo List Item No.\(i)") } updateUI() } }
apache-2.0
c59576f31c7ac645a06242dcf087a795
24.678571
132
0.679648
4.599147
false
false
false
false
cache0928/CCWeibo
CCWeibo/CCWeibo/Classes/NewPost/NewPostTabView.swift
1
9528
// // NewPostTabView.swift // CCWeibo // // Created by 徐才超 on 16/2/18. // Copyright © 2016年 徐才超. All rights reserved. // import UIKit import SnapKit class NewPostTabView: UIView, ScrollTabViewDelegate { // 滚动页码, 在监听中设置UI private var pageNum: Int = 0 { didSet { let scrollWidth = UIScreen.mainScreen().bounds.width let rectOrigin = CGRect(x: CGFloat(pageNum) * scrollWidth, y: 0, width: scrollWidth, height: self.newPostScrollView.frame.height) self.newPostScrollView.scrollRectToVisible(rectOrigin, animated: isReprensing) UIView.animateWithDuration(0.3) { self.returnCloseBar.alpha = self.pageNum == 0 ? 0 : 1 } } } // 动画属性,控制view展现和消失,以及相应的弹性动画 var isReprensing: Bool = true { didSet { animateItems() UIView.animateWithDuration(0.5, animations: { self.alpha = self.isReprensing ? 1 : 0 self.closeBtn.transform = self.isReprensing ? CGAffineTransformMakeRotation(CGFloat(M_PI_4)) : CGAffineTransformIdentity }) { _ in if !self.isReprensing { self.pageNum = 0 } } } } @IBOutlet weak var closeBtn: UIImageView! @IBOutlet weak var returnCloseBar: UIView! @IBAction func tapToClose(sender: UITapGestureRecognizer) { self.isReprensing = false } @IBAction func returnBarCloseClick(sender: UIButton) { self.isReprensing = false } @IBAction func returnToFirstPage(sender: UIButton) { pageNum = 0 } @IBOutlet weak var newPostScrollView: UIScrollView! @IBOutlet weak var newPostTabBar: UIView! override init(frame: CGRect) { super.init(frame: frame) setupXib() } // 设置xib视图 func setupXib() { let bundle = NSBundle(forClass: self.dynamicType) let nib = UINib(nibName: "NewPostTabView", bundle: bundle) let view: UIView = nib.instantiateWithOwner(self, options: nil).first as! UIView view.frame = bounds addSubview(view) setupUI() } // 核心UI设置代码 private func setupUI() { returnCloseBar.alpha = 0 newPostScrollView.contentSize = CGSize(width: UIScreen.mainScreen().bounds.width * 2, height: newPostScrollView.frame.height) let btnWidth = UIScreen.mainScreen().bounds.width/3 let btnHeight = newPostScrollView.frame.height * 0.5 let rectOrigin = CGRect(x: 0, y: 0, width: btnWidth, height: btnHeight) let textBtnView = ScrollTabView(frame:rectOrigin , imageName: "tabbar_compose_idea", labelText: "文字") textBtnView.delegate = self let photoBtnView = ScrollTabView(frame: CGRectOffset(rectOrigin, btnWidth, 0), imageName: "tabbar_compose_photo", labelText: "相片/视频") photoBtnView.delegate = self let hotBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*2, 0) , imageName: "tabbar_compose_idea", labelText: "头条文章") hotBtnView.delegate = self let locBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, 0, btnHeight) , imageName: "tabbar_compose_lbs", labelText: "签到") locBtnView.delegate = self let rateBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth, btnHeight) , imageName: "tabbar_compose_review", labelText: "点评") rateBtnView.delegate = self let moreBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*2, btnHeight) , imageName: "tabbar_compose_more", labelText: "更多") moreBtnView.delegate = self let friendsBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*3, 0) , imageName: "tabbar_compose_friend", labelText: "好友圈") friendsBtnView.delegate = self let cameraBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*4, 0) , imageName: "tabbar_compose_wbcamera", labelText: "微博相机") cameraBtnView.delegate = self let musicBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*5, 0) , imageName: "tabbar_compose_idea", labelText: "音乐") musicBtnView.delegate = self let moneyBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*3, btnHeight) , imageName: "tabbar_compose_envelope", labelText: "红包") moneyBtnView.delegate = self let bookBtnView = ScrollTabView(frame:CGRectOffset(rectOrigin, btnWidth*4, btnHeight) , imageName: "tabbar_compose_book", labelText: "书籍") bookBtnView.delegate = self newPostScrollView.addSubview(textBtnView) textBtnView.moveBottomOffScreen() newPostScrollView.addSubview(photoBtnView) photoBtnView.moveBottomOffScreen() newPostScrollView.addSubview(hotBtnView) hotBtnView.moveBottomOffScreen() newPostScrollView.addSubview(locBtnView) locBtnView.moveBottomOffScreen() newPostScrollView.addSubview(rateBtnView) rateBtnView.moveBottomOffScreen() newPostScrollView.addSubview(moreBtnView) moreBtnView.moveBottomOffScreen() newPostScrollView.addSubview(friendsBtnView) friendsBtnView.moveBottomOffScreen() newPostScrollView.addSubview(cameraBtnView) cameraBtnView.moveBottomOffScreen() newPostScrollView.addSubview(musicBtnView) musicBtnView.moveBottomOffScreen() newPostScrollView.addSubview(moneyBtnView) moneyBtnView.moveBottomOffScreen() newPostScrollView.addSubview(bookBtnView) bookBtnView.moveBottomOffScreen() } // 列表选项点击方法 func didClick(sender: ScrollTabView) { switch sender.infoLabel.text! { case "更多": pageNum = 1 default: isReprensing = false NSNotificationCenter.defaultCenter().postNotificationName(NewPostNotifications.NewPostTextItemDidClick, object: nil) } } // tab视图的弹性动画 private func animateItems() { let itemCount = newPostScrollView.subviews.count let viewArr = (pageNum == 0 ? newPostScrollView.subviews : newPostScrollView.subviews.reverse()).map { $0 as! ScrollTabView } for (index, view) in viewArr.enumerate() { UIView.animateWithDuration(0.5, delay: 0.4/Double(itemCount) * Double(index), usingSpringWithDamping: 0.9, initialSpringVelocity: 20, options: [], animations: { self.isReprensing ? view.moveUpToOrigin() : view.moveBottomOffScreen() }, completion: nil) } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupXib() } } // 列表选项视图 class ScrollTabView: UIView { weak var delegate: ScrollTabViewDelegate? override init(frame: CGRect) { super.init(frame: frame) setupUI() } convenience init(frame: CGRect, imageName: String, labelText: String) { self.init(frame: frame) imageView.image = UIImage(named: imageName) infoLabel.text = labelText infoLabel.sizeToFit() } private func setupUI() { self.addSubview(imageView) self.addSubview(infoLabel) let tap = UITapGestureRecognizer(target: self, action: #selector(ScrollTabView.didClick)) self.addGestureRecognizer(tap) imageView.snp_makeConstraints { (make) in make.top.equalTo(self.snp_top).offset(10) make.centerX.equalTo(self.snp_centerX) make.width.equalTo(71) make.height.equalTo(71) } infoLabel.snp_makeConstraints { (make) in make.top.equalTo(imageView.snp_bottom).offset(8) make.centerX.equalTo(imageView.snp_centerX) } } private lazy var imageView: UIImageView = UIImageView() private lazy var infoLabel: UILabel = { let label = UILabel() label.textColor = UIColor.whiteColor() label.textAlignment = .Center label.font = UIFont.systemFontOfSize(14) return label }() override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { imageView.transform = CGAffineTransformIdentity super.touchesEnded(touches, withEvent: event) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { imageView.transform = CGAffineTransformMakeScale(1.1, 1.1) super.touchesBegan(touches, withEvent: event) } func didClick() { if self.infoLabel.text! != "更多" { UIView.animateWithDuration(0.3, animations: { self.transform = CGAffineTransformMakeScale(2, 2) self.alpha = 0.1 }) { _ in self.delegate?.didClick(self) self.transform = CGAffineTransformIdentity self.alpha = 1 self.imageView.transform = CGAffineTransformIdentity } } else { delegate?.didClick(self) } } func moveBottomOffScreen() { self.center.y += UIScreen.mainScreen().bounds.height self.alpha = 0 } func moveUpToOrigin() { self.center.y -= UIScreen.mainScreen().bounds.height self.alpha = 1 } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } protocol ScrollTabViewDelegate: class { func didClick(sender: ScrollTabView) }
mit
23d8f862023384ecbfc97dc2aded4dcb
40.413333
172
0.657078
4.41564
false
false
false
false
omiz/CarBooking
CarBooking/Classes/UI/Booking/Detail/BookingDetailViewController.swift
1
11962
// // BookingDetailViewController.swift // CarBooking // // Created by Omar Allaham on 10/19/17. // Copyright © 2017 Omar Allaham. All rights reserved. // import UIKit import UserNotifications class BookingDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, BookingTimeDelegate, BookingDayDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var buttonsContainerView: UIView! @IBOutlet weak var buttonsContainerStackView: UIStackView! @IBOutlet weak var buttonsContainerBottomConstraint: NSLayoutConstraint! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var updateButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var notificationButton: UIButton! var isDirty = false { didSet { updateActionButtons() } } var request: Request? var unEditedBooking: Booking? var booking: Booking? { didSet { reloadNotifications() } } var datePickerExtended = false var dayPickerExtended = false var notifications: [UNNotificationRequest] = [] override func viewDidLoad() { super.viewDidLoad() setupActionsView() setupTable() } func reloadNotifications() { notifications = [] booking?.notification(completion: { self.notifications = $0 self.tableView?.performSelector(onMainThread: #selector(UITableView.reloadData), with: nil, waitUntilDone: false) }) } func setupActionsView() { let bottom = view.frame.height - buttonsContainerView.frame.origin.y - buttonsContainerView.frame.height tableView.contentInset.bottom = -bottom deleteButton.setTitle("Delete".localized, for: .normal) cancelButton.setTitle("Cancel".localized, for: .normal) updateButton.setTitle("Update".localized, for: .normal) notificationButton.setTitle("Add notification".localized, for: .normal) buttonsContainerView.backgroundColor = .primary buttonsContainerView.layer.cornerRadius = cornerRadius updateActionButtons() } func updateActionButtons() { cancelButton.isHidden = !isDirty updateButton.isHidden = !isDirty deleteButton.isHidden = isDirty notificationButton.isHidden = isDirty || (booking?.date?.timeIntervalSinceNow ?? 0) <= 0 } func setupTable() { tableView.dynamicHeight(estimated: 44) tableView.removeExtraCells() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { guard booking != nil else { return 0 } var sections = 0 sections += 1 // title sections += 1 // date sections += 1 // duration sections += 1 // notifications return sections } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard booking != nil else { return 0 } return section == 3 ? notifications.count : 1 } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 3 && !notifications.isEmpty ? "Notifications".localized : "" } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int){ view.tintColor = .white } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: return bookingTitle(in: tableView, at: indexPath) case 1: return bookingTimePicker(in: tableView, at: indexPath) case 2: return bookingDayPicker(in: tableView, at: indexPath) case 3: return bookingNotification(in: tableView, at: indexPath) default: return UITableViewCell(frame: CGRect.zero) } } func bookingTitle(in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.cell(BookingTitleCell.self, for: indexPath) cell.setup(booking) return cell } func bookingTimePicker(in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.cell(BookingTimePickerCell.self, for: indexPath) cell.setup(booking, delegate: self) cell.extended = datePickerExtended return cell } func bookingDayPicker(in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.cell(BookingDayPickerCell.self, for: indexPath) cell.setup(booking, delegate: self) cell.extended = dayPickerExtended return cell } func bookingNotification(in tableView: UITableView, at indexPath: IndexPath) -> UITableViewCell { let cell = tableView.cell(BookingNotificationCell.self, for: indexPath) cell.setup(booking, notificationRequest: notifications[indexPath.row]) return cell } @IBAction func deleteBooking(_ sender: UIButton) { guard let booking = booking else { return } let alert = UIAlertController(title: "Booking".localized, message: "Are you sure you want to delete this Booking?".localized, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Yes".localized, style: .default, handler: { _ in booking.removeAllNotifications() self.request?.cancel() self.request = DataManager.shared.bookings.delete(booking).load() self.navigationController?.popViewController(animated: true) })) alert.addAction(UIAlertAction(title: "No".localized, style: .cancel, handler: nil)) present(alert, animated: true) } @IBAction func cancelBookingUpdate(_ sender: UIButton) { isDirty = false dayPickerExtended = false datePickerExtended = false guard let old = unEditedBooking else { return } booking = old unEditedBooking = nil tableView?.reloadData() } @IBAction func updateBooking(_ sender: UIButton) { guard let booking = booking else { return } self.request?.cancel() self.request = DataManager.shared.bookings.update(booking).load(database: { self.booking = $0 self.tableView?.reloadData() self.isDirty = false self.unEditedBooking = nil }) } @IBAction func addNotification(_ sender: UIButton) { guard let booking = booking else { return } guard let date = booking.date, date.timeIntervalSinceNow > 0 else { return } showNotificationDatePicker(sender) } func showNotificationDatePicker(_ sender: UIView) { let alert = UIAlertController.init(title: nil, message: "\n\n\n\n\n\n\n\n\n", preferredStyle: .actionSheet) let picker = addDatePicker(in: alert) alert.addAction(UIAlertAction(title: "Cancel".localized, style: .cancel, handler: nil)) alert.addAction(UIAlertAction(title: "Set".localized, style: .default, handler: { _ in self.addNotification(at: picker.date) })) alert.popoverPresentationController?.sourceView = sender alert.popoverPresentationController?.sourceRect = CGRect(x: sender.bounds.midX, y: sender.bounds.midY, width: 0, height: 0) present(alert, animated: true) } func setup(notificationDatePicker picker: UIDatePicker) { picker.minimumDate = Date() picker.maximumDate = booking?.date ?? Booking.defaultDate } @discardableResult func addDatePicker(in alert: UIAlertController) -> UIDatePicker { let picker = UIDatePicker(frame: CGRect.zero) setup(notificationDatePicker: picker) alert.view.addSubview(picker) alert.view.clipsToBounds = true return picker } func addNotification(at date: Date) { guard let booking = booking else { return } guard booking.isBooked else { return } booking.addNotification(at: date) { guard $0 == nil else { return } self.reloadNotifications() } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { updateTimePickerCellIfNeeded(tableView, at: indexPath) updateDayPickerCellIfNeeded(tableView, at: indexPath) } func updateTimePickerCellIfNeeded(_ tableView: UITableView, at indexPath: IndexPath) { guard let c = tableView.cellForRow(at: indexPath) else { return } guard let cell = c as? BookingTimePickerCell else { return } datePickerExtended = !datePickerExtended UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { tableView.beginUpdates() cell.extended = self.datePickerExtended tableView.endUpdates() }) } func updateDayPickerCellIfNeeded(_ tableView: UITableView, at indexPath: IndexPath) { guard let c = tableView.cellForRow(at: indexPath) else { return } guard let cell = c as? BookingDayPickerCell else { return } dayPickerExtended = !dayPickerExtended UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { tableView.beginUpdates() cell.extended = self.dayPickerExtended tableView.endUpdates() }) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return indexPath.section == 3 } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let delete = UITableViewRowAction.init(style: .destructive, title: "Delete".localized) { self.delete(notification: $0, at: $1) } return [delete] } func delete(notification: UITableViewRowAction, at indexPath: IndexPath) { guard let date = booking?.scheduleDate(in: notifications[indexPath.row]) else { return } booking?.removeNotification(at: date) } func bookingTime(changed date: Date) { isDirty = true unEditedBooking = unEditedBooking ?? booking booking?.date = date } func bookingDay(changed days: Int) { isDirty = true unEditedBooking = unEditedBooking ?? booking booking?.duration = days } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: segue) setupDetailIndexIfNeeded(in: segue) } func setupDetailIndexIfNeeded(in segue: UIStoryboardSegue) { guard let controller = segue.destination as? VehicleDetailViewController else { return } guard let vehicle = booking?.vehicle else { return } controller.vehicleId = vehicle.id controller.vehicle = vehicle } deinit { request?.cancel() } }
mit
b086f1742149e9e96b5f7a1dfbfabf5f
31.327027
138
0.61224
5.40488
false
false
false
false
tkremenek/swift
test/IDE/complete_multifile.swift
13
4550
// RUN: %empty-directory(%t) // RUN: %{python} %utils/split_file.py -o %t %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=POINT_PAREN | %FileCheck --check-prefix=POINT_PAREN %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=POINT_DOT | %FileCheck --check-prefix=POINT_DOT %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=LENS_DOT | %FileCheck --check-prefix=LENS_DOT %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=MYENUM_DOT | %FileCheck --check-prefix=MYENUM_DOT %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=MYENUM_INSTANCE_DOT | %FileCheck --check-prefix=MYENUM_INSTANCE_DOT %s // RUN: %target-swift-ide-test -code-completion -source-filename %t/Main.swift %t/Library.swift -code-completion-token=HASWRAPPED_DOT| %FileCheck --check-prefix=HASWRAPPED_DOT %s // BEGIN Library.swift public struct Point { var x: Int var y: Int } @dynamicMemberLookup struct Lens<T> { var obj: T init(_ obj: T) { self.obj = obj } subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> { get { return Lens<U>(obj[keyPath: member]) } set { obj[keyPath: member] = newValue.obj } } } enum MyEnum: String, CaseIterable { case foo = "foo" case bar = "bar" } @propertyWrapper struct Wrap<T> { var wrappedValue: T public var projectedValue: Self { get { self } set { self = newValue } } } struct HasWrapped { @Wrap var wrapped: Int = 1 } // BEGIN Main.swift func testStructDefaultInit() { Point(#^POINT_PAREN^# // POINT_PAREN: Begin completions, 1 items // POINT_PAREN-DAG: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ['(']{#x: Int#}, {#y: Int#}[')'][#Point#]; // POINT_PAREN: End completions func sync() {} Point.#^POINT_DOT^# // POINT_DOT: Begin completions, 3 items // POINT_DOT-DAG: Keyword[self]/CurrNominal: self[#Point.Type#]; // POINT_DOT-DAG: Keyword/CurrNominal: Type[#Point.Type#]; // POINT_DOT-DAG: Decl[Constructor]/CurrNominal: init({#x: Int#}, {#y: Int#})[#Point#]; // POINT_DOT: End completions } func testDynamicMemberLookup(lens: Lens<Point>) { _ = lens.#^LENS_DOT^# // LENS_DOT: Begin completions, 4 items // LENS_DOT-DAG: Keyword[self]/CurrNominal: self[#Lens<Point>#]; // LENS_DOT-DAG: Decl[InstanceVar]/CurrNominal: x[#Lens<Int>#]; // LENS_DOT-DAG: Decl[InstanceVar]/CurrNominal: y[#Lens<Int>#]; // LENS_DOT-DAG: Decl[InstanceVar]/CurrNominal: obj[#Point#]; // LENS_DOT: End completions } func testRawRepresentable() { MyEnum.#^MYENUM_DOT^# // MYENUM_DOT: Begin completions, 9 items // MYENUM_DOT-DAG: Keyword[self]/CurrNominal: self[#MyEnum.Type#]; // MYENUM_DOT-DAG: Keyword/CurrNominal: Type[#MyEnum.Type#]; // MYENUM_DOT-DAG: Decl[EnumElement]/CurrNominal: foo[#MyEnum#]; // MYENUM_DOT-DAG: Decl[EnumElement]/CurrNominal: bar[#MyEnum#]; // MYENUM_DOT-DAG: Decl[TypeAlias]/CurrNominal: RawValue[#String#]; // MYENUM_DOT-DAG: Decl[Constructor]/CurrNominal: init({#rawValue: String#})[#MyEnum?#]; // MYENUM_DOT-DAG: Decl[TypeAlias]/CurrNominal: AllCases[#[MyEnum]#]; // MYENUM_DOT-DAG: Decl[StaticVar]/CurrNominal: allCases[#[MyEnum]#]; // MYENUM_DOT-DAG: Decl[InstanceMethod]/Super/IsSystem: hash({#(self): MyEnum#})[#(into: inout Hasher) -> Void#]; // MYENUM_DOT: End completions } func testRawRepesentableInstance(value: MyEnum) { value.#^MYENUM_INSTANCE_DOT^# // MYENUM_INSTANCE_DOT: Begin completions, 4 items // MYENUM_INSTANCE_DOT-DAG: Keyword[self]/CurrNominal: self[#MyEnum#]; // MYENUM_INSTANCE_DOT-DAG: Decl[InstanceVar]/CurrNominal: rawValue[#String#]; // MYENUM_INSTANCE_DOT-DAG: Decl[InstanceVar]/Super/IsSystem: hashValue[#Int#]; // MYENUM_INSTANCE_DOT-DAG: Decl[InstanceMethod]/Super/IsSystem: hash({#into: &Hasher#})[#Void#]; // MYENUM_INSTANCE_DOT: End completions } func testHasWrappedValue(value: HasWrapped) { value.#^HASWRAPPED_DOT^# // HASWRAPPED_DOT: Begin completions, 3 items // HASWRAPPED_DOT: Keyword[self]/CurrNominal: self[#HasWrapped#]; // HASWRAPPED_DOT: Decl[InstanceVar]/CurrNominal: wrapped[#Int#]; // HASWRAPPED_DOT: Decl[InstanceVar]/CurrNominal: $wrapped[#Wrap<Int>#]; // HASWRAPPED_DOT: End completions }
apache-2.0
fb1b1305e009e882e6b24fa45e187823
42.75
189
0.684176
3.365385
false
true
false
false
raptorxcz/Rubicon
Generator/Generator/NilableVariablesParser.swift
1
1305
// // NilableVariablesParser.swift // Generator // // Created by Kryštof Matěj on 03.06.2022. // Copyright © 2022 Kryštof Matěj. All rights reserved. // import SwiftSyntax import SwiftSyntaxBuilder import SwiftSyntaxParser public protocol NilableVariablesParser { func parse(from node: ClassDeclSyntax) -> [String] } public final class NilableVariablesParserImpl: NilableVariablesParser { public init() {} public func parse(from node: ClassDeclSyntax) -> [String] { return node.members.members.flatMap(getNilVariable(from:)) } private func getNilVariable(from member: MemberDeclListItemSyntax) -> [String] { guard let variable = member.decl.as(VariableDeclSyntax.self) else { return [] } guard variable.letOrVarKeyword.text == "var" else { return [] } return variable.bindings.compactMap(getVariable(for:)) } private func getVariable(for node: PatternBindingSyntax) -> String? { let name = node.pattern.description if node.typeAnnotation?.type.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) != nil { return name } if node.typeAnnotation?.type.as(OptionalTypeSyntax.self) != nil { return name } return nil } }
mit
c2ee058f5529c754eebd579bf7084808
25.530612
92
0.664615
4.40678
false
false
false
false
prebid/prebid-mobile-ios
EventHandlers/PrebidMobileAdMobAdapters/Sources/AdMobUtils.swift
1
1608
/*   Copyright 2018-2021 Prebid.org, 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 Foundation import GoogleMobileAds import PrebidMobile fileprivate let HBKeywordPrefix = "hb_" @objcMembers public class AdMobUtils: NSObject { public static func initializeGAD() { GADMobileAds.sharedInstance().start(completionHandler: nil) } static func removeHBKeywordsFrom(_ keywords: [String]) -> [String] { return keywords .filter { !$0.hasPrefix(HBKeywordPrefix) } } static func buildKeywords(existingKeywords: [String]?, targetingInfo: [String: String]?) -> [String]? { guard let targetingInfo = targetingInfo else { return nil } let prebidKeywords = targetingInfo.map { $0 + ":" + $1 } if let existingKeywords = existingKeywords, !existingKeywords.isEmpty { let joinedKeywords = existingKeywords + prebidKeywords return !joinedKeywords.isEmpty ? joinedKeywords : nil } return !prebidKeywords.isEmpty ? prebidKeywords : nil } }
apache-2.0
2e3ef7f719a22590eedf69a4927a5c4f
33.717391
107
0.688165
4.615607
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.RotationSpeed.swift
1
2047
import Foundation public extension AnyCharacteristic { static func rotationSpeed( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Rotation Speed", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.rotationSpeed( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func rotationSpeed( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .write, .events], description: String? = "Rotation Speed", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Float> { GenericCharacteristic<Float>( type: .rotationSpeed, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
9f52f630ce829a04b5d72cefd0fef966
32.557377
75
0.575476
5.386842
false
false
false
false
GabrielGhe/SwiftProjects
App9DrawApp/App9DrawApp/DrawView.swift
1
1273
// // DrawView.swift // App9DrawApp // // Created by Gabriel on 2014-06-30. // Copyright (c) 2014 Gabriel. All rights reserved. // import UIKit class DrawView: UIView { var lines:[Line] = [] var lastPoint: CGPoint! init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { lastPoint = touches.anyObject().locationInView(self) } override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { var newPoint = touches.anyObject().locationInView(self) lines.append(Line(start: lastPoint, end: newPoint)) lastPoint = newPoint self.setNeedsDisplay() } override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext() CGContextBeginPath(context) for line in lines { //move to start, draw line to end CGContextMoveToPoint(context, line.start.x, line.start.y) CGContextAddLineToPoint(context, line.end.x, line.end.y) } //set color CGContextSetRGBStrokeColor(context, 0, 0, 0, 1) CGContextSetLineCap(context, kCGLineCapRound) CGContextStrokePath(context) } }
mit
8d3146f430bbc412df7333205eecad1f
27.931818
76
0.634721
4.498233
false
false
false
false
hstdt/GodEye
Carthage/Checkouts/pull-to-refresh/ESPullToRefreshExample/ESPullToRefreshExample/WebViewController.swift
1
1768
// // WebViewController.swift // ESPullToRefreshExample // // Created by lihao on 16/5/6. // Copyright © 2016年 egg swift. All rights reserved. // import UIKit class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var networkTipsButton: UIButton! @IBOutlet weak var webViewXib: UIWebView! var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() if let _ = self.webViewXib { self.webView = self.webViewXib } else { self.webView = UIWebView() self.webView.frame = self.view.bounds self.view.addSubview(self.webView!) } self.webView!.delegate = self let url = "https://github.com/eggswift" self.title = "egg swift" let request = NSURLRequest.init(url: NSURL(string: url)! as URL) self.webView.scrollView.es_addPullToRefresh { [weak self] in self!.webView.loadRequest(request as URLRequest) } self.webView.scrollView.es_startPullToRefresh() } func webViewDidFinishLoad(_ webView: UIWebView) { self.webView.scrollView.es_stopPullToRefresh() self.webView.scrollView.bounces = true self.webView.scrollView.alwaysBounceVertical = true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.webView.scrollView.es_stopPullToRefresh(ignoreDate: true) self.networkTipsButton.isHidden = false } @IBAction func networkRetryAction(_ sender: AnyObject) { self.networkTipsButton.isHidden = true UIView.performWithoutAnimation { self.webView.scrollView.es_startPullToRefresh() } } }
mit
1bcbc85e53a727b7701dab87426675d1
29.431034
75
0.637394
4.694149
false
false
false
false
proversity-org/edx-app-ios
Source/UIView+LayoutDirection.swift
1
1551
// // UIView+LayoutDirection.swift // edX // // Created by Akiva Leffert on 7/20/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation extension UIView { @objc var isRightToLeft : Bool { let direction = UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute) switch direction { case .leftToRight: return false case .rightToLeft: return true } } } enum LocalizedHorizontalContentAlignment { case Leading case Center case Trailing case Fill } extension UIControl { var localizedHorizontalContentAlignment : LocalizedHorizontalContentAlignment { get { switch self.contentHorizontalAlignment { case .left: return self.isRightToLeft ? .Trailing : .Leading case .right: return self.isRightToLeft ? .Leading : .Trailing case .center: return .Center case .fill: return .Fill default: return .Fill } } set { switch newValue { case .Leading: self.contentHorizontalAlignment = self.isRightToLeft ? .right : .left case .Trailing: self.contentHorizontalAlignment = self.isRightToLeft ? .left : .right case .Center: self.contentHorizontalAlignment = .center case .Fill: self.contentHorizontalAlignment = .fill } } } }
apache-2.0
dfafa1bb7b895b5fb8964dd44297ebbf
26.210526
95
0.573179
5.442105
false
false
false
false
MadAppGang/refresher
Refresher/Animator.swift
1
4818
// // Animator.swift // // Copyright (c) 2014 Josip Cavar // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import QuartzCore import UIKit internal class AnimatorView: UIView { private let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false return label }() private let activityIndicatorView: UIActivityIndicatorView = { let activity = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activity.translatesAutoresizingMaskIntoConstraints = false return activity }() override init(frame: CGRect) { super.init(frame: frame) autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] addSubview(titleLabel) addSubview(activityIndicatorView) let leftActivityConstraint = NSLayoutConstraint(item: activityIndicatorView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1, constant: 16) let centerActivityConstraint = NSLayoutConstraint(item: activityIndicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0) let leftTitleConstraint = NSLayoutConstraint(item: titleLabel, attribute: .Left, relatedBy: .Equal, toItem: activityIndicatorView, attribute: .Right, multiplier: 1, constant: 16) let centerTitleConstraint = NSLayoutConstraint(item: self, attribute: .CenterY, relatedBy: .Equal, toItem: titleLabel, attribute: .CenterY, multiplier: 1, constant: 0) addConstraints([leftActivityConstraint, centerActivityConstraint, leftTitleConstraint, centerTitleConstraint]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class Animator: PullToRefreshViewDelegate { internal let animatorView: AnimatorView init(frame: CGRect) { animatorView = AnimatorView(frame: frame) } func pullToRefreshAnimationDidStart(view: PullToRefreshView) { animatorView.activityIndicatorView.startAnimating() animatorView.titleLabel.text = "Loading" } func pullToRefreshAnimationDidEnd(view: PullToRefreshView) { animatorView.activityIndicatorView.stopAnimating() animatorView.titleLabel.text = "" } func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat) { } func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) { switch state { case .Loading: animatorView.titleLabel.text = "Loading" case .PullToRefresh: animatorView.titleLabel.text = "Pull to refresh" case .ReleaseToRefresh: animatorView.titleLabel.text = "Release to refresh" } } } extension Animator: LoadMoreViewDelegate { func loadMoreAnimationDidStart(view: LoadMoreView) { animatorView.activityIndicatorView.startAnimating() animatorView.titleLabel.text = "Loading" } func loadMoreAnimationDidEnd(view: LoadMoreView) { animatorView.activityIndicatorView.stopAnimating() animatorView.titleLabel.text = "" } func loadMore(view: LoadMoreView, progressDidChange progress: CGFloat) { } func loadMore(view: LoadMoreView, stateDidChange state: LoadMoreViewState) { switch state { case .Loading: animatorView.titleLabel.text = "Loading" case .ScrollToLoadMore: animatorView.titleLabel.text = "Scroll to load more" case .ReleaseToLoadMore: animatorView.titleLabel.text = "Release to load more" } } }
mit
8aaadda21d89d28b317f40ad60de290c
38.170732
189
0.708385
5.175081
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/SolutionsTests/Medium/Medium_018_4Sum_Test.swift
1
2539
// // Medium_018_4Sum_Test.swift // Solutions // // Created by Di Wu on 4/19/15. // Copyright (c) 2015 diwu. All rights reserved. // import XCTest class Medium_018_4Sum_Test: XCTestCase, SolutionsTestCase { func test_001() { let input: [Any] = [[1, 0, -1], 0] let expected: [[Int]] = [ ] asyncHelper(input: input, expected: expected) } func test_002() { let input: [Any] = [[1, 0, -1, 0], 0] let expected: [[Int]] = [ [-1, 0, 0, 1] ] asyncHelper(input: input, expected: expected) } func test_003() { let input: [Any] = [[1, 0, -1, 0, -2, 2], 0] let expected: [[Int]] = [ [-1, 0, 0, 1], [-2, -1, 1, 2], [-2, 0, 0, 2], ] asyncHelper(input: input, expected: expected) } func asyncHelper(input: [Any], expected: [[Int]]) { weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName()) serialQueue().async(execute: { () -> Void in let result: [[Int]] = Medium_018_4Sum.fourSum(num: input[0] as! [Int], target: input[1] as! Int) if result.count != expected.count { assertHelper(false, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) } else { for i in 0 ..< expected.count { var flag: Bool = false for j in 0 ..< result.count { let b0 = result[j][0] == expected[i][0] let b1 = result[j][1] == expected[i][1] let b2 = result[j][2] == expected[i][2] let b3 = result[j][3] == expected[i][3] if b0 && b1 && b2 && b3 { flag = true break } } if flag == false { assertHelper(false, problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected) } } } if let unwrapped = expectation { unwrapped.fulfill() } }) waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in if error != nil { assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected) } } } }
mit
ba72949307ef899d5d86aa368908ff3e
33.780822
138
0.467901
4.06891
false
true
false
false
pixel-ink/PIForceTouch
PIForceTouchDemo/PIForceTouch/ViewController.swift
1
1239
import UIKit import PIRipple class ViewController: UIViewController, PIForceTouchViewDelegate { @IBOutlet weak var demoView: PIForceTouchView! @IBOutlet weak var messageLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() demoView.layer.borderColor = UIColor.whiteColor().CGColor demoView.layer.borderWidth = 1.0 demoView.delegate = self } //delegate func beganTouch(touch: UITouch) { let location = touch.locationInView(demoView) var opt = Ripple.option() opt.radius = 50 opt.borderColor = UIColor.whiteColor() opt.fillColor = UIColor.clearColor() Ripple.run(demoView, locationInView: location, option: opt) messageLabel.text = "Touch" } //delegate func beganForceTouch(touch: UITouch){ let location = touch.locationInView(demoView) var opt = Ripple.option() opt.radius = 50 opt.borderColor = UIColor.redColor() opt.fillColor = UIColor.redColor() Ripple.run(demoView, locationInView: location, option: opt) messageLabel.text = "Force Touch" } //delegate func cancelledTouch(touch: UITouch) { messageLabel.text = " " } //delegate func endedTouch(touch: UITouch) { messageLabel.text = " " } }
mit
bf1bd2f37d5daa8e4d2c679688c697b2
23.7
66
0.696356
4.10299
false
false
false
false
corichmond/turbo-adventure
project7/Project7/MasterViewController.swift
20
2730
// // MasterViewController.swift // Project7 // // Created by Hudzilla on 20/11/2014. // Copyright (c) 2014 Hudzilla. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var objects = [[String: String]]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() var urlString: String if navigationController?.tabBarItem.tag == 0 { urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" } else { urlString = "https://api.whitehouse.gov/v1/petitions.json?signatureCountFloor=10000&limit=100" } if let url = NSURL(string: urlString) { if let data = NSData(contentsOfURL: url, options: .allZeros, error: nil) { let json = JSON(data: data) if json["metadata"]["responseInfo"]["status"].intValue == 200 { parseJSON(json) } else { showError() } } else { showError() } } else { showError() } } func parseJSON(json: JSON) { for result in json["results"].arrayValue { let title = result["title"].stringValue let body = result["body"].stringValue let sigs = result["signatureCount"].stringValue let obj = ["title": title, "body": body, "sigs": sigs] objects.append(obj) } self.tableView.reloadData() } func showError() { let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) self.presentViewController(ac, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] (segue.destinationViewController as! DetailViewController).detailItem = object } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let object = objects[indexPath.row] cell.textLabel!.text = object["title"] cell.detailTextLabel!.text = object["body"] return cell } }
unlicense
bd743aa4fbb22c258303941245002c94
26.3
170
0.704029
3.928058
false
false
false
false
apple/swift-nio
Sources/NIOPosix/SelectorEpoll.swift
1
12669
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore #if !SWIFTNIO_USE_IO_URING #if os(Linux) || os(Android) /// Represents the `epoll` filters/events we might use: /// /// - `hangup` corresponds to `EPOLLHUP` /// - `readHangup` corresponds to `EPOLLRDHUP` /// - `input` corresponds to `EPOLLIN` /// - `output` corresponds to `EPOLLOUT` /// - `error` corresponds to `EPOLLERR` private struct EpollFilterSet: OptionSet, Equatable { typealias RawValue = UInt8 let rawValue: RawValue static let _none = EpollFilterSet([]) static let hangup = EpollFilterSet(rawValue: 1 << 0) static let readHangup = EpollFilterSet(rawValue: 1 << 1) static let input = EpollFilterSet(rawValue: 1 << 2) static let output = EpollFilterSet(rawValue: 1 << 3) static let error = EpollFilterSet(rawValue: 1 << 4) init(rawValue: RawValue) { self.rawValue = rawValue } } extension EpollFilterSet { /// Convert NIO's `SelectorEventSet` set to a `EpollFilterSet` init(selectorEventSet: SelectorEventSet) { var thing: EpollFilterSet = [.error, .hangup] if selectorEventSet.contains(.read) { thing.formUnion(.input) } if selectorEventSet.contains(.write) { thing.formUnion(.output) } if selectorEventSet.contains(.readEOF) { thing.formUnion(.readHangup) } self = thing } } extension SelectorEventSet { var epollEventSet: UInt32 { assert(self != ._none) // EPOLLERR | EPOLLHUP is always set unconditionally anyway but it's easier to understand if we explicitly ask. var filter: UInt32 = Epoll.EPOLLERR | Epoll.EPOLLHUP let epollFilters = EpollFilterSet(selectorEventSet: self) if epollFilters.contains(.input) { filter |= Epoll.EPOLLIN } if epollFilters.contains(.output) { filter |= Epoll.EPOLLOUT } if epollFilters.contains(.readHangup) { filter |= Epoll.EPOLLRDHUP } assert(filter & Epoll.EPOLLHUP != 0) // both of these are reported assert(filter & Epoll.EPOLLERR != 0) // always and can't be masked. return filter } fileprivate init(epollEvent: Epoll.epoll_event) { var selectorEventSet: SelectorEventSet = ._none if epollEvent.events & Epoll.EPOLLIN != 0 { selectorEventSet.formUnion(.read) } if epollEvent.events & Epoll.EPOLLOUT != 0 { selectorEventSet.formUnion(.write) } if epollEvent.events & Epoll.EPOLLRDHUP != 0 { selectorEventSet.formUnion(.readEOF) } if epollEvent.events & Epoll.EPOLLHUP != 0 || epollEvent.events & Epoll.EPOLLERR != 0 { selectorEventSet.formUnion(.reset) } self = selectorEventSet } } // EPollUserData supports (un)packing into an `UInt64` because epoll has a user info field that we can attach which is // up to 64 bits wide. We're using all of those 64 bits, 32 for a "registration ID" and 32 for the file descriptor. @usableFromInline struct EPollUserData { @usableFromInline var registrationID: SelectorRegistrationID @usableFromInline var fileDescriptor: CInt @inlinable init(registrationID: SelectorRegistrationID, fileDescriptor: CInt) { assert(MemoryLayout<UInt64>.size == MemoryLayout<EPollUserData>.size) self.registrationID = registrationID self.fileDescriptor = fileDescriptor } @inlinable init(rawValue: UInt64) { let unpacked = IntegerBitPacking.unpackUInt32CInt(rawValue) self = .init(registrationID: SelectorRegistrationID(rawValue: unpacked.0), fileDescriptor: unpacked.1) } } extension UInt64 { @inlinable init(_ epollUserData: EPollUserData) { let fd = epollUserData.fileDescriptor assert(fd >= 0, "\(fd) is not a valid file descriptor") self = IntegerBitPacking.packUInt32CInt(epollUserData.registrationID.rawValue, fd) } } extension Selector: _SelectorBackendProtocol { func initialiseState0() throws { self.selectorFD = try Epoll.epoll_create(size: 128) self.eventFD = try EventFd.eventfd(initval: 0, flags: Int32(EventFd.EFD_CLOEXEC | EventFd.EFD_NONBLOCK)) self.timerFD = try TimerFd.timerfd_create(clockId: CLOCK_MONOTONIC, flags: Int32(TimerFd.TFD_CLOEXEC | TimerFd.TFD_NONBLOCK)) self.lifecycleState = .open var ev = Epoll.epoll_event() ev.events = SelectorEventSet.read.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.eventFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.eventFD, event: &ev) var timerev = Epoll.epoll_event() timerev.events = Epoll.EPOLLIN | Epoll.EPOLLERR | Epoll.EPOLLRDHUP timerev.data.u64 = UInt64(EPollUserData(registrationID: .initialRegistrationID, fileDescriptor: self.timerFD)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: self.timerFD, event: &timerev) } func deinitAssertions0() { assert(self.eventFD == -1, "self.eventFD == \(self.eventFD) in deinitAssertions0, forgot close?") assert(self.timerFD == -1, "self.timerFD == \(self.timerFD) in deinitAssertions0, forgot close?") } func register0<S: Selectable>(selectable: S, fileDescriptor: CInt, interested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = interested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_ADD, fd: fileDescriptor, event: &ev) } func reregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, newInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() ev.events = newInterested.epollEventSet ev.data.u64 = UInt64(EPollUserData(registrationID: registrationID, fileDescriptor: fileDescriptor)) _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_MOD, fd: fileDescriptor, event: &ev) } func deregister0<S: Selectable>(selectable: S, fileDescriptor: CInt, oldInterested: SelectorEventSet, registrationID: SelectorRegistrationID) throws { var ev = Epoll.epoll_event() _ = try Epoll.epoll_ctl(epfd: self.selectorFD, op: Epoll.EPOLL_CTL_DEL, fd: fileDescriptor, event: &ev) } /// Apply the given `SelectorStrategy` and execute `body` once it's complete (which may produce `SelectorEvent`s to handle). /// /// - parameters: /// - strategy: The `SelectorStrategy` to apply /// - body: The function to execute for each `SelectorEvent` that was produced. func whenReady0(strategy: SelectorStrategy, onLoopBegin loopStart: () -> Void, _ body: (SelectorEvent<R>) throws -> Void) throws -> Void { assert(self.myThread == NIOThread.current) guard self.lifecycleState == .open else { throw IOError(errnoCode: EBADF, reason: "can't call whenReady for selector as it's \(self.lifecycleState).") } let ready: Int switch strategy { case .now: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: 0)) case .blockUntilTimeout(let timeAmount): // Only call timerfd_settime if we're not already scheduled one that will cover it. // This guards against calling timerfd_settime if not needed as this is generally speaking // expensive. let next = NIODeadline.now() + timeAmount if next < self.earliestTimer { self.earliestTimer = next var ts = itimerspec() ts.it_value = timespec(timeAmount: timeAmount) try TimerFd.timerfd_settime(fd: self.timerFD, flags: 0, newValue: &ts, oldValue: nil) } fallthrough case .block: ready = Int(try Epoll.epoll_wait(epfd: self.selectorFD, events: events, maxevents: Int32(eventsCapacity), timeout: -1)) } loopStart() for i in 0..<ready { let ev = events[i] let epollUserData = EPollUserData(rawValue: ev.data.u64) let fd = epollUserData.fileDescriptor let eventRegistrationID = epollUserData.registrationID switch fd { case self.eventFD: var val = EventFd.eventfd_t() // Consume event _ = try EventFd.eventfd_read(fd: self.eventFD, value: &val) case self.timerFD: // Consume event var val: UInt64 = 0 // We are not interested in the result _ = try! Posix.read(descriptor: self.timerFD, pointer: &val, size: MemoryLayout.size(ofValue: val)) // Processed the earliest set timer so reset it. self.earliestTimer = .distantFuture default: // If the registration is not in the Map anymore we deregistered it during the processing of whenReady(...). In this case just skip it. if let registration = registrations[Int(fd)] { guard eventRegistrationID == registration.registrationID else { continue } var selectorEvent = SelectorEventSet(epollEvent: ev) // we can only verify the events for i == 0 as for i > 0 the user might have changed the registrations since then. assert(i != 0 || selectorEvent.isSubset(of: registration.interested), "selectorEvent: \(selectorEvent), registration: \(registration)") // in any case we only want what the user is currently registered for & what we got selectorEvent = selectorEvent.intersection(registration.interested) guard selectorEvent != ._none else { continue } try body((SelectorEvent(io: selectorEvent, registration: registration))) } } } growEventArrayIfNeeded(ready: ready) } /// Close the `Selector`. /// /// After closing the `Selector` it's no longer possible to use it. public func close0() throws { self.externalSelectorFDLock.withLock { // We try! all of the closes because close can only fail in the following ways: // - EINTR, which we eat in Posix.close // - EIO, which can only happen for on-disk files // - EBADF, which can't happen here because we would crash as EBADF is marked unacceptable // Therefore, we assert here that close will always succeed and if not, that's a NIO bug we need to know // about. try! Posix.close(descriptor: self.timerFD) self.timerFD = -1 try! Posix.close(descriptor: self.eventFD) self.eventFD = -1 try! Posix.close(descriptor: self.selectorFD) self.selectorFD = -1 } } /* attention, this may (will!) be called from outside the event loop, ie. can't access mutable shared state (such as `self.open`) */ func wakeup0() throws { assert(NIOThread.current != self.myThread) try self.externalSelectorFDLock.withLock { guard self.eventFD >= 0 else { throw EventLoopError.shutdown } _ = try EventFd.eventfd_write(fd: self.eventFD, value: 1) } } } #endif #endif
apache-2.0
ba5d3b99a69373d7235b6216ad3456b8
41.800676
155
0.611019
4.182569
false
false
false
false