repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
711k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
m-alani/contests
refs/heads/master
leetcode/bulbSwitcher.swift
mit
1
// // bulbSwitcher.swift // // Practice solution - Marwan Alani - 2017 // // Check the problem (and run the code) on leetCode @ https://leetcode.com/problems/bulb-switcher/ // Note: make sure that you select "Swift" from the top-left language menu of the code editor when testing this code // class Solution { func bulbSwitch(_ n: Int) -> Int { return Int(sqrt(Double(n))) } } /* Greedy Initial Solution : func bulbSwitch(_ n: Int) -> Int { if n < 2 { return n } var bulbs = Array(repeating: true, count: n) var i = 2 while i <= n { var idx = i - 1 while idx < n { bulbs[idx] = !bulbs[idx] idx += i } i += 1 } return bulbs.filter({ $0 }).count } */
3c3b84faa9fbf27fd01263cf060d3991
20.363636
117
0.602837
false
false
false
false
JaSpa/swift
refs/heads/master
test/Parse/subscripting.swift
apache-2.0
6
// RUN: %target-typecheck-verify-swift struct X { } // Simple examples struct X1 { var stored: Int subscript(i: Int) -> Int { get { return stored } mutating set { stored = newValue } } } struct X2 { var stored: Int subscript(i: Int) -> Int { get { return stored + i } set(v) { stored = v - i } } } struct X3 { var stored: Int subscript(_: Int) -> Int { get { return stored } set(v) { stored = v } } } struct X4 { var stored: Int subscript(i: Int, j: Int) -> Int { get { return stored + i + j } mutating set(v) { stored = v + i - j } } } struct Y1 { var stored: Int subscript(_: i, j: Int) -> Int { // expected-error {{use of undeclared type 'i'}} get { return stored + j } set { stored = j } } } // Mutating getters on constants (https://bugs.swift.org/browse/SR-845) struct Y2 { subscript(_: Int) -> Int { mutating get { return 0 } } } let y2 = Y2() // expected-note{{change 'let' to 'var' to make it mutable}}{{1-4=var}} _ = y2[0] // expected-error{{cannot use mutating getter on immutable value: 'y2' is a 'let' constant}} // Parsing errors struct A0 { subscript // expected-error {{expected '(' for subscript parameters}} i : Int -> Int { get { return stored } set { stored = value } } subscript -> Int { // expected-error {{expected '(' for subscript parameters}} {{12-12=()}} return 1 } } struct A1 { subscript (i : Int) // expected-error{{expected '->' for subscript element type}} Int { get { return stored } set { stored = value } } } struct A2 { subscript (i : Int) -> // expected-error{{expected subscripting element type}} { get { return stored } set { stored = value } } } struct A3 { subscript(i : Int) // expected-error {{expected '->' for subscript element type}} { get { return i } } } struct A4 { subscript(i : Int) { // expected-error {{expected '->' for subscript element type}} get { return i } } } struct A5 { subscript(i : Int) -> Int // expected-error {{expected '{' in subscript to specify getter and setter implementation}} } struct A6 { subscript(i: Int)(j: Int) -> Int { // expected-error {{expected '->' for subscript element type}} get { return i + j } } } struct A7 { static subscript(a: Int) -> Int { // expected-error {{subscript cannot be marked 'static'}} {{3-10=}} get { return 42 } } } struct A7b { class subscript(a: Float) -> Int { // expected-error {{subscript cannot be marked 'class'}} {{3-9=}} get { return 42 } } } struct A8 { subscript(i : Int) -> Int // expected-error{{expected '{' in subscript to specify getter and setter implementation}} get { return stored } set { stored = value } } struct A9 { subscript x() -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}} return 0 } } struct A10 { subscript x(i: Int) -> Int { // expected-error {{subscripts cannot have a name}} {{13-14=}} return 0 } } struct A11 { subscript x y : Int -> Int { // expected-error {{expected '(' for subscript parameters}} return 0 } } } // expected-error{{extraneous '}' at top level}} {{1-3=}}
d5b6633345b2d0bb238688734ca96fa4
16.395939
119
0.550919
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
Signal/test/util/ByteParserTest.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import XCTest @testable import Signal class ByteParserTest: SignalBaseTest { override func setUp() { super.setUp() } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testGetShort_Empty() { let parser = ByteParser(data: Data(), littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextShort()) XCTAssertTrue(parser.hasError) } func testGetShort_littleEndian() { let data = Data([0x01, 0x00, 0x00, 0x01, 0x01, 0x01]) let parser = ByteParser(data: data, littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextShort()) XCTAssertTrue(parser.hasError) } func testGetShort_bigEndian() { let data = Data([0x01, 0x00, 0x00, 0x01, 0x01, 0x01]) let parser = ByteParser(data: data, littleEndian: false) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextShort()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextShort()) XCTAssertTrue(parser.hasError) } func testGetInt_Empty() { let parser = ByteParser(data: Data(), littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextInt()) XCTAssertTrue(parser.hasError) } func testGetInt_littleEndian() { let data = Data([0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00]) let parser = ByteParser(data: data, littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextInt()) XCTAssertTrue(parser.hasError) } func testGetInt_bigEndian() { let data = Data([0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01]) let parser = ByteParser(data: data, littleEndian: false) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextInt()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextInt()) XCTAssertTrue(parser.hasError) } func testGetLong_Empty() { let parser = ByteParser(data: Data(), littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextLong()) XCTAssertTrue(parser.hasError) } func testGetLong_littleEndian() { let data = Data([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) let parser = ByteParser(data: data, littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextLong()) XCTAssertTrue(parser.hasError) } func testGetLong_bigEndian() { let data = Data([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01]) let parser = ByteParser(data: data, littleEndian: false) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(1, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(256, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(257, parser.nextLong()) XCTAssertFalse(parser.hasError) XCTAssertEqual(0, parser.nextLong()) XCTAssertTrue(parser.hasError) } func testReadZero_Empty() { let parser = ByteParser(data: Data(), littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertFalse(parser.readZero(1)) XCTAssertTrue(parser.hasError) } func testReadZero() { let data = Data([0x00, 0x01, 0x00, 0x00, 0x01, 0x00]) let parser = ByteParser(data: data, littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertTrue(parser.readZero(1)) XCTAssertFalse(parser.hasError) XCTAssertFalse(parser.readZero(1)) XCTAssertFalse(parser.hasError) XCTAssertTrue(parser.readZero(2)) XCTAssertFalse(parser.hasError) XCTAssertFalse(parser.readZero(2)) XCTAssertFalse(parser.hasError) XCTAssertFalse(parser.readZero(1)) XCTAssertTrue(parser.hasError) } func testReadBytes_Empty() { let parser = ByteParser(data: Data(), littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertNil(parser.readBytes(1)) XCTAssertTrue(parser.hasError) } func testReadBytes() { let data = Data([0x00, 0x01, 0x02, 0x03, 0x04, 0x05]) let parser = ByteParser(data: data, littleEndian: true) XCTAssertNotNil(parser) XCTAssertFalse(parser.hasError) XCTAssertEqual(Data([0x00]), parser.readBytes(1)) XCTAssertFalse(parser.hasError) XCTAssertEqual(Data([0x01]), parser.readBytes(1)) XCTAssertFalse(parser.hasError) XCTAssertEqual(Data([0x02, 0x03]), parser.readBytes(2)) XCTAssertFalse(parser.hasError) XCTAssertEqual(Data([0x04, 0x05]), parser.readBytes(2)) XCTAssertFalse(parser.hasError) XCTAssertNil(parser.readBytes(1)) XCTAssertTrue(parser.hasError) } }
5223f6414b7b89aab4959a563dfcb6c0
30.131222
169
0.652471
false
true
false
false
Antondomashnev/Sourcery
refs/heads/master
SourceryTests/Stub/Performance-Code/Kiosk/Admin/AdminCardTestingViewController.swift
mit
2
import Foundation import RxSwift import Keys class AdminCardTestingViewController: UIViewController { lazy var keys = EidolonKeys() var cardHandler: CardHandler! @IBOutlet weak var logTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() self.logTextView.text = "" if AppSetup.sharedState.useStaging { cardHandler = CardHandler(apiKey: self.keys.cardflightStagingAPIClientKey(), accountToken: self.keys.cardflightStagingMerchantAccountToken()) } else { cardHandler = CardHandler(apiKey: self.keys.cardflightProductionAPIClientKey(), accountToken: self.keys.cardflightProductionMerchantAccountToken()) } cardHandler.cardStatus .subscribe { (event) in switch event { case .next(let message): self.log("\(message)") case .error(let error): self.log("\n====Error====\n\(error)\nThe card reader may have become disconnected.\n\n") if self.cardHandler.card != nil { self.log("==\n\(self.cardHandler.card!)\n\n") } case .completed: guard let card = self.cardHandler.card else { // Restarts the card reader self.cardHandler.startSearching() return } let cardDetails = "Card: \(card.name) - \(card.last4) \n \(card.cardToken)" self.log(cardDetails) } } .addDisposableTo(rx_disposeBag) cardHandler.startSearching() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) cardHandler.end() } func log(_ string: String) { self.logTextView.text = "\(self.logTextView.text ?? "")\n\(string)" } @IBAction func backTapped(_ sender: AnyObject) { _ = navigationController?.popViewController(animated: true) } }
74ee97469f18f1f986de0330bf0e6017
32.629032
159
0.567866
false
false
false
false
vector-im/riot-ios
refs/heads/develop
Riot/Modules/SetPinCode/SetupBiometrics/SetupBiometricsViewModel.swift
apache-2.0
1
// File created from ScreenTemplate // $ createScreen.sh SetPinCode/SetupBiometrics SetupBiometrics /* Copyright 2020 New Vector Ltd 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 LocalAuthentication final class SetupBiometricsViewModel: SetupBiometricsViewModelType { // MARK: - Properties // MARK: Private private let session: MXSession? private let viewMode: SetPinCoordinatorViewMode private let pinCodePreferences: PinCodePreferences // MARK: Public weak var viewDelegate: SetupBiometricsViewModelViewDelegate? weak var coordinatorDelegate: SetupBiometricsViewModelCoordinatorDelegate? // MARK: - Setup init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences) { self.session = session self.viewMode = viewMode self.pinCodePreferences = pinCodePreferences } deinit { } // MARK: - Public func localizedBiometricsName() -> String? { return pinCodePreferences.localizedBiometricsName() } func biometricsIcon() -> UIImage? { return pinCodePreferences.biometricsIcon() } func process(viewAction: SetupBiometricsViewAction) { switch viewAction { case .loadData: loadData() case .enableDisableTapped: enableDisableBiometrics() case .skipOrCancel: coordinatorDelegate?.setupBiometricsViewModelDidCancel(self) case .unlock: unlockWithBiometrics() case .cantUnlockedAlertResetAction: coordinatorDelegate?.setupBiometricsViewModelDidCompleteWithReset(self) } } // MARK: - Private private func enableDisableBiometrics() { LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: VectorL10n.biometricsUsageReason) { (success, error) in if success { // complete after a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.setupBiometricsViewModelDidComplete(self) } } } } private func unlockWithBiometrics() { LAContext().evaluatePolicy(.deviceOwnerAuthentication, localizedReason: VectorL10n.biometricsUsageReason) { (success, error) in if success { // complete after a little delay DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.setupBiometricsViewModelDidComplete(self) } } else { if let error = error as NSError?, error.code == LAError.Code.userCancel.rawValue || error.code == LAError.Code.userFallback.rawValue { self.userCancelledUnlockWithBiometrics() } } } } private func userCancelledUnlockWithBiometrics() { if pinCodePreferences.isPinSet { // cascade this cancellation, coordinator should take care of it DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.coordinatorDelegate?.setupBiometricsViewModelDidCancel(self) } } else { // show an alert to nowhere to go from here DispatchQueue.main.async { self.update(viewState: .cantUnlocked) } } } private func loadData() { switch viewMode { case .setupBiometricsAfterLogin: self.update(viewState: .setupAfterLogin) case .setupBiometricsFromSettings: self.update(viewState: .setupFromSettings) case .unlock: self.update(viewState: .unlock) case .confirmBiometricsToDeactivate: self.update(viewState: .confirmToDisable) default: break } } private func update(viewState: SetupBiometricsViewState) { self.viewDelegate?.setupBiometricsViewModel(self, didUpdateViewState: viewState) } }
541307047794f62d7576ad73bc0e98d0
33.133333
150
0.647569
false
false
false
false
mhplong/Projects
refs/heads/master
iOS/ServiceTracker/ServiceTimeTracker/AppDelegate.swift
mit
1
// // AppDelegate.swift // ServiceTimeTracker // // Created by Mark Long on 5/11/16. // Copyright © 2016 Mark Long. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.ml.ServiceTimeTracker" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ServiceTimeTracker", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
a430820d92dcc10f7bdfe163bf929f57
54.054054
291
0.72034
false
false
false
false
atrick/swift
refs/heads/main
validation-test/compiler_crashers_2_fixed/sr9584.swift
apache-2.0
3
// RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on struct S<N> {} protocol P { associatedtype A: P = Self static func f(_ x: A) -> A } extension S: P where N: P { static func f<X: P>(_ x: X) -> S<X.A> where A == X, X.A == N { // expected-error@-1 {{cannot build rewrite system for generic signature; rule length limit exceeded}} // expected-note@-2 {{failed rewrite rule is τ_0_0.[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[concrete: S<S<S<S<S<S<S<S<S<S<S<S<S<S<τ_0_0>>>>>>>>>>>>>>] => τ_0_0.[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A].[P:A] [subst↓]}} // expected-error@-3 {{'A' is not a member type of type 'X'}} // expected-error@-4 {{'A' is not a member type of type 'X'}} return S<X.A>() } }
bd080e4c09bdd0e6bf7bebb0e79f019d
44.277778
288
0.55092
false
false
false
false
chengxianghe/MissGe
refs/heads/master
MissGe/MissGe/Class/Project/UI/Controller/Mine/MLUserFansController.swift
mit
1
// // MLFansController.swift // MissLi // // Created by CXH on 2016/10/11. // Copyright © 2016年 cn. All rights reserved. // import UIKit class MLUserFansController: BaseViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet private weak var tableView: UITableView! var isFans = false var uid: String = "" private var dataSource = [MLUserModel]() private let fansRequest = MLUserFansListRequest() private let followersRequest = MLUserFollowListRequest() private var currentIndex = 0 override func viewDidLoad() { super.viewDidLoad() self.loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - 数据请求 func loadData(){ self.showLoading("正在加载...") var request: MLBaseRequest! if isFans { self.fansRequest.uid = self.uid request = self.fansRequest } else { self.followersRequest.uid = self.uid request = self.followersRequest } request.send(success: {[unowned self] (baseRequest, responseObject) in self.hideHud() guard let blacklist = ((responseObject as? NSDictionary)?["content"] as? NSDictionary)?["blacklist"] as? [[String:Any]] else { return } guard let modelArray = blacklist.map({ MLUserModel(JSON: $0) }) as? [MLUserModel] else { return } self.dataSource.append(contentsOf: modelArray) self.tableView.reloadData() }) { (baseRequest, error) in print(error) self.showError("请求出错") } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MLUserFansCell") as? MLUserFansCell let userModel = self.dataSource[indexPath.row] cell!.setInfo(model: userModel); cell!.onFollowButtonTapClosure = {(sender) in if userModel.relation == 0 { // 去关注 MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in self.showSuccess("关注成功") userModel.relation = 1 self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) }, failed: { (base, err) in self.showError("网络错误") print(err) }) } else { // 取消关注 MLRequestHelper.userFollow(self.uid, succeed: { (base, res) in self.showSuccess("已取消关注") userModel.relation = 0 self.tableView.reloadRows(at: [indexPath], with: UITableViewRowAnimation.none) }, failed: { (base, err) in self.showError("网络错误") print(err) }) } } cell!.onIconButtonTapClosure = {(sender) in // 进入用户详情 //ToUserDetail self.performSegue(withIdentifier: "ToUserDetail", sender: userModel) } return cell! } // func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // return MLTopicCell.height(model) // } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } // 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. if segue.identifier == "ToUserDetail" { let vc = segue.destination as! MLUserController vc.uid = (sender as! MLUserModel).uid } } }
fb237582f338509bd7d6341b3e7473b2
32.164063
138
0.560895
false
false
false
false
CodaFi/swift
refs/heads/main
test/Generics/slice_test.swift
apache-2.0
42
// RUN: %target-typecheck-verify-swift -parse-stdlib import Swift infix operator < : ComparisonPrecedence precedencegroup ComparisonPrecedence { associativity: none higherThan: EqualityPrecedence } infix operator == : EqualityPrecedence infix operator != : EqualityPrecedence precedencegroup EqualityPrecedence { associativity: none higherThan: AssignmentPrecedence } precedencegroup AssignmentPrecedence { assignment: true } func testslice(_ s: Array<Int>) { for i in 0..<s.count { print(s[i]+1) } for i in s { print(i+1) } _ = s[0..<2] _ = s[0...1] _ = s[...1] _ = s[1...] _ = s[..<2] } @_silgen_name("malloc") func c_malloc(_ size: Int) -> UnsafeMutableRawPointer @_silgen_name("free") func c_free(_ p: UnsafeMutableRawPointer) class Vector<T> { var length : Int var capacity : Int var base : UnsafeMutablePointer<T>! init() { length = 0 capacity = 0 base = nil } func push_back(_ elem: T) { if length == capacity { let newcapacity = capacity * 2 + 2 let size = Int(Builtin.sizeof(T.self)) let newbase = UnsafeMutablePointer<T>(c_malloc(newcapacity * size) .bindMemory(to: T.self, capacity: newcapacity)) for i in 0..<length { (newbase + i).initialize(to: (base+i).move()) } c_free(base) base = newbase capacity = newcapacity } (base+length).initialize(to: elem) length += 1 } func pop_back() -> T { length -= 1 return (base + length).move() } subscript (i : Int) -> T { get { if i >= length { Builtin.int_trap() } return (base + i).pointee } set { if i >= length { Builtin.int_trap() } (base + i).pointee = newValue } } deinit { base.deinitialize(count: length) c_free(base) } } protocol Comparable { static func <(lhs: Self, rhs: Self) -> Bool } func sort<T : Comparable>(_ array: inout [T]) { for i in 0..<array.count { for j in i+1..<array.count { if array[j] < array[i] { let temp = array[i] array[i] = array[j] array[j] = temp } } } } func find<T : Eq>(_ array: [T], value: T) -> Int { var idx = 0 for elt in array { if (elt == value) { return idx } idx += 1 } return -1 } func findIf<T>(_ array: [T], fn: (T) -> Bool) -> Int { var idx = 0 for elt in array { if (fn(elt)) { return idx } idx += 1 } return -1 } protocol Eq { static func ==(lhs: Self, rhs: Self) -> Bool static func !=(lhs: Self, rhs: Self) -> Bool }
3186ec89e45d42e699196bab1ff4bd9b
19.149606
77
0.574443
false
false
false
false
katsana/katsana-sdk-ios
refs/heads/master
KatsanaSDK/Object/KTUser.swift
apache-2.0
1
// // DriveMarkSDK.User.swift // KatsanaSDK // // Created by Wan Ahmad Lutfi on 27/01/2017. // Copyright © 2017 pixelated. All rights reserved. // public enum Gender : String{ case unknown case male case female } @objcMembers open class KTUser: NSObject { static let dateFormatter : DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() open var email: String open var userId: String! open var address: String! open var phoneHome: String! open var phoneMobile: String! open var identification: String! open var fullname: String! open var status: Int = 0 open var emergencyFullName: String! open var emergencyPhoneHome: String! open var emergencyPhoneMobile: String! open var imageURL: String! open var thumbImageURL: String! open var phoneMobileCountryCode: String! open var postcode: String! open var state: String! open var country: String! open var gender: Gender = .unknown open var fleets = [Fleet]() open var genderText: String!{ get{ if gender == .unknown{ return nil } return gender.rawValue.capitalized } set{ if let newValue = newValue{ if newValue.lowercased() == "male" { gender = .male } else if newValue.lowercased() == "female" { gender = .female } }else{ gender = .unknown } } } open var birthday: Date!{ didSet{ if let birthday = birthday { let dateStr = KTUser.dateFormatter.string(from: birthday) if let birthdayText = birthdayText, dateStr == birthdayText{ }else{ birthdayText = dateStr } }else{ birthdayText = "" } } } open var birthdayText: String!{ didSet{ if let birthdayText = birthdayText { let date = KTUser.dateFormatter.date(from: birthdayText) if let birthday = birthday, date == birthday { //Do nothing }else if date != nil{ birthday = date } }else{ birthday = nil } } } open var createdAt: Date! open var updatedAt: Date! private(set) open var image : KMImage! private(set) open var thumbImage : KMImage! private var imageBlocks = [(image: KMImage) -> Void]() private var thumbImageBlocks = [(image: KMImage) -> Void]() private var isLoadingImage = false private var isLoadingThumbImage = false ///Implemented to satisfy FastCoder and set default value override init() { email = "" } init(email: String) { self.email = email } override open class func fastCodingKeys() -> [Any]? { return ["userId", "email", "address", "phoneHome", "phoneMobile", "fullname", "status", "createdAt", "imageURL", "thumbImageURL", "postcode", "phoneMobileCountryCode", "state", "country", "birthdayText", "genderText", "fleets"] } open func jsonPatch() -> [String: Any] { var dicto = [String: Any]() if let address = address{ dicto["address"] = address } if let phoneHome = phoneHome{ dicto["phone_home"] = phoneHome } if let phoneMobile = phoneMobile{ dicto["phone_mobile"] = phoneMobile } if let fullname = fullname{ dicto["fullname"] = fullname } if let emergencyFullName = emergencyFullName{ dicto["meta.emergency.fullname"] = emergencyFullName } if let emergencyPhoneHome = emergencyPhoneHome{ dicto["meta.emergency.phone.home"] = emergencyPhoneHome } if let emergencyPhoneMobile = emergencyPhoneMobile{ dicto["meta.emergency.phone.mobile"] = emergencyPhoneMobile } return dicto } // MARK: Image open func updateImage(_ image: KMImage) { self.image = image } open func image(completion: @escaping (_ image: KMImage) -> Void){ guard imageURL != nil else { return } if let image = image { completion(image) }else if let path = NSURL(string: imageURL)?.lastPathComponent, let image = KTCacheManager.shared.image(for: path){ self.image = image completion(image) }else{ if isLoadingImage { imageBlocks.append(completion) }else{ isLoadingImage = true ImageRequest.shared.requestImage(path: imageURL, completion: { (image) in self.image = image self.isLoadingImage = false for block in self.imageBlocks{ block(image!) } completion(image!) }, failure: { (error) in KatsanaAPI.shared.log.error("Error requesting user image \(self.email)") self.isLoadingImage = false }) } } } open func thumbImage(completion: @escaping (_ image: KMImage) -> Void){ guard thumbImageURL != nil else { return } if let image = thumbImage { completion(image) }else if let path = NSURL(string: thumbImageURL)?.lastPathComponent, let image = KTCacheManager.shared.image(for: path){ completion(image) }else{ if isLoadingThumbImage { thumbImageBlocks.append(completion) }else{ isLoadingThumbImage = true ImageRequest.shared.requestImage(path: thumbImageURL, completion: { (image) in self.thumbImage = image self.isLoadingThumbImage = false for block in self.thumbImageBlocks{ block(image!) } completion(image!) }, failure: { (error) in KatsanaAPI.shared.log.error("Error requesting user thumb image \(self.email)") self.isLoadingThumbImage = false }) } } } // MARK: helper open func fleet(id: Int) -> Fleet!{ for fleet in fleets{ if fleet.fleetId == id{ return fleet } } return nil } open func profileProgress() -> CGFloat { var progressCount :CGFloat = 0 let totalCount:CGFloat = 8 - 1 if let fullname = fullname, fullname.count > 0 { progressCount += 1 } if let phoneNumber = phoneMobile, phoneNumber.count > 0 { progressCount += 1 } // if (birthday) != nil{ // progressCount += 1 // } if let address = address, address.count > 0{ progressCount += 1 } if let country = country, country.count > 0{ progressCount += 1 } if let postcode = postcode, postcode.count > 0{ progressCount += 1 } if gender != .unknown{ progressCount += 1 } if let imageURL = imageURL, imageURL.count > 0{ progressCount += 1 }else if image != nil{ progressCount += 1 } let progress = progressCount/totalCount return progress } func isPhoneNumber(_ text: String) -> Bool { if text.count < 3 { return false } let set = CharacterSet(charactersIn: "+0123456789 ") if text.trimmingCharacters(in: set) == ""{ return true } return false } open func date(from string: String) -> Date! { return KTUser.dateFormatter.date(from: string) } }
fc698f0e36f160153f19c31eb8f9dfdb
29.304029
235
0.520005
false
false
false
false
PerfectServers/Perfect-Authentication-Server
refs/heads/master
Sources/PerfectAuthServer/handlers/Handlers.swift
apache-2.0
1
// // Handlers.swift // Perfect-App-Template // // Created by Jonathan Guthrie on 2017-02-20. // Copyright (C) 2017 PerfectlySoft, Inc. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectHTTP import StORM import PerfectLocalAuthentication class Handlers { // Basic "main" handler - simply outputs "Hello, world!" static func main(data: [String:Any]) throws -> RequestHandler { return { request, response in let users = Account() try? users.findAll() if users.rows().count == 0 { response.redirect(path: "/initialize") response.completed() return } var context: [String : Any] = ["title": configTitle] if let i = request.session?.userid, !i.isEmpty { context["authenticated"] = true } // add app config vars for i in Handlers.extras(request) { context[i.0] = i.1 } for i in Handlers.appExtras(request) { context[i.0] = i.1 } response.renderMustache(template: request.documentRoot + "/views/index.mustache", context: context) } } }
e9bb162173e022e798317c299015ed7c
26.72
102
0.605339
false
false
false
false
royratcliffe/HypertextApplicationLanguage
refs/heads/master
Sources/Link+Equatable.swift
mit
1
// HypertextApplicationLanguage Link+Equatable.swift // // Copyright © 2016, Roy Ratcliffe, Pioneering Software, United Kingdom // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the “Software”), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS,” WITHOUT WARRANTY OF ANY KIND, EITHER // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO // EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES // OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // //------------------------------------------------------------------------------ extension Link: Equatable { /// - returns: Answers `true` if this `Link` compares equal to another. public static func == (lhs: Link, rhs: Link) -> Bool { return lhs.rel == rhs.rel && lhs.href == rhs.href && lhs.name == rhs.name && lhs.title == rhs.title && lhs.hreflang == rhs.hreflang && lhs.profile == rhs.profile } }
21e24c79b07f216820e41fc4043b1157
45.513514
80
0.665892
false
false
false
false
StravaKit/StravaKit
refs/heads/master
Sources/StravaClub.swift
mit
2
// // StravaClub.swift // StravaKit // // Created by Brennan Stehling on 8/22/16. // Copyright © 2016 SmallSharpTools LLC. All rights reserved. // import Foundation public enum ClubResourcePath: String { case Club = "/api/v3/clubs/:id" case Clubs = "/api/v3/athlete/clubs" } public extension Strava { /** Gets club detail. ```swift Strava.getClub(1) { (club, error) in } ``` Docs: http://strava.github.io/api/v3/clubs/#get-details */ @discardableResult public static func getClub(_ clubId: Int, completionHandler:((_ club: Club?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = replaceId(id: clubId, in: ClubResourcePath.Club.rawValue) return request(.GET, authenticated: true, path: path, params: nil) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleClubResponse(response, completionHandler: completionHandler) } } /** Gets clubs for current athlete. ```swift Strava.getClubs { (clubs, error) in } ``` Docs: http://strava.github.io/api/v3/clubs/#get-athletes */ @discardableResult public static func getClubs(_ page: Page? = nil, completionHandler:((_ clubs: [Club]?, _ error: NSError?) -> ())?) -> URLSessionTask? { let path = ClubResourcePath.Clubs.rawValue var params: ParamsDictionary? = nil if let page = page { params = [ PageKey: page.page, PerPageKey: page.perPage ] } return request(.GET, authenticated: true, path: path, params: params) { (response, error) in if let error = error { DispatchQueue.main.async { completionHandler?(nil, error) } return } handleClubsResponse(response, completionHandler: completionHandler) } } // MARK: - Internal Functions - internal static func handleClubResponse(_ response: Any?, completionHandler:((_ club: Club?, _ error: NSError?) -> ())?) { if let dictionary = response as? JSONDictionary, let club = Club(dictionary: dictionary) { DispatchQueue.main.async { completionHandler?(club, nil) } } else { DispatchQueue.main.async { let error = Strava.error(.invalidResponse, reason: "Invalid Response") completionHandler?(nil, error) } } } internal static func handleClubsResponse(_ response: Any?, completionHandler:((_ clubs: [Club]?, _ error: NSError?) -> ())?) { if let dictionaries = response as? JSONArray { let clubs = Club.clubs(dictionaries) DispatchQueue.main.async { completionHandler?(clubs, nil) } } else { DispatchQueue.main.async { let error = Strava.error(.invalidResponse, reason: "Invalid Response") completionHandler?(nil, error) } } } }
348ed667140766cf37be8f4c0429e75f
29.12963
139
0.55378
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Tool/Sources/ToolKit/General/UserPropertyRecorder/StandardUserProperty.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation /// Can be used to keep any key-value that doesn't require obfuscation public struct StandardUserProperty: UserProperty { public let key: UserPropertyKey public let value: String public let truncatesValueIfNeeded: Bool public init(key: Key, value: String, truncatesValueIfNeeded: Bool = false) { self.key = key self.value = value self.truncatesValueIfNeeded = truncatesValueIfNeeded } } extension StandardUserProperty: Hashable { public static func == (lhs: StandardUserProperty, rhs: StandardUserProperty) -> Bool { lhs.key.rawValue == rhs.key.rawValue } public func hash(into hasher: inout Hasher) { hasher.combine(key.rawValue) } } extension StandardUserProperty { /// A key for which a hashed user property is being recorded public enum Key: String, UserPropertyKey { case walletCreationDate = "creation_date" case kycCreationDate = "kyc_creation_date" case kycUpdateDate = "kyc_updated_date" case kycLevel = "kyc_level" case emailVerified = "email_verified" case twoFAEnabled = "two_fa_enabled" case totalBalance = "total_balance" case fundedCoins = "funded_coins" } }
68fe69b344f3898e22b8ab56500b4d14
31.04878
90
0.687976
false
false
false
false
shadanan/mado
refs/heads/master
Antlr4Runtime/Sources/Antlr4/BufferedTokenStream.swift
mit
1
/// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// This implementation of {@link org.antlr.v4.runtime.TokenStream} loads tokens from a /// {@link org.antlr.v4.runtime.TokenSource} on-demand, and places the tokens in a buffer to provide /// access to any previous token by index. /// /// <p> /// This token stream ignores the value of {@link org.antlr.v4.runtime.Token#getChannel}. If your /// parser requires the token stream filter tokens to only those on a particular /// channel, such as {@link org.antlr.v4.runtime.Token#DEFAULT_CHANNEL} or /// {@link org.antlr.v4.runtime.Token#HIDDEN_CHANNEL}, use a filtering token stream such a /// {@link org.antlr.v4.runtime.CommonTokenStream}.</p> public class BufferedTokenStream: TokenStream { /// The {@link org.antlr.v4.runtime.TokenSource} from which tokens for this stream are fetched. internal var tokenSource: TokenSource /// A collection of all tokens fetched from the token source. The list is /// considered a complete view of the input once {@link #fetchedEOF} is set /// to {@code true}. internal var tokens: Array<Token> = Array<Token>() // Array<Token>(100 /// The index into {@link #tokens} of the current token (next token to /// {@link #consume}). {@link #tokens}{@code [}{@link #p}{@code ]} should be /// {@link #LT LT(1)}. /// /// <p>This field is set to -1 when the stream is first constructed or when /// {@link #setTokenSource} is called, indicating that the first token has /// not yet been fetched from the token source. For additional information, /// see the documentation of {@link org.antlr.v4.runtime.IntStream} for a description of /// Initializing Methods.</p> internal var p: Int = -1 /// Indicates whether the {@link org.antlr.v4.runtime.Token#EOF} token has been fetched from /// {@link #tokenSource} and added to {@link #tokens}. This field improves /// performance for the following cases: /// /// <ul> /// <li>{@link #consume}: The lookahead check in {@link #consume} to prevent /// consuming the EOF symbol is optimized by checking the values of /// {@link #fetchedEOF} and {@link #p} instead of calling {@link #LA}.</li> /// <li>{@link #fetch}: The check to prevent adding multiple EOF symbols into /// {@link #tokens} is trivial with this field.</li> /// <ul> internal var fetchedEOF: Bool = false public init(_ tokenSource: TokenSource) { self.tokenSource = tokenSource } public func getTokenSource() -> TokenSource { return tokenSource } public func index() -> Int { return p } public func mark() -> Int { return 0 } public func release(_ marker: Int) { // no resources to release } public func reset() throws { try seek(0) } public func seek(_ index: Int) throws { try lazyInit() p = try adjustSeekIndex(index) } public func size() -> Int { return tokens.count } public func consume() throws { var skipEofCheck: Bool if p >= 0 { if fetchedEOF { // the last token in tokens is EOF. skip check if p indexes any // fetched token except the last. skipEofCheck = p < tokens.count - 1 } else { // no EOF token in tokens. skip check if p indexes a fetched token. skipEofCheck = p < tokens.count } } else { // not yet initialized skipEofCheck = false } if try !skipEofCheck && LA(1) == BufferedTokenStream.EOF { throw ANTLRError.illegalState(msg: "cannot consume EOF") //RuntimeException("cannot consume EOF") //throw ANTLRError.IllegalState /* throw IllegalStateException("cannot consume EOF"); */ } if try sync(p + 1) { p = try adjustSeekIndex(p + 1) } } /// Make sure index {@code i} in tokens has a token. /// /// - returns: {@code true} if a token is located at index {@code i}, otherwise /// {@code false}. /// - seealso: #get(int i) @discardableResult internal func sync(_ i: Int) throws -> Bool { assert(i >= 0, "Expected: i>=0") let n: Int = i - tokens.count + 1 // how many more elements we need? //print("sync("+i+") needs "+n); if n > 0 { let fetched: Int = try fetch(n) return fetched >= n } return true } /// Add {@code n} elements to buffer. /// /// - returns: The actual number of elements added to the buffer. internal func fetch(_ n: Int) throws -> Int { if fetchedEOF { return 0 } for i in 0..<n { let t: Token = try tokenSource.nextToken() if t is WritableToken { (t as! WritableToken).setTokenIndex(tokens.count) } tokens.append(t) //add if t.getType() == BufferedTokenStream.EOF { fetchedEOF = true return i + 1 } } return n } public func get(_ i: Int) throws -> Token { if i < 0 || i >= tokens.count { let index = tokens.count - 1 throw ANTLRError.indexOutOfBounds(msg: "token index \(i) out of range 0..\(index)") } return tokens[i] //tokens[i] } /// Get all tokens from start..stop inclusively public func get(_ start: Int,_ stop: Int) throws -> Array<Token>? { var stop = stop if start < 0 || stop < 0 { return nil } try lazyInit() var subset: Array<Token> = Array<Token>() if stop >= tokens.count { stop = tokens.count - 1 } for i in start...stop { let t: Token = tokens[i] if t.getType() == BufferedTokenStream.EOF { break } subset.append(t) } return subset } //TODO: LT(i)!.getType(); public func LA(_ i: Int) throws -> Int { return try LT(i)!.getType() } internal func LB(_ k: Int) throws -> Token? { if (p - k) < 0 { return nil } return tokens[p - k] } public func LT(_ k: Int) throws -> Token? { try lazyInit() if k == 0 { return nil } if k < 0 { return try LB(-k) } let i: Int = p + k - 1 try sync(i) if i >= tokens.count { // return EOF token // EOF must be last token return tokens[tokens.count - 1] } // if ( i>range ) range = i; return tokens[i] } /// Allowed derived classes to modify the behavior of operations which change /// the current stream position by adjusting the target token index of a seek /// operation. The default implementation simply returns {@code i}. If an /// exception is thrown in this method, the current stream index should not be /// changed. /// /// <p>For example, {@link org.antlr.v4.runtime.CommonTokenStream} overrides this method to ensure that /// the seek target is always an on-channel token.</p> /// /// - parameter i: The target token index. /// - returns: The adjusted target token index. internal func adjustSeekIndex(_ i: Int) throws -> Int { return i } internal final func lazyInit() throws { if p == -1 { try setup() } } internal func setup() throws { try sync(0) p = try adjustSeekIndex(0) } /// Reset this token stream by setting its token source. public func setTokenSource(_ tokenSource: TokenSource) { self.tokenSource = tokenSource tokens.removeAll() p = -1 fetchedEOF = false } public func getTokens() -> Array<Token> { return tokens } public func getTokens(_ start: Int, _ stop: Int) throws -> Array<Token>? { return try getTokens(start, stop, nil) } /// Given a start and stop index, return a List of all tokens in /// the token type BitSet. Return null if no tokens were found. This /// method looks at both on and off channel tokens. public func getTokens(_ start: Int, _ stop: Int, _ types: Set<Int>?) throws -> Array<Token>? { try lazyInit() if start < 0 || stop >= tokens.count || stop < 0 || start >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "start \(start) or stop \(stop) not in 0..\(tokens.count - 1)") } if start > stop { return nil } var filteredTokens: Array<Token> = Array<Token>() for i in start...stop { let t: Token = tokens[i] if let types = types , !types.contains(t.getType()) { }else { filteredTokens.append(t) } } if filteredTokens.isEmpty { return nil //filteredTokens = nil; } return filteredTokens } public func getTokens(_ start: Int, _ stop: Int, _ ttype: Int) throws -> Array<Token>? { //TODO Set<Int> initialCapacity var s: Set<Int> = Set<Int>() s.insert(ttype) //s.append(ttype); return try getTokens(start, stop, s) } /// Given a starting index, return the index of the next token on channel. /// Return {@code i} if {@code tokens[i]} is on channel. Return the index of /// the EOF token if there are no tokens on channel between {@code i} and /// EOF. internal func nextTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) if i >= size() { return size() - 1 } var token: Token = tokens[i] while token.getChannel() != channel { if token.getType() == BufferedTokenStream.EOF { return i } i += 1 try sync(i) token = tokens[i] } return i } /// Given a starting index, return the index of the previous token on /// channel. Return {@code i} if {@code tokens[i]} is on channel. Return -1 /// if there are no tokens on channel between {@code i} and 0. /// /// <p> /// If {@code i} specifies an index at or after the EOF token, the EOF token /// index is returned. This is due to the fact that the EOF token is treated /// as though it were on every channel.</p> internal func previousTokenOnChannel(_ i: Int, _ channel: Int) throws -> Int { var i = i try sync(i) if i >= size() { // the EOF token is on every channel return size() - 1 } while i >= 0 { let token: Token = tokens[i] if token.getType() == BufferedTokenStream.EOF || token.getChannel() == channel { return i } i -= 1 } return i } /// Collect all tokens on specified channel to the right of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL or /// EOF. If channel is -1, find any non default channel token. public func getHiddenTokensToRight(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)") } let nextOnChannel: Int = try nextTokenOnChannel(tokenIndex + 1, Lexer.DEFAULT_TOKEN_CHANNEL) var to: Int let from: Int = tokenIndex + 1 // if none onchannel to right, nextOnChannel=-1 so set to = last token if nextOnChannel == -1 { to = size() - 1 } else { to = nextOnChannel } return filterForChannel(from, to, channel) } /// Collect all hidden tokens (any off-default channel) to the right of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL /// or EOF. public func getHiddenTokensToRight(_ tokenIndex: Int) throws -> Array<Token>? { return try getHiddenTokensToRight(tokenIndex, -1) } /// Collect all tokens on specified channel to the left of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. /// If channel is -1, find any non default channel token. public func getHiddenTokensToLeft(_ tokenIndex: Int, _ channel: Int) throws -> Array<Token>? { try lazyInit() if tokenIndex < 0 || tokenIndex >= tokens.count { throw ANTLRError.indexOutOfBounds(msg: "\(tokenIndex) not in 0..\(tokens.count - 1)") //RuntimeException("\(tokenIndex) not in 0..\(tokens.count-1)") //throw ANTLRError.IndexOutOfBounds /* throw IndexOutOfBoundsException(tokenIndex+" not in 0.."+(tokens.count-1)); */ } if tokenIndex == 0 { // obviously no tokens can appear before the first token return nil } let prevOnChannel: Int = try previousTokenOnChannel(tokenIndex - 1, Lexer.DEFAULT_TOKEN_CHANNEL) if prevOnChannel == tokenIndex - 1 { return nil } // if none onchannel to left, prevOnChannel=-1 then from=0 let from: Int = prevOnChannel + 1 let to: Int = tokenIndex - 1 return filterForChannel(from, to, channel) } /// Collect all hidden tokens (any off-default channel) to the left of /// the current token up until we see a token on DEFAULT_TOKEN_CHANNEL. public func getHiddenTokensToLeft(_ tokenIndex: Int) throws -> Array<Token>? { return try getHiddenTokensToLeft(tokenIndex, -1) } internal func filterForChannel(_ from: Int, _ to: Int, _ channel: Int) -> Array<Token>? { var hidden: Array<Token> = Array<Token>() for i in from...to { let t: Token = tokens[i] if channel == -1 { if t.getChannel() != Lexer.DEFAULT_TOKEN_CHANNEL { hidden.append(t) } } else { if t.getChannel() == channel { hidden.append(t) } } } if hidden.count == 0 { return nil } return hidden } public func getSourceName() -> String { return tokenSource.getSourceName() } /// Get the text of all tokens in this buffer. public func getText() throws -> String { return try getText(Interval.of(0, size() - 1)) } public func getText(_ interval: Interval) throws -> String { let start: Int = interval.a var stop: Int = interval.b if start < 0 || stop < 0 { return "" } try fill() if stop >= tokens.count { stop = tokens.count - 1 } let buf: StringBuilder = StringBuilder() for i in start...stop { let t: Token = tokens[i] if t.getType() == BufferedTokenStream.EOF { break } buf.append(t.getText()!) } return buf.toString() } public func getText(_ ctx: RuleContext) throws -> String { return try getText(ctx.getSourceInterval()) } public func getText(_ start: Token?, _ stop: Token?) throws -> String { if let start = start, let stop = stop { return try getText(Interval.of(start.getTokenIndex(), stop.getTokenIndex())) } return "" } /// Get all tokens from lexer until EOF public func fill() throws { try lazyInit() let blockSize: Int = 1000 while true { let fetched: Int = try fetch(blockSize) if fetched < blockSize { return } } } }
4e0ac8aa07a8c7b4ebae71ca31b726c9
31.005952
129
0.560598
false
false
false
false
Zewo/Zewo
refs/heads/master
Sources/Media/MediaType/MediaType.swift
mit
1
import Foundation enum MediaTypeError : Error { case malformedMediaTypeString } public struct MediaType { public let type: String public let subtype: String public let parameters: [String: String] public init(type: String, subtype: String, parameters: [String: String] = [:]) { self.type = type self.subtype = subtype self.parameters = parameters } public init(string: String) throws { let mediaTypeTokens = string.components(separatedBy: ";") guard let mediaType = mediaTypeTokens.first else { throw MediaTypeError.malformedMediaTypeString } var parameters: [String: String] = [:] if mediaTypeTokens.count == 2 { let parametersTokens = mediaTypeTokens[1].trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: " ") for parametersToken in parametersTokens { let parameterTokens = parametersToken.components(separatedBy: "=") if parameterTokens.count == 2 { let key = parameterTokens[0] let value = parameterTokens[1] parameters[key] = value } } } let tokens = mediaType.components(separatedBy: "/") guard tokens.count == 2 else { throw MediaTypeError.malformedMediaTypeString } self.init( type: tokens[0].lowercased(), subtype: tokens[1].lowercased(), parameters: parameters ) } public static func parse(acceptHeader: String) -> [MediaType] { var acceptedMediaTypes: [MediaType] = [] let acceptedTypesString = acceptHeader.components(separatedBy: ",") for acceptedTypeString in acceptedTypesString { let acceptedTypeTokens = acceptedTypeString.components(separatedBy: ";") if acceptedTypeTokens.count >= 1 { let mediaTypeString = acceptedTypeTokens[0].trimmingCharacters(in: .whitespacesAndNewlines) if let acceptedMediaType = try? MediaType(string: mediaTypeString) { acceptedMediaTypes.append(acceptedMediaType) } } } return acceptedMediaTypes } public func matches(other mediaType: MediaType) -> Bool { if type == "*" || mediaType.type == "*" { return true } if type == mediaType.type { if subtype == "*" || mediaType.subtype == "*" { return true } return subtype == mediaType.subtype } return false } /// Returns `true` if the media type matches any of the media types /// in the `mediaTypes` collection. /// /// - Parameter mediaTypes: Collection of media types. /// - Returns: Boolean indicating if the media type matches any of the /// media types in the collection. public func matches<C : Collection>( any mediaTypes: C ) -> Bool where C.Iterator.Element == MediaType { for mediaType in mediaTypes { if matches(other: mediaType) { return true } } return false } /// Creates a `MediaType` from a file extension, if possible. /// /// - Parameter fileExtension: File extension (ie., "txt", "json", "html"). /// - Returns: Newly created `MediaType`. public static func from(fileExtension: String) -> MediaType? { guard let mediaType = fileExtensionMediaTypeMapping[fileExtension] else { return nil } return try? MediaType(string: mediaType) } } extension MediaType : CustomStringConvertible { /// :nodoc: public var description: String { var string = "\(type)/\(subtype)" if !parameters.isEmpty { string += parameters.reduce(";") { $0 + " \($1.0)=\($1.1)" } } return string } } extension MediaType : Hashable { /// :nodoc: public func hash(into hasher: inout Hasher) { hasher.combine(type) hasher.combine(subtype) } } extension MediaType : Equatable { /// :nodoc: public static func == (lhs: MediaType, rhs: MediaType) -> Bool { return lhs.hashValue == rhs.hashValue } } public extension MediaType { /// Any media type (*/*). static let any = MediaType(type: "*", subtype: "*") /// Plain text media type. static let plainText = MediaType(type: "text", subtype: "plain", parameters: ["charset": "utf-8"]) /// HTML media type. static let html = MediaType(type: "text", subtype: "html", parameters: ["charset": "utf-8"]) /// CSS media type. static let css = MediaType(type: "text", subtype: "css", parameters: ["charset": "utf-8"]) /// URL encoded form media type. static let urlEncodedForm = MediaType(type: "application", subtype: "x-www-form-urlencoded", parameters: ["charset": "utf-8"]) /// JSON media type. static let json = MediaType(type: "application", subtype: "json", parameters: ["charset": "utf-8"]) /// XML media type. static let xml = MediaType(type: "application", subtype: "xml", parameters: ["charset": "utf-8"]) /// DTD media type. static let dtd = MediaType(type: "application", subtype: "xml-dtd", parameters: ["charset": "utf-8"]) /// PDF data. static let pdf = MediaType(type: "application", subtype: "pdf") /// Zip file. static let zip = MediaType(type: "application", subtype: "zip") /// tar file. static let tar = MediaType(type: "application", subtype: "x-tar") /// Gzip file. static let gzip = MediaType(type: "application", subtype: "x-gzip") /// Bzip2 file. static let bzip2 = MediaType(type: "application", subtype: "x-bzip2") /// Binary data. static let binary = MediaType(type: "application", subtype: "octet-stream") /// GIF image. static let gif = MediaType(type: "image", subtype: "gif") /// JPEG image. static let jpeg = MediaType(type: "image", subtype: "jpeg") /// PNG image. static let png = MediaType(type: "image", subtype: "png") /// SVG image. static let svg = MediaType(type: "image", subtype: "svg+xml") /// Basic audio. static let audio = MediaType(type: "audio", subtype: "basic") /// MIDI audio. static let midi = MediaType(type: "audio", subtype: "x-midi") /// MP3 audio. static let mp3 = MediaType(type: "audio", subtype: "mpeg") /// Wave audio. static let wave = MediaType(type: "audio", subtype: "wav") /// OGG audio. static let ogg = MediaType(type: "audio", subtype: "vorbis") /// AVI video. static let avi = MediaType(type: "video", subtype: "avi") /// MPEG video. static let mpeg = MediaType(type: "video", subtype: "mpeg") } let fileExtensionMediaTypeMapping: [String: String] = [ "ez": "application/andrew-inset", "anx": "application/annodex", "atom": "application/atom+xml", "atomcat": "application/atomcat+xml", "atomsrv": "application/atomserv+xml", "lin": "application/bbolin", "cu": "application/cu-seeme", "davmount": "application/davmount+xml", "dcm": "application/dicom", "tsp": "application/dsptype", "es": "application/ecmascript", "spl": "application/futuresplash", "hta": "application/hta", "jar": "application/java-archive", "ser": "application/java-serialized-object", "class": "application/java-vm", "js": "application/javascript", "json": "application/json", "m3g": "application/m3g", "hqx": "application/mac-binhex40", "cpt": "application/mac-compactpro", "nb": "application/mathematica", "nbp": "application/mathematica", "mbox": "application/mbox", "mdb": "application/msaccess", "doc": "application/msword", "dot": "application/msword", "mxf": "application/mxf", "bin": "application/octet-stream", "oda": "application/oda", "ogx": "application/ogg", "one": "application/onenote", "onetoc2": "application/onenote", "onetmp": "application/onenote", "onepkg": "application/onenote", "pdf": "application/pdf", "pgp": "application/pgp-encrypted", "key": "application/pgp-keys", "sig": "application/pgp-signature", "prf": "application/pics-rules", "ps": "application/postscript", "ai": "application/postscript", "eps": "application/postscript", "epsi": "application/postscript", "epsf": "application/postscript", "eps2": "application/postscript", "eps3": "application/postscript", "rar": "application/rar", "rdf": "application/rdf+xml", "rtf": "application/rtf", "stl": "application/sla", "smi": "application/smil+xml", "smil": "application/smil+xml", "xhtml": "application/xhtml+xml", "xht": "application/xhtml+xml", "xml": "application/xml", "xsd": "application/xml", "xsl": "application/xslt+xml", "xslt": "application/xslt+xml", "xspf": "application/xspf+xml", "zip": "application/zip", "apk": "application/vnd.android.package-archive", "cdy": "application/vnd.cinderella", "kml": "application/vnd.google-earth.kml+xml", "kmz": "application/vnd.google-earth.kmz", "xul": "application/vnd.mozilla.xul+xml", "xls": "application/vnd.ms-excel", "xlb": "application/vnd.ms-excel", "xlt": "application/vnd.ms-excel", "xlam": "application/vnd.ms-excel.addin.macroEnabled.12", "xlsb": "application/vnd.ms-excel.sheet.binary.macroEnabled.12", "xlsm": "application/vnd.ms-excel.sheet.macroEnabled.12", "xltm": "application/vnd.ms-excel.template.macroEnabled.12", "eot": "application/vnd.ms-fontobject", "thmx": "application/vnd.ms-officetheme", "cat": "application/vnd.ms-pki.seccat", "ppt": "application/vnd.ms-powerpoint", "pps": "application/vnd.ms-powerpoint", "ppam": "application/vnd.ms-powerpoint.addin.macroEnabled.12", "pptm": "application/vnd.ms-powerpoint.presentation.macroEnabled.12", "sldm": "application/vnd.ms-powerpoint.slide.macroEnabled.12", "ppsm": "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", "potm": "application/vnd.ms-powerpoint.template.macroEnabled.12", "docm": "application/vnd.ms-word.document.macroEnabled.12", "dotm": "application/vnd.ms-word.template.macroEnabled.12", "odc": "application/vnd.oasis.opendocument.chart", "odb": "application/vnd.oasis.opendocument.database", "odf": "application/vnd.oasis.opendocument.formula", "odg": "application/vnd.oasis.opendocument.graphics", "otg": "application/vnd.oasis.opendocument.graphics-template", "odi": "application/vnd.oasis.opendocument.image", "odp": "application/vnd.oasis.opendocument.presentation", "otp": "application/vnd.oasis.opendocument.presentation-template", "ods": "application/vnd.oasis.opendocument.spreadsheet", "ots": "application/vnd.oasis.opendocument.spreadsheet-template", "odt": "application/vnd.oasis.opendocument.text", "odm": "application/vnd.oasis.opendocument.text-master", "ott": "application/vnd.oasis.opendocument.text-template", "oth": "application/vnd.oasis.opendocument.text-web", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "sldx": "application/vnd.openxmlformats-officedocument.presentationml.slide", "ppsx": "application/vnd.openxmlformats-officedocument.presentationml.slideshow", "potx": "application/vnd.openxmlformats-officedocument.presentationml.template", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "xltx": "application/vnd.openxmlformats-officedocument.spreadsheetml.template", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "dotx": "application/vnd.openxmlformats-officedocument.wordprocessingml.template", "cod": "application/vnd.rim.cod", "mmf": "application/vnd.smaf", "sdc": "application/vnd.stardivision.calc", "sds": "application/vnd.stardivision.chart", "sda": "application/vnd.stardivision.draw", "sdd": "application/vnd.stardivision.impress", "sdf": "application/vnd.stardivision.math", "sdw": "application/vnd.stardivision.writer", "sgl": "application/vnd.stardivision.writer-global", "sxc": "application/vnd.sun.xml.calc", "stc": "application/vnd.sun.xml.calc.template", "sxd": "application/vnd.sun.xml.draw", "std": "application/vnd.sun.xml.draw.template", "sxi": "application/vnd.sun.xml.impress", "sti": "application/vnd.sun.xml.impress.template", "sxm": "application/vnd.sun.xml.math", "sxw": "application/vnd.sun.xml.writer", "sxg": "application/vnd.sun.xml.writer.global", "stw": "application/vnd.sun.xml.writer.template", "sis": "application/vnd.symbian.install", "cap": "application/vnd.tcpdump.pcap", "pcap": "application/vnd.tcpdump.pcap", "vsd": "application/vnd.visio", "wbxml": "application/vnd.wap.wbxml", "wmlc": "application/vnd.wap.wmlc", "wmlsc": "application/vnd.wap.wmlscriptc", "wpd": "application/vnd.wordperfect", "wp5": "application/vnd.wordperfect5.1", "wk": "application/x-123", "7z": "application/x-7z-compressed", "abw": "application/x-abiword", "dmg": "application/x-apple-diskimage", "bcpio": "application/x-bcpio", "torrent": "application/x-bittorrent", "cab": "application/x-cab", "cbr": "application/x-cbr", "cbz": "application/x-cbz", "cdf": "application/x-cdf", "cda": "application/x-cdf", "vcd": "application/x-cdlink", "pgn": "application/x-chess-pgn", "mph": "application/x-comsol", "cpio": "application/x-cpio", "csh": "application/x-csh", "deb": "application/x-debian-package", "udeb": "application/x-debian-package", "dcr": "application/x-director", "dir": "application/x-director", "dxr": "application/x-director", "dms": "application/x-dms", "wad": "application/x-doom", "dvi": "application/x-dvi", "pfa": "application/x-font", "pfb": "application/x-font", "gsf": "application/x-font", "pcf": "application/x-font", "pcf.Z": "application/x-font", "woff": "application/x-font-woff", "mm": "application/x-freemind", "gan": "application/x-ganttproject", "gnumeric": "application/x-gnumeric", "sgf": "application/x-go-sgf", "gcf": "application/x-graphing-calculator", "gtar": "application/x-gtar", "tgz": "application/x-gtar-compressed", "taz": "application/x-gtar-compressed", "hdf": "application/x-hdf", "hwp": "application/x-hwp", "ica": "application/x-ica", "info": "application/x-info", "ins": "application/x-internet-signup", "isp": "application/x-internet-signup", "iii": "application/x-iphone", "iso": "application/x-iso9660-image", "jam": "application/x-jam", "jnlp": "application/x-java-jnlp-file", "jmz": "application/x-jmol", "chrt": "application/x-kchart", "kil": "application/x-killustrator", "skp": "application/x-koan", "skd": "application/x-koan", "skt": "application/x-koan", "skm": "application/x-koan", "kpr": "application/x-kpresenter", "kpt": "application/x-kpresenter", "ksp": "application/x-kspread", "kwd": "application/x-kword", "kwt": "application/x-kword", "latex": "application/x-latex", "lha": "application/x-lha", "lyx": "application/x-lyx", "lzh": "application/x-lzh", "lzx": "application/x-lzx", "frm": "application/x-maker", "maker": "application/x-maker", "frame": "application/x-maker", "fm": "application/x-maker", "fb": "application/x-maker", "book": "application/x-maker", "fbdoc": "application/x-maker", "md5": "application/x-md5", "mif": "application/x-mif", "m3u8": "application/x-mpegURL", "wmd": "application/x-ms-wmd", "wmz": "application/x-ms-wmz", "com": "application/x-msdos-program", "exe": "application/x-msdos-program", "bat": "application/x-msdos-program", "dll": "application/x-msdos-program", "msi": "application/x-msi", "nc": "application/x-netcdf", "pac": "application/x-ns-proxy-autoconfig", "dat": "application/x-ns-proxy-autoconfig", "nwc": "application/x-nwc", "o": "application/x-object", "oza": "application/x-oz-application", "p7r": "application/x-pkcs7-certreqresp", "crl": "application/x-pkcs7-crl", "pyc": "application/x-python-code", "pyo": "application/x-python-code", "qgs": "application/x-qgis", "shp": "application/x-qgis", "shx": "application/x-qgis", "qtl": "application/x-quicktimeplayer", "rdp": "application/x-rdp", "rpm": "application/x-redhat-package-manager", "rss": "application/x-rss+xml", "rb": "application/x-ruby", "sci": "application/x-scilab", "sce": "application/x-scilab", "xcos": "application/x-scilab-xcos", "sh": "application/x-sh", "sha1": "application/x-sha1", "shar": "application/x-shar", "swf": "application/x-shockwave-flash", "swfl": "application/x-shockwave-flash", "scr": "application/x-silverlight", "sql": "application/x-sql", "sit": "application/x-stuffit", "sitx": "application/x-stuffit", "sv4cpio": "application/x-sv4cpio", "sv4crc": "application/x-sv4crc", "tar": "application/x-tar", "tcl": "application/x-tcl", "gf": "application/x-tex-gf", "pk": "application/x-tex-pk", "texinfo": "application/x-texinfo", "texi": "application/x-texinfo", "~": "application/x-trash", "%": "application/x-trash", "bak": "application/x-trash", "old": "application/x-trash", "sik": "application/x-trash", "t": "application/x-troff", "tr": "application/x-troff", "roff": "application/x-troff", "man": "application/x-troff-man", "me": "application/x-troff-me", "ms": "application/x-troff-ms", "ustar": "application/x-ustar", "src": "application/x-wais-source", "wz": "application/x-wingz", "crt": "application/x-x509-ca-cert", "xcf": "application/x-xcf", "fig": "application/x-xfig", "xpi": "application/x-xpinstall", "amr": "audio/amr", "awb": "audio/amr-wb", "axa": "audio/annodex", "au": "audio/basic", "snd": "audio/basic", "csd": "audio/csound", "orc": "audio/csound", "sco": "audio/csound", "flac": "audio/flac", "mid": "audio/midi", "midi": "audio/midi", "kar": "audio/midi", "mpga": "audio/mpeg", "mpega": "audio/mpeg", "mp2": "audio/mpeg", "mp3": "audio/mpeg", "m4a": "audio/mpeg", "m3u": "audio/mpegurl", "oga": "audio/ogg", "ogg": "audio/ogg", "opus": "audio/ogg", "spx": "audio/ogg", "sid": "audio/prs.sid", "aif": "audio/x-aiff", "aiff": "audio/x-aiff", "aifc": "audio/x-aiff", "gsm": "audio/x-gsm", "wma": "audio/x-ms-wma", "wax": "audio/x-ms-wax", "ra": "audio/x-pn-realaudio", "rm": "audio/x-pn-realaudio", "ram": "audio/x-pn-realaudio", "pls": "audio/x-scpls", "sd2": "audio/x-sd2", "wav": "audio/x-wav", "alc": "chemical/x-alchemy", "cac": "chemical/x-cache", "cache": "chemical/x-cache", "csf": "chemical/x-cache-csf", "cbin": "chemical/x-cactvs-binary", "cascii": "chemical/x-cactvs-binary", "ctab": "chemical/x-cactvs-binary", "cdx": "chemical/x-cdx", "cer": "chemical/x-cerius", "c3d": "chemical/x-chem3d", "chm": "chemical/x-chemdraw", "cif": "chemical/x-cif", "cmdf": "chemical/x-cmdf", "cml": "chemical/x-cml", "cpa": "chemical/x-compass", "bsd": "chemical/x-crossfire", "csml": "chemical/x-csml", "csm": "chemical/x-csml", "ctx": "chemical/x-ctx", "cxf": "chemical/x-cxf", "cef": "chemical/x-cxf", "emb": "chemical/x-embl-dl-nucleotide", "embl": "chemical/x-embl-dl-nucleotide", "spc": "chemical/x-galactic-spc", "inp": "chemical/x-gamess-input", "gam": "chemical/x-gamess-input", "gamin": "chemical/x-gamess-input", "fch": "chemical/x-gaussian-checkpoint", "fchk": "chemical/x-gaussian-checkpoint", "cub": "chemical/x-gaussian-cube", "gau": "chemical/x-gaussian-input", "gjc": "chemical/x-gaussian-input", "gjf": "chemical/x-gaussian-input", "gal": "chemical/x-gaussian-log", "gcg": "chemical/x-gcg8-sequence", "gen": "chemical/x-genbank", "hin": "chemical/x-hin", "istr": "chemical/x-isostar", "ist": "chemical/x-isostar", "jdx": "chemical/x-jcamp-dx", "dx": "chemical/x-jcamp-dx", "kin": "chemical/x-kinemage", "mcm": "chemical/x-macmolecule", "mmd": "chemical/x-macromodel-input", "mmod": "chemical/x-macromodel-input", "mol": "chemical/x-mdl-molfile", "rd": "chemical/x-mdl-rdfile", "rxn": "chemical/x-mdl-rxnfile", "sd": "chemical/x-mdl-sdfile", "tgf": "chemical/x-mdl-tgf", "mcif": "chemical/x-mmcif", "mol2": "chemical/x-mol2", "b": "chemical/x-molconn-Z", "gpt": "chemical/x-mopac-graph", "mop": "chemical/x-mopac-input", "mopcrt": "chemical/x-mopac-input", "mpc": "chemical/x-mopac-input", "zmt": "chemical/x-mopac-input", "moo": "chemical/x-mopac-out", "mvb": "chemical/x-mopac-vib", "asn": "chemical/x-ncbi-asn1", "prt": "chemical/x-ncbi-asn1-ascii", "ent": "chemical/x-ncbi-asn1-ascii", "val": "chemical/x-ncbi-asn1-binary", "aso": "chemical/x-ncbi-asn1-binary", "pdb": "chemical/x-pdb", "ros": "chemical/x-rosdal", "sw": "chemical/x-swissprot", "vms": "chemical/x-vamas-iso14976", "vmd": "chemical/x-vmd", "xtel": "chemical/x-xtel", "xyz": "chemical/x-xyz", "gif": "image/gif", "ief": "image/ief", "jp2": "image/jp2", "jpg2": "image/jp2", "jpeg": "image/jpeg", "jpg": "image/jpeg", "jpe": "image/jpeg", "jpm": "image/jpm", "jpx": "image/jpx", "jpf": "image/jpx", "pcx": "image/pcx", "png": "image/png", "svg": "image/svg+xml", "svgz": "image/svg+xml", "tiff": "image/tiff", "tif": "image/tiff", "djvu": "image/vnd.djvu", "djv": "image/vnd.djvu", "ico": "image/vnd.microsoft.icon", "wbmp": "image/vnd.wap.wbmp", "cr2": "image/x-canon-cr2", "crw": "image/x-canon-crw", "ras": "image/x-cmu-raster", "cdr": "image/x-coreldraw", "pat": "image/x-coreldrawpattern", "cdt": "image/x-coreldrawtemplate", "erf": "image/x-epson-erf", "art": "image/x-jg", "jng": "image/x-jng", "bmp": "image/x-ms-bmp", "nef": "image/x-nikon-nef", "orf": "image/x-olympus-orf", "psd": "image/x-photoshop", "pnm": "image/x-portable-anymap", "pbm": "image/x-portable-bitmap", "pgm": "image/x-portable-graymap", "ppm": "image/x-portable-pixmap", "rgb": "image/x-rgb", "xbm": "image/x-xbitmap", "xpm": "image/x-xpixmap", "xwd": "image/x-xwindowdump", "eml": "message/rfc822", "igs": "model/iges", "iges": "model/iges", "msh": "model/mesh", "mesh": "model/mesh", "silo": "model/mesh", "wrl": "model/vrml", "vrml": "model/vrml", "x3dv": "model/x3d+vrml", "x3d": "model/x3d+xml", "x3db": "model/x3d+binary", "appcache": "text/cache-manifest", "ics": "text/calendar", "icz": "text/calendar", "css": "text/css", "csv": "text/csv", "323": "text/h323", "html": "text/html", "htm": "text/html", "shtml": "text/html", "uls": "text/iuls", "mml": "text/mathml", "asc": "text/plain", "txt": "text/plain", "text": "text/plain", "pot": "text/plain", "brf": "text/plain", "srt": "text/plain", "rtx": "text/richtext", "sct": "text/scriptlet", "wsc": "text/scriptlet", "tm": "text/texmacs", "tsv": "text/tab-separated-values", "ttl": "text/turtle", "jad": "text/vnd.sun.j2me.app-descriptor", "wml": "text/vnd.wap.wml", "wmls": "text/vnd.wap.wmlscript", "bib": "text/x-bibtex", "boo": "text/x-boo", "h++": "text/x-c++hdr", "hpp": "text/x-c++hdr", "hxx": "text/x-c++hdr", "hh": "text/x-c++hdr", "c++": "text/x-c++src", "cpp": "text/x-c++src", "cxx": "text/x-c++src", "cc": "text/x-c++src", "h": "text/x-chdr", "htc": "text/x-component", "c": "text/x-csrc", "d": "text/x-dsrc", "diff": "text/x-diff", "patch": "text/x-diff", "hs": "text/x-haskell", "java": "text/x-java", "ly": "text/x-lilypond", "lhs": "text/x-literate-haskell", "moc": "text/x-moc", "p": "text/x-pascal", "pas": "text/x-pascal", "gcd": "text/x-pcs-gcd", "pl": "text/x-perl", "pm": "text/x-perl", "py": "text/x-python", "scala": "text/x-scala", "etx": "text/x-setext", "sfv": "text/x-sfv", "tk": "text/x-tcl", "tex": "text/x-tex", "ltx": "text/x-tex", "sty": "text/x-tex", "cls": "text/x-tex", "vcs": "text/x-vcalendar", "vcf": "text/x-vcard", "3gp": "video/3gpp", "axv": "video/annodex", "dl": "video/dl", "dif": "video/dv", "dv": "video/dv", "fli": "video/fli", "gl": "video/gl", "mpeg": "video/mpeg", "mpg": "video/mpeg", "mpe": "video/mpeg", "ts": "video/MP2T", "mp4": "video/mp4", "qt": "video/quicktime", "mov": "video/quicktime", "ogv": "video/ogg", "webm": "video/webm", "mxu": "video/vnd.mpegurl", "flv": "video/x-flv", "lsf": "video/x-la-asf", "lsx": "video/x-la-asf", "mng": "video/x-mng", "asf": "video/x-ms-asf", "asx": "video/x-ms-asf", "wm": "video/x-ms-wm", "wmv": "video/x-ms-wmv", "wmx": "video/x-ms-wmx", "wvx": "video/x-ms-wvx", "avi": "video/x-msvideo", "movie": "video/x-sgi-movie", "mpv": "video/x-matroska", "mkv": "video/x-matroska", "ice": "x-conference/x-cooltalk", "sisx": "x-epoc/x-sisx-app", "vrm": "x-world/x-vrml", ]
0344d2faf68d64bc41b904d75b56fe80
32.336971
130
0.636438
false
false
false
false
ghotjunwoo/Tiat
refs/heads/master
CreateViewController.swift
gpl-3.0
1
// // CreateViewController.swift // Tiat // // Created by 이종승 on 2016. 8. 3.. // Copyright © 2016년 JW. All rights reserved. // import UIKit import Firebase import FirebaseStorage import MobileCoreServices class CreateViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet var nameField: UITextField! @IBOutlet var emailField: UITextField! @IBOutlet var passwordField: UITextField! @IBOutlet var profileImageView: UIImageView! @IBOutlet var registerButton: UIButton! //MARK: Declaration let okAction = UIAlertAction(title: "확인", style: UIAlertActionStyle.default){(ACTION) in print("B_T")} let userRef = FIRDatabase.database().reference().child("users") let user = FIRAuth.auth()?.currentUser let imagePicker = UIImagePickerController() let storageRef = FIRStorage.storage().reference(forURL: "gs://tiat-ea6fd.appspot.com") var userNum = 0 var gender = "남" var image:UIImage = UIImage(named: "status_green")! var metadata = FIRStorageMetadata() func create() { FIRAuth.auth()?.createUser(withEmail: emailField.text!, password: passwordField.text!, completion: { user, error in if error != nil { let duplAlert = UIAlertController(title: "실패", message: "오류가 발생했습니다", preferredStyle: UIAlertControllerStyle.alert); print(error?.localizedDescription) duplAlert.addAction(self.okAction); self.present(duplAlert, animated: true, completion: nil) } else { let profileImageRef = self.storageRef.child("users/\(user!.uid)/profileimage") self.metadata.contentType = "image/jpeg" let newImage = UIImageJPEGRepresentation(self.profileImageView.image!, 3.0) profileImageRef.put(newImage!, metadata: self.metadata) { metadata, error in if error != nil { } } self.userRef.child("\(user!.uid)/name").setValue(self.nameField.text! as String) self.userRef.child("\(user!.uid)/point").setValue(0) self.registerButton.isEnabled = false }}) } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { self.dismiss(animated: true, completion: nil) let image = info[UIImagePickerControllerOriginalImage] as! UIImage profileImageView.image = image } override func viewDidLoad() { super.viewDidLoad() nameField.delegate = self emailField.delegate = self passwordField.delegate = self imagePicker.delegate = self userRef.child("usernum").observe(.value) { (snap: FIRDataSnapshot) in self.userNum = snap.value as! Int } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func nextKeyPressed(_ sender: AnyObject) { emailField.becomeFirstResponder() } @IBAction func emailNextKeyPressed(_ sender: AnyObject) { passwordField.becomeFirstResponder() } @IBAction func passwordNextKeyPressed(_ sender: AnyObject) { create() performSegue(withIdentifier: "toMainScreen_2", sender: self) } @IBAction func registerButtonTapped(_ sender: AnyObject) { create() performSegue(withIdentifier: "toMainScreen_2", sender: self) } @IBAction func selectProfilePhoto(_ sender: AnyObject) { imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary imagePicker.mediaTypes = [kUTTypeImage as String] self.present(imagePicker, animated: true, completion: nil) } }
dd256ed86770ed9d2436d31c64a6836a
34.301724
132
0.63199
false
false
false
false
gnachman/iTerm2
refs/heads/master
sources/Porthole.swift
gpl-2.0
2
// // Porthole.swift // iTerm2SharedARC // // Created by George Nachman on 4/13/22. // import Foundation @objc protocol PortholeMarkReading: iTermMarkProtocol { var uniqueIdentifier: String { get } } @objc class PortholeMark: iTermMark, PortholeMarkReading { private static let mutex = Mutex() let uniqueIdentifier: String private let uniqueIdentifierKey = "PortholeUniqueIdentifier" override var description: String { return "<PortholeMark: \(it_addressString) id=\(uniqueIdentifier) \(isDoppelganger ? "IsDop" : "NotDop")>" } @objc init(_ uniqueIdentifier: String) { self.uniqueIdentifier = uniqueIdentifier super.init() PortholeRegistry.instance.set(uniqueIdentifier, mark: doppelganger() as! PortholeMarkReading) } required init?(dictionary dict: [AnyHashable : Any]) { guard let uniqueIdentifier = dict[uniqueIdentifierKey] as? String else { return nil } self.uniqueIdentifier = uniqueIdentifier super.init() } deinit { if !isDoppelganger { PortholeRegistry.instance.remove(uniqueIdentifier) } } override func dictionaryValue() -> [AnyHashable : Any]! { return [uniqueIdentifierKey: uniqueIdentifier].compactMapValues { $0 } } } enum PortholeType: String { case text = "Text" static func unwrap(dictionary: [String: AnyObject]) -> (type: PortholeType, info: [String: AnyObject])? { guard let typeString = dictionary[portholeType] as? String, let type = PortholeType(rawValue: typeString), let info = dictionary[portholeInfo] as? [String: AnyObject] else { return nil } return (type: type, info: info) } } struct PortholeConfig: CustomDebugStringConvertible { var text: String var colorMap: iTermColorMapReading var baseDirectory: URL? var font: NSFont var type: String? var filename: String? var debugDescription: String { "PortholeConfig(text=\(text) baseDirectory=\(String(describing: baseDirectory)) font=\(font) type=\(String(describing: type)) filename=\(String(describing: filename))" } } protocol PortholeDelegate: AnyObject { func portholeDidAcquireSelection(_ porthole: Porthole) func portholeRemove(_ porthole: Porthole) func portholeResize(_ porthole: Porthole) func portholeAbsLine(_ porthole: Porthole) -> Int64 func portholeHeight(_ porthole: Porthole) -> Int32 } @objc(Porthole) protocol ObjCPorthole: AnyObject { @objc var view: NSView { get } @objc var uniqueIdentifier: String { get } @objc var dictionaryValue: [String: AnyObject] { get } @objc func desiredHeight(forWidth width: CGFloat) -> CGFloat // includes top and bottom margin @objc func removeSelection() @objc func updateColors() @objc var savedLines: [ScreenCharArray] { get set } // Inset the view by this amount top and bottom. @objc var outerMargin: CGFloat { get } } enum PortholeCopyMode { case plainText case attributedString case controlSequences } protocol Porthole: ObjCPorthole { static var type: PortholeType { get } var delegate: PortholeDelegate? { get set } var config: PortholeConfig { get } var hasSelection: Bool { get } func copy(as: PortholeCopyMode) var mark: PortholeMarkReading? { get } func set(frame: NSRect) func find(_ query: String, mode: iTermFindMode) -> [ExternalSearchResult] func select(searchResult: ExternalSearchResult, multiple: Bool, returningRectRelativeTo view: NSView, scroll: Bool) -> NSRect? func snippet(for result: ExternalSearchResult, matchAttributes: [NSAttributedString.Key: Any], regularAttributes: [NSAttributedString.Key: Any]) -> NSAttributedString? func removeHighlights() } fileprivate let portholeType = "Type" fileprivate let portholeInfo = "Info" extension Porthole { func wrap(dictionary: [String: Any]) -> [String: AnyObject] { return [portholeType: Self.type.rawValue as NSString, portholeInfo: dictionary as NSDictionary] } } @objc class PortholeRegistry: NSObject { @objc static var instance = PortholeRegistry() private var portholes = [String: ObjCPorthole]() private var pending = [String: NSDictionary]() private var marks = [String: PortholeMarkReading]() private var _generation: Int = 0 @objc var generation: Int { get { return mutex.sync { _generation } } set { return mutex.sync { self._generation = newValue } } } private let mutex = Mutex() func add(_ porthole: ObjCPorthole) { DLog("add \(porthole)") mutex.sync { portholes[porthole.uniqueIdentifier] = porthole incrementGeneration() } } func remove(_ key: String) { DLog("remove \(key)") mutex.sync { _ = portholes.removeValue(forKey: key) _ = marks.removeValue(forKey: key) incrementGeneration() } } @objc(registerKey:forMark:) func set(_ key: String, mark: PortholeMarkReading) { DLog("register mark \(mark) for \(key)") mutex.sync { marks[key] = mark incrementGeneration() } } @objc(markForKey:) func mark(for key: String) -> PortholeMarkReading? { return mutex.sync { marks[key] } } func get(_ key: String, colorMap: iTermColorMapReading, font: NSFont) -> ObjCPorthole? { mutex.sync { if let porthole = portholes[key] { return porthole } guard let dict = pending[key] as? [String : AnyObject] else { return nil } pending.removeValue(forKey: key) DLog("hydrating \(key)") guard let porthole = PortholeFactory.porthole(dict, colorMap: colorMap, font: font) else { return nil } portholes[key] = porthole incrementGeneration() return porthole } } @objc subscript(_ key: String) -> ObjCPorthole? { return mutex.sync { return portholes[key] } } func incrementGeneration() { _generation += 1 DispatchQueue.main.async { NSApp.invalidateRestorableState() } } private let portholesKey = "Portholes" private let pendingKey = "Pending" private let generationKey = "Generation" @objc var dictionaryValue: [String: AnyObject] { let dicts = portholes.mapValues { porthole in porthole.dictionaryValue as NSDictionary } return [portholesKey: dicts as NSDictionary, generationKey: NSNumber(value: _generation)] } @objc func load(_ dictionary: [String: AnyObject]) { mutex.sync { if let pending = dictionary[pendingKey] as? [String: NSDictionary], let generation = dictionary[generationKey] as? Int, let portholes = dictionary[portholesKey] as? [String: NSDictionary] { self.pending = pending.merging(portholes) { lhs, _ in lhs } self.generation = generation } } } // Note that marks are not restored. They go through the normal mark restoration process which // as a side-effect adds them to the porthole registry. @objc func encodeAsChild(with encoder: iTermGraphEncoder, key: String) { mutex.sync { _ = encoder.encodeChild(withKey: key, identifier: "", generation: _generation) { subencoder in let keys = portholes.keys.sorted() subencoder.encodeArray(withKey: "portholes", generation: iTermGenerationAlwaysEncode, identifiers: keys) { identifier, index, subencoder, stop in let adapter = iTermGraphEncoderAdapter(graphEncoder: subencoder) let key = keys[index] adapter.merge(portholes[key]!.dictionaryValue) return true } return true } } } @objc(decodeRecord:) func decode(record: iTermEncoderGraphRecord) { mutex.sync { record.enumerateArray(withKey: "portholes") { identifier, index, plist, stop in guard let dict = plist as? NSDictionary else { return } pending[identifier] = dict } } } }
aff5239a13170d163485117470b1640b
31.374545
175
0.598787
false
false
false
false
Alloc-Studio/Hypnos
refs/heads/master
Hypnos/Hypnos/Controller/Main/HomeViewController.swift
mit
1
// // HomeViewController.swift // Hypnos // // Created by Fay on 16/5/18. // Copyright © 2016年 DMT312. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import SDCycleScrollView class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() view.addSubview(scrollviewM) scrollviewM.addSubview(search) cycleScrollView.imageURLStringsGroup = [temp1,temp2,temp3,temp4] scrollviewM.addSubview(cycleScrollView) scrollviewM.addSubview(hot) scrollviewM.addSubview(HotSelectedView.view) scrollviewM.addSubview(newSongs) scrollviewM.addSubview(musicSongs.view) presentMusicItem() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBarHidden = false tabBarController?.tabBar.hidden = false } func moreBtn() { navigationController?.pushViewController(MoreArtistsViewController(), animated: true) } // 热门精选header private lazy var hot:UIView = { let hot = NSBundle.mainBundle().loadNibNamed("Header", owner: self, options: nil).last as! UIView hot.frame = CGRectMake(0, CGRectGetMaxY(self.cycleScrollView.frame) + 10, SCREEN_WIDTH, 30) for i in hot.subviews { if i.isKindOfClass(UIButton.self) { let btn = i as! UIButton btn.addTarget(self, action: #selector(HomeViewController.moreBtn), forControlEvents: .TouchUpInside) } } return hot }() // 新歌速递header private lazy var newSongs:UIView = { let new = NSBundle.mainBundle().loadNibNamed("Header", owner: self, options: nil).first as! UIView new.frame = CGRectMake(0, CGRectGetMaxY(self.HotSelectedView.view.frame) + 10, SCREEN_WIDTH, 30) return new }() // scrollview private lazy var scrollviewM:UIScrollView = { let sv = UIScrollView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 44)) sv.contentSize = CGSizeMake(0, CGRectGetMaxY(self.musicSongs.view.frame)) sv.showsVerticalScrollIndicator = false return sv }() // 新歌速递 private var musicSongs:MusicHallViewController { let ms = MusicHallViewController() ms.view.frame = CGRectMake(0, CGRectGetMaxY(self.newSongs.frame), SCREEN_WIDTH, 1190) addChildViewController(ms) return ms } // 热门精选 private var HotSelectedView:HotSelectedViewController { let seletView = HotSelectedViewController() seletView.view.frame = CGRectMake(0, CGRectGetMaxY(self.hot.frame) + 10, SCREEN_WIDTH, 300) addChildViewController(seletView) return seletView } // 搜索框 private lazy var search:SearchBar = { let search = SearchBar(frame: CGRectMake(10, 10, SCREEN_WIDTH-20, 30)) return search }() // 轮播 private lazy var cycleScrollView:SDCycleScrollView = { let cyv = SDCycleScrollView(frame: CGRectMake(10, CGRectGetMaxY(self.search.frame) + CGFloat(10), SCREEN_WIDTH-20, 170)) cyv.autoScrollTimeInterval = 5.0 cyv.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated; cyv.showPageControl = true; cyv.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter; return cyv }() } extension HomeViewController: MCItemPresentable{ func showMuicController() { guard let _ = Player.sharedPlayer().musicModel else { SweetAlert().showAlert("亲~", subTitle: "您还没有选择歌曲哦~~~", style: AlertStyle.CustomImag(imageFile: "recommend_cry")) return } navigationController?.pushViewController(Player.sharedPlayer(), animated: true) } }
20efe26c68994aebfe6b49d80a84c376
31.04878
128
0.653222
false
false
false
false
Sephiroth87/scroll-phat-swift
refs/heads/master
Examples/Snake/main.swift
gpl-2.0
1
// // main.swift // sroll-phat-swift // // Created by Fabio Ritrovato on 14/01/2016. // Copyright (c) 2016 orange in a day. All rights reserved. // import Glibc do { let pHAT = try ScrollpHAT() try pHAT.setBrightness(2) var snake = [(x: 0, y: 0, dx: 1), (x: -1, y: 0, dx: 1), (x: -2, y: 0, dx: 1)] for i in 0..<62 { for point in snake { pHAT.setPixel(x: point.x, y: point.y, value: true) } try pHAT.update() usleep(50000) pHAT.setPixel(x: snake[2].x, y: snake[2].y, value: false) for (i, point) in snake.enumerated() { var point = point point.x += point.dx if (point.x < 0 && point.dx == -1) || (point.x > 10 && point.dx == 1) { point.y += 1 point.dx = -point.dx } snake[i] = point } } } catch let e as SMBusError { print(e) }
e1dfd5b012dd1f54b48745280a8dcf62
25.970588
83
0.487459
false
false
false
false
ospr/UIPlayground
refs/heads/master
UIPlaygroundElements/ThumbSliderView.swift
mit
1
// // ThumbSliderView.swift // UIPlayground // // Created by Kip Nicol on 8/7/16. // Copyright © 2016 Kip Nicol. All rights reserved. // import UIKit @IBDesignable public class ThumbSliderView: UIControl { @IBOutlet private weak var backgroundView: UIView! @IBOutlet private weak var vibrancyBackgroundView: UIView! @IBOutlet public private(set) weak var thumbView: UIImageView! @IBOutlet private weak var informationalLabel: UILabel! @IBOutlet private weak var backgroundInformationalLabel: UILabel! @IBOutlet private weak var backgroundLeadingConstraint: NSLayoutConstraint! @IBOutlet private weak var thumbViewTopPaddingConstraint: NSLayoutConstraint! public var value: Double = 0 { didSet { let previousValue = min(1, max(0, oldValue)) guard previousValue != value else { return } backgroundLeadingConstraint.constant = maxBackgroundLeadingConstraintConstant() * CGFloat(value) sendActions(for: [.valueChanged]) updatePowerOffLabel() } } @IBInspectable var thumbViewImage: UIImage? { get { return thumbView.image } set { thumbView.image = newValue } } @IBInspectable var informationalText: String? { get { return informationalLabel.text } set { informationalLabel.text = newValue backgroundInformationalLabel.text = newValue } } override init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { let view = addOwnedViewFrom(nibNamed: String(describing: ThumbSliderView.self)) view.backgroundColor = .clear setupThumbView() setupInformationalLabel() } private func setupThumbView() { let panGesture = UIPanGestureRecognizer(target: self, action: #selector(thumbViewWasPanned)) thumbView.addGestureRecognizer(panGesture) panGesture.isEnabled = true } private func setupInformationalLabel() { // Create a mask for the white informational label to glide through // the label to create a shimmer effect let shimmerMaskImage = UIImage(named: "ShimmerMask", in: Bundle(for: type(of: self)), compatibleWith: nil)! let shimmerMaskLayer = CALayer() let cgImage = shimmerMaskImage.cgImage! shimmerMaskLayer.contents = cgImage shimmerMaskLayer.contentsGravity = kCAGravityCenter shimmerMaskLayer.frame.size = CGSize(width: cgImage.width, height: cgImage.height) informationalLabel.layer.mask = shimmerMaskLayer } // MARK: - View Layout override public func layoutSubviews() { super.layoutSubviews() vibrancyBackgroundView.layer.cornerRadius = vibrancyBackgroundView.bounds.size.height / 2.0 thumbView.roundCornersToFormCircle() } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) updateShimmerMaskLayerLayout() } func maxBackgroundLeadingConstraintConstant() -> CGFloat { let thumbViewPadding = thumbViewTopPaddingConstraint.constant return backgroundView.superview!.bounds.width - (thumbViewPadding * 2 + thumbView.frame.width) } func updateShimmerMaskLayerLayout() { guard let shimmerMaskLayer = informationalLabel.layer.mask else { return } // Start the mask just offscreen on the left side of the super layer and centered shimmerMaskLayer.frame.origin = CGPoint(x: -shimmerMaskLayer.frame.width, y: informationalLabel.layer.bounds.height / 2.0 - shimmerMaskLayer.bounds.height / 2.0) // Create the horizontal animation to move the shimmer mask let shimmerAnimation = CABasicAnimation(keyPath: "position.x") shimmerAnimation.byValue = informationalLabel.bounds.width + shimmerMaskLayer.frame.width shimmerAnimation.repeatCount = HUGE shimmerAnimation.duration = 2.5 shimmerAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) shimmerMaskLayer.add(shimmerAnimation, forKey: "shimmerAnimation") } // MARK: - Working with slider value func updateValue() { let currentValue = max(0.0, min(1.0, Double(backgroundLeadingConstraint.constant / maxBackgroundLeadingConstraintConstant()))) if value != currentValue { value = currentValue sendActions(for: [.valueChanged]) } } func updatePowerOffLabel() { // Hide the power off label when the slider is panned let desiredPowerOffLabelAlpha: CGFloat = (value == 0) ? 1.0 : 0.0 if self.informationalLabel.alpha != desiredPowerOffLabelAlpha { UIView.animate(withDuration: 0.10, animations: { self.informationalLabel.alpha = desiredPowerOffLabelAlpha self.backgroundInformationalLabel.alpha = desiredPowerOffLabelAlpha }) } } // MARK: - Gesture Handling func thumbViewWasPanned(_ recognizer: UIPanGestureRecognizer) { switch recognizer.state { case .possible, .began: break case .changed: // Update the leading constraint to move the slider to match // the user's pan gesture let translation = recognizer.translation(in: self) backgroundLeadingConstraint.constant = max(translation.x, 0) updateValue() case .ended, .cancelled, .failed: // Determine whether the user slid the slider far enough to // either have the slider finish to the end position or slide // back to the start position let startValue = value let shouldSlideToEnd = startValue > 0.5 let _ = DisplayLinkProgressor.run(withDuration: 0.10, update: { (progress) in let finalValue = shouldSlideToEnd ? 1.0 : 0.0 let nextValue = startValue + progress * (finalValue - startValue) self.value = nextValue }) } } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) sendActions(for: [.touchDown]) } }
4d852ca9c8cdb1073a1e0da062ad364f
35.813187
135
0.635075
false
false
false
false
jdbateman/Lendivine
refs/heads/master
Lendivine/KivaUserAccount.swift
mit
1
// // KivaUserAccount.swift // OAuthSwift // // Created by john bateman on 10/29/15. // Copyright © 2015 John Bateman. All rights reserved. // // This model object describes a user account on the Kiva service. There is currently no Kiva.org REST API support for transferring the user's profile image between the client and server in either direction. import Foundation class KivaUserAccount { var firstName: String = "" var lastName: String = "" var lenderID: String = "" var id: NSNumber = -1 var isPublic: Bool = false var isDeveloper: Bool = false // designated initializer init(dictionary: [String: AnyObject]?) { if let dictionary = dictionary { if let fname = dictionary["first_name"] as? String { firstName = fname } if let lname = dictionary["last_name"] as? String { lastName = lname } if let liD = dictionary["lender_id"] as? String { lenderID = liD } if let iD = dictionary["id"] as? NSNumber { id = iD } if let isPub = dictionary["is_public"] as? Bool { isPublic = isPub } if let dev = dictionary["is_developer"] as? Bool { isDeveloper = dev } } } }
793fb1ce4be451adb42a23c868e1e9f3
30.159091
208
0.555474
false
false
false
false
cconeil/Emojify
refs/heads/master
Emojify/Source/Typeahead.swift
mit
1
// // Typeahead.swift // Emojify // // Created by Chris O'Neil on 4/9/16. // Copyright © 2016 Because. All rights reserved. // import Foundation final class Typeahead { private struct Constants { private static let WordsKey = "words" } typealias StoreType = NSMutableDictionary private let store = StoreType() func words(startingWith key: String) -> [String] { if let substore = substore(key: key) { return wordsFromStore(store: substore) } else { return [] } } func words(matching key: String) -> [String] { return substore(key: key)?[Constants.WordsKey] as? [String] ?? [] } func add(word word: String, forKey key: String) { var store = self.store for character in key.characters { let storeKey = String(character) var substore = store[storeKey] if substore == nil { substore = StoreType() store[storeKey] = substore } store = substore as! StoreType } if let words = store[Constants.WordsKey] as? NSMutableArray { words.addObject(word) } else { store[Constants.WordsKey] = NSMutableArray(object: word) } } func remove(word word: String, forKey key: String) { var store = self.store for character in key.characters { let storeKey = String(character) guard let substore = store[storeKey] else { return } store = substore as! StoreType } if let words = store[Constants.WordsKey] as? NSMutableArray { words.removeObject(word) } } func removeAll() { store.removeAllObjects() } private func wordsFromStore(store store: StoreType) -> [String] { var allWords: [String] = [] for (key, value) in store { if let words = value as? [String], let key = key as? String where key == Constants.WordsKey { allWords += words } else { allWords += wordsFromStore(store: value as! StoreType) } } return allWords } private func substore(key key: String) -> StoreType? { var store = self.store for character in key.characters { let storeKey = String(character) guard let substore = store[storeKey] as? StoreType else { return nil } store = substore } return store } }
772fa651657d267ef11f954d4385f97c
26.489362
105
0.549536
false
false
false
false
accatyyc/Buildasaur
refs/heads/master
Buildasaur/AppDelegate.swift
mit
2
// // AppDelegate.swift // Buildasaur // // Created by Honza Dvorsky on 12/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Cocoa /* Please report any crashes on GitHub, I may optionally ask you to email them to me. Thanks! You can find them at ~/Library/Logs/DiagnosticReports/Buildasaur-* Also, you can find the log at ~/Library/Application Support/Buildasaur/Builda.log */ import BuildaUtils import XcodeServerSDK import BuildaKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var syncerManager: SyncerManager! let menuItemManager = MenuItemManager() var storyboardLoader: StoryboardLoader! var dashboardViewController: DashboardViewController? var dashboardWindow: NSWindow? var windows: Set<NSWindow> = [] func applicationDidFinishLaunching(aNotification: NSNotification) { #if TESTING print("Testing configuration, not launching the app") #else self.setup() #endif } func setup() { //uncomment when debugging autolayout // let defs = NSUserDefaults.standardUserDefaults() // defs.setBool(true, forKey: "NSConstraintBasedLayoutVisualizeMutuallyExclusiveConstraints") // defs.synchronize() self.setupPersistence() self.storyboardLoader = StoryboardLoader(storyboard: NSStoryboard.mainStoryboard) self.storyboardLoader.delegate = self self.menuItemManager.syncerManager = self.syncerManager self.menuItemManager.setupMenuBarItem() let dashboard = self.createInitialViewController() self.dashboardViewController = dashboard self.presentViewControllerInUniqueWindow(dashboard) self.dashboardWindow = self.windowForPresentableViewControllerWithIdentifier("dashboard")!.0 } func migratePersistence(persistence: Persistence) { let fileManager = NSFileManager.defaultManager() //before we create the storage manager, attempt migration first let migrator = CompositeMigrator(persistence: persistence) if migrator.isMigrationRequired() { Log.info("Migration required, launching migrator") do { try migrator.attemptMigration() } catch { Log.error("Migration failed with error \(error), wiping folder...") //wipe the persistence. start over if we failed to migrate _ = try? fileManager.removeItemAtURL(persistence.readingFolder) } Log.info("Migration finished") } else { Log.verbose("No migration necessary, skipping...") } } func setupPersistence() { let persistence = PersistenceFactory.createStandardPersistence() //setup logging Logging.setup(persistence, alsoIntoFile: true) //migration self.migratePersistence(persistence) //create storage manager let storageManager = StorageManager(persistence: persistence) let factory = SyncerFactory() let loginItem = LoginItem() let syncerManager = SyncerManager(storageManager: storageManager, factory: factory, loginItem: loginItem) self.syncerManager = syncerManager } func createInitialViewController() -> DashboardViewController { let dashboard: DashboardViewController = self.storyboardLoader .presentableViewControllerWithStoryboardIdentifier("dashboardViewController", uniqueIdentifier: "dashboard", delegate: self) dashboard.syncerManager = self.syncerManager return dashboard } func applicationShouldHandleReopen(sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { self.showMainWindow() return true } func applicationDidBecomeActive(notification: NSNotification) { self.showMainWindow() } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { let runningCount = self.syncerManager.syncers.filter({ $0.active }).count if runningCount > 0 { let confirm = "Are you sure you want to quit Buildasaur? This would stop \(runningCount) running syncers." UIUtils.showAlertAskingConfirmation(confirm, dangerButton: "Quit") { (quit) -> () in NSApp.replyToApplicationShouldTerminate(quit) } return NSApplicationTerminateReply.TerminateLater } else { return NSApplicationTerminateReply.TerminateNow } } func applicationWillTerminate(aNotification: NSNotification) { //stop syncers properly self.syncerManager.stopSyncers() } //MARK: Showing Window on Reactivation func showMainWindow(){ NSApp.activateIgnoringOtherApps(true) //first window. i wish there was a nicer way (please some tell me there is) if NSApp.windows.count < 3 { self.dashboardWindow?.makeKeyAndOrderFront(self) } } } extension AppDelegate: PresentableViewControllerDelegate { func configureViewController(viewController: PresentableViewController) { // } func presentViewControllerInUniqueWindow(viewController: PresentableViewController) { //last chance to config self.configureViewController(viewController) //make sure we're the delegate viewController.presentingDelegate = self //check for an existing window let identifier = viewController.uniqueIdentifier var newWindow: NSWindow? if let existingPair = self.windowForPresentableViewControllerWithIdentifier(identifier) { newWindow = existingPair.0 } else { newWindow = NSWindow(contentViewController: viewController) newWindow?.autorecalculatesKeyViewLoop = true //if we already are showing some windows, let's cascade the new one if self.windows.count > 0 { //find the right-most window and cascade from it let rightMost = self.windows.reduce(CGPoint(x: 0.0, y: 0.0), combine: { (right: CGPoint, window: NSWindow) -> CGPoint in let origin = window.frame.origin if origin.x > right.x { return origin } return right }) let newOrigin = newWindow!.cascadeTopLeftFromPoint(rightMost) newWindow?.setFrameTopLeftPoint(newOrigin) } } guard let window = newWindow else { fatalError("Unable to create window") } window.delegate = self self.windows.insert(window) window.makeKeyAndOrderFront(self) } func closeWindowWithViewController(viewController: PresentableViewController) { if let window = self.windowForPresentableViewControllerWithIdentifier(viewController.uniqueIdentifier)?.0 { if window.delegate?.windowShouldClose!(window) ?? true { window.close() } } } } extension AppDelegate: StoryboardLoaderDelegate { func windowForPresentableViewControllerWithIdentifier(identifier: String) -> (NSWindow, PresentableViewController)? { for window in self.windows { guard let viewController = window.contentViewController else { continue } guard let presentableViewController = viewController as? PresentableViewController else { continue } if presentableViewController.uniqueIdentifier == identifier { return (window, presentableViewController) } } return nil } func storyboardLoaderExistingViewControllerWithIdentifier(identifier: String) -> PresentableViewController? { //look through our windows and their view controllers to see if we can't find this view controller let pair = self.windowForPresentableViewControllerWithIdentifier(identifier) return pair?.1 } } extension AppDelegate: NSWindowDelegate { func windowShouldClose(sender: AnyObject) -> Bool { if let window = sender as? NSWindow { self.windows.remove(window) } //TODO: based on the editing state, if editing VC (cancel/save) return true } }
55832616a55b56f74d4565aa3f541d3c
33.746032
136
0.637392
false
false
false
false
MichMich/OctoPrintApp
refs/heads/master
OctoPrint/TemperatureTableViewController.swift
mit
1
// // TemperatureTableViewController.swift // OctoPrint // // Created by Michael Teeuw on 27-07-15. // Copyright © 2015 Michael Teeuw. All rights reserved. // import UIKit class TemperatureTableViewController: UITableViewController { let sections = ["Bed", "Tools"] override func viewDidLoad() { title = "Temperature" super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdatePrinter, object: OPManager.sharedInstance) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdateVersion, object: OPManager.sharedInstance) NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateUI", key: .DidUpdateSettings, object: OPManager.sharedInstance) OPManager.sharedInstance.updateVersion() OPManager.sharedInstance.updatePrinter(autoUpdate:1) OPManager.sharedInstance.updateSettings() updateUI() } func updateUI() { tableView.reloadData() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return 1 case 1: return OPManager.sharedInstance.tools.count default: return 0 } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return sections[section] } override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if section == tableView.numberOfSections - 1 { if let updated = OPManager.sharedInstance.updateTimeStamp { let formattedDate = NSDateFormatter.localizedStringFromDate(updated,dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: .MediumStyle) return "Last update: \(formattedDate)" } } return nil } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let shortPath = (indexPath.section, indexPath.row) switch shortPath { case (0,_): let cell = tableView.dequeueReusableCellWithIdentifier("TemperatureCell", forIndexPath: indexPath) let tool = OPManager.sharedInstance.bed cell.textLabel?.text = tool.identifier cell.detailTextLabel?.text = "\(tool.actualTemperature.celciusString()) (\(tool.targetTemperature.celciusString()))" return cell case (1,_): let cell = tableView.dequeueReusableCellWithIdentifier("TemperatureCell", forIndexPath: indexPath) let tool = OPManager.sharedInstance.tools[indexPath.row] cell.textLabel?.text = tool.identifier cell.detailTextLabel?.text = "\(tool.actualTemperature.celciusString()) (\(tool.targetTemperature.celciusString()))" return cell default: let cell = tableView.dequeueReusableCellWithIdentifier("BasicCell", forIndexPath: indexPath) cell.textLabel?.text = "Unknown cell!" return cell } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("ShowTemperatureSelector", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ShowTemperatureSelector" { if let indexPath = tableView.indexPathForSelectedRow { let temperatureSelector = segue.destinationViewController as! TemperatureSelectorTableViewController temperatureSelector.heatedComponent = (indexPath.section == 0) ? OPManager.sharedInstance.bed : OPManager.sharedInstance.tools[indexPath.row] } } } }
20499d40e3fdc9418b96da4a200f24dc
34.857143
157
0.636981
false
false
false
false
BryanHoke/swift-corelibs-foundation
refs/heads/master
Foundation/NSLocale.swift
apache-2.0
5
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation public class NSLocale : NSObject, NSCopying, NSSecureCoding { typealias CFType = CFLocaleRef private var _base = _CFInfo(typeID: CFLocaleGetTypeID()) private var _identifier = UnsafeMutablePointer<Void>() private var _cache = UnsafeMutablePointer<Void>() private var _prefs = UnsafeMutablePointer<Void>() #if os(OSX) || os(iOS) private var _lock = pthread_mutex_t() #elseif os(Linux) private var _lock = Int32(0) #endif private var _nullLocale = false internal var _cfObject: CFType { return unsafeBitCast(self, CFType.self) } public func objectForKey(key: String) -> AnyObject? { return CFLocaleGetValue(_cfObject, key._cfObject) } public func displayNameForKey(key: String, value: String) -> String? { return CFLocaleCopyDisplayNameForPropertyValue(_cfObject, key._cfObject, value._cfObject)?._swiftObject } public init(localeIdentifier string: String) { super.init() _CFLocaleInit(_cfObject, string._cfObject) } public required convenience init?(coder aDecoder: NSCoder) { NSUnimplemented() } public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() } public func encodeWithCoder(aCoder: NSCoder) { NSUnimplemented() } public static func supportsSecureCoding() -> Bool { return true } } extension NSLocale { public class func currentLocale() -> NSLocale { return CFLocaleCopyCurrent()._nsObject } public class func systemLocale() -> NSLocale { return CFLocaleGetSystem()._nsObject } } extension NSLocale { public class func availableLocaleIdentifiers() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyAvailableLocaleIdentifiers()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func ISOLanguageCodes() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOLanguageCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func ISOCountryCodes() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOCountryCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func ISOCurrencyCodes() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyISOCurrencyCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func commonISOCurrencyCodes() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyCommonISOCurrencyCodes()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func preferredLanguages() -> [String] { var identifiers = Array<String>() for obj in CFLocaleCopyPreferredLanguages()._nsObject { identifiers.append((obj as! NSString)._swiftObject) } return identifiers } public class func componentsFromLocaleIdentifier(string: String) -> [String : String] { var comps = Dictionary<String, String>() CFLocaleCreateComponentsFromLocaleIdentifier(kCFAllocatorSystemDefault, string._cfObject)._nsObject.enumerateKeysAndObjectsUsingBlock { (key: NSObject, object: AnyObject, stop: UnsafeMutablePointer<ObjCBool>) -> Void in comps[(key as! NSString)._swiftObject] = (object as! NSString)._swiftObject } return comps } public class func localeIdentifierFromComponents(dict: [String : String]) -> String { return CFLocaleCreateLocaleIdentifierFromComponents(kCFAllocatorSystemDefault, dict._cfObject)._swiftObject } public class func canonicalLocaleIdentifierFromString(string: String) -> String { return CFLocaleCreateCanonicalLocaleIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } public class func canonicalLanguageIdentifierFromString(string: String) -> String { return CFLocaleCreateCanonicalLanguageIdentifierFromString(kCFAllocatorSystemDefault, string._cfObject)._swiftObject } public class func localeIdentifierFromWindowsLocaleCode(lcid: UInt32) -> String? { return CFLocaleCreateLocaleIdentifierFromWindowsLocaleCode(kCFAllocatorSystemDefault, lcid)._swiftObject } public class func windowsLocaleCodeFromLocaleIdentifier(localeIdentifier: String) -> UInt32 { return CFLocaleGetWindowsLocaleCodeFromLocaleIdentifier(localeIdentifier._cfObject) } public class func characterDirectionForLanguage(isoLangCode: String) -> NSLocaleLanguageDirection { let dir = CFLocaleGetLanguageCharacterDirection(isoLangCode._cfObject) #if os(OSX) || os(iOS) return NSLocaleLanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocaleLanguageDirection(rawValue: UInt(dir))! #endif } public class func lineDirectionForLanguage(isoLangCode: String) -> NSLocaleLanguageDirection { let dir = CFLocaleGetLanguageLineDirection(isoLangCode._cfObject) #if os(OSX) || os(iOS) return NSLocaleLanguageDirection(rawValue: UInt(dir.rawValue))! #else return NSLocaleLanguageDirection(rawValue: UInt(dir))! #endif } } public enum NSLocaleLanguageDirection : UInt { case Unknown case LeftToRight case RightToLeft case TopToBottom case BottomToTop } public let NSCurrentLocaleDidChangeNotification: String = "" // NSUnimplemented public let NSLocaleIdentifier: String = "kCFLocaleIdentifierKey" public let NSLocaleLanguageCode: String = "kCFLocaleLanguageCodeKey" public let NSLocaleCountryCode: String = "kCFLocaleCountryCodeKey" public let NSLocaleScriptCode: String = "kCFLocaleScriptCodeKey" public let NSLocaleVariantCode: String = "kCFLocaleVariantCodeKey" public let NSLocaleExemplarCharacterSet: String = "kCFLocaleExemplarCharacterSetKey" public let NSLocaleCalendar: String = "kCFLocaleCalendarKey" public let NSLocaleCollationIdentifier: String = "collation" public let NSLocaleUsesMetricSystem: String = "kCFLocaleUsesMetricSystemKey" public let NSLocaleMeasurementSystem: String = "kCFLocaleMeasurementSystemKey" public let NSLocaleDecimalSeparator: String = "kCFLocaleDecimalSeparatorKey" public let NSLocaleGroupingSeparator: String = "kCFLocaleGroupingSeparatorKey" public let NSLocaleCurrencySymbol: String = "kCFLocaleCurrencySymbolKey" public let NSLocaleCurrencyCode: String = "currency" public let NSLocaleCollatorIdentifier: String = "" // NSUnimplemented // NSString public let NSLocaleQuotationBeginDelimiterKey: String = "" // NSUnimplemented // NSString public let NSLocaleQuotationEndDelimiterKey: String = "" // NSUnimplemented // NSString public let NSLocaleAlternateQuotationBeginDelimiterKey: String = "" // NSUnimplemented // NSString public let NSLocaleAlternateQuotationEndDelimiterKey: String = "" // NSUnimplemented // NSString extension CFLocaleRef : _NSBridgable { typealias NSType = NSLocale internal var _nsObject: NSLocale { return unsafeBitCast(self, NSType.self) } }
70a79842e7ad77ae818ecb2e6ec9877b
38.454545
227
0.718474
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/public/core/BridgingBuffer.swift
apache-2.0
10
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// internal struct _BridgingBufferHeader { internal var count: Int internal init(_ count: Int) { self.count = count } } // NOTE: older runtimes called this class _BridgingBufferStorage. // The two must coexist without a conflicting ObjC class name, so it // was renamed. The old name must not be used in the new runtime. internal final class __BridgingBufferStorage : ManagedBuffer<_BridgingBufferHeader, AnyObject> { } internal typealias _BridgingBuffer = ManagedBufferPointer<_BridgingBufferHeader, AnyObject> @available(OpenBSD, unavailable, message: "malloc_size is unavailable.") extension ManagedBufferPointer where Header == _BridgingBufferHeader, Element == AnyObject { internal init(_ count: Int) { self.init( _uncheckedBufferClass: __BridgingBufferStorage.self, minimumCapacity: count) self.withUnsafeMutablePointerToHeader { $0.initialize(to: Header(count)) } } internal var count: Int { @inline(__always) get { return header.count } @inline(__always) set { return header.count = newValue } } internal subscript(i: Int) -> Element { @inline(__always) get { return withUnsafeMutablePointerToElements { $0[i] } } } internal var baseAddress: UnsafeMutablePointer<Element> { @inline(__always) get { return withUnsafeMutablePointerToElements { $0 } } } internal var storage: AnyObject? { @inline(__always) get { return buffer } } }
4588351bf4dd033f884e16e7e661ae7f
26.930556
80
0.640975
false
false
false
false
auth0/Auth0.swift
refs/heads/master
Auth0/NSURLComponents+OAuth2.swift
mit
1
#if WEB_AUTH_PLATFORM import Foundation extension URLComponents { var fragmentValues: [String: String] { var dict: [String: String] = [:] let items = fragment?.components(separatedBy: "&") items?.forEach { item in let parts = item.components(separatedBy: "=") guard parts.count == 2, let key = parts.first, let value = parts.last else { return } dict[key] = value } return dict } var queryValues: [String: String] { var dict: [String: String] = [:] self.queryItems?.forEach { dict[$0.name] = $0.value } return dict } } #endif
21963484044227bda8b6399a2d84edd6
25.916667
97
0.569659
false
false
false
false
LateralView/swift-lateral-toolbox
refs/heads/master
Example/Tests/UIColorSpec.swift
mit
1
import Quick import Nimble import UIKit import swift_lateral_toolbox class UIColorSpec: QuickSpec { override func spec() { describe("creating color from hex number") { it("works with color #000000") { let reference = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1) let color = UIColor(hex: 0x000000) expect(reference).to(equal(color)) } it("works with color #FFFFFF") { let reference = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1) let color = UIColor(hex: 0xFFFFFF) expect(reference).to(equal(color)) } } describe("extracting components") { it("works with color #123456 and alpha 78") { let reference = UIColor(colorLiteralRed: 0x12/0xFF, green: 0x34/0xFF, blue: 0x56/0xFF, alpha: 0x78/0xFF) let c = reference.components expect(c.red - 0x12/0xFF).to(beLessThan(0.001)) expect(c.green - 0x34/0xFF).to(beLessThan(0.001)) expect(c.blue - 0x56/0xFF).to(beLessThan(0.001)) expect(c.alpha - 0x78/0xFF).to(beLessThan(0.001)) } } describe("changing color tones") { it("returns a 20% darker color than white") { let reference = UIColor(colorLiteralRed: 0.8, green: 0.8, blue: 0.8, alpha: 1) let color = UIColor.whiteColor().darker() expect(color).to(equal(reference)) } it("returns a 20% brighter color than black") { let reference = UIColor(colorLiteralRed: 0.2, green: 0.2, blue: 0.2, alpha: 1) let color = UIColor.blackColor().brighter() expect(color).to(equal(reference)) } it("returns white even after trying to make it brighter") { let white = UIColor(colorLiteralRed: 1, green: 1, blue: 1, alpha: 1) expect(white.brighter()).to(equal(white)) } it("returns black even after trying to make it darker") { let black = UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 1) expect(black.darker()).to(equal(black)) } } describe("creating an image") { it("consists of a single pixel") { let color = UIColor(colorLiteralRed: 0.75, green: 0.50, blue: 0.25, alpha: 1) var image : UIImage! image = color.toImage() expect(image.size.width).to(equal(1)) expect(image.size.height).to(equal(1)) } } } }
d9cb0aab33e3797998ad3467bb47ecc5
34.455696
120
0.516244
false
false
false
false
geekaurora/ReactiveListViewKit
refs/heads/master
Example/ReactiveListViewKitDemo/Data Layer/User.swift
mit
1
// // User.swift // ReactiveListViewKit // // Created by Cheng Zhang on 1/3/17. // Copyright © 2017 Cheng Zhang. All rights reserved. // import CZUtils import ReactiveListViewKit /// Model of user class User: ReactiveListDiffable { let userId: String let userName: String let fullName: String? let portraitUrl: String? enum CodingKeys: String, CodingKey { case userId = "id" case userName = "username" case fullName = "full_name" case portraitUrl = "profile_picture" } // MARK: - CZListDiffable func isEqual(toDiffableObj object: AnyObject) -> Bool { return isEqual(toCodable: object) } // MARK: - NSCopying func copy(with zone: NSZone? = nil) -> Any { return codableCopy(with: zone) } }
fd74b64dc5deacb662d0a3090eb5da42
20.702703
59
0.628892
false
false
false
false
nheagy/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/BlogSettingsDiscussionTests.swift
gpl-2.0
1
import Foundation @testable import WordPress class BlogSettingsDiscussionTests : XCTestCase { private var manager : TestContextManager! override func setUp() { manager = TestContextManager() } override func tearDown() { manager = nil } func testCommentsAutoapprovalDisabledEnablesManualModerationFlag() { let settings = newSettings() settings.commentsAutoapproval = .Disabled XCTAssertTrue(settings.commentsRequireManualModeration) XCTAssertFalse(settings.commentsFromKnownUsersWhitelisted) } func testCommentsAutoapprovalFromKnownUsersEnablesWhitelistedFlag() { let settings = newSettings() settings.commentsAutoapproval = .FromKnownUsers XCTAssertFalse(settings.commentsRequireManualModeration) XCTAssertTrue(settings.commentsFromKnownUsersWhitelisted) } func testCommentsAutoapprovalEverythingDisablesManualModerationAndWhitelistedFlags() { let settings = newSettings() settings.commentsAutoapproval = .Everything XCTAssertFalse(settings.commentsRequireManualModeration) XCTAssertFalse(settings.commentsFromKnownUsersWhitelisted) } func testCommentsSortingSetsTheCorrectCommentSortOrderIntegerValue() { let settings = newSettings() settings.commentsSorting = .Ascending XCTAssertTrue(settings.commentsSortOrder == Sorting.Ascending.rawValue) settings.commentsSorting = .Descending XCTAssertTrue(settings.commentsSortOrder == Sorting.Descending.rawValue) } func testCommentsSortOrderAscendingSetsTheCorrectCommentSortOrderIntegerValue() { let settings = newSettings() settings.commentsSortOrderAscending = true XCTAssertTrue(settings.commentsSortOrder == Sorting.Ascending.rawValue) settings.commentsSortOrderAscending = false XCTAssertTrue(settings.commentsSortOrder == Sorting.Descending.rawValue) } func testCommentsThreadingDisablesSetsThreadingEnabledFalse() { let settings = newSettings() settings.commentsThreading = .Disabled XCTAssertFalse(settings.commentsThreadingEnabled) } func testCommentsThreadingEnabledSetsThreadingEnabledTrueAndTheRightDepthValue() { let settings = newSettings() settings.commentsThreading = .Enabled(depth: 10) XCTAssertTrue(settings.commentsThreadingEnabled) XCTAssert(settings.commentsThreadingDepth == 10) settings.commentsThreading = .Enabled(depth: 2) XCTAssertTrue(settings.commentsThreadingEnabled) XCTAssert(settings.commentsThreadingDepth == 2) } // MARK: - Typealiases typealias Sorting = BlogSettings.CommentsSorting // MARK: - Private Helpers private func newSettings() -> BlogSettings { let context = manager!.mainContext let name = BlogSettings.classNameWithoutNamespaces() let entity = NSEntityDescription.insertNewObjectForEntityForName(name, inManagedObjectContext: context) return entity as! BlogSettings } }
abd30c2bd79c3b36db45646e9518dd96
34.6
111
0.712859
false
true
false
false
jpsim/SourceKitten
refs/heads/main
Source/SourceKittenFramework/SwiftVersion.swift
mit
1
/// The version triple of the Swift compiler, for example "5.1.3" struct SwiftVersion: RawRepresentable, Comparable { typealias RawValue = String let rawValue: String init(rawValue: String) { self.rawValue = rawValue } /// Comparable static func < (lhs: SwiftVersion, rhs: SwiftVersion) -> Bool { return lhs.rawValue < rhs.rawValue } } extension SwiftVersion { static let beforeFiveDotOne = SwiftVersion(rawValue: "1.0.0") static let fiveDotOne = SwiftVersion(rawValue: "5.1.0") /// The version of the Swift compiler providing SourceKit. Accurate only from /// compiler version 5.1.0: earlier versions return `.beforeFiveDotOne`. static let current: SwiftVersion = { if let result = try? Request.compilerVersion.send(), let major = result["key.version_major"] as? Int64, let minor = result["key.version_minor"] as? Int64, let patch = result["key.version_patch"] as? Int64 { return SwiftVersion(rawValue: "\(major).\(minor).\(patch)") } return .beforeFiveDotOne }() }
cfbc3e90f0b1e9dabd032d972b6082e6
33.78125
82
0.645103
false
false
false
false
DavidHu0921/LyricsEasy
refs/heads/master
Carthage/Checkouts/FileKit/Sources/Operators.swift
mit
2
// // Operators.swift // FileKit // // The MIT License (MIT) // // Copyright (c) 2015-2016 Nikolai Vazquez // // 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. // // swiftlint:disable file_length import Foundation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // MARK: - File /// Returns `true` if both files' paths are the same. public func ==<DataType: ReadableWritable>(lhs: File<DataType>, rhs: File<DataType>) -> Bool { return lhs.path == rhs.path } /// Returns `true` if `lhs` is smaller than `rhs` in size. public func < <DataType: ReadableWritable>(lhs: File<DataType>, rhs: File<DataType>) -> Bool { return lhs.size < rhs.size } infix operator |> /// Writes data to a file. /// /// - Throws: `FileKitError.WriteToFileFail` /// public func |> <DataType: ReadableWritable>(data: DataType, file: File<DataType>) throws { try file.write(data) } // MARK: - TextFile /// Returns `true` if both text files have the same path and encoding. public func == (lhs: TextFile, rhs: TextFile) -> Bool { return lhs.path == rhs.path && lhs.encoding == rhs.encoding } infix operator |>> /// Appends a string to a text file. /// /// If the text file can't be read from, such in the case that it doesn't exist, /// then it will try to write the data directly to the file. /// /// - Throws: `FileKitError.WriteToFileFail` /// public func |>> (data: String, file: TextFile) throws { var data = data if let contents = try? file.read() { data = contents + "\n" + data } try data |> file } /// Return lines of file that match the motif. public func | (file: TextFile, motif: String) -> [String] { return file.grep(motif) } infix operator |- /// Return lines of file that does'nt match the motif. public func |- (file: TextFile, motif: String) -> [String] { return file.grep(motif, include: false) } infix operator |~ /// Return lines of file that match the regex motif. public func |~ (file: TextFile, motif: String) -> [String] { return file.grep(motif, options: NSString.CompareOptions.regularExpression) } // MARK: - Path /// Returns `true` if the standardized form of one path equals that of another /// path. public func == (lhs: Path, rhs: Path) -> Bool { if lhs.isAbsolute || rhs.isAbsolute { return lhs.absolute.rawValue == rhs.absolute.rawValue } return lhs.standardRawValueWithTilde == rhs.standardRawValueWithTilde } /// Returns `true` if the standardized form of one path not equals that of another /// path. public func != (lhs: Path, rhs: Path) -> Bool { return !(lhs == rhs) } /// Concatenates two `Path` instances and returns the result. /// /// ```swift /// let systemLibrary: Path = "/System/Library" /// print(systemLib + "Fonts") // "/System/Library/Fonts" /// ``` /// public func + (lhs: Path, rhs: Path) -> Path { if lhs.rawValue.isEmpty || lhs.rawValue == "." { return rhs } if rhs.rawValue.isEmpty || rhs.rawValue == "." { return lhs } switch (lhs.rawValue.hasSuffix(Path.separator), rhs.rawValue.hasPrefix(Path.separator)) { case (true, true): let rhsRawValue = rhs.rawValue.substring(from: rhs.rawValue.characters.index(after: rhs.rawValue.startIndex)) return Path("\(lhs.rawValue)\(rhsRawValue)") case (false, false): return Path("\(lhs.rawValue)\(Path.separator)\(rhs.rawValue)") default: return Path("\(lhs.rawValue)\(rhs.rawValue)") } } /// Converts a `String` to a `Path` and returns the concatenated result. public func + (lhs: String, rhs: Path) -> Path { return Path(lhs) + rhs } /// Converts a `String` to a `Path` and returns the concatenated result. public func + (lhs: Path, rhs: String) -> Path { return lhs + Path(rhs) } /// Appends the right path to the left path. public func += (lhs: inout Path, rhs: Path) { lhs = lhs + rhs } /// Appends the path value of the String to the left path. public func += (lhs: inout Path, rhs: String) { lhs = lhs + rhs } /// Concatenates two `Path` instances and returns the result. public func / (lhs: Path, rhs: Path) -> Path { return lhs + rhs } /// Converts a `String` to a `Path` and returns the concatenated result. public func / (lhs: Path, rhs: String) -> Path { return lhs + rhs } /// Converts a `String` to a `Path` and returns the concatenated result. public func / (lhs: String, rhs: Path) -> Path { return lhs + rhs } /// Appends the right path to the left path. public func /= (lhs: inout Path, rhs: Path) { lhs += rhs } /// Appends the path value of the String to the left path. public func /= (lhs: inout Path, rhs: String) { lhs += rhs } precedencegroup FileCommonAncestorPrecedence { associativity: left } infix operator <^> : FileCommonAncestorPrecedence /// Returns the common ancestor between the two paths. public func <^> (lhs: Path, rhs: Path) -> Path { return lhs.commonAncestor(rhs) } infix operator </> /// Runs `closure` with the path as its current working directory. public func </> (path: Path, closure: () throws -> ()) rethrows { try path.changeDirectory(closure) } infix operator ->> /// Moves the file at the left path to a path. /// /// Throws an error if the file at the left path could not be moved or if a file /// already exists at the right path. /// /// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.MoveFileFail` /// public func ->> (lhs: Path, rhs: Path) throws { try lhs.moveFile(to: rhs) } /// Moves a file to a path. /// /// Throws an error if the file could not be moved or if a file already /// exists at the destination path. /// /// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.MoveFileFail` /// public func ->> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { try lhs.move(to: rhs) } infix operator ->! /// Forcibly moves the file at the left path to the right path. /// /// - Warning: If a file at the right path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func ->! (lhs: Path, rhs: Path) throws { if rhs.isAny { try rhs.deleteFile() } try lhs ->> rhs } /// Forcibly moves a file to a path. /// /// - Warning: If a file at the right path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func ->! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { if rhs.isAny { try rhs.deleteFile() } try lhs ->> rhs } infix operator +>> /// Copies the file at the left path to the right path. /// /// Throws an error if the file at the left path could not be copied or if a file /// already exists at the right path. /// /// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CopyFileFail` /// public func +>> (lhs: Path, rhs: Path) throws { try lhs.copyFile(to: rhs) } /// Copies a file to a path. /// /// Throws an error if the file could not be copied or if a file already /// exists at the destination path. /// /// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CopyFileFail` /// public func +>> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { try lhs.copy(to: rhs) } infix operator +>! /// Forcibly copies the file at the left path to the right path. /// /// - Warning: If a file at the right path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func +>! (lhs: Path, rhs: Path) throws { if rhs.isAny { try rhs.deleteFile() } try lhs +>> rhs } /// Forcibly copies a file to a path. /// /// - Warning: If a file at the right path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func +>! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { if rhs.isAny { try rhs.deleteFile() } try lhs +>> rhs } infix operator =>> /// Creates a symlink of the left path at the right path. /// /// If the symbolic link path already exists and _is not_ a directory, an /// error will be thrown and a link will not be created. /// /// If the symbolic link path already exists and _is_ a directory, the link /// will be made to a file in that directory. /// /// - Throws: /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func =>> (lhs: Path, rhs: Path) throws { try lhs.symlinkFile(to: rhs) } /// Symlinks a file to a path. /// /// If the path already exists and _is not_ a directory, an error will be /// thrown and a link will not be created. /// /// If the path already exists and _is_ a directory, the link will be made /// to the file in that directory. /// /// - Throws: `FileKitError.FileDoesNotExist`, `FileKitError.CreateSymlinkFail` /// public func =>> <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { try lhs.symlink(to: rhs) } infix operator =>! /// Forcibly creates a symlink of the left path at the right path by deleting /// anything at the right path before creating the symlink. /// /// - Warning: If the symbolic link path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func =>! (lhs: Path, rhs: Path) throws { // guard lhs.exists else { // throw FileKitError.FileDoesNotExist(path: lhs) // } let linkPath = rhs.isDirectory ? rhs + lhs.fileName : rhs if linkPath.isAny { try linkPath.deleteFile() } try lhs =>> rhs } /// Forcibly creates a symlink of a file at a path by deleting anything at the /// path before creating the symlink. /// /// - Warning: If the path already exists, it will be deleted. /// /// - Throws: /// `FileKitError.DeleteFileFail`, /// `FileKitError.FileDoesNotExist`, /// `FileKitError.CreateSymlinkFail` /// public func =>! <DataType: ReadableWritable>(lhs: File<DataType>, rhs: Path) throws { try lhs.path =>! rhs } postfix operator % /// Returns the standardized version of the path. public postfix func % (path: Path) -> Path { return path.standardized } postfix operator * /// Returns the resolved version of the path. public postfix func * (path: Path) -> Path { return path.resolved } postfix operator ^ /// Returns the path's parent path. public postfix func ^ (path: Path) -> Path { return path.parent }
28606484880ebfedf1997cf5a9fd221e
26.548387
117
0.663349
false
false
false
false
OscarSwanros/swift
refs/heads/master
test/stdlib/TestLocale.swift
apache-2.0
16
// 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 // //===----------------------------------------------------------------------===// // // RUN: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/FoundationBridge/FoundationBridge.m -c -o %t/FoundationBridgeObjC.o -g // RUN: %target-build-swift %s -I %S/Inputs/FoundationBridge/ -Xlinker %t/FoundationBridgeObjC.o -o %t/TestLocale // RUN: %target-run %t/TestLocale > %t.txt // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import FoundationBridgeObjC #if FOUNDATION_XCTEST import XCTest class TestLocaleSuper : XCTestCase { } #else import StdlibUnittest class TestLocaleSuper { } #endif class TestLocale : TestLocaleSuper { func test_bridgingAutoupdating() { let tester = LocaleBridgingTester() do { let loc = Locale.autoupdatingCurrent let result = tester.verifyAutoupdating(loc) expectTrue(result) } do { let loc = tester.autoupdatingCurrentLocale() let result = tester.verifyAutoupdating(loc) expectTrue(result) } } func test_equality() { let autoupdating = Locale.autoupdatingCurrent let autoupdating2 = Locale.autoupdatingCurrent expectEqual(autoupdating, autoupdating2) let current = Locale.current expectNotEqual(autoupdating, current) } func test_localizedStringFunctions() { let locale = Locale(identifier: "en") expectEqual("English", locale.localizedString(forIdentifier: "en")) expectEqual("France", locale.localizedString(forRegionCode: "fr")) expectEqual("Spanish", locale.localizedString(forLanguageCode: "es")) expectEqual("Simplified Han", locale.localizedString(forScriptCode: "Hans")) expectEqual("Computer", locale.localizedString(forVariantCode: "POSIX")) expectEqual("Buddhist Calendar", locale.localizedString(for: .buddhist)) expectEqual("US Dollar", locale.localizedString(forCurrencyCode: "USD")) expectEqual("Phonebook Sort Order", locale.localizedString(forCollationIdentifier: "phonebook")) // Need to find a good test case for collator identifier // expectEqual("something", locale.localizedString(forCollatorIdentifier: "en")) } func test_properties() { let locale = Locale(identifier: "zh-Hant-HK") expectEqual("zh-Hant-HK", locale.identifier) expectEqual("zh", locale.languageCode) expectEqual("HK", locale.regionCode) expectEqual("Hant", locale.scriptCode) expectEqual("POSIX", Locale(identifier: "en_POSIX").variantCode) expectTrue(locale.exemplarCharacterSet != nil) // The calendar we get back from Locale has the locale set, but not the one we create with Calendar(identifier:). So we configure our comparison calendar first. var c = Calendar(identifier: .gregorian) c.locale = Locale(identifier: "en_US") expectEqual(c, Locale(identifier: "en_US").calendar) expectEqual("「", locale.quotationBeginDelimiter) expectEqual("」", locale.quotationEndDelimiter) expectEqual("『", locale.alternateQuotationBeginDelimiter) expectEqual("』", locale.alternateQuotationEndDelimiter) expectEqual("phonebook", Locale(identifier: "en_US@collation=phonebook").collationIdentifier) expectEqual(".", locale.decimalSeparator) expectEqual(".", locale.decimalSeparator) expectEqual(",", locale.groupingSeparator) expectEqual("HK$", locale.currencySymbol) expectEqual("HKD", locale.currencyCode) expectTrue(Locale.availableIdentifiers.count > 0) expectTrue(Locale.isoLanguageCodes.count > 0) expectTrue(Locale.isoRegionCodes.count > 0) expectTrue(Locale.isoCurrencyCodes.count > 0) expectTrue(Locale.commonISOCurrencyCodes.count > 0) expectTrue(Locale.preferredLanguages.count > 0) // Need to find a good test case for collator identifier // expectEqual("something", locale.collatorIdentifier) } func test_AnyHashableContainingLocale() { let values: [Locale] = [ Locale(identifier: "en"), Locale(identifier: "uk"), Locale(identifier: "uk"), ] let anyHashables = values.map(AnyHashable.init) expectEqual(Locale.self, type(of: anyHashables[0].base)) expectEqual(Locale.self, type(of: anyHashables[1].base)) expectEqual(Locale.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } func test_AnyHashableCreatedFromNSLocale() { let values: [NSLocale] = [ NSLocale(localeIdentifier: "en"), NSLocale(localeIdentifier: "uk"), NSLocale(localeIdentifier: "uk"), ] let anyHashables = values.map(AnyHashable.init) expectEqual(Locale.self, type(of: anyHashables[0].base)) expectEqual(Locale.self, type(of: anyHashables[1].base)) expectEqual(Locale.self, type(of: anyHashables[2].base)) expectNotEqual(anyHashables[0], anyHashables[1]) expectEqual(anyHashables[1], anyHashables[2]) } } #if !FOUNDATION_XCTEST var LocaleTests = TestSuite("TestLocale") LocaleTests.test("test_bridgingAutoupdating") { TestLocale().test_bridgingAutoupdating() } LocaleTests.test("test_equality") { TestLocale().test_equality() } LocaleTests.test("test_localizedStringFunctions") { TestLocale().test_localizedStringFunctions() } LocaleTests.test("test_properties") { TestLocale().test_properties() } LocaleTests.test("test_AnyHashableContainingLocale") { TestLocale().test_AnyHashableContainingLocale() } LocaleTests.test("test_AnyHashableCreatedFromNSLocale") { TestLocale().test_AnyHashableCreatedFromNSLocale() } runAllTests() #endif
6cf915ed32c1da3dd119aa083402af4f
40.986577
168
0.669118
false
true
false
false
Vayne-Lover/Swift-Filter
refs/heads/master
Median Filter.playground/Contents.swift
mit
1
//Setting Start import UIKit func getTestValueUInt16()->UInt16{ return UInt16(arc4random_uniform(255)) } func getTestValueInt()->Int{ return Int(arc4random_uniform(255)) } //Setting End //Double Extension Start extension Double{//If you want to format you can use the extension. func format(f:String) -> String { return NSString(format: "%\(f)f",self) as String } } //Double Extension End //Extension Example Start //print(Double(3.1415).format(".2"))//There is the example to format Double //Extension Example End //Median Filter //Filter2 Start var Value2=128.0 func filter2(inout Value:Double)->Double{ var value2:[Int]=[getTestValueInt(),getTestValueInt(),getTestValueInt(),getTestValueInt()] for i in 0..<3 { for j in 0..<3-i { if value2[j]>value2[j+1] { let temp=value2[j] value2[j]=value2[j+1] value2[j+1]=temp } } } Value=Double(value2[2]+value2[1])/2.0 return Value } //Filter2 End //Filter2 Test Start print(filter2(&Value2).format(".2")) //Filter2 Test End
35665f0a4c547284c92e016dca2cd5e7
25.853659
94
0.641818
false
true
false
false
johannescarlen/daterangeview
refs/heads/master
DateRange/ViewController.swift
mit
1
// // The MIT License (MIT) // // Copyright (c) 2015 Johannes Carlén, Wildberry // // 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 ViewController: UIViewController, DateRangeDelegate { @IBOutlet weak var upperView: UIView! @IBOutlet weak var dateRangeContainerView: UIView! @IBOutlet weak var periodLabel: UILabel! var dateRangeView: DateRangeView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. upperView.backgroundColor = UIColor(22, 122, 182) dateRangeView = DateRangeView(frame: CGRectMake(0, 80, self.view.frame.width, 200)) dateRangeView.delegate = self dateRangeView.setContentOffset(year: 2016, month: 1) self.view.addSubview(upperView) self.dateRangeContainerView.addSubview(dateRangeView) self.view.layoutIfNeeded() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func dateSelected(start start: Int, end: Int) { print("Start: \(start) End:\(end)") // Format 201503 var selectedString : (String) if(start == end && start == 0) { selectedString = "No filter" } else { let formatter = NSDateFormatter() let month1Index = (start % 100) let month1: String = formatter.monthSymbols[month1Index - 1] selectedString = "\(month1) \((start-month1Index)/100)" if(start != end) { let month2Index = (end % 100) let month2: String = formatter.monthSymbols[month2Index - 1] selectedString += " - \(month2) \((end-month2Index)/100)" } } self.periodLabel!.text = selectedString } }
7ddac6207aa6de8d3f1dcb2fbdf30173
38.346667
91
0.664521
false
false
false
false
spacedrabbit/100-days
refs/heads/master
One00Days/One00Days/Day8ViewController.swift
mit
1
// // Dat8ViewController.swift // One00Days // // Created by Louis Tur on 2/28/16. // Copyright © 2016 SRLabs. All rights reserved. // import UIKit class Day8ViewController: UIViewController { let frontCardView: UIView = { let view: UIView = UIView() view.backgroundColor = UIColor.lightGray return view }() let backCardView: UIView = { let view: UIView = UIView() view.backgroundColor = UIColor.blue return view }() let frontCardText: UILabel = { let label: UILabel = UILabel() label.text = "Hello world, how are you" label.font = UIFont(name: "Menlo", size: 40.0) label.numberOfLines = 3 label.adjustsFontSizeToFitWidth = true return label }() let insideCardText: UILabel = { let label: UILabel = UILabel() label.text = "World keeps turning and I've been better" label.font = UIFont(name: "Menlo", size: 40.0) label.adjustsFontSizeToFitWidth = true label.numberOfLines = 3 return label }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.brown self.setupViewHierarchy() self.configureConstraints() self.applyTransform() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } internal func configureConstraints() { self.frontCardView.snp.makeConstraints { (make) -> Void in make.width.equalTo(200.0) make.height.equalTo(170.0) make.center.equalTo(self.view.snp.center) } self.backCardView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self.frontCardView.snp.edges) } self.frontCardText.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self.frontCardView.snp.edges) } self.insideCardText.snp.makeConstraints { (make) -> Void in make.edges.equalTo(self.backCardView.snp.edges) } } internal func setupViewHierarchy() { self.view.addSubview(self.backCardView) self.view.addSubview(self.frontCardView) self.frontCardView.addSubview(self.frontCardText) self.backCardView.addSubview(self.insideCardText) } internal func applyTransform() { let frontCardAngle: CGFloat = degreesToRadians(35.0) let sideTwist: CGFloat = degreesToRadians(20.0) self.frontCardView.layer.anchorPoint = CGPoint(x: 0.0, y: 0.0) // self.frontCardView.layer.position = CGPointMake( CGRectGetMidX(self.frontCardView.frame), CGRectGetMaxY(self.frontCardView.frame)) let rotateForwardOnX = CATransform3DMakeRotation(frontCardAngle, 1.0, 0.0, 0.0) let rotateLeftOnY = CATransform3DMakeRotation(sideTwist, 0.0, -1.0, 0.0) self.frontCardView.layer.transform = CATransform3DConcat(rotateForwardOnX, rotateLeftOnY) } }
43a37becf7fd0fb59afaaad025a169bc
27.44898
136
0.688307
false
false
false
false
Perfect-Server-Swift-LearnGuide/Today-News-Admin
refs/heads/master
Sources/Handler/UploadArticleImageHandler.swift
apache-2.0
1
// // UploadArticleImageHandler.swift // Today-News-Admin // // Created by Mac on 17/7/24. // Copyright © 2017年 lovemo. All rights reserved. // import PerfectHTTP import PerfectLib import Config public struct UploadArticleImageHandler { public init(){} /// 上传文章缩略图 public static func upload(req: HTTPRequest, res: HTTPResponse) -> String { var imgs = [[String:Any]]() if let uploads = req.postFileUploads , uploads.count > 0 { // 创建路径用于存储已上传文件 let fileDir = Dir(Dir.workingDir.path + req.documentRoot + "/\(app.upload)/") do { try fileDir.create() } catch { print(error) } for upload in uploads { let judgeResult: (Bool, String) = self.judge(contenType: upload.contentType, fileSize: upload.fileSize) if judgeResult.0 { // 将文件转移走,如果目标位置已经有同名文件则进行覆盖操作。 let thisFile = File(upload.tmpFileName) let path = upload.fieldName + self.ext(contentType: upload.contentType) do { let _ = try thisFile.moveTo(path: fileDir.path + path, overWrite: true) imgs.append(["url" : "./\(app.upload)/" + path]) } catch { print(error) } } } } if imgs.count > 0 { return try! ["result" : ["msg" : "success", "urls" : imgs]].jsonEncodedString() } else { return try! ["result" : ["msg" : "error", "urls" : ""]].jsonEncodedString() } } static func ext(contentType: String) -> String { let filterStr = ["gif", "jpg", "jpeg", "bmp", "png"]; for str in filterStr { if contentType.contains(string: str) { return ".\(str)" } } return ".jpg" } static func judge(contenType: String, fileSize: Int) -> (Bool, String) { let filter = ["gif", "jpg", "jpeg", "bmp", "png"]; var contain = false for str in filter { if contenType.contains(string: str) { contain = true } } if !contain { return (false, try! ["result" : "上传失败, 图片格式不对"].jsonEncodedString()) } if fileSize > 1000 * 1000 * 10 { return (false, try! ["result" : "上传失败, 图片尺寸太大"].jsonEncodedString()) } return (true, try! ["result" : "上传成功"].jsonEncodedString()) } }
4924913b1a50b5a427095f23ec403e4d
29.255556
119
0.47264
false
false
false
false
MrMatthias/SwiftColorPicker
refs/heads/master
Source/HuePicker.swift
mit
1
// Created by Matthias Schlemm on 05/03/15. // Copyright (c) 2015 Sixpolys. All rights reserved. // Licensed under the MIT License. // URL: https://github.com/MrMatthias/SwiftColorPicker import UIKit @IBDesignable open class HuePicker: UIView { var _h:CGFloat = 0.1111 open var h:CGFloat { // [0,1] set(value) { _h = min(1, max(0, value)) currentPoint = CGPoint(x: CGFloat(_h), y: 0) setNeedsDisplay() } get { return _h } } var image:UIImage? fileprivate var data:[UInt8]? fileprivate var currentPoint = CGPoint.zero open var handleColor:UIColor = UIColor.black open var onHueChange:((_ hue:CGFloat, _ finished:Bool) -> Void)? open func setHueFromColor(_ color:UIColor) { var h:CGFloat = 0 color.getHue(&h, saturation: nil, brightness: nil, alpha: nil) self.h = h } public override init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = true; } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isUserInteractionEnabled = true } func renderBitmap() { if bounds.isEmpty { return } let width = UInt(bounds.width) let height = UInt(bounds.height) if data == nil { data = [UInt8](repeating: UInt8(255), count: Int(width * height) * 4) } var p = 0.0 var q = 0.0 var t = 0.0 var i = 0 //_ = 255 var double_v:Double = 0 var double_s:Double = 0 let widthRatio:Double = 360 / Double(bounds.width) var d = data! for hi in 0..<Int(bounds.width) { let double_h:Double = widthRatio * Double(hi) / 60 let sector:Int = Int(floor(double_h)) let f:Double = double_h - Double(sector) let f1:Double = 1.0 - f double_v = Double(1) double_s = Double(1) p = double_v * (1.0 - double_s) * 255 q = double_v * (1.0 - double_s * f) * 255 t = double_v * ( 1.0 - double_s * f1) * 255 let v255 = double_v * 255 i = hi * 4 switch(sector) { case 0: d[i+1] = UInt8(v255) d[i+2] = UInt8(t) d[i+3] = UInt8(p) case 1: d[i+1] = UInt8(q) d[i+2] = UInt8(v255) d[i+3] = UInt8(p) case 2: d[i+1] = UInt8(p) d[i+2] = UInt8(v255) d[i+3] = UInt8(t) case 3: d[i+1] = UInt8(p) d[i+2] = UInt8(q) d[i+3] = UInt8(v255) case 4: d[i+1] = UInt8(t) d[i+2] = UInt8(p) d[i+3] = UInt8(v255) default: d[i+1] = UInt8(v255) d[i+2] = UInt8(p) d[i+3] = UInt8(q) } } var sourcei = 0 for v in 1..<Int(bounds.height) { for s in 0..<Int(bounds.width) { sourcei = s * 4 i = (v * Int(width) * 4) + sourcei d[i+1] = d[sourcei+1] d[i+2] = d[sourcei+2] d[i+3] = d[sourcei+3] } } let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue) let provider = CGDataProvider(data: Data(bytes: d, count: d.count * MemoryLayout<UInt8>.size) as CFData) let cgimg = CGImage(width: Int(width), height: Int(height), bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: Int(width) * Int(MemoryLayout<UInt8>.size * 4), space: colorSpace, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) image = UIImage(cgImage: cgimg!) } fileprivate func handleTouch(_ touch:UITouch, finished:Bool) { let point = touch.location(in: self) currentPoint = CGPoint(x: max(0, min(bounds.width, point.x)) / bounds.width , y: 0) _h = currentPoint.x onHueChange?(h, finished) setNeedsDisplay() } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { handleTouch(touches.first! as UITouch, finished: false) } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { handleTouch(touches.first! as UITouch, finished: false) } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { handleTouch(touches.first! as UITouch, finished: true) } override open func draw(_ rect: CGRect) { if image == nil { renderBitmap() } if let img = image { img.draw(in: rect) } let handleRect = CGRect(x: bounds.width * currentPoint.x-3, y: 0, width: 6, height: bounds.height) drawHueDragHandler(frame: handleRect) } func drawHueDragHandler(frame: CGRect) { //// Polygon Drawing let polygonPath = UIBezierPath() polygonPath.move(to: CGPoint(x: frame.minX + 4, y: frame.maxY - 6)) polygonPath.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.maxY)) polygonPath.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.maxY)) polygonPath.close() UIColor.black.setFill() polygonPath.fill() //// Polygon 2 Drawing let polygon2Path = UIBezierPath() polygon2Path.move(to: CGPoint(x: frame.minX + 4, y: frame.minY + 6)) polygon2Path.addLine(to: CGPoint(x: frame.minX + 7.46, y: frame.minY)) polygon2Path.addLine(to: CGPoint(x: frame.minX + 0.54, y: frame.minY)) polygon2Path.close() UIColor.white.setFill() polygon2Path.fill() } }
99d23013d9f9602ba7f939f72088e52f
31.545455
167
0.52514
false
false
false
false
hgani/ganilib-ios
refs/heads/master
glib/Classes/JsonUi/Actions/JsonAction.swift
mit
1
open class JsonAction { public let spec: Json // public let screen: GScreen // public var targetView: UIView? = nil public let screen: UIViewController public var targetView: UIView? public var launch: LaunchHelper { return LaunchHelper(screen) } public var nav: NavHelper { return NavHelper(navController: GApp.instance.navigationController) } public required init(_ spec: Json, _ screen: UIViewController) { self.spec = spec self.screen = screen } public final func execute() { if !silentExecute() { GLog.w("Invalid action spec: \(spec)") } } open func silentExecute() -> Bool { fatalError("Need implementation") } private static func create(spec: Json, screen: UIViewController) -> JsonAction? { if let klass = JsonUi.loadClass(name: spec["action"].stringValue, type: JsonAction.self) as? JsonAction.Type { return klass.init(spec, screen) } GLog.w("Failed loading action: \(spec)") return nil } public static func execute(spec: Json, screen: UIViewController, creator: UIView?) { if let instance = create(spec: spec, screen: screen) { instance.targetView = creator instance.execute() } } public static func execute(spec: Json, screen: UIViewController, creator: JsonAction) { if let instance = create(spec: spec, screen: screen) { instance.targetView = creator.targetView instance.execute() } } }
357632a96b9bac93a16a319ad967d5a3
28.867925
118
0.618446
false
false
false
false
leo150/Pelican
refs/heads/develop
Sources/Pelican/API/Types/Type+Custom.swift
mit
1
import Foundation import Vapor import FluentProvider /* // Defines what the thumbnail is being used for. enum InlineThumbnailType: String { case contact case document case photo case GIF // JPEG or GIF. case mpeg4GIF // JPEG or GIF. case video // JPEG only. case location } // A thumbnail to represent a preview of an inline file. NOT FOR NORMAL FILE USE. struct InlineThumbnail { //var type: ThumbnailType var url: String = "" var width: Int = 0 var height: Int = 0 init () { } func getQuerySet() -> [String : CustomStringConvertible] { var keys: [String:CustomStringConvertible] = [ "thumb_url": url] if width != 0 { keys["thumb_width"] = width } if height != 0 { keys["thumb_height"] = height } return keys } // NodeRepresentable conforming methods init(node: Node, in context: Context) throws { //type = try node.extract("type") url = try node.extract("thumb_url") width = try node.extract("thumb_width") height = try node.extract("thumb_height") } func makeNode() throws -> Node { var keys: [String:NodeRepresentable] = [ "url": url ] if width != 0 { keys["width"] = width } if height != 0 { keys["height"] = height } return try Node(node: keys) } func makeNode(context: Context) throws -> Node { return try self.makeNode() } } enum InputFileType { case fileID(String) case url(String) } // A type for handling files for sending. class InputFile: NodeConvertible, JSONConvertible { var type: InputFileType // NodeRepresentable conforming methods required init(node: Node, in context: Context) throws { let fileID: String = try node.extract("file_id") if fileID != "" { type = .fileID(fileID) } else { type = .url(try node.extract("url")) } } func makeNode() throws -> Node { var keys: [String:NodeRepresentable] = [:] switch type{ case .fileID(let fileID): keys["file_id"] = fileID case .url(let url): keys["url"] = url } return try Node(node: keys) } func makeNode(context: Context) throws -> Node { return try self.makeNode() } } */
a2c4a6f113bce9ec884b7351feb9ba0a
20.980198
82
0.618468
false
false
false
false
dnseitz/YAPI
refs/heads/master
YAPI/YAPI/V2/V2_YelpPhoneSearchRequest.swift
mit
1
// // YelpPhoneSearchRequest.swift // YAPI // // Created by Daniel Seitz on 9/12/16. // Copyright © 2016 Daniel Seitz. All rights reserved. // import Foundation import OAuthSwift public final class YelpV2PhoneSearchRequest : YelpRequest { public typealias Response = YelpV2PhoneSearchResponse public let oauthVersion: OAuthSwiftCredential.Version = .oauth1 public let path: String = YelpEndpoints.V2.phone public let parameters: [String: String] public let session: YelpHTTPClient public var requestMethod: OAuthSwiftHTTPRequest.Method { return .GET } init(phoneSearch: YelpV2PhoneSearchParameters, session: YelpHTTPClient = YelpHTTPClient.sharedSession) { var parameters = [String: String]() parameters.insertParameter(phoneSearch.phone) if let countryCode = phoneSearch.countryCode { parameters.insertParameter(countryCode) } if let category = phoneSearch.category { parameters.insertParameter(category) } self.parameters = parameters self.session = session } }
1578b165d238e689422b60e208ec06d6
28.027778
106
0.745455
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Neocom/Neocom/Killboard/zKillboard/ShipPickerGroups.swift
lgpl-2.1
2
// // ShipPickerGroups.swift // Neocom // // Created by Artem Shimanski on 4/2/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import CoreData import Expressible struct ShipPickerGroups: View { @Environment(\.managedObjectContext) private var managedObjectContext @State private var selectedType: SDEInvType? @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState var category: SDEInvCategory var completion: (NSManagedObject) -> Void private func getGroups() -> FetchedResultsController<SDEInvGroup> { let controller = managedObjectContext.from(SDEInvGroup.self) .filter(/\SDEInvGroup.category == category && /\SDEInvGroup.published == true) .sort(by: \SDEInvGroup.groupName, ascending: true) .fetchedResultsController(sectionName: /\SDEInvGroup.published) return FetchedResultsController(controller) } private let groups = Lazy<FetchedResultsController<SDEInvGroup>, Never>() @State private var searchString: String = "" @State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil var body: some View { let groups = self.groups.get(initial: getGroups()) let predicate = /\SDEInvType.group?.category == self.category && /\SDEInvType.published == true return TypesSearch(predicate: predicate, searchString: $searchString, searchResults: $searchResults) { if self.searchResults != nil { TypePickerTypesContent(types: self.searchResults!, selectedType: self.$selectedType, completion: self.completion) } else { ShipPickerGroupsContent(groups: groups, completion: self.completion) } } .navigationBarTitle(category.categoryName ?? NSLocalizedString("Categories", comment: "")) .sheet(item: $selectedType) { type in NavigationView { TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil}) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } struct ShipPickerGroupsContent: View { var groups: FetchedResultsController<SDEInvGroup> var completion: (NSManagedObject) -> Void var body: some View { ForEach(groups.sections, id: \.name) { section in Section(header: section.name == "0" ? Text("UNPUBLISHED") : Text("PUBLISHED")) { ForEach(section.objects, id: \.objectID) { group in NavigationLink(destination: ShipPickerTypes(parentGroup: group, completion: self.completion)) { HStack { GroupCell(group: group) Spacer() Button(NSLocalizedString("Select", comment: "")) { self.completion(group) }.foregroundColor(.blue) } }.buttonStyle(PlainButtonStyle()) } } } } } struct ShipPickerTypes: View { var parentGroup: SDEInvGroup var completion: (SDEInvType) -> Void @State private var selectedType: SDEInvType? @Environment(\.managedObjectContext) private var managedObjectContext @Environment(\.self) private var environment @EnvironmentObject private var sharedState: SharedState var predicate: PredicateProtocol { /\SDEInvType.group == parentGroup && /\SDEInvType.published == true } private func getTypes() -> FetchedResultsController<SDEInvType> { Types.fetchResults(with: predicate, managedObjectContext: managedObjectContext) } private let types = Lazy<FetchedResultsController<SDEInvType>, Never>() @State private var searchString: String = "" @State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil var body: some View { let types = self.types.get(initial: getTypes()) return TypesSearch(predicate: self.predicate, searchString: $searchString, searchResults: $searchResults) { TypePickerTypesContent(types: self.searchResults ?? types.sections, selectedType: self.$selectedType, completion: self.completion) } .navigationBarTitle(parentGroup.groupName ?? "") .sheet(item: $selectedType) { type in NavigationView { TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil}) } .modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState)) .navigationViewStyle(StackNavigationViewStyle()) } } } #if DEBUG struct ShipPickerGroups_Previews: PreviewProvider { static var previews: some View { let category = try? Storage.testStorage.persistentContainer.viewContext.from(SDEInvCategory.self).filter(/\SDEInvCategory.categoryID == SDECategoryID.ship.rawValue).first() return NavigationView { ShipPickerGroups(category: category!) { _ in} }.modifier(ServicesViewModifier.testModifier()) } } #endif
2e6371107572fce644380abd7f7aa232
41.464567
180
0.6514
false
false
false
false
benzhipeng/HardChoice
refs/heads/master
HardChoice/DataKit/Wormhole.swift
mit
3
// // Wormhole.swift // HardChoice // // Created by 杨萧玉 on 15/4/3. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import CoreFoundation public typealias MessageListenerBlock = (AnyObject) -> Void let WormholeNotificationName = "WormholeNotificationName" let center = CFNotificationCenterGetDarwinNotifyCenter() let helpMethod = HelpMethod() public class Wormhole: NSObject { var applicationGroupIdentifier:String! var directory:String? var fileManager:NSFileManager! var listenerBlocks:Dictionary<String, MessageListenerBlock>! /** 初始化方法 :param: identifier AppGroup的Identifier :param: dir 可选的文件夹名称 :returns: Wormhole实例对象 */ public init(applicationGroupIdentifier identifier:String, optionalDirectory dir:String) { super.init() applicationGroupIdentifier = identifier directory = dir fileManager = NSFileManager() listenerBlocks = Dictionary() NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveMessageNotification:", name: WormholeNotificationName, object: nil) } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) CFNotificationCenterRemoveEveryObserver(center, unsafeAddressOf(self)) } // MARK: - Private File Operation Methods func messagePassingDirectoryPath() -> String? { var appGroupContainer = self.fileManager.containerURLForSecurityApplicationGroupIdentifier(applicationGroupIdentifier) var appGroupContainerPath = appGroupContainer?.path if directory != nil, var directoryPath = appGroupContainerPath { directoryPath = directoryPath.stringByAppendingPathComponent(directory!) fileManager.createDirectoryAtPath(directoryPath, withIntermediateDirectories: true, attributes: nil, error: nil) return directoryPath } return nil } func filePathForIdentifier(identifier:String) -> String? { if count(identifier) != 0, let directoryPath = messagePassingDirectoryPath() { let fileName = "\(identifier).archive" return directoryPath.stringByAppendingPathComponent(fileName) } return nil } func writeMessageObject(messageObject:AnyObject, toFileWithIdentifier identifier:String) { var data = NSKeyedArchiver.archivedDataWithRootObject(messageObject) if let filePath = filePathForIdentifier(identifier) { if !data.writeToFile(filePath, atomically: true) { return } else{ sendNotificationForMessageWithIdentifier(identifier) } } } func messageObjectFromFileWithIdentifier(identifier:String) -> AnyObject? { if var data = NSData(contentsOfFile: filePathForIdentifier(identifier) ?? "") { var messageObject: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data) return messageObject } return nil } func deleteFileForIdentifier(identifier:String) { if let filePath = filePathForIdentifier(identifier) { fileManager.removeItemAtPath(filePath, error: nil) } } // MARK: - Private Notification Methods func sendNotificationForMessageWithIdentifier(identifier:String) { CFNotificationCenterPostNotification(center, identifier, nil, nil, 1) } func registerForNotificationsWithIdentifier(identifier:String) { CFNotificationCenterAddObserver(center, unsafeAddressOf(self), helpMethod.callback, identifier, nil, CFNotificationSuspensionBehavior.DeliverImmediately) } func unregisterForNotificationsWithIdentifier(identifier:String) { CFNotificationCenterRemoveObserver(center, unsafeAddressOf(self), identifier, nil) } // func wormholeNotificationCallback(center:CFNotificationCenter!, observer:UnsafeMutablePointer<Void>, name:CFString!, object:UnsafePointer<Void>, userInfo:CFDictionary!) { // NSNotificationCenter.defaultCenter().postNotificationName(WormholeNotificationName, object: nil, userInfo: ["identifier":name]) // } func didReceiveMessageNotification(notification:NSNotification) { let userInfo = notification.userInfo if let identifier = userInfo?["identifier"] as? String, let listenerBlock = listenerBlockForIdentifier(identifier), let messageObject: AnyObject = messageObjectFromFileWithIdentifier(identifier) { listenerBlock(messageObject) } } func listenerBlockForIdentifier(identifier:String) -> MessageListenerBlock? { return listenerBlocks[identifier] } //MARK: - Public Interface Methods public func passMessageObject(messageObject:AnyObject ,identifier:String) { writeMessageObject(messageObject, toFileWithIdentifier: identifier) } public func messageWithIdentifier(identifier:String) -> AnyObject? { return messageObjectFromFileWithIdentifier(identifier) } public func clearMessageContentsForIdentifier(identifier:String) { deleteFileForIdentifier(identifier) } public func clearAllMessageContents() { if directory != nil, let directoryPath = messagePassingDirectoryPath(), let messageFiles = fileManager.contentsOfDirectoryAtPath(directoryPath, error: nil) { for path in messageFiles as! [String] { fileManager.removeItemAtPath(directoryPath.stringByAppendingPathComponent(path), error: nil) } } } public func listenForMessageWithIdentifier(identifier:String, listener:MessageListenerBlock) { listenerBlocks[identifier] = listener registerForNotificationsWithIdentifier(identifier) } public func stopListeningForMessageWithIdentifier(identifier:String) { listenerBlocks[identifier] = nil unregisterForNotificationsWithIdentifier(identifier) } }
9996f32adda823994b608ab2f0b110f7
38.715232
204
0.710522
false
false
false
false
audiokit/AudioKit
refs/heads/v5-develop
Tests/AudioKitTests/MIDI Tests/Support/UMPSysex.swift
mit
1
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ private extension UInt8 { init(highNibble: UInt8, lowNibble: UInt8) { self = highNibble << 4 + lowNibble & 0x0F } var highNibble: UInt8 { self >> 4 } var lowNibble: UInt8 { self & 0x0F } } // simple convenience struct for creating ump sysex for testing struct UMPSysex { enum UMPType: UInt8 { // from Universal MIDI Packet (UMP) Format spec case utility = 0 // 1 word case system = 1 // 1 word case channelVoice1 = 2 // 1 word case sysex = 3 // 2 words case channelVoice2 = 4 // 2 words case data128 = 5 // 4 words case reserved6 = 6 // 1 word case reserved7 = 7 // 1 word case reserved8 = 8 // 2 words case reserved9 = 9 // 2 words case reserved10 = 10 // 2 words case reserved11 = 11 // 3 words case reserved12 = 12 // 3 words case reserved13 = 13 // 4 words case reserved14 = 14 // 4 words case reserved15 = 15 // 4 words init(_ byte0: UInt8) { self = UMPType(rawValue: byte0.highNibble)! } } enum UMPSysexType: UInt8 { // from Universal MIDI Packet (UMP) Format spec case complete = 0 case start = 1 case `continue` = 2 case end = 3 } struct UMP64 { var word0: UInt32 = 0 var word1: UInt32 = 0 } let umpBigEndian: UMP64 init(group: UInt8 = 0, type: UMPSysexType, data: [UInt8]) { var ump = UMP64() let numBytes = min(data.count, 6) let dataRange = 2..<2+numBytes withUnsafeMutableBytes(of: &ump) { $0[0] = .init(highNibble: UMPType.sysex.rawValue, lowNibble: group) $0[1] = .init(highNibble: type.rawValue, lowNibble: UInt8(numBytes)) let buffer = UnsafeMutableRawBufferPointer(rebasing: $0[dataRange]) buffer.copyBytes(from: data[0..<numBytes]) } self.umpBigEndian = ump } init(word0: UInt32, word1: UInt32) { umpBigEndian = .init(word0: .init(bigEndian:word0), word1: .init(bigEndian:word1)) } var umpType: UMPType { withUnsafeBytes(of: umpBigEndian) { UMPType($0[0]) } } var group: UInt8 { withUnsafeBytes(of: umpBigEndian) { $0[0].lowNibble } } var status: UMPSysexType { withUnsafeBytes(of: umpBigEndian) { UMPSysexType(rawValue: $0[1].highNibble)! } } var numDataBytes: Int { withUnsafeBytes(of: umpBigEndian) { Int($0[1].lowNibble) } } var dataRange: Range<Int> { 2..<2+numDataBytes } var data: [UInt8] { withUnsafeBytes(of: umpBigEndian) { .init($0[dataRange]) } } var word0: UInt32 { .init(bigEndian: umpBigEndian.word0) } var word1: UInt32 { .init(bigEndian: umpBigEndian.word1) } var words: [UInt32] { [word0, word1] } static func sysexComplete(group: UInt8 = 0, data: [UInt8]) -> Self { .init(group: group, type: .complete, data: data) } static func sysexStart(group: UInt8 = 0, data: [UInt8]) -> Self { .init(group: group, type: .start, data: data) } static func sysexContinue(group: UInt8 = 0, data: [UInt8]) -> Self { .init(group: group, type: .continue, data: data) } static func sysexEnd(group: UInt8 = 0, data: [UInt8]) -> Self { .init(group: group, type: .end, data: data) } }
7e16a9bd75ff4ea4373a3713f2883208
28.148438
100
0.547038
false
false
false
false
martinLilili/JSONModelWithMirror
refs/heads/master
JSONModel/ViewController.swift
mit
1
// // ViewController.swift // JSONModel // // Created by UBT on 2016/12/5. // Copyright © 2016年 martin. All rights reserved. // import UIKit //电话结构体 struct Telephone { var title:String //电话标题 var number:String //电话号码 } extension Telephone: JSON { } //用户类 class User : JSONModel { var name:String = "" //姓名 var nickname:String? //昵称 var age:Int = 0 //年龄 var emails:[String]? //邮件地址 // var tels:[Telephone]? //电话 } class Student: User { var accountID : Int = 0 } class SchoolStudent: Student { var schoolName : String? var schoolmates : [Student]? var principal : User? } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // testUser() // // testStudent() var any: Any // any = nil var op : String? op = nil any = op print(any) print(any == nil) testSchoolStudent() } func testUser() { //创建一个User实例对象 let user = User() user.name = "hangge" user.age = 100 user.emails = ["hangge@hangge.com","system@hangge.com"] //添加动画 // let tel1 = Telephone(title: "手机", number: "123456") // let tel2 = Telephone(title: "公司座机", number: "001-0358") // user.tels = [tel1, tel2] //输出json字符串 print("user = \(user)") } func testStudent() { //创建一个student实例对象 let student = Student() student.accountID = 2009 student.name = "hangge" student.age = 100 student.emails = ["hangge@hangge.com","system@hangge.com"] //添加动画 // let tel1 = Telephone(title: "手机", number: "123456") // let tel2 = Telephone(title: "公司座机", number: "001-0358") // student.tels = [tel1, tel2] //输出json字符串 print("student = \(student)") } func testSchoolStudent() { //创建一个schoolstudent实例对象 let schoolstudent = SchoolStudent() schoolstudent.schoolName = "清华大学" schoolstudent.accountID = 1024 schoolstudent.name = "martin" schoolstudent.age = 20 let principal = User() principal.name = "校长" principal.age = 60 principal.emails = ["zhang@hangge.com","xiao@hangge.com"] schoolstudent.principal = principal let student1 = Student() student1.accountID = 2009 student1.name = "martin" student1.age = 25 student1.emails = ["martin1@hangge.com","martin2@hangge.com"] // //添加手机 // let tel1 = Telephone(title: "手机", number: "123456") // let tel2 = Telephone(title: "公司座机", number: "001-0358") // student1.tels = [tel1, tel2] let student2 = Student() student2.accountID = 2008 student2.name = "james" student2.age = 26 student2.emails = ["james1@hangge.com","james2@hangge.com"] // //添加手机 // let tel3 = Telephone(title: "手机", number: "123456") // let tel4 = Telephone(title: "公司座机", number: "001-0358") // student2.tels = [tel3, tel4] schoolstudent.schoolmates = [student1, student2] //输出json字符串 print("school student = \(schoolstudent)") let a = NSKeyedArchiver.archivedData(withRootObject: schoolstudent) let b = NSKeyedUnarchiver.unarchiveObject(with: a) print("unarchiveObject = \(b)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
82a485bd938caeda783f9ff3e65352ec
24.390728
80
0.547731
false
false
false
false
FredrikSjoberg/KFDataStructures
refs/heads/master
KFDataStructures/Swift/UniqueQueue.swift
mit
1
// // UniqueQueue.swift // KFDataStructures // // Created by Fredrik Sjöberg on 24/09/15. // Copyright © 2015 Fredrik Sjoberg. All rights reserved. // import Foundation public struct UniqueQueue<Element: Hashable> { fileprivate var contents:[Element] fileprivate var uniques: Set<Element> public init() { contents = [] uniques = Set() } } extension UniqueQueue : DynamicQueueType { public mutating func push(element: Element) { if !uniques.contains(element) { contents.append(element) uniques.insert(element) } } public mutating func pop() -> Element? { guard !contents.isEmpty else { return nil } let element = contents.removeFirst() // NOTE: removeFirst() is O(self.count), we need O(1). Doubly-Linked-List? uniques.remove(element) return element } public mutating func invalidate(element: Element) { guard !contents.isEmpty else { return } guard let index = contents.index(of: element) else { return } contents.remove(at: index) uniques.remove(element) } public func peek() -> Element? { return contents.first } } extension UniqueQueue : Collection { public var startIndex: Int { return contents.startIndex } public var endIndex: Int { return contents.endIndex } public subscript(index: Int) -> Element { return contents[index] } public func index(after i: Int) -> Int { return i + 1 } } extension UniqueQueue : ExpressibleByArrayLiteral { public init(arrayLiteral elements: Element...) { uniques = Set(elements) contents = [] contents += elements.filter{ uniques.contains($0) } } } extension UniqueQueue : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return contents.description } public var debugDescription: String { return contents.debugDescription } }
179bdc4dcdc2ff73f17b3501ffbd027e
24.45
119
0.633104
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/Models/Domain.swift
gpl-2.0
2
import Foundation import CoreData import WordPressKit public typealias Domain = RemoteDomain extension Domain { init(managedDomain: ManagedDomain) { domainName = managedDomain.domainName isPrimaryDomain = managedDomain.isPrimary domainType = managedDomain.domainType } } class ManagedDomain: NSManagedObject { // MARK: - NSManagedObject override class var entityName: String { return "Domain" } struct Attributes { static let domainName = "domainName" static let isPrimary = "isPrimary" static let domainType = "domainType" } struct Relationships { static let blog = "blog" } @NSManaged var domainName: String @NSManaged var isPrimary: Bool @NSManaged var domainType: DomainType @NSManaged var blog: Blog func updateWith(_ domain: Domain, blog: Blog) { self.domainName = domain.domainName self.isPrimary = domain.isPrimaryDomain self.domainType = domain.domainType self.blog = blog } } extension Domain: Equatable {} public func ==(lhs: Domain, rhs: Domain) -> Bool { return lhs.domainName == rhs.domainName && lhs.domainType == rhs.domainType && lhs.isPrimaryDomain == rhs.isPrimaryDomain }
2bae0a74f7c585725af76819c5440a1d
23.596154
51
0.670055
false
false
false
false
josepvaleriano/iOS-practices
refs/heads/master
PetCent/PetCent/AppDelegate.swift
mit
1
// // AppDelegate.swift // PetCent // // Created by Infraestructura on 14/10/16. // Copyright © 2016 Valeriano Lopez. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { //let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) //let origen = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCent.sqlite") // 1 Encontrar la unicacion de la BD origen ees en resource con nsbundel let origen = NSBundle.mainBundle().pathForResource("PetCens", ofType: "sqlite") // 2 Obtener la ubicacion destino let destino = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCens.sqlite") //3. valida si la DB no exite en el dfestino if NSFileManager.defaultManager().fileExistsAtPath(destino.path!){ return true; } else{ do{ try NSFileManager.defaultManager().copyItemAtPath(origen!, toPath: destino.path!) print("\tCopio datos de t \(origen) \t al destino \(destino.path)") } catch{ print("\tNo puede copiar de t \(origen) \t al destino \(destino.path)") abort() } } return true //4 } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let masterNavigationController = splitViewController.viewControllers[0] as! UINavigationController let controller = masterNavigationController.topViewController as! MasterViewController controller.managedObjectContext = self.managedObjectContext return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "mx.com.lpz.valeriano.PetCent" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("PetCens", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("PetCens.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
d6c50585d82afa798597b444e098193e
53.956522
291
0.713834
false
false
false
false
fahidattique55/FAPanels
refs/heads/master
FAPanels/IQKeyboardManagerSwift/Categories/IQUIWindow+Hierarchy.swift
apache-2.0
1
// // IQUIWindow+Hierarchy.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 /** @abstract UIWindow hierarchy category. */ public extension UIWindow { /** @return Returns the current Top Most ViewController in hierarchy. */ public func topMostControllerOfWindow()->UIViewController? { var topController = rootViewController while let presentedController = topController?.presentedViewController { topController = presentedController } return topController } /** @return Returns the topViewController in stack of topMostController. */ public func currentViewController()->UIViewController? { var currentViewController = topMostControllerOfWindow() while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil { currentViewController = (currentViewController as! UINavigationController).topViewController } return currentViewController } }
981dd03e666ba4be68d0099b43208087
41.566038
174
0.73094
false
false
false
false
lanserxt/teamwork-ios-sdk
refs/heads/master
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+PeopleStatuses.swift
mit
1
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire extension TWApiClient{ func createStatus(userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){ let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createStatus.path), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.createStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func createStatusForPerson(personId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){ let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createStatusForPerson.path, personId), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.createStatusForPerson.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func updateStatus(statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateStatus.path, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.updateStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func updatePeopleStatus(statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updatePeopleStatus.path, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.updatePeopleStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func updateStatusForPeople(personId: String, statusId: String, userStatus: UserStatus, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["userstatus" : userStatus.dictionaryRepresentation() as! [String: Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.editUser.path, personId, statusId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.editUser.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteStatus(statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteStatus.path, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deletePeopleStatus(statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deletePeopleStatus.path, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deletePeopleStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteStatusForPeople(personId: String, statusId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteStatusForPeople.path, personId, statusId), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.deleteStatusForPeople.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func getCurrentUserStatus(_ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getCurrentUserStatus.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getCurrentUserStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getPeopleStatus(peopleId: String, _ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getPeopleStatus.path, peopleId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getPeopleStatus.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getAllStatuses(_ responseBlock: @escaping (Bool, Int, [UserStatus]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getAllStatuses.path), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<UserStatus>.init(rootObjectName: TWApiClientConstants.APIPath.getAllStatuses.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } }
93fb8085cd73de762bf0a7dea75241d4
53.425714
223
0.533834
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
osx-apps/GeoPhotos/GeoPhotos/DecimalOnlyNumberFormatter.swift
apache-2.0
1
// // DecimalOnlyNumberFormatter.swift // GeoPhotos // // Created by mcxiaoke on 16/6/9. // Copyright © 2016年 mcxiaoke. All rights reserved. // import Cocoa class DecimalOnlyNumberFormatter: NSNumberFormatter { override func awakeFromNib() { super.awakeFromNib() self.setUp() } private func setUp(){ self.allowsFloats = true self.numberStyle = NSNumberFormatterStyle.DecimalStyle self.maximumFractionDigits = 8 } override func isPartialStringValid(partialStringPtr: AutoreleasingUnsafeMutablePointer<NSString?>, proposedSelectedRange proposedSelRangePtr: NSRangePointer, originalString origString: String, originalSelectedRange origSelRange: NSRange, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool { guard let partialString = partialStringPtr.memory as? String else { return true } return !partialString.isEmpty && Double(partialString) != nil } }
0def6b4c2c6a774c0e6dc2832c23a120
30.2
319
0.762821
false
false
false
false
koden-km/dialekt-swift
refs/heads/develop
Dialekt/Parser/ExpressionParser.swift
mit
1
public class ExpressionParser: AbstractParser { public var logicalOrByDefault = false internal override func parseExpression() -> AbstractExpression! { startExpression() var expression = parseUnaryExpression() if expression != nil { expression = parseCompoundExpression(expression) } if expression == nil { return nil } endExpression(expression) return expression } private func parseUnaryExpression() -> AbstractExpression! { let foundExpected = expectToken( TokenType.Text, TokenType.LogicalNot, TokenType.OpenBracket ) if !foundExpected { return nil } if TokenType.LogicalNot == _currentToken.tokenType { return parseLogicalNot() } else if TokenType.OpenBracket == _currentToken.tokenType { return parseNestedExpression() } else if _currentToken.value.rangeOfString(wildcardString, options: NSStringCompareOptions.LiteralSearch) == nil { return parseTag() } else { return parsePattern() } } private func parseTag() -> AbstractExpression { startExpression() let expression = Tag( _currentToken.value ) nextToken() endExpression(expression) return expression } private func parsePattern() -> AbstractExpression { startExpression() // Note: // Could not get regex to escape wildcardString correctly for splitting with capture. // Using string split for now. let parts = _currentToken.value.componentsSeparatedByString(wildcardString) let expression = Pattern() if _currentToken.value.hasPrefix(wildcardString) { expression.add(PatternWildcard()) } var chunks = parts.count - 1 for value in parts { expression.add(PatternLiteral(value)) if chunks > 1 { --chunks expression.add(PatternWildcard()) } } if _currentToken.value.hasSuffix(wildcardString) { expression.add(PatternWildcard()) } nextToken() endExpression(expression) return expression } private func parseNestedExpression() -> AbstractExpression! { startExpression() nextToken() let expression = parseExpression() if expression == nil { return nil } let foundExpected = expectToken(TokenType.CloseBracket) if !foundExpected { return nil } nextToken() endExpression(expression) return expression } private func parseLogicalNot() -> AbstractExpression { startExpression() nextToken() let expression = LogicalNot( parseUnaryExpression() ) endExpression(expression) return expression } private func parseCompoundExpression(expression: ExpressionProtocol, minimumPrecedence: Int = 0) -> AbstractExpression! { var leftExpression = expression var allowCollapse = false while true { // Parse the operator and determine whether or not it's explicit ... let (oper, isExplicit) = parseOperator() let precedence = operatorPrecedence(oper) // Abort if the operator's precedence is less than what we're looking for ... if precedence < minimumPrecedence { break } // Advance the token pointer if an explicit operator token was found ... if isExplicit { nextToken() } // Parse the expression to the right of the operator ... var rightExpression = parseUnaryExpression() if rightExpression == nil { return nil } // Only parse additional compound expressions if their precedence is greater than the // expression already being parsed ... let (nextOperator, _) = parseOperator() if precedence < operatorPrecedence(nextOperator) { rightExpression = parseCompoundExpression(rightExpression, minimumPrecedence: precedence + 1) if rightExpression == nil { return nil } } // Combine the parsed expression with the existing expression ... // Collapse the expression into an existing expression of the same type ... if oper == TokenType.LogicalAnd { if allowCollapse && leftExpression is LogicalAnd { (leftExpression as LogicalAnd).add(rightExpression) } else { leftExpression = LogicalAnd(leftExpression, rightExpression) allowCollapse = true } } else if oper == TokenType.LogicalOr { if allowCollapse && leftExpression is LogicalOr { (leftExpression as LogicalOr).add(rightExpression) } else { leftExpression = LogicalOr(leftExpression, rightExpression) allowCollapse = true } } else { fatalError("Unknown operator type.") } } return leftExpression as AbstractExpression } private func parseOperator() -> (oper: TokenType?, isExplicit: Bool) { // End of input ... if _currentToken == nil { return (nil, false) // Closing bracket ... } else if TokenType.CloseBracket == _currentToken.tokenType { return (nil, false) // Explicit logical OR ... } else if TokenType.LogicalOr == _currentToken.tokenType { return (TokenType.LogicalOr, true) // Explicit logical AND ... } else if TokenType.LogicalAnd == _currentToken.tokenType { return (TokenType.LogicalAnd, true) // Implicit logical OR ... } else if logicalOrByDefault { return (TokenType.LogicalOr, false) // Implicit logical AND ... } else { return (TokenType.LogicalAnd, false) } } private func operatorPrecedence(oper: TokenType?) -> Int { if oper == TokenType.LogicalAnd { return 1 } else if oper == TokenType.LogicalOr { return 0 } else { return -1 } } }
836ee2c4a55021bbeeeaaf8bdb5f59a6
29.637209
125
0.56991
false
false
false
false
cybertk/CKTextFieldTableCell
refs/heads/master
CKTextFieldTableCell/CKTextFieldTableCell.swift
mit
1
// // CKTextFieldTableCell.swift // CKTextFieldTableCell // // Copyright © 2015 cybertk. All rights reserved. // import UIKit public class CKTextFieldTableCell : UITableViewCell { // MARK: Internal Properties // MARK: APIs @IBOutlet var textField: UITextField! @IBInspectable public var enableFixedTitleWidth: Bool = false @IBInspectable public var titleWidth: Int = 100 // MARK: Initilizers // MARK: Overrides public override func awakeFromNib() { super.awakeFromNib(); guard let textField = textField else { print("Warnning: You must set textField in IB") return } // Customize TableCell selectionStyle = .None textField.translatesAutoresizingMaskIntoConstraints = false textLabel?.translatesAutoresizingMaskIntoConstraints = false setupConstraints() } public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) if (textField!.isFirstResponder() && event?.touchesForView(textField) == nil) { // textField lost focus textField!.endEditing(true) } } // MRAK: Priviate private func constraintsWithVisualFormat(format: String, _ options: NSLayoutFormatOptions) -> [NSLayoutConstraint] { let views = [ "textLabel": textLabel!, "textField": textField!, "superview": contentView ] return NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: nil, views: views) } private func setupConstraints() { var constraints: [NSLayoutConstraint] = [] // VFL Syntax, see https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/VisualFormatLanguage/VisualFormatLanguage.html#//apple_ref/doc/uid/TP40010853-CH3-SW1 // Horizontal constraints if enableFixedTitleWidth { textLabel!.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal) constraints += constraintsWithVisualFormat("H:|-15-[textLabel(\(titleWidth))]-20-[textField]-|", .AlignAllCenterY) } else { constraints += constraintsWithVisualFormat("H:|-15-[textLabel]-20-[textField]-|", .AlignAllCenterY) // Remove empty space of textLabel textLabel!.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal) } // Vertical constraints constraints += constraintsWithVisualFormat("H:[superview]-(<=1)-[textLabel]", .AlignAllCenterY) contentView.addConstraints(constraints) } }
de91faa8ab6c0681aac6cd7d5f1957b1
31.988372
205
0.642228
false
false
false
false
watson-developer-cloud/ios-sdk
refs/heads/master
Sources/LanguageTranslatorV3/Models/TranslationModel.swift
apache-2.0
1
/** * (C) Copyright IBM Corp. 2018, 2020. * * 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 /** Response payload for models. */ public struct TranslationModel: Codable, Equatable { /** Availability of a model. */ public enum Status: String { case uploading = "uploading" case uploaded = "uploaded" case dispatching = "dispatching" case queued = "queued" case training = "training" case trained = "trained" case publishing = "publishing" case available = "available" case deleted = "deleted" case error = "error" } /** A globally unique string that identifies the underlying model that is used for translation. */ public var modelID: String /** Optional name that can be specified when the model is created. */ public var name: String? /** Translation source language code. */ public var source: String? /** Translation target language code. */ public var target: String? /** Model ID of the base model that was used to customize the model. If the model is not a custom model, this will be an empty string. */ public var baseModelID: String? /** The domain of the translation model. */ public var domain: String? /** Whether this model can be used as a base for customization. Customized models are not further customizable, and some base models are not customizable. */ public var customizable: Bool? /** Whether or not the model is a default model. A default model is the model for a given language pair that will be used when that language pair is specified in the source and target parameters. */ public var defaultModel: Bool? /** Either an empty string, indicating the model is not a custom model, or the ID of the service instance that created the model. */ public var owner: String? /** Availability of a model. */ public var status: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case modelID = "model_id" case name = "name" case source = "source" case target = "target" case baseModelID = "base_model_id" case domain = "domain" case customizable = "customizable" case defaultModel = "default_model" case owner = "owner" case status = "status" } }
0b577a4e796fb8b51ac1e7fd0bf63e82
27.518519
119
0.646104
false
false
false
false
hooman/swift
refs/heads/main
test/Interop/Cxx/static/static-var-silgen.swift
apache-2.0
5
// RUN: %target-swift-emit-sil -I %S/Inputs -enable-cxx-interop %s | %FileCheck %s import StaticVar func initStaticVars() -> CInt { return staticVar + staticVarInit + staticVarInlineInit + staticConst + staticConstInit + staticConstInlineInit + staticConstexpr + staticNonTrivial.val + staticConstNonTrivial.val + staticConstexprNonTrivial.val } // Constexpr globals should be inlined and removed. // CHECK-NOT: sil_global public_external [let] @staticConstexpr : $Int32 // CHECK: // clang name: staticVar // CHECK: sil_global public_external @staticVar : $Int32 // CHECK: // clang name: staticVarInit // CHECK: sil_global public_external @staticVarInit : $Int32 // CHECK: // clang name: staticVarInlineInit // CHECK: sil_global public_external @staticVarInlineInit : $Int32 // CHECK: // clang name: staticConst // CHECK: sil_global public_external [let] @staticConst : $Int32 // CHECK: // clang name: staticConstInit // CHECK: sil_global public_external [let] @staticConstInit : $Int32 // CHECK: // clang name: staticConstInlineInit // CHECK: sil_global public_external [let] @staticConstInlineInit : $Int32 // CHECK: // clang name: staticNonTrivial // CHECK: sil_global public_external @staticNonTrivial : $NonTrivial // CHECK: // clang name: staticConstNonTrivial // CHECK: sil_global public_external [let] @staticConstNonTrivial : $NonTrivial // CHECK: // clang name: staticConstexprNonTrivial // CHECK: sil_global public_external [let] @staticConstexprNonTrivial : $NonTrivial func readStaticVar() -> CInt { return staticVar } // CHECK: sil hidden @$s4main13readStaticVars5Int32VyF : $@convention(thin) () -> Int32 // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int32 // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*Int32 // CHECK: return [[VALUE]] : $Int32 func writeStaticVar(_ v: CInt) { staticVar = v } // CHECK: sil hidden @$s4main14writeStaticVaryys5Int32VF : $@convention(thin) (Int32) -> () // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32 // CHECK: store %0 to [[ACCESS]] : $*Int32 func readStaticNonTrivial() -> NonTrivial { return staticNonTrivial } // CHECK: sil hidden @$s4main20readStaticNonTrivialSo0dE0VyF : $@convention(thin) () -> NonTrivial // CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*NonTrivial // CHECK: [[VALUE:%.*]] = load [[ACCESS]] : $*NonTrivial // CHECK: return [[VALUE]] : $NonTrivial func writeStaticNonTrivial(_ i: NonTrivial) { staticNonTrivial = i } // CHECK: sil hidden @$s4main21writeStaticNonTrivialyySo0dE0VF : $@convention(thin) (NonTrivial) -> () // CHECK: [[ADDR:%.*]] = global_addr @staticNonTrivial : $*NonTrivial // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*NonTrivial // CHECK: store %0 to [[ACCESS]] : $*NonTrivial func modifyInout(_ c: inout CInt) { c = 42 } func passingVarAsInout() { modifyInout(&staticVar) } // CHECK: sil hidden @$s4main17passingVarAsInoutyyF : $@convention(thin) () -> () // CHECK: [[ADDR:%.*]] = global_addr @staticVar : $*Int32 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int32 // CHECK: [[FUNC:%.*]] = function_ref @$s4main11modifyInoutyys5Int32VzF : $@convention(thin) (@inout Int32) -> () // CHECK: apply [[FUNC]]([[ACCESS]]) : $@convention(thin) (@inout Int32) -> ()
8a047cc0b7e997c38934d7713e17a17c
41.156627
113
0.684481
false
false
false
false
darina/omim
refs/heads/master
iphone/Maps/UI/PlacePage/Components/ActionBarViewController.swift
apache-2.0
5
protocol ActionBarViewControllerDelegate: AnyObject { func actionBar(_ actionBar: ActionBarViewController, didPressButton type: ActionBarButtonType) } class ActionBarViewController: UIViewController { @IBOutlet var stackView: UIStackView! var downloadButton: ActionBarButton? = nil var popoverSourceView: UIView? { stackView.arrangedSubviews.last } var placePageData: PlacePageData! var isRoutePlanning = false var canAddStop = false private var visibleButtons: [ActionBarButtonType] = [] private var additionalButtons: [ActionBarButtonType] = [] weak var delegate: ActionBarViewControllerDelegate? private func configureButtons() { if placePageData.isRoutePoint { visibleButtons.append(.routeRemoveStop) } else if placePageData.roadType != .none { switch placePageData.roadType { case .toll: visibleButtons.append(.avoidToll) case .ferry: visibleButtons.append(.avoidFerry) case .dirty: visibleButtons.append(.avoidDirty) default: fatalError() } } else { configButton1() configButton2() configButton3() configButton4() } for buttonType in visibleButtons { let (selected, enabled) = buttonState(buttonType) let button = ActionBarButton(delegate: self, buttonType: buttonType, partnerIndex: placePageData.partnerIndex, isSelected: selected, isEnabled: enabled) stackView.addArrangedSubview(button) if buttonType == .download { downloadButton = button updateDownloadButtonState(placePageData.mapNodeAttributes!.nodeStatus) } } } func resetButtons() { stackView.arrangedSubviews.forEach { stackView.removeArrangedSubview($0) $0.removeFromSuperview() } visibleButtons.removeAll() additionalButtons.removeAll() downloadButton = nil configureButtons() } override func viewDidLoad() { super.viewDidLoad() configureButtons() } func updateDownloadButtonState(_ nodeStatus: MapNodeStatus) { guard let downloadButton = downloadButton, let mapNodeAttributes = placePageData.mapNodeAttributes else { return } switch mapNodeAttributes.nodeStatus { case .downloading: downloadButton.mapDownloadProgress?.state = .progress case .applying, .inQueue: downloadButton.mapDownloadProgress?.state = .spinner case .error: downloadButton.mapDownloadProgress?.state = .failed case .onDisk, .undefined, .onDiskOutOfDate: downloadButton.mapDownloadProgress?.state = .completed case .notDownloaded, .partly: downloadButton.mapDownloadProgress?.state = .normal @unknown default: fatalError() } } private func configButton1() { if let mapNodeAttributes = placePageData.mapNodeAttributes { switch mapNodeAttributes.nodeStatus { case .onDiskOutOfDate, .onDisk, .undefined: break case .downloading, .applying, .inQueue, .error, .notDownloaded, .partly: visibleButtons.append(.download) return @unknown default: fatalError() } } var buttons: [ActionBarButtonType] = [] if isRoutePlanning { buttons.append(.routeFrom) } if placePageData.previewData.isBookingPlace { buttons.append(.booking) } if placePageData.isPartner { buttons.append(.partner) } if placePageData.bookingSearchUrl != nil { buttons.append(.bookingSearch) } if placePageData.infoData?.phone != nil, AppInfo.shared().canMakeCalls { buttons.append(.call) } if !isRoutePlanning { buttons.append(.routeFrom) } assert(buttons.count > 0) visibleButtons.append(buttons[0]) if buttons.count > 1 { additionalButtons.append(contentsOf: buttons.suffix(from: 1)) } } private func configButton2() { var buttons: [ActionBarButtonType] = [] if canAddStop { buttons.append(.routeAddStop) } buttons.append(.bookmark) assert(buttons.count > 0) visibleButtons.append(buttons[0]) if buttons.count > 1 { additionalButtons.append(contentsOf: buttons.suffix(from: 1)) } } private func configButton3() { visibleButtons.append(.routeTo) } private func configButton4() { if additionalButtons.isEmpty { visibleButtons.append(.share) } else { additionalButtons.append(.share) visibleButtons.append(.more) } } private func showMore() { let actionSheet = UIAlertController(title: placePageData.previewData.title, message: placePageData.previewData.subtitle, preferredStyle: .actionSheet) for button in additionalButtons { let (selected, enabled) = buttonState(button) let action = UIAlertAction(title: titleForButton(button, placePageData.partnerIndex, selected), style: .default, handler: { [weak self] _ in guard let self = self else { return } self.delegate?.actionBar(self, didPressButton: button) }) action.isEnabled = enabled actionSheet.addAction(action) } actionSheet.addAction(UIAlertAction(title: L("cancel"), style: .cancel)) if let popover = actionSheet.popoverPresentationController, let sourceView = stackView.arrangedSubviews.last { popover.sourceView = sourceView popover.sourceRect = sourceView.bounds } present(actionSheet, animated: true) } private func buttonState(_ buttonType: ActionBarButtonType) -> (Bool /* selected */, Bool /* enabled */) { var selected = false var enabled = true if buttonType == .bookmark, let bookmarkData = placePageData.bookmarkData { selected = true enabled = bookmarkData.isEditable } return (selected, enabled) } } extension ActionBarViewController: ActionBarButtonDelegate { func tapOnButton(with type: ActionBarButtonType) { if type == .more { showMore() return } delegate?.actionBar(self, didPressButton: type) } }
522a9cbddda35da8bb7af065ddc2cc0e
30.41
118
0.65632
false
true
false
false
eelcokoelewijn/StepUp
refs/heads/master
StepUp/Modules/Reminder/ReminderViewController.swift
mit
1
import UIKit class ReminderViewController: UIViewController, ReminderViewOutput, UsesReminderViewModel { internal let reminderViewModel: ReminderViewModel private lazy var descriptionLabel: UILabel = { let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.textColor = .buttonDisabled l.font = UIFont.light(withSize: 14) l.textAlignment = .center l.numberOfLines = 0 l.lineBreakMode = .byWordWrapping var text = "Stel hier een reminder in.\nOp het ingestelde tijdstip" text += " ontvang je elke dag een reminder voor je oefeningen." l.text = text l.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) return l }() private lazy var switchOnOff: UISwitch = { let s = UISwitch() s.translatesAutoresizingMaskIntoConstraints = false s.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .horizontal) s.addTarget(self, action: #selector(switchChanged(sender:)), for: .valueChanged) return s }() private lazy var timePicker: UIDatePicker = { let p = UIDatePicker() p.translatesAutoresizingMaskIntoConstraints = false p.datePickerMode = UIDatePicker.Mode.time p.isEnabled = false p.addTarget(self, action: #selector(pickerChanged(sender:)), for: UIControl.Event.valueChanged) return p }() private lazy var noPushMessage: UILabel = { let l = UILabel() l.translatesAutoresizingMaskIntoConstraints = false l.textColor = .buttonDisabled l.font = UIFont.light(withSize: 14) l.textAlignment = .center l.numberOfLines = 0 l.lineBreakMode = .byWordWrapping var text = "Om een reminder in te stellen, heeft StepUp! Push permissies nodig." text += " Deze kun je aanzetten bij Instelligen > StepUp!" l.text = text l.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal) l.isHidden = true return l }() init(viewModel: ReminderViewModel) { reminderViewModel = viewModel super.init(nibName: nil, bundle: nil) reminderViewModel.setModel(output: self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() setupViews() applyViewConstraints() registerForAppActivationNotification() reminderViewModel.start() } // MARK: view output func showReminder(_ date: Date) { timePicker.date = date } func pop() { presentingViewController?.dismiss(animated: true, completion: nil) } func timePicker(enabled: Bool) { timePicker.isEnabled = enabled } func controlSwitch(on: Bool) { switchOnOff.isOn = on } func showNoPushMessage() { noPushMessage.isHidden = false } // MARK: view controller helper @objc func switchChanged(sender: UISwitch) { reminderViewModel.pushTryTo(enabled: sender.isOn, theDate: timePicker.date) } @objc private func cancel(sender: UIBarButtonItem) { reminderViewModel.cancel() } @objc private func pickerChanged(sender: UIDatePicker) { reminderViewModel.save(theDate: sender.date, pushEnabled: switchOnOff.isOn) } private func setupViews() { view.backgroundColor = .white view.addSubview(descriptionLabel) view.addSubview(switchOnOff) view.addSubview(timePicker) view.addSubview(noPushMessage) let leftButton = UIBarButtonItem(title: "Sluiten", style: .plain, target: self, action: #selector(cancel(sender:))) leftButton.tintColor = .actionGreen navigationItem.leftBarButtonItem = leftButton } private func applyViewConstraints() { let views: [String: Any] = ["descriptionLabel": descriptionLabel, "switchOnOff": switchOnOff, "timePicker": timePicker, "noPushMessage": noPushMessage] var constraints: [NSLayoutConstraint] = [] constraints.append(NSLayoutConstraint(item: descriptionLabel, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1, constant: 10)) constraints.append(NSLayoutConstraint(item: switchOnOff, attribute: .centerY, relatedBy: .equal, toItem: descriptionLabel, attribute: .centerY, multiplier: 1, constant: 0)) constraints.append(NSLayoutConstraint(item: timePicker, attribute: .top, relatedBy: .equal, toItem: descriptionLabel, attribute: .bottom, multiplier: 1, constant: 10)) constraints.append(NSLayoutConstraint(item: noPushMessage, attribute: .top, relatedBy: .equal, toItem: timePicker, attribute: .bottom, multiplier: 1, constant: 10)) NSLayoutConstraint.activate(constraints) let vsl = "H:|-15-[descriptionLabel]-8-[switchOnOff]-15-|" NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: vsl, options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[timePicker]-15-|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-15-[noPushMessage]-15-|", options: [], metrics: nil, views: views)) } private func registerForAppActivationNotification() { NotificationCenter.default.addObserver(self, selector: #selector(appBecomeActive(notification:)), name: UIApplication.willEnterForegroundNotification, object: nil) } @objc private func appBecomeActive(notification: Notification) { reminderViewModel.start() } }
4c75b44cc90be1ea3483ffc2de48d0cc
41.005495
115
0.529235
false
false
false
false
Lweek/Formulary
refs/heads/master
Formulary/Forms/TextEntry.swift
mit
1
// // TextEntry.swift // Formulary // // Created by Fabian Canas on 1/17/15. // Copyright (c) 2015 Fabian Canas. All rights reserved. // import Foundation //MARK: Sub-Types public enum TextEntryType: String { case Plain = "Formulary.Plain" case Number = "Formulary.Number" case Decimal = "Formulary.Decimal" case Email = "Formulary.Email" case Twitter = "Formulary.Twitter" case URL = "Formulary.URL" case WebSearch = "Formulary.WebSearch" case Phone = "Formulary.Phone" case NamePhone = "Formulary.PhoneName" } private let KeyMap :[TextEntryType : UIKeyboardType] = [ TextEntryType.Plain : UIKeyboardType.Default, TextEntryType.Number : UIKeyboardType.NumberPad, TextEntryType.Decimal : UIKeyboardType.DecimalPad, TextEntryType.Email : UIKeyboardType.EmailAddress, TextEntryType.Twitter : UIKeyboardType.Twitter, TextEntryType.URL : UIKeyboardType.URL, TextEntryType.WebSearch : UIKeyboardType.WebSearch, TextEntryType.Phone : UIKeyboardType.PhonePad, TextEntryType.NamePhone : UIKeyboardType.NamePhonePad, ] //MARK: Form Row public class TextEntryFormRow : FormRow { public let textType: TextEntryType public let formatter: NSFormatter? public init(name: String, tag: String, textType: TextEntryType = .Plain, value: AnyObject? = nil, validation: Validation = PermissiveValidation, formatter: NSFormatter? = nil, action: Action? = nil) { self.textType = textType self.formatter = formatter super.init(name: name, tag: tag, type: .Specialized, value: value, validation: validation, action: action) } } //MARK: Cell class TextEntryCell: UITableViewCell, FormTableViewCell { var configured: Bool = false var action :Action? var textField :NamedTextField? var formatterAdapter : FormatterAdapter? var formRow :FormRow? { didSet { if var formRow = formRow as? TextEntryFormRow { configureTextField(&formRow).keyboardType = KeyMap[formRow.textType]! } selectionStyle = .None } } func configureTextField(inout row: TextEntryFormRow) -> UITextField { if (textField == nil) { let newTextField = NamedTextField(frame: contentView.bounds) newTextField.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addSubview(newTextField) textField = newTextField contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-15-[textField]-|", options: nil, metrics: nil, views: ["textField":newTextField])) textField = newTextField } formatterAdapter = map(row.formatter) { FormatterAdapter(formatter: $0) } textField?.text = row.value as? String textField?.placeholder = row.name textField?.validation = row.validation textField?.delegate = formatterAdapter textField?.enabled = row.enabled map(textField, { (field :NamedTextField) -> ActionTarget in ActionTarget.clear(field, controlEvents: .EditingChanged) return ActionTarget(control: field, controlEvents: .EditingChanged, action: { _ in row.value = field.text }) }) configured = true return textField! } }
ecfeb5511de8ff747365c7a8c88c0c59
34.905263
204
0.662562
false
false
false
false
ZoranPandovski/al-go-rithms
refs/heads/master
data_structures/trie/swift/trie.swift
cc0-1.0
1
import Foundation class TrieNode { private var charMap: [Character: TrieNode] public var size: Int init() { charMap = [:] size = 0 } public func add(c: Character) { if let _ = self.charMap[c] { // do nothing if exists } else { self.charMap[c] = TrieNode() } } public func getChild(c: Character) -> TrieNode? { return self.charMap[c] } } class Trie { private var root: TrieNode init() { root = TrieNode() } init(words: [String]) { root = TrieNode() for word in words { self.add(word: word) } } public func add(word: String) { var current = root for c in word { current.add(c: c) current = current.getChild(c: c)! current.size = current.size + 1 } } public func find(prefix: String) -> Int { var current = root for c in prefix { if let childNode = current.getChild(c: c) { current = childNode } else { return 0 } } return current.size } }
f5a46ee4bdd4b88a4efd9fee48899250
19.131148
55
0.463355
false
false
false
false
123kyky/SteamReader
refs/heads/master
Demo/Pods/AlamofireImage/Source/UIImage+AlamofireImage.swift
apache-2.0
25
// UIImage+AlamofireImage.swift // // Copyright (c) 2015-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreGraphics import Foundation import UIKit #if os(iOS) || os(tvOS) import CoreImage #endif // MARK: Initialization private let lock = NSLock() extension UIImage { /** Initializes and returns the image object with the specified data in a thread-safe manner. It has been reported that there are thread-safety issues when initializing large amounts of images simultaneously. In the event of these issues occurring, this method can be used in place of the `init?(data:)` method. - parameter data: The data object containing the image data. - returns: An initialized `UIImage` object, or `nil` if the method failed. */ public static func af_threadSafeImageWithData(data: NSData) -> UIImage? { lock.lock() let image = UIImage(data: data) lock.unlock() return image } /** Initializes and returns the image object with the specified data and scale in a thread-safe manner. It has been reported that there are thread-safety issues when initializing large amounts of images simultaneously. In the event of these issues occurring, this method can be used in place of the `init?(data:scale:)` method. - parameter data: The data object containing the image data. - parameter scale: The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. - returns: An initialized `UIImage` object, or `nil` if the method failed. */ public static func af_threadSafeImageWithData(data: NSData, scale: CGFloat) -> UIImage? { lock.lock() let image = UIImage(data: data, scale: scale) lock.unlock() return image } } // MARK: - Inflation extension UIImage { private struct AssociatedKeys { static var InflatedKey = "af_UIImage.Inflated" } /// Returns whether the image is inflated. public var af_inflated: Bool { get { if let inflated = objc_getAssociatedObject(self, &AssociatedKeys.InflatedKey) as? Bool { return inflated } else { return false } } set(inflated) { objc_setAssociatedObject(self, &AssociatedKeys.InflatedKey, inflated, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /** Inflates the underlying compressed image data to be backed by an uncompressed bitmap representation. Inflating compressed image formats (such as PNG or JPEG) can significantly improve drawing performance as it allows a bitmap representation to be constructed in the background rather than on the main thread. */ public func af_inflate() { guard !af_inflated else { return } af_inflated = true CGDataProviderCopyData(CGImageGetDataProvider(CGImage)) } } // MARK: - Alpha extension UIImage { /// Returns whether the image contains an alpha component. public var af_containsAlphaComponent: Bool { let alphaInfo = CGImageGetAlphaInfo(CGImage) return ( alphaInfo == .First || alphaInfo == .Last || alphaInfo == .PremultipliedFirst || alphaInfo == .PremultipliedLast ) } /// Returns whether the image is opaque. public var af_isOpaque: Bool { return !af_containsAlphaComponent } } // MARK: - Scaling extension UIImage { /** Returns a new version of the image scaled to the specified size. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageScaledToSize(size: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) drawInRect(CGRect(origin: CGPointZero, size: size)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } /** Returns a new version of the image scaled from the center while maintaining the aspect ratio to fit within a specified size. The resulting image contains an alpha component used to pad the width or height with the necessary transparent pixels to fit the specified size. In high performance critical situations, this may not be the optimal approach. To maintain an opaque image, you could compute the `scaledSize` manually, then use the `af_imageScaledToSize` method in conjunction with a `.Center` content mode to achieve the same visual result. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageAspectScaledToFitSize(size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.width / self.size.width } else { resizeFactor = size.height / self.size.height } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, false, 0.0) drawInRect(CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } /** Returns a new version of the image scaled from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall outside the specified size are clipped. - parameter size: The size to use when scaling the new image. - returns: A new image object. */ public func af_imageAspectScaledToFillSize(size: CGSize) -> UIImage { let imageAspectRatio = self.size.width / self.size.height let canvasAspectRatio = size.width / size.height var resizeFactor: CGFloat if imageAspectRatio > canvasAspectRatio { resizeFactor = size.height / self.size.height } else { resizeFactor = size.width / self.size.width } let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor) let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0) UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0) drawInRect(CGRect(origin: origin, size: scaledSize)) let scaledImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return scaledImage } } // MARK: - Rounded Corners extension UIImage { /** Returns a new version of the image with the corners rounded to the specified radius. - parameter radius: The radius to use when rounding the new image. - parameter divideRadiusByImageScale: Whether to divide the radius by the image scale. Set to `true` when the image has the same resolution for all screen scales such as @1x, @2x and @3x (i.e. single image from web server). Set to `false` for images loaded from an asset catalog with varying resolutions for each screen scale. `false` by default. - returns: A new image object. */ public func af_imageWithRoundedCornerRadius(radius: CGFloat, divideRadiusByImageScale: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0.0) let scaledRadius = divideRadiusByImageScale ? radius / scale : radius let clippingPath = UIBezierPath(roundedRect: CGRect(origin: CGPointZero, size: size), cornerRadius: scaledRadius) clippingPath.addClip() drawInRect(CGRect(origin: CGPointZero, size: size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage } /** Returns a new version of the image rounded into a circle. - returns: A new image object. */ public func af_imageRoundedIntoCircle() -> UIImage { let radius = min(size.width, size.height) / 2.0 var squareImage = self if size.width != size.height { let squareDimension = min(size.width, size.height) let squareSize = CGSize(width: squareDimension, height: squareDimension) squareImage = af_imageAspectScaledToFillSize(squareSize) } UIGraphicsBeginImageContextWithOptions(squareImage.size, false, 0.0) let clippingPath = UIBezierPath( roundedRect: CGRect(origin: CGPointZero, size: squareImage.size), cornerRadius: radius ) clippingPath.addClip() squareImage.drawInRect(CGRect(origin: CGPointZero, size: squareImage.size)) let roundedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return roundedImage } } #if os(iOS) || os(tvOS) // MARK: - Core Image Filters extension UIImage { /** Returns a new version of the image using a CoreImage filter with the specified name and parameters. - parameter filterName: The name of the CoreImage filter to use on the new image. - parameter filterParameters: The parameters to apply to the CoreImage filter. - returns: A new image object, or `nil` if the filter failed for any reason. */ public func af_imageWithAppliedCoreImageFilter( filterName: String, filterParameters: [String: AnyObject]? = nil) -> UIImage? { var image: CoreImage.CIImage? = CIImage if image == nil, let CGImage = self.CGImage { image = CoreImage.CIImage(CGImage: CGImage) } guard let coreImage = image else { return nil } let context = CIContext(options: [kCIContextPriorityRequestLow: true]) var parameters: [String: AnyObject] = filterParameters ?? [:] parameters[kCIInputImageKey] = coreImage guard let filter = CIFilter(name: filterName, withInputParameters: parameters) else { return nil } guard let outputImage = filter.outputImage else { return nil } let cgImageRef = context.createCGImage(outputImage, fromRect: outputImage.extent) return UIImage(CGImage: cgImageRef, scale: scale, orientation: imageOrientation) } } #endif
1b93cc671d33fcefeabafa702ab33fa8
36.523077
121
0.666995
false
false
false
false
ioscreator/ioscreator
refs/heads/master
IOSSnapBehaviourTutorial/IOSSnapBehaviourTutorial/ViewController.swift
mit
1
// // ViewController.swift // IOSSnapBehaviourTutorial // // Created by Arthur Knopper on 24/02/2019. // Copyright © 2019 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { var animator:UIDynamicAnimator! var snapBehaviour:UISnapBehavior! @IBOutlet weak var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Create the Tap Gesture Recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userHasTapped)) self.view.addGestureRecognizer(tapGesture) // Create the Dynamic Animator animator = UIDynamicAnimator(referenceView: view) } @objc func userHasTapped(tap:UITapGestureRecognizer) { let touchPoint = tap.location(in: view) if snapBehaviour != nil { animator.removeBehavior(snapBehaviour) } snapBehaviour = UISnapBehavior(item: imageView, snapTo: touchPoint) snapBehaviour.damping = 0.3 animator.addBehavior(snapBehaviour) } }
418548b0295bdb3de4048444ffff296d
26.725
95
0.667268
false
false
false
false
SvenTiigi/PerfectAPIClient
refs/heads/master
Sources/PerfectAPIClient/Models/APIClientResponse.swift
mit
1
// // APIClientResponse.swift // PerfectAPIClient // // Created by Sven Tiigi on 30.10.17. // import Foundation import PerfectCURL import PerfectHTTP import ObjectMapper /// APIClientResponse represents an API response public struct APIClientResponse { /// The url that has been requested public let url: String /// The response status public let status: HTTPResponseStatus /// The payload public var payload: String /// The request public var request: APIClientRequest /// Indicating if the response is successful (Status code: 200 - 299) public var isSuccessful: Bool { return 200 ... 299 ~= self.status.code } /// The curlResponse private var curlResponse: CURLResponse? /// The response HTTP headers set via initializer private var headers: [String: String]? /// Initializer to construct custom APIClientResponse /// /// - Parameters: /// - url: The request url /// - status: The response status /// - headers: The response HTTP header fields /// - payload: The response payload public init(url: String, status: HTTPResponseStatus, payload: String, request: APIClientRequest, headers: [String: String]? = nil) { self.url = url self.status = status self.payload = payload self.request = request self.headers = headers } /// Intitializer with CURLResponse /// /// - Parameter curlResponse: The CURLResponse public init(request: APIClientRequest, curlResponse: CURLResponse) { self.init( url: curlResponse.url, status: HTTPResponseStatus.statusFrom(code: curlResponse.responseCode), payload: curlResponse.bodyString, request: request ) self.curlResponse = curlResponse } /// Get response HTTP header field /// /// - Parameter name: The HTTP header response name /// - Returns: The HTTP header field value public func getHTTPHeader(name: HTTPResponseHeader.Name) -> String? { // Check if headers are available by direct initialization if let headers = self.headers { // Return HTTP header field return headers[name.standardName] } else if let curlResponse = self.curlResponse { // Return HTTP header field from CURLResponse return curlResponse.get(name) } else { // Unable to return HTTP header field return nil } } /// Retrieve Payload in JSON/Dictionary format /// /// - Returns: The payload as Dictionary public func getPayloadJSON() -> [String: Any]? { // Instantiate Data object from payload let data = Data(self.payload.utf8) // JSONSerialization payload data to Dictionary guard let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String: Any] else { // JSONSerialization fails return nil return nil } // Return JSON/Dictionary format return json } /// Retrieve Payload in JSON Array format /// /// - Returns: The payload as Array public func getPayloadJSONArray() -> [[String: Any]]? { // Instantiate Data object from payload let data = Data(self.payload.utf8) // JSONSerialization payload data to Array guard let jsonArray = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [[String: Any]] else { // JSONSerialization fails return nil return nil } // Return JSON Array return jsonArray } /// Retrieve Payload as Mappable Type /// /// - Parameters: /// - type: The mappable type /// - Returns: The mapped object type public func getMappablePayload<T: BaseMappable>(type: T.Type) -> T? { // Try to construct mappable with payload guard let mappable = Mapper<T>().map(JSONString: self.payload) else { // Unable to construct return nil return nil } // Return mapped object return mappable } /// Retrieve Payload as Mappable Array Type /// /// - Parameter type: The mappable type /// - Returns: The mapped object array public func getMappablePayloadArray<T: BaseMappable>(type: T.Type) -> [T]? { // Try to construct mappables with payload guard let mappables = Mapper<T>().mapArray(JSONString: self.payload) else { // Unable to construct mappables return nil return nil } // Return mapped objects return mappables } } // MARK: CustomStringConvertible Extension extension APIClientResponse: JSONCustomStringConvertible { /// A JSON representation of this instance public var json: [String: Any] { return [ "url": self.url, "status": self.status.description, "payload": self.payload, "request": self.request.description, "isSuccessful": self.isSuccessful ] } }
f40e8be9c3c52be35d463b1c62de9e59
30.864198
117
0.611003
false
false
false
false
KevinCoble/AIToolbox
refs/heads/master
Playgrounds/LinearRegression.playground/Sources/MachineLearningProtocols.swift
apache-2.0
1
// // MachineLearningProtocols.swift // AIToolbox // // Created by Kevin Coble on 1/16/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation public enum MachineLearningError: Error { case dataNotRegression case dataWrongDimension case notEnoughData case modelNotRegression case modelNotClassification case notTrained case initializationError case didNotConverge case continuationNotSupported case operationTimeout case continueTrainingClassesNotSame } public protocol Classifier { func getInputDimension() -> Int func getParameterDimension() -> Int // May only be valid after training func getNumberOfClasses() -> Int // May only be valid after training func setParameters(_ parameters: [Double]) throws func setCustomInitializer(_ function: ((_ trainData: DataSet)->[Double])!) func getParameters() throws -> [Double] func trainClassifier(_ trainData: DataSet) throws func continueTrainingClassifier(_ trainData: DataSet) throws // Trains without initializing parameters first func classifyOne(_ inputs: [Double]) throws ->Int func classify(_ testData: DataSet) throws } public protocol Regressor { func getInputDimension() -> Int func getOutputDimension() -> Int func getParameterDimension() -> Int func setParameters(_ parameters: [Double]) throws func setCustomInitializer(_ function: ((_ trainData: DataSet)->[Double])!) func getParameters() throws -> [Double] func trainRegressor(_ trainData: DataSet) throws func continueTrainingRegressor(_ trainData: DataSet) throws // Trains without initializing parameters first func predictOne(_ inputs: [Double]) throws ->[Double] func predict(_ testData: DataSet) throws } public protocol NonLinearEquation { // If output dimension > 1, parameters is a matrix with each row the parameters for one of the outputs var parameters: [Double] { get set } func getInputDimension() -> Int func getOutputDimension() -> Int func getParameterDimension() -> Int // This must be an integer multiple of output dimension func setParameters(_ parameters: [Double]) throws func getOutputs(_ inputs: [Double]) throws -> [Double] // Returns vector outputs sized for outputs func getGradient(_ inputs: [Double]) throws -> [Double] // Returns vector gradient sized for parameters - can be stubbed for ParameterDelta method } extension Classifier { /// Calculate the precentage correct on a classification network using a test data set public func getClassificationPercentage(_ testData: DataSet) throws -> Double { // Verify the data set is the right type if (testData.dataType != .classification) { throw DataTypeError.invalidDataType } var countCorrect = 0 // Do for the entire test set for index in 0..<testData.size { // Get the results of a feedForward run let result = try classifyOne(testData.inputs[index]) if (result == testData.classes![index]) {countCorrect += 1} } // Calculate the percentage return Double(countCorrect) / Double(testData.size) } } extension Regressor { /// Calculate the total absolute value of error on a regressor using a test data set public func getTotalAbsError(_ testData: DataSet) throws -> Double { // Verify the data set is the right type if (testData.dataType != .regression) { throw DataTypeError.invalidDataType } var sum = 0.0 // Do for the entire test set for index in 0..<testData.size{ // Get the results of a prediction let results = try predictOne(testData.inputs[index]) // Sum up the differences for nodeIndex in 0..<results.count { sum += abs(results[nodeIndex] - testData.outputs![index][nodeIndex]) } } return sum } } internal class ClassificationData { var foundLabels: [Int] = [] var classCount: [Int] = [] var classOffsets: [[Int]] = [] var numClasses: Int { return foundLabels.count } }
4663ab9d52c1c5b5430c7e475f9cfa84
34.352459
157
0.658938
false
true
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/FMS/FMS_Paginator.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension FMS { /// Returns an array of PolicyComplianceStatus objects. Use PolicyComplianceStatus to get a summary of which member accounts are protected by the specified policy. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listComplianceStatusPaginator<Result>( _ input: ListComplianceStatusRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listComplianceStatus, tokenKey: \ListComplianceStatusResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listComplianceStatusPaginator( _ input: ListComplianceStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listComplianceStatus, tokenKey: \ListComplianceStatusResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns a MemberAccounts object that lists the member accounts in the administrator's AWS organization. The ListMemberAccounts must be submitted by the account that is set as the AWS Firewall Manager administrator. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listMemberAccountsPaginator<Result>( _ input: ListMemberAccountsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listMemberAccounts, tokenKey: \ListMemberAccountsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listMemberAccountsPaginator( _ input: ListMemberAccountsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listMemberAccounts, tokenKey: \ListMemberAccountsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Returns an array of PolicySummary objects. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listPoliciesPaginator<Result>( _ input: ListPoliciesRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listPolicies, tokenKey: \ListPoliciesResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listPoliciesPaginator( _ input: ListPoliciesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListPoliciesResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listPolicies, tokenKey: \ListPoliciesResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension FMS.ListComplianceStatusRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> FMS.ListComplianceStatusRequest { return .init( maxResults: self.maxResults, nextToken: token, policyId: self.policyId ) } } extension FMS.ListMemberAccountsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> FMS.ListMemberAccountsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension FMS.ListPoliciesRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> FMS.ListPoliciesRequest { return .init( maxResults: self.maxResults, nextToken: token ) } }
8cd6420744af83b235cab6888b7431aa
41.910891
223
0.643286
false
false
false
false
argon/mas
refs/heads/master
MasKit/Formatters/AppListFormatter.swift
mit
1
// // AppListFormatter.swift // MasKit // // Created by Ben Chatelain on 6/7/20. // Copyright © 2019 mas-cli. All rights reserved. // import Foundation /// Formats text output for the search command. struct AppListFormatter { static let idColumnMinWidth = 10 static let nameColumnMinWidth = 50 /// Formats text output with list results. /// /// - Parameter products: List of sortware products app data. /// - Returns: Multiliune text outoutp. static func format(products: [SoftwareProduct]) -> String { // find longest appName for formatting, default 50 let maxLength = products.map { $0.appNameOrBbundleIdentifier } .max(by: { $1.count > $0.count })?.count ?? nameColumnMinWidth var output: String = "" for product in products { let appId = product.itemIdentifier.stringValue .padding(toLength: idColumnMinWidth, withPad: " ", startingAt: 0) let appName = product.appNameOrBbundleIdentifier.padding(toLength: maxLength, withPad: " ", startingAt: 0) let version = product.bundleVersion output += "\(appId) \(appName) (\(version))\n" } return output.trimmingCharacters(in: .newlines) } }
bad9f6ea05329c514852dc8dce42883f
30.725
118
0.635146
false
false
false
false
AngryLi/Onmyouji
refs/heads/master
Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesAPI.swift
mit
4
// // GitHubSearchRepositoriesAPI.swift // RxExample // // Created by Krunoslav Zaher on 10/18/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif import struct Foundation.URL import struct Foundation.Data import struct Foundation.URLRequest import struct Foundation.NSRange import class Foundation.HTTPURLResponse import class Foundation.URLSession import class Foundation.NSRegularExpression import class Foundation.JSONSerialization import class Foundation.NSString /** Parsed GitHub repository. */ struct Repository: CustomDebugStringConvertible { var name: String var url: URL init(name: String, url: URL) { self.name = name self.url = url } } extension Repository { var debugDescription: String { return "\(name) | \(url)" } } enum GitHubServiceError: Error { case offline case githubLimitReached case networkError } typealias SearchRepositoriesResponse = Result<(repositories: [Repository], nextURL: URL?), GitHubServiceError> class GitHubSearchRepositoriesAPI { // ***************************************************************************************** // !!! This is defined for simplicity sake, using singletons isn't advised !!! // !!! This is just a simple way to move services to one location so you can see Rx code !!! // ***************************************************************************************** static let sharedAPI = GitHubSearchRepositoriesAPI(reachabilityService: try! DefaultReachabilityService()) fileprivate let _reachabilityService: ReachabilityService private init(reachabilityService: ReachabilityService) { _reachabilityService = reachabilityService } } extension GitHubSearchRepositoriesAPI { public func loadSearchURL(_ searchURL: URL) -> Observable<SearchRepositoriesResponse> { return URLSession.shared .rx.response(request: URLRequest(url: searchURL)) .retry(3) .observeOn(Dependencies.sharedDependencies.backgroundWorkScheduler) .map { httpResponse, data -> SearchRepositoriesResponse in if httpResponse.statusCode == 403 { return .failure(.githubLimitReached) } let jsonRoot = try GitHubSearchRepositoriesAPI.parseJSON(httpResponse, data: data) guard let json = jsonRoot as? [String: AnyObject] else { throw exampleError("Casting to dictionary failed") } let repositories = try Repository.parse(json) let nextURL = try GitHubSearchRepositoriesAPI.parseNextURL(httpResponse) return .success(repositories: repositories, nextURL: nextURL) } .retryOnBecomesReachable(.failure(.offline), reachabilityService: _reachabilityService) } } // MARK: Parsing the response extension GitHubSearchRepositoriesAPI { private static let parseLinksPattern = "\\s*,?\\s*<([^\\>]*)>\\s*;\\s*rel=\"([^\"]*)\"" private static let linksRegex = try! NSRegularExpression(pattern: parseLinksPattern, options: [.allowCommentsAndWhitespace]) fileprivate static func parseLinks(_ links: String) throws -> [String: String] { let length = (links as NSString).length let matches = GitHubSearchRepositoriesAPI.linksRegex.matches(in: links, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: length)) var result: [String: String] = [:] for m in matches { let matches = (1 ..< m.numberOfRanges).map { rangeIndex -> String in let range = m.rangeAt(rangeIndex) let startIndex = links.characters.index(links.startIndex, offsetBy: range.location) let endIndex = links.characters.index(links.startIndex, offsetBy: range.location + range.length) let stringRange = startIndex ..< endIndex return links.substring(with: stringRange) } if matches.count != 2 { throw exampleError("Error parsing links") } result[matches[1]] = matches[0] } return result } fileprivate static func parseNextURL(_ httpResponse: HTTPURLResponse) throws -> URL? { guard let serializedLinks = httpResponse.allHeaderFields["Link"] as? String else { return nil } let links = try GitHubSearchRepositoriesAPI.parseLinks(serializedLinks) guard let nextPageURL = links["next"] else { return nil } guard let nextUrl = URL(string: nextPageURL) else { throw exampleError("Error parsing next url `\(nextPageURL)`") } return nextUrl } fileprivate static func parseJSON(_ httpResponse: HTTPURLResponse, data: Data) throws -> AnyObject { if !(200 ..< 300 ~= httpResponse.statusCode) { throw exampleError("Call failed") } return try JSONSerialization.jsonObject(with: data, options: []) as AnyObject } } extension Repository { fileprivate static func parse(_ json: [String: AnyObject]) throws -> [Repository] { guard let items = json["items"] as? [[String: AnyObject]] else { throw exampleError("Can't find items") } return try items.map { item in guard let name = item["name"] as? String, let url = item["url"] as? String else { throw exampleError("Can't parse repository") } return Repository(name: name, url: try URL(string: url).unwrap()) } } }
dd84829d386ca6a1d33f5caabfa5703e
33.433735
172
0.626662
false
false
false
false
NoodleOfDeath/PastaParser
refs/heads/master
runtime/swift/GrammarKit/Classes/model/io/IO.TokenStream.swift
mit
1
// // The MIT License (MIT) // // Copyright © 2020 NoodleOfDeath. All rights reserved. // NoodleOfDeath // // 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 extension IO { /// Data structure that represents a token stream. open class TokenStream<T: Token>: NSObject, IOStream { public typealias Atom = T public typealias AtomSequence = [T] // MARK: - CustomStringConvertible Properties override open var description: String { return tokens.map({ $0.description }).joined(separator: ", ") } // MARK: - IOStream Properties open var length: Int { guard let first = tokens.first, let last = tokens.last else { return 0 } return last.range.max - first.range.location } /// Shorthand for `NSMakeRange(0, length)`. open var range: NSRange { guard let first = tokens.first else { return .zero } return NSMakeRange(first.range.location, length) } // MARK: - Instance Properties /// Tokens contained in this token stream. open var tokens = AtomSequence() /// Number of tokens open var tokenCount: Int { return tokens.count } /// Character stream from which tokens were derived. public let characterStream: CharacterStream /// Constructs a new token stream with an initial character stream. /// /// - Parameters: /// - characterStream: of the new token stream. public init(characterStream: CharacterStream) { self.characterStream = characterStream } open subscript(index: Int) -> Atom { return tokens[index] } open subscript(range: Range<Int>) -> AtomSequence { var subtokens = AtomSequence() for i in range.lowerBound ..< range.upperBound { subtokens.append(tokens[i]) } return subtokens } open func reduce<Result>(over range: Range<Int>, _ prefix: Result, _ lambda: ((Result, Atom) -> Result)) -> Result { return self[range].reduce(prefix, lambda) } /// Adds a token to this token stream. /// /// - Parameters: /// - token: to add to this token stream. open func add(token: Atom) { tokens.append(token) } } } extension IO.TokenStream { public func reduce<Result>(over range: NSRange, _ prefix: Result, _ lambda: ((Result, Atom) -> Result)) -> Result { return reduce(over: range.bridgedRange, prefix, lambda) } }
a4acb7c1cc98ae115b948857c81de968
33.609524
124
0.641992
false
false
false
false
AlesTsurko/DNMKit
refs/heads/master
DNM_iOS/DNM_iOS/UIBezierPathExtensions.swift
gpl-2.0
1
// // UIBezierPathExtensions.swift // denm_view // // Created by James Bean on 8/17/15. // Copyright © 2015 James Bean. All rights reserved. // import UIKit import DNMModel extension UIBezierPath { public func rotate(degrees degrees: Float) { let bounds = CGPathGetBoundingBox(self.CGPath) let center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)) let toOrigin = CGAffineTransformMakeTranslation(-center.x, -center.y) let rotation = CGAffineTransformMakeRotation(CGFloat(DEGREES_TO_RADIANS(degrees))) let fromOrigin = CGAffineTransformMakeTranslation(center.x, center.y) self.applyTransform(toOrigin) self.applyTransform(rotation) self.applyTransform(fromOrigin) } public func mirror() { let mirrorOverXOrigin = CGAffineTransformMakeScale(-1, 1) let translate = CGAffineTransformMakeTranslation(bounds.width, 0) self.applyTransform(mirrorOverXOrigin) self.applyTransform(translate) } public func scale(sx: CGFloat, sy: CGFloat) { let scale = CGAffineTransformMakeScale(sx, sy) let beforeBounds = CGPathGetBoundingBox(self.CGPath) let beforeCenter = CGPointMake(CGRectGetMidX(beforeBounds), CGRectGetMidY(beforeBounds)) self.applyTransform(scale) let afterBounds = CGPathGetBoundingBox(self.CGPath) let afterCenter = CGPointMake(CGRectGetMidX(afterBounds), CGRectGetMidY(afterBounds)) let ΔY: CGFloat = -(afterCenter.y - beforeCenter.y) let ΔX: CGFloat = -(afterCenter.x - beforeCenter.x) let backToCenter = CGAffineTransformMakeTranslation(ΔX, ΔY) self.applyTransform(backToCenter) } }
38a04eb448e41ee585f26202f88ebdcc
38.090909
96
0.704651
false
false
false
false
robconrad/fledger-common
refs/heads/master
FledgerCommon/services/models/location/LocationAnnotation.swift
mit
1
// // LocationAnnotation.swift // fledger-ios // // Created by Robert Conrad on 4/26/15. // Copyright (c) 2015 Robert Conrad. All rights reserved. // import Foundation import MapKit public class LocationAnnotation: MKPointAnnotation { public let location: Location public required init(location: Location) { self.location = location super.init() coordinate = location.coordinate title = location.title() subtitle = location.title() == location.address ? nil : location.address } }
446cf657871d4e72be47d39c61dbac2f
20.222222
80
0.63986
false
false
false
false
apple/swift
refs/heads/main
test/AutoDiff/SILOptimizer/differentiation_control_flow_sil.swift
apache-2.0
2
// RUN: %target-swift-frontend -emit-sil -verify -Xllvm -debug-only=differentiation 2>&1 %s | %FileCheck %s -check-prefix=CHECK-DATA-STRUCTURES // RUN: %target-swift-frontend -emit-sil -verify -Xllvm -sil-print-after=differentiation -o /dev/null 2>&1 %s | %FileCheck %s -check-prefix=CHECK-SIL // REQUIRES: asserts // TODO: Add FileCheck tests. import _Differentiation //===----------------------------------------------------------------------===// // Conditionals //===----------------------------------------------------------------------===// @differentiable(reverse) @_silgen_name("cond") func cond(_ x: Float) -> Float { if x > 0 { return x + x } return x - x } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb0__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb1__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb1__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: var pullback_0: (Float) -> (Float, Float) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb2__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb2__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: var pullback_1: (Float) -> (Float, Float) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: struct _AD__cond_bb3__PB__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: var predecessor: _AD__cond_bb3__Pred__src_0_wrt_0 // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb0__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb1__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb0(_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb2__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb0(_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-DATA-STRUCTURES: enum _AD__cond_bb3__Pred__src_0_wrt_0 { // CHECK-DATA-STRUCTURES: case bb2(_AD__cond_bb2__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: case bb1(_AD__cond_bb1__PB__src_0_wrt_0) // CHECK-DATA-STRUCTURES: } // CHECK-SIL-LABEL: sil hidden [ossa] @condTJrSpSr : $@convention(thin) (Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[INPUT_ARG:%.*]] : $Float): // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__cond_bb0__PB__src_0_wrt_0 () // CHECK-SIL: cond_br {{%.*}}, bb1, bb2 // CHECK-SIL: bb1: // CHECK-SIL: [[BB1_PRED:%.*]] = enum $_AD__cond_bb1__Pred__src_0_wrt_0, #_AD__cond_bb1__Pred__src_0_wrt_0.bb0!enumelt, [[BB0_PB_STRUCT]] // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__cond_bb1__PB__src_0_wrt_0 // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__cond_bb3__Pred__src_0_wrt_0, #_AD__cond_bb3__Pred__src_0_wrt_0.bb1!enumelt, [[BB1_PB_STRUCT]] // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED1]] : $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: bb2: // CHECK-SIL: [[BB2_PRED:%.*]] = enum $_AD__cond_bb2__Pred__src_0_wrt_0, #_AD__cond_bb2__Pred__src_0_wrt_0.bb0!enumelt, [[BB0_PB_STRUCT]] // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__cond_bb2__PB__src_0_wrt_0 // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__cond_bb3__Pred__src_0_wrt_0, #_AD__cond_bb3__Pred__src_0_wrt_0.bb2!enumelt, [[BB2_PB_STRUCT]] // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED2]] : $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: bb3([[ORIG_RES:%.*]] : $Float, [[BB3_PRED_ARG:%.*]] : @owned $_AD__cond_bb3__Pred__src_0_wrt_0) // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__cond_bb3__PB__src_0_wrt_0 // CHECK-SIL: [[PULLBACK_REF:%.*]] = function_ref @condTJpSpSr // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PULLBACK_REF]]([[BB3_PB_STRUCT]]) // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[ORIG_RES]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] // CHECK-SIL-LABEL: sil private [ossa] @condTJpSpSr : $@convention(thin) (Float, @owned _AD__cond_bb3__PB__src_0_wrt_0) -> Float { // CHECK-SIL: bb0([[SEED:%.*]] : $Float, [[BB3_PB_STRUCT:%.*]] : @owned $_AD__cond_bb3__PB__src_0_wrt_0): // CHECK-SIL: [[BB3_PRED:%.*]] = destructure_struct [[BB3_PB_STRUCT]] : $_AD__cond_bb3__PB__src_0_wrt_0 // CHECK-SIL: switch_enum [[BB3_PRED]] : $_AD__cond_bb3__Pred__src_0_wrt_0, case #_AD__cond_bb3__Pred__src_0_wrt_0.bb2!enumelt: bb1, case #_AD__cond_bb3__Pred__src_0_wrt_0.bb1!enumelt: bb3 // CHECK-SIL: bb1([[BB3_PRED2_TRAMP_PB_STRUCT:%.*]] : @owned $_AD__cond_bb2__PB__src_0_wrt_0): // CHECK-SIL: br bb2({{%.*}} : $Float, {{%.*}}: $Float, [[BB3_PRED2_TRAMP_PB_STRUCT]] : $_AD__cond_bb2__PB__src_0_wrt_0) // CHECK-SIL: bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB2_PB_STRUCT:%.*]] : @owned $_AD__cond_bb2__PB__src_0_wrt_0): // CHECK-SIL: ([[BB2_PRED:%.*]], [[BB2_PB:%.*]]) = destructure_struct [[BB2_PB_STRUCT]] // CHECK-SIL: [[BB2_ADJVALS:%.*]] = apply [[BB2_PB]]([[SEED]]) : $@callee_guaranteed (Float) -> (Float, Float) // CHECK-SIL: switch_enum [[BB2_PRED]] : $_AD__cond_bb2__Pred__src_0_wrt_0, case #_AD__cond_bb2__Pred__src_0_wrt_0.bb0!enumelt: bb6 // CHECK-SIL: bb3([[BB3_PRED1_TRAMP_PB_STRUCT:%.*]] : @owned $_AD__cond_bb1__PB__src_0_wrt_0): // CHECK-SIL: br bb4({{%.*}} : $Float, {{%.*}}: $Float, [[BB3_PRED1_TRAMP_PB_STRUCT]] : $_AD__cond_bb1__PB__src_0_wrt_0) // CHECK-SIL: bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB1_PB_STRUCT:%.*]] : @owned $_AD__cond_bb1__PB__src_0_wrt_0): // CHECK-SIL: ([[BB1_PRED:%.*]], [[BB1_PB:%.*]]) = destructure_struct [[BB1_PB_STRUCT]] // CHECK-SIL: [[BB1_ADJVALS:%.*]] = apply [[BB1_PB]]([[SEED]]) : $@callee_guaranteed (Float) -> (Float, Float) // CHECK-SIL: switch_enum [[BB1_PRED]] : $_AD__cond_bb1__Pred__src_0_wrt_0, case #_AD__cond_bb1__Pred__src_0_wrt_0.bb0!enumelt: bb5 // CHECK-SIL: bb5([[BB1_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB1_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb6([[BB2_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB2_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb7({{%.*}} : $Float, [[BB0_PB_STRUCT:%.*]] : $_AD__cond_bb0__PB__src_0_wrt_0): // CHECK-SIL: return {{%.*}} : $Float @differentiable(reverse) @_silgen_name("nested_cond") func nested_cond(_ x: Float, _ y: Float) -> Float { if x > 0 { if y > 10 { return x * y } else { return x + y } } return y - x } @differentiable(reverse) @_silgen_name("nested_cond_generic") func nested_cond_generic<T : Differentiable & FloatingPoint>(_ x: T, _ y: T) -> T { if x > 0 { if y > 10 { return y } else { return x } } return y } @differentiable(reverse) @_silgen_name("loop_generic") func loop_generic<T : Differentiable & FloatingPoint>(_ x: T) -> T { var result = x for _ in 1..<3 { var y = x for _ in 1..<3 { result = y y = result } } return result } // Test `switch_enum`. enum Enum { case a(Float) case b(Float, Float) } @differentiable(reverse) @_silgen_name("enum_notactive") func enum_notactive(_ e: Enum, _ x: Float) -> Float { switch e { case let .a(a): return x * a case let .b(b1, b2): return x * b1 * b2 } } // CHECK-SIL-LABEL: sil hidden [ossa] @enum_notactiveTJrUSpSr : $@convention(thin) (Enum, Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[ENUM_ARG:%.*]] : $Enum, [[X_ARG:%.*]] : $Float): // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb0__PB__src_0_wrt_1 () // CHECK-SIL: switch_enum [[ENUM_ARG]] : $Enum, case #Enum.a!enumelt: bb1, case #Enum.b!enumelt: bb2 // CHECK-SIL: bb1([[ENUM_A:%.*]] : $Float): // CHECK-SIL: [[BB1_PRED_PRED0:%.*]] = enum $_AD__enum_notactive_bb1__Pred__src_0_wrt_1, #_AD__enum_notactive_bb1__Pred__src_0_wrt_1.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_notactive_bb0__PB__src_0_wrt_1 // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb1__PB__src_0_wrt_1 ({{.*}}) // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__enum_notactive_bb3__Pred__src_0_wrt_1, #_AD__enum_notactive_bb3__Pred__src_0_wrt_1.bb1!enumelt, [[BB1_PB_STRUCT]] : $_AD__enum_notactive_bb1__PB__src_0_wrt_1 // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED1]] : $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: bb2([[ENUM_B:%.*]] : $(Float, Float)): // CHECK-SIL: [[BB2_PRED_PRED0:%.*]] = enum $_AD__enum_notactive_bb2__Pred__src_0_wrt_1, #_AD__enum_notactive_bb2__Pred__src_0_wrt_1.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_notactive_bb0__PB__src_0_wrt_1 // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb2__PB__src_0_wrt_1 ({{.*}}) // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__enum_notactive_bb3__Pred__src_0_wrt_1, #_AD__enum_notactive_bb3__Pred__src_0_wrt_1.bb2!enumelt, [[BB2_PB_STRUCT]] : $_AD__enum_notactive_bb2__PB__src_0_wrt_1 // CHECK-SIL: br bb3({{.*}} : $Float, [[BB3_PRED_PRED2]] : $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: bb3([[ORIG_RES:%.*]] : $Float, [[BB3_PRED_ARG:%.*]] : @owned $_AD__enum_notactive_bb3__Pred__src_0_wrt_1) // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__enum_notactive_bb3__PB__src_0_wrt_1 // CHECK-SIL: [[PULLBACK_REF:%.*]] = function_ref @enum_notactiveTJpUSpSr // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PULLBACK_REF]]([[BB3_PB_STRUCT]]) // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[ORIG_RES]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] // Test `switch_enum_addr`. // Clone of `enum Optional<Wrapped>`. enum AddressOnlyEnum<T> { case some(T) case none } @differentiable(reverse) @_silgen_name("enum_addr_notactive") func enum_addr_notactive<T>(_ e: AddressOnlyEnum<T>, _ x: Float) -> Float { switch e { case .none: break case .some: break } return x } // CHECK-SIL-LABEL: sil hidden [ossa] @enum_addr_notactivelTJrUSpSr : $@convention(thin) <τ_0_0> (@in_guaranteed AddressOnlyEnum<τ_0_0>, Float) -> (Float, @owned @callee_guaranteed (Float) -> Float) { // CHECK-SIL: bb0([[ENUM_ARG:%.*]] : $*AddressOnlyEnum<τ_0_0>, [[X_ARG:%.*]] : $Float): // CHECK-SIL: [[ENUM_ADDR:%.*]] = alloc_stack $AddressOnlyEnum<τ_0_0> // CHECK-SIL: copy_addr [[ENUM_ARG]] to [init] [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB0_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> () // CHECK-SIL: switch_enum_addr [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0>, case #AddressOnlyEnum.none!enumelt: bb1, case #AddressOnlyEnum.some!enumelt: bb2 // CHECK-SIL: bb1: // CHECK-SIL: [[BB1_PRED_PRED0:%.*]] = enum $_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: dealloc_stack [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB1_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb1__PB__src_0_wrt_1_l<τ_0_0> ([[BB1_PRED_PRED0]] : $_AD__enum_addr_notactive_bb1__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[BB3_PRED_PRED1:%.*]] = enum $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l.bb1!enumelt, [[BB1_PB_STRUCT]] : $_AD__enum_addr_notactive_bb1__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: br bb3([[BB3_PRED_PRED1]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: bb2: // CHECK-SIL: [[BB2_PRED_PRED0:%.*]] = enum $_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l.bb0!enumelt, [[BB0_PB_STRUCT]] : $_AD__enum_addr_notactive_bb0__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: [[ENUM_DATA:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0>, #AddressOnlyEnum.some!enumelt // CHECK-SIL: destroy_addr [[ENUM_DATA]] : $*τ_0_0 // CHECK-SIL: dealloc_stack [[ENUM_ADDR]] : $*AddressOnlyEnum<τ_0_0> // CHECK-SIL: [[BB2_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb2__PB__src_0_wrt_1_l<τ_0_0> ([[BB2_PRED_PRED0]] : $_AD__enum_addr_notactive_bb2__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[BB3_PRED_PRED2:%.*]] = enum $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>, #_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l.bb2!enumelt, [[BB2_PB_STRUCT]] : $_AD__enum_addr_notactive_bb2__PB__src_0_wrt_1_l<τ_0_0> // CHECK-SIL: br bb3([[BB3_PRED_PRED2]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: bb3([[BB3_PRED_ARG:%.*]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>): // CHECK-SIL: [[BB3_PB_STRUCT:%.*]] = struct $_AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0> ([[BB3_PRED_ARG]] : $_AD__enum_addr_notactive_bb3__Pred__src_0_wrt_1_l<τ_0_0>) // CHECK-SIL: [[PB_FNREF:%.*]] = function_ref @enum_addr_notactivelTJpUSpSr : $@convention(thin) <τ_0_0> (Float, @owned _AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0>) -> Float // CHECK-SIL: [[PB:%.*]] = partial_apply [callee_guaranteed] [[PB_FNREF]]<τ_0_0>([[BB3_PB_STRUCT]]) : $@convention(thin) <τ_0_0> (Float, @owned _AD__enum_addr_notactive_bb3__PB__src_0_wrt_1_l<τ_0_0>) -> Float // CHECK-SIL: [[VJP_RESULT:%.*]] = tuple ([[X_ARG]] : $Float, [[PB]] : $@callee_guaranteed (Float) -> Float) // CHECK-SIL: return [[VJP_RESULT]] : $(Float, @callee_guaranteed (Float) -> Float) // Test control flow + tuple buffer. // Verify that pullback buffers are not allocated for address projections. @differentiable(reverse) @_silgen_name("cond_tuple_var") func cond_tuple_var(_ x: Float) -> Float { // expected-warning @+1 {{variable 'y' was never mutated; consider changing to 'let' constant}} var y = (x, x) if x > 0 { return y.0 } return y.1 } // CHECK-SIL-LABEL: sil private [ossa] @cond_tuple_varTJpSpSr : $@convention(thin) (Float, @owned _AD__cond_tuple_var_bb3__PB__src_0_wrt_0) -> Float { // CHECK-SIL: bb0([[SEED:%.*]] : $Float, [[BB3_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb3__PB__src_0_wrt_0): // CHECK-SIL: [[BB3_PRED:%.*]] = destructure_struct [[BB3_PB_STRUCT]] : $_AD__cond_tuple_var_bb3__PB__src_0_wrt_0 // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB3_PRED]] : $_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0.bb2!enumelt: bb1, case #_AD__cond_tuple_var_bb3__Pred__src_0_wrt_0.bb1!enumelt: bb3 // CHECK-SIL: bb1([[BB3_PRED2_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0): // CHECK-SIL: br bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB3_PRED2_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0) // CHECK-SIL: bb2({{%.*}} : $Float, {{%.*}} : $Float, [[BB2_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb2__PB__src_0_wrt_0): // CHECK-SIL: [[BB2_PRED:%.*]] = destructure_struct [[BB2_PB_STRUCT]] // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB2_PRED]] : $_AD__cond_tuple_var_bb2__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb2__Pred__src_0_wrt_0.bb0!enumelt: bb6 // CHECK-SIL: bb3([[BB3_PRED1_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0): // CHECK-SIL: br bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB3_PRED1_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0) // CHECK-SIL: bb4({{%.*}} : $Float, {{%.*}} : $Float, [[BB1_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb1__PB__src_0_wrt_0): // CHECK-SIL: [[BB1_PRED:%.*]] = destructure_struct [[BB1_PB_STRUCT]] // CHECK-SIL: copy_addr {{%.*}} to {{%.*}} : $*(Float, Float) // CHECK-SIL-NOT: copy_addr {{%.*}} to {{%.*}} : $*Float // CHECK-SIL: switch_enum [[BB1_PRED]] : $_AD__cond_tuple_var_bb1__Pred__src_0_wrt_0, case #_AD__cond_tuple_var_bb1__Pred__src_0_wrt_0.bb0!enumelt: bb5 // CHECK-SIL: bb5([[BB1_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB1_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb6([[BB2_PRED0_TRAMP_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: br bb7({{%.*}} : $Float, [[BB2_PRED0_TRAMP_PB_STRUCT]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0) // CHECK-SIL: bb7({{%.*}} : $Float, [[BB0_PB_STRUCT:%.*]] : $_AD__cond_tuple_var_bb0__PB__src_0_wrt_0): // CHECK-SIL: return {{%.*}} : $Float
70a32bae76f9376866cf2dc3f3e56d73
58.807971
244
0.592779
false
false
false
false
anpavlov/swiftperl
refs/heads/master
Sources/Perl/UnsafeSV.swift
mit
1
import CPerl public enum SvType { case scalar, array, hash, code, format, io init(_ t: svtype) { switch t { case SVt_PVAV: self = .array case SVt_PVHV: self = .hash case SVt_PVCV: self = .code case SVt_PVFM: self = .format case SVt_PVIO: self = .io default: self = .scalar } } } public typealias UnsafeSV = CPerl.SV public typealias UnsafeSvPointer = UnsafeMutablePointer<UnsafeSV> extension UnsafeSV { @discardableResult mutating func refcntInc() -> UnsafeSvPointer { return SvREFCNT_inc(&self) } mutating func refcntDec(perl: UnsafeInterpreterPointer) { SvREFCNT_dec(perl, &self) } var type: SvType { mutating get { return SvType(SvTYPE(&self)) } } var defined: Bool { mutating get { return SvOK(&self) } } var isInt: Bool { mutating get { return SvIOK(&self) } } var isDouble: Bool { mutating get { return SvNOK(&self) } } var isString: Bool { mutating get { return SvPOK(&self) } } var isRef: Bool { mutating get { return SvROK(&self) } } var referent: UnsafeSvPointer? { mutating get { return SvROK(&self) ? SvRV(&self) : nil } } mutating func isObject(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return perl.pointee.sv_isobject(&self) } mutating func isDerived(from: String, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> Bool { return from.withCString { perl.pointee.sv_derived_from(&self, $0) } } mutating func classname(perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) -> String? { guard isObject(perl: perl) else { return nil } return String(cString: perl.pointee.sv_reftype(SvRV(&self), true)) } mutating func hasSwiftObjectMagic(perl: UnsafeInterpreterPointer) -> Bool { return SvTYPE(&self) == SVt_PVMG && perl.pointee.mg_findext(&self, PERL_MAGIC_ext, &objectMgvtbl) != nil } mutating func swiftObject(perl: UnsafeInterpreterPointer) -> PerlBridgedObject? { guard isObject(perl: perl) else { return nil } let sv = SvRV(&self)! guard sv.pointee.hasSwiftObjectMagic(perl: perl) else { return nil } let iv = perl.pointee.SvIV(sv) let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!) return (u.takeUnretainedValue() as! PerlBridgedObject) } } extension UnsafeInterpreter { mutating func newSV(_ v: Bool) -> UnsafeSvPointer { return newSV(boolSV(v)) } mutating func newSV(_ v: String, mortal: Bool = false) -> UnsafeSvPointer { let flags = mortal ? SVf_UTF8|SVs_TEMP : SVf_UTF8 return v.withCStringWithLength { newSVpvn_flags($0, $1, UInt32(flags)) } } mutating func newSV(_ v: UnsafeRawBufferPointer, utf8: Bool = false, mortal: Bool = false) -> UnsafeSvPointer { let flags = (utf8 ? SVf_UTF8 : 0) | (mortal ? SVs_TEMP : 0) return newSVpvn_flags(v.baseAddress?.assumingMemoryBound(to: CChar.self), v.count, UInt32(flags)) } mutating func newRV<T: UnsafeSvCastable>(inc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer { return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(inc: $0) } } mutating func newRV<T: UnsafeSvCastable>(noinc v: UnsafeMutablePointer<T>) -> UnsafeSvPointer { return v.withMemoryRebound(to: UnsafeSV.self, capacity: 1) { newRV(noinc: $0) } } mutating func newSV(_ v: AnyObject, isa: String) -> UnsafeSvPointer { let u = Unmanaged<AnyObject>.passRetained(v) let iv = unsafeBitCast(u, to: Int.self) let sv = sv_setref_iv(newSV(), isa, iv) sv_magicext(SvRV(sv), nil, PERL_MAGIC_ext, &objectMgvtbl, nil, 0) return sv } mutating func newSV(_ v: PerlBridgedObject) -> UnsafeSvPointer { return newSV(v, isa: type(of: v).perlClassName) } } private var objectMgvtbl = MGVTBL( svt_get: nil, svt_set: nil, svt_len: nil, svt_clear: nil, svt_free: { (perl, sv, magic) in let iv = perl.unsafelyUnwrapped.pointee.SvIV(sv.unsafelyUnwrapped) let u = Unmanaged<AnyObject>.fromOpaque(UnsafeRawPointer(bitPattern: iv)!) u.release() return 0 }, svt_copy: nil, svt_dup: nil, svt_local: nil ) extension Bool { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvTRUE(sv) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { guard SvOK(sv) else { return nil } self = perl.pointee.SvTRUE(sv) } } extension Int { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else { throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvIV(sv) } } extension Double { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvNIOK(sv) || perl.pointee.looks_like_number(sv) else { throw PerlError.notNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { self = perl.pointee.SvNV(sv) } } extension String { public init(_ sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvPOK(sv) || SvNIOK(sv) else { throw PerlError.notStringOrNumber(fromUnsafeSvPointer(inc: sv, perl: perl)) } self.init(unchecked: sv, perl: perl) } public init?(nilable sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) throws { guard SvOK(sv) else { return nil } try self.init(sv, perl: perl) } public init(unchecked sv: UnsafeSvPointer, perl: UnsafeInterpreterPointer = UnsafeInterpreter.current) { var clen = 0 let cstr = perl.pointee.SvPV(sv, &clen)! self = String(cString: cstr, withLength: clen) } }
b6adca4fe73dd8323f82ed1764ccb748
31.430052
112
0.717846
false
false
false
false
randallli/material-components-ios
refs/heads/develop
demos/Shrine/Shrine/ShrineHeaderContentView.swift
apache-2.0
3
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialPageControl class ShrineHeaderContentView: UIView, UIScrollViewDelegate { var pageControl = MDCPageControl() var scrollView = UIScrollView() var logoImageView = UIImageView(image: UIImage(named: "ShrineLogo")) var logoTextImageView = UIImageView(image: UIImage(named: "ShrineTextLogo")) fileprivate var pages = NSMutableArray() fileprivate var label = UILabel() fileprivate var labelDesc = UILabel() fileprivate var label2 = UILabel() fileprivate var labelDesc2 = UILabel() fileprivate var label3 = UILabel() fileprivate var labelDesc3 = UILabel() fileprivate var cyanBox = UIView() fileprivate var cyanBox2 = UIView() fileprivate var cyanBox3 = UIView() fileprivate var imageView = UIImageView() fileprivate var imageView2 = UIImageView() fileprivate var imageView3 = UIImageView() override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder: NSCoder) { super.init(coder: coder)! } func commonInit() { let boundsWidth = bounds.width let boundsHeight = bounds.height scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.delegate = self scrollView.isPagingEnabled = true scrollView.showsHorizontalScrollIndicator = false addSubview(scrollView) autoresizingMask = [.flexibleWidth, .flexibleHeight] for i in 0...2 { let boundsLeft = CGFloat(i) * boundsWidth let pageFrame = bounds.offsetBy(dx: boundsLeft, dy: 0) let page = UIView(frame:pageFrame) page.clipsToBounds = true page.autoresizingMask = [.flexibleWidth, .flexibleHeight] pages.add(page) scrollView.addSubview(page) } pageControl.numberOfPages = 3 pageControl.autoresizingMask = [.flexibleWidth, .flexibleHeight] let pageControlSize = pageControl.sizeThatFits(bounds.size) pageControl.frame = CGRect(x: 0, y: boundsHeight - pageControlSize.height, width: boundsWidth, height: pageControlSize.height) pageControl.addTarget(self, action: #selector(didChangePage), for: UIControlEvents.valueChanged) addSubview(pageControl) addHeaderPages() addSubview(logoImageView) addSubview(logoTextImageView) } func addHeaderPages() { _ = ShrineHeaderPage(page: pages[0] as! UIView, imageView: imageView, label: label, labelDesc: labelDesc, cyanBox: cyanBox, imageName: "chair.png", description: "Green \ncomfort chair") _ = ShrineHeaderPage(page: pages[1] as! UIView, imageView: imageView2, label: label2, labelDesc: labelDesc2, cyanBox: cyanBox2, imageName: "backpack.png", description: "Best gift for \nthe traveler") _ = ShrineHeaderPage(page: pages[2] as! UIView, imageView: imageView3, label: label3, labelDesc: labelDesc3, cyanBox: cyanBox3, imageName: "heels.png", description: "Better \nwearing heels") } override func layoutSubviews() { super.layoutSubviews() var safeAreaInset: CGFloat = 0 #if swift(>=3.2) if #available(iOS 11.0, *) { safeAreaInset = min(self.safeAreaInsets.top, 10) } #endif let boundsWidth = bounds.width let boundsHeight = bounds.height for i in 0...pages.count - 1 { let boundsLeft = CGFloat(i) * boundsWidth let pageFrame = bounds.offsetBy(dx: boundsLeft, dy: 0) let page = pages[i] as! UIView page.frame = pageFrame } let pageControlSize = pageControl.sizeThatFits(bounds.size) pageControl.frame = CGRect(x: 0, y: boundsHeight - pageControlSize.height, width: boundsWidth, height: pageControlSize.height) let scrollWidth: CGFloat = boundsWidth * CGFloat(pages.count) scrollView.frame = CGRect(x: 0, y: 0, width: boundsWidth, height: boundsHeight) scrollView.contentSize = CGSize(width: scrollWidth, height: boundsHeight) let scrollViewOffsetX = CGFloat(pageControl.currentPage) * boundsWidth scrollView.setContentOffset(CGPoint(x: scrollViewOffsetX, y: 0), animated: false) logoImageView.center = CGPoint(x: (frame.size.width) / 2, y: 44 + safeAreaInset) logoTextImageView.center = CGPoint(x: (frame.size.width) / 2, y: 44 + safeAreaInset) let labelWidth = CGFloat(250) let labelWidthFrame = CGRect(x: frame.size.width - labelWidth, y: 90, width: labelWidth, height: label.frame.size.height) let labelDescWidth = CGFloat(200) let labelDescWidthFrame = CGRect(x: frame.size.width - labelDescWidth - 10, y: 190, width: labelDescWidth, height: 40) label.frame = labelWidthFrame labelDesc.frame = labelDescWidthFrame label2.frame = labelWidthFrame labelDesc2.frame = labelDescWidthFrame label3.frame = labelWidthFrame labelDesc3.frame = labelDescWidthFrame let cyanBoxFrame = CGRect(x: frame.size.width - 210, y: 180, width: 100, height: 8) cyanBox.frame = cyanBoxFrame cyanBox2.frame = cyanBoxFrame cyanBox3.frame = cyanBoxFrame imageView.frame = CGRect(x: -180, y: 120, width: 420, height: frame.size.height) imageView2.frame = CGRect(x: -220, y: 110, width: 420, height: frame.size.height) imageView3.frame = CGRect(x: -180, y: 40, width: 420, height: frame.size.height) } func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl.scrollViewDidScroll(scrollView) } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControl.scrollViewDidEndDecelerating(scrollView) } func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { pageControl.scrollViewDidEndScrollingAnimation(scrollView) } func didChangePage(_ sender: MDCPageControl) { var offset = scrollView.contentOffset offset.x = CGFloat(sender.currentPage) * scrollView.bounds.size.width scrollView.setContentOffset(offset, animated: true) } }
8c2abbf09fb26b578be9aefbf64d729b
37.661111
98
0.670786
false
false
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/View/LinearEquations/Project/Items/VLinearEquationsProjectCellNewPolynomial.swift
mit
1
import UIKit class VLinearEquationsProjectCellNewPolynomial:VLinearEquationsProjectCell { override init(frame:CGRect) { super.init(frame:frame) let imageView:UIImageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.isUserInteractionEnabled = false imageView.image = #imageLiteral(resourceName: "assetGenericColNew") addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self) } required init?(coder:NSCoder) { return nil } }
10abb41c9fff0b0b1cfa591da39d2028
25.851852
75
0.656552
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/ConfigurationMessageCell/Components/ConversationIconBasedCell.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import UIKit import WireDataModel class ConversationIconBasedCell: UIView { let imageContainer = UIView() let imageView = UIImageView() let textLabel = WebLinkTextView() let lineView = UIView() let topContentView = UIView() let bottomContentView = UIView() let labelFont: UIFont = .mediumFont private var containerWidthConstraint: NSLayoutConstraint! private var textLabelTrailingConstraint: NSLayoutConstraint! private var textLabelTopConstraint: NSLayoutConstraint! private var topContentViewTrailingConstraint: NSLayoutConstraint! weak var delegate: ConversationMessageCellDelegate? weak var message: ZMConversationMessage? var isSelected: Bool = false var selectionView: UIView? { return textLabel } var selectionRect: CGRect { return textLabel.bounds } var attributedText: NSAttributedString? { didSet { textLabel.attributedText = attributedText textLabel.accessibilityLabel = attributedText?.string let font = attributedText?.attributes(at: 0, effectiveRange: nil)[.font] as? UIFont if let lineHeight = font?.lineHeight { textLabelTopConstraint.constant = (32 - lineHeight) / 2 } else { textLabelTopConstraint.constant = 0 } } } private var trailingTextMargin: CGFloat { return -conversationHorizontalMargins.right * 2 } override init(frame: CGRect) { super.init(frame: frame) configureSubviews() configureConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init?(coder aDecoder: NSCoder) is not implemented") } func configureSubviews() { imageView.contentMode = .center imageView.isAccessibilityElement = true imageView.accessibilityLabel = "Icon" textLabel.isAccessibilityElement = true textLabel.backgroundColor = .clear textLabel.font = labelFont textLabel.delegate = self textLabel.linkTextAttributes = [ NSAttributedString.Key.underlineStyle: NSUnderlineStyle().rawValue as NSNumber, NSAttributedString.Key.foregroundColor: SelfUser.provider?.selfUser.accentColor ?? UIColor.accent() ] lineView.backgroundColor = SemanticColors.View.backgroundSeparatorConversationView imageContainer.addSubview(imageView) addSubview(imageContainer) addSubview(textLabel) addSubview(topContentView) addSubview(bottomContentView) addSubview(lineView) } func configureConstraints() { imageContainer.translatesAutoresizingMaskIntoConstraints = false imageView.translatesAutoresizingMaskIntoConstraints = false textLabel.translatesAutoresizingMaskIntoConstraints = false topContentView.translatesAutoresizingMaskIntoConstraints = false bottomContentView.translatesAutoresizingMaskIntoConstraints = false lineView.translatesAutoresizingMaskIntoConstraints = false topContentViewTrailingConstraint = topContentView.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: trailingTextMargin) containerWidthConstraint = imageContainer.widthAnchor.constraint(equalToConstant: conversationHorizontalMargins.left) textLabelTrailingConstraint = textLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: trailingTextMargin) textLabelTopConstraint = textLabel.topAnchor.constraint(equalTo: topContentView.bottomAnchor) // We want the content view to at least be below the image container let contentViewTopConstraint = bottomContentView.topAnchor.constraint(equalTo: imageContainer.bottomAnchor) contentViewTopConstraint.priority = .defaultLow NSLayoutConstraint.activate([ // imageContainer containerWidthConstraint, imageContainer.leadingAnchor.constraint(equalTo: leadingAnchor), imageContainer.topAnchor.constraint(equalTo: topContentView.bottomAnchor, constant: 0), imageContainer.heightAnchor.constraint(equalTo: imageView.heightAnchor), imageContainer.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: 0), // imageView imageView.widthAnchor.constraint(equalToConstant: 32), imageView.heightAnchor.constraint(equalToConstant: 32), imageView.centerXAnchor.constraint(equalTo: imageContainer.centerXAnchor), imageView.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), // topContentView topContentView.topAnchor.constraint(equalTo: topAnchor), topContentView.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor), topContentViewTrailingConstraint, // textLabel textLabel.leadingAnchor.constraint(equalTo: imageContainer.trailingAnchor), textLabelTopConstraint, textLabelTrailingConstraint, // lineView lineView.leadingAnchor.constraint(equalTo: textLabel.trailingAnchor, constant: 16), lineView.heightAnchor.constraint(equalToConstant: .hairline), lineView.trailingAnchor.constraint(equalTo: trailingAnchor), lineView.centerYAnchor.constraint(equalTo: imageContainer.centerYAnchor), // bottomContentView bottomContentView.leadingAnchor.constraint(equalTo: textLabel.leadingAnchor), bottomContentView.topAnchor.constraint(greaterThanOrEqualTo: textLabel.bottomAnchor), bottomContentView.trailingAnchor.constraint(equalTo: trailingAnchor), bottomContentView.bottomAnchor.constraint(equalTo: bottomAnchor), contentViewTopConstraint ]) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) containerWidthConstraint.constant = conversationHorizontalMargins.left textLabelTrailingConstraint.constant = trailingTextMargin topContentViewTrailingConstraint.constant = trailingTextMargin } } extension ConversationIconBasedCell: UITextViewDelegate { public func textView(_ textView: UITextView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { // Fixes Swift 5.0 release build child class overridden method not called bug return false } }
d09bdf0356908ee131b7ee8dc8b92072
40.793103
151
0.723322
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Syntax/HBCISegmentDescription.swift
gpl-2.0
1
// // HBCISegmentDescription.swift // HBCIBackend // // Created by Frank Emminghaus on 27.12.14. // Copyright (c) 2014 Frank Emminghaus. All rights reserved. // import Foundation class HBCISegmentDescription: HBCISyntaxElementDescription { let code:String; let version:Int; init(syntax:HBCISyntax, element:XMLElement, code:String, version:Int) throws { self.code = code; self.version = version; try super.init(syntax: syntax, element: element); self.delimiter = HBCIChar.plus.rawValue; self.elementType = ElementType.segment; } override func elementDescription() -> String { if self.identifier == nil { let type = self.type ?? "none" let name = self.name ?? "none" return "SEG type: \(type), name: \(name) \n" } else { return "SEG id: \(self.identifier!) \n" } } override func parse(_ bytes: UnsafePointer<CChar>, length: Int, binaries:Array<Data>)->HBCISyntaxElement? { let seg = HBCISegment(description: self); var ref:HBCISyntaxElementReference; var refIdx = 0; var num = 0; var count = 0; var delimiter = HBCIChar.plus.rawValue; var p: UnsafeMutablePointer<CChar> = UnsafeMutablePointer<CChar>(mutating: bytes); var resLength = length; while(refIdx < self.children.count) { ref = self.children[refIdx]; // check if optional tail is cut if delimiter == HBCIChar.quote.rawValue { if num >= ref.minnum { refIdx += 1; continue; // check next } else { // error: non-optional element but end of SEG logInfo("Parse error: non-optional element is missing at the end of data element group"); return nil; } } if p.pointee == HBCIChar.plus.rawValue && refIdx > 0 { // empty element - check if element was optional if ref.minnum > num { // error: minimal occurence logInfo("Parse error: element \(ref.name ?? "?") is empty but not optional"); return nil; } else { num = 0; refIdx += 1; p = p.advanced(by: 1); // consume delimiter count += 1; resLength = length - count; } } else { if let element = ref.elemDescr.parse(p, length: resLength, binaries: binaries) { if ref.name != nil { element.name = ref.name; } else { logInfo("Parse error: reference without name"); return nil; } seg.children.append(element); if element.isEmpty { // check if element was optional if ref.minnum > num { // error: minimal occurence logInfo("Parse error: element \(ref.name ?? "?") is empty but not optional"); return nil; } else { num = 0; refIdx += 1; } } else { num += 1; if num == ref.maxnum { // new object num = 0; refIdx += 1; } } p = p.advanced(by: element.length); delimiter = p.pointee; p = p.advanced(by: 1); // consume delimiter count += element.length + 1; resLength = length - count; } else { // parse error for children return nil; } } } seg.length = count-1; if seg.name == "" { seg.name = seg.descr.type ?? ""; } return seg; } func parse(_ segData:Data, binaries:Array<Data>) ->HBCISegment? { return parse((segData as NSData).bytes.bindMemory(to: CChar.self, capacity: segData.count), length: segData.count, binaries: binaries) as? HBCISegment; } override func getElement() -> HBCISyntaxElement? { return HBCISegment(description: self); } }
87f8ce88888e91b04798c0ed948d5d91
34.80303
159
0.454084
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
iOSRACSwift/iOSRACSwift/ViewController.swift
mit
1
// // ViewController.swift // iOSRACSwift // // Created by Hanguang on 1/18/16. // Copyright © 2016 Hanguang. All rights reserved. // import UIKit import ReactiveCocoa class ViewController: UIViewController { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBAction func loginButton(sender: UIButton) { } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. nameTextField.rac_textSignal() .toSignalProducer() .skip(2) .filter { (text) -> Bool in let string = text as! String return string.characters.count > 3 }.startWithNext { (text) -> () in print(text!) } // let searchStrings = nameTextField.rac_textSignal() // .toSignalProducer() // .map { text in text as! String } // .throttle(0.5, onScheduler: QueueScheduler.mainQueueScheduler) // // let searchResult = searchStrings // .flatMap(.Latest) { (query: String) -> SignalProducer<(NSData, NSURLResponse), NSError> in // let URLRequest = NSURLRequest(URL: NSURL(string: "http://www.baidu.com")!) // return NSURLSession.sharedSession() // .rac_dataWithRequest(URLRequest) // .retry(2) // .flatMapError { error in // print("Error: \(error)") // return SignalProducer.empty // } // } // .map { (data, URLResponse) -> String in // let string = String(data: data, encoding: NSUTF8StringEncoding)! // return string // } // .observeOn(UIScheduler()) // // searchResult.startWithNext { (results) -> () in // print("Search results: \(results)") // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
d4d39b2ca5c44993a319ca2bb6e7a45d
32.523077
104
0.543827
false
false
false
false
sammyd/VT_InAppPurchase
refs/heads/master
projects/01_GettingStarted/001_ChallengeComplete/GreenGrocer/IAPHelper.swift
mit
3
/* * Copyright (c) 2015 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import StoreKit import Foundation class IAPHelper: NSObject { typealias ProductsRequestCompletionHandler = (products: [SKProduct]?) -> () private let productIndentifiers: Set<String> private var productsRequest: SKProductsRequest? private var productsRequestCompletionHandler: ProductsRequestCompletionHandler? init(prodIds: Set<String>) { self.productIndentifiers = prodIds super.init() } } //:- API extension IAPHelper { func requestProducts(completionHandler: ProductsRequestCompletionHandler) { productsRequest?.cancel() productsRequestCompletionHandler = completionHandler productsRequest = SKProductsRequest(productIdentifiers: productIndentifiers) productsRequest?.delegate = self productsRequest?.start() } } //:- SKProductsRequestDelegate extension IAPHelper: SKProductsRequestDelegate { func productsRequest(request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) { productsRequestCompletionHandler?(products: response.products) productsRequestCompletionHandler = .None productsRequest = .None } func request(request: SKRequest, didFailWithError error: NSError) { print("Error: \(error.localizedDescription)") productsRequestCompletionHandler?(products: .None) productsRequestCompletionHandler = .None productsRequest = .None } }
3203c0b0bf24bd263d1ea745010d8735
35.205882
101
0.773355
false
false
false
false
tamanyan/SwiftPageMenu
refs/heads/master
PageMenuExample/Sources/StoryboardPageTabMenuViewController.swift
mit
1
// // StoryboardPageTabMenuViewController.swift // PageMenuExample // // Created by Tamanyan on 9/3/31 H. // Copyright © 31 Heisei Tamanyan. All rights reserved. // import UIKit import SwiftPageMenu class StoryboardPageTabMenuViewController: PageMenuController { let items: [[String]] let titles: [String] init(items: [[String]], titles: [String], options: PageMenuOptions? = nil) { self.items = items self.titles = titles super.init(options: options) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = [] if options.layout == .layoutGuide && options.tabMenuPosition == .bottom { self.view.backgroundColor = Theme.mainColor } else { self.view.backgroundColor = .white } if self.options.tabMenuPosition == .custom { self.view.addSubview(self.tabMenuView) self.tabMenuView.translatesAutoresizingMaskIntoConstraints = false self.tabMenuView.heightAnchor.constraint(equalToConstant: self.options.menuItemSize.height).isActive = true self.tabMenuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.tabMenuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true if #available(iOS 11.0, *) { self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true } else { self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } self.delegate = self self.dataSource = self } } extension StoryboardPageTabMenuViewController: PageMenuControllerDataSource { func viewControllers(forPageMenuController pageMenuController: PageMenuController) -> [UIViewController] { return self.titles.enumerated().map({ (i, title) -> UIViewController in let storyboard = UIStoryboard(name: "StoryboardChildViewController", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "StoryboardChildViewController") as! StoryboardChildViewController controller.title = "Storyboard #\(i) (\(title))" return controller }) } func menuTitles(forPageMenuController pageMenuController: PageMenuController) -> [String] { return self.titles } func defaultPageIndex(forPageMenuController pageMenuController: PageMenuController) -> Int { return 0 } } extension StoryboardPageTabMenuViewController: PageMenuControllerDelegate { func pageMenuController(_ pageMenuController: PageMenuController, didScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) { // The page view controller will begin scrolling to a new page. print("didScrollToPageAtIndex index:\(index)") } func pageMenuController(_ pageMenuController: PageMenuController, willScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) { // The page view controller scroll progress between pages. print("willScrollToPageAtIndex index:\(index)") } func pageMenuController(_ pageMenuController: PageMenuController, scrollingProgress progress: CGFloat, direction: PageMenuNavigationDirection) { // The page view controller did complete scroll to a new page. print("scrollingProgress progress: \(progress)") } func pageMenuController(_ pageMenuController: PageMenuController, didSelectMenuItem index: Int, direction: PageMenuNavigationDirection) { print("didSelectMenuItem index: \(index)") } }
0002e62f07fcda5c8074eedb8a186632
37.989796
148
0.70191
false
false
false
false
mercadopago/px-ios
refs/heads/develop
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXOneTapItem.swift
mit
1
import Foundation /// :nodoc: open class PXOneTapItem: NSObject, Codable { open var paymentMethodId: String open var paymentTypeId: String? open var oneTapCard: PXOneTapCard? public init(paymentMethodId: String, paymentTypeId: String?, oneTapCard: PXOneTapCard?) { self.paymentMethodId = paymentMethodId self.paymentTypeId = paymentTypeId self.oneTapCard = oneTapCard } public enum PXOneTapItemKeys: String, CodingKey { case paymentMethodId = "payment_method_id" case paymentTypeId = "payment_type_id" case oneTapCard = "card" } public required convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PXOneTapItemKeys.self) let oneTapCard: PXOneTapCard? = try container.decodeIfPresent(PXOneTapCard.self, forKey: .oneTapCard) let paymentMethodId: String = try container.decode(String.self, forKey: .paymentMethodId) let paymentTypeId: String? = try container.decodeIfPresent(String.self, forKey: .paymentTypeId) self.init(paymentMethodId: paymentMethodId, paymentTypeId: paymentTypeId, oneTapCard: oneTapCard) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PXOneTapItemKeys.self) try container.encodeIfPresent(self.oneTapCard, forKey: .oneTapCard) try container.encodeIfPresent(self.paymentMethodId, forKey: .paymentMethodId) try container.encodeIfPresent(self.paymentTypeId, forKey: .paymentTypeId) } open func toJSONString() throws -> String? { let encoder = JSONEncoder() let data = try encoder.encode(self) return String(data: data, encoding: .utf8) } open func toJSON() throws -> Data { let encoder = JSONEncoder() return try encoder.encode(self) } open class func fromJSONToPXOneTapItem(data: Data) throws -> PXOneTapItem { return try JSONDecoder().decode(PXOneTapItem.self, from: data) } open class func fromJSON(data: Data) throws -> PXOneTapItem { return try JSONDecoder().decode(PXOneTapItem.self, from: data) } }
3fd5693e1b0107697b081c414145c55c
39.222222
109
0.701657
false
false
false
false
Lucky-Orange/Tenon
refs/heads/master
Pitaya/Source/Helper.swift
mit
1
// The MIT License (MIT) // Copyright (c) 2015 JohnLui <wenhanlv@gmail.com> https://github.com/johnlui // 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. // // Helper.swift // Pitaya // // Created by 吕文翰 on 15/10/7. // import Foundation class Helper { // stolen from Alamofire static func buildParams(parameters: [String: AnyObject]) -> String { var components: [(String, String)] = [] for key in Array(parameters.keys).sort(<) { let value: AnyObject! = parameters[key] components += Helper.queryComponents(key, value) } return components.map{"\($0)=\($1)"}.joinWithSeparator("&") } // stolen from Alamofire static func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] { var components: [(String, String)] = [] components.appendContentsOf([(Helper.escape(key), Helper.escape("\(value)"))]) return components } // stolen from Alamofire static func escape(string: String) -> String { let legalURLCharactersToBeEscaped: CFStringRef = ":&=;+!@#$()',*" return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String } }
c8690d1d8fc8dbf1835bb0c91100a43a
42.264151
153
0.698517
false
false
false
false
WenchaoD/FSPagerView
refs/heads/master
Sources/FSPageViewTransformer.swift
mit
1
// // FSPagerViewTransformer.swift // FSPagerView // // Created by Wenchao Ding on 05/01/2017. // Copyright © 2017 Wenchao Ding. All rights reserved. // import UIKit @objc public enum FSPagerViewTransformerType: Int { case crossFading case zoomOut case depth case overlap case linear case coverFlow case ferrisWheel case invertedFerrisWheel case cubic } open class FSPagerViewTransformer: NSObject { open internal(set) weak var pagerView: FSPagerView? open internal(set) var type: FSPagerViewTransformerType @objc open var minimumScale: CGFloat = 0.65 @objc open var minimumAlpha: CGFloat = 0.6 @objc public init(type: FSPagerViewTransformerType) { self.type = type switch type { case .zoomOut: self.minimumScale = 0.85 case .depth: self.minimumScale = 0.5 default: break } } // Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D. open func applyTransform(to attributes: FSPagerViewLayoutAttributes) { guard let pagerView = self.pagerView else { return } let position = attributes.position let scrollDirection = pagerView.scrollDirection let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing() switch self.type { case .crossFading: var zIndex = 0 var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch scrollDirection { case .horizontal: transform.tx = -itemSpacing * position case .vertical: transform.ty = -itemSpacing * position } if (abs(position) < 1) { // [-1,1] // Use the default slide transition when moving to the left page alpha = 1 - abs(position) zIndex = 1 } else { // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 zIndex = Int.min } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .zoomOut: var alpha: CGFloat = 0 var transform = CGAffineTransform.identity switch position { case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 case -1 ... 1 : // [-1,1] // Modify the default slide transition to shrink the page as well let scaleFactor = max(self.minimumScale, 1 - abs(position)) transform.a = scaleFactor transform.d = scaleFactor switch scrollDirection { case .horizontal: let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2; let horzMargin = itemSpacing * (1 - scaleFactor) / 2; transform.tx = position < 0 ? (horzMargin - vertMargin*2) : (-horzMargin + vertMargin*2) case .vertical: let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2; let vertMargin = itemSpacing * (1 - scaleFactor) / 2; transform.ty = position < 0 ? (vertMargin - horzMargin*2) : (-vertMargin + horzMargin*2) } // Fade the page relative to its size. alpha = self.minimumAlpha + (scaleFactor-self.minimumScale)/(1-self.minimumScale)*(1-self.minimumAlpha) case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity] // This page is way off-screen to the right. alpha = 0 default: break } attributes.alpha = alpha attributes.transform = transform case .depth: var transform = CGAffineTransform.identity var zIndex = 0 var alpha: CGFloat = 0.0 switch position { case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1) // This page is way off-screen to the left. alpha = 0 zIndex = 0 case -1 ... 0: // [-1,0] // Use the default slide transition when moving to the left page alpha = 1 transform.tx = 0 transform.a = 1 transform.d = 1 zIndex = 1 case 0 ..< 1: // (0,1) // Fade the page out. alpha = CGFloat(1.0) - position // Counteract the default slide transition switch scrollDirection { case .horizontal: transform.tx = itemSpacing * -position case .vertical: transform.ty = itemSpacing * -position } // Scale the page down (between minimumScale and 1) let scaleFactor = self.minimumScale + (1.0 - self.minimumScale) * (1.0 - abs(position)); transform.a = scaleFactor transform.d = scaleFactor zIndex = 0 case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity) // This page is way off-screen to the right. alpha = 0 zIndex = 0 default: break } attributes.alpha = alpha attributes.transform = transform attributes.zIndex = zIndex case .overlap,.linear: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let scale = max(1 - (1-self.minimumScale) * abs(position), self.minimumScale) let transform = CGAffineTransform(scaleX: scale, y: scale) attributes.transform = transform let alpha = (self.minimumAlpha + (1-abs(position))*(1-self.minimumAlpha)) attributes.alpha = alpha let zIndex = (1-abs(position)) * 10 attributes.zIndex = Int(zIndex) case .coverFlow: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } let position = min(max(-position,-1) ,1) let rotation = sin(position*(.pi)*0.5)*(.pi)*0.25*1.5 let translationZ = -itemSpacing * 0.5 * abs(position) var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0) transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ) attributes.zIndex = 100 - Int(abs(position)) attributes.transform3D = transform3D case .ferrisWheel, .invertedFerrisWheel: guard scrollDirection == .horizontal else { // This type doesn't support vertical mode return } // http://ronnqvi.st/translate-rotate-translate/ var zIndex = 0 var transform = CGAffineTransform.identity switch position { case -5 ... 5: let itemSpacing = attributes.bounds.width+self.proposedInteritemSpacing() let count: CGFloat = 14 let circle: CGFloat = .pi * 2.0 let radius = itemSpacing * count / circle let ty = radius * (self.type == .ferrisWheel ? 1 : -1) let theta = circle / count let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1) transform = transform.translatedBy(x: -position*itemSpacing, y: ty) transform = transform.rotated(by: rotation) transform = transform.translatedBy(x: 0, y: -ty) zIndex = Int((4.0-abs(position)*10)) default: break } attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha attributes.transform = transform attributes.zIndex = zIndex case .cubic: switch position { case -CGFloat.greatestFiniteMagnitude ... -1: attributes.alpha = 0 case -1 ..< 1: attributes.alpha = 1 attributes.zIndex = Int((1-position) * CGFloat(10)) let direction: CGFloat = position < 0 ? 1 : -1 let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1) let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height var transform3D = CATransform3DIdentity transform3D.m34 = -0.002 switch scrollDirection { case .horizontal: // ForwardX -> RotateY -> BackwardX attributes.center.x += direction*radius*0.5 // ForwardX transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY transform3D = CATransform3DTranslate(transform3D,-direction*radius*0.5, 0, 0) // BackwardX case .vertical: // ForwardY -> RotateX -> BackwardY attributes.center.y += direction*radius*0.5 // ForwardY transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX transform3D = CATransform3DTranslate(transform3D,0, -direction*radius*0.5, 0) // BackwardY } attributes.transform3D = transform3D case 1 ... CGFloat.greatestFiniteMagnitude: attributes.alpha = 0 default: attributes.alpha = 0 attributes.zIndex = 0 } } } // An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view. open func proposedInteritemSpacing() -> CGFloat { guard let pagerView = self.pagerView else { return 0 } let scrollDirection = pagerView.scrollDirection switch self.type { case .overlap: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.6 case .linear: guard scrollDirection == .horizontal else { return 0 } return pagerView.itemSize.width * -self.minimumScale * 0.2 case .coverFlow: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * sin(.pi*0.25*0.25*3.0) case .ferrisWheel,.invertedFerrisWheel: guard scrollDirection == .horizontal else { return 0 } return -pagerView.itemSize.width * 0.15 case .cubic: return 0 default: break } return pagerView.interitemSpacing } }
3c885851638a9701828c8f75cd90802d
40.901099
145
0.537722
false
false
false
false
Motsai/neblina-motiondemo-swift
refs/heads/master
src/NeblinaControl.swift
mit
2
// // NeblinaControl.swift // // // Created by Hoan Hoang on 2017-04-06. // Copyright © 2017 Motsai. All rights reserved. // import Foundation import CoreBluetooth extension Neblina { // // MARK : **** API // // ******************************** // * Neblina Command API // ******************************** // // *** // *** Subsystem General // *** func getSystemStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SYSTEM_STATUS, paramLen: 0, paramData: [0]) } func getFusionStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FUSION_STATUS, paramLen: 0, paramData: [0]) } func getRecorderStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RECORDER_STATUS, paramLen: 0, paramData: [0]) } func getFirmwareVersion() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_VERSION, paramLen: 0, paramData: [0]) } func getDataPortState() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATUS, paramLen: 0, paramData: [0]) } func setDataPort(_ PortIdx : Int, Ctrl : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(PortIdx) param[1] = Ctrl // 1 - Open, 0 - Close sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_INTERFACE_STATE, paramLen: 2, paramData: param) } func getPowerStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_POWER_STATUS, paramLen: 0, paramData: [0]) } func getSensorStatus() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SENSOR_STATUS, paramLen: 0, paramData: [0]) } func disableStreaming() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DISABLE_STREAMING, paramLen: 0, paramData: [0]) } func resetTimeStamp( Delayed : Bool) { var param = [UInt8](repeating: 0, count: 1) if Delayed == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_RESET_TIMESTAMP, paramLen: 1, paramData: param) } func firmwareUpdate() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_FIRMWARE_UPDATE, paramLen: 0, paramData: [0]) } func getDeviceName() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_GET, paramLen: 0, paramData: [0]) } func setDeviceName(name : String) { let param = [UInt8](name.utf8) print("setDeviceName \(name) \(param))") var len = param.count if len > Int(NEBLINA_NAME_LENGTH_MAX) { len = Int(NEBLINA_NAME_LENGTH_MAX) } sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_NAME_SET, paramLen: len, paramData: param) } func shutdown() { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_DEVICE_SHUTDOWN, paramLen: 0, paramData: [0]) } func getUnixTime(uTime : UInt32) { sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_GET_UNIX_TIMESTAMP, paramLen: 0, paramData: [0]) } func setUnixTime(uTime : UInt32) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(uTime & 0xFF) param[1] = UInt8((uTime >> 8) & 0xFF) param[2] = UInt8((uTime >> 16) & 0xFF) param[3] = UInt8((uTime >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_GENERAL, cmd: NEBLINA_COMMAND_GENERAL_SET_UNIX_TIMESTAMP, paramLen: param.count, paramData: param) } // *** // *** EEPROM // *** func eepromRead(_ pageNo : UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_READ, paramLen: param.count, paramData: param) } func eepromWrite(_ pageNo : UInt16, data : UnsafePointer<UInt8>) { var param = [UInt8](repeating: 0, count: 10) param[0] = UInt8(pageNo & 0xff) param[1] = UInt8((pageNo >> 8) & 0xff) for i in 0..<8 { param[i + 2] = data[i] } sendCommand(subSys: NEBLINA_SUBSYSTEM_EEPROM, cmd: NEBLINA_COMMAND_EEPROM_WRITE, paramLen: param.count, paramData: param) } // *** LED subsystem commands func getLed() { sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATUS, paramLen: 0, paramData: [0]) } func setLed(_ LedNo : UInt8, Value:UInt8) { var param = [UInt8](repeating: 0, count: 2) param[0] = LedNo param[1] = Value sendCommand(subSys: NEBLINA_SUBSYSTEM_LED, cmd: NEBLINA_COMMAND_LED_STATE, paramLen: param.count, paramData: param) } // *** Power management sybsystem commands func getTemperature() { sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_TEMPERATURE, paramLen: 0, paramData: [0]) } func setBatteryChargeCurrent(_ Current: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Current & 0xFF) param[1] = UInt8((Current >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_POWER, cmd: NEBLINA_COMMAND_POWER_CHARGE_CURRENT, paramLen: param.count, paramData: param) } // *** // *** Fusion subsystem commands // *** func setFusionRate(_ Rate: NeblinaRate_t) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate.rawValue & 0xFF) param[1] = UInt8((Rate.rawValue >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_RATE, paramLen: param.count, paramData: param) } func setFusionDownSample(_ Rate: UInt16) { var param = [UInt8](repeating: 0, count: 2) param[0] = UInt8(Rate & 0xFF) param[1] = UInt8((Rate >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_DOWNSAMPLE, paramLen: param.count, paramData: param) } func streamMotionState(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_STATE_STREAM, paramLen: param.count, paramData: param) } func streamQuaternion(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_QUATERNION_STREAM, paramLen: param.count, paramData: param) } func streamEulerAngle(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EULER_ANGLE_STREAM, paramLen: param.count, paramData: param) } func streamExternalForce(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_FORCE_STREAM, paramLen: param.count, paramData: param) } func setFusionType(_ Mode:UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = Mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FUSION_TYPE, paramLen: param.count, paramData: param) } func recordTrajectory(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_RECORD, paramLen: param.count, paramData: param) } func streamTrajectoryInfo(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_TRAJECTORY_INFO_STREAM, paramLen: param.count, paramData: param) } func streamPedometer(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_PEDOMETER_STREAM, paramLen: param.count, paramData: param) } func streamSittingStanding(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SITTING_STANDING_STREAM, paramLen: param.count, paramData: param) } func lockHeadingReference() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_LOCK_HEADING_REFERENCE, paramLen: 0, paramData: [0]) } func streamFingerGesture(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_FINGER_GESTURE_STREAM, paramLen: param.count, paramData: param) } func streamRotationInfo(_ Enable:Bool, Type : UInt8) { var param = [UInt8](repeating: 0, count: 2) param[1] = Type if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ROTATION_INFO_STREAM, paramLen: param.count, paramData: param) } func externalHeadingCorrection(yaw : Int16, error : UInt16 ) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(yaw & 0xFF) param[1] = UInt8((yaw >> 8) & 0xFF) param[2] = UInt8(error & 0xFF) param[3] = UInt8((error >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_EXTERNAL_HEADING_CORRECTION, paramLen: param.count, paramData: param) } func resetAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_RESET, paramLen: 0, paramData: [0]) } func calibrateAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CALIBRATE, paramLen: 0, paramData: [0]) } func createPoseAnalysis(id : UInt8, qtf : [Int16]) { var param = [UInt8](repeating: 0, count: 2 + 8) param[0] = UInt8(id & 0xFF) for i in 0..<4 { param[1 + (i << 1)] = UInt8(qtf[i] & 0xFF) param[2 + (i << 1)] = UInt8((qtf[i] >> 8) & 0xFF) } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_CREATE_POSE, paramLen: param.count, paramData: param) } func setActivePoseAnalysis(id : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_SET_ACTIVE_POSE, paramLen: param.count, paramData: param) } func getActivePoseAnalysis() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_GET_ACTIVE_POSE, paramLen: 0, paramData: [0]) } func streamAnalysis(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_STREAM, paramLen: param.count, paramData: param) } func getPoseAnalysisInfo(_ id: UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = id sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_ANALYSIS_POSE_INFO, paramLen: param.count, paramData: param) } func calibrateForwardPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_FORWARD_POSITION, paramLen: 0, paramData: [0]) } func calibrateDownPosition() { sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CALIBRATE_DOWN_POSITION, paramLen: 0, paramData: [0]) } func streamMotionDirection(_ Enable:Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_MOTION_DIRECTION_STREAM, paramLen: param.count, paramData: param) } func streamShockSegment(_ Enable:Bool, threshold : UInt8 ) { var param = [UInt8](repeating: 0, count: 2) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = threshold sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SHOCK_SEGMENT_STREAM, paramLen: param.count, paramData: param) } func setGolfSwingAnalysisMode(_ mode : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = mode sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_ANALYSIS_MODE, paramLen: param.count, paramData: param) } func setGolfSwingMaxError(_ count : UInt8) { var param = [UInt8](repeating: 0, count: 1) param[0] = count sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_SET_GOLFSWING_MAXIMUM_ERROR, paramLen: param.count, paramData: param) } func streamFunsionClustering(_ enable:Bool, mode : UInt8, sensor : UInt8, downSample : UInt8, snr : UInt8) { var param = [UInt8](repeating: 0, count: 5) if enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = mode param[2] = sensor param[3] = downSample param[4] = snr sendCommand(subSys: NEBLINA_SUBSYSTEM_FUSION, cmd: NEBLINA_COMMAND_FUSION_CLUSTERING_INFO_STREAM, paramLen: param.count, paramData: param) } // *** // *** Storage subsystem commands // *** func getSessionCount() { sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_COUNT, paramLen: 0, paramData: [0]) } func getSessionInfo(_ sessionId : UInt16, idx : UInt8) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) param[2] = idx; sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_GENERAL_INFO, paramLen: param.count, paramData: param) } func getSessionName(_ sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) param[0] = UInt8(sessionId & 0xFF) param[1] = UInt8((sessionId >> 8) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_NAME, paramLen: param.count, paramData: param) } func eraseStorage(_ quickErase:Bool) { var param = [UInt8](repeating: 0, count: 1) if quickErase == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_ERASE_ALL, paramLen: param.count, paramData: param) } func sessionPlayback(_ Enable:Bool, sessionId : UInt16) { var param = [UInt8](repeating: 0, count: 3) if Enable == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(sessionId & 0xff) param[2] = UInt8((sessionId >> 8) & 0xff) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_PLAYBACK, paramLen: param.count, paramData: param) } func sessionRecord(_ Enable:Bool, info : String) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } print("\(info)") param += info.utf8 print("\(param)") sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_RECORD, paramLen: min(param.count, 16), paramData: param) } func sessionRead(_ SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 8) // Command parameter param[0] = UInt8(SessionId & 0xFF) param[1] = UInt8((SessionId >> 8) & 0xFF) param[2] = UInt8(Len & 0xFF) param[3] = UInt8((Len >> 8) & 0xFF) param[4] = UInt8(Offset & 0xFF) param[5] = UInt8((Offset >> 8) & 0xFF) param[6] = UInt8((Offset >> 16) & 0xFF) param[7] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_READ, paramLen: param.count, paramData: param) } func sessionDownload(_ Start : Bool, SessionId:UInt16, Len:UInt16, Offset:UInt32) { var param = [UInt8](repeating: 0, count: 9) // Command parameter if Start == true { param[0] = 1 } else { param[0] = 0 } param[1] = UInt8(SessionId & 0xFF) param[2] = UInt8((SessionId >> 8) & 0xFF) param[3] = UInt8(Len & 0xFF) param[4] = UInt8((Len >> 8) & 0xFF) param[5] = UInt8(Offset & 0xFF) param[6] = UInt8((Offset >> 8) & 0xFF) param[7] = UInt8((Offset >> 16) & 0xFF) param[8] = UInt8((Offset >> 24) & 0xFF) sendCommand(subSys: NEBLINA_SUBSYSTEM_RECORDER, cmd: NEBLINA_COMMAND_RECORDER_SESSION_DOWNLOAD, paramLen: param.count, paramData: param) } // *** // *** Sensor subsystem commands // *** func sensorSetDownsample(stream : UInt16, factor : UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(stream & 0xFF) param[1] = UInt8(stream >> 8) param[2] = UInt8(factor & 0xFF) param[3] = UInt8(factor >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorSetRange(type : UInt16, range: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(range & 0xFF) param[3] = UInt8(range >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RANGE, paramLen: param.count, paramData: param) } func sensorSetRate(type : UInt16, rate: UInt16) { var param = [UInt8](repeating: 0, count: 4) param[0] = UInt8(type & 0xFF) param[1] = UInt8(type >> 8) param[2] = UInt8(rate & 0xFF) param[3] = UInt8(rate >> 8) sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_SET_RATE, paramLen: param.count, paramData: param) } func sensorGetDownsample(stream : NeblinaSensorStream_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = stream.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_DOWNSAMPLE, paramLen: param.count, paramData: param) } func sensorGetRange(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RANGE, paramLen: param.count, paramData: param) } func sensorGetRate(type : NeblinaSensorType_t) { var param = [UInt8](repeating: 0, count: 1) param[0] = type.rawValue sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GET_RATE, paramLen: param.count, paramData: param) } func sensorStreamAccelData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamHumidityData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_HUMIDITY_STREAM, paramLen: param.count, paramData: param) } func sensorStreamMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } func sensorStreamPressureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_PRESSURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamTemperatureData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_TEMPERATURE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelGyroData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_GYROSCOPE_STREAM, paramLen: param.count, paramData: param) } func sensorStreamAccelMagData(_ Enable: Bool) { var param = [UInt8](repeating: 0, count: 1) if Enable == true { param[0] = 1 } else { param[0] = 0 } sendCommand(subSys: NEBLINA_SUBSYSTEM_SENSOR, cmd: NEBLINA_COMMAND_SENSOR_ACCELEROMETER_MAGNETOMETER_STREAM, paramLen: param.count, paramData: param) } }
7524c91751cd3276a91923b7a352669d
25.803526
151
0.670473
false
false
false
false
magi82/MGRelativeKit
refs/heads/master
Sources/RelativeLayout+align.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2017 ByungKook Hwang (https://magi82.github.io) // // 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 extension RelativeLayout { public func alignLeft(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.x = from.frame.origin.x + padding self.layoutChanged.insert(.alignLeft) return self } public func alignRight(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.x = (from.frame.origin.x + from.frame.size.width) - (myView.frame.size.width + padding) self.layoutChanged.insert(.alignRight) return self } public func alignTop(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.y = from.frame.origin.y + padding self.layoutChanged.insert(.alignTop) return self } public func alignBottom(from: UIView, padding: CGFloat = 0) -> Self { guard let myView = self.myView else { return self } myView.frame.origin.y = (from.frame.origin.y + from.frame.size.height) - (myView.frame.size.height + padding) self.layoutChanged.insert(.alignBottom) return self } }
de30219926bfa38d5c511cfad4a8ee87
36.793651
81
0.706006
false
false
false
false
jaischeema/Twist
refs/heads/master
Source/MediaItemResourceLoader.swift
mit
1
// // AVPlayerCaching.swift // Twist // // Created by Jais Cheema on 4/04/2016. // Copyright © 2016 Needle Apps. All rights reserved. // import Foundation import AVFoundation import MobileCoreServices func replaceUrlScheme(_ url: URL, scheme: String) -> URL? { var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false) urlComponents?.scheme = scheme return urlComponents?.url } class MediaItemResourceLoader: NSObject, URLSessionDataDelegate, AVAssetResourceLoaderDelegate { var pendingRequests = [AVAssetResourceLoadingRequest]() var data: NSMutableData? var response: URLResponse? var session: URLSession! var connection: URLSessionDataTask? var successfulDownloadCallback: ((URL) -> Void)? let mediaURL: URL let cachePath: String? let cachingEnabled: Bool var _asset: AVURLAsset? init(mediaURL: URL, cachePath: String?, cachingEnabled: Bool?) { self.mediaURL = mediaURL self.cachePath = cachePath self.cachingEnabled = cachingEnabled == nil ? false : cachingEnabled! super.init() let configuration = URLSessionConfiguration.default configuration.allowsCellularAccess = true configuration.timeoutIntervalForRequest = 30 self.session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main) } var asset: AVURLAsset { if self._asset == nil { self.configureAsset() } return self._asset! } var isCachingEnabled: Bool { return self.cachingEnabled && self.cachePath != nil } var hasCachedFile: Bool { guard let cachePath = self.cachePath else { return false } let fileManager = FileManager.default return fileManager.fileExists(atPath: cachePath) } func configureAsset() { if isCachingEnabled { Twist.log.twistDebug("Caching is enabled") if hasCachedFile { Twist.log.twistDebug("Local cached file is available") self._asset = AVURLAsset(url: URL(fileURLWithPath: self.cachePath!), options: [:]) } else { Twist.log.twistDebug("Local cache file is not available") let streamingURL = replaceUrlScheme(self.mediaURL, scheme: "streaming")! self._asset = AVURLAsset(url: streamingURL, options: [:]) self._asset!.resourceLoader.setDelegate(self, queue: DispatchQueue.main) } } else { Twist.log.twistDebug("Caching is not enabled") self._asset = AVURLAsset(url: self.mediaURL, options: [:]) } assert(self._asset != nil, "Asset should not be nil") } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { Twist.log.twistDebug("Received response") self.data = NSMutableData() self.response = response self.processPendingRequests() completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { print(".", terminator: "") self.data?.append(data) self.processPendingRequests() } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { if error != nil { Twist.log.twistError(error!.localizedDescription) } else { self.processPendingRequests() Twist.log.twistInfo("Writing data to local cached file: \(self.cachePath!)") do { try self.data?.write(toFile: self.cachePath!, options: NSData.WritingOptions.atomicWrite) self.successfulDownloadCallback?(mediaURL) } catch { Twist.log.twistError("Unable to write to original file") } } } func processPendingRequests() { self.pendingRequests = self.pendingRequests.filter { loadingRequest in self.fillInContentInformation(loadingRequest.contentInformationRequest) if self.respondWithDataForRequest(loadingRequest.dataRequest) { loadingRequest.finishLoading() return false } return true } } func fillInContentInformation(_ contentInformationRequest: AVAssetResourceLoadingContentInformationRequest?) { if(contentInformationRequest == nil || self.response == nil) { return } let mimeType = self.response!.mimeType! guard let contentType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType as CFString, nil)?.takeRetainedValue() else { return } contentInformationRequest?.isByteRangeAccessSupported = true contentInformationRequest?.contentType = contentType as String contentInformationRequest?.contentLength = self.response!.expectedContentLength } func respondWithDataForRequest(_ dataRequest: AVAssetResourceLoadingDataRequest?) -> Bool { guard let dataRequest = dataRequest else { return false } let startOffset = Int(dataRequest.currentOffset == 0 ? dataRequest.requestedOffset : dataRequest.currentOffset) if self.data!.length < startOffset { return false } let unreadBytes = self.data!.length - startOffset let numberOfBytesToRespondWith = min(Int(dataRequest.requestedLength), unreadBytes) dataRequest.respond(with: self.data!.subdata(with: NSMakeRange(startOffset, numberOfBytesToRespondWith))) return self.data!.length >= startOffset + dataRequest.requestedLength } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { if self.connection == nil { Twist.log.twistDebug("Starting request to get media URL: \(self.mediaURL)") let request = URLRequest(url: replaceUrlScheme(loadingRequest.request.url!, scheme: "http")!) self.connection = session.dataTask(with: request) self.connection?.resume() } self.pendingRequests.append(loadingRequest) return true } func resourceLoader(_ resourceLoader: AVAssetResourceLoader, didCancel loadingRequest: AVAssetResourceLoadingRequest) { self.pendingRequests = self.pendingRequests.filter { $0 != loadingRequest } } }
39ac48fa74f7dd406c1e9ebf3c3a03a7
39.193939
179
0.661037
false
false
false
false
phimage/MomXML
refs/heads/master
Sources/Model/MomUniquenessConstraints.swift
mit
1
// // MomUniquenessConstraints.swift // MomXML // // Created by Eric Marchand on 01/07/2020. // Copyright © 2020 phimage. All rights reserved. // import Foundation public struct MomUniquenessConstraints { public var constraints: [MomUniquenessConstraint] = [] public mutating func add(constraint: MomUniquenessConstraint) { self.constraints.append(constraint) } public var isEmpty: Bool { return constraints.isEmpty } public init(uniquenessConstraints: [[Any]] = []) { self.constraints = uniquenessConstraints.compactMap { MomUniquenessConstraint(constraints: $0) } } } public struct MomUniquenessConstraint { public var constraints: [MomConstraint] = [] public init() {} public init?(constraints: [Any]) { self.constraints = constraints.compactMap { MomConstraint(any: $0) } if self.constraints.isEmpty { return nil } } } public struct MomConstraint { public var value: String public init(value: String) { self.value = value } public init?(any: Any) { guard let value = any as? String else { return nil } self.value = value } }
6e6eee20c76b88f4e080239828e3f851
21.481481
104
0.640033
false
false
false
false
volodg/iAsync.async
refs/heads/master
Pods/iAsync.async/Lib/JAsyncsOwner.swift
mit
2
// // JAsyncsOwner.swift // JAsync // // Created by Vladimir Gorbenko on 19.06.14. // Copyright (c) 2014 EmbeddedSources. All rights reserved. // import Foundation import iAsync_utils public class JAsyncsOwner { private class ActiveLoaderData { var handler: JAsyncHandler? func clear() { handler = nil } } private var loaders = [ActiveLoaderData]() let task: JAsyncHandlerTask public init(task: JAsyncHandlerTask) { self.task = task } public func ownedAsync<T>(loader: JAsyncTypes<T>.JAsync) -> JAsyncTypes<T>.JAsync { return { [weak self] ( progressCallback: JAsyncProgressCallback?, stateCallback: JAsyncChangeStateCallback?, finishCallback: JAsyncTypes<T>.JDidFinishAsyncCallback?) -> JAsyncHandler in if let self_ = self { let loaderData = ActiveLoaderData() self_.loaders.append(loaderData) let finishCallbackWrapper = { (result: JResult<T>) -> () in if let self_ = self { for (index, element) in enumerate(self_.loaders) { if self_.loaders[index] === loaderData { self_.loaders.removeAtIndex(index) break } } } finishCallback?(result: result) loaderData.clear() } loaderData.handler = loader( progressCallback: progressCallback, stateCallback : stateCallback, finishCallback : finishCallbackWrapper) return { (task: JAsyncHandlerTask) -> () in if let self_ = self { var loaderIndex = Int.max for (index, element) in enumerate(self_.loaders) { if self_.loaders[index] === loaderData { loaderIndex = index break } } if loaderIndex == Int.max { return } self_.loaders.removeAtIndex(loaderIndex) loaderData.handler?(task: task) loaderData.clear() } } } else { let error = JAsyncFinishedByCancellationError() finishCallback?(result: JResult.error(error)) return jStubHandlerAsyncBlock } } } public func handleAll(task: JAsyncHandlerTask) { let tmpLoaders = loaders loaders.removeAll(keepCapacity: false) for (_, element) in enumerate(tmpLoaders) { element.handler?(task: task) } } deinit { handleAll(self.task) } }
8dbcb005bdbb51c2384a37542d38d4cb
29.93578
88
0.430012
false
false
false
false
BlakeBarrett/MettaVR-Coding-Exercise
refs/heads/master
MettaVR Coding Exercise/MettaItem.swift
mit
1
// // MetaItem.swift // MettaVR Coding Exercise // // Created by Blake Barrett on 6/4/16. // Copyright © 2016 Blake Barrett. All rights reserved. // import Foundation class MettaItem { var title: String? var description: String? var copies: [MettaVideoItem]? var previewUrl: NSURL? init(info: NSDictionary) { self.title = info["title"] as? String self.description = info["description"] as? String if let url = info["previewUrl"] as? String { self.previewUrl = NSURL(string: url) } copies = [MettaVideoItem]() if let copiesDictionary = info["copies"] as? NSDictionary { copiesDictionary.allKeys.forEach({ (key:AnyObject) in let item = copiesDictionary.valueForKey(key as! String) as! NSDictionary let video = MettaVideoItem(info: item) copies?.append(video) }) } } }
901dfb9671bbd615328684903dd9f3f7
25.540541
88
0.575943
false
false
false
false
apple/swift-nio
refs/heads/main
Sources/NIOHTTP1/NIOHTTPClientUpgradeHandler.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-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 /// Errors that may be raised by the `HTTPClientProtocolUpgrader`. public struct NIOHTTPClientUpgradeError: Hashable, Error { // Uses the open enum style to allow additional errors to be added in future. private enum Code: Hashable { case responseProtocolNotFound case invalidHTTPOrdering case upgraderDeniedUpgrade case writingToHandlerDuringUpgrade case writingToHandlerAfterUpgradeCompleted case writingToHandlerAfterUpgradeFailed case receivedResponseBeforeRequestSent case receivedResponseAfterUpgradeCompleted } private var code: Code private init(_ code: Code) { self.code = code } public static let responseProtocolNotFound = NIOHTTPClientUpgradeError(.responseProtocolNotFound) public static let invalidHTTPOrdering = NIOHTTPClientUpgradeError(.invalidHTTPOrdering) public static let upgraderDeniedUpgrade = NIOHTTPClientUpgradeError(.upgraderDeniedUpgrade) public static let writingToHandlerDuringUpgrade = NIOHTTPClientUpgradeError(.writingToHandlerDuringUpgrade) public static let writingToHandlerAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeCompleted) public static let writingToHandlerAfterUpgradeFailed = NIOHTTPClientUpgradeError(.writingToHandlerAfterUpgradeFailed) public static let receivedResponseBeforeRequestSent = NIOHTTPClientUpgradeError(.receivedResponseBeforeRequestSent) public static let receivedResponseAfterUpgradeCompleted = NIOHTTPClientUpgradeError(.receivedResponseAfterUpgradeCompleted) } extension NIOHTTPClientUpgradeError: CustomStringConvertible { public var description: String { return String(describing: self.code) } } /// An object that implements `NIOHTTPClientProtocolUpgrader` knows how to handle HTTP upgrade to /// a protocol on a client-side channel. /// It has the option of denying this upgrade based upon the server response. public protocol NIOHTTPClientProtocolUpgrader { /// The protocol this upgrader knows how to support. var supportedProtocol: String { get } /// All the header fields the protocol requires in the request to successfully upgrade. /// These header fields will be added to the outbound request's "Connection" header field. /// It is the responsibility of the custom headers call to actually add these required headers. var requiredUpgradeHeaders: [String] { get } /// Additional headers to be added to the request, beyond the "Upgrade" and "Connection" headers. func addCustom(upgradeRequestHeaders: inout HTTPHeaders) /// Gives the receiving upgrader the chance to deny the upgrade based on the upgrade HTTP response. func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool /// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel /// pipeline to add whatever channel handlers are required. /// Until the returned `EventLoopFuture` succeeds, all received data will be buffered. func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture<Void> } /// A client-side channel handler that sends a HTTP upgrade handshake request to perform a HTTP-upgrade. /// When the first HTTP request is sent, this handler will add all appropriate headers to perform an upgrade to /// the a protocol. It may add headers for a set of protocols in preference order. /// If the upgrade fails (i.e. response is not 101 Switching Protocols), this handler simply /// removes itself from the pipeline. If the upgrade is successful, it upgrades the pipeline to the new protocol. /// /// The request sends an order of preference to request which protocol it would like to use for the upgrade. /// It will only upgrade to the protocol that is returned first in the list and does not currently /// have the capability to upgrade to multiple simultaneous layered protocols. public final class NIOHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableChannelHandler { public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = HTTPClientRequestPart public typealias InboundIn = HTTPClientResponsePart public typealias InboundOut = HTTPClientResponsePart private var upgraders: [NIOHTTPClientProtocolUpgrader] private let httpHandlers: [RemovableChannelHandler] private let upgradeCompletionHandler: (ChannelHandlerContext) -> Void /// Whether we've already seen the first response from our initial upgrade request. private var seenFirstResponse = false private var upgradeState: UpgradeState = .requestRequired private var receivedMessages: CircularBuffer<NIOAny> = CircularBuffer() /// Create a `HTTPClientUpgradeHandler`. /// /// - Parameter upgraders: All `HTTPClientProtocolUpgrader` objects that will add their upgrade request /// headers and handle the upgrade if there is a response for their protocol. They should be placed in /// order of the preference for the upgrade. /// - Parameter httpHandlers: All `RemovableChannelHandler` objects which will be removed from the pipeline /// once the upgrade response is sent. This is used to ensure that the pipeline will be in a clean state /// after the upgrade. It should include any handlers that are directly related to handling HTTP. /// At the very least this should include the `HTTPEncoder` and `HTTPDecoder`, but should also include /// any other handler that cannot tolerate receiving non-HTTP data. /// - Parameter upgradeCompletionHandler: A closure that will be fired when HTTP upgrade is complete. public convenience init( upgraders: [NIOHTTPClientProtocolUpgrader], httpHandlers: [RemovableChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) { self.init(_upgraders: upgraders, httpHandlers: httpHandlers, upgradeCompletionHandler: upgradeCompletionHandler) } private init( _upgraders upgraders: [NIOHTTPClientProtocolUpgrader], httpHandlers: [RemovableChannelHandler], upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void ) { precondition(upgraders.count > 0, "A minimum of one protocol upgrader must be specified.") self.upgraders = upgraders self.httpHandlers = httpHandlers self.upgradeCompletionHandler = upgradeCompletionHandler } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { switch self.upgradeState { case .requestRequired: let updatedData = self.addHeadersToOutboundOut(data: data) context.write(updatedData, promise: promise) case .awaitingConfirmationResponse: // Still have full http stack. context.write(data, promise: promise) case .upgraderReady, .upgrading: promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade) case .upgradingAddingHandlers: // These are most likely messages immediately fired by a new protocol handler. // As that is added last we can just forward them on. context.write(data, promise: promise) case .upgradeComplete: // Upgrade complete and this handler should have been removed from the pipeline. promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) case .upgradeFailed: // Upgrade failed and this handler should have been removed from the pipeline. promise?.fail(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) context.fireErrorCaught(NIOHTTPClientUpgradeError.writingToHandlerAfterUpgradeCompleted) } } private func addHeadersToOutboundOut(data: NIOAny) -> NIOAny { let interceptedOutgoingRequest = self.unwrapOutboundIn(data) if case .head(var requestHead) = interceptedOutgoingRequest { self.upgradeState = .awaitingConfirmationResponse self.addConnectionHeaders(to: &requestHead) self.addUpgradeHeaders(to: &requestHead) return self.wrapOutboundOut(.head(requestHead)) } return data } private func addConnectionHeaders(to requestHead: inout HTTPRequestHead) { let requiredHeaders = ["upgrade"] + self.upgraders.flatMap { $0.requiredUpgradeHeaders } requestHead.headers.add(name: "Connection", value: requiredHeaders.joined(separator: ",")) } private func addUpgradeHeaders(to requestHead: inout HTTPRequestHead) { let allProtocols = self.upgraders.map { $0.supportedProtocol.lowercased() } requestHead.headers.add(name: "Upgrade", value: allProtocols.joined(separator: ",")) // Allow each upgrader the chance to add custom headers. for upgrader in self.upgraders { upgrader.addCustom(upgradeRequestHeaders: &requestHead.headers) } } public func channelRead(context: ChannelHandlerContext, data: NIOAny) { guard !self.seenFirstResponse else { // We're waiting for upgrade to complete: buffer this data. self.receivedMessages.append(data) return } let responsePart = unwrapInboundIn(data) switch self.upgradeState { case .awaitingConfirmationResponse: self.firstResponseHeadReceived(context: context, responsePart: responsePart) case .upgrading, .upgradingAddingHandlers: if case .end = responsePart { // This is the end of the first response. Swallow it, we're buffering the rest. self.seenFirstResponse = true } case .upgraderReady(let upgrade): if case .end = responsePart { // This is the end of the first response, and we can upgrade. Time to kick it off. self.seenFirstResponse = true upgrade() } case .upgradeFailed: // We were reentrantly called while delivering the response head. We can just pass this through. context.fireChannelRead(data) case .upgradeComplete: //Upgrade has completed but we have not seen a whole response and still got reentrantly called. context.fireErrorCaught(NIOHTTPClientUpgradeError.receivedResponseAfterUpgradeCompleted) case .requestRequired: //We are receiving an upgrade response and we have not requested the upgrade. context.fireErrorCaught(NIOHTTPClientUpgradeError.receivedResponseBeforeRequestSent) } } private func firstResponseHeadReceived(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) { // We should decide if we're can upgrade based on the first response header: if we aren't upgrading, // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're // upgrading, the only thing we should see is a response head. Anything else in an error. guard case .head(let response) = responsePart else { self.notUpgrading(context: context, data: responsePart, error: .invalidHTTPOrdering) return } // Assess whether the upgrade response has accepted our upgrade request. guard case .switchingProtocols = response.status else { self.notUpgrading(context: context, data: responsePart, error: nil) return } do { let callback = try self.handleUpgrade(context: context, upgradeResponse: response) self.gotUpgrader(upgrader: callback) } catch { let clientError = error as? NIOHTTPClientUpgradeError self.notUpgrading(context: context, data: responsePart, error: clientError) } } private func handleUpgrade(context: ChannelHandlerContext, upgradeResponse response: HTTPResponseHead) throws -> (() -> Void) { // Ok, we have a HTTP response. Check if it's an upgrade confirmation. // If it's not, we want to pass it on and remove ourselves from the channel pipeline. let acceptedProtocols = response.headers[canonicalForm: "upgrade"] // At the moment we only upgrade to the first protocol returned from the server. guard let protocolName = acceptedProtocols.first?.lowercased() else { // There are no upgrade protocols returned. throw NIOHTTPClientUpgradeError.responseProtocolNotFound } return try self.handleUpgradeForProtocol(context: context, protocolName: protocolName, response: response) } /// Attempt to upgrade a single protocol. private func handleUpgradeForProtocol(context: ChannelHandlerContext, protocolName: String, response: HTTPResponseHead) throws -> (() -> Void) { let matchingUpgrader = self.upgraders .first(where: { $0.supportedProtocol.lowercased() == protocolName }) guard let upgrader = matchingUpgrader else { // There is no upgrader for this protocol. throw NIOHTTPClientUpgradeError.responseProtocolNotFound } guard upgrader.shouldAllowUpgrade(upgradeResponse: response) else { // The upgrader says no. throw NIOHTTPClientUpgradeError.upgraderDeniedUpgrade } return self.performUpgrade(context: context, upgrader: upgrader, response: response) } private func performUpgrade(context: ChannelHandlerContext, upgrader: NIOHTTPClientProtocolUpgrader, response: HTTPResponseHead) -> () -> Void { // Before we start the upgrade we have to remove the HTTPEncoder and HTTPDecoder handlers from the // pipeline, to prevent them parsing any more data. We'll buffer the incoming data until that completes. // While there are a lot of Futures involved here it's quite possible that all of this code will // actually complete synchronously: we just want to program for the possibility that it won't. // Once that's done, we call the internal handler, then call the upgrader code, and then finally when the // upgrader code is done, we do our final cleanup steps, namely we replay the received data we // buffered in the meantime and then remove ourselves from the pipeline. return { self.upgradeState = .upgrading self.removeHTTPHandlers(context: context) .map { // Let the other handlers be removed before continuing with upgrade. self.upgradeCompletionHandler(context) self.upgradeState = .upgradingAddingHandlers } .flatMap { upgrader.upgrade(context: context, upgradeResponse: response) } .map { // We unbuffer any buffered data here. // If we received any, we fire readComplete. let fireReadComplete = self.receivedMessages.count > 0 while self.receivedMessages.count > 0 { let bufferedPart = self.receivedMessages.removeFirst() context.fireChannelRead(bufferedPart) } if fireReadComplete { context.fireChannelReadComplete() } // We wait with the state change until _after_ the channel reads here. // This is to prevent firing writes in response to these reads after we went to .upgradeComplete // See: https://github.com/apple/swift-nio/issues/1279 self.upgradeState = .upgradeComplete } .whenComplete { _ in context.pipeline.removeHandler(context: context, promise: nil) } } } /// Removes any extra HTTP-related handlers from the channel pipeline. private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture<Void> { guard self.httpHandlers.count > 0 else { return context.eventLoop.makeSucceededFuture(()) } let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) } return .andAllSucceed(removeFutures, on: context.eventLoop) } private func gotUpgrader(upgrader: @escaping (() -> Void)) { self.upgradeState = .upgraderReady(upgrader) if self.seenFirstResponse { // Ok, we're good to go, we can upgrade. Otherwise we're waiting for .end, which // will trigger the upgrade. upgrader() } } private func notUpgrading(context: ChannelHandlerContext, data: HTTPClientResponsePart, error: NIOHTTPClientUpgradeError?) { self.upgradeState = .upgradeFailed if let error = error { context.fireErrorCaught(error) } assert(self.receivedMessages.isEmpty) context.fireChannelRead(self.wrapInboundOut(data)) // We've delivered the data. We can now remove ourselves, which should happen synchronously. context.pipeline.removeHandler(context: context, promise: nil) } } extension NIOHTTPClientUpgradeHandler: @unchecked Sendable {} extension NIOHTTPClientUpgradeHandler { /// The state of the upgrade handler. fileprivate enum UpgradeState { /// Request not sent. This will need to be sent to initiate the upgrade. case requestRequired /// Awaiting confirmation response which will allow the upgrade to zero one or more protocols. case awaitingConfirmationResponse /// The response head has been received. We have an upgrader, which means we can begin upgrade. case upgraderReady(() -> Void) /// The response head has been received. The upgrade is in process. case upgrading /// The upgrade is in process and all of the http handlers have been removed. case upgradingAddingHandlers /// The upgrade has succeeded, and we are being removed from the pipeline. case upgradeComplete /// The upgrade has failed. case upgradeFailed } }
309432e82511424d7eaae5a6e1aeaa3b
46.687961
149
0.678397
false
false
false
false
ChenJian345/realm-cocoa
refs/heads/master
Pods/RealmSwift/RealmSwift/Util.swift
apache-2.0
4
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: Internal Helpers internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) { NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise() } internal func throwForNegativeIndex(int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { do { let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions(rawValue: 0)) return regex.stringByReplacingMatchesInString(string, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } catch { // no-op } return nil }
90827c4ec9ebf148e8613d13c58b9f33
35.285714
183
0.651294
false
false
false
false
TrustWallet/trust-wallet-ios
refs/heads/master
Trust/Transactions/Types/LocalizedOperationObject.swift
gpl-3.0
1
// Copyright DApps Platform Inc. All rights reserved. import Foundation import RealmSwift import TrustCore final class LocalizedOperationObject: Object, Decodable { @objc dynamic var from: String = "" @objc dynamic var to: String = "" @objc dynamic var contract: String? = .none @objc dynamic var type: String = "" @objc dynamic var value: String = "" @objc dynamic var name: String? = .none @objc dynamic var symbol: String? = .none @objc dynamic var decimals: Int = 18 convenience init( from: String, to: String, contract: String?, type: String, value: String, symbol: String?, name: String?, decimals: Int ) { self.init() self.from = from self.to = to self.contract = contract self.type = type self.value = value self.symbol = symbol self.name = name self.decimals = decimals } enum LocalizedOperationObjectKeys: String, CodingKey { case from case to case type case value case contract } convenience required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: LocalizedOperationObjectKeys.self) let from = try container.decode(String.self, forKey: .from) let to = try container.decode(String.self, forKey: .to) guard let fromAddress = EthereumAddress(string: from), let toAddress = EthereumAddress(string: to) else { let context = DecodingError.Context(codingPath: [LocalizedOperationObjectKeys.from, LocalizedOperationObjectKeys.to, ], debugDescription: "Address can't be decoded as a TrustKeystore.Address") throw DecodingError.dataCorrupted(context) } let type = try container.decode(OperationType.self, forKey: .type) let value = try container.decode(String.self, forKey: .value) let contract = try container.decode(ERC20Contract.self, forKey: .contract) self.init(from: fromAddress.description, to: toAddress.description, contract: contract.address, type: type.rawValue, value: value, symbol: contract.symbol, name: contract.name, decimals: contract.decimals ) } var operationType: OperationType { return OperationType(string: type) } }
60da331df068320882511bbca78dd8f6
32.987013
124
0.584639
false
false
false
false
gkaimakas/Ion
refs/heads/master
Example/Tests/Tests.swift
mit
1
// https://github.com/Quick/Quick import Quick import Nimble import Ion class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } } } } }
0818d05d1848d26a9fedbad3ba3ec442
19.138889
60
0.387586
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Eurofurence/Modules/Dealer Detail/Interactor/DefaultDealerDetailViewModel.swift
mit
1
import EurofurenceModel import Foundation private protocol DetailViewModelComponent { func describe(to visitor: DealerDetailViewModelVisitor) } struct DefaultDealerDetailViewModel: DealerDetailViewModel { struct SummaryComponent: DetailViewModelComponent { var summary: DealerDetailSummaryViewModel func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(summary) } } struct LocationAndAvailabilityComponent: DetailViewModelComponent { var locationAndAvailability: DealerDetailLocationAndAvailabilityViewModel init?(locationAndAvailability: DealerDetailLocationAndAvailabilityViewModel) { guard locationAndAvailability.mapPNGGraphicData != nil || locationAndAvailability.limitedAvailabilityWarning != nil || locationAndAvailability.locatedInAfterDarkDealersDenMessage != nil else { return nil } self.locationAndAvailability = locationAndAvailability } func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(locationAndAvailability) } } struct AboutTheArtistComponent: DetailViewModelComponent { var aboutTheArtist: DealerDetailAboutTheArtistViewModel func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(aboutTheArtist) } } struct AboutTheArtComponent: DetailViewModelComponent { var aboutTheArt: DealerDetailAboutTheArtViewModel init?(aboutTheArt: DealerDetailAboutTheArtViewModel) { guard aboutTheArt.aboutTheArt != nil || aboutTheArt.artPreviewImagePNGData != nil || aboutTheArt.artPreviewImagePNGData != nil else { return nil } self.aboutTheArt = aboutTheArt } func describe(to visitor: DealerDetailViewModelVisitor) { visitor.visit(aboutTheArt) } } private var components = [DetailViewModelComponent]() private let dealer: Dealer private let dealerIdentifier: DealerIdentifier private let dealersService: DealersService private let shareService: ShareService init(dealer: Dealer, data: ExtendedDealerData, dealerIdentifier: DealerIdentifier, dealersService: DealersService, shareService: ShareService) { self.dealer = dealer self.dealerIdentifier = dealerIdentifier self.dealersService = dealersService self.shareService = shareService let summary = DealerDetailSummaryViewModel(artistImagePNGData: data.artistImagePNGData, title: data.preferredName, subtitle: data.alternateName, categories: data.categories.joined(separator: ", "), shortDescription: data.dealerShortDescription, website: data.websiteName, twitterHandle: data.twitterUsername, telegramHandle: data.telegramUsername) let summaryComponent = SummaryComponent(summary: summary) components.append(summaryComponent) var afterDarkMessage: String? if data.isAfterDark { afterDarkMessage = .locatedWithinAfterDarkDen } let limitedAvailabilityMessage = prepareLimitedAvailabilityMessage(data) let locationAndAvailability = DealerDetailLocationAndAvailabilityViewModel(title: .locationAndAvailability, mapPNGGraphicData: data.dealersDenMapLocationGraphicPNGData, limitedAvailabilityWarning: limitedAvailabilityMessage, locatedInAfterDarkDealersDenMessage: afterDarkMessage) if let locationAndAvailabilityComponent = LocationAndAvailabilityComponent(locationAndAvailability: locationAndAvailability) { components.append(locationAndAvailabilityComponent) } var aboutTheArtistText: String = .aboutTheArtistPlaceholder if let text = data.aboutTheArtist { aboutTheArtistText = text } let aboutTheArtist = DealerDetailAboutTheArtistViewModel(title: .aboutTheArtist, artistDescription: aboutTheArtistText) let aboutTheArtistComponent = AboutTheArtistComponent(aboutTheArtist: aboutTheArtist) components.append(aboutTheArtistComponent) let aboutTheArt = DealerDetailAboutTheArtViewModel(title: .aboutTheArt, aboutTheArt: data.aboutTheArt, artPreviewImagePNGData: data.artPreviewImagePNGData, artPreviewCaption: data.artPreviewCaption) if let aboutTheArtComponent = AboutTheArtComponent(aboutTheArt: aboutTheArt) { components.append(aboutTheArtComponent) } } private func prepareLimitedAvailabilityMessage(_ data: ExtendedDealerData) -> String? { var limitedAvailabilityMessage: String? if !data.isAttendingOnThursday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Friday", "Saturday"]) } if !data.isAttendingOnFriday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday", "Saturday"]) } if !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday", "Friday"]) } if !data.isAttendingOnFriday && !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Thursday"]) } if !data.isAttendingOnThursday && !data.isAttendingOnSaturday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Friday"]) } if !data.isAttendingOnThursday && !data.isAttendingOnFriday { limitedAvailabilityMessage = String.formattedOnlyPresentOnDaysString(["Saturday"]) } return limitedAvailabilityMessage } var numberOfComponents: Int { return components.count } func describeComponent(at index: Int, to visitor: DealerDetailViewModelVisitor) { guard index < components.count else { return } components[index].describe(to: visitor) } func openWebsite() { dealer.openWebsite() } func openTwitter() { dealer.openTwitter() } func openTelegram() { dealer.openTelegram() } func shareDealer(_ sender: Any) { let url = dealer.makeContentURL() shareService.share(url, sender: sender) } }
34b5aa2dd3e21a495fc6c4bba26cc7d4
37.367021
143
0.626369
false
false
false
false
kenwilcox/TheForecaster
refs/heads/master
TheForecaster/ViewController.swift
mit
1
// // ViewController.swift // TheForecaster // // Created by Kenneth Wilcox on 5/12/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import UIKit import WeatherShare class ViewController: UIViewController { @IBOutlet weak var temperatureLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var weatherImageView: UIImageView! @IBOutlet weak var weatherConditionsLabel: UILabel! @IBOutlet weak var updateDateLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "locationDidUpdate:", name: GlobalConstants.NotificationNames.locationDidUpdate, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshWeatherButtonPressed(sender: UIButton) { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.locationController?.locationManager.stopUpdatingLocation() appDelegate.locationController?.locationManager.startUpdatingLocation() } func locationDidUpdate(notification: NSNotification) { println("locationAvaliable") let locationDictionary = notification.userInfo as! Dictionary<String,AnyObject> let latitude = locationDictionary[GlobalConstants.LocationDictionary.latitude] as! Double let longitude = locationDictionary[GlobalConstants.LocationDictionary.longitude] as! Double let city = locationDictionary[GlobalConstants.LocationDictionary.city] as! String let state = locationDictionary[GlobalConstants.LocationDictionary.state] as! String let country = locationDictionary[GlobalConstants.LocationDictionary.country] as! String let lastUpdatedAt = locationDictionary[GlobalConstants.LocationDictionary.timestamp] as! NSDate println(locationDictionary) //locationLabel.text = "\(city), \(state) (\(country))" ForecastNetwork.requestWeather(latitude: latitude, longitude: longitude) { (responseDictionary) -> () in println(responseDictionary) if responseDictionary != nil { dispatch_async(dispatch_get_main_queue()) { let currentConditionsDictionary = responseDictionary![GlobalConstants.ForecastNetwork.currently] as! NSDictionary let iconName = currentConditionsDictionary[GlobalConstants.ForecastNetwork.icon] as! String self.weatherImageView.image = UIImage(named: iconName) let temperature = currentConditionsDictionary[GlobalConstants.ForecastNetwork.temperature] as! Double self.temperatureLabel.text = "\(temperature) ℉" let conditions = currentConditionsDictionary[GlobalConstants.ForecastNetwork.summary] as! String self.weatherConditionsLabel.text = conditions self.locationLabel.text = "\(city), \(state), \(country)" let formattedDate = NSDateFormatter.localizedStringFromDate(lastUpdatedAt, dateStyle: NSDateFormatterStyle.MediumStyle, timeStyle: NSDateFormatterStyle.MediumStyle) self.updateDateLabel.text = formattedDate } } else { println("No Response: could not update") } } } }
b55b78ed412d838f830f4893c6a70c89
42.571429
174
0.743964
false
false
false
false
catloafsoft/AudioKit
refs/heads/master
AudioKit/iOS/AudioKit/AudioKit.playground/Pages/MultiDelay Example.xcplaygroundpage/Contents.swift
mit
1
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## MultiDelay Example //: ### This is similar to the MultiDelay implemented in the Analog Synth X example project. import XCPlayground import AudioKit let bundle = NSBundle.mainBundle() let file = bundle.pathForResource("drumloop", ofType: "wav") //: Here we set up a player to the loop the file's playback var player = AKAudioPlayer(file!) player.looping = true func multitapDelay(input: AKNode, times: [Double], gains: [Double]) -> AKMixer { let mix = AKMixer(input) zip(times, gains).forEach { (time, gain) -> () in let delay = AKVariableDelay(input, time: time, feedback: 0.0) mix.connect(AKBooster(delay, gain: gain)) } return mix } // Delay Properties var delayTime = 0.2 // Seconds var delayMix = 0.4 // 0 (dry) - 1 (wet) let gains = [0.5, 0.25, 0.15].map { g -> Double in g * delayMix } let input = player // Delay Definition let leftDelay = multitapDelay(input, times: [1.5, 2.5, 3.5].map { t -> Double in t * delayTime }, gains: gains) let rightDelay = multitapDelay(input, times: [1, 2, 3].map { t -> Double in t * delayTime }, gains: gains) let delayPannedLeft = AKPanner(leftDelay, pan: -1) let delayPannedRight = AKPanner(rightDelay, pan: 1) let mix = AKMixer(delayPannedLeft, delayPannedRight) AudioKit.output = mix AudioKit.start() player.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
422288393bc5d62cfe832ebfc0d708f3
29.94
92
0.676794
false
false
false
false
lenssss/whereAmI
refs/heads/master
Whereami/Controller/Personal/PersonalTravelFollowViewController.swift
mit
1
// // PersonalTravelFollowViewController.swift // Whereami // // Created by A on 16/5/17. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class PersonalTravelFollowViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { typealias theCallback = ([AnyObject]) -> Void var type:String? = nil var tableView:UITableView? = nil var models:[FriendsModel]? = nil override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.setConfig() self.setUI() } /* override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBar.backgroundColor = UIColor.getMainColor() self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: .Default) self.navigationController?.navigationBar.barTintColor = UIColor.getMainColor() } */ func setUI(){ let backBtn = TheBackBarButton.initWithAction({ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) self.tableView = UITableView() self.tableView?.separatorStyle = .None self.tableView?.delegate = self self.tableView?.dataSource = self self.view.addSubview(self.tableView!) self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsetsMake(0, 0, 0, 0)) self.tableView?.registerClass(ContactItemTableViewCell.self, forCellReuseIdentifier: "ContactItemTableViewCell") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if self.models != nil { return (self.models?.count)! } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ContactItemTableViewCell", forIndexPath: indexPath) as! ContactItemTableViewCell cell.selectionStyle = .None let user = self.models![indexPath.row] let avatarUrl = user.headPortrait != nil ? user.headPortrait : "" cell.avatar?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.chatName?.text = user.nickname cell.location?.text = "chengdu,China" cell.callBack = {(button) -> Void in self.addFriend(indexPath, cell: cell) } cell.addButton?.hidden = false if user.friendId == UserModel.getCurrentUser()!.id { cell.addButton?.hidden = true } cell.addButton?.setTitle(NSLocalizedString("add",tableName:"Localizable", comment: ""), forState: .Normal) if self.models != nil { let friendModel = models![indexPath.row] let friend = CoreDataManager.sharedInstance.fetchFriendByFriendId(friendModel.accountId!, friendId: friendModel.friendId!) if friend != nil { cell.addButton?.setTitle(NSLocalizedString("added",tableName:"Localizable", comment: ""), forState: .Normal) } } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let friendModel:FriendsModel = models![indexPath.row] let personalVC = TourRecordsViewController() personalVC.userId = friendModel.friendId personalVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(personalVC, animated: true) } func addFriend(indexPath:NSIndexPath,cell:ContactItemTableViewCell){ var dict = [String: AnyObject]() dict["accountId"] = UserModel.getCurrentUser()?.id dict["friendId"] = models![indexPath.row].friendId SocketManager.sharedInstance.sendMsg("addFreind", data: dict, onProto: "addFreinded", callBack: { (code, objs) in if code == statusCode.Normal.rawValue { let friend = self.models![indexPath.row] var dic = [String:AnyObject]() dic["searchIds"] = [friend.friendId!] SocketManager.sharedInstance.sendMsg("getUserDatasByUserIds", data: dic, onProto: "getUserDatasByUserIdsed") { (code, objs) in if code == statusCode.Normal.rawValue { let userData = objs[0]["userData"] as! [AnyObject] let user = UserModel.getModelFromDictionary(userData[0] as! NSDictionary) CoreDataManager.sharedInstance.increaseOrUpdateUser(user) } } CoreDataManager.sharedInstance.increaseFriends(friend) self.runInMainQueue({ cell.addButton?.setTitle(NSLocalizedString("added",tableName:"Localizable", comment: ""), forState: .Normal) cell.addButton?.enabled = false }) } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
fa23571936c130e21314dcd0b13a8f88
42.572519
176
0.647162
false
false
false
false
zisko/swift
refs/heads/master
test/SILOptimizer/outliner.swift
apache-2.0
1
// RUN: %target-swift-frontend -Osize -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s // RUN: %target-swift-frontend -Osize -g -import-objc-header %S/Inputs/Outliner.h %s -emit-sil | %FileCheck %s // REQUIRES: objc_interop import Foundation public class MyGizmo { private var gizmo : Gizmo private var optionalGizmo : Gizmo? init() { gizmo = Gizmo() } // CHECK-LABEL: sil @$S8outliner7MyGizmoC11usePropertyyyF // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTeab_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK-NOT: return // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK: return public func useProperty() { print(gizmo.stringProperty) print(optionalGizmo!.stringProperty) } } // CHECK-LABEL: sil @$S8outliner13testOutliningyyF // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvgToTepb_ // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]](%{{.*}}) : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Gizmo) -> () // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> // CHECK: [[FUN:%.*]] = function_ref @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: apply [[FUN]]({{.*}}) : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> // CHECK: return public func testOutlining() { let gizmo = Gizmo() let foobar = Gizmo() print(gizmo.stringProperty) print(gizmo.stringProperty) gizmo.stringProperty = "foobar" gizmo.stringProperty = "foobar2" gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) gizmo.modifyString("hello", withNumber:1, withFoobar: foobar) let arr = [ "foo", "bar"] gizmo.doSomething(arr) gizmo.doSomething(arr) } // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTeab_ : $@convention(thin) (@in_guaranteed Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $*Gizmo): // CHECK: %1 = load %0 : $*Gizmo // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %3 = apply %2(%1) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %3 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK: bb1(%5 : $NSString): // CHECK: %6 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %7 = metatype $@thin String.Type // CHECK: %8 = apply %6(%3, %7) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %9 = enum $Optional<String>, #Optional.some!enumelt.1, %8 : $String // CHECK: br bb3(%9 : $Optional<String>) // CHECK: bb2: // CHECK: %11 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%11 : $Optional<String>) // CHECK: bb3(%13 : $Optional<String>): // CHECK: return %13 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvgToTepb_ : $@convention(thin) (Gizmo) -> @owned Optional<String> // CHECK: bb0(%0 : $Gizmo): // CHECK: %1 = objc_method %0 : $Gizmo, #Gizmo.stringProperty!getter.1.foreign : (Gizmo) -> () -> String? // CHECK: %2 = apply %1(%0) : $@convention(objc_method) (Gizmo) -> @autoreleased Optional<NSString> // CHECK: switch_enum %2 : $Optional<NSString>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2 // CHECK:bb1(%4 : $NSString): // CHECK: %5 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %6 = metatype $@thin String.Type // CHECK: %7 = apply %5(%2, %6) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %8 = enum $Optional<String>, #Optional.some!enumelt.1, %7 : $String // CHECK: br bb3(%8 : $Optional<String>) // CHECK:bb2: // CHECK: %10 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%10 : $Optional<String>) // CHECK:bb3(%12 : $Optional<String>): // CHECK: return %12 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC14stringPropertySSSgvsToTembnn_ : $@convention(thin) (@owned String, Gizmo) -> () { // CHECK: bb0(%0 : $String, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.stringProperty!setter.1.foreign : (Gizmo) -> (String?) -> () // CHECK: %3 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %4 = apply %3(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %6 = enum $Optional<NSString>, #Optional.some!enumelt.1, %4 : $NSString // CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSString>, Gizmo) -> () // CHECK: strong_release %4 : $NSString // CHECK: return %7 : $() // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC12modifyString_10withNumber0D6FoobarSSSgAF_SiypSgtFToTembnnnb_ : $@convention(thin) (@owned String, Int, Optional<AnyObject>, Gizmo) -> @owned Optional<String> { // CHECK: bb0(%0 : $String, %1 : $Int, %2 : $Optional<AnyObject>, %3 : $Gizmo): // CHECK: %4 = objc_method %3 : $Gizmo, #Gizmo.modifyString!1.foreign : (Gizmo) -> (String?, Int, Any?) -> String? // CHECK: %5 = function_ref @$SSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: %6 = apply %5(%0) : $@convention(method) (@guaranteed String) -> @owned NSString // CHECK: release_value %0 : $String // CHECK: %8 = enum $Optional<NSString>, #Optional.some!enumelt.1, %6 : $NSString // CHECK: %9 = apply %4(%8, %1, %2, %3) : $@convention(objc_method) (Optional<NSString>, Int, Optional<AnyObject>, Gizmo) -> @autoreleased Optional<NSString> // CHECK: strong_release %6 : $NSString // CHECK: switch_enum %9 : $Optional<NSString>, case #Optional.some!enumelt.1: bb2, case #Optional.none!enumelt: bb1 // // CHECK: bb1: // CHECK: %12 = enum $Optional<String>, #Optional.none!enumelt // CHECK: br bb3(%12 : $Optional<String>) // // CHECK: bb2(%14 : $NSString): // CHECK: %15 = function_ref @$SSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %16 = metatype $@thin String.Type // CHECK: %17 = apply %15(%9, %16) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: %18 = enum $Optional<String>, #Optional.some!enumelt.1, %17 : $String // CHECK: br bb3(%18 : $Optional<String>) // // CHECK: bb3(%20 : $Optional<String>): // CHECK: return %20 : $Optional<String> // CHECK-LABEL: sil shared [noinline] @$SSo5GizmoC11doSomethingyypSgSaySSGSgFToTembnn_ : $@convention(thin) (@owned Array<String>, Gizmo) -> @owned Optional<AnyObject> { // CHECK: bb0(%0 : $Array<String>, %1 : $Gizmo): // CHECK: %2 = objc_method %1 : $Gizmo, #Gizmo.doSomething!1.foreign : (Gizmo) -> ([String]?) -> Any? // CHECK: %3 = function_ref @$SSa10FoundationE19_bridgeToObjectiveCSo7NSArrayCyF : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK: %4 = apply %3<String>(%0) : $@convention(method) <{{.*}}> (@guaranteed Array<{{.*}}>) -> @owned NSArray // CHECK: release_value %0 : $Array<String> // CHECK: %6 = enum $Optional<NSArray>, #Optional.some!enumelt.1, %4 : $NSArray // CHECK: %7 = apply %2(%6, %1) : $@convention(objc_method) (Optional<NSArray>, Gizmo) -> @autoreleased Optional<AnyObject> // CHECK: strong_release %4 : $NSArray // CHECK: return %7 : $Optional<AnyObject> public func dontCrash<T: Proto>(x : Gizmo2<T>) { let s = x.doSomething() print(s) } public func dontCrash2(_ c: SomeGenericClass) -> Bool { guard let str = c.version else { return false } guard let str2 = c.doSomething() else { return false } let arr = [ "foo", "bar"] c.doSomething2(arr) return true }
b0416e7f2815356a80a306f29f325d16
56.5
211
0.661315
false
false
false
false
spritesun/MeditationHelper
refs/heads/master
MeditationHelper/MeditationHelper/MHMigrator.swift
mit
1
// // MHMigrator.swift // MeditationHelper // // Created by Long Sun on 22/01/2015. // Copyright (c) 2015 Sunlong. All rights reserved. // struct MHMigrator { private init () {} static func migrate () { // migrateMeditationCommentToCommentRaw() } // static func migrateMeditationCommentToCommentRaw() { // let query = MHMeditation.query() // query.findObjectsInBackgroundWithBlock({ (meditations, error) -> Void in // if error == nil { // for meditation in meditations as [MHMeditation] { // meditation.commentRaw = meditation.comment?.dataUsingEncoding(NSUTF8StringEncoding) // meditation.comment = nil // println("\(meditation) migrated") // meditation.saveInBackground() // } // } // }) // } }
1c229370ee9295b8c558aee01bbef5a9
25.3
95
0.633714
false
false
false
false
OEASLAN/OEANotification
refs/heads/master
Classes/OEANotification.swift
mit
1
// // OEANotification.swift // OEANotification // // Created by Ömer Emre Aslan on 15/11/15. // Copyright © 2015 omer. All rights reserved. // import UIKit public class OEANotification : UIView { static let constant = Constants() static var rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight) static var viewController: UIViewController! static var notificationCount = 0 static var rotated:Bool = false // MARK: - Initial notification methods /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - omeremreaslan@gmail.com - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, type: NotificationType, isDismissable: Bool ){ self.notify(title, subTitle: subTitle, image: nil, type: type, isDismissable: isDismissable) } /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - omeremreaslan@gmail.com - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter image: The main icon image of notification like avatar, success, warning etc. icons - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, image: UIImage?, type: NotificationType, isDismissable: Bool ) { self.notify(title, subTitle: subTitle, image: image, type: type, isDismissable: isDismissable, completion: nil, touchHandler: nil) } /** Initial static method of creating notification. - since: 0.1.0 - author: @OEASLAN - omeremreaslan@gmail.com - parameter title: The title of notification. - parameter subTitle: The subtitle of notification. - parameter type: The type of notification which are Success, Warning, and Info. - parameter image: The main icon image of notification like avatar, success, warning etc. icons - parameter completion: The main icon image of notification like avatar, success, warning etc. icons - parameter isDismissable: The notification center from which the notification should be dispatched. - return: void */ static public func notify( title: String, subTitle: String, image: UIImage?, type: NotificationType, isDismissable: Bool, completion: (() -> Void)?, touchHandler: (() ->Void)? ) { let notificationView: NotificationView = NotificationView( frame: rect, title: title, subTitle: subTitle, image: image, type: type, completionHandler: completion, touchHandler: touchHandler, isDismissable: isDismissable ) OEANotification.notificationCount++ OEANotification.removeOldNotifications() print(OEANotification.viewController.view.frame) if OEANotification.viewController.navigationController != nil { OEANotification.viewController.navigationController!.view.addSubview(notificationView) } else { OEANotification.viewController.view.addSubview(notificationView) } } /** Sets the default view controller as a main view controller. - since: 0.1.0 - author: @OEASLAN - omeremreaslan@gmail.com - parameter viewController: The main controller which shows the notification. - return: void */ static public func setDefaultViewController (viewController: UIViewController) { self.viewController = viewController NSNotificationCenter.defaultCenter().addObserver(self, selector: "rotateRecognizer", name: UIDeviceOrientationDidChangeNotification, object: nil) } // MARK: - Helper methods static public func removeOldNotifications() { if OEANotification.viewController.navigationController != nil { for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.notificationTimer.invalidate() subUIView.removeFromSuperview() OEANotification.notificationCount-- } } } else { for subUIView in OEANotification.viewController.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.notificationTimer.invalidate() subUIView.removeFromSuperview() OEANotification.notificationCount-- } } } } // Close active notification static public func closeNotification() { if OEANotification.viewController.navigationController != nil { for subUIView in OEANotification.viewController.navigationController!.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.close() } } } else { for subUIView in OEANotification.viewController.view.subviews as [UIView] { if subUIView.isKindOfClass(NotificationView) { let view: NotificationView = subUIView as! NotificationView view.close() } } } } // Checking device's rotation process and remove notifications to handle UI conflicts. static public func rotateRecognizer() { removeOldNotifications() UIApplication.sharedApplication().delegate?.window??.windowLevel = UIWindowLevelNormal self.rect = CGRectMake(constant.nvMarginLeft, constant.nvStartYPoint, OEANotification.viewController.view.frame.width - constant.nvMarginLeft - constant.nvMarginRight, constant.nvHeight) } } public enum NotificationType { case Warning case Success case Info }
8255ec88fbf554bf0cb62096ef6443b1
39.10929
196
0.613079
false
false
false
false
karivalkama/Agricola-Scripture-Editor
refs/heads/master
Pods/QRCodeReader.swift/Sources/QRCodeReaderView.swift
mit
1
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit final public class QRCodeReaderView: UIView, QRCodeReaderDisplayable { public lazy var overlayView: UIView? = { let ov = ReaderOverlayView() ov.backgroundColor = .clear ov.clipsToBounds = true ov.translatesAutoresizingMaskIntoConstraints = false return ov }() public let cameraView: UIView = { let cv = UIView() cv.clipsToBounds = true cv.translatesAutoresizingMaskIntoConstraints = false return cv }() public lazy var cancelButton: UIButton? = { let cb = UIButton() cb.translatesAutoresizingMaskIntoConstraints = false cb.setTitleColor(.gray, for: .highlighted) return cb }() public lazy var switchCameraButton: UIButton? = { let scb = SwitchCameraButton() scb.translatesAutoresizingMaskIntoConstraints = false return scb }() public lazy var toggleTorchButton: UIButton? = { let ttb = ToggleTorchButton() ttb.translatesAutoresizingMaskIntoConstraints = false return ttb }() private weak var reader: QRCodeReader? public func setupComponents(showCancelButton: Bool, showSwitchCameraButton: Bool, showTorchButton: Bool, showOverlayView: Bool, reader: QRCodeReader?) { self.reader = reader reader?.lifeCycleDelegate = self addComponents() cancelButton?.isHidden = !showCancelButton switchCameraButton?.isHidden = !showSwitchCameraButton toggleTorchButton?.isHidden = !showTorchButton overlayView?.isHidden = !showOverlayView guard let cb = cancelButton, let scb = switchCameraButton, let ttb = toggleTorchButton, let ov = overlayView else { return } let views = ["cv": cameraView, "ov": ov, "cb": cb, "scb": scb, "ttb": ttb] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[cv]|", options: [], metrics: nil, views: views)) if showCancelButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv][cb(40)]|", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[cb]-|", options: [], metrics: nil, views: views)) } else { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[cv]|", options: [], metrics: nil, views: views)) } if showSwitchCameraButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[scb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[scb(70)]|", options: [], metrics: nil, views: views)) } if showTorchButton { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[ttb(50)]", options: [], metrics: nil, views: views)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[ttb(70)]", options: [], metrics: nil, views: views)) } for attribute in Array<NSLayoutAttribute>([.left, .top, .right, .bottom]) { addConstraint(NSLayoutConstraint(item: ov, attribute: attribute, relatedBy: .equal, toItem: cameraView, attribute: attribute, multiplier: 1, constant: 0)) } } public override func layoutSubviews() { super.layoutSubviews() reader?.previewLayer.frame = bounds } // MARK: - Scan Result Indication func startTimerForBorderReset() { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) { if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .white } } } func addRedBorder() { self.startTimerForBorderReset() if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .red } } func addGreenBorder() { self.startTimerForBorderReset() if let ovl = self.overlayView as? ReaderOverlayView { ovl.overlayColor = .green } } @objc public func setNeedsUpdateOrientation() { setNeedsDisplay() overlayView?.setNeedsDisplay() if let connection = reader?.previewLayer.connection, connection.isVideoOrientationSupported { let application = UIApplication.shared let orientation = UIDevice.current.orientation let supportedInterfaceOrientations = application.supportedInterfaceOrientations(for: application.keyWindow) connection.videoOrientation = QRCodeReader.videoOrientation(deviceOrientation: orientation, withSupportedOrientations: supportedInterfaceOrientations, fallbackOrientation: connection.videoOrientation) } } // MARK: - Convenience Methods private func addComponents() { NotificationCenter.default.addObserver(self, selector: #selector(self.setNeedsUpdateOrientation), name: .UIDeviceOrientationDidChange, object: nil) addSubview(cameraView) if let ov = overlayView { addSubview(ov) } if let scb = switchCameraButton { addSubview(scb) } if let ttb = toggleTorchButton { addSubview(ttb) } if let cb = cancelButton { addSubview(cb) } if let reader = reader { cameraView.layer.insertSublayer(reader.previewLayer, at: 0) setNeedsUpdateOrientation() } } } extension QRCodeReaderView: QRCodeReaderLifeCycleDelegate { func readerDidStartScanning() { setNeedsUpdateOrientation() } func readerDidStopScanning() {} }
4ac81615ed93d2703bc1a8045c716033
32.065327
206
0.700152
false
false
false
false