hexsha
stringlengths
40
40
size
int64
3
1.03M
content
stringlengths
3
1.03M
avg_line_length
float64
1.33
100
max_line_length
int64
2
1k
alphanum_fraction
float64
0.25
0.99
f49f339b1309ee69fb6fe9ea656fbf6e614d2c5c
2,169
// // AppDelegate.swift // FTVLIVE // // Created by jianhao on 2016/9/17. // Copyright © 2016年 cocoaswifty. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.148936
285
0.755648
239b7acac37891695abd626aacaf917912d43d15
1,194
// // WordCollectionView.swift // PicTalkPreSchool // // Created by Pak on 03/09/16. // Copyright © 2016 pictalk.se. All rights reserved. // import UIKit import AVFoundation class WordCollectionView: PicTalkCollectionView { var messageView:MessageColelctionView! override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SubCell", for: indexPath) as! WordCollectionViewCell // Configure the cell cell.text.text = textInSelectedLang(dataItems[(indexPath as NSIndexPath).item]) cell.imageView.image = dataItems[(indexPath as NSIndexPath).item].pic return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { //print("a word is selected") let selectedItem = dataItems[(indexPath as NSIndexPath).item] messageView.addItem(selectedItem) messageView.reloadData() utter(selectedItem: selectedItem) } }
26.533333
130
0.673367
5b5524c9a5d7baea2441b79d8f44398f164a50ef
754
// // CameraGlobals.swift // ALCameraViewController // // Created by Alex Littlejohn on 2016/02/16. // Copyright © 2016 zero. All rights reserved. // import UIKit import AVFoundation internal let itemSpacing: CGFloat = 1 internal let columns: CGFloat = 4 internal let thumbnailDimension = (UIScreen.main.bounds.width - ((columns * itemSpacing) - itemSpacing))/columns internal let scale = UIScreen.main.scale public class CameraGlobals { public static let shared = CameraGlobals() public var bundle = Bundle.module public var stringsTable = "CameraView" public var photoLibraryThumbnailSize = CGSize(width: thumbnailDimension, height: thumbnailDimension) public var defaultCameraPosition = AVCaptureDevice.Position.back }
30.16
112
0.759947
4ba3b1fc8d345f79bfeac5e5f19b29d4df9b661f
6,933
import ClockKit extension UIImage { static func make(_ size: CGFloat) -> UIImage { let middle = size * 0.5 let center = CGPoint(x: middle, y: middle) let radius = middle - 8 UIGraphicsBeginImageContext(.init(width: size, height: size)) let c = UIGraphicsGetCurrentContext()! c.addArc(center: center, radius: radius + 1, startAngle: 0, endAngle: .pi * 2, clockwise: false) c.setFillColor(UIColor.black.cgColor) c.setStrokeColor(UIColor(named: "shade")!.cgColor) c.setLineWidth(1) c.setShadow(offset: .zero, blur: radius / 2, color: UIColor(named: "haze")!.cgColor) c.drawPath(using: .fillStroke) switch app.phase { case .waxingCrescent: c.addPath(waxingCrescent(center, radius)) case .firstQuarter: c.addPath(firstQuarter(center, radius)) case .waxingGibbous: c.addPath(waxingGibbous(center, radius)) case .full: c.addPath(full(center, radius)) case .waningGibbous: c.addPath(waningGibbous(center, radius)) case .lastQuarter: c.addPath(lastQuarter(center, radius)) case .waningCrescent: c.addPath(waningCrescent(center, radius)) default: break } c.setFillColor(UIColor(named: "haze")!.cgColor) c.drawPath(using: .fill) c.addPath(craters(middle, radius)) c.setFillColor(.init(srgbRed: 0, green: 0, blue: 0, alpha: 0.2)) c.drawPath(using: .fill) let image = UIImage(cgImage: c.makeImage()!) UIGraphicsEndImageContext() return image } private static func waxingCrescent(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / 2, endAngle: .pi / -2, clockwise: true) path.addLine(to: CGPoint(x: center.x, y: center.y - radius)) path.addCurve(to: CGPoint(x: center.x, y: center.y + radius), control1: CGPoint(x: center.x + (((app.fraction - 0.5) / -0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / 0.5) * radius)), control2: CGPoint(x: center.x + (((app.fraction - 0.5) / -0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / -0.5) * radius))) return path } private static func firstQuarter(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / 2, endAngle: .pi / -2, clockwise: true) return path } private static func waxingGibbous(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / 2, endAngle: .pi / -2, clockwise: true) path.addLine(to: CGPoint(x: center.x, y: center.y - radius)) path.addCurve(to: CGPoint(x: center.x, y: center.y + radius), control1: CGPoint(x: center.x + (((app.fraction - 0.5) / -0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / -0.5) * radius)), control2: CGPoint(x: center.x + (((app.fraction - 0.5) / -0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / 0.5) * radius))) return path } private static func full(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: false) return path } private static func waningGibbous(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / -2, endAngle: .pi / 2, clockwise: true) path.addLine(to: CGPoint(x: center.x, y: center.y + radius)) path.addCurve(to: CGPoint(x: center.x, y: center.y - radius), control1: CGPoint(x: center.x + (((app.fraction - 0.5) / 0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / 0.5) * radius)), control2: CGPoint(x: center.x + (((app.fraction - 0.5) / 0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / -0.5) * radius))) return path } private static func lastQuarter(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / -2, endAngle: .pi / 2, clockwise: true) return path } private static func waningCrescent(_ center: CGPoint, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addArc(center: center, radius: radius, startAngle: .pi / -2, endAngle: .pi / 2, clockwise: true) path.addLine(to: CGPoint(x: center.x, y: center.y + radius)) path.addCurve(to: CGPoint(x: center.x, y: center.y - radius), control1: CGPoint(x: center.x + (((app.fraction - 0.5) / 0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / -0.5) * radius)), control2: CGPoint(x: center.x + (((app.fraction - 0.5) / 0.5) * (radius * 1.35)), y: center.y + (((app.fraction - 0.5) / 0.5) * radius))) return path } private static func craters(_ middle: CGFloat, _ radius: CGFloat) -> CGPath { let path = CGMutablePath() path.addPath({ $0.addArc(center: CGPoint(x: middle + (radius / -3), y: middle + (radius / -3.5)), radius: radius / 2.2, startAngle: 0, endAngle: .pi * -2, clockwise: true) return $0 } (CGMutablePath())) path.addPath({ $0.addArc(center: CGPoint(x: middle + (radius / -3), y: middle + (radius / 2.25)), radius: radius / 4, startAngle: 0, endAngle: .pi * -2, clockwise: true) return $0 } (CGMutablePath())) path.addPath({ $0.addArc(center: CGPoint(x: middle + (radius / 2), y: middle + (radius / 3.5)), radius: radius / 4, startAngle: 0, endAngle: .pi * -2, clockwise: true) return $0 } (CGMutablePath())) path.addPath({ $0.addArc(center: CGPoint(x: middle + (radius / 6), y: middle + (radius / 1.5)), radius: radius / 5, startAngle: 0, endAngle: .pi * -2, clockwise: true) return $0 } (CGMutablePath())) path.addPath({ $0.addArc(center: CGPoint(x: middle + (radius / 4), y: middle + (radius / -1.5)), radius: radius / 6, startAngle: 0, endAngle: .pi * -2, clockwise: true) return $0 } (CGMutablePath())) return path } }
52.522727
168
0.552286
488bebfce0a6c0af4c6edb6ca7d3f3c71211c2f1
911
// // ColdKeySwiftTests.swift // ColdKeySwiftTests // // Created by Huang Yu on 7/29/15. // Copyright (c) 2015 BitGo, Inc. All rights reserved. // import UIKit import XCTest class ColdKeySwiftTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.621622
111
0.616905
6a94214f898cbb952ed5ff0fd05dbe092b49033f
2,480
// // AppHorizontalController.swift // AStore // // Created by SANGBONG MOON on 22/04/2019. // Copyright © 2019 Scott Moon. All rights reserved. // import UIKit import SDWebImage class AppsHorizontalController: HorizontalSnappingController { private let cellId = "cellId" private let topBottomPadding: CGFloat = 12 private let lineSpacing: CGFloat = 10 var didSelectHandler: ((FeedResult) -> Void)? var appGroup: AppGroup? override func viewDidLoad() { super.viewDidLoad() collectionView.backgroundColor = .white collectionView.register(AppRowCell.self, forCellWithReuseIdentifier: cellId) collectionView.contentInset = .init(top: 0, left: 16, bottom: 0, right: 16) } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return appGroup?.feed.results.count ?? 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) guard let appRowCell = cell as? AppRowCell, let app = appGroup?.feed.results[indexPath.item] else { return cell } appRowCell.nameLabel.text = app.name appRowCell.companyLabel.text = app.artistName appRowCell.imageView.sd_setImage(with: URL(string: app.artworkUrl100)) return appRowCell } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let app = appGroup?.feed.results[indexPath.item] { didSelectHandler?(app) } } } extension AppsHorizontalController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let height = (view.frame.height - 2 * topBottomPadding - 2 * lineSpacing) / 3 return .init(width: view.frame.width - 48, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return lineSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return .init(top: topBottomPadding, left: 0, bottom: topBottomPadding, right: 0) } }
33.972603
168
0.752419
0ab6c309b002187b811ec5dd596db7bebc40669d
896
// // DelicacyTests.swift // DelicacyTests // // Created by Youwei Teng on 9/5/15. // Copyright (c) 2015 Dcard. All rights reserved. // import UIKit import XCTest class DelicacyTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
24.216216
111
0.612723
3310d394ab98c4f042c807a1148d721f23271a55
204
// // WOWDropMenuColumn.swift // Wow // // import UIKit class WOWDropMenuColumn: UIView { @IBOutlet weak var titleButton: UIButton! @IBOutlet weak var arrowImageView: UIImageView! }
13.6
51
0.676471
5628abf10b590c5d3274cf35c6603528ca22f882
1,114
/// Copyright (c) 2012-2016 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. /// /// - Sam Harwell public final class PrecedencePredicateTransition: AbstractPredicateTransition, CustomStringConvertible { public final var precedence: Int public init(_ target: ATNState, _ precedence: Int) { self.precedence = precedence super.init(target) } override public func getSerializationType() -> Int { return Transition.PRECEDENCE } override public func isEpsilon() -> Bool { return true } override public func matches(_ symbol: Int, _ minVocabSymbol: Int, _ maxVocabSymbol: Int) -> Bool { return false } public func getPredicate() -> SemanticContext.PrecedencePredicate { return SemanticContext.PrecedencePredicate(precedence) } public var description: String { return "\(precedence) >= _p" } public func toString() -> String { return description } }
23.702128
104
0.663375
9b5daa988aea920fbe299ccfd96a6435a0fad7fd
5,549
//#-hidden-code import UIKit //#-end-hidden-code /*: Notice: Run this playground in your iPad in **landscape** mode with your device **heading to the left** and switch **on** the **orientation lock** of your device. **Switch off** the **mute** so you can hear the sound effect. # BouncingBall A small game controlled by the position of the device. * Start the game by clicking 'Run My Code'. * Change the preference by editing the variables below. * Tip: Many famous games like Asphalt are also based on the accelerometer. */ //#-hidden-code import UIKit import CoreMotion import PlaygroundSupport import AudioToolbox class BouncingBall: UIViewController,UIAccelerometerDelegate { var ball = UIImageView(image:#imageLiteral(resourceName: "ball.png")) //#-end-hidden-code //The percentage of the speed of the ball left after bouncing let bouncingSpeed:Double = /*#-editable-code */0.6/*#-end-editable-code*/ //Update the speed of the ball according to the acceleration how many times per second let interval:Double = /*#-editable-code */60/*#-end-editable-code*/ //#-hidden-code var motionManager = CMMotionManager() var speed = Speed(x:0,y:0) var noticeSound = SystemSoundID() var collideY:Bool = false var collideX:Bool = false struct Speed { var x:UIAccelerationValue var y:UIAccelerationValue } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white title = "BouncingBall" if(self.orientationCheck()){ self.noticeSound = self.returnSoundDetail() self.startGame() } } //Start the game! func startGame() { ball.frame = CGRect(x: 0, y: 0, width: 30, height: 30) ball.center = self.view.center self.view.addSubview(ball) self.view.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "background.jpg")) motionManager.accelerometerUpdateInterval = 1/self.interval if(motionManager.isAccelerometerAvailable) { let queue = OperationQueue.current motionManager.startAccelerometerUpdates(to: queue!, withHandler: { (accelerometerData, error) in self.speed.y += accelerometerData!.acceleration.x self.speed.x -= accelerometerData!.acceleration.y var x = self.ball.center.x + CGFloat(self.speed.x) var y = self.ball.center.y - CGFloat(self.speed.y) if (y < 60) { //Hit the roof if(!self.collideY){ self.soundEffect() self.collideY = true } y = 60 self.speed.y *= -self.bouncingSpeed } else if (y > (self.view.bounds.size.height - 15)){ //Hit the floor if(!self.collideY){ self.soundEffect() self.collideY = true } y = self.view.bounds.size.height - 15 self.speed.y *= -self.bouncingSpeed } else{ self.collideY = false } if (x < 15) { //Hit the left wall if(!self.collideX){ self.soundEffect() self.collideX = true } x = 15 self.speed.x *= -self.bouncingSpeed } else if (x > (self.view.bounds.size.width - 15)) { //Hit the right wall if(!self.collideX){ self.soundEffect() self.collideX = true } x = self.view.bounds.size.width - 15 self.speed.x *= -self.bouncingSpeed } else { self.collideX = false } self.ball.center=CGPoint(x:x, y:y) } ) } } //Check the device's orientation func orientationCheck() -> Bool { if(self.view.bounds.width < 1024){ let noticeLabel = UILabel(frame: CGRect(x: 35,y :20, width: 700, height:100)) noticeLabel.numberOfLines = 0 noticeLabel.text = "Please switch to lanscape mode with the device heading to the left and try again." noticeLabel.textColor = UIColor.red noticeLabel.lineBreakMode = NSLineBreakMode.byWordWrapping self.view.addSubview(noticeLabel) return false } return true } //Sound Effect! func soundEffect(){ AudioServicesPlaySystemSound(self.noticeSound) //AudioServicesPlaySystemSound(kSystemSoundID_Vibrate) //iPad does not have any vibrations... } //Return the sound id func returnSoundDetail() -> SystemSoundID { var soundID:SystemSoundID = 0 let soundURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), "bounce" as CFString, "m4a" as CFString, nil) AudioServicesCreateSystemSoundID(soundURL!, &soundID) return soundID } } func startMyPlayground(_ view:UIViewController){ PlaygroundPage.current.liveView = UINavigationController(rootViewController: view) } //#-end-hidden-code startMyPlayground(BouncingBall())
36.993333
225
0.561723
dd2644e183979030df0d6c4f79e12ca0aea86825
3,631
// // WebCheckoutSession.swift // UnityBuySDK // // Created by Shopify. // Copyright © 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import WebKit import SafariServices private var activeWebPaySession: WebCheckoutSession? protocol WebCheckoutSessionDelegate { func webCheckoutSessionPresentsController(controller: UIViewController) } @objc public class WebCheckoutSession: NSObject { @objc public static func createSession(unityDelegateObjectName: String, url: String) -> WebCheckoutSession { let session = WebCheckoutSession(unityDelegateObjectName: unityDelegateObjectName, checkoutURL: url) activeWebPaySession = session return session } private let checkoutURL: String fileprivate let unityDelegateObjectName: String init(unityDelegateObjectName: String, checkoutURL: String) { self.unityDelegateObjectName = unityDelegateObjectName self.checkoutURL = checkoutURL super.init() } @objc public func startCheckout() -> Bool { guard let url = URL(string: checkoutURL) else { return false } HTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.always let webViewController = SFSafariViewController(url: url) webViewController.delegate = self let navController = UnityModalNavigationController(rootViewController: webViewController) navController.isNavigationBarHidden = true UnityGetGLViewController().present(navController, animated: true, completion: nil) return true } } extension WebCheckoutSession: SFSafariViewControllerDelegate { public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { let message = UnityMessage(content: "dismissed", object: unityDelegateObjectName, method: "OnNativeMessage") MessageCenter.send(message) } } //// Helper subclass that matches the Unity controller's configuration. private class UnityModalNavigationController: UINavigationController { override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UnityGetGLViewController().supportedInterfaceOrientations } override var preferredStatusBarStyle: UIStatusBarStyle { return UnityGetGLViewController().preferredStatusBarStyle } override var prefersStatusBarHidden: Bool { return UnityGetGLViewController().prefersStatusBarHidden } }
38.62766
116
0.736712
23db402dd3d826e8d867b076e9d0aa08bdfe0b35
1,415
// // AppDelegate.swift // PullRefresh // // Created by Shuai Hao on 2019/9/23. // Copyright © 2019 Shuai Hao. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.236842
179
0.746996
fff03a80598044257fe1624fa09c67f9d0bf2475
409
// swift-tools-version:5.0 import PackageDescription let package = Package( name: "JelloSwift", products: [ .library(name: "JelloSwift", targets: ["JelloSwift"]) ], targets: [ .target(name: "JelloSwift", dependencies: [], path: "Sources"), .testTarget(name: "JelloSwiftTests", dependencies: ["JelloSwift"]) ] )
22.722222
61
0.540342
5d04918ceb4cf2296f081c98c67ac94b1669c751
458
// // ViewController.swift // metal.one // // Created by Andrew Finke on 3/12/20. // Copyright © 2020 Andrew Finke. All rights reserved. // import Cocoa class ViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
16.357143
58
0.620087
50a51ef827aeaf485a22896e3baeead7b43031eb
2,181
// // AppDelegate.swift // SABlurImageViewSample // // Created by 鈴木大貴 on 2015/03/27. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> 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:. } }
47.413043
285
0.753783
116d9d82df3649c70dbc90e203bf6f319172d342
14,014
// // PXLayout.swift // TestAutolayout // // Created by Demian Tejo on 10/18/17. // Copyright © 2017 Demian Tejo. All rights reserved. // import UIKit class PXLayout: NSObject { //Margins static let ZERO_MARGIN: CGFloat = 0.0 static let XXXS_MARGIN: CGFloat = 4.0 static let XXS_MARGIN: CGFloat = 8.0 static let XS_MARGIN: CGFloat = 12.0 static let S_MARGIN: CGFloat = 16.0 static let SM_MARGIN: CGFloat = 20.0 static let M_MARGIN: CGFloat = 24.0 static let L_MARGIN: CGFloat = 32.0 static let XL_MARGIN: CGFloat = 40.0 static let XXL_MARGIN: CGFloat = 48.0 static let XXXL_MARGIN: CGFloat = 50.0 //Font Sizes static let XXXS_FONT: CGFloat = 12.0 static let XXS_FONT: CGFloat = 14.0 static let XS_FONT: CGFloat = 16.0 static let S_FONT: CGFloat = 18.0 static let M_FONT: CGFloat = 20.0 static let L_FONT: CGFloat = 22.0 static let XL_FONT: CGFloat = 24.0 static let XXL_FONT: CGFloat = 26.0 static let XXXL_FONT: CGFloat = 26.0 static let DEFAULT_CONTRAINT_ACTIVE = true static let NAV_BAR_HEIGHT: CGFloat = 44 static func checkContraintActivation(_ constraint: NSLayoutConstraint, withDefault isActive: Bool = DEFAULT_CONTRAINT_ACTIVE) -> NSLayoutConstraint { constraint.isActive = isActive return constraint } //Altura fija @discardableResult static func setHeight(owner: UIView, height: CGFloat, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { owner.translatesAutoresizingMaskIntoConstraints = false return checkContraintActivation(NSLayoutConstraint(item: owner, attribute: .height, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)) } //Ancho fijo @discardableResult static func setWidth(owner: UIView, width: CGFloat, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { return checkContraintActivation(NSLayoutConstraint(item: owner, attribute: .width, relatedBy: relation, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)) } // Pin Left @discardableResult static func pinLeft(view: UIView, to otherView: UIView? = nil, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: .leading, relatedBy: relation, toItem: superView, attribute: .leading, multiplier: 1, constant: margin)) } //Pin Right @discardableResult static func pinRight(view: UIView, to otherView: UIView? = nil, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: .trailing, relatedBy: relation, toItem: superView, attribute: .trailing, multiplier: 1, constant: -margin)) } //Pin Top @discardableResult static func pinTop(view: UIView, to otherView: UIView? = nil, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: .top, relatedBy: relation, toItem: superView, attribute: .top, multiplier: 1, constant: margin)) } //Pin Bottom @discardableResult static func pinBottom(view: UIView, to otherView: UIView? = nil, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: relation, toItem: superView, attribute: .bottom, multiplier: 1, constant: -margin)) } //Pin All Edges to Superview @discardableResult static func pinAllEdges(view: UIView, to otherView: UIView? = nil, withMargin margin: CGFloat = 0 ) -> [NSLayoutConstraint] { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } let topConstraint = checkContraintActivation(NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal, toItem: superView, attribute: .top, multiplier: 1, constant: margin)) let bottomConstraint = checkContraintActivation(NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, toItem: superView, attribute: .bottom, multiplier: 1, constant: -margin)) let leftConstraint = checkContraintActivation(NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal, toItem: superView, attribute: .left, multiplier: 1, constant: margin)) let rightConstraint = checkContraintActivation(NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal, toItem: superView, attribute: .right, multiplier: 1, constant: -margin)) return [topConstraint, bottomConstraint, leftConstraint, rightConstraint] } //Pin parent last subview to Bottom @discardableResult static func pinLastSubviewToBottom(view: UIView, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint? { guard let lastView = view.subviews.last else { return nil } return pinBottom(view: lastView, to: view, withMargin: margin, relation: relation) } //Pin parent first subview to Top @discardableResult static func pinFirstSubviewToTop(view: UIView, withMargin margin: CGFloat = 0 ) -> NSLayoutConstraint? { guard let firstView = view.subviews.first else { return nil } return pinTop(view: firstView, to: view, withMargin: margin) } //Vista 1 abajo de vista 2 @discardableResult static func put(view: UIView, onBottomOf view2: UIView, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = NSLayoutConstraint.Relation.equal) -> NSLayoutConstraint { return checkContraintActivation(NSLayoutConstraint( item: view, attribute: .top, relatedBy: relation, toItem: view2, attribute: .bottom, multiplier: 1.0, constant: margin )) } //Vista 1 abajo de la ultima vista @discardableResult static func put(view: UIView, onBottomOfLastViewOf view2: UIView, withMargin margin: CGFloat = 0) -> NSLayoutConstraint? { if !view2.subviews.contains(view) { return nil } for actualView in view2.subviews.reversed() where actualView != view { return put(view: view, onBottomOf: actualView, withMargin: margin) } return nil } //Vista 1 arriba de vista 2 @discardableResult static func put(view: UIView, aboveOf view2: UIView, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = NSLayoutConstraint.Relation.equal) -> NSLayoutConstraint { return checkContraintActivation(NSLayoutConstraint( item: view, attribute: .bottom, relatedBy: relation, toItem: view2, attribute: .top, multiplier: 1.0, constant: margin )) } //Vista 1 a la izquierda de vista 2 @discardableResult static func put(view: UIView, leftOf view2: UIView, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { return checkContraintActivation(NSLayoutConstraint( item: view, attribute: .right, relatedBy: relation, toItem: view2, attribute: .left, multiplier: 1.0, constant: -margin )) } //Vista 1 a la derecha de vista 2 @discardableResult static func put(view: UIView, rightOf view2: UIView, withMargin margin: CGFloat = 0, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { return checkContraintActivation(NSLayoutConstraint( item: view, attribute: .left, relatedBy: relation, toItem: view2, attribute: .right, multiplier: 1.0, constant: margin )) } //Centrado horizontal @discardableResult static func centerHorizontally(view: UIView, to container: UIView? = nil) -> NSLayoutConstraint { var superView: UIView! if container == nil { superView = view.superview } else { superView = container } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: .equal, toItem: superView, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0)) } //Centrado Vertical @discardableResult static func centerVertically(view: UIView, to container: UIView? = nil, withMargin margin: CGFloat = 0) -> NSLayoutConstraint { var superView: UIView! if container == nil { superView = view.superview } else { superView = container } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: .equal, toItem: superView, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1.0, constant: margin)) } @discardableResult static func matchWidth(ofView view: UIView, toView otherView: UIView? = nil, withPercentage percent: CGFloat = 100, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: NSLayoutConstraint.Attribute.width, relatedBy: relation, toItem: superView, attribute: NSLayoutConstraint.Attribute.width, multiplier: percent / 100, constant: 0)) } @discardableResult static func matchHeight(ofView view: UIView, toView otherView: UIView? = nil, withPercentage percent: CGFloat = 100, relation: NSLayoutConstraint.Relation = .equal) -> NSLayoutConstraint { var superView: UIView! if otherView == nil { superView = view.superview } else { superView = otherView } return checkContraintActivation(NSLayoutConstraint(item: view, attribute: NSLayoutConstraint.Attribute.height, relatedBy: relation, toItem: superView, attribute: NSLayoutConstraint.Attribute.height, multiplier: percent / 100, constant: 0)) } static func getScreenWidth(applyingMarginFactor percent: CGFloat = 100) -> CGFloat { let screenSize = UIScreen.main.bounds let availableWidth = screenSize.width * percent / 100 return availableWidth } static func getAvailabelScreenHeight(in viewController: UIViewController, applyingMarginFactor percent: CGFloat = 100) -> CGFloat { let screenHeight = getScreenHeight() let topBarHeight = UIApplication.shared.statusBarFrame.size.height + (viewController.navigationController?.navigationBar.frame.height ?? 0.0) let availableScreenHeight = screenHeight - topBarHeight return availableScreenHeight * percent / 100 } static func getScreenHeight(applyingMarginFactor percent: CGFloat = 100) -> CGFloat { let screenSize = UIScreen.main.bounds let availableHeight = screenSize.height * percent / 100 return availableHeight } } extension PXLayout { static func getSafeAreaBottomInset() -> CGFloat { // iPhoneX or any device with safe area inset > 0 var bottomDeltaMargin: CGFloat = 0 if #available(iOS 11.0, *) { let window = UIApplication.shared.keyWindow let bottomSafeAreaInset = window?.safeAreaInsets.bottom if let bottomDeltaInset = bottomSafeAreaInset, bottomDeltaInset > 0 { bottomDeltaMargin = bottomDeltaInset } } return bottomDeltaMargin } static func getSafeAreaTopInset(topDeltaMargin: CGFloat = 0) -> CGFloat { // iPhoneX or any device with safe area inset > 0 var topDeltaMargin: CGFloat = topDeltaMargin if #available(iOS 11.0, *) { let window = UIApplication.shared.keyWindow let topSafeAreaInset = window?.safeAreaInsets.top if let topDeltaInset = topSafeAreaInset, topDeltaInset > 0 { topDeltaMargin = topDeltaInset } } return topDeltaMargin } static func getStatusBarHeight() -> CGFloat { let defaultStatusBarHeight: CGFloat = 20 return getSafeAreaTopInset(topDeltaMargin: defaultStatusBarHeight) } } class ClosureSleeve { let closure: () -> Void init (_ closure: @escaping () -> Void) { self.closure = closure } @objc func invoke () { closure() } } extension UIControl { func add (for controlEvents: UIControl.Event, _ closure: @escaping () -> Void) { let sleeve = ClosureSleeve(closure) addTarget(sleeve, action: #selector(ClosureSleeve.invoke), for: controlEvents) objc_setAssociatedObject(self, String(format: "[%d]", arc4random()), sleeve, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } }
42.98773
247
0.670615
0e7bb0cbcf18b2e6788cfc7dc22674e6ffea07d1
471
// // PacketTunnelProvider.swift // VPNSDK Demo Hydra Provider // // Created by Dan Vasilev on 26.01.2021. // import VPNTunnelProviderSDK class PacketTunnelProvider: NSObject, NetworkExtensionDelegate { private let categorizationProcessor = CategorizationProcessor.default() var fireshieldManager: FireshieldManager? func vpnDidHandleCategorization(_ categorization: VPNCategorization) { categorizationProcessor.process(categorization) } }
24.789474
75
0.77707
f9e54b3028d56bd8ca07448f5d4ec5c38985258c
2,055
import Combine import SwiftUI import XCTest @testable import Hooks final class UsePublisherSubscribeTests: XCTestCase { func testUpdate() { let subject = PassthroughSubject<Void, URLError>() let tester = HookTester(0) { value in usePublisherSubscribe { subject.map { value } } } XCTAssertEqual(tester.value.phase, .pending) tester.value.subscribe() XCTAssertEqual(tester.value.phase, .running) subject.send() XCTAssertEqual(tester.value.phase.value, 0) tester.update(with: 1) tester.value.subscribe() subject.send() XCTAssertEqual(tester.value.phase.value, 1) tester.update(with: 2) tester.value.subscribe() subject.send() XCTAssertEqual(tester.value.phase.value, 2) } func testUpdateFailure() { let subject = PassthroughSubject<Void, URLError>() let tester = HookTester(0) { value in usePublisherSubscribe { subject.map { value } } } XCTAssertEqual(tester.value.phase, .pending) tester.value.subscribe() XCTAssertEqual(tester.value.phase, .running) subject.send(completion: .failure(URLError(.badURL))) XCTAssertEqual(tester.value.phase.error, URLError(.badURL)) } func testDispose() { var isSubscribed = false let subject = PassthroughSubject<Int, Never>() let tester = HookTester { usePublisherSubscribe { subject.handleEvents(receiveSubscription: { _ in isSubscribed = true }) } } XCTAssertEqual(tester.value.phase, .pending) tester.dispose() subject.send(1) XCTAssertEqual(tester.value.phase, .pending) XCTAssertFalse(isSubscribed) tester.value.subscribe() subject.send(2) XCTAssertEqual(tester.value.phase, .pending) XCTAssertFalse(isSubscribed) } }
24.464286
67
0.596594
61b3979fd6fcc4d5aa1b1575fa9165b59a834c04
238
// // BluetoothInfoDelegate.swift // BluetoothGateway // // Created by OE Hi Loki on 2018/01/03. // Copyright © 2018 Yairi Lab. All rights reserved. // import Foundation protocol BluetoothInfoDelegate { func show(_ s: String) }
17
52
0.705882
16d4202e427b91a12e35043fdb0a0717fc4b7fd4
3,040
// // AddColor.swift // HyperCardCommon // // Created by Pierre Lorenzi on 05/06/2018. // Copyright © 2018 Pierre Lorenzi. All rights reserved. // /// All the AddColor colors declared on a card or on a background public struct LayerColor { /// The color declarations to apply public var elements: [AddColorElement] } /// An RGB color public struct AddColor { public var red: Double public var green: Double public var blue: Double } /// A color declaration in a card or background. /// <p> /// The elements are displayed in the order of the resource, not the order of the HyperCard object public enum AddColorElement { case button(AddColorButton) case field(AddColorField) case rectangle(AddColorRectangle) case pictureResource(AddColorPictureResource) case pictureFile(AddColorPictureFile) } /// A declaration to colorize a button public struct AddColorButton { /// The ID of the button public var buttonIdentifier: Int /// Thickness of the 3D-like border public var bevel: Int /// The color to use public var color: AddColor /// If unset, this declaration is ignored public var enabled: Bool } /// A declaration to colorize a text field public struct AddColorField { /// The ID of the field public var fieldIdentifier: Int /// Thickness of the 3D-like border public var bevel: Int /// The color to use public var color: AddColor /// If unset, this declaration is ignored public var enabled: Bool } /// A declaration to colorize a certain rectangle public struct AddColorRectangle { /// Position of the rectangle public var rectangle: Rectangle /// Thickness of the 3D-like border public var bevel: Int /// The color to use public var color: AddColor /// If unset, this declaration is ignored public var enabled: Bool } /// A declaration to draw a colored picture out of a resource public struct AddColorPictureResource { /// Rectangle where to draw the picture public var rectangle: Rectangle /// Transparent means that the white pixels of the image are drawn transparent public var transparent: Bool /// The name of the PICT resource containing the picture public var resourceName: HString /// If unset, this declaration is ignored public var enabled: Bool } /// A declaration to draw a colored picture out of a file public struct AddColorPictureFile { /// Rectangle where to draw the picture public var rectangle: Rectangle /// Transparent means that the white pixels of the image are drawn transparent public var transparent: Bool /// The file name is just the name of the file, not the path. The file is supposed to be in the same folder /// as the HyperCard application, the Home stack or the current stack public var fileName: HString /// If unset, this declaration is ignored public var enabled: Bool }
26.206897
111
0.687171
b91397258c8799a5a9301e50533d432ccccfffd0
1,509
// // IssueReviewViewCommentsCell.swift // Freetime // // Created by Ryan Nystrom on 11/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit import SnapKit protocol IssueReviewViewCommentsCellDelegate: class { func didTapViewComments(cell: IssueReviewViewCommentsCell) } final class IssueReviewViewCommentsCell: IssueCommentBaseCell, ListBindable { weak var delegate: IssueReviewViewCommentsCellDelegate? private let button = UIButton() override init(frame: CGRect) { super.init(frame: frame) button.setTitle(NSLocalizedString("View Comments", comment: ""), for: .normal) button.setTitleColor(Styles.Colors.Blue.medium.color, for: .normal) button.addTarget(self, action: #selector(IssueReviewViewCommentsCell.onButton), for: .touchUpInside) button.titleLabel?.font = Styles.Text.body.preferredFont contentView.addSubview(button) button.snp.makeConstraints { make in make.left.equalToSuperview() make.centerY.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() layoutContentViewForSafeAreaInsets() } // MARK: Private API @objc func onButton() { delegate?.didTapViewComments(cell: self) } // MARK: ListBindable func bindViewModel(_ viewModel: Any) {} }
26.473684
108
0.693837
7ad01aae7c74dea4f8bab13d1bfdafb868e07130
8,720
// // TBAnalytics.swift // Pods // // Created by Timothy Barnard on 08/02/2017. // // import Foundation public enum SendType: String { case OpenApp = "OpenApp" case CloseApp = "CloseApp" case ViewOpen = "ViewOpen" case ViewClose = "ViewClose" case ButtonClick = "ButtonClick" case Generic = "Generic" } public class TBAnalytics { class private var dateFormatter : DateFormatter { let dateFormatter = DateFormatter() dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone! dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss" return dateFormatter } class private var nowDate: String { return self.dateFormatter.string(from: NSDate() as Date) } //MARK: - Internal methods class private func getTags() -> [String:AnyObject] { var tags = [String:AnyObject]() if tags["Build version"] == nil { if let buildVersion: AnyObject = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject? { tags["Build version"] = buildVersion as AnyObject? tags["Build name"] = RCFileManager.readPlistString(value: "CFBundleDisplayName") as AnyObject? } } #if os(iOS) || os(tvOS) if (tags["OS version"] == nil) { tags["OS version"] = UIDevice.current.systemVersion as AnyObject? } if (tags["Device model"] == nil) { tags["Device model"] = UIDevice.current.model as AnyObject? } #endif return tags } struct TBAnalyitcs: TBJSONSerializable { var timeStamp: String = "" var method: String = "" var className: String = "" var fileName: String = "" var configVersion: String = "" var type: String = "" var tags = [String:AnyObject]() init() {} init(jsonObject: TBJSON) {} } /** SendOpenApp - parameters: - app: Self if running from AppDelegate class */ public class func sendOpenApp(_ app: UIResponder , method: String? = #function , file: String? = #file) { self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: .OpenApp ) } /** SendOpenApp - parameters: - app: Self if running from UIVIew class */ public class func sendOpenApp(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .OpenApp ) } /** SendCloseApp - parameters: - app: Self if running from AppDelegate class */ public class func sendCloseApp(_ app: UIResponder , method: String? = #function , file: String? = #file) { self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: .CloseApp ) } /** SendCloseApp - parameters: - app: Self if running from UIView class */ public class func sendCloseApp(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .CloseApp ) } /** SendButtonClick - parameters: - view: Self if running from UIView class */ public class func sendButtonClick(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ButtonClick ) } /** SendButtonClick - parameters: - view: Self if running from UIViewController class */ public class func sendButtonClick(_ view: UIViewController , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ButtonClick) } /** SendViewOpen - parameters: - view: Self if running from UIView class */ public class func sendViewOpen(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewOpen ) } /** SendViewOpen - parameters: - view: Self if running from UIViewController class */ public class func sendViewOpen(_ view: UIViewController , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewOpen) } /** SendViewClose - parameters: - view: Self if running from UIView class */ public class func sendViewClose(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewClose ) } /** SendViewClose - parameters: - view: Self if running from UIViewController class */ public class func sendViewClose(_ view: UIViewController , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewClose) } /** Send - parameters: - view: Self if running from UIResponder class - type: of tpye SendType */ public class func send(_ app: UIResponder, type: SendType , method: String? = #function , file: String? = #file) { self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: type ) } /** Send - parameters: - view: Self if running from UIView class - type: of tpye SendType */ class func send(_ view: UIView ,type: SendType, method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: type ) } /** Send - parameters: - view: Self if running from UIViewController class - type: of tpye SendType */ class func send(_ view: UIViewController ,type: SendType , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: type ) } /** Send - parameters: - view: Self if running from UIResponder class */ public class func send(_ app: UIResponder , method: String? = #function , file: String? = #file) { self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "" ) } /** Send - parameters: - view: Self if running from UIView class */ public class func send(_ view: UIView , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "" ) } /** Send - parameters: - view: Self if running from UIViewController class */ public class func send(_ view: UIViewController , method: String? = #function , file: String? = #file){ self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "" ) } private class func sendData(_ className: String, file:String, method:String, type: SendType = .Generic ) { let doAnalytics = UserDefaults.standard.value(forKey: "doAnalytics") as? String ?? "0" if doAnalytics == "1" { let version = UserDefaults.standard.value(forKey: "version") as? String var newAnalytics = TBAnalyitcs() newAnalytics.className = className newAnalytics.fileName = file newAnalytics.method = method newAnalytics.timeStamp = self.nowDate newAnalytics.configVersion = version ?? "0.0" newAnalytics.tags = self.getTags() newAnalytics.type = type.rawValue self.sendUserAnalytics(newAnalytics) } } class private func sendUserAnalytics(_ tbAnalyitcs: TBAnalyitcs) { tbAnalyitcs.sendInBackground("") { (completed, data) in DispatchQueue.main.async { if (completed) { print("sent") } else { print("error") } } } } }
33.030303
118
0.571216
8abbe0992d77ca3c323fbeda3e750e6940099d1b
3,198
// // StringExtension.swift // SwiftLinkPreview // // Created by Leonardo Cardoso on 09/06/2016. // Copyright © 2016 leocardz.com. All rights reserved. // import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import UIKit #elseif os(OSX) import Cocoa #endif extension String { // Trim var trim: String { return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } // Remove extra white spaces var extendedTrim: String { let components = self.components(separatedBy: CharacterSet.whitespacesAndNewlines) return components.filter { !$0.isEmpty }.joined(separator: " ").trim } // Decode HTML entities var decoded: String { let encodedData = self.data(using: String.Encoding.utf8)! let attributedOptions: [NSAttributedString.DocumentReadingOptionKey: Any] = [ .documentType: NSAttributedString.DocumentType.html, .characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue) ] do { let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) return attributedString.string } catch _ { return self } } // Strip tags var tagsStripped: String { return self.deleteTagByPattern(Regex.rawTagPattern) } // Delete tab by pattern func deleteTagByPattern(_ pattern: String) -> String { return self.replacingOccurrences(of: pattern, with: "", options: .regularExpression, range: nil) } // Replace func replace(_ search: String, with: String) -> String { let replaced: String = self.replacingOccurrences(of: search, with: with) return replaced.isEmpty ? self : replaced } // Substring func substring(_ start: Int, end: Int) -> String { return self.substring(NSRange(location: start, length: end - start)) } func substring(_ range: NSRange) -> String { var end = range.location + range.length end = end > self.count ? self.count - 1 : end return self.substring(range.location, end: end) } // Check if url is an image func isImage() -> Bool { let possible = ["gif", "jpg", "jpeg", "png", "bmp"] if let url = URL(string: self), possible.contains(url.pathExtension) { return true } return false } func isVideo() -> Bool { let possible = ["mp4", "mov", "mpeg", "avi", "m3u8"] if let url = URL(string: self), possible.contains(url.pathExtension) { return true } return false } // Split into substring of equal length func split(by length: Int) -> [String] { var startIndex = self.startIndex var results = [Substring]() while startIndex < self.endIndex { let endIndex = self.index(startIndex, offsetBy: length, limitedBy: self.endIndex) ?? self.endIndex results.append(self[startIndex..<endIndex]) startIndex = endIndex } return results.map { String($0) } } }
23.343066
129
0.608505
d98270aaecb5187fdf5f998a4db2e161c91bfb20
686
// // HQELookCertificateController.swift // TianYuFly // // Created by 王红庆 on 2017/8/11. // Copyright © 2017年 王红庆. All rights reserved. // import UIKit class HQELookCertificateController: HQBaseViewController { var viewModel: HQEViewModel? } // MARK: - UI extension HQELookCertificateController { override func setupTableView() { super.setupTableView() let newView = HQELookCertificateView() newView.frame = CGRect(x: 0, y: navHeight, width: UIScreen.hq_screenWidth(), height: UIScreen.hq_screenHeight() - navHeight) view.insertSubview(newView, belowSubview: navigationBar) newView.viewModel = viewModel } }
24.5
132
0.690962
f89e93016ee59cd1332c7c96b8eee1c2de887715
155
import Foundation protocol ViewModelOwner { associatedtype ViewModel var viewModel: ViewModel? { get set } var isSelected: Bool { get set } }
19.375
41
0.716129
917bd0cbb078bff598aba4e0f5aae6745b174c80
408
import UIKit import ContentsquareModule @available(iOS 13.0, *) class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { // Handle incoming urls to monitor CS in-app activation if let url = URLContexts.first?.url { Contentsquare.handle(url: url) } } }
27.2
86
0.688725
e6deb4230effa97de1a13d71ce4c9785aedce7a4
1,410
// // AppDelegate.swift // TodoList // // Created by Apollo Zhu on 12/6/19. // Copyright © 2019 UWAppDev. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.105263
179
0.746809
cc8788b6f9156ce2d01fce070c89f83c4d4b6ea6
6,232
// // Hardware.swift // Pods // // Created by zixun on 17/1/20. // // import Foundation open class Hardware: NSObject { //-------------------------------------------------------------------------- // MARK: OPEN PROPERTY //-------------------------------------------------------------------------- /// System uptime, you can get the components from the result open static var uptime: Date { get { /// get the info about the process let processsInfo = ProcessInfo.processInfo /// get the uptime of the system let timeInterval = processsInfo.systemUptime /// create and return the date return Date(timeIntervalSinceNow: -timeInterval) } } /// model of the device, eg: "iPhone", "iPod touch" open static let deviceModel: String = UIDevice.current.model /// name of the device, eg: "My iPhone" open static var deviceName: String = UIDevice.current.name /// system name of the device, eg: "iOS" open static let systemName: String = UIDevice.current.systemName /// system version of the device, eg: "10.0" open static let systemVersion: String = UIDevice.current.systemVersion /// version code of device, eg: "iPhone7,1" open static var deviceVersionCode: String { get { var systemInfo = utsname() uname(&systemInfo) let versionCode: String = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!)! return versionCode } } /// version of device, eg: "iPhone5" open static var deviceVersion: String { get { switch self.deviceVersionCode { /*** iPhone ***/ case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone4" case "iPhone4,1", "iPhone4,2", "iPhone4,3": return "iPhone4S" case "iPhone5,1", "iPhone5,2": return "iPhone5" case "iPhone5,3", "iPhone5,4": return "iPhone5C" case "iPhone6,1", "iPhone6,2": return "iPhone5S" case "iPhone7,2": return "iPhone6" case "iPhone7,1": return "iPhone6Plus" case "iPhone8,1": return "iPhone6S" case "iPhone8,2": return "iPhone6SPlus" case "iPhone8,4": return "iPhoneSE" case "iPhone9,1", "iPhone9,3": return "iPhone7" case "iPhone9,2", "iPhone9,4": return "iPhone7Plus" /*** iPad ***/ case "iPad1,1": return "iPad1" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad3" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad4" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPadAir" case "iPad5,3", "iPad5,4": return "iPadAir2" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPadMini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPadMini2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPadMini3" case "iPad5,1", "iPad5,2": return "iPadMini4" case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return "iPadPro" /*** iPod ***/ case "iPod1,1": return "iPodTouch1Gen" case "iPod2,1": return "iPodTouch2Gen" case "iPod3,1": return "iPodTouch3Gen" case "iPod4,1": return "iPodTouch4Gen" case "iPod5,1": return "iPodTouch5Gen" case "iPod7,1": return "iPodTouch6Gen" /*** Simulator ***/ case "i386", "x86_64": return "Simulator" default: return "Unknown" } } } /// get the screen width (x) open static var screenWidth: CGFloat { get { return UIScreen.main.bounds.size.width } } /// get the screen height (y) open static var screenHeight: CGFloat { get { return UIScreen.main.bounds.size.height } } /// get the brightness of screen open static var screenBrightness: CGFloat { get { return UIScreen.main.brightness } } open static var isMultitaskingSupported: Bool { get { return UIDevice.current.isMultitaskingSupported } } /// is the debugger attached open static var isDebuggerAttached: Bool { get { var info = kinfo_proc() var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()] var size = MemoryLayout.stride(ofValue: info) let junk = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0) assert(junk == 0, "sysctl failed") return (info.kp_proc.p_flag & P_TRACED) != 0 } } /// is the device plugged in open static var isPluggedIn: Bool { get { let preEnable = UIDevice.current.isBatteryMonitoringEnabled UIDevice.current.isBatteryMonitoringEnabled = true let batteryState = UIDevice.current.batteryState UIDevice.current.isBatteryMonitoringEnabled = preEnable return (batteryState == .charging || batteryState == .full) } } /// is the device jailbrokened open static var isJailbroken: Bool { let cydiaURL = "/Applications/Cydia.app" return FileManager.default.fileExists(atPath: cydiaURL) } }
42.394558
181
0.489891
fca63eb45385519e83f63e592ea84de4be08550c
1,330
// // MovieAPIManager.swift // flix // // Created by Sandra Luo on 3/1/18. // Copyright © 2018 Sandra Luo. All rights reserved. // import Foundation class MovieAPIManager { static let baseURL = "https://api.themoviedb.org/3/movie/" static let apiKeyString = "now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed" var session: URLSession init() { session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) } func nowPlayingMovies(completion: @escaping([Movie]?, Error?) -> ()) { let url = URL(string: MovieAPIManager.baseURL + MovieAPIManager.apiKeyString) let request = URLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let task = session.dataTask(with: request) { (data, response, error) in if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movieDictionaries = dataDictionary["results"] as! [[String: Any]] let movies = Movie.movies(dictionaries: movieDictionaries) completion(movies, nil) } else { completion(nil, error) } } task.resume() } }
35
113
0.619549
b9068c312a8267563c5f9431f2157832d3ab2315
2,333
// // SceneDelegate.swift // versi-app // // Created by roosky on 11/5/19. // Copyright © 2019 K W. All rights reserved. // import UIKit class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). guard let _ = (scene as? UIWindowScene) else { return } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
43.203704
147
0.71153
91c2bcd28d336e0507f0a0a02130f5c471012903
1,609
// // CertificatesOverviewRouter.swift // // // © Copyright IBM Deutschland GmbH 2021 // SPDX-License-Identifier: Apache-2.0 // import CovPassCommon import CovPassUI import PromiseKit import Scanner import UIKit class CertificatesOverviewRouter: CertificatesOverviewRouterProtocol, DialogRouterProtocol { // MARK: - Properties let sceneCoordinator: SceneCoordinator // MARK: - Lifecycle init(sceneCoordinator: SceneCoordinator) { self.sceneCoordinator = sceneCoordinator } // MARK: - Methods func showCertificates(_ certificates: [ExtendedCBORWebToken]) -> Promise<CertificateDetailSceneResult> { sceneCoordinator.push( CertificateDetailSceneFactory( router: CertificateDetailRouter(sceneCoordinator: sceneCoordinator), certificates: certificates ) ) } func showHowToScan() -> Promise<Void> { sceneCoordinator.present( HowToScanSceneFactory( router: HowToScanRouter(sceneCoordinator: sceneCoordinator) ) ) } func scanQRCode() -> Promise<ScanResult> { sceneCoordinator.present( ScanSceneFactory( cameraAccessProvider: CameraAccessProvider( router: DialogRouter(sceneCoordinator: sceneCoordinator) ) ) ) } func showAppInformation() { sceneCoordinator.push( AppInformationSceneFactory( router: AppInformationRouter(sceneCoordinator: sceneCoordinator) ) ) } }
25.539683
108
0.638906
38bca438ca8739726c363cd2e879addf2eb519d7
185
import Foundation extension CharacterSet { static var englishMnemonic: CharacterSet { return CharacterSet(charactersIn: "a"..."z") .union(.whitespaces) } }
20.555556
52
0.654054
d50087cd9ab80d38bc0698c079e2ec1cfcb8534e
316
// // OPViewController.swift // Frontier // // Created by Brent Simmons on 4/19/17. // Copyright © 2017 Ranchero Software. All rights reserved. // import Cocoa class OPViewController: NSViewController { override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } }
16.631579
60
0.648734
7565f3b48594ab92d2d82852d7e492e0f65ffd44
10,475
// // ViewController.swift // projectteli18 // // Created by Space Lab on 2020-03-04. // Copyright © 2020 Space Lab. All rights reserved. // import UIKit import HealthKit import WatchConnectivity struct postData: Decodable { let success: Bool let errors: [Int] } struct activityStatus : Decodable{ let success: Bool let errors: [Int] let activity_id: Int } struct activityControl : Decodable{ let success: Bool let errors: [Int] let activity_id: Int } class ViewController: UIViewController, WCSessionDelegate { @IBOutlet var postButton: UIButton! @IBOutlet var sendButton: UIButton! @IBOutlet var getButton: UIButton! @IBOutlet var userField: UITextField! @IBOutlet var deviceField: UITextField! @IBOutlet var serverField: UITextField! @IBOutlet var APIField: UITextField! @IBOutlet var jsonInfo: UITextView! var watchSession : WCSession! = nil var lastHeartRate = "" var activityId = 0 var activityRunning = false @IBAction func getTapped(_ sender: Any) { let serverURL = serverField.text! + "api/v1/activity/status" guard let url = URL(string: serverURL)else{ return } var getReq = URLRequest(url: url) getReq.httpMethod = "GET" getReq.setValue("application/json", forHTTPHeaderField: "Content-Type") getReq.setValue(userField.text, forHTTPHeaderField: "USER-ID") getReq.setValue(APIField.text, forHTTPHeaderField: "API-KEY") let session = URLSession.shared session.dataTask(with: getReq) { (data, response, error) in if let data = data { do { let posts = try JSONDecoder().decode(activityStatus.self, from: data) if posts.success == true{ if posts.activity_id != 0 { DispatchQueue.main.async { self.jsonInfo.text = "Activity is running successfully. Activity ID: " + String(self.activityId) } } else{ DispatchQueue.main.async { self.jsonInfo.text = "No activity is currently running" } } } else{ DispatchQueue.main.async { self.jsonInfo.text = self.handleError(code: posts.errors[0]) } } } catch{ DispatchQueue.main.async { self.jsonInfo.text = "Check unsuccessful, check network connection" } print(error) } } }.resume() } @IBAction func displayHeartRate(_ sender: Any){ jsonInfo.text = "current heartrate: " + lastHeartRate } func startActivity(start: Bool) -> String { if start == true{ return "stop" } else{ return "start" } } @IBAction func postTapped(_ sender: Any){ //var activityRunning = false let serverURL = serverField.text! + "api/v1/activity/control" let deviceID = deviceField.text let parameters = ["device_id" : deviceID, "action" : startActivity(start: activityRunning), "type":"code review", "repo":"torvalds/linux", "commit": "asd123"] guard let url = URL(string: serverURL)else { return } var postReq = URLRequest(url: url) postReq.httpMethod = "POST" postReq.setValue("application/json", forHTTPHeaderField: "Content-Type") postReq.setValue(userField.text, forHTTPHeaderField: "USER-ID") postReq.setValue(APIField.text, forHTTPHeaderField: "API-KEY") guard let body = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return } postReq.httpBody = body let session = URLSession.shared session.dataTask(with: postReq) { (data, response, error) in if let data = data { do { let posts = try JSONDecoder().decode(activityControl.self, from: data) if posts.success == true{ DispatchQueue.main.async { if self.activityRunning == true{ self.activityId = posts.activity_id self.jsonInfo.text = "Activity is started successfully. Activity ID: " + String(self.activityId) } else{ self.activityId = posts.activity_id self.jsonInfo.text = "Activity has been stopped" } } } else{ DispatchQueue.main.async { self.jsonInfo.text = self.handleError(code: posts.errors[0]) } } } catch{ DispatchQueue.main.async { self.jsonInfo.text = "Post unsuccessful, check network connection" } print(error) } } }.resume() if activityRunning == false && activityId != 0 { activityRunning = true postButton.setTitle("Stop Activity", for: .normal) } else{ activityRunning = false postButton.setTitle("Start Activity", for: .normal) } } func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { let heartRateText = message["message"] as! String lastHeartRate = heartRateText } @IBAction func sendTapped(_ sender: Any){ let heartRate = lastHeartRate let serverURL = serverField.text! + "api/v1/data/in" let parameters = ["bpm" : heartRate, "message" : "asd123"] guard let url = URL(string: serverURL) else { return } var postReq = URLRequest(url: url) postReq.httpMethod = "POST" postReq.setValue("application/json", forHTTPHeaderField: "Content-Type") postReq.setValue(userField.text, forHTTPHeaderField: "USER-ID") postReq.setValue(APIField.text, forHTTPHeaderField: "API-KEY") postReq.setValue(deviceField.text, forHTTPHeaderField: "DEVICE-ID") postReq.setValue(String(activityId), forHTTPHeaderField: "ACTIVITY-ID") postReq.setValue("heatbeat", forHTTPHeaderField: "TYPE") guard let body = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return } postReq.httpBody = body let session = URLSession.shared session.dataTask(with: postReq) {(data, response, error) in if let data = data { do { let jsonPost = try JSONDecoder().decode(postData.self, from: data) if jsonPost.success == true { DispatchQueue.main.async { if (self.lastHeartRate != "" && self.activityRunning == true){ self.jsonInfo.text = "Data posted successfully" } else { self.jsonInfo.text = "Activity Not running or no heartrate to send" } } print(jsonPost) } else{ DispatchQueue.main.async { self.jsonInfo.text = self.handleError(code: jsonPost.errors[0]) print(jsonPost) } } } catch{ DispatchQueue.main.async { self.jsonInfo.text = "Send unsuccessful, check network connection" } print(error) } } }.resume() } func handleError(code: Int) -> String { switch code { case 100: return "Error code 100: Invalid API key or user ID" case 101: return "Error code 101: Invalid API permissions" case 200: return "Error code 200: No activity available" case 201: return "Error code 201: Wrong activity_id in request" case 300: return "Error code 300: General server error" case 301: return "Error code 301: Invalid parameter used" case 302: return "Error code 302: Malformed request" case 303: return "Error code 303: Device doesnt belong to user" case 304: return "Error code 304: device_id doesn't exist" case 400: return "Error code 400: JSON not valid" default: return "Error" } } override func viewDidLoad() { super.viewDidLoad() watchSession = WCSession.default watchSession.delegate = self watchSession.activate() userField.delegate = self deviceField.delegate = self serverField.delegate = self APIField.delegate = self } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { //code } func sessionDidBecomeInactive(_ session: WCSession) { //kod } func sessionDidDeactivate(_ session: WCSession) { //kod } } extension ViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
34.68543
166
0.505298
e51f9dd7cc803c6a2418551cada473c9ebf487ea
3,570
// // UIButtonExtention.swift // mbc_jrcxpt // // Created by chen on 2020/3/5. // Copyright © 2020 MBC. All rights reserved. // import UIKit public typealias buttonClick = (()->()) // 定义数据类型(其实就是设置别名) public extension UIButton { enum XButtonEdgeInsetsStyle { case ImageTop // 图片在上,文字在下 case ImageLeft // 图片在上,文字在下 case ImageBottom // 图片在上,文字在下 case ImageRight // 图片在上,文字在下 } /** ># Important:按钮图文位置设置 知识点:titleEdgeInsets是title相对于其上下左右的inset,跟tableView的contentInset是类似的, * 如果只有title,那它上下左右都是相对于button的,image也是一样; * 如果同时有image和label,那这时候image的上左下是相对于button,右边是相对于label的;title的上右下是相对于button,左边是相对于image的。 */ func layoutButtonWithEdgInsetStyle(_ style: XButtonEdgeInsetsStyle, _ space: CGFloat) { // 获取image宽高 let imageW = imageView?.frame.size.width let imageH = imageView?.frame.size.height // 获取label宽高 var lableW = titleLabel?.intrinsicContentSize.width let lableH = titleLabel?.intrinsicContentSize.height var imageEdgeInsets: UIEdgeInsets = .zero var lableEdgeInsets: UIEdgeInsets = .zero if frame.size.width <= lableW! { // 如果按钮文字超出按钮大小,文字宽为按钮大小 lableW = frame.size.width } // 根据传入的 style 及 space 确定 imageEdgeInsets和labelEdgeInsets的值 switch style { case .ImageTop: imageEdgeInsets = UIEdgeInsets(top: 0.0 - lableH! - space / 2.0, left: 0, bottom: 0, right: 0.0 - lableW!) lableEdgeInsets = UIEdgeInsets(top: 0, left: 0.0 - imageW!, bottom: 0.0 - imageH! - space / 2.0, right: 0) case .ImageLeft: imageEdgeInsets = UIEdgeInsets(top: 0, left: 0.0 - space / 2.0, bottom: 0, right: space / 2.0) lableEdgeInsets = UIEdgeInsets(top: 0, left: space / 2.0, bottom: 0, right: 0.0 - space / 2.0) case .ImageBottom: imageEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0.0 - lableH! - space / 2.0, right: 0.0 - lableW!) lableEdgeInsets = UIEdgeInsets(top: 0.0 - imageH! - space / 2.0, left: 0.0 - imageW!, bottom: 0, right: 0) case .ImageRight: imageEdgeInsets = UIEdgeInsets(top: 0, left: lableW! + space / 2.0, bottom: 0, right: 0.0 - lableW! - space / 2.0) lableEdgeInsets = UIEdgeInsets(top: 0, left: 0.0 - imageW! - space / 2.0, bottom: 0, right: imageW! + space / 2.0) } // 赋值 titleEdgeInsets = lableEdgeInsets self.imageEdgeInsets = imageEdgeInsets } // 改进写法【推荐】 private struct RuntimeKey { static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue) /// ...其他Key声明 } /// 运行时关联 private var actionBlock: buttonClick? { set { objc_setAssociatedObject(self, UIButton.RuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } get { return objc_getAssociatedObject(self, UIButton.RuntimeKey.actionBlock!) as? buttonClick } } /// 点击回调 @objc func tapped(button:UIButton){ if self.actionBlock != nil { self.actionBlock!() } } @objc func click(action:@escaping buttonClick) { self.addTarget(self, action:#selector(tapped(button:)) , for:.touchUpInside) self.actionBlock = action } /// 快速创建 convenience init(action:@escaping buttonClick){ self.init() self.addTarget(self, action:#selector(tapped(button:)) , for:.touchUpInside) self.actionBlock = action self.sizeToFit() } }
38.804348
126
0.626611
7a4d2be65264e1bfe02c91e2822789b1e4707e14
12,688
// // SwiftColor_Tests.swift // SVGKit // // Created by C.W. Betts on 3/18/15. // Copyright (c) 2015 C.W. Betts. All rights reserved. // import Foundation import XCTest import SVGKit private let gColorDict = [ "aliceblue": SVGColor(red: 240, green: 248, blue: 255), "antiquewhite": SVGColor(red: 250, green: 235, blue: 215), "aqua": SVGColor(red: 0, green: 255, blue: 255), "aquamarine": SVGColor(red: 127, green: 255, blue: 212), "azure": SVGColor(red: 240, green: 255, blue: 255), "beige": SVGColor(red: 245, green: 245, blue: 220), "bisque": SVGColor(red: 255, green: 228, blue: 196), "black": SVGColor(red: 0, green: 0, blue: 0), "blanchedalmond": SVGColor(red: 255, green: 235, blue: 205), "blue": SVGColor(red: 0, green: 0, blue: 255), "blueviolet": SVGColor(red: 138, green: 43, blue: 226), "brown": SVGColor(red: 165, green: 42, blue: 42), "burlywood": SVGColor(red: 222, green: 184, blue: 135), "cadetblue": SVGColor(red: 95, green: 158, blue: 160), "chartreuse": SVGColor(red: 127, green: 255, blue: 0), "chocolate": SVGColor(red: 210, green: 105, blue: 30), "coral": SVGColor(red: 255, green: 127, blue: 80), "cornflowerblue": SVGColor(red: 100, green: 149, blue: 237), "cornsilk": SVGColor(red: 255, green: 248, blue: 220), "crimson": SVGColor(red: 220, green: 20, blue: 60), "cyan": SVGColor(red: 0, green: 255, blue: 255), "darkblue": SVGColor(red: 0, green: 0, blue: 139), "darkcyan": SVGColor(red: 0, green: 139, blue: 139), "darkgoldenrod": SVGColor(red: 184, green: 134, blue: 11), "darkgray": SVGColor(red: 169, green: 169, blue: 169), "darkgreen": SVGColor(red: 0, green: 100, blue: 0), "darkgrey": SVGColor(red: 169, green: 169, blue: 169), "darkkhaki": SVGColor(red: 189, green: 183, blue: 107), "darkmagenta": SVGColor(red: 139, green: 0, blue: 139), "darkolivegreen": SVGColor(red: 85, green: 107, blue: 47), "darkorange": SVGColor(red: 255, green: 140, blue: 0), "darkorchid": SVGColor(red: 153, green: 50, blue: 204), "darkred": SVGColor(red: 139, green: 0, blue: 0), "darksalmon": SVGColor(red: 233, green: 150, blue: 122), "darkseagreen": SVGColor(red: 143, green: 188, blue: 143), "darkslateblue": SVGColor(red: 72, green: 61, blue: 139), "darkslategray": SVGColor(red: 47, green: 79, blue: 79), "darkslategrey": SVGColor(red: 47, green: 79, blue: 79), "darkturquoise": SVGColor(red: 0, green: 206, blue: 209), "darkviolet": SVGColor(red: 148, green: 0, blue: 211), "deeppink": SVGColor(red: 255, green: 20, blue: 147), "deepskyblue": SVGColor(red: 0, green: 191, blue: 255), "dimgray": SVGColor(red: 105, green: 105, blue: 105), "dimgrey": SVGColor(red: 105, green: 105, blue: 105), "dodgerblue": SVGColor(red: 30, green: 144, blue: 255), "firebrick": SVGColor(red: 178, green: 34, blue: 34), "floralwhite": SVGColor(red: 255, green: 250, blue: 240), "forestgreen": SVGColor(red: 34, green: 139, blue: 34), "fuchsia": SVGColor(red: 255, green: 0, blue: 255), "gainsboro": SVGColor(red: 220, green: 220, blue: 220), "ghostwhite": SVGColor(red: 248, green: 248, blue: 255), "gold": SVGColor(red: 255, green: 215, blue: 0), "goldenrod": SVGColor(red: 218, green: 165, blue: 32), "gray": SVGColor(red: 128, green: 128, blue: 128), "green": SVGColor(red: 0, green: 128, blue: 0), "greenyellow": SVGColor(red: 173, green: 255, blue: 47), "grey": SVGColor(red: 128, green: 128, blue: 128), "honeydew": SVGColor(red: 240, green: 255, blue: 240), "hotpink": SVGColor(red: 255, green: 105, blue: 180), "indianred": SVGColor(red: 205, green: 92, blue: 92), "indigo": SVGColor(red: 75, green: 0, blue: 130), "ivory": SVGColor(red: 255, green: 255, blue: 240), "khaki": SVGColor(red: 240, green: 230, blue: 140), "lavender": SVGColor(red: 230, green: 230, blue: 250), "lavenderblush": SVGColor(red: 255, green: 240, blue: 245), "lawngreen": SVGColor(red: 124, green: 252, blue: 0), "lemonchiffon": SVGColor(red: 255, green: 250, blue: 205), "lightblue": SVGColor(red: 173, green: 216, blue: 230), "lightcoral": SVGColor(red: 240, green: 128, blue: 128), "lightcyan": SVGColor(red: 224, green: 255, blue: 255), "lightgoldenrodyellow": SVGColor(red: 250, green: 250, blue: 210), "lightgray": SVGColor(red: 211, green: 211, blue: 211), "lightgreen": SVGColor(red: 144, green: 238, blue: 144), "lightgrey": SVGColor(red: 211, green: 211, blue: 211), "lightpink": SVGColor(red: 255, green: 182, blue: 193), "lightsalmon": SVGColor(red: 255, green: 160, blue: 122), "lightseagreen": SVGColor(red: 32, green: 178, blue: 170), "lightskyblue": SVGColor(red: 135, green: 206, blue: 250), "lightslategray": SVGColor(red: 119, green: 136, blue: 153), "lightslategrey": SVGColor(red: 119, green: 136, blue: 153), "lightsteelblue": SVGColor(red: 176, green: 196, blue: 222), "lightyellow": SVGColor(red: 255, green: 255, blue: 224), "lime": SVGColor(red: 0, green: 255, blue: 0), "limegreen": SVGColor(red: 50, green: 205, blue: 50), "linen": SVGColor(red: 250, green: 240, blue: 230), "magenta": SVGColor(red: 255, green: 0, blue: 255), "maroon": SVGColor(red: 128, green: 0, blue: 0), "mediumaquamarine": SVGColor(red: 102, green: 205, blue: 170), "mediumblue": SVGColor(red: 0, green: 0, blue: 205), "mediumorchid": SVGColor(red: 186, green: 85, blue: 211), "mediumpurple": SVGColor(red: 147, green: 112, blue: 219), "mediumseagreen": SVGColor(red: 60, green: 179, blue: 113), "mediumslateblue": SVGColor(red: 123, green: 104, blue: 238), "mediumspringgreen": SVGColor(red: 0, green: 250, blue: 154), "mediumturquoise": SVGColor(red: 72, green: 209, blue: 204), "mediumvioletred": SVGColor(red: 199, green: 21, blue: 133), "midnightblue": SVGColor(red: 25, green: 25, blue: 112), "mintcream": SVGColor(red: 245, green: 255, blue: 250), "mistyrose": SVGColor(red: 255, green: 228, blue: 225), "moccasin": SVGColor(red: 255, green: 228, blue: 181), "navajowhite": SVGColor(red: 255, green: 222, blue: 173), "navy": SVGColor(red: 0, green: 0, blue: 128), "oldlace": SVGColor(red: 253, green: 245, blue: 230), "olive": SVGColor(red: 128, green: 128, blue: 0), "olivedrab": SVGColor(red: 107, green: 142, blue: 35), "orange": SVGColor(red: 255, green: 165, blue: 0), "orangered": SVGColor(red: 255, green: 69, blue: 0), "orchid": SVGColor(red: 218, green: 112, blue: 214), "palegoldenrod": SVGColor(red: 238, green: 232, blue: 170), "palegreen": SVGColor(red: 152, green: 251, blue: 152), "paleturquoise": SVGColor(red: 175, green: 238, blue: 238), "palevioletred": SVGColor(red: 219, green: 112, blue: 147), "papayawhip": SVGColor(red: 255, green: 239, blue: 213), "peachpuff": SVGColor(red: 255, green: 218, blue: 185), "peru": SVGColor(red: 205, green: 133, blue: 63), "pink": SVGColor(red: 255, green: 192, blue: 203), "plum": SVGColor(red: 221, green: 160, blue: 221), "powderblue": SVGColor(red: 176, green: 224, blue: 230), "purple": SVGColor(red: 128, green: 0, blue: 128), "red": SVGColor(red: 255, green: 0, blue: 0), "rosybrown": SVGColor(red: 188, green: 143, blue: 143), "royalblue": SVGColor(red: 65, green: 105, blue: 225), "saddlebrown": SVGColor(red: 139, green: 69, blue: 19), "salmon": SVGColor(red: 250, green: 128, blue: 114), "sandybrown": SVGColor(red: 244, green: 164, blue: 96), "seagreen": SVGColor(red: 46, green: 139, blue: 87), "seashell": SVGColor(red: 255, green: 245, blue: 238), "sienna": SVGColor(red: 160, green: 82, blue: 45), "silver": SVGColor(red: 192, green: 192, blue: 192), "skyblue": SVGColor(red: 135, green: 206, blue: 235), "slateblue": SVGColor(red: 106, green: 90, blue: 205), "slategray": SVGColor(red: 112, green: 128, blue: 144), "slategrey": SVGColor(red: 112, green: 128, blue: 144), "snow": SVGColor(red: 255, green: 250, blue: 250), "springgreen": SVGColor(red: 0, green: 255, blue: 127), "steelblue": SVGColor(red: 70, green: 130, blue: 180), "tan": SVGColor(red: 210, green: 180, blue: 140), "teal": SVGColor(red: 0, green: 128, blue: 128), "thistle": SVGColor(red: 216, green: 191, blue: 216), "tomato": SVGColor(red: 255, green: 99, blue: 71), "turquoise": SVGColor(red: 64, green: 224, blue: 208), "violet": SVGColor(red: 238, green: 130, blue: 238), "wheat": SVGColor(red: 245, green: 222, blue: 179), "white": SVGColor(red: 255, green: 255, blue: 255), "whitesmoke": SVGColor(red: 245, green: 245, blue: 245), "yellow": SVGColor(red: 255, green: 255, blue: 0), "yellowgreen": SVGColor(red: 154, green: 205, blue: 50) ] private var gColorValues: [SVGColor] = { var toRet = [SVGColor]() //var names = gColorDict.keys.array let names = gColorNames #if false names.sort( { return $0 < $1 }) #endif for name in names { toRet.append(gColorDict[name]!) } return toRet }() private let gColorNames = [ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige", "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown", "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue", "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod", "darkgray", "darkgreen", "darkgrey", "darkkhaki", "darkmagenta", "darkolivegreen", "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen", "darkslateblue", "darkslategray", "darkslategrey", "darkturquoise", "darkviolet", "deeppink", "deepskyblue", "dimgray", "dimgrey", "dodgerblue", "firebrick", "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite", "gold", "goldenrod", "gray", "green", "greenyellow", "grey", "honeydew", "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender", "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral", "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightgrey", "lightpink", "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray", "lightslategrey", "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta", "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple", "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise", "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin", "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered", "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred", "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue", "purple", "red", "rosybrown", "royalblue", "saddlebrown", "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue", "slateblue", "slategray", "slategrey", "snow", "springgreen", "steelblue", "tan", "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white", "whitesmoke", "yellow", "yellowgreen" ] class SwiftColor_Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } lazy var SVGcolorDict: [String: SVGColor] = self.colorDictionary() func colorDictionary() -> [String: SVGColor] { var toRetArray = [String: SVGColor]() for colorName in gColorNames { toRetArray[colorName] = SVGColor(string: colorName) } return toRetArray } func testCColorPerformance() { //measure the block for populating a color array with the C Function self.measureBlock() { var cLookupArray = [SVGColor]() for strColor in gColorNames { var aColor = SVGColorFromString(strColor) cLookupArray.append(aColor) } } } func testCColorEquality() { var cLookupArray = [SVGColor]() for strColor in gColorNames { var aColor = SVGColorFromString(strColor) cLookupArray.append(aColor) } for i in 0 ..< cLookupArray.count { XCTAssertEqual(cLookupArray[i], gColorValues[i]) } XCTAssertEqual(cLookupArray, gColorValues) } func testSwiftColorPerformance() { self.measureBlock() { let colorDict = self.colorDictionary() var swiftLookupArray = [SVGColor]() for strColor in gColorNames { if let aColor = colorDict[strColor] { swiftLookupArray.append(aColor) } else { XCTAssert(false, "Got wrong value") } } } } func testSwiftColorEquality() { var swiftLookupArray = [SVGColor]() for strColor in gColorNames { if let aColor = SVGcolorDict[strColor] { swiftLookupArray.append(aColor) } else { XCTAssert(false, "Got wrong value") } } XCTAssertEqual(swiftLookupArray, gColorValues) } }
30.946341
111
0.660073
87edd2b4ecaf6e7a8b38f37181665a9ba4edc56a
744
// // HyperlinkTextField.swift // Hidden Bar // // Created by phucld on 12/19/19. // Copyright © 2019 Dwarves Foundation. All rights reserved. // import Foundation import Cocoa @IBDesignable class HyperlinkTextField: NSTextField { @IBInspectable var href: String = "" override func resetCursorRects() { discardCursorRects() addCursorRect(self.bounds, cursor: NSCursor.pointingHand) } override func awakeFromNib() { super.awakeFromNib() // TODO: Fix this and get the hover click to work. } override func mouseDown(with theEvent: NSEvent) { if let localHref = URL(string: href) { NSWorkspace.shared.open(localHref) } } }
21.257143
65
0.63172
d98a86d9adb31ffdf45b76706be57a15b777afd2
775
private let kRestrictedHeaderPrefix = ":" extension Request { /// Returns a set of outbound headers that include HTTP /// information on the URL, method, and additional headers. /// /// - returns: Outbound headers to send with an HTTP request. func outboundHeaders() -> [String: [String]] { var headers = self.headers .filter { !$0.key.hasPrefix(kRestrictedHeaderPrefix) } .reduce(into: [ ":method": [self.method.stringValue], ":scheme": [self.scheme], ":authority": [self.authority], ":path": [self.path], ]) { $0[$1.key] = $1.value } if let retryPolicy = self.retryPolicy { headers = headers.merging(retryPolicy.outboundHeaders()) { _, retryHeader in retryHeader } } return headers } }
31
96
0.632258
4ab2a68c8afa0d50924c46ac8041e9351a47f02a
717
// // UIDevice.swift // Hanabi // // Created by Sergey on 25.09.2018. // Copyright © 2018 Sergey. All rights reserved. // import UIKit extension UIDevice { var iPad: Bool { return userInterfaceIdiom == .pad } // indicate current device is in the LandScape orientation var isLandscape: Bool { return orientation.isValidInterfaceOrientation ? orientation.isLandscape : UIApplication.shared.statusBarOrientation.isLandscape } // indicate current device is in the Portrait orientation var isPortrait: Bool { return orientation.isValidInterfaceOrientation ? orientation.isPortrait : UIApplication.shared.statusBarOrientation.isPortrait } }
25.607143
136
0.705718
1a2c1610c3571a5cb67f2f29be641a1e2b2b0c2e
1,142
// // SortLeastToGreatest.swift // Alien Adventure // // Created by Jarrod Parkes on 10/4/15. // Copyright © 2015 Udacity. All rights reserved. // extension Hero { func sortLeastToGreatest(inventory: [UDItem]) -> [UDItem] { return inventory.sorted(by: ({ if $0.rarity == $1.rarity{ if $0.baseValue < $1.baseValue{ return true }else{ return false } }else if $0.rarity == .legendary && ($1.rarity == .rare || $1.rarity == .uncommon || $1.rarity == .common){ return false }else if $0.rarity == .rare && ($1.rarity == .uncommon || $1.rarity == .common){ return false }else if $0.rarity == .uncommon && $1.rarity == .common{ return false } return true })) } } // If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 5"
32.628571
235
0.537653
87050c5e21c03eb972a61ed50fcdc6d17e31695e
11,546
// // MyBackendLib.swift // PaymentSDKSwift // // Created by Gustavo Sotelo on 19/09/17. // // import Foundation import PaymentSDK class MyBackendLib { static let myBackendUrl = "https://example-paymentez-backend.herokuapp.com/" static func verifyTrx(uid:String, transactionId:String, type:Int, value:String, callback:@escaping (_ error:PaymentSDKError?, _ verified:Bool) ->Void) { var verifyType = "BY_AMOUNT" if type == 1 { verifyType = "BY_AUTH_CODE" } let params = ["uid": uid, "transaction_id": transactionId, "type": verifyType, "value":value] makeRequestPOST("verify-transaction", parameters: params as NSDictionary) { (error, statusCode, responseData) in if statusCode == 200 { callback(nil,true) } else { do { var dataR = (responseData as! [String:Any]) if dataR["error"] != nil { dataR = dataR["error"] as! [String:Any] } let errorPa = PaymentSDKError.createError(statusCode!, description: dataR["description"] as! String, help: dataR["help"] as? String, type: dataR["type"] as? String) //parse error in strutcture callback(errorPa,false) } } } } static func deleteCard(uid:String, cardToken:String, callback:@escaping (_ deleted:Bool) ->Void) { let params = ["token": cardToken, "uid": uid] makeRequestPOST("delete-card", parameters: params as NSDictionary) { (error, statusCode, responseData) in if statusCode == 200 { callback(true) } else { callback(false) } } } static func debitCard(uid:String, cardToken:String, sessionId:String, devReference:String, amount:Double, description:String, callback:@escaping (_ error:NSError?, _ transaction:PaymentTransaction?) ->Void) { let params = ["uid": uid, "token": cardToken, "session_id": sessionId, "amount": String(format: "%.2f", amount), "dev_reference":devReference, "description":description] as NSDictionary makeRequestPOST("create-charge", parameters: params) { (error, statusCode, responseData) in if error == nil { if statusCode == 200 { let responseD = responseData as! [String:Any] let transaction = responseD["transaction"] as! [String:Any] let trx = PaymentTransaction() trx.amount = transaction["amount"] as? NSNumber trx.status = transaction["status"] as? String trx.statusDetail = transaction["status_detail"] as? Int as NSNumber? trx.transactionId = transaction["id"] as? String if let authCode = Int(transaction["authorization_code"] as! String) { trx.authorizationCode = NSNumber(value:authCode) } trx.carrierCode = transaction["carrier_code"] as? String trx.message = transaction["message"] as? String let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" if let paymentdate = (responseD["payment_date"] as? String) { trx.paymentDate = dateFormatter.date(from: paymentdate) } if trx.statusDetail == 11 { callback(nil, trx) } else if trx.statusDetail != 3 { callback(error, trx) } else { callback(nil, trx) } } else { do { callback(error, nil) } } } else { callback(error, nil) } } } static func listCard(uid:String, callback:@escaping (_ cardList:[PaymentCard]?) ->Void) { let parameters = ["uid": uid] as [String:Any] makeRequestGet("get-cards", parameters: parameters as NSDictionary) { (error, statusCode, responseData) in var responseCards = [PaymentCard]() if error == nil { if statusCode == 200 { let responseObj = responseData as! NSDictionary let cardsArray = responseObj["cards"] as! [[String:Any]] for card in cardsArray { let pCard = PaymentCard() pCard.bin = "\(card["bin"]!)" pCard.token = "\(card["token"]!)" pCard.cardHolder = "\(card["holder_name"]!)" pCard.expiryMonth = card["expiry_month"] as! String pCard.expiryYear = card["expiry_year"] as! String pCard.termination = "\(card["number"]!)" pCard.status = "\(card["status"]!)" pCard.type = "\(card["type"]!)" responseCards.append(pCard) } } callback(responseCards) } else { callback(responseCards) } } } static func makeRequestGet(_ urlToRequest:String, parameters:NSDictionary, responseCallback:@escaping (_ error:NSError?, _ statusCode:Int?,_ responseData:Any?) ->Void) { var completeUrl = self.myBackendUrl + urlToRequest var bodyData = "" for (key,value) in parameters{ let scapedKey = (key as! String).addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)! let scapedValue = (value as! String).addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)! bodyData += "\(scapedKey)=\(scapedValue)&" } completeUrl += "?" + bodyData let url:URL? = URL(string: completeUrl) let session = URLSession.shared var request = URLRequest(url:url!) request.httpMethod = "GET" let task = session.dataTask(with: request){ data, resp, err in if err == nil { var json:Any? = nil do{ json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) } catch { } if json == nil{ let error = NSError(domain: "JSON", code: 400, userInfo: ["parsing" : false]) print ("parsing json error") responseCallback(error, 400,nil) } else { responseCallback(err as NSError?, (resp as! HTTPURLResponse).statusCode, json) } } else { responseCallback(err as NSError?, 400, nil) } } task.resume() } static func makeRequestPOST(_ urlToRequest:String, parameters:NSDictionary, responseCallback:@escaping (_ error:NSError?, _ statusCode:Int?,_ responseData:Any?) ->Void) { let completeUrl = self.myBackendUrl + urlToRequest let url:URL? = URL(string: completeUrl) let session = URLSession.shared var request = URLRequest(url:url!) request.httpMethod = "POST" request.httpBody = encodeParams(parameters) let task = session.dataTask(with: request){ data, resp, err in print(data as Any) if err == nil { var json:Any? = nil do{ json = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) print(json as Any) } catch { } if json == nil{ let error = NSError(domain: "JSON", code: 400, userInfo: ["parsing" : false]) print ("parsing json error") if resp != nil { responseCallback(error, (resp as! HTTPURLResponse).statusCode,nil) } else { responseCallback(error, 400,nil) } } else { print(json as Any) responseCallback(err as NSError?, (resp as! HTTPURLResponse).statusCode, json) } } else { responseCallback(err as NSError?, 400, nil) } } task.resume() } static func encodeParams(_ parameters:NSDictionary) ->Data? { var bodyData = "" for (key,value) in parameters{ let scapedKey = (key as! String).addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)! let scapedValue = (value as! String).addingPercentEncoding( withAllowedCharacters: .urlHostAllowed)! bodyData += "\(scapedKey)=\(scapedValue)&" } print(bodyData) return bodyData.data(using: String.Encoding.utf8, allowLossyConversion: true) } }
40.512281
217
0.414689
086f673606631fb46334c219fb8c7b6564f980d6
1,015
// AutomaticTuningOptionModeDesired enumerates the values for automatic tuning option mode desired. // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. public enum AutomaticTuningOptionModeDesiredEnum: String, Codable { // AutomaticTuningOptionModeDesiredDefault specifies the automatic tuning option mode desired default state for // automatic tuning option mode desired. case AutomaticTuningOptionModeDesiredDefault = "Default" // AutomaticTuningOptionModeDesiredOff specifies the automatic tuning option mode desired off state for automatic // tuning option mode desired. case AutomaticTuningOptionModeDesiredOff = "Off" // AutomaticTuningOptionModeDesiredOn specifies the automatic tuning option mode desired on state for automatic tuning // option mode desired. case AutomaticTuningOptionModeDesiredOn = "On" }
53.421053
119
0.805911
fefbb47b9de89b18998f531c530eed207c1b0743
1,276
// // dnCalendarUITests.swift // dnCalendarUITests // // Created by romdoni agung purbayanto on 5/11/16. // Copyright © 2016 romdoni agung purbayanto. All rights reserved. // import XCTest class dnCalendarUITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } }
34.486486
182
0.669279
ddd8ff9abe0070fcfed0360b6c41b1e581b29b9c
332
// // UIView.swift // UXMPDFKit // // Created by Diego Stamigni on 26/01/2018. // import UIKit extension UIView { var hasNotch: Bool { get { // https://stackoverflow.com/a/46192822 return UIDevice().userInterfaceIdiom == .phone && UIScreen.main.nativeBounds.height >= 2436 } } }
18.444444
103
0.593373
ac317ca11b8ec75905c8c727ba2b764b7c4a5cc5
2,173
// // AppDelegate.swift // Photo Map // // Created by Timothy Lee on 10/20/14. // Copyright (c) 2014 Timothy Lee. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.234043
285
0.753336
bb41a3b4768373114c1c533bdeaaa8be9d05ac92
1,130
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Cocoa class FlutterWindow: NSWindow { @IBOutlet weak var flutterViewController: FLEViewController! override func awakeFromNib() { PluginRegistrant.register(with: flutterViewController) let assets = NSURL.fileURL(withPath: "flutter_assets", relativeTo: Bundle.main.resourceURL) var arguments: [String] = []; #if !DEBUG arguments.append("--disable-dart-asserts"); #endif flutterViewController.launchEngine( withAssetsPath: assets, commandLineArguments: arguments) super.awakeFromNib() } }
31.388889
95
0.740708
758ecf72663ffa1cc066969922b739101961bbbd
12,728
import XCTest import UIKit @testable import RKAutoLayout class RKConstraintCenterTests: XCTestCase { let view: UIView = UIView() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testResultIsCorrectXBuilder() { do { let builderHolder = RKConstraintCenter.centerX() guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 0) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.required.value) XCTAssert(builder.isActive == true) } do { let builderHolder = RKConstraintCenter.centerX(10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.centerXAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(view.leftAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.leftAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(min: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(min: view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.centerXAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(min: view.leftAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.leftAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(max: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(max: view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.centerXAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerX(max: view.leftAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterXBuilder else { XCTFail("Builder must be RKConstraintCenterXBuilder type") return } XCTAssert(builder.anchor == view.leftAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } } func testResultIsCorrectYBuilder() { do { let builderHolder = RKConstraintCenter.centerY() guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 0) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.required.value) XCTAssert(builder.isActive == true) } do { let builderHolder = RKConstraintCenter.centerY(10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.centerYAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(view.topAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.topAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .equal) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(min: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(min: view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.centerYAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(min: view.topAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.topAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .greaterThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(max: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == nil) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(max: view, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.centerYAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } do { let builderHolder = RKConstraintCenter.centerY(max: view.topAnchor, offset: 10, priority: .low, isActive: false) guard let builder = builderHolder.builder as? RKConstraintCenterYBuilder else { XCTFail("Builder must be RKConstraintCenterYBuilder type") return } XCTAssert(builder.anchor == view.topAnchor) XCTAssert(builder.value == 10) XCTAssert(builder.relation == .lessThanOrEqual) XCTAssert(builder.priority.value == RKConstraintPriority.low.value) XCTAssert(builder.isActive == false) } } }
42.145695
125
0.611251
9029380c7e2ddf4fea5798f7a52bed43f9f642f8
12,751
// // QuackClient.swift // Quack // // Created by Christoph on 16.05.17. // // import Foundation import SwiftyJSON import Dispatch extension Quack { open class ClientBase { public private(set) var url: URL public private(set) var timeoutInterval: TimeInterval // MARK: - Init public init(url: URL, timeoutInterval: TimeInterval = 5) { self.url = url self.timeoutInterval = timeoutInterval } convenience public init?(urlString: String, timeoutInterval: TimeInterval = 5) { if let url = URL(string: urlString) { self.init(url: url, timeoutInterval: timeoutInterval) } else { return nil } } // MARK: - Methods overridden by subclasses open func _respondWithData(method: Quack.HTTP.Method, path: String, body: Quack.Body?, headers: [String: String], validStatusCodes: CountableRange<Int>, requestModification: ((Quack.Request) -> (Quack.Request))?) -> Quack.Result<Data> { fatalError("this method must be implemented in subclass") } open func _respondWithDataAsync(method: Quack.HTTP.Method, path: String, body: Quack.Body?, headers: [String: String], validStatusCodes: CountableRange<Int>, requestModification: ((Quack.Request) -> (Quack.Request))?, completion: @escaping (Quack.Result<Data>) -> (Swift.Void)) { fatalError("this method must be implemented in subclass") } } } // MARK: - Synchronous Response public extension Quack.ClientBase { public func respond<Model: Quack.DataModel>(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, parser: Quack.CustomModelParser? = nil, model: Model.Type, requestModification: ((Quack.Request) -> (Quack.Request))? = nil) -> Quack.Result<Model> { let result = _respondWithData(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) switch result { case .success(let data): return (parser ?? self).parseModel(data: data, model: model) case .failure(let error): return Quack.Result.failure(error) } } public func respondWithArray<Model: Quack.DataModel>(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, parser: Quack.CustomArrayParser? = nil, model: Model.Type, requestModification: ((Quack.Request) -> (Quack.Request))? = nil) -> Quack.Result<[Model]> { let result = _respondWithData(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) switch result { case .success(let data): return (parser ?? self).parseArray(data: data, model: model) case .failure(let error): return Quack.Result.failure(error) } } public func respondVoid(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, requestModification: ((Quack.Request) -> (Quack.Request))? = nil) -> Quack.Void { let result = _respondWithData(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) switch result { case .success: return Quack.Result.success(()) case .failure(let error): return Quack.Result.failure(error) } } } // MARK: - Asynchronous Response public extension Quack.ClientBase { public func respondAsync<Model: Quack.DataModel>(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, parser: Quack.CustomModelParser? = nil, model: Model.Type, requestModification: ((Quack.Request) -> (Quack.Request))? = nil, completion: @escaping (Quack.Result<Model>) -> (Void)) { _respondWithDataAsync(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) { result in switch result { case .success(let data): completion((parser ?? self).parseModel(data: data, model: model)) case .failure(let error): completion(Quack.Result.failure(error)) } } } public func respondWithArrayAsync<Model: Quack.DataModel>(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, parser: Quack.CustomArrayParser? = nil, model: Model.Type, requestModification: ((Quack.Request) -> (Quack.Request))? = nil, completion: @escaping (Quack.Result<[Model]>) -> (Void)) { _respondWithDataAsync(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) { result in switch result { case .success(let data): completion((parser ?? self).parseArray(data: data, model: model)) case .failure(let error): completion(Quack.Result.failure(error)) } } } public func respondVoidAsync(method: Quack.HTTP.Method = .get, path: String, body: Quack.Body? = nil, headers: [String: String] = [:], validStatusCodes: CountableRange<Int> = 200..<300, requestModification: ((Quack.Request) -> (Quack.Request))? = nil, completion: @escaping (Quack.Void) -> (Void)) { _respondWithDataAsync(method: method, path: path, body: body, headers: headers, validStatusCodes: validStatusCodes, requestModification: requestModification) { result in switch result { case .success: completion(Quack.Result.success(())) case .failure(let error): completion(Quack.Result.failure(error)) } } } } // MARK: - Path Builder public extension Quack.ClientBase { public func buildPath(_ path: String, withParams params: [String: String]) -> String { var urlComponents = URLComponents() urlComponents.path = path var queryItems = [URLQueryItem]() for (key, value) in params { let queryItem = URLQueryItem(name: key, value: value) queryItems.append(queryItem) } urlComponents.queryItems = queryItems var query = "" if let percentEncodedQuery = urlComponents.percentEncodedQuery { query = "?\(percentEncodedQuery)" } return "\(urlComponents.percentEncodedPath)\(query)" } } // MARK: - Response Handling public extension Quack.ClientBase { public func _handleClientResponse(_ response: Quack.Response?, validStatusCodes: CountableRange<Int>, completion: @escaping (Quack.Result<Data>) -> (Void)) { guard let response = response else { completion(.failure(.withType(.errorWithName("No Response")))) return } guard validStatusCodes.contains(response.statusCode) else { let error = Quack.Error(type: .invalidStatusCode(response.statusCode), userInfo: [ "response": response ]) completion(.failure(error)) return } completion(.success(response.body ?? Data())) } } extension Quack.ClientBase: Quack.CustomModelParser { public func parseModel<Model>(data: Data, model: Model.Type) -> Quack.Result<Model> where Model : Quack.DataModel { if let model = Model(data: data) { return .success(model) } else { return .failure(.withType(.modelParsingError)) } } } extension Quack.ClientBase: Quack.CustomArrayParser { public func parseArray<Model>(data: Data, model: Model.Type) -> Quack.Result<[Model]> where Model : Quack.DataModel { let json = JSON(data: data) guard let jsonArray = json.array else { return .failure(.withType(.jsonParsingError)) } var models: [Model] = [] for jsonObject in jsonArray { guard let JSONModel = Model.self as? Quack.Model.Type, let jsonModel = JSONModel.init(json: jsonObject), let model = jsonModel as? Model else { continue } models.append(model) } return .success(models) } }
43.223729
149
0.437221
9b445b34cad77c70ec8ca72649adf7ef3db34188
1,408
// // OrderDeliveryTableViewCell.swift // AdForMerchant // // Created by Kuma on 3/11/16. // Copyright © 2016 Windward. All rights reserved. // import UIKit class OrderDeliveryTableViewCell: UITableViewCell { @IBOutlet internal var leftTxtLabel: UILabel! // @IBOutlet internal var rightButton: UIButton! @IBOutlet internal var centerTxtField: UITextField! var endEditingBlock: ((UITextField) -> Void)? override func awakeFromNib() { super.awakeFromNib() // Initialization code centerTxtField.delegate = self // let qrCodeImg = UIImage(named: "NaviIconQRCode")?.imageWithRenderingMode(.AlwaysTemplate) // rightButton.setImage(qrCodeImg, forState: .Normal) } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension OrderDeliveryTableViewCell: UITextFieldDelegate { func textFieldDidEndEditing(_ textField: UITextField) { if let block = endEditingBlock { block(textField) } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string == "\n" { textField.resignFirstResponder() return false } return true } }
27.607843
129
0.666193
2658398b4cf52723304db2e13ffed69752395679
1,237
// // SettingsViewController.swift // TipCalculator // // Created by Xinxin Xie on 12/6/15. // Copyright © 2015 Xinxin Xie. All rights reserved./ import UIKit class SettingsViewController: UIViewController { @IBOutlet weak var tipControl: UISegmentedControl! @IBOutlet weak var colorThemeControl: UISegmentedControl! let tipPercentage = TipPercentage() let backgroundColorSetting = BackgroundColorSetting() override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //print("view will appear") tipControl.selectedSegmentIndex = tipPercentage.index if backgroundColorSetting.isNight { colorThemeControl.selectedSegmentIndex = 1 } else { colorThemeControl.selectedSegmentIndex = 0 } } @IBAction func tipControlValueChanged(sender: AnyObject) { tipPercentage.index = tipControl.selectedSegmentIndex } @IBAction func colorThemeControlValueChanged(sender: AnyObject) { if colorThemeControl.selectedSegmentIndex == 0 { backgroundColorSetting.isNight = false } else { backgroundColorSetting.isNight = true } } }
28.767442
69
0.674212
6174b3914a5244a3404a8fde3bf525ca64f3a865
2,437
// // ProductAttributes.swift // OpenFoodFacts // // Created by Alexander Scott Beaty on 9/29/20. // import ObjectMapper /** A model for Products usinig the [Product Attributes api](https://wiki.openfoodfacts.org/Product_Attributes) */ struct ProductAttributes { var barcode: String? var attributeGroups: [AttributeGroup]? init?(map: Map) { barcode <- map[ProductAttributesJson.BarcodeKey] attributeGroups <- map["\(OFFJson.ProductKey + "." + ProductAttributesJson.attributeGroupsLang())"] // Fail init if some basic values are not present if self.barcode == nil && self.attributeGroups == nil { return nil } } } struct AttributeGroup: Mappable { var id: String? var name: String? var attributes: [Attribute]? init() {} init?(map: Map) {} mutating func mapping(map: Map) { id <- map[AttributeGroupJson.id] name <- map[AttributeGroupJson.NameKey] attributes <- map[AttributeGroupJson.AttributesKey] } } struct Attribute: Mappable { var id: String? var name: String? var status: String? var match: Double? var iconUrl: String? var title: String? var details: String? var descriptionShort: String? var descriptionLong: String? var recommendationShort: String? var recommendationLong: String? var officialLinkTitle: String? var officialLinkUrl: String? var offLinkTitle: String? var offLinkUrl: String? init() {} init?(map: Map) {} mutating func mapping(map: Map) { id <- map[AttributeJson.IDKey] name <- map[AttributeJson.NameKey] status <- map[AttributeJson.StatusKey] match <- (map[AttributeJson.MatchKey], DoubleTransform()) iconUrl <- map[AttributeJson.IconUrlKey] title <- map[AttributeJson.TitleKey] details <- map[AttributeJson.DetailsKey] descriptionShort <- map[AttributeJson.DescriptionShortKey] descriptionLong <- map[AttributeJson.DescriptionLongKey] recommendationShort <- map[AttributeJson.RecommendationShortKey] recommendationLong <- map[AttributeJson.RecommendationLongKey] officialLinkTitle <- map[AttributeJson.OfficialLinkTitleKey] officialLinkUrl <- map[AttributeJson.OfficialLinkUrlKey] offLinkTitle <- map[AttributeJson.OffLinkTitleKey] offLinkUrl <- map[AttributeJson.OffLinkUrlKey] } }
30.848101
108
0.6746
91ef9eac115a9cc43c735ca8fd1a1356105b1ec6
1,414
// // Generated by SwagGen // https://github.com/yonaskolb/SwagGen // import Foundation public class ArrayOfNumberOnly: Codable, Equatable { public var arrayNumber: [Double]? public init(arrayNumber: [Double]? = nil) { self.arrayNumber = arrayNumber } private enum CodingKeys: String, CodingKey { case arrayNumber = "ArrayNumber" } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) arrayNumber = try container.decodeArrayIfPresent(.arrayNumber) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) } public func isEqual(to object: Any?) -> Bool { guard let object = object as? ArrayOfNumberOnly else { return false } guard self.arrayNumber == object.arrayNumber else { return false } return true } public static func == (lhs: ArrayOfNumberOnly, rhs: ArrayOfNumberOnly) -> Bool { return lhs.isEqual(to: rhs) } }
16.833333
84
0.545262
014fdff704f377b398193b28854a0c9bc06d387d
736
// // Receiver.swift // Aojet // // Created by Qihe Bian on 6/6/16. // Copyright © 2016 Qihe Bian. All rights reserved. // public protocol Receiver: Identifiable { func onReceive(message: Any) throws } public final class AnyReceiver: Receiver, IdentifierHashable { private let _base: Any? public let objectId: Identifier let _onReceive: (_ message: Any) throws -> () init<T: Receiver>(_ base: T) { _base = base objectId = base.objectId _onReceive = base.onReceive } init(_ closure: @escaping (_ message: Any) throws -> ()) { _base = nil objectId = type(of: self).generateObjectId() _onReceive = closure } public func onReceive(message: Any) throws { try _onReceive(message) } }
21.028571
62
0.668478
626ada17a52c4777d70ac4fdb66d6156484fcbd8
20,720
/* Expressions */ public __abstract class CGExpression: CGStatement { } public class CGRawExpression : CGExpression { // not language-agnostic. obviosuly. public var Lines: List<String> public init(_ lines: List<String>) { Lines = lines } /*public convenience init(_ lines: String ...) { init(lines.ToList()) }*/ public init(_ lines: String) { Lines = lines.Replace("\r", "").Split("\n").MutableVersion() } } public class CGTypeReferenceExpression : CGExpression{ public var `Type`: CGTypeReference public init(_ type: CGTypeReference) { `Type` = type } } public class CGAssignedExpression: CGExpression { public var Value: CGExpression public var Inverted: Boolean = false public init(_ value: CGExpression) { Value = value } public init(_ value: CGExpression, inverted: Boolean) { Value = value Inverted = inverted } } public class CGSizeOfExpression: CGExpression { public var Expression: CGExpression public init(_ expression: CGExpression) { Expression = expression } } public class CGTypeOfExpression: CGExpression { public var Expression: CGExpression public init(_ expression: CGExpression) { Expression = expression } } public class CGDefaultExpression: CGExpression { public var `Type`: CGTypeReference public init(_ type: CGTypeReference) { `Type` = type } } public class CGSelectorExpression: CGExpression { /* Cocoa only */ public var Name: String public init(_ name: String) { Name = name } } public class CGTypeCastExpression: CGExpression { public var Expression: CGExpression public var TargetType: CGTypeReference public var ThrowsException = false public var GuaranteedSafe = false // in Silver, this uses "as" public var CastKind: CGTypeCastKind? // C++ only public init(_ expression: CGExpression, _ targetType: CGTypeReference) { Expression = expression TargetType = targetType } public convenience init(_ expression: CGExpression, _ targetType: CGTypeReference, _ throwsException: Boolean) { init(expression, targetType) ThrowsException = throwsException } } public enum CGTypeCastKind { // C++ only case Constant case Dynamic case Reinterpret case Static case Interface // C++Builder only case Safe // VC++ only } public class CGAwaitExpression: CGExpression { public var Expression: CGExpression public init(_ expression: CGExpression) { Expression = expression } } public class CGAnonymousMethodExpression: CGExpression { public var Lambda = true public var Parameters: List<CGParameterDefinition> public var ReturnType: CGTypeReference? public var Statements: List<CGStatement> public var LocalVariables: List<CGVariableDeclarationStatement>? // Legacy Delphi only. public init(_ statements: List<CGStatement>) { super.init() Parameters = List<CGParameterDefinition>() Statements = statements } public convenience init(_ statements: CGStatement...) { init(statements.ToList()) } public init(_ parameters: List<CGParameterDefinition>, _ statements: List<CGStatement>) { super.init() Statements = statements Parameters = parameters } public convenience init(_ parameters: CGParameterDefinition[], _ statements: CGStatement[]) { init(parameters.ToList(), statements.ToList()) } } public enum CGAnonymousTypeKind { case Class case Struct case Interface } public class CGAnonymousTypeExpression : CGExpression { public var Kind: CGAnonymousTypeKind public var Ancestor: CGTypeReference? public var Members = List<CGAnonymousMemberDefinition>() public init(_ kind: CGAnonymousTypeKind) { Kind = kind } } public __abstract class CGAnonymousMemberDefinition : CGEntity{ public var Name: String public init(_ name: String) { Name = name } } public class CGAnonymousPropertyMemberDefinition : CGAnonymousMemberDefinition{ public var Value: CGExpression public init(_ name: String, _ value: CGExpression) { super.init(name) Value = value } } public class CGAnonymousMethodMemberDefinition : CGAnonymousMemberDefinition{ public var Parameters = List<CGParameterDefinition>() public var ReturnType: CGTypeReference? public var Statements: List<CGStatement> public init(_ name: String, _ statements: List<CGStatement>) { super.init(name) Statements = statements } public convenience init(_ name: String, _ statements: CGStatement...) { init(name, statements.ToList()) } } public class CGInheritedExpression: CGExpression { public static lazy let Inherited = CGInheritedExpression() } public class CGIfThenElseExpression: CGExpression { // aka Ternary operator public var Condition: CGExpression public var IfExpression: CGExpression public var ElseExpression: CGExpression? public init(_ condition: CGExpression, _ ifExpression: CGExpression, _ elseExpression: CGExpression?) { Condition = condition IfExpression= ifExpression ElseExpression = elseExpression } } /* public class CGSwitchExpression: CGExpression { //* Oxygene only */ //incomplete } public class CGSwitchExpressionCase : CGEntity { public var CaseExpression: CGExpression public var ResultExpression: CGExpression public init(_ caseExpression: CGExpression, _ resultExpression: CGExpression) { CaseExpression = caseExpression ResultExpression = resultExpression } } public class CGForToLoopExpression: CGExpression { //* Oxygene only */ //incomplete } public class CGForEachLoopExpression: CGExpression { //* Oxygene only */ //incomplete } */ public class CGPointerDereferenceExpression: CGExpression { public var PointerExpression: CGExpression public init(_ pointerExpression: CGExpression) { PointerExpression = pointerExpression } } public class CGParenthesesExpression: CGExpression { public var Value: CGExpression public init(_ value: CGExpression) { Value = value } } public class CGRangeExpression: CGExpression { public var StartValue: CGExpression public var EndValue: CGExpression public init(_ startValue: CGExpression, _ endValue: CGExpression) { StartValue = startValue EndValue = endValue } } public class CGUnaryOperatorExpression: CGExpression { public var Value: CGExpression public var Operator: CGUnaryOperatorKind? // for standard operators public var OperatorString: String? // for custom operators public init(_ value: CGExpression, _ `operator`: CGUnaryOperatorKind) { Value = value Operator = `operator` } public init(_ value: CGExpression, _ operatorString: String) { Value = value OperatorString = operatorString } public static func NotExpression(_ value: CGExpression) -> CGUnaryOperatorExpression { return CGUnaryOperatorExpression(value, CGUnaryOperatorKind.Not) } } public enum CGUnaryOperatorKind { case Plus case Minus case Not case AddressOf case ForceUnwrapNullable case BitwiseNot } public class CGBinaryOperatorExpression: CGExpression { public var LefthandValue: CGExpression public var RighthandValue: CGExpression public var Operator: CGBinaryOperatorKind? // for standard operators public var OperatorString: String? // for custom operators public init(_ lefthandValue: CGExpression, _ righthandValue: CGExpression, _ `operator`: CGBinaryOperatorKind) { LefthandValue = lefthandValue RighthandValue = righthandValue Operator = `operator` } public init(_ lefthandValue: CGExpression, _ righthandValue: CGExpression, _ operatorString: String) { LefthandValue = lefthandValue RighthandValue = righthandValue OperatorString = operatorString } } public enum CGBinaryOperatorKind { case Concat // string concat, can be different than + case Addition case Subtraction case Multiplication case Division case LegacyPascalDivision // "div" case Modulus case Equals case NotEquals case LessThan case LessThanOrEquals case GreaterThan case GreatThanOrEqual case LogicalAnd case LogicalOr case LogicalXor case Shl case Shr case BitwiseAnd case BitwiseOr case BitwiseXor case Implies /* Oxygene only */ case Is case IsNot case In /* Oxygene only */ case NotIn /* Oxygene only */ case Assign case AssignAddition case AssignSubtraction case AssignMultiplication case AssignDivision /*case AssignModulus case AssignBitwiseAnd case AssignBitwiseOr case AssignBitwiseXor case AssignShl case AssignShr*/ case AddEvent case RemoveEvent } /* Literal Expressions */ public class CGNamedIdentifierExpression: CGExpression { public var Name: String public init(_ name: String) { Name = name } } public class CGSelfExpression: CGExpression { // "self" or "this" public static lazy let `Self` = CGSelfExpression() } public class CGResultExpression: CGExpression { // "result" public static lazy let Result = CGResultExpression() } public class CGNilExpression: CGExpression { // "nil" or "null" public static lazy let Nil = CGNilExpression() } public class CGPropertyValueExpression: CGExpression { /* "value" or "newValue" in C#/Swift */ public static lazy let PropertyValue = CGPropertyValueExpression() } public class CGLiteralExpression: CGExpression { } public __abstract class CGLanguageAgnosticLiteralExpression: CGExpression { internal __abstract func StringRepresentation() -> String } public class CGStringLiteralExpression: CGLiteralExpression { public var Value: String = "" public static lazy let Empty: CGStringLiteralExpression = "".AsLiteralExpression() public static lazy let Space: CGStringLiteralExpression = " ".AsLiteralExpression() public init() { } public init(_ value: String) { Value = value } } public class CGCharacterLiteralExpression: CGLiteralExpression { public var Value: Char = "\0" //public static lazy let Zero: CGCharacterLiteralExpression = "\0".AsLiteralExpression() public static lazy let Zero = CGCharacterLiteralExpression("\0") public init() { } public init(_ value: Char) { Value = value } } public class CGIntegerLiteralExpression: CGLanguageAgnosticLiteralExpression { public var SignedValue: Int64? = nil { didSet { if SignedValue != nil { UnsignedValue = nil } } } public var UnsignedValue: Int64? = nil { didSet { if UnsignedValue != nil { SignedValue = nil } } } @Obsolete public var Value: Int64 { return coalesce(SignedValue, UnsignedValue, 0) } public var Base = 10 public var NumberKind: CGNumberKind? public static lazy let Zero: CGIntegerLiteralExpression = 0.AsLiteralExpression() public init() { } public init(_ value: Int64) { SignedValue = value } public init(_ value: Int64, # base: Int32) { SignedValue = value Base = base } public init(_ value: UInt64) { UnsignedValue = value } public init(_ value: UInt64, # base: Int32) { UnsignedValue = value Base = base } override func StringRepresentation() -> String { return StringRepresentation(base: Base) } internal func StringRepresentation(base: Int32) -> String { if let SignedValue = SignedValue { return Convert.ToString(SignedValue, base) } else if let UnsignedValue = UnsignedValue { return Convert.ToString(UnsignedValue, base) } else { return Convert.ToString(0, base) } } } public class CGFloatLiteralExpression: CGLanguageAgnosticLiteralExpression { public private(set) var DoubleValue: Double? public private(set) var IntegerValue: Integer? public private(set) var StringValue: String? public var NumberKind: CGNumberKind? public var Base = 10 // Swift only public static lazy let Zero: CGFloatLiteralExpression = CGFloatLiteralExpression(0) public init() { } public init(_ value: Double) { DoubleValue = value } public init(_ value: Integer) { IntegerValue = value } public init(_ value: String) { StringValue = value } override func StringRepresentation() -> String { return StringRepresentation(base: 10) } internal func StringRepresentation(# base: Int32) -> String { switch base { case 10: if let value = DoubleValue { var result = Convert.ToStringInvariant(value) let any: Char[] = [".", "E", "e"] if !result.ContainsAny(any) { result += ".0"; } return result } else if let value = IntegerValue { return value.ToString()+".0" } else if let value = StringValue { if value.IndexOf(".") > -1 || value.ToLower().IndexOf("e") > -1 { return value } else { return value+".0" } } else { return "0.0" } case 16: if DoubleValue != nil { throw Exception("base 16 (Hex) float literals with double value are not currently supported.") } else if let value = IntegerValue { return Convert.ToString(value, base)+".0" } else if let value = StringValue { if value.IndexOf(".") > -1 || value.ToLower().IndexOf("p") > -1 { return value } else { return value+".0" } } else { return "0.0" } default: throw Exception("Base \(base) float literals are not currently supported.") } } } public class CGImaginaryLiteralExpression: CGFloatLiteralExpression { internal override func StringRepresentation(# base: Int32) -> String { return super.StringRepresentation(base: base)+"i"; } } public enum CGNumberKind { case Unsigned, Long, UnsignedLong, Float, Double, Decimal } public class CGBooleanLiteralExpression: CGLanguageAgnosticLiteralExpression { public let Value: Boolean public static lazy let True = CGBooleanLiteralExpression(true) public static lazy let False = CGBooleanLiteralExpression(false) public convenience init() { init(false) } public init(_ bool: Boolean) { Value = bool } override func StringRepresentation() -> String { if Value { return "true" } else { return "false" } } } public class CGArrayLiteralExpression: CGExpression { public var Elements: List<CGExpression> public var ElementType: CGTypeReference? //c++ only at this moment public var ArrayKind: CGArrayKind = .Dynamic public init() { Elements = List<CGExpression>() } public init(_ elements: List<CGExpression>) { Elements = elements } public init(_ elements: List<CGExpression>, _ type: CGTypeReference) { Elements = elements ElementType = type } public convenience init(_ elements: CGExpression...) { init(elements.ToList()) } } public class CGSetLiteralExpression: CGExpression { public var Elements: List<CGExpression> public var ElementType: CGTypeReference? public init() { Elements = List<CGExpression>() } public init(_ elements: List<CGExpression>) { Elements = elements } public init(_ elements: List<CGExpression>, _ type: CGTypeReference) { Elements = elements ElementType = type } public convenience init(_ elements: CGExpression...) { init(elements.ToList()) } } public class CGDictionaryLiteralExpression: CGExpression { /* Swift only, currently */ public var Keys: List<CGExpression> public var Values: List<CGExpression> public init() { Keys = List<CGExpression>() Values = List<CGExpression>() } public init(_ keys: List<CGExpression>, _ values: List<CGExpression>) { Keys = keys Values = values } public convenience init(_ keys: CGExpression[], _ values: CGExpression[]) { init(keys.ToList(), values.ToList()) } } public class CGTupleLiteralExpression : CGExpression { public var Members: List<CGExpression> public init(_ members: List<CGExpression>) { Members = members } public convenience init(_ members: CGExpression...) { init(members.ToList()) } } /* Calls */ public class CGNewInstanceExpression : CGExpression { public var `Type`: CGExpression public var ConstructorName: String? // can optionally be provided for languages that support named .ctors (Elements, Objectice-C, Swift) public var Parameters: List<CGCallParameter> public var ArrayBounds: List<CGExpression>? // for array initialization. public var PropertyInitializers = List<CGPropertyInitializer>() // for Oxygene and C# extended .ctor calls public convenience init(_ type: CGTypeReference) { init(type.AsExpression()) } public convenience init(_ type: CGTypeReference, _ parameters: List<CGCallParameter>) { init(type.AsExpression(), parameters) } public convenience init(_ type: CGTypeReference, _ parameters: CGCallParameter...) { init(type.AsExpression(), parameters) } public init(_ type: CGExpression) { `Type` = type Parameters = List<CGCallParameter>() } public init(_ type: CGExpression, _ parameters: List<CGCallParameter>) { `Type` = type Parameters = parameters } public convenience init(_ type: CGExpression, _ parameters: CGCallParameter...) { init(type, parameters.ToList()) } } public class CGDestroyInstanceExpression : CGExpression { public var Instance: CGExpression; public init(_ instance: CGExpression) { Instance = instance; } } public class CGLocalVariableAccessExpression : CGExpression { public var Name: String public var NilSafe: Boolean = false // true to use colon or elvis operator public var UnwrapNullable: Boolean = false // Swift only public init(_ name: String) { Name = name } } public enum CGCallSiteKind { case Unspecified case Static case Instance case Reference } public __abstract class CGMemberAccessExpression : CGExpression { public var CallSite: CGExpression? // can be nil to call a local or global function/variable. Should be set to CGSelfExpression for local methods. public var Name: String public var NilSafe: Boolean = false // true to use colon or elvis operator public var UnwrapNullable: Boolean = false // Swift only public var CallSiteKind: CGCallSiteKind = .Unspecified //C++ only public init(_ callSite: CGExpression?, _ name: String) { CallSite = callSite Name = name } } public class CGFieldAccessExpression : CGMemberAccessExpression { } public class CGEventAccessExpression : CGFieldAccessExpression { } public class CGEnumValueAccessExpression : CGExpression { public var `Type`: CGTypeReference public var ValueName: String public init(_ type: CGTypeReference, _ valueName: String) { `Type` = type ValueName = valueName } } public class CGMethodCallExpression : CGMemberAccessExpression{ public var Parameters: List<CGCallParameter> public var GenericArguments: List<CGTypeReference>? public var CallOptionally: Boolean = false // Swift only public init(_ callSite: CGExpression?, _ name: String) { super.init(callSite, name) Parameters = List<CGCallParameter>() } public init(_ callSite: CGExpression?, _ name: String, _ parameters: List<CGCallParameter>?) { super.init(callSite, name) if let parameters = parameters { Parameters = parameters } else { Parameters = List<CGCallParameter>() } } public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) { init(callSite, name, List<CGCallParameter>(parameters)) } } public class CGPropertyAccessExpression: CGMemberAccessExpression { public var Parameters: List<CGCallParameter> public init(_ callSite: CGExpression?, _ name: String, _ parameters: List<CGCallParameter>?) { super.init(callSite, name) if let parameters = parameters { Parameters = parameters } else { Parameters = List<CGCallParameter>() } } public convenience init(_ callSite: CGExpression?, _ name: String, _ parameters: CGCallParameter...) { init(callSite, name, List<CGCallParameter>(parameters)) } } public class CGCallParameter: CGEntity { public var Name: String? // optional, for named parameters or prooperty initialziers public var Value: CGExpression public var Modifier: CGParameterModifierKind = .In public var EllipsisParameter: Boolean = false // used mainly for Objective-C, wioch needs a different syntax when passing elipsis paframs public init(_ value: CGExpression) { Value = value } public init(_ value: CGExpression, _ name: String) { //public init(value) // 71582: Silver: delegating to a second .ctor doesn't properly detect that a field will be initialized Value = value Name = name } } public class CGPropertyInitializer: CGEntity { public var Name: String public var Value: CGExpression public init(_ name: String, _ value: CGExpression) { Value = value Name = name } } public class CGArrayElementAccessExpression: CGExpression { public var Array: CGExpression public var Parameters: List<CGExpression> public init(_ array: CGExpression, _ parameters: List<CGExpression>) { Array = array Parameters = parameters } public convenience init(_ array: CGExpression, _ parameters: CGExpression...) { init(array, parameters.ToList()) } } public class CGYieldExpression: CGExpression { public var Value: CGExpression public init(_ value: CGExpression) { Value = value } } public class CGThrowExpression: CGExpression { public var Exception: CGExpression? public init() { } public init(_ exception: CGExpression?) { Exception = exception } }
25.997491
147
0.744595
bff7ffc1fdd5deb836590bfa4f38a313e9e16cc1
275
// // OrderableManagedObject.swift // BrainKit // // Created by Ondřej Hanák on 09. 08. 2021. // Copyright © 2021 Userbrain. All rights reserved. // import CoreData import Foundation public protocol OrderableManagedObject: NSManagedObject { var ord: Int32 { get } }
16.176471
57
0.723636
2f2782d540e67ecd7cf6e2f0a8e88388d578b93b
1,558
import Foundation protocol URLProviderProtocol { func url() -> URL func rss() -> URL } class BaseURLProvider { var key: String init(key: String) { self.key = key } static func baseUrl() -> URL { return URL(string: "https://weworkremotely.com")! } } class URLProviderFactory { var isTesting: Bool init(isTesting: Bool? = Platform.isRunningTests()) { self.isTesting = isTesting! } func build(key: String) -> URLProviderProtocol { if isTesting { return Testing(key: key) } else { return Running(key: key) } } class Testing: BaseURLProvider, URLProviderProtocol { static var testingHits: [String: String] = [:] func url() -> URL { Testing.testingHits[key] = testingFile() return FileLoader.load(name: Testing.testingHits[key]!, type: "xml") } func rss() -> URL { return url() } private func testingFile() -> String { if Testing.testingHits[key] == nil { return "jobs" } else { return "jobs-other" } } } class Running: BaseURLProvider, URLProviderProtocol { func url() -> URL { return BaseURLProvider .baseUrl() .appendingPathComponent("categories") .appendingPathComponent(key) } func rss() -> URL { return url().appendingPathExtension("rss") } } }
22.57971
80
0.528883
62531a56c8c8db2afe34842c84c9f1a2b403ddd0
453
/** Appearance object used for high contrast or dark mode images. */ public protocol Appearance: Hashable { /** The type of appearance object. */ var appearance: String { get } /** The value of the appearance object. */ var value: String { get } } public extension Appearance { /** Type erases the Appearance object. */ func eraseToAny() -> AnyAppearance { AnyAppearance(appearance: appearance, value: value) } }
19.695652
63
0.662252
61e7d7b135f6bab903693a7c3043e920fc9b483e
978
// // TipCalcutatorTests.swift // TipCalcutatorTests // // Created by Nour on 12/9/15. // Copyright © 2015 Nour. All rights reserved. // import XCTest @testable import Tiptobot class TipCalcutatorTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
26.432432
111
0.637014
1c59310e656d6988f57ad0c0b42487522e4ee8ab
357
// // Configuration.swift // recipe.ios // // Created by Shaun Sargent on 10/8/16. // Copyright © 2016 My Family Cooks. All rights reserved. // import Foundation public struct Configuration{ // TODO: pull these from the pList. static var webUrl: String{ get{ return "http://192.168.86.33:60679" } } }
17
58
0.596639
088a644384ff6aeb1da1817338bc5c800bc70d63
6,094
// RUN: %target-swift-frontend -typecheck -dump-type-refinement-contexts %s > %t.dump 2>&1 // RUN: %FileCheck --strict-whitespace %s < %t.dump // REQUIRES: OS=macosx // CHECK: {{^}}(root versions=[10.{{[0-9]+}}.0,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=SomeClass // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someMethod() // CHECK-NEXT: {{^}} (decl versions=[10.53,+Inf) decl=someInnerFunc() // CHECK-NEXT: {{^}} (decl versions=[10.53,+Inf) decl=InnerClass // CHECK-NEXT: {{^}} (decl versions=[10.54,+Inf) decl=innerClassMethod // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someStaticProperty // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someComputedProperty // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someOtherMethod() @available(OSX 10.51, *) class SomeClass { @available(OSX 10.52, *) func someMethod() { @available(OSX 10.53, *) func someInnerFunc() { } @available(OSX 10.53, *) class InnerClass { @available(OSX 10.54, *) func innerClassMethod() { } } } func someUnrefinedMethod() { } @available(OSX 10.52, *) static var someStaticProperty: Int = 7 @available(OSX 10.52, *) var someComputedProperty: Int { get { } set(v) { } } @available(OSX 10.52, *) func someOtherMethod() { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=someFunction() @available(OSX 10.51, *) func someFunction() { } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=SomeProtocol // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=protoMethod() // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=protoProperty @available(OSX 10.51, *) protocol SomeProtocol { @available(OSX 10.52, *) func protoMethod() -> Int @available(OSX 10.52, *) var protoProperty: Int { get } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=extension.SomeClass // CHECK-NEXT: {{^}} (decl versions=[10.52,+Inf) decl=someExtensionFunction() @available(OSX 10.51, *) extension SomeClass { @available(OSX 10.52, *) func someExtensionFunction() { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithStmtCondition // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.55,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.55,+Inf) decl=funcInGuardElse() // CHECK-NEXT: {{^}} (guard_fallthrough versions=[10.55,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.56,+Inf) // CHECK-NEXT: {{^}} (guard_fallthrough versions=[10.56,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.57,+Inf) decl=funcInInnerIfElse() @available(OSX 10.51, *) func functionWithStmtCondition() { if #available(OSX 10.52, *), let x = (nil as Int?), #available(OSX 10.53, *) { if #available(OSX 10.54, *) { guard #available(OSX 10.55, *) else { @available(OSX 10.55, *) func funcInGuardElse() { } } guard #available(OSX 10.56, *) else { } } else { @available(OSX 10.57, *) func funcInInnerIfElse() { } } } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithUnnecessaryStmtCondition // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.53,+Inf) // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.54,+Inf) // CHECK-NEXT: {{^}} (if_then versions=[10.54,+Inf) @available(OSX 10.51, *) func functionWithUnnecessaryStmtCondition() { // Shouldn't introduce refinement context for then branch when unnecessary if #available(OSX 10.51, *) { } if #available(OSX 10.9, *) { } // Nested in conjunctive statement condition if #available(OSX 10.53, *), let x = (nil as Int?), #available(OSX 10.52, *) { } if #available(OSX 10.54, *), #available(OSX 10.54, *) { } // Wildcard is same as minimum deployment target if #available(iOS 7.0, *) { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithUnnecessaryStmtConditionsHavingElseBranch // CHECK-NEXT: {{^}} (if_else versions=empty // CHECK-NEXT: {{^}} (decl versions=empty decl=funcInInnerIfElse() // CHECK-NEXT: {{^}} (if_else versions=empty // CHECK-NEXT: {{^}} (guard_else versions=empty // CHECK-NEXT: {{^}} (guard_else versions=empty // CHECK-NEXT: {{^}} (if_else versions=empty @available(OSX 10.51, *) func functionWithUnnecessaryStmtConditionsHavingElseBranch(p: Int?) { // Else branch context version is bottom when check is unnecessary if #available(OSX 10.51, *) { } else { if #available(OSX 10.52, *) { } @available(OSX 10.52, *) func funcInInnerIfElse() { } if #available(iOS 7.0, *) { } else { } } if #available(iOS 7.0, *) { } else { } guard #available(iOS 8.0, *) else { } // Else branch will execute if p is nil, so it is not dead. if #available(iOS 7.0, *), let x = p { } else { } if #available(iOS 7.0, *), let x = p, #available(iOS 7.0, *) { } else { } // Else branch is dead guard #available(iOS 7.0, *), #available(iOS 8.0, *) else { } if #available(OSX 10.51, *), #available(OSX 10.51, *) { } else { } } // CHECK-NEXT: {{^}} (decl versions=[10.51,+Inf) decl=functionWithWhile() // CHECK-NEXT: {{^}} (condition_following_availability versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (while_body versions=[10.52,+Inf) // CHECK-NEXT: {{^}} (decl versions=[10.54,+Inf) decl=funcInWhileBody() @available(OSX 10.51, *) func functionWithWhile() { while #available(OSX 10.52, *), let x = (nil as Int?) { @available(OSX 10.54, *) func funcInWhileBody() { } } }
31.251282
108
0.613062
1627367059694eab4ed346f6b1ef6b96b1257358
3,075
// // BaseCollectionCell.swift // DoorRush // // Created by edwin on 03/06/2020. // Copyright © 2020 edwin. All rights reserved. // import UIKit class BaseCollectionCell: UICollectionViewCell, ReuseIdentifying { var leftConstraint: NSLayoutConstraint? var trailingConstraint: NSLayoutConstraint? var topConstraint: NSLayoutConstraint? var bottomConstraint: NSLayoutConstraint? override init(frame: CGRect) { super.init(frame: frame) setupViews() registerClass() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } let collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.backgroundColor = .white collectionView.showsHorizontalScrollIndicator = false collectionView.translatesAutoresizingMaskIntoConstraints = false return collectionView }() func setupViews() { addSubview(collectionView) collectionView.delegate = self collectionView.dataSource = self leftConstraint = collectionView.leftAnchor.constraint(equalTo: leftAnchor) leftConstraint?.isActive = true topConstraint = collectionView.topAnchor.constraint(equalTo: topAnchor) topConstraint?.isActive = true trailingConstraint = collectionView.rightAnchor.constraint(equalTo: rightAnchor) trailingConstraint?.isActive = true bottomConstraint = collectionView.bottomAnchor.constraint(equalTo: bottomAnchor) bottomConstraint?.isActive = true } func registerClass() { collectionView.register(BaseCell.self, forCellWithReuseIdentifier: BaseCell.reuseIdentifier) } } extension BaseCollectionCell: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: BaseCell.reuseIdentifier, for: indexPath) as! BaseCell return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { CGSize(width: collectionView.frame.width / 4, height: collectionView.frame.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 14, bottom: 0, right: 14) } }
36.607143
162
0.71252
897c0d48f6cea936bb4a200d4db6c0cb6b8bf288
7,012
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ import AVFoundation import CAudioKit /// Super-naive code to read a .sfz file, as produced by vonRed's free ESX24-to-SFZ program /// See https://bitbucket.org/vonred/exstosfz/downloads/ (you'll need Python 3 to run it). extension Sampler { /// Load an SFZ at the given location /// /// Parameters: /// - path: Path to the file as a string /// - fileName: Name of the SFZ file /// internal func loadSFZ(path: String, fileName: String) { loadSFZ(url: URL(fileURLWithPath: path).appendingPathComponent(fileName)) } /// Load an SFZ at the given location /// /// Parameters: /// - url: File url to the SFZ file /// public func loadSFZ(url: URL) { stopAllVoices() unloadAllSamples() var lowNoteNumber: MIDINoteNumber = 0 var highNoteNumber: MIDINoteNumber = 127 var noteNumber: MIDINoteNumber = 60 var lowVelocity: MIDIVelocity = 0 var highVelocity: MIDIVelocity = 127 var sample: String = "" var loopMode: String = "" var loopStartPoint: Float32 = 0 var loopEndPoint: Float32 = 0 let samplesBaseURL = url.deletingLastPathComponent() do { let data = try String(contentsOf: url, encoding: .ascii) let lines = data.components(separatedBy: .newlines) for line in lines { let trimmed = String(line.trimmingCharacters(in: .whitespacesAndNewlines)) if trimmed == "" || trimmed.hasPrefix("//") { // ignore blank lines and comment lines continue } if trimmed.hasPrefix("<group>") { // parse a <group> line for part in trimmed.dropFirst(7).components(separatedBy: .whitespaces) { if part.hasPrefix("key") { noteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0 lowNoteNumber = noteNumber highNoteNumber = noteNumber } else if part.hasPrefix("lokey") { lowNoteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("hikey") { highNoteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("pitch_keycenter") { noteNumber = MIDINoteNumber(part.components(separatedBy: "=")[1]) ?? 0 } } } if trimmed.hasPrefix("<region>") { // parse a <region> line for part in trimmed.dropFirst(8).components(separatedBy: .whitespaces) { if part.hasPrefix("lovel") { lowVelocity = MIDIVelocity(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("hivel") { highVelocity = MIDIVelocity(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("loop_mode") { loopMode = part.components(separatedBy: "=")[1] } else if part.hasPrefix("loop_start") { loopStartPoint = Float32(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("loop_end") { loopEndPoint = Float32(part.components(separatedBy: "=")[1]) ?? 0 } else if part.hasPrefix("sample") { sample = trimmed.components(separatedBy: "sample=")[1] } } let noteFrequency = Float(440.0 * pow(2.0, (Double(noteNumber) - 69.0) / 12.0)) let noteLog = "load \(noteNumber) \(noteFrequency) NN range \(lowNoteNumber)-\(highNoteNumber)" Log("\(noteLog) vel \(lowVelocity)-\(highVelocity) \(sample)") let sampleDescriptor = SampleDescriptor(noteNumber: Int32(noteNumber), noteFrequency: noteFrequency, minimumNoteNumber: Int32(lowNoteNumber), maximumNoteNumber: Int32(highNoteNumber), minimumVelocity: Int32(lowVelocity), maximumVelocity: Int32(highVelocity), isLooping: loopMode != "", loopStartPoint: loopStartPoint, loopEndPoint: loopEndPoint, startPoint: 0.0, endPoint: 0.0) sample = sample.replacingOccurrences(of: "\\", with: "/") let sampleFileURL = samplesBaseURL .appendingPathComponent(sample) if sample.hasSuffix(".wv") { sampleFileURL.path.withCString { path in loadCompressedSampleFile(from: SampleFileDescriptor(sampleDescriptor: sampleDescriptor, path: path)) } } else { if sample.hasSuffix(".aif") || sample.hasSuffix(".wav") { let compressedFileURL = samplesBaseURL .appendingPathComponent(String(sample.dropLast(4) + ".wv")) let fileMgr = FileManager.default if fileMgr.fileExists(atPath: compressedFileURL.path) { compressedFileURL.path.withCString { path in loadCompressedSampleFile( from: SampleFileDescriptor(sampleDescriptor: sampleDescriptor, path: path)) } } else { let sampleFile = try AVAudioFile(forReading: sampleFileURL) loadAudioFile(from: sampleDescriptor, file: sampleFile) } } } } } } catch { Log("Could not load SFZ: \(error.localizedDescription)") } buildKeyMap() restartVoices() } }
51.182482
115
0.463349
7991f231d16722aff87c5c60a289d35516b2381c
1,201
// // ViewController.swift // PQTransitionDemo // // Created by pgq on 2019/12/9. // Copyright © 2019 pgq. All rights reserved. // import UIKit import PQTransition class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let v2 = ViewController2(transition: PQTransition(type: .bottomPush, presentFrame: CGRect(x: 0, y: UIScreen.main.bounds.height - 300, width: UIScreen.main.bounds.width, height: 300), duration: 0.25)) present(v2, animated: true, completion: nil) } } class ViewController2: UIViewController { let transition: PQTransition init(transition: PQTransition) { self.transition = transition super.init(nibName: nil, bundle: nil) self.modalPresentationStyle = .custom self.transitioningDelegate = transition self.view.backgroundColor = .systemRed } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() } }
23.54902
207
0.646961
f5f419812909d55bf4a6c1c4c7697eb5e969b852
985
// // ViewController.swift // BezierPathRealWorldExample // // Created by Gokhan Gultekin on 11.11.2018. // Copyright © 2018 Gokhan. All rights reserved. // import UIKit import GGShadowedView class ViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var infoView: UIView! @IBOutlet weak var profileView: UIView! override func viewDidLoad() { super.viewDidLoad() profileImageView.layer.cornerRadius = profileImageView.frame.width/2 profileImageView.layer.masksToBounds = true infoView.layer.cornerRadius = 24 infoView.layer.masksToBounds = true profileView.dropShadow() } } extension UIView { func dropShadow() { layer.masksToBounds = false layer.shadowOffset = CGSize(width: 0, height: 0); layer.shadowOpacity = 0.70 layer.shadowRadius = 12 layer.shadowColor = UIColor.lightGray.cgColor } }
24.02439
76
0.675127
d773bf631aa06233303dd6fcc4b4ac53be53a3fd
638
// // Singer+CoreDataProperties.swift // P12F CoreDataProject // // Created by Julian Moorhouse on 03/04/2021. // // import Foundation import CoreData extension Singer { @nonobjc public class func fetchRequest() -> NSFetchRequest<Singer> { return NSFetchRequest<Singer>(entityName: "Singer") } @NSManaged public var timestamp: Date? @NSManaged public var firstName: String? @NSManaged public var lastName: String? var wrappedFirstName: String { firstName ?? "Unknown" } var wrappedLastName: String { lastName ?? "Unknown" } } extension Singer : Identifiable { }
18.228571
73
0.667712
8aea6ab34a2c9fe350723feb0326df01759be637
427
// // AppDelegate.swift // JWSMVVMSample // // Created by Clint on 2018. 2. 19.. // Copyright © 2018년 clint. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return true } }
22.473684
144
0.723653
f474240a6c95d56df6e1d5f614c4b6f58725304d
1,139
// // UserDefaultWrapper.swift // FoodLuxMea // // Created by SEONG YEOL YI on 2020/10/17. // import Foundation @propertyWrapper struct AutoSave<T: Codable> { private let key: String private let defaultValue: T init(_ key: String, defaultValue: T) { self.key = key self.defaultValue = defaultValue } var wrappedValue: T { get { // Read value from UserDefaults guard let data = UserDefaults.snuYum.object(forKey: key) as? Data else { // Return defaultValue when no data in UserDefaults return defaultValue } // Convert data to the desire data type let value = try? JSONDecoder().decode(T.self, from: data) return value ?? defaultValue } set { // Convert newValue to data let data = try? JSONEncoder().encode(newValue) // Set value to UserDefaults UserDefaults.snuYum.set(data, forKey: key) } } } extension UserDefaults { static let snuYum = UserDefaults(suiteName: "group.com.wannasleep.FoodLuxMea")! }
25.886364
84
0.593503
76f2a55446dbef92fdc749fe0241db2778eb99d1
3,002
// // Copyright (c) 2020 Related Code - http://relatedcode.com // // 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 MessageKit //------------------------------------------------------------------------------------------------------------------------------------------------- class MKAudioLoader: NSObject { //--------------------------------------------------------------------------------------------------------------------------------------------- class func start(_ mkmessage: MKMessage, in messagesCollectionView: MessagesCollectionView) { if let path = MediaDownload.pathAudio(mkmessage.messageId) { showMedia(mkmessage, path: path) } else { loadMedia(mkmessage, in: messagesCollectionView) } } //--------------------------------------------------------------------------------------------------------------------------------------------- class func manual(_ mkmessage: MKMessage, in messagesCollectionView: MessagesCollectionView) { MediaDownload.clearManualAudio(mkmessage.messageId) downloadMedia(mkmessage, in: messagesCollectionView) messagesCollectionView.reloadData() } //--------------------------------------------------------------------------------------------------------------------------------------------- private class func loadMedia(_ mkmessage: MKMessage, in messagesCollectionView: MessagesCollectionView) { let network = Persons.networkAudio() if (network == NETWORK_MANUAL) || ((network == NETWORK_WIFI) && (Connectivity.isReachableViaWiFi() == false)) { mkmessage.mediaStatus = MEDIASTATUS_MANUAL } else { downloadMedia(mkmessage, in: messagesCollectionView) } } //--------------------------------------------------------------------------------------------------------------------------------------------- private class func downloadMedia(_ mkmessage: MKMessage, in messagesCollectionView: MessagesCollectionView) { mkmessage.mediaStatus = MEDIASTATUS_LOADING MediaDownload.startAudio(mkmessage.messageId) { path, error in if (error == nil) { Cryptor.decrypt(path: path, chatId: mkmessage.chatId) showMedia(mkmessage, path: path) } else { mkmessage.mediaStatus = MEDIASTATUS_MANUAL } messagesCollectionView.reloadData() } } //--------------------------------------------------------------------------------------------------------------------------------------------- private class func showMedia(_ mkmessage: MKMessage, path: String) { mkmessage.audioItem?.url = URL(fileURLWithPath: path) mkmessage.mediaStatus = MEDIASTATUS_SUCCEED } }
42.885714
147
0.53964
f9aa8893b4a0acdcbf6228d8dce8dbfd2ddf2c38
1,415
// // AppDelegate.swift // BucketList // // Created by Robert Shrestha on 9/11/20. // Copyright © 2020 robert. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } // MARK: UISceneSession Lifecycle func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { // Called when a new scene session is being created. // Use this method to select a configuration to create the new scene with. return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) } func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) { // Called when the user discards a scene session. // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } }
37.236842
179
0.747703
e66fb60f7f61c95cdd3be38930bfb4239e1b7fca
5,374
/* * CalendarView+Delegate.swift * Created by Michael Michailidis on 24/10/2017. * http://blog.karmadust.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 extension CalendarView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let date = self.dateFromIndexPath(indexPath) else { return } if let index = selectedIndexPaths.firstIndex(of: indexPath) { delegate?.calendar(self, didDeselectDate: date) if enableDeselection { // bug: when deselecting the second to last item programmatically, during // didDeselectDate delegation, the index returned is out of the bounds of // the selectedIndexPaths array. This guard prevents the crash guard index < selectedIndexPaths.count, index < selectedDates.count else { return } selectedIndexPaths.remove(at: index) selectedDates.remove(at: index) } } else { if let currentCell = collectionView.cellForItem(at: indexPath) as? CalendarDayCell, currentCell.isOutOfRange || currentCell.isAdjacent { self.reloadData() return } if !multipleSelectionEnable { selectedIndexPaths.removeAll() selectedDates.removeAll() } selectedIndexPaths.append(indexPath) selectedDates.append(date) let eventsForDaySelected = eventsByIndexPath[indexPath] ?? [] delegate?.calendar(self, didSelectDate: date, withEvents: eventsForDaySelected) } self.reloadData() } public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard let dateBeingSelected = self.dateFromIndexPath(indexPath) else { return false } if let delegate = self.delegate { return delegate.calendar(self, canSelectDate: dateBeingSelected) } return true // default } // MARK: UIScrollViewDelegate public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.updateAndNotifyScrolling() } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { self.updateAndNotifyScrolling() } func updateAndNotifyScrolling() { guard let date = self.dateFromScrollViewPosition() else { return } self.displayDateOnHeader(date) self.delegate?.calendar(self, didScrollToMonth: date) } @discardableResult func dateFromScrollViewPosition() -> Date? { var page: Int = 0 switch self.direction { case .horizontal: let offsetX = ceilf(Float(self.collectionView.contentOffset.x)) let width = self.collectionView.bounds.size.width page = Int(floor(offsetX / Float(width))) case .vertical: let offsetY = ceilf(Float(self.collectionView.contentOffset.y)) let height = self.collectionView.bounds.size.height page = Int(floor(offsetY / Float(height))) @unknown default: fatalError() } page = page > 0 ? page : 0 var monthsOffsetComponents = DateComponents() monthsOffsetComponents.month = page return self.calendar.date(byAdding: monthsOffsetComponents, to: self.firstDayCache); } func displayDateOnHeader(_ date: Date) { let month = self.calendar.component(.month, from: date) // get month let formatter = DateFormatter() formatter.locale = style.locale formatter.timeZone = style.calendar.timeZone let monthName = formatter.standaloneMonthSymbols[(month-1) % 12].capitalized // 0 indexed array let year = self.calendar.component(.year, from: date) self.headerView.monthLabel.text = dataSource?.headerString(date) ?? monthName + " " + String(year) self.displayDate = date } }
38.113475
148
0.640677
e02a1bdf6899312a064bbd721af930e54e91a93c
4,416
// // NowPlayingViewController.swift // Flix // // Created by Mayank Gandhi on 27/07/18. // Copyright © 2018 Mayank Gandhi. All rights reserved. // import UIKit import AlamofireImage class NowPlayingViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var reloadIndicator: UIActivityIndicatorView! @IBOutlet weak var tableView: UITableView! var movies: [[String: Any]] = [] var refreshControl: UIRefreshControl! override func viewDidLoad() { super.viewDidLoad() refreshControl = UIRefreshControl() reloadIndicator.startAnimating() refreshControl.addTarget(self, action: #selector(NowPlayingViewController.didPulltoRefresh(_:)), for: .valueChanged) tableView.insertSubview(refreshControl, at: 0) tableView.dataSource = self self.tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 150 fetchMovies() // Do any additional setup after loading the view. } @objc func didPulltoRefresh(_ refreshControl: UIRefreshControl) { fetchMovies() } func fetchMovies() { let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed")! let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10) let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main) let task = session.dataTask(with: request) { (data, response, error) in // This will run when the network request returns if let error = error { print(error.localizedDescription) } else if let data = data { let dataDictionary = try! JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] let movies = dataDictionary["results"] as! [[String: Any]] self.movies = movies self.tableView.reloadData() self.refreshControl.endRefreshing() self.reloadIndicator.stopAnimating() for movie in movies { let title = movie["title"] as! String print(title) } // TODO: Get the array of movies // TODO: Store the movies in a property to use elsewhere // TODO: Reload your table view data } } task.resume() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movies.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCellTableViewCell let movie = movies[indexPath.row] let title = movie["title"] as! String tableView.rowHeight = UITableViewAutomaticDimension let overview = movie["overview"] as! String cell.titleLabel.text = title cell.overviewLabel.text = overview let PosterPathString = movie["poster_path"] as! String let baseURLString = "https://image.tmdb.org/t/p/w500" let PosterURL = URL(string: baseURLString + PosterPathString)! cell.posterImageView.af_setImage(withURL: PosterURL) return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let cell = sender as! UITableViewCell if let indexPath = tableView.indexPath(for: cell) { let movie = movies[indexPath.row] let detailview = segue.destination as! detailViewController detailview.movie = movie } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
37.109244
124
0.631793
d54e16cfef4a406117bbad3d1a65090018fd35ac
2,071
// // PcapngIdb.swift // // // Created by Darrell Root on 2/2/20. // import Foundation import Logging public struct PcapngCb: CustomStringConvertible { public let blockType: UInt32 public let blockLength: Int // encoded as UInt32 in header public let enterpriseNumber: Int public let customDataAndOptions: Data // TODO Options public var description: String { let output = String(format: "PcapngCb blockType 0x%x blockLength %d enterpriseNumber %d customDataCount %d\n",blockType, blockLength, enterpriseNumber, customDataAndOptions.count) return output } init?(data: Data, verbose: Bool = false) { guard data.count >= 16 && data.count % 4 == 0 else { Pcapng.logger.error("PcapCb Custom Block initializer: Invalid data.count \(data.count)") return nil } let blockType = Pcapng.getUInt32(data: data) guard blockType == 0xbad || blockType == 0x40000bad else { Pcapng.logger.error("Pcapngcb: Invalid blocktype \(blockType) should be 0xbad or 0x40000bad") return nil } self.blockType = blockType let blockLength = Int(Pcapng.getUInt32(data: data.advanced(by: 4))) guard data.count >= blockLength && blockLength % 4 == 0 else { Pcapng.logger.error("PcapngIdb initializer: invalid blockLength \(blockLength) data.count \(data.count)") return nil } self.blockLength = blockLength self.enterpriseNumber = Int(Pcapng.getUInt32(data: data.advanced(by: 8))) self.customDataAndOptions = data[data.startIndex + 12 ..< data.startIndex + blockLength - 4] let finalBlockLength = Pcapng.getUInt32(data: data.advanced(by: Int(blockLength) - 4)) guard finalBlockLength == blockLength else { Pcapng.logger.error("PcapngCb: firstBlockLength \(blockLength) does not match finalBlockLength \(blockLength)") return nil } if verbose { debugPrint(self.description) } } }
39.075472
187
0.645582
0986955382fc1c4c71e5cd738e2d4142e1e75872
1,807
// // Created by 蒋具宏 on 2020/10/27. // import Foundation import ImSDK /// 自定义信令监听 class CustomSignalingListener: NSObject, V2TIMSignalingListener { ///收到新邀请时 func onReceiveNewInvitation(_ inviteID: String!, inviter: String!, groupID: String!, inviteeList: [String]!, data: String!) { SwiftTencentImPlugin.invokeListener(type: ListenerType.ReceiveNewInvitation, params: [ "inviteID": inviteID, "inviter": inviter, "groupID": groupID, "inviteeList": inviteeList, "data": data, ]) } /// 被邀请者接受邀请 func onInviteeAccepted(_ inviteID: String!, invitee: String!, data: String!) { SwiftTencentImPlugin.invokeListener(type: ListenerType.InviteeAccepted, params: [ "inviteID": inviteID, "invitee": invitee, "data": data, ]) } /// 被邀请者拒绝邀请 func onInviteeRejected(_ inviteID: String!, invitee: String!, data: String!) { SwiftTencentImPlugin.invokeListener(type: ListenerType.InviteeRejected, params: [ "inviteID": inviteID, "invitee": invitee, "data": data, ]) } /// 邀请被取消 func onInvitationCancelled(_ inviteID: String!, inviter: String!, data: String!) { SwiftTencentImPlugin.invokeListener(type: ListenerType.InvitationCancelled, params: [ "inviteID": inviteID, "inviter": inviter, "data": data, ]) } /// 邀请超时 func onInvitationTimeout(_ inviteID: String!, inviteeList: [String]!) { SwiftTencentImPlugin.invokeListener(type: ListenerType.InvitationTimeout, params: [ "inviteID": inviteID, "inviteeList": inviteeList, ]) } }
31.701754
130
0.590481
0e0880c7ec1f17942b621c8d2fd9257401f6d2d7
2,227
// // ExampleBackgroundContentView.swift // ESTabBarControllerExample // // Created by lihao on 2017/2/9. // Copyright © 2017年 Vincent Li. All rights reserved. // import UIKit class ExampleBackgroundContentView: ExampleBasicContentView { override init(frame: CGRect) { super.init(frame: frame) textColor = UIColor.init(white: 165.0 / 255.0, alpha: 1.0) highlightTextColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) iconColor = UIColor.init(white: 165.0 / 255.0, alpha: 1.0) highlightIconColor = UIColor.init(white: 255.0 / 255.0, alpha: 1.0) backdropColor = UIColor.init(red: 37/255.0, green: 39/255.0, blue: 42/255.0, alpha: 1.0) highlightBackdropColor = UIColor.init(red: 22/255.0, green: 24/255.0, blue: 25/255.0, alpha: 1.0) } public convenience init(specialWithAutoImplies implies: Bool) { self.init(frame: CGRect.zero) textColor = .white highlightTextColor = .white iconColor = .white highlightIconColor = .white backdropColor = UIColor.init(red: 17/255.0, green: 86/255.0, blue: 136/255.0, alpha: 1.0) highlightBackdropColor = UIColor.init(red: 22/255.0, green: 24/255.0, blue: 25/255.0, alpha: 1.0) if implies { let timer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(ExampleBackgroundContentView.playImpliesAnimation(_:)), userInfo: nil, repeats: true) RunLoop.current.add(timer, forMode: .commonModes) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc internal func playImpliesAnimation(_ sender: AnyObject?) { if self.selected == true || self.highlighted == true { return } let view = self.imageView let impliesAnimation = CAKeyframeAnimation(keyPath: "transform.scale") impliesAnimation.values = [1.15, 0.8, 1.15] impliesAnimation.duration = 0.3 impliesAnimation.calculationMode = kCAAnimationCubic impliesAnimation.isRemovedOnCompletion = true view.layer.add(impliesAnimation, forKey: nil) } }
39.767857
183
0.647508
5bd9e1b7845f2b1634e866838b94f9456b45227d
275
import Foundation /// No Algorithm, i-e, insecure public final class NoneAlgorithm: JWAAlgorithm, SignAlgorithm, VerifyAlgorithm { public var name: String { return "none" } public init() {} public func sign(_ message: Data) -> Data { return Data() } }
17.1875
80
0.672727
e095f891739c1f58548299bcfb4770b8e089613e
862
import MiniApp extension ViewController { func getUserName() -> String? { guard let userProfile = getProfileSettings(), let userName = userProfile.displayName else { return nil } return userName } func getProfilePhoto() -> String? { guard let userProfile = getProfileSettings(), let userProfilePhoto = userProfile.profileImageURI else { return nil } return userProfilePhoto } func getAccessToken(miniAppId: String, completionHandler: @escaping (Result<MATokenInfo, MASDKCustomPermissionError>) -> Void) { guard let tokenInfo = getTokenInfo() else { completionHandler(.failure(.unknownError)) return } completionHandler(.success(.init(accessToken: tokenInfo.tokenString, expirationDate: tokenInfo.expiryDate))) } }
31.925926
132
0.658933
28426bf98c9ac0b7bc1575ef09a1eb1f33211908
21,939
// // CSV.swift // swift-csv // // Created by Matthias Hochgatterer on 02/06/2017. // Copyright © 2017 Matthias Hochgatterer. All rights reserved. // import Foundation public protocol ParserDelegate: class { /// Called when the parser begins parsing. func parserDidBeginDocument(_ parser: CSV.Parser) /// Called when the parser finished parsing without errors. func parserDidEndDocument(_ parser: CSV.Parser) /// Called when the parser begins parsing a line. func parser(_ parser: CSV.Parser, didBeginLineAt index: UInt) /// Called when the parser finished parsing a line. func parser(_ parser: CSV.Parser, didEndLineAt index: UInt) /// Called for every field in a line. func parser(_ parser: CSV.Parser, didReadFieldAt index: UInt, value: String) } extension String.Encoding { /// Unicode text data may start with a [byte order mark](https://en.wikipedia.org/wiki/Byte_order_mark) to specify the encoding and endianess. struct BOM { let encoding: String.Encoding init?(bom0: UInt8, bom1: UInt8, bom2: UInt8, bom3: UInt8) { switch (bom0, bom1, bom2, bom3) { case (0xEF, 0xBB, 0xBF, _): self.encoding = .utf8 case (0xFE, 0xFF, _, _): self.encoding = .utf16BigEndian case (0xFF, 0xFE, _, _): self.encoding = .utf16LittleEndian case (0x00, 0x00, 0xFE, 0xFF): self.encoding = .utf32BigEndian case (0xFF, 0xFE, 0x00, 0x00): self.encoding = .utf32LittleEndian default: return nil } } var length: Int { switch self.encoding { case String.Encoding.utf8: return 3 case String.Encoding.utf16BigEndian, String.Encoding.utf16LittleEndian: return 2 case String.Encoding.utf32BigEndian, String.Encoding.utf32LittleEndian: return 4 default: return 0 } } } } public struct CSVError: Error { public let description: String } public struct CSV { static let CarriageReturn: UnicodeScalar = "\r" static let LineFeed: UnicodeScalar = "\n" static let DoubleQuote: UnicodeScalar = "\"" static let Nul: UnicodeScalar = UnicodeScalar(0) /// Writes data in CSV format into an output stream. /// The writer uses the line feed "\n" character for line breaks. (Even though [RFC 4180](https://tools.ietf.org/html/rfc4180) specifies CRLF as line break characters.) public class Writer { let outputStream: OutputStream let configuration: CSV.Configuration internal let illegalCharacterSet: CharacterSet internal var maxNumberOfWrittenFields: Int? internal var numberOfWrittenLines: Int = 0 public init(outputStream: OutputStream, configuration: CSV.Configuration) { if outputStream.streamStatus == .notOpen { outputStream.open() } self.outputStream = outputStream self.configuration = configuration self.illegalCharacterSet = CharacterSet(charactersIn: "\(DoubleQuote)\(configuration.delimiter)\(CarriageReturn)\(LineFeed)") } /// Writes fields as a line to the output stream. public func writeLine(of fields: [String]) throws { if let count = self.maxNumberOfWrittenFields { if count != fields.count { throw CSVError(description: "Invalid number of fields") } } else { maxNumberOfWrittenFields = fields.count } if numberOfWrittenLines > 0 { self.writeNewLineCharacter() } let escapedValues = fields.map({ self.escapedValue(for: $0) }) let string = escapedValues.joined(separator: String(configuration.delimiter)) self.writeString(string) numberOfWrittenLines += 1 } internal func writeNewLineCharacter() { self.writeString(String(LineFeed)) } internal func escapedValue(for field: String) -> String { if let _ = field.rangeOfCharacter(from: illegalCharacterSet) { // A double quote must be preceded by another double quote let value = field.replacingOccurrences(of: String(DoubleQuote), with: "\"\"") // Quote fields containing illegal characters return "\"\(value)\"" } return field } internal func writeString(_ string: String) { if let data = string.data(using: configuration.encoding) { data.withUnsafeBytes({ (pointer: UnsafeRawBufferPointer) -> Void in if let bytes = pointer.bindMemory(to: UInt8.self).baseAddress { self.outputStream.write(bytes, maxLength: pointer.count) } }) } } } public class Parser { public weak var delegate: ParserDelegate? public let configuration: CSV.Configuration public var trimsWhitespaces: Bool = false // Reference to the file stream private let inputStream: InputStream // The buffer for field values private var fieldBuffer = [UInt8]() // The current row index private var row: UInt = 0 // The current column index private var column: UInt = 0 // Flag to know if the parser was cancelled. private var cancelled: Bool = false private enum State { case beginningOfDocument case endOfDocument case beginningOfLine case endOfLine case inField case inQuotedField case maybeEndOfQuotedField case endOfField } // The current parser state private var state: State = .beginningOfDocument { didSet { if oldValue == .beginningOfDocument { delegate?.parserDidBeginDocument(self) } switch (state) { case .endOfDocument: delegate?.parserDidEndDocument(self) case .beginningOfLine: delegate?.parser(self, didBeginLineAt: row) case .endOfLine: delegate?.parser(self, didEndLineAt: row) column = 0 row += 1 case .endOfField: let data = Data(fieldBuffer) let value: String if let string = String(data: data, encoding: configuration.encoding) { // Try to decode using the specified encoding value = string } else { value = String(cString: fieldBuffer + [0]) // cString requires '\0' at the end } fieldBuffer.removeAll() if !value.isEmpty && self.trimsWhitespaces { let trimmed = value.trimmingCharacters(in: CharacterSet.whitespaces) delegate?.parser(self, didReadFieldAt: column, value: trimmed) } else { delegate?.parser(self, didReadFieldAt: column, value: value) } column += 1 default: break } } } /// Initializes the parser with an url. /// /// - Paramter url: An url referencing a CSV file. public convenience init?(url: URL, configuration: CSV.Configuration) { guard let inputStream = InputStream(url: url) else { return nil } self.init(inputStream: inputStream, configuration: configuration) } /// Initializes the parser with a string. /// /// - Paramter string: A CSV string. public convenience init(string: String, configuration: CSV.Configuration) { self.init(data: string.data(using: .utf8)!, configuration: configuration) } /// Initializes the parser with data. /// /// - Paramter data: Data represeting CSV content. public convenience init(data: Data, configuration: CSV.Configuration) { self.init(inputStream: InputStream(data: data), configuration: configuration) } /// Initializes the parser with an input stream. /// /// - Paramter inputStream: An input stream of CSV data. public init(inputStream: InputStream, configuration: CSV.Configuration = CSV.Configuration(delimiter: ",")) { self.inputStream = inputStream self.configuration = configuration } /// Cancels the parser. public func cancel() { self.cancelled = true } /// Starts parsing the CSV data. Calling this method does nothing if the parser already finished parsing the data. /// /// - Throws: An error if the data doesn't conform to [RFC 4180](https://tools.ietf.org/html/rfc4180). public func parse() throws { guard self.state != .endOfDocument && !cancelled else { return } let reader = BufferedByteReader(inputStream: inputStream) // Consume bom if available if let bom0 = reader.peek(at: 0), let bom1 = reader.peek(at: 1), let bom2 = reader.peek(at: 2), let bom3 = reader.peek(at: 3) { if let bom = String.Encoding.BOM(bom0: bom0, bom1: bom1, bom2: bom2, bom3: bom3) { for _ in 0..<bom.length { let _ = reader.pop() } } } while !reader.isAtEnd { while let char = reader.pop(), !cancelled { let scalar = UnicodeScalar(char) // If we are at the begin of the data and there is a new character, we transition to the beginning of the line if state == .beginningOfDocument { state = .beginningOfLine } // If we are at the end of the line and there is a new character, we transition to the beginning of the line if state == .endOfLine { state = .beginningOfLine } switch scalar { case self.configuration.delimiter: switch state { case .beginningOfLine: state = .endOfField case .inField: state = .endOfField case .inQuotedField: fieldBuffer.append(char) case .maybeEndOfQuotedField: state = .endOfField case .endOfField: state = .endOfField default: assertionFailure("Invalid state") } case CSV.CarriageReturn: switch state { case .beginningOfLine: fallthrough case .inField: fallthrough case .maybeEndOfQuotedField: fallthrough case .endOfField: // If there is a \n after the carriage return, we read it. // But that's optional if let next = reader.peek(), UnicodeScalar(next) == "\n" { let _ = reader.pop() } state = .endOfField state = .endOfLine case .inQuotedField: fieldBuffer.append(char) default: assertionFailure("Invalid state") } case CSV.LineFeed: switch state { case .beginningOfLine: fallthrough case .inField: fallthrough case .maybeEndOfQuotedField: fallthrough case .endOfField: state = .endOfField state = .endOfLine case .inQuotedField: fieldBuffer.append(char) default: assertionFailure("Invalid state") } case CSV.DoubleQuote: switch state { case .beginningOfLine: state = .inQuotedField case .endOfField: state = .inQuotedField case .maybeEndOfQuotedField: fieldBuffer.append(char) state = .inQuotedField case .inField: Swift.print("Double quote unexpected in unquoted field") // Ignore error fieldBuffer.append(char) break case .inQuotedField: state = .maybeEndOfQuotedField default: assertionFailure("Invalid state") } case CSV.Nul: // Nul characters happen when characters are made up of more than 1 byte switch state { case .inField: fallthrough case .inQuotedField: if fieldBuffer.count > 0 { // Append to any existing character fieldBuffer.append(char) } default: break } default: // Any other characters switch state { case .beginningOfLine: fieldBuffer.append(char) state = .inField case .endOfField: fieldBuffer.append(char) state = .inField case .maybeEndOfQuotedField: // Skip values outside of quoted fields break case .inField: fieldBuffer.append(char) case .inQuotedField: fieldBuffer.append(char) default: assertionFailure("Invalid state") } } } if cancelled { return } // Transition to the correct state at the end of the document switch state { case .beginningOfDocument: // There was no data at all break case .endOfDocument: assertionFailure("Invalid state") case .beginningOfLine: break case .endOfLine: break case .endOfField: // Rows must not end with the delimieter // Therefore we there must be a new field before the end state = .inField state = .endOfField state = .endOfLine case .inField: state = .endOfField state = .endOfLine case .inQuotedField: throw CSVError(description: "Unexpected end of quoted field") case .maybeEndOfQuotedField: state = .endOfField state = .endOfLine } // Now we are at the end state = .endOfDocument } } } /// A configuration specifies the delimiter and encoding for parsing CSV data. public struct Configuration { public let delimiter: UnicodeScalar public let encoding: String.Encoding /// Returns a configuration by detecting the delimeter and text encoding from a file at an url. public static func detectConfigurationForContentsOfURL(_ url: URL) -> Configuration? { guard let stream = InputStream(url: url) else { return nil } return self.detectConfigurationForInputStream(stream) } /// Returns a configuration by detecting the delimeter and text encoding from the CSV input stream. public static func detectConfigurationForInputStream(_ stream: InputStream) -> Configuration? { if stream.streamStatus == .notOpen { stream.open() } let maxLength = 400 var buffer = Array<UInt8>(repeating: 0, count: maxLength) let length = stream.read(&buffer, maxLength: buffer.count) if let error = stream.streamError { print(error) return nil } var encoding: String.Encoding = .utf8 if length > 4, let bom = String.Encoding.BOM(bom0: buffer[0], bom1: buffer[1], bom2: buffer[2], bom3: buffer[3]) { encoding = bom.encoding buffer.removeFirst(bom.length) } let string: String if let decoded = String(bytes: buffer, encoding: encoding) { string = decoded } else if let macOSRoman = String(bytes: buffer, encoding: .macOSRoman) { string = macOSRoman encoding = .macOSRoman } else { return nil } let scanner = Scanner(string: string) var firstLine: NSString? = nil scanner.scanUpToCharacters(from: CharacterSet.newlines, into: &firstLine) guard let header = firstLine else { return nil } return self.detectConfigurationForString(header as String, encoding: encoding) } /// Returns a configuration by detecting the delimeter and text encoding from a CSV string. public static func detectConfigurationForString(_ string: String, encoding: String.Encoding) -> Configuration { struct Delimiter { let scalar: UnicodeScalar let weight: Int } let delimiters = [",", ";", "\t"].map({ Delimiter(scalar: UnicodeScalar($0)!, weight: string.components(separatedBy: $0).count) }) let winner = delimiters.sorted(by: { lhs, rhs in return lhs.weight > rhs.weight }).first! return Configuration(delimiter: winner.scalar, encoding: encoding) } /// Initializes a configuration with a delimiter and text encoding. public init(delimiter: UnicodeScalar, encoding: String.Encoding = .utf8) { self.delimiter = delimiter self.encoding = encoding } } } internal class BufferedByteReader { let inputStream: InputStream var isAtEnd = false var buffer = [UInt8]() var bufferIndex = 0 init(inputStream: InputStream) { if inputStream.streamStatus == .notOpen { inputStream.open() } self.inputStream = inputStream } /// - returns: The next character and removes it from the stream after it has been returned, or nil if the stream is at the end. func pop() -> UInt8? { guard let byte = self.peek() else { isAtEnd = true return nil } bufferIndex += 1 return byte } /// - Returns: The character at `index`, or nil if the stream is at the end. func peek(at index: Int = 0) -> UInt8? { let peekIndex = bufferIndex + index guard peekIndex < buffer.count else { guard read(100) > 0 else { // end of file or error return nil } return self.peek(at:index) } return buffer[peekIndex] } // MARK: - Private private func read(_ amount: Int) -> Int { if bufferIndex > 0 { buffer.removeFirst(bufferIndex) bufferIndex = 0 } var temp = [UInt8](repeating: 0, count: amount) let length = inputStream.read(&temp, maxLength: temp.count) if length > 0 { buffer.append(contentsOf: temp[0..<length]) } return length } }
38.422067
172
0.492775
239ce74dcc2166d80a516ed215f31c1ad52fa930
413
// // Dog.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation public struct Dog: Codable { public var className: String public var color: String? = "red" public var breed: String? public init(className: String, color: String?, breed: String?) { self.className = className self.color = color self.breed = breed } }
15.296296
68
0.634383
714ef86b1498497ef66c77bcdf42057ae74589f2
2,006
// // ColorStyle.swift // TReader // // Created by tadas on 2020-02-14. // Copyright © 2020 Scale3C. All rights reserved. // import UIKit enum ColorStyle: CaseIterable { case textGray case textDark case orange case menuGray case menuDark case bkgrndWhite case iconsLight case readingUnderline case darkGray case lightBackground var color: UIColor { switch self { case .textGray: return UIColor.textGray case .textDark: return UIColor.textDark case .orange: return UIColor.orange case .menuGray: return UIColor.menuGray case .menuDark: return UIColor.menuDark case .bkgrndWhite: return UIColor.bkgrndWhite case .iconsLight: return UIColor.iconsLight case .readingUnderline: return UIColor.readingUnderline case .darkGray: return UIColor.darkGray case .lightBackground: return UIColor.lightBackground } } } fileprivate extension UIColor { @nonobjc class var textGray: UIColor { return UIColor.init(named: "TextGray")! } @nonobjc class var textDark: UIColor { return UIColor.init(named: "TextDark")! } @nonobjc class var orange: UIColor { return UIColor.init(named: "Orange")! } @nonobjc class var menuGray: UIColor { return UIColor.init(named: "MenuGray")! } @nonobjc class var menuDark: UIColor { return UIColor.init(named: "MenuDark")! } @nonobjc class var bkgrndWhite: UIColor { return UIColor.init(named: "BkgrndWhite")! } @nonobjc class var iconsLight: UIColor { return UIColor.init(named: "IconsLight")! } @nonobjc class var readingUnderline: UIColor { return UIColor.init(named: "ReadingUnderline")! } @nonobjc class var darkGray: UIColor { return UIColor.init(named: "DarkGray")! } @nonobjc class var lightBackground: UIColor { return UIColor.init(named: "LightBackground")! } }
25.075
63
0.654038
235828be617e938f50f85c09baccfa54dbc0778c
1,594
// // AppDelegate.swift // APNGDemo-macOS // // Created by WANG WEI on 2017/4/3. // // Copyright (c) 2016 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } }
34.652174
81
0.740903
4833dfba4c0ed65578eec1b5df019e2ca3d424e8
562
// // ViewController.swift // ModelsForSteriflowApp // // Created by Carlos Santiago Cruz on 12/28/18. // Copyright © 2018 Carlos Santiago Cruz. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let productOne = Product(mark: .mk978Inline, model: nil) print(productOne.clasification) print(productOne.description) print(Product.clasifications) print(Product.marks.count) print(Product.clasifications.count) } }
22.48
64
0.683274
e0a199a2a861a1fcba9ea25c70bc50ebfdc85304
545
// // Date+Milliseconds.swift // Insights // // Created by Vladislav Fitc on 30/11/2018. // Copyright © 2018 Algolia. All rights reserved. // import Foundation public extension Date { var millisecondsSince1970: Int64 { return timeIntervalSince1970.milliseconds } init(milliseconds: Int) { self = Date(timeIntervalSince1970: TimeInterval(milliseconds / 1000)) } } public extension TimeInterval { var milliseconds: Int64 { return Int64((self * 1000.0).rounded()) } }
18.166667
77
0.644037
14fe8a5c12d4a441cd4d59acfa4cb6813fdad4a1
2,818
// // PasswordCriteriaView.swift // Password // // Created by jrasmusson on 2022-01-29. // import Foundation import Foundation import UIKit class PasswordCriteriaView: UIView { let stackView = UIStackView() let imageView = UIImageView() let label = UILabel() let checkmarkImage = UIImage(systemName: "checkmark.circle")!.withTintColor(.systemGreen, renderingMode: .alwaysOriginal) let xmarkImage = UIImage(systemName: "xmark.circle")!.withTintColor(.systemRed, renderingMode: .alwaysOriginal) let circleImage = UIImage(systemName: "circle")!.withTintColor(.tertiaryLabel, renderingMode: .alwaysOriginal) var isCriteriaMet: Bool = false { didSet { if isCriteriaMet { imageView.image = checkmarkImage } else { imageView.image = xmarkImage } } } func reset() { isCriteriaMet = false imageView.image = circleImage } init(text: String) { super.init(frame: .zero) label.text = text style() layout() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize: CGSize { return CGSize(width: 200, height: 40) } } extension PasswordCriteriaView { func style() { translatesAutoresizingMaskIntoConstraints = false stackView.translatesAutoresizingMaskIntoConstraints = false stackView.spacing = 8 imageView.translatesAutoresizingMaskIntoConstraints = false imageView.image = UIImage(systemName: "circle")!.withTintColor(.tertiaryLabel, renderingMode: .alwaysOriginal) label.translatesAutoresizingMaskIntoConstraints = false label.font = .preferredFont(forTextStyle: .subheadline) label.textColor = .secondaryLabel } func layout() { stackView.addArrangedSubview(imageView) stackView.addArrangedSubview(label) addSubview(stackView) // Stack NSLayoutConstraint.activate([ stackView.topAnchor.constraint(equalTo: topAnchor), stackView.leadingAnchor.constraint(equalTo: leadingAnchor), stackView.trailingAnchor.constraint(equalTo: trailingAnchor), stackView.bottomAnchor.constraint(equalTo: bottomAnchor) ]) // Image NSLayoutConstraint.activate([ imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor) ]) // CHCR imageView.setContentHuggingPriority(UILayoutPriority.defaultHigh, for: .horizontal) label.setContentHuggingPriority(UILayoutPriority.defaultLow, for: .horizontal) } }
29.663158
125
0.640525
0e5a2130e02f2ce91fe2386835cd856debb4c672
544
import UIKit extension UIViewController { var defaultContentInsets: UIEdgeInsets { if #available(iOS 11.0, *) { return UIEdgeInsets( top: topLayoutGuide.length, left: 0, bottom: view.safeAreaInsets.bottom, right: 0 ) } else { return UIEdgeInsets( top: topLayoutGuide.length, left: 0, bottom: bottomLayoutGuide.length, right: 0 ) } } }
24.727273
51
0.46875
23e5a5b1b3f9e720884b4ef4963e19b92068bafb
2,182
// // AppDelegate.swift // Running and Gunning tvOS // // Created by Ruan Botha on 10/1/18. // Copyright © 2018 Ruan Botha. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
46.425532
285
0.753437
918d6c2bef204f958aa000287a9fe4bde16f810d
1,941
// // MKAnnotationPoint.swift // MapPoints // // Created by Evgeny Karev on 12.05.17. // Copyright © 2017 Evgeny Karev. All rights reserved. // import MapKit protocol MKPointAnnotationIconDelegate: class { func pointAnnotationIcon(_ annotation: MKPointAnnotationIcon, didChangeIconTo icon: UIImage, withCenterOffset centerOffset: CGPoint) func pointAnnotationIcon(_ annotation: MKPointAnnotationIcon, didSave isSaved: Bool) } class MKPointAnnotationIcon: MKPointAnnotation { static var savedPointIconNotActive = UIImage(named: "empty_point")! static var notSavedPoint = UIImage(named: "active_point")! static var savedPointIconActive = UIImage(named: "saved_position_point")! weak var delegate: MKPointAnnotationIconDelegate? var isActive: Bool { didSet { if oldValue != isActive { delegate?.pointAnnotationIcon(self, didChangeIconTo: self.icon, withCenterOffset: self.centerOffset) } } } private var _isSaved: Bool var isSaved: Bool { return _isSaved } func save() { guard !_isSaved else { return } self._isSaved = true delegate?.pointAnnotationIcon(self, didSave: true) } var icon: UIImage { if isSaved { return isActive ? type(of: self).savedPointIconActive : type(of: self).savedPointIconNotActive } else { return type(of: self).notSavedPoint } } var centerOffset: CGPoint { if isSaved && isActive { return CGPoint(x: 0, y: 0) } return CGPoint(x: 0, y: -icon.size.height/2) } var iconForAccessoryView: UIImage { return type(of: self).savedPointIconNotActive } init(isActive: Bool, isSaved: Bool) { self.isActive = isActive self._isSaved = isSaved super.init() } }
25.88
136
0.628542
7142c15feb9b4d356d406e73d08128d84be6d6a1
1,524
// // UserSettings.swift // Music Player // // Created by Jz D on 2019/10/6. // Copyright © 2019 polat. All rights reserved. // import Foundation enum Keys{ static let isInShuffle = "shuffleState" static let isInRepeat = "repeatState" } struct UserSettings { static var shared = UserSettings() var isInShuffle: Bool{ get { return UserDefaults.standard.bool(forKey: Keys.isInShuffle) } set(newVal){ UserDefaults.standard.set(newVal, forKey: Keys.isInShuffle) } } var isInRepeat: Bool{ get { return UserDefaults.standard.bool(forKey: Keys.isInRepeat) } set(newVal){ UserDefaults.standard.set(newVal, forKey: Keys.isInRepeat) } } var playerProgress: Float{ get{ return UserDefaults.standard.float(forKey: AudioTags.playerProgress.rawValue) } set(newVal){ UserDefaults.standard.set(newVal , forKey: AudioTags.playerProgress.rawValue) } } var currentAudioIndex: Int{ get{ return UserDefaults.standard.intVal(forKey: AudioTags.currentIndex.rawValue) } set(newVal){ UserDefaults.standard.set(newVal, forKey: AudioTags.currentIndex.rawValue) } } } enum PlayRules:String{ case shuffleLoops = "无限乱序循环" case shuffleNoLoop = "乱序来一遍" case loopNoShuffle = "单曲循环" case none = "顺序来一遍" }
20.32
89
0.593832
01b35d722ee1aef5383b2c2e449f3ca189023575
616
// Appfile.swift // Copyright (c) 2020 FastlaneTools var appIdentifier: String { return "" } // The bundle identifier of your app var appleID: String { return "" } // Your Apple email address var teamID: String { return "" } // Developer Portal Team ID var itcTeam: String? { return nil } // App Store Connect Team ID (may be nil if no team) // you can even provide different app identifiers, Apple IDs and team names per lane: // More information: https://docs.fastlane.tools/advanced/#appfile // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.1]
38.5
88
0.728896
09150ee0883053983c259b6b530a76c46fa06854
396
// // Guests.swift // Useful_Closures_2 // // Created by Jon Hoffman on 1/26/15. // Copyright (c) 2015 Jon Hoffman. All rights reserved. // import Foundation class Guests { var guestNames = ["Jon","Kim","Kailey","Kara","Buddy","Lily","Dash"] typealias UseArrayClosure = (([String]) -> Void) func getGuest(handler:UseArrayClosure) { handler(guestNames) } }
19.8
72
0.628788
624432f5373b0a678a5df5d13ef24240e7daf3d1
463
// // Riddle1.swift // RxSwiftRiddles // // Created by Balázs Varga on 2019. 04. 17.. // Copyright © 2019. W.UP Ltd. All rights reserved. // import Foundation import RxSwift class Riddle1 { /** * Transform the given [value] into an Observable that emits the value and then completes. * * Use case: You want to transform some value to the reactive world. */ func solve(value: Int) -> Observable<Int> { TODO() } }
20.130435
94
0.62635
8f5d5dabdb3746205fab42a6b4ee149cd66a260b
3,080
// // ModuleManager.swift // ModuleManager // // Created by NeroXie on 2019/1/18. // import Foundation import UIKit public final class ModuleManager { public static let shared = ModuleManager() private var registerServices = [Method]() private var awakes = [Method]() private init() { // register services Module.register(service: ModuleRouteService.self, used: URLRouter.self) Module.register(service: ModuleTabService.self, used: ModuleTabServiceImpl.self) Module.register(service: ModuleLaunchTaskService.self, used: ModuleLaunchTaskServiceImpl.self) Module.register(service: ModuleNotificationService.self, used: ModuleNotificationServiceImpl.self) Module.register(service: ModuleApplicationService.self, used: ModuleApplicationServiceImpl.self) // register more services loadAllMethods(from: Module.RegisterService.self) } public func application( _ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? ) -> Bool { // wake up all modules to register loadAllMethods(from: Module.Awake.self) // execute launch task Module.launchTaskService.execute() return Module.applicationService.application?(application, willFinishLaunchingWithOptions: launchOptions) ?? true } public func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { loadWindowIfNeed() return Module.applicationService.application(application, didFinishLaunchingWithOptions: launchOptions) } } private extension ModuleManager { func loadWindowIfNeed() { guard UIApplication.shared.keyWindow == nil else { return } // forcibly load the window let sel = NSSelectorFromString("setWindow:") var window = UIWindow(frame: UIScreen.main.bounds) window.backgroundColor = .white if let win = Module.applicationService.window as? UIWindow { window = win } Module.applicationService.perform(sel, with: window) if let delegate = UIApplication.shared.delegate, delegate.responds(to: sel) { delegate.perform(sel, with: window) } window.makeKeyAndVisible() } func loadAllMethods(from aClass: AnyClass) { guard let metaClass: AnyClass = object_getClass(aClass) else { return } var count: UInt32 = 0 guard let methodList = class_copyMethodList(metaClass, &count) else { return } let handle = dlopen(nil, RTLD_LAZY) let methodInvoke = dlsym(handle, "method_invoke") for i in 0..<Int(count) { let method = methodList[i] unsafeBitCast(methodInvoke, to:(@convention(c)(Any, Method)->Void).self)(metaClass, method) } dlclose(handle) free(methodList) } }
29.615385
121
0.660714
56bbaac2730fdaa914fe996b7dfdf75232b1ec06
828
// // ObjCommit.swift // BeeFun // // Created by WengHengcong on 2/23/16. // Copyright © 2016 JungleSong. All rights reserved. // import UIKit import ObjectMapper /* "sha": "134f57a577b4dc45a29818d11d2484c549a86ac0", "author":ObjUser, "message": "starred repos done", "distinct": true, "url": "https://api.github.com/repos/wenghengcong/BeeFun/commits/134f57a577b4dc45a29818d11d2484c549a86ac0" */ class ObjCommit: NSObject, Mappable { var sha: String? var author: ObjUser? var message: String? var distinct: Bool? var url: String? required init?(map: Map) { } func mapping(map: Map) { // super.mapping(map) sha <- map["sha"] author <- map["author"] message <- map["message"] distinct <- map["distinct"] url <- map["url"] } }
19.255814
106
0.625604
61d1f32446a76dcd0df2f1812a33d1b9a4dd5361
661
// // CollectionCycleCell.swift // DYTV // // Created by hegaokun on 2017/4/7. // Copyright © 2017年 AAS. All rights reserved. // import UIKit import Kingfisher class CollectionCycleCell: UICollectionViewCell { //MARK:- 控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! //MARK:- 定义属性 var cycleModel: CycleModel? { didSet { titleLabel.text = cycleModel?.title let iconUrl = NSURL(string: cycleModel?.pic_url ?? "")! let resource = ImageResource(downloadURL: iconUrl as URL) iconImageView.kf.setImage(with: resource) } } }
24.481481
69
0.639939
ede2efac37a8cca746789b93604eb94c6986ca45
350
// // PHAnalitycsModule.swift // Product Hunt // // Created by Vlado on 5/5/16. // Copyright © 2016 ProductHunt. All rights reserved. // import ReSwift struct PHTrackPostAction: Action { var post: PHPost } struct PHTrackPostShare: Action { var post: PHPost var medium: String } struct PHTrackVisit: Action { var page: String }
15.909091
54
0.691429
5086576fd1b97da26f597d99e444a4509d6f79e7
2,196
// // MiscellaneousAPI.swift // // Generated by openapi-generator // https://openapi-generator.tech // import Foundation import Alamofire open class MiscellaneousAPI: APIBase { /** Get statistics on the sales of Minecraft. - parameter orderStatisticsRequest: (body) The payload is a json list of options under the metricKeys key. You will receive a single object corresponding to the sum of sales of the requested type(s). You must request at least one type of sale. Below is the default list used by https://minecraft.net/en/stats/ - parameter completion: completion handler to receive the data and the error objects */ open class func getOrdersStatistics(orderStatisticsRequest: OrderStatisticsRequest, completion: @escaping ((_ data: OrderStatisticsResponse?, _ error: ErrorResponse?) -> Void)) { getOrdersStatisticsWithRequestBuilder(orderStatisticsRequest: orderStatisticsRequest).execute { (response, error) -> Void in completion(response?.body, error) } } /** Get statistics on the sales of Minecraft. - POST /orders/statistics - BASIC: - type: http - name: MojangStatisticsToken - parameter orderStatisticsRequest: (body) The payload is a json list of options under the metricKeys key. You will receive a single object corresponding to the sum of sales of the requested type(s). You must request at least one type of sale. Below is the default list used by https://minecraft.net/en/stats/ - returns: RequestBuilder<OrderStatisticsResponse> */ open class func getOrdersStatisticsWithRequestBuilder(orderStatisticsRequest: OrderStatisticsRequest) -> RequestBuilder<OrderStatisticsResponse> { let path = "/orders/statistics" let URLString = OpenAPIClientAPI.basePath + path let parameters = orderStatisticsRequest.encodeToJSON() let url = URLComponents(string: URLString) let requestBuilder: RequestBuilder<OrderStatisticsResponse>.Type = OpenAPIClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } }
46.723404
315
0.735883
acc710e7b44b07cc157cc450cccfed6313b173f5
1,325
import SwiftUI struct ContentView: View { @State var selected: Bool = false @State var cardOffset: CGSize = .zero var body: some View { Rectangle() .frame(width: 320, height: selected ? 80 : 200) .cornerRadius(selected ? 42 : 12) .foregroundColor(selected ? .pink : .gray) .shadow(radius: 30) .onTapGesture { selected.toggle() } .scaleEffect(selected ? 1.0 : 0.5) .rotationEffect(selected ? Angle(degrees: 15) : .zero) .offset(cardOffset) .animation(.interpolatingSpring(mass: 0.75, stiffness: 400, damping: 10, initialVelocity: 0)) .gesture( DragGesture() .onChanged({ changedValue in cardOffset = changedValue.translation }) .onEnded({ _ in cardOffset = .zero }) ) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
28.191489
66
0.42566
d79066d5555fff1e37a462fb56700e3373331f26
4,850
// // DailyWordTableViewController.swift // memuDemo // // Created by Mr.Mang Pi on 6/5/19. // Copyright © 2019 Parth Changela. All rights reserved. // import UIKit import RealmSwift import SwipeCellKit //checker = 1 let realm = try! Realm() class DailyWordTableViewController: UITableViewController { @IBOutlet weak var dailyWordButton: UIBarButtonItem! @IBOutlet weak var tblAppleProducts: UITableView! var favoriteWord: Results<Favorite>? var wordSearch: Results<Data>? var recentWord: Results<recentSearch>? var searchedWord = [String]() var rSearch = recentSearch() var wSearch = Data() var fSearch = Favorite() var dailyWord: Results<wordOfTheDay>? var wordOfDay = wordOfTheDay() override func viewDidLoad() { super.viewDidLoad() revealViewController().rearViewRevealWidth = 200 dailyWordButton.target = revealViewController() dailyWordButton.action = #selector(SWRevealViewController.revealToggle(_:)) loadDailyWord() print(Realm.Configuration.defaultConfiguration.fileURL!) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dailyWord?.count ?? 1 } // override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! SwipeTableViewCell // cell.delegate = self // return cell // } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "favorite", for: indexPath) as! SwipeTableViewCell cell.textLabel?.text = dailyWord?[indexPath.row].word ?? "No word found" //print (final) return cell } //animate select cell override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) //performSegue(withIdentifier: "favorite", sender: self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let detailVC = segue.destination as? DetailsViewController { detailVC.wordOfDay = (dailyWord![(tblAppleProducts.indexPathForSelectedRow?.row)!]) } DetailsViewController.GlobalVariable.wordOfDay = true } func loadDailyWord() { dailyWord = realm.objects(wordOfTheDay.self).sorted(byKeyPath: "dateCreated",ascending: false) tableView.reloadData() } } extension Date { func toString( dateFormat format : String ) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } } //extension RecentViewController: UISearchBarDelegate //{ // // // recentWord = recentWord?.filter("recentSearch CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "recentSearch", ascending: true) // // recentWord = recentWord?.filter("searchWord CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "searchWord", ascending: true) // // // rSearch.recentSearch = searchBar.text! // // // print (rSearch) // // // // try! realm.write { // // realm.add(rSearch) ////} // // // tableView.reloadData() //extension FavoriteTableViewController: SwipeTableViewCellDelegate{ // // func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { // guard orientation == .right else { return nil } // // let deleteAction = SwipeAction(style: .destructive, title: nil) { action, indexPath in // // handle action by updating model with deletion // // if let favoriteForDeletion = self.favoriteWord?[indexPath.row]{ // do { // try self.realm.write { // self.realm.delete(favoriteForDeletion) // } // } // catch{ // print ("Error deleting Recent Word") // } // } // // } // // // customize the action appearance // deleteAction.image = UIImage(named: "delete-icon") // // return [deleteAction] // } // //// func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions { // var options = SwipeOptions() // options.expansionStyle = .destructive // return options // }
30.124224
157
0.627835
fe57d40ae37bb215128570dfd315407f30282024
790
//___FILEHEADER___ import UIKit class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___ { // MARK: - init override init(frame: CGRect) { super.init(frame: frame) commit_init() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commit_init() } private func commit_init() { subView_add() subView_layout() } // MARK: - subview private func subView_add() { } private func subView_layout() { } /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ }
19.268293
78
0.592405
79c8f21559b86edc3a4b92c4d54c47994692c577
983
// // HomeSectionHeaderView.swift // Futures-07 // // Created by Ssiswent on 2020/7/29. // import UIKit typealias MoreBtnBlock = () -> Void class INSHomeSectionHeaderView: UIView { @IBOutlet var view: UIView! @IBOutlet weak var leftLabel: UILabel! var moreBtnBlock: MoreBtnBlock? override init(frame: CGRect) { super.init(frame: frame) // 加载xib // swiftlint:disable force_cast view = (Bundle.main.loadNibNamed("INSHomeSectionHeaderView", owner: self, options: nil)?.last as! UIView) // swiftlint:enable force_cast // 设置frame view.frame = frame view.backgroundColor = .clear // 添加上去 addSubview(view) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @IBAction func moreBtnClicked(_ sender: Any) { if moreBtnBlock != nil { moreBtnBlock!() } } }
21.844444
113
0.592065
18fa672665c547d633ea702a56cccd19921b2f5e
5,693
// // DateTableItemGroupTests.swift // ResearchTests_iOS // // Copyright © 2019 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest @testable import Research @available(*, deprecated, message: "These tests are for the deprecated RSDInputField objects") class DateTableItemGroupTests: XCTestCase { override func setUp() { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testSetPreviousAnswer_TimeOnly() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let json = """ { "identifier": "reminderTime", "type": "date", "prompt": "Set reminder", "range" : { "defaultDate" : "09:00", "minuteInterval" : 15, "codingFormat" : "HH:mm" } } """.data(using: .utf8)! // our data in native (JSON) format do { let inputField = try decoder.decode(RSDInputFieldObject.self, from: json) let itemGroup = RSDDateTableItemGroup(beginningRowIndex: 0, inputField: inputField, uiHint: .picker) // Previous answer is encoded using the default "time-only" formatter for the given app. // This is based on using a date coding where the input formatter and the result // formatter are different. let previousAnswer = "08:30:00.000" try itemGroup.setPreviousAnswer(from: previousAnswer) XCTAssertNotNil(itemGroup.answer) guard let dateAnswer = itemGroup.answer as? Date else { XCTFail("Failed to set the previous answer to the expected type. \(String(describing: itemGroup.answer))") return } let calendar = Calendar.current let dateComponents = calendar.dateComponents([.hour, .minute], from: dateAnswer) XCTAssertEqual(dateComponents.hour, 8) XCTAssertEqual(dateComponents.minute, 30) } catch let err { XCTFail("Failed to decode object or set previous answer: \(err)") return } } func testSetPreviousAnswer_TimeOnly_OldFormat() { NSLocale.setCurrentTest(Locale(identifier: "en_US")) let json = """ { "identifier": "reminderTime", "type": "date", "prompt": "Set reminder", "range" : { "defaultDate" : "09:00", "minuteInterval" : 15, "codingFormat" : "HH:mm" } } """.data(using: .utf8)! // our data in native (JSON) format do { let inputField = try decoder.decode(RSDInputFieldObject.self, from: json) let itemGroup = RSDDateTableItemGroup(beginningRowIndex: 0, inputField: inputField, uiHint: .picker) // syoung 11/06/2019 The time only format used by Bridge is different from what was // previously encoded for SageResearch. I suspect this is the result of a translation // fail from when we were supporting ResearchKit/AppCore? let previousAnswer = "08:30:00" try itemGroup.setPreviousAnswer(from: previousAnswer) XCTAssertNotNil(itemGroup.answer) guard let dateAnswer = itemGroup.answer as? Date else { XCTFail("Failed to set the previous answer to the expected type. \(String(describing: itemGroup.answer))") return } let calendar = Calendar.current let dateComponents = calendar.dateComponents([.hour, .minute], from: dateAnswer) XCTAssertEqual(dateComponents.hour, 8) XCTAssertEqual(dateComponents.minute, 30) } catch let err { XCTFail("Failed to decode object or set previous answer: \(err)") return } } }
43.128788
122
0.647813